Beginners Guide to Tkinter – Python Most Popular GUI Library
Learn how to write a GUI application in Python using Tkinter
Introduction
In this tutorial, we are going to explore Tkinter – a free Python GUI library. This library is widely used for creating cross-platform desktop applications. We will learn how to create GUI applications using Tkinter and also, check out some of the most useful components of the tkinter library. Let’s get started.
What is Tkinter?
Tkinter is a python binding of the tcl/tk GUI toolkit. It acts as a Python interface to the underlying tcl/tk library. tcl/tk library consists of multiple unique modules with distinct functionalities and documentation. The most important two are described below:
- Tcl is a general-purpose programming language just like python. However, it is mostly used as an embedded language with other programming languages such as C, Python, etc. It also has the utility to interface with tk tools.
- Tk is implemented in C and contains multiple custom commands to create and manipulate graphical widgets. Tk can take advantage of GUI facilities of different operating systems i.e. GDI on Windows, Cocoa on macOS, and Xlib on Unix/X11.
Brief History & Major Contributors
Tkinter was first written by Steen Lumholt and the creator of Python Programming Language Guido van Rossum. According to Tkinter’s wiki, It was later revised by Fredrik Lundh. Late John Shipman also has a major contribution to this library, especially in the documentation. Before his retirement from New Mexico Tech in 2013, he made significant contributions to the reference by adding valuable Tkinter resources. Unfortunately, he passed away in 2017.
What is Tkinter Used For
Tkinter is primarily used to interface with the tcl-tk library from Python. This enables developers to create a graphical user interface with a native look and feel.
Tkinter is arguably one of the best choices to learn GUI application development in Python. Compared to other python GUI libraries, it is easy to learn which makes it a compelling choice for beginners. Also, it can be used in all the major operating systems almost out of the box. Due to its popularity, the latest python versions include Tkinter in the binaries by default. And, for the older python versions, it can be installed with a single command. Check out the installation instruction below. Moreover, Tkinter is extremely lightweight and relatively easy to setup and install. The applications developed using Tkinter are versatile and give the end users a native experience with high performance.
How to Install it
You will need python to install and use the Tkinter module. First, go to the official Python website and download the latest binary installer for your operating system from here. You can skip this step if you have already installed Python.
If you are using the latest version of Python then there is a high chance that Tkinter is already installed! All the Python versions above 3.7 usually ship Tkinter as a built-in standard library if installed through official binaries. The only exception is in some Linux distros where python is installed at the system level, and Tkinter is bundled as a separate package.
You can validate you have a working Tkinter module by opening the Python shell or, IDLE and typing the below:
>>> import tkinter
>>> tkinter._test()
It will open a default Tkinter app similar to the one below.
💡 Pro Tip: You can also test your tkinter installation by simply running the following command in your terminal:
>>python3 –m tkinter * in windows, you might have to use the command `py` instead of `python3` |
If you get an error, then you will have to install Tkinter. In Ubuntu, you will have to install the python3-tk module. You can install it using the below command:
>>sudo apt install python3-tk
For Mac OS, you will have to download the official python binaries which include Tkinter. And, for Windows you can install Tkinter using pip like below:
pip install tk
Now, that you have installed the tkinter. Let’s write our first tkinter app.
Your First Tkinter Application – Catch the Pi game
Before we begin, first we need to understand some GUI concepts. Every GUI application needs a User Interface where user can interact with the application. In Tkinter, there are lots of classes that create different elements that users can interact with. Let’s learn some of the important tkinter elements:
- Window – It is more like a container that holds other GUI elements in it.
- Frame – A way to group related widgets in a rectangular area and add padding between widgets.
- Label – displays text on the screen.
- Button – A button can perform an action when clicked.
- Entry – A text box to take single-line text input from user.
- Text – A text box that allows multiline text entry.
There are some more advanced widgets which are also useful. For example, Listbox, Scrollbar,
Scale, Spinbox, Progressbar, etc. Check out the ttk module documentation for more detail.
For our tkinter application, we can create a user interface using a window. Let’s learn how to do it.
How to create & customize a Tkinter Window
To create a tkinter window, we will have to use the Tk Class. We can create our main window by instantiating a Tk class instance. Take a look at the following snippet:
from tkinter import Tk
main_window = Tk()
main_window.title("Tkinter Window - Tutorial")
main_window.mainloop()
First we import the Tk class from the tkinter module. Then we create a Tk object named `main_window`. Using this object we can manipulate the application window. We then added a title to the window using the title() method.
Finally, the mainloop() function call tells Python to start the Tkinter’s eventloop. This is a blocking call that keeps the application running and interactable. So, if a user sends some events such as button clicks or keypress, the Application will receive it via this event loop and process them accordingly. Let’s go ahead and run it. Once you run it, you will notice the window is too tiny, since it doesn’t have any elements in it.
Let’s configure it so that it has some width and height. We will also add a background color.
main_window.configure(width=320, height=320) main_window.configure(bg='white')
Insert the above two lines before the mainloop() call. Once, you’ve done it, try re-running it. You will see something similar to this:
Now, let’s make it interactable. We will create a fun little game. Let’s call it “The Pi Game”. The game will have a timer that the user can start or stop using a button. The user will attempt to stop the timer exactly at 3 seconds and 14 milliseconds if he/she succeeds the app will show “You win!”, otherwise another message.
Let’s modify the current window to reflect the title:
from tkinter import Tk if __name__ == "__main__": main_window = Tk() main_window.title("The Pi Game") main_window.configure(width=320, height=320) main_window.configure(bg='black')
We added a new if condition as well. The code you see under if __name__ == “__main__”: will be the entry point of our application. It will only get called upon when the Python file is executed as a script. Next, We will add some labels.
How to Create Tkinter Label
To create a tkinter label. We will have to import the Label class:
from tkinter import Label
And inside the “if” statement, we will create two new labels:
timer_label = Label(main_window, font=("arial", 72, "bold"), fg="white", bg="black", text="Catch the Π.") help_label = Label(main_window, font=("arial", 24, "bold"), fg="white", bg="black", text="Press start and\nstop the timer at 3.14s")
Notice, we are passing the window that we created as the first argument. We are also telling which font to use by the second positional argument. The “fg” and “bg” tell what will be the font color and background of the label. And lastly, we pass a string to display in the label text.
Adding a Tkinter Button
To add a tkinter button we can follow a similar process as the labels. Just like before, we will first import the Button class from the tkinter module:
from tkinter import Button
and then inside the “if” statement, we will use this class to add the button.
button = Button(main_window, width=25, font=("arial", 24, "bold"), text="Start/Stop", command=lambda: toggle_button(timer_label))
There is a new parameter command. This tells tkinter which function to execute when the button is clicked. We haven’t implemented this function yet. Let’s implement it:
ticking = False def toggle_button(label): global ticking ticking = not ticking if ticking: tick(label)
We keep track of the state using the global variable `ticking`. So, when the user clicks the button for the first time, it will start ticking by setting ticking = True. And, if the timer is already ticking then, if the user clicks the button it will make ticking = False, which will stop the timer.
You might have noticed a new function call tick(label). We also haven’t written this function yet. Let’s write it:
def tick(label, timer=0): second = timer//1000 millisecond, timer = str(timer - second * 1000)[:2], timer + 10 global ticking if ticking: label.config(text = "{}.{}s".format(second, millisecond)) label.after(10, tick, label, timer) else: if second == 3 and millisecond == "14": label.config(text="{}.{}s\nYou win!".format(second, millisecond)) elif second == 3: label.config(text="{}.{}s\nSo Close! Try again.".format(second, millisecond)) else: label.config(text="{}.{}s\nBetter luck next time.".format(second, millisecond))
Let’s walk you through it. When the user click’s the start button, The tick function refreshes the timer label every 10 milliseconds and shows the timer to the user. When the user click’s the stop button, it stops and shows whether the user wins or loses.
The first couple of lines are pretty straightforward, we are calculating seconds and milliseconds and also increasing the timer by 10ms each time the function gets executed.
In the next few lines, based on the global ticking variable, we decide whether to tick the timer or to show the end results. We use the config() method to update the label’s text.
The after() method tells tkinter to execute the tick function again after 10ms. That’s it.
Finally, we need to pack these elements to make them visible in the main_window and start the eventloop. The full source code will look like below:
from tkinter import Tk from tkinter import Label from tkinter import Button ticking = False def tick(label, timer=0): second = timer//1000 millisecond, timer = str(timer - second * 1000)[:2], timer + 10 global ticking if ticking: label.config(text = "{}.{}s".format(second, millisecond)) label.after(10, tick, label, timer) else: if second == 3 and millisecond == "14": label.config(text="{}.{}s\nYou win!".format(second, millisecond)) elif second == 3: label.config(text="{}.{}s\nSo Close! Try again.".format(second, millisecond)) else: label.config(text="{}.{}s\nBetter luck next time.".format(second, millisecond)) def toggle_button(label): global ticking ticking = not ticking if ticking: tick(label) if __name__ == "__main__": main_window = Tk() main_window.title("The Pi Game") main_window.configure(width=320, height=320) main_window.configure(bg='black') timer_label = Label(main_window, font=("arial", 72, "bold"), fg="white", bg="black", text="Catch the Π.") help_label = Label(main_window, font=("arial", 24, "bold"), fg="white", bg="black", text="Press start and\nstop the timer at 3.14s") button = Button(main_window, width=25, font=("arial", 24, "bold"), text="Start/Stop", command=lambda: toggle_button(timer_label)) timer_label.pack() help_label.pack() button.pack() main_window.mainloop()
Output
Let’s go ahead and save this script in a python file e.g. “pi_game.py” and run it. Once you run it, a new window will pop up:
Try clicking the start/stop button and playing around. This window is resizable so you can drag any edge of the window and make it smaller or larger. It is possible to customize the size of the window and also to center or maximize it! Read the official tkinter documentation to learn how to do so.
Conclusion
We’ve developed our first GUI Application using Tkinter. We also learned the basics of Python GUI Application development by developing a small game. Feel free to play around and tweak the source code to make it more fun.
The only way to learn Tkinter and Python is coding and solving problems. Keep practicing building real desktop applications like those available here at Practity.