0% found this document useful (0 votes)
25 views15 pages

Unit-V GUI Programming

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views15 pages

Unit-V GUI Programming

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

GUI Programming

Introduction to Python GUI Programming


Most of the programs we have done till now are text-based programming. But many applications need
GUI (Graphical User Interface).
Python provides several different options for writing GUI based programs. These are listed below:

• Tkinter: It is easiest to start with. Tkinter is Python's standard GUI (graphical user interface)
package. It is the most commonly used toolkit for GUI programming in Python.
• JPython: It is the Python platform for Java that is providing Python scripts seamless access o
Java class Libraries for the local machine.
• wxPython: It is an open-source, cross-platform GUI toolkit written in C++. It is one of the
alternatives to Tkinter, which is bundled with Python.
When Tkinter is used alongside Python, it results in the creation of GUI very conveniently and quite
fast. The main advantage of using Tkinter is that it has an object-oriented interface. The success of any
application or website depends on how well it interacts with the user, i.e. an attractive graphical interface
helps to create a good application. Well, Python Tkinter does that for us.

Using Tkinter:
It is the standard GUI toolkit for Python. Fredrik Lundh wrote it. For modern Tk binding, Tkinter is
implemented as a Python wrapper for the Tcl Interpreter embedded within the interpreter of Python. Tk
provides the following widgets:

• button
• canvas
• combo-box
• frame
• level
• check-button
• entry
• level-frame
• menu
• list - box
• menu button
• message
• tk_optoinMenu
• progress-bar
• radio button
• scroll bar
• separator
• tree-view, and many more.
Creating a GUI program using this Tkinter is simple. For this, programmers need to follow the steps
mentioned below:

• First, we need to import the Tkinter module.


• Secondly, we need to create a container window.
• Then we add any number of widgets to the container window.
• Lastly, we apply the event trigger on the widgets.

Syntax:
Here, we import the Tkinter module
import tkinter
Here, we create container window object
c = tkinter. Tk ()
widgets that need to be added
This executes the application until and unless it is stopped
[Link]()

There are two main methods used which the user needs to remember while creating the Python
application with GUI.
1) Tk(screenName=None, baseName=None, className=’Tk’, useTk=1):
To create a main window, tkinter offers a method ‘Tk(screenName=None, baseName=None,
className=’Tk’, useTk=1)’.
To change the name of the window, you can change the className to the desired one. The
basic code used to create the main window of the application is:
m=[Link]() where m is the name of the main window object
2) mainloop ():
There is a method known by the name 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.
[Link]()

import tkinter
m = [Link]()
'''
widgets are added here
'''
[Link]()
Why do we use Python Tkinter?
Python Tkinter is the most preferred package used for creating nice GUIs for applications as it has a
variety of methods like pack(), grid(), and place() for geometry management.
It has standard attributed dimensions, fonts, colors, cursors, anchors, and bitmaps for better GUI.
Moreover, it has a vast array of widgets to choose from and is by far the easiest to use. The combination
of all these features makes Python Tkinter makes it very popular among Python developers and makes it
a favourable tool to use.
Standard attributes for GUI:

• Dimensions
• Fonts
• Colors
• Cursors
• Anchors
• Bitmaps
Methods for Geometry Management:
The following are the methods used in Python Tkinter for geometry management: -
1. pack():
It places the child widget in blocks before placing it inside the parent widget.
Syntax:
[Link](pack_options)
The possible options for pack_options are the following:
expand: It is a Boolean which can either be True or False. When it is set to True, the child
widget expands to fill the parent widget’s full space.
fill: The default value is none. The other values being X (fill only horizontally), Y (fill only
vertically) and both (fill both horizontally and vertically)
side: It determines the side of the parent widget against which the child widget packs against.
The default value is the top. The other values are bottom, left, and right.
Example:
from tkinter import *
root = Tk()

