avatarEsteban Thilliez

Summary

The provided content is a comprehensive guide on how to create user interfaces in Python using the Tkinter library, covering basic concepts, window manipulation, and user interaction.

Abstract

The article "How to Build User Interfaces with Python — Tkinter Basics" is a tutorial designed for Python developers looking to transition from console-based applications to graphical user interfaces (GUIs). It introduces Tkinter, a standard Python library for GUI development, and contrasts it with PyQt, another popular GUI framework. The author provides a step-by-step approach to creating a first window, adding widgets like labels, and modifying window geometry for size and position adjustments, including centering the window on the screen. The tutorial also covers resizing capabilities, window transparency, icon customization, and the use of the Ttk module for more modern widgets. Additionally, it explains how to handle user interactions through callback functions and event binding, ensuring that the application can respond to actions such as clicks and key presses. The article concludes by promising further exploration of layout management and additional widgets in future installments, encouraging readers to engage with the author's other Python-related content.

Opinions

  • The author suggests that Tkinter is a straightforward and accessible library for Python developers to start building GUIs.
  • There is an emphasis on the importance of using the Ttk module for its improved widgets and separation of behavior and appearance.
  • The author provides a subjective opinion on the ease of creating a basic window and adding elements, implying that it is a simple process for beginners.
  • The article implies that understanding how to manipulate window geometry, resizing constraints, and transparency can greatly enhance the user experience.
  • The author indicates a preference for Tkinter over PyQt for certain use cases, although the specifics of this preference are not detailed in the provided content.
  • The use of lambda functions for passing arguments to callbacks is presented as a practical solution to a common problem in event handling.
  • The tutorial encourages readers to explore more advanced topics in subsequent articles, suggesting a progressive learning approach.

How to Build User Interfaces with Python — Tkinter Basics

Photo by Kelly Sikkema on Unsplash

Are you tired of all the programs you create running in the console? Try graphical interfaces! It’s very easy to do in Python.

Tkinter is one of the Python libraries you can use to build user interfaces (the other being PyQt but it’s more a framework than a library). We’ve already talked in this story about when you should or shouldn’t prefer PyQt or Tkinter so I won’t talk about this anymore.

If you want to follow this story better, I made a GitHub repo with the code, you can find it here.

Tkinter is already installed if you have a standard Python installation. You can directly import it:

import tkinter as tk

First window

To create a window, we use the Tk class.

main_window = tk.Tk()

We can then change its title:

main_window.title("Hello World")

Then, we have to execute the main loop of the window.

main_window.mainloop()

You can run the code now. It will display an empty window. You can resize it, or close it if you want.

Now we will try to add a label to make this window a bit less empty.

label = tk.Label(main_window, text="Hello World!") message.pack()

More generally, to add any widget you do it this way:

widget = WidgetName(container, **args)

container is either a window or a frame and args are just options as text in the case of a Label . Then we use widget.pack() to make the widget visible.

Changing window geometry

You can modify the geometry of a window to modify its size and position. The geometry’s format is:

widthxheight±x±y
  • width is the window’s width in pixels.
  • height is the window’s height in pixels.
  • x is the window’s horizontal position. It can be either positive or negative.
  • y is the same thing as x but for the vertical position.

x = 0 and y = 0 at the top left of your screen. If x = +10, the window will be placed 10 pixels away from the top left of your screen. If x = -10, the window will be placed 10 pixels away from the top right of your screen. It’s the same principle for y.

geometry = "500x500+100+100"
main_window.geometry(geometry)

You can also use geometry without arguments to retrieve the current geometry of the window.

current_geometry = window.geometry()

Centering the window

How can I center the window? I don’t know the size of the screen…

You can retrieve the size of the screen easily:

screen_width = main_window.winfo_screenwidth()
screen_height = main_window.winfo_screenheight()

Then, it’s just math!

window_width = 500
window_height = 500

screen_width = main_window.winfo_screenwidth()
screen_height = main_window.winfo_screenheight()

center_x = int((screen_width / 2) - (window_width / 2))
center_y = int((screen_height / 2) - (window_height / 2))

geometry = "{}x{}+{}+{}".format(window_width, window_height, center_x, center_y)
main_window.geometry(geometry)

Resizing

You can enable or disable resizing for your window:

main_window.resizable(False, False) # horizontal and vertical resizing disabled

You can also specify the maximum/minimum sizes:

main_window.minsize(min_width, min_height)
main_window.maxsize(min_height, max_height)

Transparency

main_window.attributes("-alpha", 0.75) # 0.75 is the opacity

Icon

You can easily change the window’s icon. The format supported is only .ico, so you must use a converter if your image is a jpg or a png.

main_window.iconbitmap("icon.ico")

Ttk

Ttk stands for Tk themed. It’s a module containing all the newer widgets of tkinter. It also separates widgets’ behaviors and appearances. A good practice is to always use ttk.

from tkinter import ttk
label = ttk.Label(main_window, "Hellow World")
label.pack()

In ttk, you find all the widgets you can find in tkinter, and even more!

Widgets’ options

You have many ways to set options for widgets. We’ve already seen the first way which is passing arguments when you create the widgets. There are other ways:

  • widget[option] = value. For example: label['text'] = 'Hi!' .
  • config. It works the same way as if you were initializing the widget, but it doesn’t recreate it: label.config(text='Hi!')

Interactions

An application needs to respond to user actions such as clicks or key presses. To deal with this, you can assign callback functions to events.

To do this, we need first to define a function to use as a callback, then we need to bind this function to a widget.

def clicked():
    print("Button clicked!")
button = ttk.Button(main_window, text="Hello World!", command=clicked)
button.pack()

Yes, it’s that easy!

What if I want to pass arguments to callbacks?

We’ll use lambda functions.

def callback(text):
    print(text)


button2 = ttk.Button(main_window, text="Hello World!", command=lambda: callback("Button 2 clicked!"))
button2.pack()

But every widget doesn’t have a command parameter. That’s why we can also use another binding: event binding.

Event binding

This is the way of binding you will use when you will have to deal with more complex cases. Here is the syntax of the bind method we will use:

widget.bind(event, handler, add=None)
  • event: the event to which the widget must respond.
  • handler: the handler.
  • add: if you want to use multiple handlers, you pass a + to the add argument. It means you can bind multiple times.

Event pattern: to deal with events, you have to know how to build one. Here is the syntax of an event:

<modifier-type-detail>
  • type: the type of the event. For example, KeyPress means a key is pressed.
  • detail: some more detail about the event. For example, Caps_Lock means you need to press CapsLocks while doing something to trigger the event.
  • modifier: either Alt , Control , Shift or Any . The first three mean you have to hold the corresponding key, and the last one makes your event general.

You can apply events to any widget, or to a window. Let’s create an event and bind it to the main window:

main_window.bind("<Button>", lambda event: callback("Button clicked!"))

When we will click somewhere in the window, our callback will be triggered. We have to provide one argument to our callback: event . It allows us to have more information about the event in the callback.

If you want to bind an event to a class instead of an instance of a widget, you can do it this way:

main_window.bind_class('Button', '<Button>', clicked)

Finally, there are some situations where you will have to unbind events. You do it this way:

widget.unbind(event)

For example:

main_window.unbind("<Button>")

Final note

There are a lot of things to know about Tkinter. In a next story, we’ll talk about layout and other widgets.

For now, you have the basics!

You can find the other stories of this series here:

To explore more of my Python stories, click here!

If you liked the story, don’t forget to clap and maybe follow me if you want to explore more of my content :)

You can also subscribe to me via email to be notified every time I publish a new story, just click here!

If you’re not subscribed to medium yet and wish to support me or get access to all my stories, you can use my link:

Python
Programming
Software Development
User Interface
Development
Recommended from ReadMedium