Chapter 3:
Graphical User Interfaces (GUI)
in Python Using Tkinter
Graphical User Interfaces
• A GUI (graphical user interface) is a system of interactive visual components for
computer software.
• A GUI displays objects that convey information, and represent actions that can be taken
by the user.
• The objects change color, size, or visibility when the user interacts with them
• The GUI was first developed at Xerox PARC by Alan Kay, Douglas Engelbart, and a
group of other researchers in 1981.
• Later, Apple introduced the Lisacomputer with a GUI on January 19, 1983
• GUI is often pronounced by saying each letter (G-U-I or gee-you-eye).
• It sometimes is also pronounced as "gooey.“
• A GUI includes GUI objects, like icons, cursors, and buttons.
• These graphical elements are sometimes enhanced with sounds, or visual effects like
transparency and drop shadows. Using these objects, a user can use the computer
without having to know commands.
2
Elements of a GUI?
❑ To make a GUI as user-friendly as possible, there are different elements and
objects that the user uses to interact with the software.
❑ Below is a list of each of these with a brief description.
• Button - A graphical representation of a button that performs an action in a program
when pressed
• Dialog box - A type of window that displays additional information, and asks a user for
input.
• Icon - Small graphical representation of a program, features, or file.
• Menu - List of commands or choices offered to the user through the menu bar.
• Menu bar - Thin, horizontal bar containing the labels of menus.
• Ribbon - Replacement for the file menu and toolbar that groups programs activities
together.
• Tab - Clickable area at the top of a window that shows another page or area.
• Toolbar - Row of buttons, often near the top of an application window that controls
software functions.
• Window - Rectangular section of the computer's display that shows the program
currently being used.
3
Benefits of GUI?
❑ A GUI is considered to be more user-friendly than a text- based command-
line interface, such as MS-DOS, or the shell of Unix- like operating systems.
❑ Unlike a command-line operating system or CUI, like Unix or MS-DOS, GUI
operating systems are easier to learn and use because commands do not need to
be memorized.
❑ Additionally, users do not need to know any programming languages. Because of
their ease of use and more modern appearance, GUI operating systems have
come to dominate today's market.
4
…
❑ Examples of a GUI operating system ❑ Examples of a GUI interface
1. Apple macOS
• Microsoft Windows 2. Microsoft Windows
• Apple System 7 and macOS 3. GNOME
• Chrome OS 4. KDE
5. Any Microsoft program, including
• Linux variants like Ubuntu using a GUI
Word, Excel, and Outlook.
interface. 6. Internet browsers,
such as Internet
Explorer, Chrome, and
Firefox.
5
Using the tkinter Module
❑ Python provides the standard library Tkinter for creating the graphical user
interface for desktop based applications.
❑ An empty Tkinter top-level window can be created by using the following steps.
1. import the Tkinter module.
2. Create the main application window.
3. Add the widgets like labels, buttons, frames, etc.
to the window.
4. Call the main event loop so that the
actions can take place on the user's
computer screen.
6
…
First, we will import Tkinter package and create a window
and set its title:
from tkinter import *
window = Tk()
[Link]("Welcome to LikeGeeks app")
[Link]()
The last line which calls mainloop function, this function calls
the endless loop of the window, so the window will wait for
any user interaction till we close it.
If you forget to call the mainloop function, nothing will
appear to the user.
7
Create a label widget
To add a label to our previous example, we will create a label using the label
class like this:
lbl = Label(window, text="Hello")
Then we will set its position on the form using the grid function and give it the
location like this:
[Link](column=0, row=0)
So the complete code will be like this:
from tkinter import *
window = Tk()
[Link]("Welcome to LikeGeeks app")
lbl = Label(window, text="Hello")
[Link](column=0, row=0)
[Link]()
Without calling the grid function for the label, it won’t show up.
8
Set label font size
You can set the label font so you can make it bigger and maybe bold. You can also change the font style.
To do so, you can pass the font parameter like this:
lbl = Label(window, text="Hello", font=("Arial Bold", 50))
Note that the font parameter can be passed to any widget to change its font not labels only.
Great, but the window is so small, we can even see the title, what about setting the window size?
9
Setting window size
We can set the default window size using geometry function like this:
[Link]('350x200')
The above line sets the window width to 350 pixels and the height to 200 pixels.
Let’s try adding more GUI widgets like buttons and see how to handle button click event.
10
Adding a button widget
Let’s start by adding the button to the window, the button is created and added to the window the same as the
label:
btn = Button(window, text="Click Me")
[Link](column=1, row=0)
So our window will be like this:
from tkinter import *
window = Tk()
[Link]("Welcome to LikeGeeks app")
[Link]('350x200')
lbl = Label(window, text="Hello")
[Link](column=0, row=0)
btn = Button(window, text="Click Me")
[Link](column=1, row=0)
[Link]()
Note that we place the button on the second column of the window which is 1. If you forget and place the
button on the same column which is 0, it will show the button only, since the button will be on the top of the
label.
11
Change button foreground and background colors
You can change foreground for a button or any other widget using fg property.
Also, you can change the background color for any widget using bg property.
btn = Button(window, text="Click Me", bg="orange", fg="red")
Now, if you tried to click on the button, nothing happens because the click event of the button isn’t written yet.
12
Handle button click event
First, we will write the function that we need to execute when the button is clicked:
def clicked():
[Link](text="Button was clicked !!")
Then we will wire it with the button by specifying the function like this:
btn = Button(window, text=“Click Me”, command=clicked)
Note that, we typed clicked only not clicked() with parentheses.
Now the full code will be like this:
from tkinter import *
window = Tk()
[Link]("Welcome to LikeGeeks app")
[Link]('350x200')
lbl = Label(window, text="Hello")
[Link](column=0, row=0)
def clicked():
[Link](text="Button was clicked !!")
btn = Button(window, text="Click Me", command=clicked)
[Link](column=1, row=0)
[Link]()
And when we click the button, the result as expected:
13
Get input using Entry class (Tkinter textbox)
In the previous Python GUI examples, we saw how to add simple widgets, now let’s try getting the user input using
Tkinter Entry class (Tkinter textbox).
You can create a textbox using Tkinter Entry class like this:
txt = Entry(window,width=10)
Then you can add it to the window using grid function as usual
So our window will be like this:
from tkinter import *
window = Tk()
[Link]("Welcome to LikeGeeks app")
[Link]('350x200')
lbl = Label(window, text="Hello")
[Link](column=0, row=0)
txt = Entry(window,width=10)
[Link](column=1, row=0)
def clicked():
[Link](text="Button was clicked !!")
btn = Button(window, text="Click Me", command=clicked)
[Link](column=2, row=0)
14
[Link]()
Get input using Entry class (Tkinter textbox) (Con.)
Now, if you click the button, it will show the same old message, what about showing the entered text
on the Entry widget?
First, you can get entry text using get function. So we can write this code to our clicked function like
this:
def clicked():
res = "Welcome to " + [Link]()
[Link](text= res)
If you click the button and there is a text on the entry widget, it will show “Welcome to” concatenated
with the entered text.
15
Get input using Entry class (Tkinter textbox) (Con.)
And this is the complete code:
from tkinter import *
window = Tk()
[Link]("Welcome to LikeGeeks app")
[Link]('350x200')
lbl = Label(window, text="Hello")
[Link](column=0, row=0)
txt = Entry(window,width=10)
[Link](column=1, row=0)
def clicked():
res = "Welcome to " + [Link]()
[Link](text= res)
btn = Button(window, text="Click Me", command=clicked)
[Link](column=2, row=0)
[Link]()
Every time we run the code, we need to click on the entry widget to set focus to write the text, what about setting the
focus automatically?
16
Set focus to entry widget
That’s super easy, all we need to do is to call focus function like this:
[Link]()
And when you run your code, you will notice that the entry widget has the focus so you can write your text
right away.
17
Disable entry widget
To disable entry widget, you can set the state property to disabled:
txt = Entry(window,width=10, state='disabled’)
Now, you won’t be able to enter any text.
18
Add a combobox widget
To add a combobox widget, you can use the Combobox class from ttk library like this:
from [Link] import *
combo = Combobox(window)
Then you can add your values to the combobox.
from tkinter import *
from [Link] import *
window = Tk()
[Link]("Welcome to LikeGeeks app")
[Link]('350x200')
combo = Combobox(window)
combo['values']= (1, 2, 3, 4, 5, "Text")
[Link](1) #set the selected item
[Link](column=0, row=0)
[Link]()
As you can see, we add the combobox items using the tuple.
To set the selected item, you can pass the index of the desired item to the current function.
To get the select item, you can use the get function like this:
[Link]()
19
Add a Checkbutton widget (Tkinter checkbox)
To create a checkbutton widget, you can use Checkbutton class like this:
chk = Checkbutton(window, text='Choose')
Also, you can set the checked state by passing the check value to the Checkbutton like this:
from tkinter import *
from [Link] import *
window = Tk()
[Link]("Welcome to LikeGeeks app")
[Link]('350x200')
chk_state = BooleanVar()
chk_state.set(True) #set check state
chk = Checkbutton(window, text='Choose', var=chk_state)
[Link](column=0, row=0)
[Link]()
20
Set check state of a Checkbutton
Here we create a variable of type BooleanVar which is not a standard Python variable, it’s a Tkinter variable, and then we
pass it to the Checkbutton class to set the check state as the highlighted line in the above example.
You can set the Boolean value to false to make it unchecked.
Also, you can use IntVar instead of BooleanVar and set the value to 0 or 1.
chk_state = IntVar()
chk_state.set(0) #uncheck
chk_state.set(1) #check
These examples give the same result as the BooleanVar.
21
Add radio buttons widgets
To add radio buttons, simply you can use RadioButton class like this:
rad1 = Radiobutton(window,text='First', value=1)
Note that you should set the value for every radio button with a different value, otherwise, they won’t work.
from tkinter import *
from [Link] import *
window = Tk()
[Link]("Welcome to LikeGeeks app")
[Link]('350x200')
rad1 = Radiobutton(window,text='First', value=1)
rad2 = Radiobutton(window,text='Second', value=2)
rad3 = Radiobutton(window,text='Third', value=3)
[Link](column=0, row=0)
[Link](column=1, row=0)
[Link](column=2, row=0)
[Link]()
Also, you can set the command of any of these radio buttons to a specific function, so if the user clicks on any one of them, it runs
the function code. This is an example:
rad1 = Radiobutton(window,text='First', value=1, command=clicked)
22
def clicked(): # Do what you need
Get radio button value (selected radio button)
To get the currently selected radio button or the radio button value, you can pass the variable parameter to the radio
buttons and later you can get its value.
from tkinter import *
from [Link] import *
window = Tk()
[Link]("Welcome to LikeGeeks app")
selected = IntVar()
rad1 = Radiobutton(window,text='First', value=1, variable=selected)
rad2 = Radiobutton(window,text='Second', value=2, variable=selected)
rad3 = Radiobutton(window,text='Third', value=3, variable=selected)
def clicked():
print([Link]())
btn = Button(window, text="Click Me", command=clicked)
[Link](column=0, row=0)
[Link](column=1, row=0)
[Link](column=2, row=0)
[Link](column=3, row=0)
[Link]() 23
Every time you select a radio button, the value of the variable will be changed to the value of the selected radio button.
Add a ScrolledText widget (Tkinter textarea)
To add a ScrolledText widget, you can use the ScrolledText class like this:
from tkinter import scrolledtext
txt = [Link](window,width=40,height=10)
Here we specify the width and the height of the ScrolledText widget, otherwise, it will fill the entire window.
from tkinter import *
from tkinter import scrolledtext
window = Tk()
[Link]("Welcome to LikeGeeks app")
[Link]('350x200')
txt = [Link](window,width=40,height=10)
[Link](column=0,row=0)
[Link]()
24
Set scrolledtext content
To set scrolledtext content, you can use the insert method like this:
[Link](INSERT,'You text goes here’)
Delete/Clear scrolledtext content
To clear the contents of a scrolledtext widget, you can use delete method like this:
[Link](1.0,END)
25
Create a MessageBox
To show a message box using Tkinter, you can use messagebox library like this:
from tkinter import messagebox
[Link]('Message title','Message content’)
Let’s show a message box when the user clicks a button.
from tkinter import *
from tkinter import messagebox
window = Tk()
[Link]("Welcome to LikeGeeks app")
[Link]('350x200')
def clicked():
[Link]('Message title', 'Message content')
btn = Button(window,text='Click here', command=clicked)
[Link](column=0,row=0)
[Link]()
When you click the button, an info messagebox will appear. 26
Show warning and error messages
You can show a warning message or error message the same way. The only thing that needs to be changed is the message
function.
[Link]('Message title', 'Message content') #shows warning message
[Link]('Message title', 'Message content') #shows error message
Show askquestion dialogs
To show a yes no message box to the user, you can use one of the following messagebox functions:
from tkinter import messagebox
res = [Link]('Message title','Message content')
res = [Link]('Message title','Message content')
res = [Link]('Message title','Message content')
res = [Link]('Message title','Message content')
res = [Link]('Message title','Message content’)
You can choose the appropriate message style according to your needs. Just replace the showinfo function line from the
previous line and run it.
Also, you can check what button was clicked using the result variable
If you click OK or yes or retry, it will return True value, but if you choose no or cancel, it will return False.
The only function that returns one of three values is askyesnocancel function, it returns True or False or None. 27
Add a SpinBox (numbers widget)
To create a Spinbox widget, you can use Spinbox class like this:
spin = Spinbox(window, from_=0, to=100)
Here we create a Spinbox widget and we pass the from_ and to parameters to specify the numbers range for the
Spinbox.
Also, you can specify the width of the widget using the width parameter:
spin = Spinbox(window, from_=0, to=100, width=5)
Check the complete example:
from tkinter import *
window = Tk()
[Link]("Welcome to LikeGeeks app")
[Link]('350x200')
spin = Spinbox(window, from_=0, to=100, width=5)
[Link](column=0,row=0)
[Link]()
You can specify the numbers for the Spinbox instead of using the whole range like this:
spin = Spinbox(window, values=(3, 8, 11), width=5)
Here the Spinbox widget only shows these 3 numbers only 3, 8 and 11.
28
Set default value for Spinbox
To set the Spinbox default value, you can pass the value to the textvariable parameter like this:
var =IntVar()
[Link](36)
spin = Spinbox(window, from_=0, to=100, width=5, textvariable=var)
Now, if you run the program, it will show 36 as a default value for the Spinbox.
Add a Progressbar widget
To create a progress bar, you can use the progressbar class like this:
from [Link] import Progressbar
bar = Progressbar(window, length=200)
You can set the progress bar value like this:
bar['value'] = 70
29
Change Progressbar color
Changing Progressbar color is a bit tricky, but super easy.
First, we will create a style and set the background color and finally set the created style to the Progressbar.
Check the following example:
from tkinter import *
from [Link] import Progressbar
from tkinter import ttk
window = Tk()
[Link]("Welcome to LikeGeeks app")
[Link]('350x200')
style = [Link]()
style.theme_use('default')
[Link]("[Link]", background='black')
bar = Progressbar(window, length=200, style='[Link]')
bar['value'] = 70
[Link](column=0, row=0)
[Link]()
30
Add a filedialog (file & directory chooser)
To create a file dialog (file chooser), you can use the filedialog class like this:
from tkinter import filedialog
file = [Link]()
After you choose a file and click open, the file variable will hold that file path.
Also, you can ask for multiple files like this:
files = [Link]()
Specify file types (filter file extensions)
You can specify the file types for a file dialog using filetypes parameter, just specify the extensions in tuples.
file = [Link](filetypes = (("Text files","*.txt"),("all files","*.*")))
You can ask for a directory using askdirectory method:
dir = [Link]()
You can specify the initial directory for the file dialog by specifying the initialdir like this:
from os import path
file = [Link](initialdir= [Link]( file ))
31
Add a Menu bar
To add a menu bar, you can use menu class like this:
from tkinter import Menu
menu = Menu(window)
menu.add_command(label='File')
[Link](menu=menu)
First, we create a menu, then we add our first label, and finally, we assign the menu to our window.
You can add menu items under any menu by using add_cascade() function like this:
menu.add_cascade(label='File', menu=new_item)
So our code will be like this:
from tkinter import *
from tkinter import Menu
window = Tk()
[Link]("Welcome to LikeGeeks app")
menu = Menu(window)
new_item = Menu(menu)
new_item.add_command(label='New')
menu.add_cascade(label='File', menu=new_item)
[Link](menu=menu)
[Link]()
32
Add a Menu bar
Using this way, you can add many menu items as you want.
from tkinter import *
from tkinter import Menu
window = Tk()
[Link]("Welcome to LikeGeeks app")
menu = Menu(window)
new_item = Menu(menu)
new_item.add_command(label='New')
new_item.add_separator()
new_item.add_command(label='Edit')
menu.add_cascade(label='File', menu=new_item)
[Link](menu=menu)
[Link]()
Here we add another menu item called Edit with a menu separator.
You may notice a dashed line at the beginning, well, if you click that line, it will show the menu items in a small separate window.
You can disable this feature by disabling the tearoff feature like this:
new_item = Menu(menu, tearoff=0)
Just replace the new_item in the above example with this one and it won’t show the dashed line anymore.
I don’t need to remind you that you can type any code that works when the user clicks on any menu item by specifying the
command property.
new_item.add_command(label='New', command=clicked)
33
Add a Notebook widget (tab control)
❑ To create a tab control, there are 3 steps to do so. First, we create a tab control using Notebook class Create a tab
using Frame class.
❑ Add that tab to the tab control.
❑ Pack the tab control so it becomes visible in the window.
❑ from tkinter import * from tkinter import ttk window = Tk()
❑ [Link]("Welcome to LikeGeeks app") tab_control = [Link](window)
❑ tab1 = [Link](tab_control) tab_control.add(tab1, text='First')
❑ tab_control.pack(expand=1, fill='both') [Link]()
❑ You can add many tabs as you want the same way.
34
Add widgets to Notebooks
After creating tabs, you can put widgets inside these tabs by assigning the parent property to the desired tab.
from tkinter import *
from tkinter import ttk
window = Tk()
[Link]("Welcome to LikeGeeks app")
tab_control = [Link](window)
tab1 = [Link](tab_control)
tab2 = [Link](tab_control)
tab_control.add(tab1, text='First')
tab_control.add(tab2, text='Second')
lbl1 = Label(tab1, text= 'label1')
[Link](column=0, row=0)
lbl2 = Label(tab2, text= 'label2')
[Link](column=0, row=0)
tab_control.pack(expand=1, fill='both')
[Link]()
35
Add spacing for widgets (padding)
You can add padding for your controls to make it looks well organized using padx and pady properties.
Just pass padx and pady to any widget and give them a value.
lbl1 = Label(tab1, text= 'label1', padx=5, pady=5)
36
End of Chapter 3
37