Python GUI
Python GUI
Python GUI
What is tkinter?
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.
There are basically five main steps that are required to get your GUI up and running:
2. Create a top-level windowing object that contains your entire GUI application.
3. Build all your GUI components (and functionality) on top (or within) of your top-level
windowing object.
In GUI programming, a top-level root windowing object contains all of the little
windowing objects that will be part of your complete GUI application. These can be text
labels, buttons, list boxes, etc. These individual little GUI components are known as
widgets.So when we say create a top-level window, we just mean that you need a place
where you put all your widgets. In Python, this would typically look like this line:
top = tkinter.Tk() # or just Tk() with "from tkinter import *" For eg the
Output:
The object returned by tkinter.Tk() is usually referred to as the root window. Top-
level windows are those that show up stand-alone as part of your application. You can have
more than one top-level window for your GUI, but only one of them should be your root
window.
A widget is 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 hierachy
tree.Widgets can be stand-alone or be containers. If a widget contains other widgets, it is
considered the parent of those widgets. Accordingly, if a widget is contained in another
widget, it’s considered a child of the parent, the parent being the next immediate enclosing
container widget.
Usually, widgets have some associated behaviors, such as when a button is pressed, or text
is filled into a text field. These types of user behaviors are called events, and the GUI’s
response to such events are known as callbacks.
Events can include the actual button press (and release), mouse movement, hitting the
Return or Enter key, etc. The entire system of events that occurs from the beginning until
the end of a GUI application is what drives it. This is known as event-driven processing.
Label Widget: It refers to the display box where you can put any text or image which can
be updated any time as per the code. It cannot be used for accepting data from the user.
The general syntax is:
Output:
Entry Widget :It is used to input the single line text entry from the user.. For multi-
line text input, Text widget is used. The general syntax is:
w=Entry(master, option=value) master is the parameter used to represent the parent
window.
There are number of options which are used to change the format of the widget. Number
of options can be passed as parameters separated by commas. Some of them are listed
below.
• bd: to set the border width in pixels.
• bg: to set the normal background color.
• cursor: to set the cursor used.
• command: to call a function.
• highlightcolor: to set the color shown in the focus highlight.
3 PROF. MAYA NAIR
Programming with Python Semester II,Unit 2
Output:
Button widget:
On click of stop button the application gets closed since we have given command
=r.destroy .
The command can be explicitly specified with a function name which should be defined
to be executed as shown in the following example.
else:
label.configure(text="Hello World")
label=Label(window,text="Hello World")
label.pack()
button=Button(window,text="Click to change text",command=onclick)
button.pack()
window.mainloop()
Output:
Python’s strings, integers, floating-point numbers, and Booleans are immutable, so module
tkinter provides one class for each of the immutable types: StringVar for str, IntVar for int,
BooleanVar for bool, and DoubleVar for float. (The use of the word double is historical; it
is short for “double-precision floating-point number.”) These mutable types can be used
instead of the immutable ones.
import tkinter
window = tkinter.Tk()
data = tkinter.StringVar()
data.set('Data to display')
label = tkinter.Label(window, textvariable=data)
label.pack()
window.mainloop()
Notice that this time we assign to the textvariable parameter of the label rather than the
text parameter. The values in tkinter containers are set and retrieved using the methods set
and get. Whenever a set method is called, it tells the label, and any other widgets it has
been assigned to, that it’s time to update the GUI. Another example
def add():
x.set(int(e1.get())+int(e2.get()))
label.grid(column=0,row=0,padx=10,pady=10)
e1=Entry(root)
e1.grid(column=1,row=0,padx=10,pady=10)
label=Label(root,text="SecondNo")
label.grid(column=0,row=1,padx=10,pady=10)
e2=Entry(root)
e2.grid(column=1,row=1,padx=10,pady=10)
label=Label(root,textvariable=x)
label.grid(column=0,row=2,columnspan=2,padx=10,pady
=10)
b1=Button(root,text="ADD",command=add)
b1.grid(column=1,row=3,padx=10,pady=10)
root.mainloop()
Output:
When several button widget have similar function to execute then rather than defining
several function, it will be beneficial to write one function and pass parameters to the
function to customize it. This can be implemented in tkinter with lambda function. It lets
us write one controller function to handle different buttons in a general way and then wrap
up calls to that function when and as needed.
Output:
This code creates a zero-argument lambda function to pass into each button just where it’s
needed. Those lambda functions then pass the right values into click. This is cleaner than
the preceding code because the function definitions are enclosed in the call that uses
them—there is no need to clutter the GUI with little functions that are used only in one
place.
RadioButton: It is used to offer multi-choice option to the user. It offers several options to the
user and the user has to choose one option. The general syntax is:
w = RadioButton(master, option=value)
There are number of options which are used to change the format of this widget. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
• activebackground: to set the background color when widget is under the cursor.
activeforeground: to set the foreground color when widget is under the cursor.
• bg: to set he normal background color.
• command: to call a function.
• font: to set the font on the button label.
• image: to set the image on the widget.
• width: to set the width of the label in characters.
• height: to set the height of the label in characters.
Canvas: It is used to draw pictures and other complex layout like graphics, text and widgets.
The general syntax is:
w = Canvas(master, option=value) master is the parameter used to represent the
parent window.
There are number of options which are used to change the format of the widget. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
• bd: to set the border width in pixels.
• bg: to set the normal background color.
• cursor: to set the cursor used in the canvas.
• highlightcolor: to set the color shown in the focus highlight.
• width: to set the width of the widget.
• height: to set the height of the widget
This method is used to set the dimensions of the Tkinter window and is used to set the position
of the main window on the user’s desktop. Without geometry() function as soon as you run the
application, you’ll see the position of the Tkinter window is at the north-west position of the
screen and the size of the window is also small.
Using geometry method we can set the size and position of the root window.
e.g.
root.geometry('200x200')
creates a window of size 200x200 pixels
root.geometry('200x150 + 400 + 300')
creates a window of size 200x150 pixels positioned at so that 300 shifted on Y-axis and 400
shifted on X-axis.
Tkinter Anchors
Anchors are used to define where text is positioned relative to a reference point.
Here is list of possible constants, which can be used for Anchor attribute.
• NW
• N
• NE
• W
• CENTER
• E
• SW
• S
• SE
For example, if you use CENTER as a text anchor, the text will be centered horizontally and
vertically around the reference point.
Geometry Managers
Tk has three geometry managers that help with positioning your widget set:
• Placer
You provide the size of the widgets and locations to place them; the manager then places
them for you. The problem is that you have to do this with all the widgets, burdening the
developer with coding that should otherwise take place automatically.
• Packer
Output:
You can use the fill=X option to make all widgets as wide as the parent widget:
root = Tk()
w = Label(root, text="Red", bg="red", fg="white")
w.pack(fill=X)
w = Label(root, text="Green", bg="green", fg="black")
w.pack(fill=X)
w = Label(root, text="Blue", bg="blue", fg="white")
w.pack(fill=X)
root.mainloop()
Output:
root = Tk()
Output:
• Grid
It is used to specify GUI widget placement, based on grid coordinates. The Grid will render
each object in the GUI in their grid position.
Using the grid manager is easy. Just create the widgets, and use the grid() method to tell the
manager in which row and column to place them. You don’t have to specify the size of the
grid beforehand; the manager automatically determines that from the widgets in it.
e1 = Entry(master)
e2 = Entry(master)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
label1.grid(sticky=E)
label2.grid(sticky=E)
entry1.grid(row=0, column=1)
The Listbox widget is used to display the list items to the user. We can place only text items in
the Listbox and all text items contain the same font and color.
The user can choose one or more items from the list depending upon the configuration.
w = Listbox(parent, options)
SN Option Description
3 Cursor The mouse pointer will look like the cursor type like dot,
arrow, etc.
7 Highlightcolor The color of the Listbox items when the widget is under
focus.
4 get(first, last = None) It is used to get the list items that exist in
the given range.
Combobox is a combination of Listbox and an entry field. It is one of the Tkinter widgets where
it contains a down arrow to select from a list of options. It helps the users to select according to
the list of options displayed. When the user clicks on the drop-down arrow on the entry field, a
pop up of the scrolled Listbox is displayed down the entry field. The selected option will be
displayed in the entry field only when an option from the Listbox is selected.
Widget Groupings
You will design a more user friendly interface if you group and organize your widgets in a
coherent design. Tkinter has four basic ways to group widgets. These are described in the
Widget Purpose
tk.PanedWindow Group one or more widgets into “panes”, where the “panes” can be re-
sized by the user by dragging separator lines.
ttk.Notebook A tabbed set of frames, only one of which is visible at any given time.
Widgets are always organized as a hierarchy, where the main application window is the root
of the hierarchy. Typically, the child widgets of an application window are a combination of
“frames”. The “frames” hold other widgets. A “frame” will not be visible until it is assigned
a size and location using a layout manager. The image below shows examples of the four
types of widget “containers”. The “containers” in this example used a grid layout manager
on a 2x2 grid.
def onadd():
data.set(int(e1.get())+int(e2.get()))
window=Tk()
frame=Frame(window,borderwidth=4,relief=GROOVE)
frame.grid(column=0,row=0)
data=IntVar()
data.set(0)
btn=Button(frame,text="Add",command=onadd,relief=RAISED)
btn.grid(column=1,row=2,ipadx=10,ipady=10)
e1=Entry(frame) e2=Entry(frame)
e1.grid(column=0,row=0,ipadx=10,ipady=10)
e2.grid(column=0,row=1,ipadx=10,ipady=10)
frame1=LabelFrame(window,text="Result",borderwidth=4,relief=RAISED)
frame1.grid(column=1,row=0)
l1=Label(frame1,textvariable=data)
l1.grid(column=0,row=2,ipadx=10,ipady=10)
frame2=ttk.Notebook(window)
tab1=Frame(frame2)
tab2=Frame(frame2)
tab3=Frame(frame2)
frame2.add(tab1,text="TabI",compound=TOP)
frame2.add(tab2,text="TabII",compound=TOP)
frame2.add(tab3,text="TabIII",compound=TOP)
l2=Label(tab1,text="I am in tab1")
l2.pack()
l3=Label(tab2,text="I am in tab2")
l3.pack()
l4=Label(tab3,text="I am in tab3")
l4.pack()
window.mainloop()
Output: