Meeting11 12 GUI Programming N
Meeting11 12 GUI Programming N
Meetings #11_12
GUI Programming
AOU- M110 2
Graphical User Interfaces (1 of 3)
A computer’s user interface is the part of the computer with which the user
interacts. One part of the user interface consists of hardware devices, such as the
keyboard and the video display. Another part of the user interface lies in the way
that the computer’s operating system accepts commands from the user.
For many years, the only way that the user could interact with an operating
system was through a command line interface.
In the 1980s, a new type of interface known as a graphical user interface came
into use in commercial operating systems, called the graphical user interface
• User Interface: the part of the computer with which the user interacts
• Command line interface: it displays a prompt, and the user types a command that is then
executed
• Graphical User Interface (GUI): allows users to interact with a program through graphical
elements on the screen.
AOU- M110 3
Graphical User Interfaces (2 of 3)
• Command line interface: displays a prompt and the user types a command that
is then executed
AOU- M110 4
Graphical User Interfaces (3 of 3)
Graphical User Interface (GUI): (GUI; pronounced “gooey”),
allows the user to interact with the operating system and
other programs through graphical elements on the screen.
•GUIs also popularized the use of the mouse as an input
device.
•GUIs allow the user to point at graphical elements and
click the mouse button to activate them.
•Much of the interaction with a GUI is done through dialog
boxes, which are small windows that display information
and allow the user to perform actions.
• Responsible for most of the interaction through GUI
• User interacts with graphical elements such as icons,
buttons, and slider bars
AOU- M110 5
GUI Programs Are Event-Driven
• In text-based environments, programs determine the order in which
things happen
• The user can only enter data in the order requested by the program
• GUI environment is event-driven
• The user determines the order in which things happen
• User causes events to take place and the program responds to the events
AOU- M110 6
Using the tkinter Module (1 of 3)
• Python does not have GUI programming features built into the language itself. However,
it comes with a module named tkinter that allows you to create simple GUI programs.
• The name “tkinter” is short for “Tk interface.”
AOU- M110 7
Using the tkinter Module (2 of 3)
Widget Description
Button A button that can cause an action to occur when it is clicked.
Canvas A rectangular area that can be used to display graphics.
Checkbutton A button that may be in either the “on” or “off” position.
Entry An area in which the user may type a single line of input from the keyboard.
Frame A container that can hold other widgets.
Label An area that displays one line of text or an image.
Listbox A list from which the user may select an item
Menu A list of menu choices displayed when the user clicks a Menubutton widget.
Menubutton A menu that is displayed on the screen and may be clicked by the user
Message Displays multiple lines of text.
Radiobutton A widget that can be either selected or deselected. Radiobutton widgets usually
appear in groups and allow the user to select one of several options.
Scale A widget that allows the user to select a value by moving a slider along a track.
Scrollbar Can be used with some other types of widgets to provide scrolling ability.
Text A widget that allows the user to enter multiple lines of text input.
Toplevel A container, like a Frame, but displayed in its own window.
AOU- M110 8
Using the tkinter Module
The simplest GUI program that we can demonstrate is one that displays an empty window.
The below program shows how we can do this using the tkinter module. When the program
runs, the window shown in the figure is displayed. To exit the program, simply click the
standard Windows close button (×) in the upper right corner of the window.
tkinter.mainloop() calls the tkinter module’s mainloop function. This function runs like an
indefinite loop until you close the main window.
AOU- M110 9
import <module> vs. from <module> import *
In general, we use from <module>import * when we want to save ourselves from
typing the module name repeatedly.
In other words, use from <module> import * when referring to a member of the
module many times in the code.
• Example: in order to avoid writing tkinter. before each command, you can
use from tkinter import * instead of import tkinter at the beginning of
your program.
AOU- M110 10
Using the tkinter Module (OOP)
• Programs that use tkinter do not always run reliably under IDLE
• For best results run them from operating system command prompt
• Most programmers take an object-oriented approach when writing GUI
programs.
• __init__ method builds the GUI
• When an instance is created the GUI appears on the screen.
object-oriented approach Output
# This program displays a window with a title.
# This program displays an empty window.
from tkinter import *
from tkinter import *
class MyGUI:
def main():
def __init__(self):
# Create the main window widget.
# Create the main window widget.
main_window = Tk()
self.main_window = Tk()
# Enter the tkinter main loop.
# Enter the tkinter main loop.
mainloop()
mainloop()
# Call the main function.
# Create an instance of the MyGUI class.
main()
my_gui = MyGUI()
AOU- M110 11
Changing the Tkinter GUI Window Title
To change the title of the GUI window in Tkinter, use the title() method to set the title
of the window:
Format: self.root.title(“Your Title")
Example 1
# This program displays a window with a title.
AOU- M110
Display Text with Label Widgets
• Label widget: displays a single line of text in a window
• Made by creating an instance of tkinter module’s Label class
• Format: Label(self.main_window,text='my text')
• First argument references the root widget, second argument shows text that should
appear in label
• pack method: determines where a widget should be positioned and makes it visible
when the main window is displayed
AOU- M110 13
Example 2
# This program displays a title and a label with text.
Output
from tkinter import *
class MyGUI:
def __init__(self):
# Create the main window widget.
self.main_window = Tk()
# Display a title.
self.main_window.title('My First GUI')
# Create a Label widget containing the text 'Hello World!'
self.label = Label(self.main_window, text='Hello World!')
Output
Notice the two Label widgets are displayed with one stacked on top of the other. We
can change this layout by specifying an argument to pack method
AOU- M110 15
Example 4
Output
In lines 16 and 17, label1 widget was added to the main window first, it will appear at the leftmost edge. The
label2 widget was added next, so it appears next to the label1 widget.
As a result, the labels appear side by side.
AOU- M110 16
Adding Borders to Labels
• When creating a Label widget, you can use the borderwidth and relief
arguments to display a border around the label
• The borderwidth argument specifies the width of the border, in pixels
• The relief argument specifies the border style
self.label = Label(self.main_window,
text='Hello World',
borderwidth=1,
relief='solid')
self.label = Label(self.main_window,
text='Hello World',
borderwidth=4,
relief='solid')
AOU- M110 17
Values for relief Argument (1 of 2)
relief Argument Description
relief='flat' The border is hidden and there is no 3D effect.
relief='raised' The widget has a raised 3D appearance.
relief='sunken' The widget has a sunken 3D appearance.
relief='ridge' The border around the widget has a raised 3D appearance.
relief='solid' The border appears as a solid line with no 3D effect.
relief='groove' The border around the widget appears as a groove.
AOU- M110 18
Example 5
Output
AOU- M110 19
Padding
• Padding: space that appears around a widget
• Internal padding appears around the inside edge of a widget
• External padding appears around the outside edge of a widget
AOU- M110 20
Internal Padding (1 of 2)
• To add horizontal internal padding to a widget, pass the argument ipadx=n
to the widget's pack method
• To add vertical internal padding to a widget, pass the argument ipady=n to
the widget's pack method
AOU- M110 21
Internal Padding- Example (2 of 2)
AOU- M110 22
External Padding (1 of 2)
• To add horizontal external padding to a widget, pass the argument padx=n
to the widget's pack method
• To add vertical external padding to a widget, pass the argument pady=n to
the widget's pack method
AOU- M110 23
External Padding- Example (2 of 2)
Output
AOU- M110 24
Internal and External Padding- Example
Output
AOU- M110 25
Organizing Widgets with Frames (1 of 2)
• Frame widget: A container that holds other widgets
• Useful for organizing and arranging groups of widgets in a window.
• For example, you can place a set of widgets in one Frame and arrange them in a
particular way, then place a set of widgets in another Frame and arrange them
in a different way.
• Example:
Label(self.top_frame,text = 'hi')
AOU- M110 26
Organizing Widgets with Frames (2 of 2)
AOU- M110 27
Output
AOU- M110 28
Editable code # Create three Label widgets for the bottom frame.
self.label4 = Label(self.bottom_frame,
# This program creates labels in three different frames. text='Deposit')
self.label5 = Label(self.bottom_frame,
from tkinter import * text='Withdraw')
self.label6 = Label(self.bottom_frame,
class MyGUI: text='Balance')
def __init__(self):
# Create the main window widget. # Pack the labels that are in the bottom frame.
self.main_window = Tk() # Use the side='left' argument to arrange them
# horizontally from the left of the frame.
# Create two frames, one for the top of the self.label4.pack(side='left')
# window, and one for the bottom. self.label5.pack(side='left')
self.top_frame = Frame(self.main_window) self.label6.pack(side='left')
self.bottom_frame = Frame(self.main_window)
self.bbb=Frame(self.main_window) # My new bbb frame
self.label99 = Label(self.bbb,text='Third Frame',relief="raised")
# Create three Label widgets for the top frame. self.label99.pack(side='top',ipadx=45,ipady=30,padx=20,pady=20)
self.label1 = Label(self.top_frame, # Yes, we have to pack the frames too!
text='Location') self.top_frame.pack()
self.label2 = Label(self.top_frame, self.bottom_frame.pack()
text='Traffic') self.bbb.pack()
self.label3 = Label(self.top_frame, # Enter the tkinter main loop.
text='Date’) mainloop()
self.label1.pack(side='top')
self.label2.pack(side='top') # Create an instance of the MyGUI class
self.label3.pack(side='top') my_gui = MyGUI()
AOU- M110 29
Button Widgets and Info Dialog Boxes
You use the Button widget to create a standard button in a window.
When the user clicks a button, a specified function or method is called.
An info dialog box is a simple window that displays a message to the user and has an
OK button that dismisses the dialog box.
You can use the tkinter.messagebox module’s showinfo function to display an info
dialog box.
• Button widget: widget that the user can click to cause an action to take
place
• When creating a button can specify:
• Text to appear on the face of the button
• A callback function
• Callback function: A function or method that executes when the user
clicks the button
• Also known as an event handler.
AOU- M110 30
Button Widgets and Info Dialog Boxes
Syntax: w = Button ( root, option=value, ... )
Parameters:
root: represents the parent window.
options: below is the list of most used options for this widget. These options can be
used as key-value pairs separated by commas.
option Description
command Function or method to be called when the button is clicked.
bg Normal background color.
fg Normal foreground (text) color.
font Text font to be used for the button's label.
image Image to be displayed on the button (instead of text).
padx Additional padding left and right of the text.
pady Additional padding above and below the text.
Set this option to DISABLED to gray out the button and make it
state unresponsive. Has the value ACTIVE when the mouse is over it.
Default is NORMAL.
Relief specifies the type of the border. Some of the values are
relief
SUNKEN, RAISED, GROOVE, and RIDGE.
AOU- M110 31
Button Widgets and Info Dialog Boxes
• Info dialog box: a dialog box that shows information to the user.
• Format for creating an info dialog box:
• Import tkinter.messagebox module
• tkinter.messagebox.showinfo(title, message)
• title is displayed in dialog box’s title bar
• message is an informational string displayed in the main part of the dialog box
AOU- M110 32
Button Widgets and Info Dialog Boxes
AOU- M110 33
Output
tkinter.messagebox.showinfo(title, message)
AOU- M110 34
Creating a Quit Button
GUI programs usually have a Quit button (or an Exit button) that closes the
program when the user clicks it.
To create a Quit button in a Python program, you simply create a Button widget that
calls the root widget’s destroy method as a callback function.
AOU- M110 35
When the Quit button is
clicked, the root widget's
destroy method is called and
the program ends
AOU- M110 3
Getting Input with the Entry Widget
• Entry widget: A rectangular area that the user can type text into.
• Used to gather input in a GUI program
• Typically followed by a button for submitting the data
• The button’s callback function retrieves the data from the Entry widgets and
processes it
• Entry widget’s get method: used to retrieve the data from an Entry
widget
• Returns a string
AOU- M110 37
Getting Input with the Entry Widget
AOU- M110 38
Using Labels as Output Fields
AOU- M110 39
Using Labels as Output Fields
• StringVar class: tkinter module class that can be used along with Label
widget to display data
• Create StringVar object and then create Label widget and associate it with
the StringVar object
• Subsequently, any value stored in the StringVar object with automatically be
displayed in the Label widget
AOU- M110 40
Notice that we use the argument textvariable=self.value.
This creates an association between the Label widget and the StringVar object that is referenced by the value variable.
Any value that we store in the StringVar object will be displayed in the label.
41
AOU- M110
Using Labels as Output Fields
AOU- M110 42
More about Tkinter pack() Method
Syntax: widget.pack( pack_options )
Here is the list of possible options:
•expand − When set to true, widget expands to fill any space not otherwise
used in widget's parent.
•fill − Determines whether widget fills any extra space allocated to it by the
packer or keeps its own minimal dimensions: NONE (default), X (fill only
horizontally), Y (fill only vertically), or BOTH (fill both horizontally and
vertically).
•side − Determines which side of the parent widget packs against: TOP
(default), BOTTOM, LEFT, or RIGHT.
AOU- M110 43
More techniques to use pack method
# Importing tkinter module
from tkinter import *
# creating Tk window
master = Tk()
# creating a Frame which can expand according
# to the size of the window
pane = Frame(master)
pane.pack(fill = BOTH, expand = True)
# Button 2
b2 = Button(pane, text = "Click me too")
b2.pack(fill = BOTH, expand = True)
# Execute Tkinter
master.mainloop()
AOU- M110 44
More techniques to use pack method
from tkinter import *
# creating Tk window
master = Tk()
# creating a Frame which can expand according
# to the size of the window
pane = Frame(master)
pane.pack(fill = BOTH, expand = True)
# button widgets which can also expand and fill
# in the parent widget entirely
# Button 1
b1 = Button(pane, text = "Click me !",
bg = "red", fg = "white")
b1.pack(side = TOP, expand = True, fill = BOTH)
# Button 2
b2 = Button(pane, text = "Click me too",
bg = "yellow", fg = "blue")
b2.pack(side = TOP, expand = True, fill = BOTH)
# Button 3
b3 = Button(pane, text = "I'm also a button",
bg = "green", fg = "white")
b3.pack(side = TOP, expand = True, fill = BOTH)
# Execute Tkinter
master.mainloop()
AOU- M110 45
More techniques to use pack method
# Importing tkinter module
from tkinter import *
# from tkinter.ttk import *
# creating Tk window
master = Tk()
# creating a Fra, e which can expand according
# to the size of the window
pane = Frame(master)
pane.pack(fill = BOTH, expand = True)
# button widgets which can also expand and fill
# in the parent widget entirely
# Button 1
b1 = Button(pane, text = "Click me !",
bg = "red", fg = "white")
b1.pack(side = LEFT, expand = True, fill = BOTH)
# Button 2
b2 = Button(pane, text = "Click me too",
bg = "blue", fg = "white")
b2.pack(side = LEFT, expand = True, fill = BOTH)
# Button 3
b3 = Button(pane, text = "I'm also a button",
bg = "green", fg = "white")
b3.pack(side = LEFT, expand = True, fill = BOTH)
# Execute Tkinter
master.mainloop()
AOU- M110 46