PythonGUI
PythonGUI
Python provides various options for developing graphical user interfaces (GUIs). Most
important are listed below.
Tkinter − Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We
would look this option in this chapter.
Tkinter Programming: Tkinter is the standard GUI library for Python. Python when
combined with Tkinter provides a fast and easy way to create GUI applications. Tkinter
provides a powerful object-oriented interface to the Tk GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All you need to do is perform the
following steps −
4. Enter the main event loop to take action against each event triggered by the user.
1. Importing tkinter is same as importing any other module in the Python code.
import Tkinter as tk
There are two main methods used which the user needs to remember while creating the
Python application with GUI.
2.Tk(): To create a main window,The basic code used to create the main window of the
application is:
4. mainloop(): The method mainloop() is used when your application is ready to run.
mainloop() is an infinite loop used to run the application, wait for an event to occur and
process the event as long as the window is not closed.
m.mainloop()
Example1:
import tkinter
m = tkinter.Tk()
m.mainloop()
Example2:
import tkinter as tk
my_w = tk.Tk()
geometry():
Resizing of window is possible by default, but we can manage this setting by making resizing height,
width to False
Or
my_w.resizable(False,False)
Values for this option are normal (default value ) , iconic, withdrawn, or zoomed.
my_w.state('zoomed')
my_w.configure(background='black')
OR
my_w.configure(background='#FFFF00')
Python Tkinter Geometry:
The Tkinter geometry specifies the method by using which, the widgets are represented or
placed on main window. The python Tkinter provides the following geometry methods.
1. pack() : It organizes the widgets in blocks before placing in the parent widget. Places the
widget following the previous.
Syntax: widget.pack(options)
expand: If the expand is set to true, the widget expands to fill any space.
Fill: By default, the fill is set to NONE. However, we can set it to X or Y to determine
whether the widget contains any extra space.
size: it represents the side of the parent to which the widget is to be placed on the window.
2. grid() :The grid() geometry manager organizes the widgets in the tabular form. We can
specify the rows and columns as the options in the method call. We can also specify the
columnspan (width) or rowspan(height) of a widget.
Syntax: widget.grid(options)
A list of possible options that can be passed inside the grid() method is given below.
column: The column number in which the widget is to be placed. Leftmost column is 0.
row: row number in which the widget is to be placed. The topmost row is represented by 0.
columnspan: width of the widget, number of columns up to which, the column is expanded.
rowspan: height of the widget, i.e. the number of the row up to which the widget is expanded.
ipadx, ipady: It represents the number of pixels to pad the widget inside the widget's border.
padx, pady:It represents the number of pixels to pad the widget outside the widget's border.
Sticky:If the cell is larger than a widget, then sticky is used to specify the position of the
widget inside the cell. It may be the concatenation of the sticky letters representing the
position of the widget. It may be N, E, W, S, NE, NW, NS, EW, ES.
3. place( ):It organizes the widgets by placing them on specific positions directed by the
programmer.
relx, rely: It is represented as the float between 0.0 and 1.0 that is the offset in the horizontal
and vertical direction.
Tkinter widgets:
There are various widgets like button, canvas, checkbutton, entry, etc. that are used to build
the python GUI applications. Following is the list of main widgets in Tkinter.
1.Button:The Button is used to add various kinds of buttons to the python application.
2.Canvas:The canvas widget is used to draw the canvas on the window.The Canvas is a
rectangular area intended for drawing pictures or other complex layouts. You can place
graphics, text, widgets or frames on a Canvas.
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.
5.Frame: It can be defined as a container to which, another widget can be added and
organized.
6. Label: A label is a text used to display some message or information about the other
widgets.
7.ListBox:TheListBox widget is used to display a list of options to the user. The user can
choose more than one item from the list to be displayed
14.Text: It is different from Entry because it provides a multi-line text field to the user so that
the user can write the text and edit the text inside it.
15.Spinbox:It is an entry widget used to select from options of values. Using Spinbox user
can select value from a range of given options.
16.LabelFrame: LabelFrame widget is a container that contains other related widgets. For
example, you can group Radiobutton widgets and place the group on a LabelFrame.
1.Button
The Button widget is used to add various types of buttons to the python application. Python
allows us to configure the look of the button according to our requirements. Various options
can be set or reset depending upon the requirements.
We can also associate a method or function with a button which is called when the button is
pressed.
Example:
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("500x500")
my_font=('times', 8, 'bold')
width=20,bg='yellow',font=my_font,fg='green')
b1.pack()
my_w.mainloop()
Now let us add the click event of the button. This will close the window.
b1 = tk.Button(my_w, text='Hi Welcome', width=20,bg='yellow',
command=my_w.destroy())
command=lambda: my_upd())
b1=tk.Button(my_w,text='My Button',width=10,bg='green')
2. bd :borderwidth
b1=tk.Button(my_w,text='My Button',width=10,bg='yellow',bd=5)
b1=tk.Button(my_w,text='MyButton',width=10,activebackground='red')
b1=tk.Button(my_w,text='B1',width=10,activeforeground='green')
import tkinter as tk
my_w=tk.Tk()
my_w.geometry('200x100')
def my_upd():
print('hi')
b1.grid(row=1,column=1)
my_w.mainloop()
b1=tk.Button(my_w,text='My Button',width=10,cursor='boat')
b1=tk.Button(my_w,text='My Button',width=10,font=18)
# We can use variable for type and style.
my_font=('times', 8, 'underline')
8. fg: foreground
9. height:Height of the buttons ( We can manage size of the button using height and width )
b1=tk.Button(my_w,text='My Button',width=10,height=3)
b1=tk.Button(my_w,text='B1',highlightbackground='red',bd=5)
b1=tk.Button(my_w,text='B1',width=10,highlightcolor='red',bd=5)
b1=tk.Button(my_w,text='B1',width=5,height=1, padx=20,pady=10)
14. relief:The Button (borders) 3D effect style.Take values raised , sunken ,flat, ridge, solid
& groove.
t1 = tk.Button(my_w,height=10,relief='raised')
15. overrelief:Similar to relief but all effects takes place when Mouse is over the button.
t1 = tk.Button(my_w, width=10,height=1,overrelief='groove')
b1=tk.Button(my_w,text='MyButton',width=15,height=1,underline=3)
The invoke() method used to Trigger events without Clicking the button
Example:
my_w = tk.Tk()
b1=tk.Button(my_w,text='One',font=28,
b1.grid(row=0,column=0,padx=30,pady=10)
b2=tk.Button(my_w,text='Two',font=28,
b2.grid(row=0,column=1,padx=10,pady=10)
#command=lambda :b1.invoke()
width=13,font=('Times',26,'normal'))
l1.grid(row=1,column=0,padx=30,pady=10,columnspan=3)
my_w.mainloop()
Here the default text on the Label l1 will be displayed and the same will change on click of
any button.
By adding the line b2.invoke() we can show the text of button b2 on Label l1 . This is the
default behavior which without the click of Second button b2.
We can change the command part of button b2 to call the button 1 click event.
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("420x200")
b1=tk.Button(my_w,text='One',font=28,
b1.grid(row=0,column=0,padx=10,pady=10)
b2=tk.Button(my_w,text='Two',font=28,
command=lambda :b1.invoke())
b2.grid(row=0,column=1,padx=10,pady=10)
#command=lambda :b1.invoke()
l1=tk.Label(my_w,text='No Click',bg='yellow',font=('Times',26,'normal'))
l1.grid(row=1,column=0,padx=2,pady=10,columnspan=3)
my_w.mainloop()
flash() : Drawing user attention. We can flash() the button by changing the colour from active
to normal several times.
Example : Here we are having two buttons, user must click the second button saying Click
Me to Agree before clicking the Submit button.
If the user clicks the Submit button without Clicking the Agree button, then this button will
flash several times drawing the user attention to click it.
import tkinter as tk
my_w = tk.Tk()
def my_upd():
else:
b2['text']='Click Me to Agree' # change the text on the button
b1=tk.Button(my_w,text='Submit',font=font1,bd=6,command=my_upd)
b1.grid(row=0,column=1,padx=10,pady=60)
b2=tk.Button(my_w,text='Click Me to Agree',font=font1,bd=6,width=14,
command=lambda:b2.config(text='I agree'),
activebackground='red',activeforeground='yellow')
b2.grid(row=0,column=2,padx=5,pady=60)
my_w.mainloop()
2. Entry
The Entry widget is used to provide the single line text-box to the user to accept a value from
the user. We can use the Entry widget to accept the text strings from the user. It can only be
used for one line of text from the user. For multiple lines of text, we must use the text widget.
Syntax: E1=tk.Entry(parent_window,options)
bg,bd,cursor,exportselection,fg,font,highlightbackground,highlightcolor,highlightthickness,in
sertbackground,insertborderwidth,insertofftime,insertontime,insertwidth,justify,relief,selectba
ckground,selectborderwidth,selectforeground,show,textvariable,width,xscrollcommand.
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("250x150")
l1.grid(row=1,column=1)
e1.grid(row=1,column=2)
my_w.mainloop()
#This code we will add one label.
import tkinter as tk
my_w=tk.Tk()
my_w.geometry('300x100')
my_w.title('Computer Application')
l3.grid(row=1,column=1)
my_w.mainloop()
3. Checkbutton(Checkbox)
The Checkbutton is used to track the user's choices provided to the application. Checkbutton
is used to implement the on/off selections.
The Checkbutton can contain the text or images. Checkbutton is used to provide many
choices to the user.
Example: Checkbox:How many languages you know ? Answer can be more than one of the
given options like PHP, Python, JavaScript, JQuery. Here Checkbox or checkbuttons
representing one language as option is to be used.
activebackground,activeforeground,bg,bitmap,bd,command,cursor,disableforeground,font,fg
heighthighlightcolor,image,justify,offvalue,onvalue,padx,pady,relief,selectcolor,selectimage,s
tate,underline,variable,widthwraplength.
Example1:
import tkinter as tk
my_w = tk.Tk()
c_v1=tk.IntVar()
c1 = tk.Checkbutton(my_w,text='PHP',variable=c_v1,onvalue=1,offvalue=0)
c1.grid(row=7,column=5)
my_w.mainloop() # Keep the window open
In above code we have linked the IntVar() variable c_v1 to the checkbutton. This value we
will be using for our reading and writting (setting) the status of the checkbutton.
onvalue=1 mean the variable c_v1 will get value 1 when checkbutton is clicked. or checked
offvalue=0 mean the variable c_v1 will get value 0 when checkbutton is unchecked
How to read the status (get value of the associated variable ) of the check box. ?
c1_v1.set(1)
c1_v1.set(False)
Note that checkbutton can have values 1 or 0 ( integer variable ), Yes or No ( string variable)
, True or False ( Boolean variable )
c1_v1=tk.StringVar()
c1_v1=tk.BooleanVar()
c1.config(state='normal')
Example2:
import tkinter as tk
top = tk.Tk()
top.geometry("200x200")
checkvar1 = tk.IntVar()
checkvar2 = tk.IntVar()
checkvar3 =tk.IntVar()
chkbtn1.pack()
chkbtn2.pack()
chkbtn3.pack()
top.mainloop()
Methods:
4.Radiobutton
This widget implements a multiple-choice button, which is a way to offer many possible
selections to the user and lets user choose only one of them.
In order to implement this functionality, each group of radiobuttons must be associated to the
same variable and each one of the buttons must symbolize a single value.
value = each radiobutton should have different value otherwise more than 1 radiobutton will
get selected.
Options:activebackground,activeforeground,anchor,bg,bitmap,borderwidth,command,cursor,f
ont,fg,height,highlightcolor,highlightbackground,image,justify,padx,pady,relief,selectcolor,se
lectimage, state,text, textvariable,underline,value,variable,width,wraplength
import tkinter as tk
root = tk.Tk()
v = tk.IntVar()
root.mainloop()
anchor:If the widget inhabits a space larger than it needs, this option specifies where the
radiobutton will sit in that space. The default is anchor=CENTER.
Methods:
flash():Flashes the radiobutton a few times between its active and normal colors, but leaves it
the way it started.
invoke():You can call this method to get the same actions that would occur if the user clicked
on the radiobutton to change its state.
5. Label
This widget is used to place text or images, which helps the user to know for what the other
widget is for. This widget provides a message as to what the widget will do to the user.
Tkinter Listbox widget is used to display a list of items of which all are text items having the
same font and color. The user can choose more than one item from the list to be displayed
depending on the widget’s configuration.
The master represents the parent window, and the option is the list of options that can be used
for the widget, and options are the key-value pairs separated by commas.
import tkinter as tk
my_w = tk.Tk()
my_w.title("Creating Listbox")
l1 = tk.Listbox(my_w,height=3)
l1.grid(row=1,column=1)
l1.insert(2,'Python')
l1.insert(3,'MySQL')
7. Scrollbar
Tkinter Scrollbar widget basically provides the slide controller, which is used to implement
the vertical scrolling widgets like the Listbox, Canvas, and the Text.
Using the Tkinter scrollbar widget, one can also try creating the horizontal scrollbar on the
entry widgets.
Tkinter scrollbar is used to roll through the content to see the whole content vertically when
the scrollbar is set to vertical.
A horizontal scrollbar is used to scroll over the content horizontally. Scrollbar() syntax will
be used to get a scrollbar with the attributes: master and the option/options.
master: This master attribute of the Tkinter scrollbar represents only the parent window
options: The option attribute of the Tkinter scrollbar will have the list of option which are
commonly used for the scrollbar widget. These option mainly are used as the key-value pairs,
which are separated by the commas.
import tkinter as tk
my_w=tk.Tk()
my_w.geometry("350x200")
sb = tk.Scrollbar(my_w,cursor='hand1')
sb.pack(side=RIGHT,fill=Y)
l1.pack(side=LEFT,padx=15)
my_w.mainloop()
Options:
In above code we used cursor='hand' to change the cursor shape when it is over the scrollbar
orient:By default the option orient is 'vertical' , we can set it to horizontal to display the
Scrollbar in horizontal direction.
sb = tk.Scrollbar(my_w,orient='horizontal')
8.Spinbox:
Using Spinbox user can select value from a range of given options.
Two SpinBox widgets, one for integer and other one for string selection by user.
import tkinter as tk
my_w = tk.Tk()
sb1.grid(row=1,column=1,padx=20,pady=20)
sb2 = Spinbox(my_w,values=my_list,width=10)
sb2.grid(row=1,column=2,padx=20,pady=20)
9. LabelFrame
LabelFrame widget is a container that contains other related widgets. For example, you can
group Radiobutton widgets and place the group on a LabelFrame.
options − Here is the list of most commonly used options for this widget. These options can
be used as key-value pairs separated by commas.
root = Tk()
labelframe.pack(fill="both", expand="yes")
left.pack()
root.mainloop()
To create a LabelFrame widget, you can also use ttk.LabelFrame:
root1 = Tk()
root1.geometry('250x150')
button = Button(labelframe, text = 'option 1') # Buttons are defined and created
mainloop()