In Python programing language there are many libraries and frameworks which help in building a graphical user interface (GUI). Most of the old frameworks and libraries offer classic looks, yet they also provide a solid and stable development experience. Moreover, the old frameworks and libraries are best to build a quick GUI.
There are many community projects which help in building GUI in Python but Tkinter is best for small GUI applications. Tkinter supports all the major operating systems like Windows, macOS, and Linux.
To get started with Tkinter you should have an installed and functional Python 3.7 or greater.
Note: Python 3.7 is required for the new version of Tkinter. However, in Linux systems, you might have to install Tkinter separately. And the command for the Debian base system is ‘Sudo apt-get install python3-tk’.
To write your first hello world program in Tkinter write the following lines in your Python file.
import tkinter as tk window = tk.Tk() greeting = tk.Label(text="Hello World") greeting.pack() window.mainloop()
From the above code, we have 5 things we need to know:
1. First is the import statement, we have to import a file named tkinter which contains all the components required.
import tkinter as tk
2. The second thing is the object window of class Tk, which contains the constructor to construct the basic window (the window which will appear if you run the above code) which looks like the image below.
window = tk.Tk()
3. The window will say ‘hello world’ because we added the widget. We will discuss widgets later in this article, for now, we can say that all the features visible inside an application is called widgets.
greeting = tk.Label(text="Hello World")
4. Calling the method to create a widget is not enough you will have to tell the Python interpreter how to render the widget on the screen and then bring us to our fourth thing knowns as the packer one of Tk’s geometry-management mechanisms. We will see geometry-management mechanisms later, for now, it is something that tells how and where to place a widget in the window.
5. Last but not least the fifth thing is to call a method named mainloop if you do not call mainloop, your application will close as soon as it opens, to make it visible all the time you have to call mainloop which will allow the application to run in a loop and re-renders the application when required.
Widgets are the element through which a user interacts with the application. There are multiple types of widgets in the Tkinter library, which we have used in the above examples called a Label. Label is a very simple widget because it renders a text on the screen using a method Label of class Tk simple.
greeting = tk.Label(text="Hello World")
There are many more widgets that can be used, some of the most common are explained below:
Labels are used to render text messages and images on the screen. The output displayed on the screen is not editable by the user; they are used for display purposes only.
WLabel = tk.Label( text = "I am a Label with blue background and red foreground", background = "blue", foreground = "red" ) WLabel.pack()
If you don’t feel like typing out foreground and background all the time, you can use the shorthand fg and bg parameters to set the foreground and background colors:
WLabel = tk.Label(text="Hello, Tkinter", fg="white", bg="black")
Note: To ensure that the program behaves consistently across platforms, Tkinter employs text units rather than measures like inches, millimeters, or pixels for width and height measurements.
When units are calculated based on character width, a widget's size is determined by the user's computer's default font. No matter where the application is running, this guarantees that the text will fit appropriately on labels and buttons.
To render an image on the screen using the Label method you have to create an object of class PhotoImage and pass it into the label image parameter
logo = tk.PhotoImage(file="giphy.gif") WLableImage = tk.Label(image=logo)
Note: At present, only GIF and PPM/PGM formats are supported, but an interface exists to allow additional image file formats to be added easily.
Buttons are used to render clickable buttons. You can use the call functions when the button is clicked, you can style your button with optional parameters, call functions, etc.
WButton = tk.Button( text = "Click Me!", width = 20, height = 10, bg = "red", fg = "blue" ) WButton.pack()
You can pass the command parameter and specify the function, remember not to call the function but only provide its signature.
def out(): print("Button Clicked") WButton = tk.Button( text = "Click Me!", width = 20, height = 10, bg = "red", fg = "blue", command = out ) WButton.pack()
When you click the button, a 'Button Clicked' message will be displayed in your console.
The fundamental Tkinter widgets, or entry widgets, are used to collect input from application users in the form of text strings. One line of text can be entered with this widget. The content will scroll if the user enters a string that is longer than the widget’s allotted display area. This indicates that the complete string cannot be seen.
To access the string’s unseen sections, use the arrow keys. You must use the text widget if you wish to enter numerous lines of text. A single typeface can only be used in an entry widget.
tk.Label(master, text="First Name").grid(row=0) tk.Label(master, text="Last Name").grid(row=1) e1 = tk.Entry(master) e2 = tk.Entry(master) e1.grid(row=0, column=1) e2.grid(row=1, column=1)
Here in this program, we used a grid, which is used to display widgets in the matrix or a grid format by providing two value row and a column.
You can get the provided input data using the get method, you can use a function and bind it to a button to display the data on the button click.
def show(): tk.Label(text=e1.get()).grid(row=3,column=0) tk.Label(text=e2.get()).grid(row=3,column=1) tk.Label(master, text="First Name").grid(row=0) tk.Label(master, text="Last Name").grid(row=1) e1 = tk.Entry(master) e2 = tk.Entry(master) b1 = tk.Button(text="show", command=show) e1.grid(row=0, column=1) e2.grid(row=1, column=1) b1.grid(row=2, column=1)
Checkboxes, also known as tickboxes, are widgets that let users select numerous items from a variety of choices. This is distinct from a radio button, which allows the user to select only one option.
Typically, checkboxes appear on screens as square boxes with either a tick mark or an X (for checked) or a white space (for false) (for true, i.e. checked).
Typically, a caption detailing the checkbox’s purpose is displayed next to it. Clicking on a checkbox changes the checkbox’s state. The caption can also be selected by clicking on it, or a keyboard shortcut, like the space bar, can be used instead.
A checkbox can be either turned on or off.
The Tkinter checkbutton widget supports images, text with a single font, and buttons that are connected to Python functions and methods. Tkinter invokes the associated function or method whenever a button is pressed. A button’s wording may extend across multiple lines.
Below is a sample program demonstrating the checkbox and button.
from tkinter import * class Checkbar(Frame): def __init__(self, parent=None, picks=, side=LEFT, anchor=W): Frame.__init__(self, parent) self.vars =  for pick in picks: var = IntVar() chk = Checkbutton(self, text=pick, variable=var) chk.pack(side=side, anchor=anchor, expand=YES) self.vars.append(var) def state(self): return map((lambda var: var.get()), self.vars) if __name__ == '__main__': root = Tk() lng = Checkbar(root, ['Python', 'Ruby', 'Perl', 'C++']) tgl = Checkbar(root, ['English', 'German']) lng.pack(side=TOP, fill=X) tgl.pack(side=LEFT) lng.config(relief=GROOVE, bd=2) def allstates(): print(list(lng.state()), list(tgl.state())) Button(root, text='Quit', command=root.quit).pack(side=RIGHT) Button(root, text='Peek', command=allstates).pack(side=RIGHT) root.mainloop()
Note: IntVar() function is used to make variables in tkinter. This example shows how you can create widgets dynamically using classes and loops. Loops are very useful for building tables or chart structures.
You can use this widget to make any form for your application, you can take data from the user, process it, and display the results. There are many more widgets in the Tkinter library.
Tkinter have only three geometry managers - pack, grid, and place.
Never combine the three layout managers, pack, grid, and place, in the same master window! Different purposes are served by geometry managers. They arrange widgets on the screen, register widgets with the underlying windowing system, manage the display of widgets on the screen
Choosing the size and placement of widget components entails arranging their components on the screen. Geometry managers can get size and alignment information from widgets, but they always have the last say in terms of positioning and sizing.
Of the three geometry managers for Tk and Tkinter, pack is the most user-friendly. Instead of specifying the exact location of a widget on the display screen, we may specify the positions of widgets relative to one another using the pack command. The pack command handles the specifics. Although the pack command is simpler to use, it has fewer options than the grid and place managers for layout management. It is undoubtedly the manager of choice for straightforward applications. Simple applications could consist of stacking or arranging several widgets one on top of the other.
import tkinter as tk root = tk.Tk() w = tk.Label(root, text="Red Sun", bg="red", fg="white") w.pack() w = tk.Label(root, text="Green Grass", bg="green", fg="black") w.pack() w = tk.Label(root, text="Blue Sky", bg="blue", fg="white") w.pack() tk.mainloop()
We have passed the object of the class Tk because in Tkinter you can create a widget known as a frame. The frame contains a group of widgets together but doesn’t contain a visible body.
from tkinter import * root = Tk() frame = Frame(root) frame.pack() bottomframe = Frame(root) redbutton = Button(frame, text="Red", fg="red") greenbutton = Button(frame, text="Brown", fg="brown") bluebutton = Button(frame, text="Blue", fg="blue") blackbutton = Button(bottomframe, text="Black", fg="black") bottomframe.pack( side = BOTTOM ) redbutton.pack( side = LEFT) greenbutton.pack( side = LEFT ) bluebutton.pack( side = LEFT ) blackbutton.pack( side = BOTTOM) root.mainloop()
To specify the specific location that a widget should occupy in a window or frame, use the .place() function. Two keyword arguments, x and y, are required and must be used to indicate the x- and y-coordinates for the widget’s top-left corner. Pixels, not text units, are used to measure both x and y.
Remember that the top-left corner of the frame or window is the origin, where x and y are both 0. As a result, the y argument of .place() can be thought of as the distance in pixels from the window’s top, and the x argument as the distance from the window’s left edge.
This is an illustration of how the .place() geometry manager functions:
Wlabel1 = tk.Label(master=frame, text="I'm at (0, 0)", bg="red") Wlabel2 = tk.Label(master=frame, text="I'm at (20, 20)", bg="yellow") Wlabel1.place(x=0, y=0) Wlabel2.place(x=20, y=20)
There is a couple of drawbacks to using place geometry manager:
1. Layout might be challenging to manage in a place(). This is particularly true if your application contains a large number of widgets.
2. The layouts created by place() are not responsive. When the window is resized, they remain unchanged. This is the reason developers don’t use place often or avoid using it.
The majority of the time, .pack() is preferable to .place(), although even .pack() has drawbacks. Without a thorough grasp of the code governing the layout, it can be challenging to adapt old apps because the positioning of widgets depends on the sequence in which .pack() is invoked. Many of these problems are resolved by the. grid() geometry manager, as you’ll see in the following section.
The pack had been the first geometry manager for Tk. Pack’s algorithmic behavior is difficult to comprehend, and changing an existing design might be challenging. In 1996, the grid was created to replace the pack. Although the grid is simpler to use and learn and it creates superior layouts, many developers continue to use pack.
The grid is the best option for many use cases in many situations. The place allows you complete control over the location of every element, but this makes it much more complex than pack and grid. The pack is sometimes insufficient for modifying layout specifics.
A window or frame is divided into rows and columns for .grid() to function. You may specify the widget's placement by calling .grid() and supplying the row and column indices to the corresponding keyword arguments. A row index of 1 and a column number of 2 instructs .grid() to place a widget in the third column of the second row because both row and column indices begin at 0.
colors = ['red', 'green', 'orange', 'white', 'yellow', 'blue'] row = 0 for column in colors: tk.Label(text=column, relief=tk.RIDGE, width=15).grid(row=r, column=0) tk.Entry(bg=column, relief=tk.SUNKEN, width=10).grid(row=r, column=1) row = row + 1
GUI menus display a combination of text and symbols to show the available options. An action will be started by clicking on one of the symbols or text. Such a procedure or action might involve, for instance, starting or stopping an application, opening or saving a file, or closing one.
A context menu is where the choices are altered based on the context.
The following Python script creates a simple application window with menus.
from tkinter import * from tkinter.filedialog import askopenfilename def NewFile(): print("New File!") def OpenFile(): name = askopenfilename() print(name) def About(): print("example of a menu") window = Tk() menu = Menu(window) window.config(menu=menu) filemenu = Menu(menu) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="New", command=NewFile) filemenu.add_command(label="Open...", command=OpenFile) filemenu.add_separator() filemenu.add_command(label="Exit", command=window.quit) helpmenu = Menu(menu) menu.add_cascade(label="Help", menu=helpmenu) helpmenu.add_command(label="About...", command=About) mainloop()
All the things mentioned above can be used to create classic but functional GUI applications which make your shell application a hint of a button. You can use the official documentation by Python to get more parameters and widgets to use in your application, you can also check out Tk for the styled widget which provides a modern look.
Python can be used to make GUI very easily with robust and maintainable code boilerplate code that can be automated and produce a table-like structure.
Tkinter is useful if you want to build a less complex structure for your application. Everything is a widget and deploying functionality to the widget is also straightforward.
Hence, Python with Tkinter can be used to produce a small application with ease.
Shubham is a skilled data analyst, machine learning, computer vision, researcher, and freelance. Contributing to open-source programs and organizations to provide open education. Currently acting as R&D Head@ACE. He writes about ML and statistics.
Tell us the skills you need and we'll find the best developer for you in days, not weeks.