Back to: Python Tutorials For Beginners and Professionals
Despite the fact that there are many GUI frameworks in Python, only Tkinter is built into the Python standard library. There are several strengths to Tkinter. The cross-platform nature of the tkinter allows it to run on Windows, Mac OS, and Linux. With Tkinter, visual elements appear as if they belong on the platform where they are run since they run using native operating system elements.
This article introduces the fundamentals of GUI programming using Tkinter.
What is a GUI?
Graphical user interfaces (GUIs) allow you to interact with computers on the desktop. They use desktop computers, laptop computers, and mobile devices to carry out various tasks. Various types of files can be built, read, downloaded, and erased using text editors and other graphical user interface applications. With these apps, you can also play Sudoku, Chess, and Solitaire. Examples of GUI Internet browsers include Google Chrome, Firefox, and Microsoft Edge.
A graphic user interface would become the standard for user-centered programming in software applications. It allows users to control computers and other electronic devices intuitively by manipulating graphical icons like buttons, scroll bars, windows, tabs, menus, cursors, and the mouse-pointing device directly. Touchscreens and voice-command interactions are common features of modern graphical user interfaces.
GUIs are designed to be intuitive enough so that they can be operated even by individuals without any programming skills. As opposed to being fundamentally machine-centered, their design is always user-centered, making them the standard in software application programming.
Python GUI use cases
The examples below illustrate just a few of the popular things that can be done with Python GUI programming!
1. Developing a mobile application
In many ways, mobile apps are great examples of Python GUIs in action, with easy-to-use interfaces for liking, posting, commenting, and interacting! Did you know some of these successful and popular mobile apps are written in Python? Do you recognize any of them or use any of them yourself?
2. To build games
Python programming language has also been used to create some of the games we know and love! The game industry heavily leverages GUIs to create value and enjoyment for users with flashy graphics and rewarding interactivity. It was Python that was used to program games such as Flappy Bird and Mount & Blade!
3. Industries that utilize human-machine interfaces
It is true that GUIs are used prominently in entertainment and utility, but they also serve an important role in the industrial sector through Human Machine Interfaces (HMIs). Operators can use HMIs to monitor and control industrial systems as well as rectify anomalies in operating conditions using an easy-to-use GUI. Developing industrial applications with Python is easy and affordable, which is a crucial factor for businesses.
GUI Frameworks for Python
Python’s popularity as a GUI programming language can be attributed to the frameworks available. Here are a few popular choices to get you started, although there are many others available for developers with different tastes.
4. Python QT
The ease of use and quickness of Tkinter makes it the first choice for a lot of learners and developers. Tkinter allows you to create basic graphical user interfaces (GUIs) using Python. Python GUI applications are mostly built with this module.
Next, let’s take a look at Tkinter.
What is Tkinter?
Python’s Tkinter module is used for creating GUI applications. This module is one of the most commonly used in Python for creating GUI applications due to its simplicity and ease of use. It’s not necessary to install Tkinter separately since it is included with Python. One of the things that make Tkinter stand out is its modularity with widgets. Widgets are customizable components that can be combined easily to create a complete GUI. There are many types of widgets, such as frames, buttons, check buttons, labels, dialog boxes, etc.
Tkinter is actually a package with lots of modules. Following is a list of them:
|tkinter.scrolledtext||Text widget that offers vertical scrolling|
|tkinter.colorchooser||A dialog box where the user can choose a color.|
|tkinter.commondialog||Defines the dialogs found in the other modules listed here|
|tkinter.filedialog||Provides common dialogs for selecting and saving files|
|tkinter.font||A collection of font-related utilities.|
|tkinter.messagebox||Provides access to Tk dialog boxes.|
|tkinter.simpledialog||Provides basic dialogs and convenience functions|
|tkinter.dnd||Drag-and-drop support for tkinter.|
|tkinter.ttk||provides access to Tk themed widgets|
Widgets are elements of the Graphical User Interface (GUI) that provide information display/illustration or allow users to interact with the operating system. Widgets in Tkinter are objects representing buttons, frames, etc.
Each widget is an object in Python. A widget’s parent must be passed as a parameter to the widget creation function. There is only one exception: the “root” window, which contains all the other windows and has no parent.
Python Tkinter module includes 19 widgets. Listed below are all the widgets, along with their basic descriptions:
|Button||Adds various types of buttons to Python applications|
|Canvas||This widget allows you to draw a canvas on your window.|
|CheckButton||A Check button widget is used if you want to display multiple options as checkboxes. With it, you can select multiple options at the same time.|
|Entry||This widget displays a single-line text field that allows users to enter values.|
|Frames||They serve as containers in Tkinter.|
|Labels||It can be used to create single-line widgets, such as text and photographs.|
|Listbox||It is used to display a list of options for the user.|
|Menubutton||Using the Menubutton widget, you can create menus in your application.|
|Menu||Menu widgets provide users with various commands. Those commands are contained within the Menubutton.|
|Message||Message widgets mostly display message boxes to users. It is a multi-line text that cannot be edited.|
|Scrollbar||Using this widget, you can implement vertically scrolling widgets such as Listboxes, Text, and Canvases.|
|Scale||A Scale widget is used to pick a single value from a set of values. The sliding bar can be used to select values from left to right or from top to bottom.|
|Radiobutton||This widget displays various options as radio buttons. A user can only select one option at a time.|
|Text||Displaying text on multiple lines is possible with the Text widget.|
|Toplevel||Toplevel widgets provide separate window containers.|
|SpinBox||Spin Box serves as an entry point to the “Entry widget” that accepts a fixed number value as input|
|PannedWindow||It is also a container widget that handles different panes. Inside it, you can arrange the panes either horizontally or vertically|
|LabelFrame||Labelframe are simple container widgets. In general, it sits between complex window layouts as a spacer or container.|
|tkMessageBox||In your applications, message boxes are displayed using this module.|
Tkinter geometry specifies how widgets are displayed on the screen. Following are the geometry methods provided by Tkinter in Python.
- The pack() method
- The grid() method
- The place() method
Our next step will be to examine each of them in more detail.
The pack() method
The function returns a geometry manager that organizes the widgets according to their relative positions. Placements like this are useful for arranging controls horizontally or vertically.
A widget can be made as wide as possible using the pack() function (fill=X) or as tall as possible using the fill() function (fill=Y). It is also possible to leave certain margins along the width and height with the padx and pady options.
from tkinter import * parent = Tk() button1 = Button(parent, text = "Hello", fg = "black") button1.pack( side = LEFT) button2 = Button(parent, text = "Muthu", fg = "black") button2.pack( side = RIGHT ) button3 = Button(parent, text = "Annamalai", fg = "black") button3.pack( side = TOP ) button4 = Button(parent, text = "Venkatachalam", fg = "black") button4.pack( side = BOTTOM) parent.mainloop()
The grid method
Widgets are arranged in tabular form using the grid() geometry manager. In the method call, we can specify rows and columns. It is also possible to specify the column span (width) and rowspan (height) of a widget. The widgets can be placed in a more organized manner this way.
from tkinter import * parent = Tk() name = Label(parent,text = "Enter your email").grid(row = 0, column = 0) e1 = Entry(parent).grid(row = 0, column = 1) password = Label(parent,text = "Enter your name").grid(row = 1, column = 0) e2 = Entry(parent).grid(row = 1, column = 1) submit = Button(parent, text = "Submit button").grid(row = 4, column = 0) parent.mainloop()
The place method
The geometry manager arranges the controls in the application window according to their absolute positioning. The widget’s absolute coordinates are relative to the window’s dimensions.
from tkinter import * top = Tk() top.geometry("400x250") name = Label(top, text = "Name").place(x = 30,y = 50) email = Label(top, text = "Age").place(x = 30, y = 90) password = Label(top, text = "Occupation").place(x = 30, y = 130) e1 = Entry(top).place(x = 80, y = 50) e2 = Entry(top).place(x = 80, y = 90) e3 = Entry(top).place(x = 95, y = 130) top.mainloop()
Tkinter Event handling:
Due to its event listening loop, the Application object anticipates events at all times. There are different types of GUI widgets that can identify different types of user interactions, called events. When a user clicks a mouse button or double clicks it, types text in an entry box changes the focus of a widget, etc., an event object is created. Event notifications are sent to an application object that maps them to user-defined event handlers. In order to be processed, any event must be registered with one or more GUI widgets.
Identifiers of events consist of the type, the modifier, and the qualifier in the string format <modifier-type-qualifier>
The following are some tkinter events:
|<Button-1>||Button||1||Clicks the mouse left button.|
|<Button-2>||Button||2||Clicks the middle mouse button.|
|<Destroy>||Destroy||Enables the destruction of the window|
|<Double-Button-1>||Double||Button||1||Click the mouse button1 twice.|
|<Enter>||Expose||The cursor enters the window or widget|
|<Expose>||Keypress||It displays the window completely or partially.|
|<KeyPress-a>||KeyPress||a||Key that is pressed.|
|<KeyRelease>||KeyRelease||Any released key.|
|<Leave>||Leave||The cursor leaves the window.|
|<Print>||The PRINT key has been activated|
|<FocusIn>||FocusIn||Widget gains attention|
How to organize Layouts And Widgets in Tkinter?
In order to arrange the layout in the window, we will use the Frame class. Now let’s take a look at the steps involved in organizing the layouts and widgets
Here are the steps involved
- The frame is responsible for creating the divisions in the window. With the side parameter of pack(), you can align the frames as you wish.
- By clicking the Button, you will create a button in the window. It takes several parameters, including text (Button value), fg (Text color), and bg (Background color).
import tkinter window = tkinter.Tk() window.title("gui") tkinter.Label(window, text = "Name").grid(row = 0) tkinter.Entry(window).grid(row = 0, column = 1) tkinter.Label(window, text = "Age").grid(row = 1) tkinter.Entry(window).grid(row = 1, column = 1) tkinter.Checkbutton(window, text = "Do you want to logged in always").grid(columnspan = 2) window.mainloop()
How to Build Your First Python GUI Application With Tkinter?
The following steps will guide you through the process of building your first Python GUI application using Tkinter:
1. Import the Tkinter module as follows:
import tkinter as tk
2. Set up the main window as follows:
window = tk.Tk()
3. Add widgets to the main window
codelabel = tk.Label(window, text=”Hello How are you!”)
label.pack() button = tk.Button(window, text=”Press Me”, command=say_hi)
4. Add any necessary functions:
def say_hi(): label.config(text=”Hi!”)
5. Start the GUI event loop, by doing this:
Example of a Tkinter Application: A temperature converter app
There are two buttons in this program, one for converting degrees Fahrenheit to Celsius and one for converting degrees Celsius to Fahrenheit. As soon as you click a button, the corresponding conversion function will be called, calculating the result and updating the output field.
A variety of widgets can be customized according to their appearance and behavior, the GUI layout can be changed, and functions can be bound to events like key presses and mouse clicks, allowing you to build more interactive and complex applications.
import tkinter as tk window = tk.Tk() window.title("Temperature Conversion Calculator") input_field = tk.Entry(window) input_field.pack() output_field = tk.Label(window) output_field.pack() def celsius_temperature_to_fahrenheit_temperature(): celsius_temperature = float(input_field.get()) fahrenheit_temperature = celsius_temperature * 9 / 5 + 32 output_field.config(text=str(fahrenheit_temperature) + "°F") def fahrenheit_temperature_to_celsius_temperature(): fahrenheit_temperature = float(input_field.get()) celsius_temperature = (fahrenheit_temperature - 32) * 5 / 9 output_field.config(text=str(celsius_temperature) + "°C") celsius_temperature_button = tk.Button(window, text="Press this to Convert to Fahrenheit", command=celsius_temperature_to_fahrenheit_temperature) fahrenheit_temperature_button = tk.Button(window, text="Press this to Convert to Celsius", command=fahrenheit_temperature_to_celsius_temperature) celsius_temperature_button.pack() fahrenheit_temperature_button.pack() window.mainloop()
Throughout this article, you learned how to create GUI applications using Python. As a Python GUI framework, Tkinter is a great choice since it’s part of the standard Python library and is relatively easy to use.
Having mastered the foundations of Python GUI programming with Tkinter, it’s time to build some applications of your own. What are you going to create? Comment below with your fun projects!