Python Programming with Tkinter
One of the best modules for the Python programming language is Tkinter. Specifically, a Graphical User Interface is made with it. This module allows us to write some amazing programs. This Tkinter article will assist with understanding Tkinter from the ground up to enhance GUI programming, with all required features thoroughly taught. Discover why should you learn Python and enhance your development skills.
What is Tkinter?
Python’s Tkinter makes it easy to create graphical user interfaces (GUIs). Tkinter is the only GUI framework that comes pre-installed with Python in the Standard Library.
- The cross-platform compatibility of Tkinter allows for easy code translation across Linux, macOS, and Windows.
- The Tkinter module is small and light.
- It does not need to be installed separately because it is included in the normal Python installation.
- Numerous pre-installed widgets are supported, and they can be utilized straight away to develop desktop apps.
Why Tkinter?
Tkinter is implemented as a module in Python and acts as a wrapper for C extensions that make use of Tcl/Tk resources. Tkinter is a useful tool for Python GUI programming since it lets you create desktop apps. Tkinter is a better option because of the following:
- Simple to pick up.
- Create a desktop application that works with little to no code.
- Design with layers.
- Portable on all platforms, including Linux, macOS, and Windows.
- Includes the standard Python library pre-installed.
Suggested Article: Python Developer Salary in India
What are Tcl, Tk, and Tkinter?
Let’s discuss more about the Tkinter module’s origin to gain a better understanding of it.
The Tk toolkit, which was initially created for the Tool Command Language (Tcl), is the foundation of Tkinter. Owing to Tk’s immense popularity, numerous other scripting languages have seen it ported, such as Perl (Perl/Tk), Ruby (Ruby/Tk), and Python (Tkinter).
Tk is the ideal tool for designing and implementing a wide range of simple and complicated projects because of its many widgets, portability, and flexibility.
Building functional desktop apps with Python and Tkinter is quicker and more effective than programming directly in C or C++ with the help of native OS system libraries.
Tkinter Installation
The typical Python installation includes a Tkinter. Therefore, you are done if you have installed the most recent version of Python. Try importing the Tkinter module to find out if Tkinter is supported by your Python interpreter.
import tkinter
There won’t be any errors if Tkinter is available; if not, errors will appear in the console.
Related Article: OOPs Concepts in Python
Build Desktop Application in Python with Tkinter
The following are the fundamental procedures for developing a basic desktop application in Python with the Tkinter module:
- Bring in the Tkinter module first.
- Making a simple desktop application window would be the second stage.
- Next, you can customize the window with various GUI widgets and components, as well as add functionality to them.
- Next, use the mainloop() function to launch the desktop application and enter the main event loop.
Example: Hello World Program in Python with Tkinter
- The first step in creating a desktop application is to open the application in a new window.
- In Tkinter, the Tk class creates the primary window object.
- Once you have a window, you may add buttons, text, and other elements to it.
Here is an example of code:
import tkinter as tk
win = tk.Tk()
win.title(‘Hello World!’)
win.mainloop()
Output
When writing Python desktop apps, two primary approaches are employed:
Tk()
The Tk() method has the following syntax:
Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)
The primary window is created using this way.
You can use it in the same way as the Hello World code example.
win = tkinter.Tk()
The mainloop() function
The application is launched using this way. The application is performed using an infinite loop, the mainloop() function. As long as the window is open, it will wait for events to happen before processing them.
Explore our Python Web Development training syllabus.
Most Popular Tkinter Widgets
Here are a few Tkinter widgets that are often used:
Button: A straightforward button that can be pressed to initiate a process.
Label: This is where basic text is displayed.
Entry: A straightforward area for user input. For single-line input, use this.
Text: This can be used to display text, accept user input, or create multi-line text boxes.
Canvas: You can create custom graphics, photos, and shapes using this widget.
Frame: This widget serves as a container that holds other widgets together.
Checkbutton: Toggle options on and off with this checkbox widget.
Radiobutton: With this, radio buttons can be made.
Listbox: This is a tool for making a list widget that shows a list of values.
Scrollbar: This widget is used to scroll content in listbox and text widgets, among other widgets.
Here is an elementary example of how we have utilized a few of the widgets:
import tkinter as tk
root = tk.Tk()
root.title(“Tkinter World”)
label = tk.Label(root, text=”Hello, SLA Students!”)
label.pack()
entry = tk.Entry(root)
entry.pack()
button = tk.Button(root, text=”Click Me!”)
button.pack()
root.mainloop()
Output
Article Suggestion: Top Reasons Why Should You Choose Python for Big Data
Layout Options of Tkinter
In the last example, we set up the three widgets inside the window in a single column to create a rather simple GUI. We accomplished this by using the pack technique, one of Tkinter’s three accessible geometry managers. For each of our widgets, we must provide a position using one of the various geometry managers; otherwise, the widget will not show up in our window.
Pack aligns widgets vertically, from top to bottom, inside their parent container by default. However, we can use the optional side argument to align widgets left, right, or bottom. Although we can combine various alignments within a single container, complicated layouts might not benefit greatly from this. Still, it ought to function fairly well in our straightforward scenario:
from tkinter import LEFT, RIGHT
# (…)
self.label.pack()
self.greet_button.pack(side=LEFT)
self.close_button.pack(side=RIGHT)
By arranging widgets in frames and aligning the groups according to our preferences, we may use packs to construct rather sophisticated layouts. However, by using the grid technique instead, we can eliminate a lot of this complexity. It gives us more versatility in widget positioning by utilizing a grid architecture. For intricate interfaces, the geometry manager suggested this one:
from tkinter import W
# (…)
self.label.grid(columnspan=2, sticky=W)
self.greet_button.grid(row=1)
self.close_button.grid(row=1, column=1)
We designate a row and a column for each widget when placing it in a cell inside a table; the default row is the first empty row that is available, and the default column is 0.
The sticky option allows us to customize the alignment of a widget if it is smaller than its cell. The cardinal directions (N, S, E, and W) are the potential values, which we may mix by addition. The widget is centered both horizontally and vertically by default, but by passing it through the sticky option, we may force it to adhere to a specific side. For instance, the widget will be stretched to fill the entire cell horizontally when sticky=W+E is applied, and sticky=W will cause it to be left-aligned horizontally. Moreover, we can designate corners with NE, SW, etc.
The columnspan and rowspan parameters allow us to have a widget span several rows or columns. In the example above, we have had the label span two columns so that it occupies the same horizontal area as both of the buttons underneath it.
Place, the third geometry manager, enables us to give widgets precise sizes and locations. Using this strategy for standard GUIs is rarely a good idea because it is too rigid and time-consuming to provide an absolute position for each element. However, there are a few specific situations where it can be helpful.
Recommended Link: Top 5 IDE for Python Programming Language
Custom Events
Thus far, we have solely attached event handlers to events that are predefined in Tkinter; the Button class is already cognizant of button clicks, as clicking is a typical button behavior. But, we are not limited to these specific events; instead, we can use the bind function, which is present on every widget class, to configure widgets to listen for other events and assign handlers to them.
In string format, an event is uniquely recognized by its sequence name; this format is defined by a mini-language that is not Python-specific. Here are some instances of typical occurrences:
- The events “<Button-1>”, “<Button-2>”, and “<Button-3>” indicate that a certain mouse button has been pressed when the mouse pointer is over the relevant widget. Not all mice have a center button, therefore keep in mind that button 1 is the left mouse button, button 3 is the right, and button 2 is the middle button.
- “<ButtonRelease-1>” signifies the release of the left button.
- When the left button is pressed and the mouse is moved, “<B1-Motion>” appears (we may use B2 or B3 for the other buttons).
- The text “<Leave>” and “<Enter>” indicate if the mouse pointer has left or entered the widget.
- “<Key>” indicates that any key has been hit on the keyboard. Additionally, we can listen for certain key combinations, such as “\Shift-Up>” (shift-up-arrow) or “<Return>” (the enter key). For most printed letters, key presses result in the bare character (e.g., the letter an is just “a”) without any brackets.
- “<Configure>” indicates a size modification for the widget.
Now that we have expanded our basic example, we can make the label interactive by having the text on the label cycle through a series of messages each time it is clicked:
from tkinter import Tk, Label, Button, StringVar
class MyFirstGUI:
LABEL_TEXT = [
“This is our first GUI!”,
“Actually, this is our second GUI.”,
“We made it more interesting…”,
“…by making this label interactive.”,
“Go on, click on it again.”,
]
def __init__(self, master):
self.master = master
master.title(“A simple GUI”)
self.label_index = 0
self.label_text = StringVar()
self.label_text.set(self.LABEL_TEXT[self.label_index])
self.label = Label(master, textvariable=self.label_text)
self.label.bind(“<Button-1>”, self.cycle_label_text)
self.label.pack()
self.greet_button = Button(master, text=”Greet”, command=self.greet)
self.greet_button.pack()
self.close_button = Button(master, text=”Close”, command=master.quit)
self.close_button.pack()
def greet(self):
print(“Greetings!”)
def cycle_label_text(self, event):
self.label_index += 1
self.label_index %= len(self.LABEL_TEXT) # wrap around
self.label_text.set(self.LABEL_TEXT[self.label_index])
root = Tk()
my_gui = MyFirstGUI(root)
root.mainloop()
It’s a little complicated to update a label’s text; a regular Python string won’t work for this. Rather, to update the text on the label, we must supply a unique tkinter string variable object to the label and set a new value on it.
We created a handler that iterates through the text strings in the sequence, and we bound our new handler to the left clicks on the label using the label’s bind method. It is significant to notice that an event object, which provides some information about the event, is an additional argument taken by this handler. If a few comparable events occur on various widgets, for instance, we might use the same handler for a variety of events and utilize this parameter to identify between them. We can just disregard the event parameter in this instance since we are only utilizing our handler for one specific type of event.
Explore the top 10 frameworks of Python.
Simple Calculator Program in Python with Tkinter
We can now make a basic calculator using all of this information. A text field will be used for the user to enter a number, which will then be added to or subtracted from a running total that will be shown. Additionally, the user will be able to reset the total:
from tkinter import Tk, Label, Button, Entry, IntVar, END, W, E
class Calculator:
def __init__(self, master):
self.master = master
master.title(“Calculator”)
self.total = 0
self.entered_number = 0
self.total_label_text = IntVar()
self.total_label_text.set(self.total)
self.total_label = Label(master, textvariable=self.total_label_text)
self.label = Label(master, text=”Total:”)
vcmd = master.register(self.validate)
self.entry = Entry(master, validate=”key”, validatecommand=(vcmd, ‘%P’))
self.add_button = Button(master, text=”+”, command=lambda: self.update(“add”))
self.subtract_button = Button(master, text=”-“, command=lambda: self.update(“subtract”))
self.reset_button = Button(master, text=”Reset”, command=lambda: self.update(“reset”))
self.label.grid(row=0, column=0, sticky=W)
self.total_label.grid(row=0, column=1, columnspan=2, sticky=E)
self.entry.grid(row=1, column=0, columnspan=3, sticky=W+E)
self.add_button.grid(row=2, column=0)
self.subtract_button.grid(row=2, column=1)
self.reset_button.grid(row=2, column=2, sticky=W+E)
def validate(self, new_text):
if not new_text:
self.entered_number = 0
return True
try:
self.entered_number = int(new_text)
return True
except ValueError:
return False
def update(self, method):
if method == “add”:
self.total += self.entered_number
elif method == “subtract”:
self.total -= self.entered_number
else: # reset
self.total = 0
self.total_label_text.set(self.total)
self.entry.delete(0, END)
root = Tk()
my_gui = Calculator(root)
root.mainloop()
Our class defines two methods: one for updating our total and the other for validating the data entered in the entry field. Learn about the role of Python in artificial intelligence.
Guessing Game: Python Programming with Tkinter
import random
from tkinter import Tk, Label, Button, Entry, StringVar, DISABLED, NORMAL, END, W, E
class GuessingGame:
def __init__(self, master):
self.master = master
master.title(“Guessing Game”)
self.secret_number = random.randint(1, 100)
self.guess = None
self.num_guesses = 0
self.message = “Guess a number from 1 to 100”
self.label_text = StringVar()
self.label_text.set(self.message)
self.label = Label(master, textvariable=self.label_text)
vcmd = master.register(self.validate) # we have to wrap the command
self.entry = Entry(master, validate=”key”, validatecommand=(vcmd, ‘%P’))
self.guess_button = Button(master, text=”Guess”, command=self.guess_number)
self.reset_button = Button(master, text=”Play again”, command=self.reset, state=DISABLED)
self.label.grid(row=0, column=0, columnspan=2, sticky=W+E)
self.entry.grid(row=1, column=0, columnspan=2, sticky=W+E)
self.guess_button.grid(row=2, column=0)
self.reset_button.grid(row=2, column=1)
def validate(self, new_text):
if not new_text:
self.guess = None
return True
try:
guess = int(new_text)
if 1 <= guess <= 100:
self.guess = guess
return True
else:
return False
except ValueError:
return False
def guess_number(self):
self.num_guesses += 1
if self.guess is None:
self.message = “Guess a number from 1 to 100”
elif self.guess == self.secret_number:
suffix = ” if self.num_guesses == 1 else ‘es’
self.message = “Congratulations! You guessed the number after %d guess%s.” % (self.num_guesses, suffix)
self.guess_button.configure(state=DISABLED)
self.reset_button.configure(state=NORMAL)
elif self.guess < self.secret_number:
self.message = “Too low! Guess again!”
else:
self.message = “Too high! Guess again!”
self.label_text.set(self.message)
def reset(self):
self.entry.delete(0, END)
self.secret_number = random.randint(1, 100)
self.guess = 0
self.num_guesses = 0
self.message = “Guess a number from 1 to 100”
self.label_text.set(self.message)
self.guess_button.configure(state=NORMAL)
self.reset_button.configure(state=DISABLED)
root = Tk()
my_gui = GuessingGame(root)
root.mainloop()
Try this game code and enhance your Python skills. The reason behind the bright future of Python will amaze you and encourage you to learn Python programming.
Alternatives of Tkinter
Python offer numerous methods for creating projects and apps with a graphical user interface. Below are several approaches:
PyQt/PySide
The Qt framework is the foundation for PyQt and PySide. Both desktop and mobile devices can make use of it. Both open-source and free.
wxPython
This C++ GUI toolkit is available for free and runs on multiple platforms. An additional substitute for Tkinter.
Kivy
Developing multi-touch compatible modern applications for smartphones and tablets can benefit from this. It can be used to construct programs and games for contemporary mobile devices.
Python GTK+
This can be used to write programs that use GTK.
Toga
It is a multi-platform, native toolkit that may be used to make high-quality desktop apps.
Useful Link: Python Interview Questions and Answers
End Note
Learn Python Programming with Tkinter with comprehensive hands-on exposure at SLA Jobs. Explore a wide range of opportunities in the Python domain by enrolling in our Python training in Chennai with 100% placement assistance.