12. Python GUI
Introduction
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python.
Python with tkinter outputs the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task.
What is Tkinter
Tkinter is an inbuilt Python module used to create simple GUI apps. It is the most commonly used module for GUI apps in the Python.You don't need to worry about installation of the Tkinter module as it comes with Python default. Tkinter is a Python interface to the Tk graphics library. Tk is a graphics library widely used and available everywhere.
Tkinter is an open source, portable graphical user interface (GUI) library designed for use in Python scripts. Tkinter relies on the Tk library, the GUI library used by Tcl/Tk and Perl, which is in turn implemented in C. Thus, Tkinter is implemented using multiple layers
Tkinter is included with Python as a library. To use it:
from Tkinter import *
create a tkinter:
Importing the module – tkinter
Create the main window (container)
Add any number of widgets to the main window
Apply the event Trigger on the widgets.
What can I do with Tkinter?
Tkinter gives you the ability to create Windows with widgets in them.
Definition: widget is a graphical component on the screen (button, text label, drop-down menu, scroll bar, picture, etc…)
GUIs are built by arranging and combining different widgets on the screen.
Create First Hello Program
import the module tkinter.
Initialize the window manager with the tkinter.Tk() method and assign it to a variable window. This method creates a blank window with close, maximize and minimize buttons.
Rename the title of the window as you like with the window.title(title_of_the_window).
Label is used to insert some objects into the window. Here, we are adding a Label with some text.
pack() attribute of the widget is used to display the widget in a size it requires.
Finally, the mainloop() method to display the window until you manually close it.
import tkinter
window = tkinter.Tk()
# to rename the title of the window
window.title("Welcome to Tkinter")
# pack is used to show the object in the window
label = tkinter.Label(window, text = "Hello World!").pack()
window.mainloop()
Output:
When you run this program this will open a new window and display text Hello World!
Tkinter Widgets
Widgets are something like elements in the HTML. You will find different types of widgets to the different types of elements in Tkinter.A widget is therefore a graphical object that is available from the Tkinter library. It is a kind of graphical building block. Intuitively, widgets are implemented as classes in Tkinter.
Each widget therefore has a constructor, a destructor, its own set of properties and methods, and so on. While most other GUI toolkits have a very complex widget hierarchy, Tkinter’s hierarchy is extremely simple. All widgets (like Button, Checkbutton, etc.) are derived from the Widget class. All widget subclasses occupy the same level in the hierarchy tree.
Currently there are 19 types of widgets. These are:
Button - The Button widget is used to display buttons in your application.
canvas - The Canvas widget is used to draw shapes, such as lines, ovals, polygons and rectangles, in your application.
checkbutton - The Checkbutton widget is used to display a number of options as checkboxes. The user can select multiple options at a time.
Entry - The Entry widget is used to display a single-line text field for accepting values from a user.
Frame - The Frame widget is used as a container widget to organize other widgets.
Label - The Label widget is used to provide a single-line captions for other widgets. It can also contain images.
Listbox - The Listbox widget is used to provide a list of options to a user.
Menubutton - The Menubutton widget is used to display menus in your application.
Menu - The Menu widget is used to provide various commands to a user. These commands are contained inside Menubutton.
Message - The Message widget is used to display multiline text fields for accepting values from a user.
Radiobutton - The Radiobutton widget is used to display a number of options as radio buttons. The user can select only one option at a time.
Scale - The Scale widget is used to provide a slider widget.
Scrollbar - The Scrollbar widget is used to add scrolling capability to various widgets, such as list boxes.
Text - The Text widget is used to display text in multiple lines.
Toplevel - The Toplevel widget is used to provide a separate window container.
Spinbox - The Spinbox widget is a variant of the standard Tkinter Entry widget, which can be used to select from a fixed number of values.
panedwindow - A PanedWindow is a container widget that may contain any number of panes, arranged horizontally or vertically
labelFrame - A labelframe is a simple container widget. Its primary purpose is to act as a spacer or container for complex window layouts.
tkMessageBox - This module is used to display message boxes in your applications.
Geometry Management
All widgets in the tkinter will have some geometry measurements. These measurements give you to organize the widgets and their parent frames, windows, etc..
Tkinter has the following three Geometry Manager classes.
pack():- It organizes the widgets in the block, which means it occupies the entire available width. It's a standard method to show the widgets in the window
grid():- It organizes the widgets in table-like structure. You will see details about grid later in this tutorial.
place():- It's used to place the widgets at a specific position you want.
Command Handlers
A callback is the name of the function that is to be run in response to an event
Callbacks can be defined as a free standing function in our program or as a class member.
use the 'command=' keyword followed by the command you want executed.
For Example:
from tkinter import *
window = Tk()
window.title("Welcome to Tkinter")
Button (window, text='Click Me', command=window.quit).pack(side=LEFT)
window.mainloop()
# command=window.quit # it says, whenever someone clicks the button, call the window.quit function which will exit from the screen
Organizing Layout And Widgets
To arrange the layout in the window, we will use Frame, class. Let's create a simple program to see how the Frame works
Frame is used to create divisions in the window. You can align the frames as you like with side parameter of pack() method.
Button is used to create a button in the window. It takes several parameters like text(Value of the Button), fg(Color of the text), bg(Background color), etc..,
Note:- The parameter of any widget method must be where to place the widget. In the below code, we use to place in the window, top_frame, bottom_frame.
import tkinter
window = tkinter.Tk()
window.title("Welcome Tkinter")
# creating 2 frames TOP and BOTTOM
top_frame = tkinter.Frame(window).pack()
bottom_frame = tkinter.Frame(window).pack(side = "bottom")
# now, create some widgets in the top_frame and bottom_frame
btn1 = tkinter.Button(top_frame, text = "Button1", fg = "red").pack()
# 'fg - foreground' is used to color the contents
btn2 = tkinter.Button(top_frame, text = "Button2", fg = "green").pack()# 'text' is used to write the text on the Button
btn3 = tkinter.Button(bottom_frame, text = "Button2", fg = "purple").pack(side = "left")# 'side' is used to align the widgets
btn4 = tkinter.Button(bottom_frame, text = "Button2", fg = "orange").pack(side = "left")
window.mainloop()
output:
When you run this program it will create four button in open windows with different text colors inside button
Grid Layout
Grid is another way to organize the widgets. It uses the Matrix row column concepts. Something like this. see the below example to get an idea of how it works.
import tkinter
window = tkinter.Tk()
window.title("Welcome Tkinter")
# creating 2 text labels and input labels
tkinter.Label(window, text = "Username").grid(row = 0) # this is placed in 0 0
# 'Entry' is used to display the input-field
tkinter.Entry(window).grid(row = 0, column = 1) # this is placed in 0 1
tkinter.Label(window, text = "Password").grid(row = 1) # this is placed in 1 0
tkinter.Entry(window).grid(row = 1, column = 1) # this is placed in 1 1
# 'Checkbutton' is used to create the check buttons
tkinter.Checkbutton(window, text = "Keep Me Logged In").grid(columnspan = 2) # 'columnspan' tells to take the width of 2 columns
# you can also use 'rowspan' in the similar manner
window.mainloop()
Output
when you run this program you will get.
Mouse Clicking Events
Clicking events are of 3 different types namely leftClick, middleClick, and rightClick.
Let us see how to call a particular function based on the event that occurs.
import tkinter
window = tkinter.Tk()
window.title("Welcome Tkinter")
#creating 3 different functions for 3 events
def left_click(event):
tkinter.Label(window, text = "Left Click!").pack()
def middle_click(event):
tkinter.Label(window, text = "Middle Click!").pack()
def right_click(event):
tkinter.Label(window, text = "Right Click!").pack()
window.bind("<Button-1>", left_click)
window.bind("<Button-2>", middle_click)
window.bind("<Button-3>", right_click)
window.mainloop()
Output:
If you run the above program, you will see a blank window. Now, click the left, middle and rightbutton to call respective functions.
Classes
Classes is handy when you're developing a large software or something that's big.Let's see how we use Classes in the GUI apps.
import tkinter
class CreateButton:
def __init__(self, window):
self.text_btn = tkinter.Button(window, text = "Click Me!", command = self.say_hi) # create a button to call a function called 'say_hi'
self.text_btn.pack()
self.close_btn = tkinter.Button(window, text = "Close", command = window.quit) # closing the 'window' when you click the button
self.close_btn.pack()
def say_hi(self):
tkinter.Label(window, text = "Hi").pack()
window = tkinter.Tk()
window.title("Welcome Tkinter")
create_btn = CreateButton(window)
window.mainloop()
Drop Down Menus
Steps to create drop down menus are:
Create a root menu to insert different types of menu options using tkinter.Menu(para) and it takes a parameter where to place the Menu.
You have to tell the tkinter to initiate Menu using window_variable.config(menu = para) and it takes a parameter called menu which is the root menu
Now, creating sub menus using same method tkinter.Menu(para) and it takes the parameter root menu.
root menu.add_cascade(para1, menu = para2) creates the name of the sub menu, and it takes 2 parameters one is label which is the name of the sub menu, and another one is menu which is sub menu.
sub menu.add_command() adds an option to the sub menu.
sub menu.add_separator() adds a separator
For Example:
import tkinter
window = tkinter.Tk()
window.title("Menus")
def function():
pass
# creating a root menu to insert all the sub menus
root_menu = tkinter.Menu(window)
window.config(menu = root_menu)
# creating sub menus in the root menu
file_menu = tkinter.Menu(root_menu) # it intializes a new sub menu in the root menu
root_menu.add_cascade(label = "Home", menu = file_menu) # it creates the name of the sub menu
file_menu.add_command(label = "Sub Menu one", command = function) # it adds a option to the sub menu 'command' parameter is used to do some action
file_menu.add_command(label = "Sub Menu two", command = function)
file_menu.add_separator() # it adds a line after the 'Open files' option
file_menu.add_command(label = "Exit", command = window.quit)
# creating another sub menu
edit_menu = tkinter.Menu(root_menu)
root_menu.add_cascade(label = "Edit", menu = edit_menu)
edit_menu.add_command(label = "Undo", command = function)
edit_menu.add_command(label = "Redo", command = function)
window.mainloop()
Alert Box
We can create alert boxes in the tkinter using messagebox method. We can also create questions using the message box method.
For Example:
import tkinter
import tkinter.messagebox
window = tkinter.Tk()
window.title("GUI")
# creating a simple alert box
tkinter.messagebox.showinfo("Alert Message", "This is just an alert message!")
# creating a question to get the response from the user [Yes or No Question]
response = tkinter.messagebox.askquestion("Simple Question", "Do you love Python?")
# If user clicks 'Yes' then it returns 1 else it returns 0
if response == 'yes':
tkinter.Label(window, text = "You love Python!").pack()
else:
tkinter.Label(window, text = "You don't love Python!").pack()
window.mainloop()
Shapes
We can also create shapes using Python GUI. Let us see how to create shapes using Canvas Widget provided by tkinter in GUI.
For Example:
import tkinter
window = tkinter.Tk()
window.title("Welcome Tkinter")
# creating the 'Canvas' area of width and height 500px
canvas = tkinter.Canvas(window, width = 500, height = 500)
canvas.pack()
# 'create_rectangle' is used to create rectangle. Parameters:- (starting x-point, starting y-point, width, height, fill)
# starting point the coordinates of top-left point of rectangle
rect = canvas.create_rectangle(500, 25, 175, 75, fill = "green")
# you 'delete' shapes using delete method passing the name of the variable as parameter.
#canvas.delete(line1)
# you 'delete' all the shapes by passing 'ALL' as parameter to the 'delete' method
# canvas.delete(tkinter.ALL)
window.mainloop()
Images And Icons
we can also add Images and Icons using PhotoImage method.
For Example:
import tkinter
window = tkinter.Tk()
window.title("GUI")
# taking image from the directory and storing the source in a variable
icon = tkinter.PhotoImage(file = "images/download.png")
# displaying the picture using a 'Label' by passing the 'picture' variable to 'image' parameter
label = tkinter.Label(window, image = icon)
label.pack()
window.mainloop()
Frame Widget
Frames are used as containers for other widgets. Widgets placed in a
frame can use any of the geometry managers (but only one per frame)
You can have multiple frames per window
For Example:
from tkinter import *
root= Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
redbutton = Button(frame, text="Red", fg="red")
redbutton.pack( side = LEFT)
greenbutton = Button(frame, text="Brown", fg="brown")
greenbutton.pack( side = LEFT )
bluebutton = Button(frame, text="Blue", fg="blue")
bluebutton.pack( side = LEFT )
blackbutton = Button(bottomframe, text="Black", fg="black")
blackbutton.pack( side = BOTTOM)
root.mainloop()
Checkbutton and RadioButtons
Checkbuttons are used for multiple choice situations, i.e.choosing m of n possible options. This is done by assigning each checkbox a variable of its own.
Radio buttons are used for choosing one of n possible choices; i.e. a mutually exclusive single choice by giving each button a unique value of the same Tkinter variable.
Example of Checkbutton
from tkinter import *
def cb():
print("variable is", var.get())
win = Tk()
var = IntVar()
c = Checkbutton(win, text="Enable Tab",variable=var,command= (lambda: cb()))
c.pack()
mainloop()
Example of Radio Button
from tkinter import *
def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)
root = Tk()
var = IntVar()
R1 = Radiobutton(root, text="Option 1", variable=var, value=1, command=sel)
R1.pack( anchor = W )
R2 = Radiobutton(root, text="Option 2", variable=var, value=2, command=sel)
R2.pack( anchor = W )
R3 = Radiobutton(root, text="Option 3", variable=var, value=3, command=sel)
R3.pack( anchor = W)
label = Label(root)
label.pack()
root.mainloop()
Sliders
A slider is a Tkinter object with which a user can set a value by moving an indicator. Sliders can be vertically or horizontally arranged. A slider is created with the Scale method().
Using the Scale widget creates a graphical object, which allows the user to select a numerical value by moving a knob along a scale of a range of values.
The minimum and maximum values can be set as parameters, as well as the resolution. We can also determine if we want the slider vertically or horizontally positioned.
A Scale widget is a good alternative to an Entry widget, if the user is supposed to put in a number from a finite range, i.e. a bounded numerical value.
For Example:
from tkinter import *
master = Tk()
w = Scale(master, from_=0, to=42)
w.pack()
w = Scale(master, from_=0, to=200, orient=HORIZONTAL)
w.pack()
mainloop()
ListBox
The Listbox widget is used to display a list of alternatives. The listbox can only contain text items, and all items must have the same font and color. Depending on the widget configuration, the user can choose one or more alternatives from the list.
When to use the Listbox Widget
a.) Listboxes are used to select from a group of textual items. Depending on how the listbox is configured, the user can select one or many items from that list
Patterns
a.) When you first create the listbox, it is empty. The first thing to do is usually to insert one or more lines of text. The insert method takes an index and a string to insert. The index is usually an item number (0 for the first item in the list), but you can also use some special indexes, including ACTIVE, which refers to the “active” item (set when you click on an item, or by the arrow keys), and END, which is used to append items to the list.
For Example:
from tkinter import *
master = Tk()
listbox = Listbox(master)
listbox.pack()
listbox.insert(END, "a list entry")
for item in ["one", "two", "three", "four"]:
listbox.insert(END, item)
mainloop()
Scrollbar
This widget is used to implement scrolled listboxes, canvases, and text fields.
The Scrollbar widget is almost always used in conjunction with a Listbox, Canvas, or Text widget. Horizontal scrollbars can also be used with the Entry widget.
To connect a vertical scrollbar to such a widget, you have to do two things:
Set the widget’s yscrollcommand callbacks to the set method of the scrollbar
Set the scrollbar’s command to the yview method of the widget.
For Example:
from tkinter import *
master = Tk()
scrollbar = Scrollbar(master)
scrollbar.pack(side=RIGHT, fill=Y)
listbox = Listbox(master, yscrollcommand=scrollbar.set)
for i in range(1000):
listbox.insert(END, str(i))
listbox.pack(side=LEFT, fill=BOTH)
scrollbar.config(command=listbox.yview)
mainloop()
Entry Widget
used to enter or display a single line of text. To enter multiple lines of text, use the Text widget
For Example:
from tkinter import *
master = Tk()
e = Entry(master)
e.pack()
def callback():
print(e.get())
b = Button(master, text="get", width=10, command=callback)
b.pack()
mainloop()
Message Widget
The Message widget is used to display text. This is a widget not a text window. Use for on screen instructions or to make a custom message window
For Example:
from tkinter import *
master =Tk()
msg = Message(master, text='This is a Simple Text Message to display')
msg.config(font=('times',14))
msg.pack()
mainloop()