label1 = Label(root,text="This is a tutorial about Python


Tkinter")
[Link](side=TOP,expand=True)
label2 = Label(root,text="Do you wish to
learn?",fg="blue")
[Link](side=TOP,expand=True)
button1 = Button(root, text="Accept",
fg="green",command=[Link])
[Link](side=LEFT,expand=True)
button2 = Button(root, text="Close",
fg="red",command=[Link])
[Link](side=RIGHT,expand=True)
[Link]()
Output:

2. grid():
It places the child widget in grids before placing it inside the parent widget.
Syntax:
[Link](grid_options)
The possible options for grid_options are the following:

• column: It determines the column to put the child widget inside the parent widget. The
default value is 0, which signifies the leftmost column.
• columnspan: It determines the number of columns the widget occupies. The default
value is 1.
• ipadx, ipady: It signifies the horizontal and vertical padding for the child widget inside
the parent widget’s border in terms of pixels.
• padx, pady: It signifies the horizontal and vertical padding for the child widget outside
the parent widget’s border in terms of pixels.
• row: It signifies the row to put the widget in.
• rowspan: It determines the number of rows the widget occupies. The default value being
1.

Example:
from tkinter import *
root = Tk()
for r in range(4):
for c in range(4):
Label(root , text = 'R%s/C%s'%(r,c),
borderwidth = 1).grid(row = r , column = c , rowspan =
1 , columnspan = 1 , padx = 3 , pady = 3)
[Link]()

Output:
3. place():

It organizes the widgets by placing them on a specific position as indicated by the developer.

Syntax:
[Link](place_options)

The possible options for place_options are the following:

• anchor: This determines the exact position of the widget. The values correspond to the
different directions available in the compass. The possible values are N, S, E, W, NE,
NW, SE and SW. The default value is NW which is at the upper left corner.
• bordermode: The possible values are inside and outside. The default being inside.
• height, width: This indicates the height and weight in pixels.
• relheight, relwidth: This indicates the height and width relative to the parent widget’s
height and width. This is a floating-point number between 0.0 and 1.0
• relx, rey: This indicates the offset of the child widget relative to the parent widget. It is a
floating-point number between 0.0 and 1.0
• x, y: This indicates the vertical and horizontal offset of the child widget in pixel.

Example:
from tkinter import *
root = Tk()
button1 = Button(root, text ="Hello" , fg="blue")
[Link](side = TOP)
[Link](anchor = E , relheight = 0.25 , relwidth = 0.25
, relx = 0.4 , rely = 0.5)
button2 = Button(root, text = "World" , fg = "green")
[Link](side = BOTTOM)
[Link](anchor = W , relheight = 0.25 , relwidth = 0.25
, relx=0.6 , rely= 0.5)
[Link]()

Output:
Introduction to Tkinter Widgets
Python Tkinter is a package or inbuilt library that is used for GUI programming. To develop GUI
applications, Tkinter provides widgets that are used to represent in the browser.
Tkinter widgets are eventful and represented in the browser, such as textbox, button, etc. In Python,
Tkinter widgets are standard GUI elements used to handle events through elements like button, frames,
labels, etc.
In Python, Tkinter provides a small range of widgets that are used in some basic GUI programming, and
it also allows us to create specialized widgets as custom widgets. Tkinter widgets usually provide various
controls in the GUI applications.
Tkinter in Python provides various ranges of widgets; roughly, Tkinter has 11 different widgets in it.
Tkinter widgets are necessary as they provide GUI application with a different and attractive look and
feel. Let us see some basic and major widgets in detail with an example:
1. Button
The button is a widget that is used for the user to interact with just one click, or a button is usually used
when there is a click event in the GUI applications. The button is used to control behavior which means
if we press or click the button, action or event is performed, such as displaying text or images.
Syntax:
Button (master, option = value)
Parameters:

• Master: This argument is used to represent or declare the root or parent window.
• Options: There are many different values for options that are provided button widgets such as
activebackground color, activeforeground color, bg, font, image, width, height, command, etc

Example:
import tkinter as tk
r = [Link]()
button = [Link](r, text='click me', width=25,
command=[Link])
[Link]()
[Link]()

Output:

In the above code, Tkinter must be imported and then declare root window and initialize button with
the text to be displayed on the button as “click me” with button width as “25” and we have given
command as [Link], which is used to close the root window.
2. CheckButton
Checkbutton widget is used to display the checkbox without the checkmark and can access it through
the Tkinter variable. This button usually used to store or record status like on or off, true or false, etc.,
which means these are also like buttons but used when the user wants to choose between two different
values or status. In this, the user can select more than one checkbox. Let us see an example of how this
button works.
Syntax:
CheckButton (master, option = value)
Options can be like the title for giving the title to the widget, activebackground, and activeforeground
for setting back and foreground color, bg for setting up the background color, command, font, image,
etc.
Example:
from tkinter import *
root = Tk()
v1 = IntVar()
Checkbutton(root, text='Python',width =25, variable=v1).grid(row=0, sticky=S)
v2 = IntVar()
Checkbutton(root, text='Unix',width =25, variable=v2).grid(row=1, sticky=S)
v3 = IntVar()
Checkbutton(root, text='Perl',width =25, variable=v3).grid(row=2, sticky=S)
mainloop()

Output:

In the above example, we can see in the screenshot “Python”, and “Unix” checkboxes are check marked.
In the above code, we have declared variables as intvar() for each option to access these checkbuttons.
3. RadioButton
This is also similar to the checkbutton, but this widget is used when the user is given many different
options but is asked to select only one among all these options. The radiobutton widgets must be
associated with the same variable, and each symbolizes a single value.
Syntax:
RadioButton (master, option = values)
Options are the same as for checkbuttons.
Example:
from tkinter import *
root = Tk()
v = IntVar()
Radiobutton(root, text='male',width =25, variable=v, value=1).pack(anchor=W)
Radiobutton(root, text='female',width =25, variable=v, value=2).pack(anchor=W)
Radiobutton(root, text='others',width =25, variable=v, value=3).pack(anchor=W)
mainloop()

Output:

In the above example, in the screenshot, we can see that only one button can be selected using the
RadioButton widget.
4. MenuButton:
This button is associated with a menu widget and displays the selected option when the user clicks on it.
MenuButton is part of a dropdown menu that is always present on the window.
Syntax:
MenuButton (master, option = value)
Again, the options are the same as that of checkbuttons and radiobuttons.
Example:
from tkinter import *
root = Tk()
[Link]("300x350")
menubutton = Menubutton(root, text = "File", width = 35)
[Link]()
[Link] = Menu(menubutton)
menubutton["menu"]=[Link]
[Link].add_checkbutton(label = "New file",
variable=IntVar())
[Link].add_checkbutton(label = "Save", variable =
IntVar())
[Link].add_checkbutton(label = "Save as", variable =
IntVar())
[Link]()
[Link]()

Output:
6. Label:
This widget is used to tell us specifically where 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.
Syntax:
Label (master, option = value)
Options are again the same as for the Entry widget, and there are many different options also.

Example:
from tkinter import *
root = Tk()
[Link]("300x150")
r = Label(root, text='Python Programming',width =35)
[Link]()
[Link]()
Output:
Events and Bindings
A Tkinter application runs most of its time inside an event loop, which is entered via the mainloop method.
It waiting for events to happen. Events can be key presses or mouse operations by the user.
Tkinter provides a mechanism to let the programmer deal with events. For each widget, it's possible to
bind Python functions and methods to an event.
[Link](event, handler)
If the defined event occurs in the widget, the "handler" function is called with an event object. describing
the event.
Tkinter Events are generally used to provide an interface that works as a bridge between the User and the
application logic. We can use Events in any Tkinter application to make it operable and functional.
Here is a list of some common Tkinter events which are generally used for making the application
interactive.
Events are given as strings, using a special event syntax:
<modifier-type-detail>
The type field is the most important part of an event specifier. It specifies the kind of event that we wish
to bind, and can be user actions like Button, and Key, or window manager events like Enter, Configure,
and others.
The modifier and detail fields are used to give additional information, and can in many cases be left out.
There are also various ways to simplify the event string; for example, to match a keyboard key, you can
leave out the angle brackets and just use the key as is. Unless it is a space or an angle bracket, of course.
Instead of spending a few pages on discussing all the syntactic shortcuts, let's take a look on the most
common event formats:

Event Description
<Button-1> A mouse button is pressed over the widget.
Button 1 is the leftmost button, button 2 is the middle button (where available), and
button 3 the rightmost button.
When you press down a mouse button over a widget, Tkinter will automatically
"grab" the mouse pointer, and mouse events will then be sent to the current widget
as long as the mouse button is held down.

The current position of the mouse pointer (relative to the widget) is provided in the
x and y members of the event object passed to the callback.

You can use ButtonPress instead of Button, or even leave it out completely:
<Button-1>, <ButtonPress-1>, and <1> are all synonyms. For clarity, I prefer the
<Button-1> syntax.
<B1-Motion> The mouse is moved, with mouse button 1 being held down (use B2 for the middle
button, B3 for the right button).
The current position of the mouse pointer is provided in the x and y members of
the event object passed to the callback.
<ButtonRelease- Button 1 was released. The current position of the mouse pointer is provided in the
1> x and y members of the event object passed to the callback.
<Double-Button- Button 1 was double clicked. You can use Double or Triple as prefixes.
1> Note that if you bind to both a single click (<Button-1>) and a double click, both
bindings will be called.
<Enter> The mouse pointer entered the widget (the user did not press the Enter key!).
<Leave> The mouse pointer left the widget.
<Return> The user pressed the Enter key.
You can bind to virtually all keys on the keyboard.
For an ordinary 102-key PC-style keyboard, the special keys are Cancel (the Break
key), BackSpace, Tab, Return (the Enter key), Shift_L (any Shift key), Control_L
(any Control key), Alt_L (any Alt key), Pause, Caps_Lock, Escape, Prior (Page
Up), Next (Page Down), End, Home, Left, Up, Right, Down, Print, Insert,
Delete, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, Num_Lock, and
Scroll_Lock.
<Key> The user pressed any key.
The key is provided in the char member of the event object passed to the callback
(this is an empty string for special keys).
a The user typed an "a".
Most printable characters can be used as is.
The exceptions are space (<space>) and less than (<less>).
Note that 1 is a keyboard binding, while <1> is a button binding.
<Shift-Up> The user pressed the Up arrow, while holding the Shift key pressed. You can use
prefixes like Alt, Shift, and Control.
<Configure> The widget changed size (or location, on some platforms).
The new size is provided in the width and height attributes of the event object
passed to the callback.
< Destroy > Use this event to kill or terminate a particular widget.
<Expose> The event occurs whenever a widget or some part of the application becomes
visible that covered by another window in the application.
<Focus In> This event is generally used to get the focus on a particular widget.
<Focus Out> To move the focus from the current widget.
<Key Press> Start the process or call the handler by pressing the key.
<KeyRelease> Start the process or call an event by releasing a key.
<Map> Use Map event to show or display any widget in the application.
<Motion> Track the event whenever the mouse pointer moves entirely within the application.
<Unmap> A widget can be unmapped from the application. It is similar to hiding the widget
using grid_remove ().
<Visibility>− An event can happen if some part of the application gets visible in the screen.

Python Tkinter event and bind


In this section, we will learn about how to bind an event in Python Tkinter.
Allocate a function to an event is known as event binding. When an event occurs the allotted function
call automatically.
The syntax of the bind() method:
[Link](event, handler, add=None)
When an event occurs in the widget, Tkinter will invoke the handler automatically with the event detail.
If you want to register an additional handler, you can pass the '+' to the add argument. It means that
you can have multiple event handlers that respond to the same event.

Example:
In the following code, we can create a widget in which an event can occur.
We create a button on the widget, if a user clicks on the button a single time the text shows after clicking
on the button “Hello“.
If the user doubles click on the button the execution of the program stop.
from tkinter import *
def task(event):
print("Hello")
def quit(event):
print("Double click to stop")
import sys; [Link]()

ws=Tk()
[Link]("Python guides")
[Link]("200x200")

button = Button(ws, text='Press')


[Link](pady=10)
[Link]('<Button-1>', task)
[Link]('<Double-1>', quit)
[Link]()

Output:
After running the above code, we get the following output in which we can see the widget.
In the widget, a button is placed, after clicking on the button once they print Hello. After that clicking
again twice, they quit all the programs.

>>>= RESTART: C:\Users\Pranav


Joshi\AppData\Local\Programs\Python\Python310\tkinter_event [Link]
Hello
Hello
Hello
Hello
Hello
Hello
Double click to stop
>>>

Example 2:
The following program illustrates how to bind the return_pressed function to the Return key pressed
event of the 'Save' button:
import tkinter as tk
from tkinter import ttk

def return_pressed(event):
print('Return key pressed.')

root = [Link]()

btn = [Link](root, text='Save')


[Link]('<Return>', return_pressed)

[Link]()
[Link](expand=True)

[Link]()

Output:
Example:
The following example illustrates how to use the bind() method to register multiple handlers for
the same event:
import tkinter as tk
from tkinter import ttk

def return_pressed(event):
print('Return key pressed.')

def log(event):
print(event)

root = [Link]()

btn = [Link](root, text='Save')


[Link]('<Return>', return_pressed)
[Link]('<Return>', log, add='+')

[Link]()
[Link](expand=True)

[Link]()

Output:
When you move the focus to the button and press the Return key, Tkinter automatically invokes the
return_pressed and log functions.

[Link]() is used to given the title to the widget.


sys is a function that gives the name to the existing Python module

You might also like