Python Tkinter Tutorial
Python Tkinter Tutorial
Python provides the standard library Tkinter for creating the graphical user interface for
desktop based applications.
Developing desktop based applications with python Tkinter is not a complex task. 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.
Example
# !/usr/bin/python3 from tkinter
import *
#creating the application main window.
top = Tk()
#Entering the event main loop top.mainloop()
Tkinter widgets
There are various widgets like button, canvas, checkbutton, entry, etc. that are used to build
the python GUI applications.
SN Widget Description
1 Button
2 Canvas The canvas widget is used to draw the canvas on the window.
4 Entry
The entry widget is used to display the single-line text field to the
user. It is commonly used to accept user values.
1
5 Frame
6 Label
7 ListBox The ListBox widget is used to display a list of options to the user.
8 Menubutton The Menubutton is used to display the menu items to the user.
10 Message The Message widget is used to display the message-box to the user.
11 Radiobutton
The Radiobutton is different from a checkbutton. Here, the user is
provided with various options and the user can select only one
option among them.
13 Scrollbar
It provides the scrollbar to the user so that the user can scroll the
window up and down.
14 Text
2
15 Spinbox It is an entry widget used to select from options of values.
18 MessageBox
Example
# !/usr/bin/python3
from tkinter import *
parent = Tk()
redbutton = Button(parent, text = "Red", fg = "red")
3
redbutton.pack( side = LEFT)
greenbutton = Button(parent, text = "Black", fg = "black")
greenbutton.pack( side = RIGHT )
bluebutton = Button(parent, text = "Blue", fg = "blue")
bluebutton.pack( side = TOP )
blackbutton = Button(parent, text = "Green", fg = "red")
blackbutton.pack( side = BOTTOM)
parent.mainloop()
Output:
4
AD
Example
from tkinter import *
parent = Tk()
name = Label(parent,text = "Name").grid(row = 0, column = 0)
e1 = Entry(parent).grid(row = 0, column = 1)
password = Label(parent,text = "Password").grid(row = 1,column= 0)
e2 = Entry(parent).grid(row = 1, column = 1)
submit = Button(parent, text = "Submit").grid(row = 4, column = 0)
parent.mainloop()
Output:
Example
from tkinter import *
top = Tk()
top.geometry("400x250")
name = Label(top, text = "Name").place(x = 30,y = 50)
email = Label(top, text = "Email").place(x = 30, y = 90)
password = Label(top, text = "Password").place(x = 30, y= 130)
5
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()
Output:
SN Option Description
1 activebackground
It represents the background of the button when the mouse hover
the button.
2 activeforeground
It represents the font color of the button when the mouse hover
the button.
6
3 Bd It represents the border width in pixels.
5 Command
Example
Output:
Example
from tkinter import *
top= Tk()
top.geometry("200x100")
7
def fun():
messagebox.showinfo("Hello", "Red Button clicked")
b1 = Button(top,text = "Red",command = fun,activeforeground = "red",active background =
"pink",pady=10)
b2 = Button(top, text = "Blue",activeforeground = "blue",activebackground = "pink",pady=10)
b3 = Button(top, text = "Green",activeforeground = "green",activebackground ="pink",
pady = 10)
b4 = Button(top, text = "Yellow",activeforeground = "yellow",activebackground = "pink",
pady = 10)
b1.pack(side = LEFT)
b2.pack(side = RIGHT)
b3.pack(side = TOP)
b4.pack(side = BOTTOM)
top.mainloop()
Output:
SN Option Description
8
2 bd The border width of the widget in pixels.
3 fg It represents the color of the text.
4 font It represents the font type of the text.
5 justify It specifies how the text is organized if the text contains multiple
lines.
6 textvariable It is set to the instance of the StringVar to retrieve the text from
the entry.
7 width The width of the displayed text or image.
Example
top = Tk()
top.geometry("400x250")
name = Label(top, text = "Name").place(x = 30,y =50)
email = Label(top, text = "Email").place(x = 30, y = 90)
password = Label(top, text = "Password").place(x = 30, y = 130)
submit= Button(top, text = "Submit",activebackground = "pink", activefore ground =
"blue").place(x = 30, y = 170)
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()
9
Output
SN Option Description
1 anchor
It specifies the exact position of the text within the size
provided to the widget. The default value is CENTER, which
is used to center the text within the specified space.
3 bitmap
It is used to set the bitmap to the graphical object specified
so that, the label can represent the graphics instead of text.
10
5 cursor
The mouse pointer will be changed to the type of the cursor
specified, i.e., arrow, dot, etc.
6 font The font type of the text written inside the widget.
Example 1
11
Output:
import tkinter as tk
def add():
num1 = float(num1_entry.get())
num2 = float(num2_entry.get())
result = num1 + num2
result_label.config(text=("Sum:"+str(result)))
root=tk.Tk()
root.title("Add Two Numbers")
12
# layout the widgets
gradeText.set(grade)
root = Tk()
root.title("Student Marks Calculation System") ‘
root.geometry("300x400")
13
global e1
global e2
global e3
global e4
global e5
global totText
global avgText
global gradeText
totText = StringVar()
avgText = StringVar()
gradeText = StringVar()
14
marks2 = Entry(root)
marks3 = Entry(root)
marks4 = Entry(root)
marks5 = Entry(root)
root.mainloop()
The Checkbutton is used to track the user's choices provided to the application. In
other words, we can say that Checkbutton is used to implement the on/off selections.
The Checkbutton can contain the text or images. The Checkbutton is mostly used to
provide many choices to the user among which, the user needs to choose the one. It
generally implements many of many selections.
Syntax
w = checkbutton(master, options)
SN Option Description
15
7 cursor The mouse pointer will be changed to the cursor name when it is
over the checkbutton.
12 highlightcolor The color of the focus highlight when the checkbutton is under
focus.
14 justify This specifies the justification of the text if the text contains multiple
lines.
16
24 underline It represents the index of the character in the text which is to be
underlined. The indexing starts with zero in the text.
25 variable It represents the associated variable that tracks the state of the
checkbutton.
27 wraplength If this option is set to an integer number, the text will be broken into
the number of pieces.
Methods
The methods that can be called with the Checkbuttons are described in the following table.
SN Method Description
2 flash() The checkbutton is flashed between the active and normal colors.
3 invoke() This will invoke the method associated with the checkbutton.
Example
from tkinter import *
top = Tk()
top.geometry("200x200")
checkvar1 = IntVar()
checkvar2 = IntVar()
checkvar3 = IntVar()
chkbtn1 = Checkbutton(top, text = "C", variable = checkvar1, onvalue = 1, offvalue
= 0, height = 2, width = 10)
17
chkbtn2 = Checkbutton(top, text = "C++", variable = checkvar2, onvalue = 1,
offvalue = 0, height = 2, width = 10)
chkbtn3 = Checkbutton(top, text = "Java", variable = checkvar3, onvalue = 1,
offvalue = 0, height = 2, width = 10)
chkbtn1.pack()
chkbtn2.pack()
chkbtn3.pack()
top.mainloop
Output:
Eg:
import tkinter
check_1 = tkinter.IntVar()
check_2 = tkinter.IntVar()
check_3 = tkinter.IntVar()
def check1Clicked():
if check_1.get() :
print('Checkbox 1 selected')
else :
print('Checkbox 1 unselected')
def check2Clicked():
if check_2.get() :
18
print('Checkbox 2 selected')
else :
print('Checkbox 2 unselected')
def check3Clicked():
if check_3.get() :
print('Checkbox 3 selected')
else :
print('Checkbox 3 unselected')
window_main.mainloop()
The canvas widget is used to add the structured graphics to the python application. It is
used to draw the graph and plots to the python application. The syntax to use the canvas is given
below.
Syntax
w = canvas(parent, options)
SN Option Description
19
3 confine It is set to make the canvas unscrollable outside the scroll region.
4 cursor The cursor is used as the arrow, circle, dot, etc. on the canvas.
7 relief It represents the type of the border. The possible values are SUNKEN,
RAISED, GROOVE, and RIDGE.
8 scrollregion It represents the coordinates specified as the tuple containing the area
of the canvas.
10 xscrollincrement If it is set to a positive value. The canvas is placed only to the multiple
of this value.
11 xscrollcommand If the canvas is scrollable, this attribute should be the .set() method of
the horizontal scrollbar.
13 yscrollcommand If the canvas is scrollable, this attribute should be the .set() method of
the vertical scrollbar.
Example
20
Output:
Output:
21
Python Tkinter Radiobutton
The Radiobutton widget is used to implement one-of-many selection in the python
application. It shows multiple choices to the user out of which, the user can select only one out of
them. We can associate different methods with each of the radiobutton.
We can display the multiple line text or images on the radiobuttons. To keep track the user's
selection the radiobutton, it is associated with a single variable. Each button displays a single
value for that particular variable.
The syntax to use the Radiobutton is given below.
Syntax
w = Radiobutton(top, options)
SN Option Description
1 activebackground The background color of the widget when it has the focus.
2 activeforeground The font color of the widget text when it has the focus.
3 anchor It represents the exact position of the text within the widget if the
widget contains more space than the requirement of the text. The
default value is CENTER.
7 command This option is set to the procedure which must be called every-
time when the state of the radiobutton is changed.
8 cursor The mouse pointer is changed to the specified cursor type. It can
be set to the arrow, dot, etc.
12 highlightcolor It represents the color of the focus highlight when the widget has
the focus.
22
13 highlightbackground The color of the focus highlight when the widget is not having
the focus.
21 state It represents the state of the radio button. The default state of the
Radiobutton is NORMAL. However, we can set this to DISABLED
to make the radiobutton unresponsive.
24 underline The default value of this option is -1, however, we can set this
option to the number of character which is to be underlined.
26 variable It is the control variable which is used to keep track of the user's
choices. It is shared among all the radiobuttons.
28 wraplength We can wrap the text to the number of lines by setting this option
to the desired number so that each line contains only that
number of characters.
23
Methods
The radio button widget provides the following methods.
SN Method Description
2 flash() It is used to flash the radiobutton between its active and normal colors few
times.
3 invoke() It is used to call any procedure associated when the state of a Radiobutton
is changed.
Example
from tkinter import *
def selection():
selection = "You selected the option " + str(radio.get())
label.config(text = selection)
top = Tk()
top.geometry("300x150")
radio = IntVar()
lbl = Label(text = "Favourite programming language:")
lbl.pack()
R1 = Radiobutton(top, text="C", variable=radio, value=1,
command=selection)
R1.pack( anchor = W )
R2 = Radiobutton(top, text="C++", variable=radio, value=2,
command=selection)
R2.pack( anchor = W )
R3 = Radiobutton(top, text="Java", variable=radio, value=3,
command=selection)
R3.pack( anchor = W)
label = Label(top)
label.pack()
top.mainloop()
24
Output:
Eg:
import tkinter as tk
# Create Radiobuttons
radio_button1 = tk.Radiobutton(window, text="Option 1", variable=radio_var, value="Option 1")
radio_button2 = tk.Radiobutton(window, text="Option 2", variable=radio_var, value="Option 2")
radio_button3 = tk.Radiobutton(window, text="Option 3", variable=radio_var, value="Option 3")
25
def check_if_option_selected():
selected_option = radio_var.get()
if selected_option == "":
print("No option selected.")
else:
print(f"Selected option : {selected_option}")
# Button widget
clear_button = tk.Button(window, text="Check if an Option is Selected",
command=check_if_option_selected)
clear_button.pack()
26