Python GUI Programming using Tkinter
Python GUI Programming using Tkinter
Introduction:
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()
Output:
Tkinter widgets:
There are various widgets like button, label,entry, canvas, checkbutton,Radio button, frame etc. that
are used to build the python GUI applications.
Example
# !/usr/bin/python3
from tkinter import *
parent = Tk()
redbutton = Button(parent, text = "Red", fg = "red")
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:
S Option Description
N
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.
3 Bd It represents the border width in pixels.
4 Bg It represents the background color of the button.
5 Command It is set to the function call which is scheduled when the function is
called.
6 Fg Foreground color of the button.
7 Font The font of the button text.
8 Height The height of the button. The height is represented in the number of text
lines for the textual lines or the number of pixels for the images.
10 Highlightcolor The color of the highlight when the button has the focus.
11 Image It is set to the image displayed on the button.
12 justify It illustrates the way by which the multiple text lines are represented. It is
set to LEFT for left justification, RIGHT for the right justification, and
CENTER for the center.
13 Padx Additional padding to the button in the horizontal direction.
14 pady Additional padding to the button in the vertical direction.
15 Relief It represents the type of the border. It can be SUNKEN, RAISED,
GROOVE, and RIDGE.
17 State This option is set to DISABLED to make the button unresponsive. The
ACTIVE represents the active state of the button.
18 Underline Set this option to make the button text underlined.
19 Width The width of the button. It exists as a number of letters for textual buttons
or pixels for image buttons.
20 Wraplength If the value is set to a positive number, the text lines will be wrapped to fit
within this length.
Example
from tkinter import *
top = Tk()
top.geometry("200x100")
def fun():
messagebox.showinfo("Hello", "Red Button clicked")
Example
# !/usr/bin/python3
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)
sbmitbtn = Button(top, text = "Submit",activebackground = "pink", activeforeground = "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()
Output:
Example:
# !/usr/bin/python3
from tkinter import *
top = Tk()
top.geometry("400x250")
#creating label
uname = Label(top, text = "Username").place(x = 30,y = 50)
#creating label
password = Label(top, text = "Password").place(x = 30, y = 90)
sbmitbtn = Button(top, text = "Submit",activebackground = "pink", activeforeground = "blue").place
(x = 30, y = 120)
e1 = Entry(top,width = 20).place(x = 100, y = 50)
e2 = Entry(top, width = 20).place(x = 100, y = 90)
top.mainloop()
Output:
Methods:
The methods that can be called with the Checkbuttons are described in the following table.
SN Method Description
1 deselect() It is called to turn off the checkbutton.
2 flash() The checkbutton is flashed between the active and normal colors.
3 invoke() This will invoke the method associated with the checkbutton.
4 select() It is called to turn on the checkbutton.
5 toggle() It is used to toggle between the different Checkbuttons.
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)
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:
S Option Description
N
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.
4 bg The background color of the widget.
5 bitmap It is used to display the graphics on the widget. It can be set to
any graphical or image object.
6 borderwidth It represents the size of the border.
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.
9 font It represents the font type of the widget text.
10 fg The normal foreground color of the widget text.
11 height The vertical dimension of the widget. It is specified as the
number of lines (not pixel).
12 highlightcolor It represents the color of the focus highlight when the widget has
the focus.
13 highlightbackground The color of the focus highlight when the widget is not having
the focus.
14 image It can be set to an image object if we want to display an image
on the radiobutton instead the text.
15 justify It represents the justification of the multi-line text. It can be set
to CENTER(default), LEFT, or RIGHT.
16 padx The horizontal padding of the widget.
17 pady The vertical padding of the widget.
18 relief The type of the border. The default value is FLAT.
19 selectcolor The color of the radio button when it is selected.
20 selectimage The image to be displayed on the radiobutton when it is selected.
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.
22 text The text to be displayed on the radiobutton.
23 textvariable It is of String type that represents the text displayed by the
widget.
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.
25 value The value of each radiobutton is assigned to the control variable
when it is turned on by the user.
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.
27 width The horizontal dimension of the widget. It is represented as the
number of characters.
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.
S Method Description
N
1 deselect() It is used to turn of the radiobutton.
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.
4 select() It is used to select the radiobutton.
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 )
label = Label(top)
label.pack()
top.mainloop()
Output:
SN Option Description
1 add_command(options) It is used to add the Menu items to the menu.
2 add_radiobutton(options) This method adds the radiobutton to the menu.
3 add_checkbutton(options) This method is used to add the checkbuttons to the menu.
4 add_cascade(options) It is used to create a hierarchical menu to the parent menu by
associating the given menu to the parent menu.
5 add_seperator() It is used to add the seperator line to the menu.
6 add(type, options) It is used to add the specific menu item to the menu.
7 delete(startindex, It is used to delete the menu items exist in the specified range.
endindex)
8 entryconfig(index, It is used to configure a menu item identified by the given index.
options)
9 index(item) It is used to get the index of the specified menu item.
10 insert_seperator(index) It is used to insert a seperator at the specified index.
11 invoke(index) It is used to invoke the associated with the choice given at the
specified index.
12 type(index) It is used to get the type of the choice specified by the index.
Example:
top = Tk()
menubar = Menu(top)
file = Menu(menubar, tearoff=0)
file.add_command(label="New")
file.add_command(label="Open")
file.add_command(label="Save")
file.add_command(label="Save as...")
file.add_command(label="Close")
file.add_separator()
file.add_command(label="Exit", command=top.quit)
menubar.add_cascade(label="File", menu=file)
edit = Menu(menubar, tearoff=0)
edit.add_command(label="Undo")
edit.add_separator()
edit.add_command(label="Cut")
edit.add_command(label="Copy")
edit.add_command(label="Paste")
edit.add_command(label="Delete")
edit.add_command(label="Select All")
menubar.add_cascade(label="Edit", menu=edit)
help = Menu(menubar, tearoff=0)
help.add_command(label="About")
menubar.add_cascade(label="Help", menu=help)
top.config(menu=menubar)
top.mainloop()
Output:
SN Method Description
1 delete(startindex, This method is used to delete the characters of the specified range.
endindex)
2 get(startindex, It returns the characters present in the specified range.
endindex)
3 index(index) It is used to get the absolute index of the specified index.
4 insert(index, It is used to insert the specified string at the given index.
string)
5 see(index) It returns a boolean value true or false depending upon whether the text
at the specified index is visible or not.
1. default
The default option is used to mention the types of the default button, i.e. ABORT, RETRY, or
IGNORE in the message box.
2. parent
The parent option specifies the parent window on top of which, the message box is to be
displayed.
There is one of the following functions used to show the appropriate message boxes. All the
functions are used with the same syntax but have the specific functionalities.
13. showerror(): This method is used to display the error message to the user.
Consider the following example.
Example
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
messagebox.showerror("error","Error")
top.mainloop()
Output:
14. askquestion(): This method is used to ask some question to the user which can be
answered in yes or no. Consider the following example.
Example
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
messagebox.askquestion("Confirm","Are you sure?")
top.mainloop()
Output:
5. askokcancel(): This method is used to confirm the user's action regarding some
application activity. Consider the following example.
Example
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
messagebox.askokcancel("Redirect","Redirecting you to www.javatpoint.com")
top.mainloop()
Output:
6. askyesno(): This method is used to ask the user about some action to which, the
user can answer in yes or no. Consider the following example.
Example
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
messagebox.askyesno("Application","Got It?")
top.mainloop()
Output:
7. askretrycancel(): This method is used to ask the user about doing a particular task
again or not. Consider the following example.
Example
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
messagebox.askretrycancel("Application","try again?")
top.mainloop()
Output: