Create a window
The best way to create a GUI with Python is to use tkinter, a module that comes with the installation of Python, so that you can use it without anything to be installed apart Python itself. Let’s see how it easy, after you understand the basics, to use this module.
If you want to create a GUI, graphic user interface with Python, you have a lot of choice. The fastest way to make a GUI is probably the one that uses tkinter, a module with wich you can use the ttk libraries that allow you to make pretty, nice, simple guis. It is a thin object-oriented layer on top Tcl/tk. To create a window this is the code:
- we import the module tkinter (Tkinter for Python 2)
- we instantiate the class Tk(), making the window appear and storing the window as root (or any other name)
- We make the window to stay active with the mainloop()
# create a window import tkinter root = tkinter.Tk() # the main class root.mainloop() # windows needs a loop
Give a name and a size to the window
The root object has the method title to give the window a title that appears on topo of the window and the geometry method to set the width and height, the x and y position on the screen in the simple way you can see in the code below.
import tkinter root = tkinter.Tk() root.title("MyApp") root.geometry("400x400+100+100") root.mainloop()
Insert a frame colored yellow
A frame is a container, let’s add one with a nice color:
The geometry method could have been root.geometry(“500×400+100+100”). I used the syntax that has been added with python 3.6 to use the two variables dimx and dimy. It’s just a matter of choice.
As you can see, the attributes of the window are stored in a dictionary of the istance, so that you can access to them with the name of the attribute in square parenthesis after the name of the istance of Tk() (that is root in this case).
Add a label
We can add a label simply like:
label = tkinter.Label(root, text="My GUI for Python") label.pack()
Let’s take a look to a complete code example, with some colors:
import tkinter root = tkinter.Tk() root.title("MyApp") WIDTH = 500 HEIGHT = 400 root.geometry(f'{WIDTH}x{HEIGHT}') # from python 3.6 root['bg'] = 'yellow' label = tkinter.Label(root, text="My GUI for Python") label.pack() root.mainloop()