How to Build User Interfaces with Python — Tkinter Basics
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 =…