0% found this document useful (0 votes)
36 views80 pages

13 Gaddis Python Lecture PPT Ch13

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

13 Gaddis Python Lecture PPT Ch13

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

Starting out with Python

Fifth Edition

Chapter 13
GUI Programming

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 1
Topics (1 of 2)
• Graphical User Interfaces
• Using the tkinter Module
• Displaying Text with Label Widgets
• Organizing Widgets with Frames
• Button Widgets and Info Dialog Boxes
• Getting Input with the Entry Widget
• Using Labels as Output Fields

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 2
Topics (2 of 2)
• Radio Buttons and Check Buttons
• ListBox Widgets
• Drawing Shapes with the Canvas Widget

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 3
Graphical User Interfaces (1 of 3)
• User Interface: the part of the computer with which the
user interacts
• Command line interface: 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

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 4
Graphical User Interfaces (2 of 3)
• Command line interfaces

Figure 13-1 A command line interface

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 5
Graphical User Interfaces (3 of 3)
• Dialog boxes: 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

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 6
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

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 7
Using the tkinter Module (1 of 3)
• No GUI programming features built into Python
• tkinter module: allows you to create simple GUI
programs
– Comes with Python
• Widget: graphical element that the user can interact
with or view
– Presented by a GUI program

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 8
Using the tkinter Module (2 of 3)
Table 13-1 tkinter widgets

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 that are 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.

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 9
Using the tkinter Module
• 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

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 10
Example (1 of 6)
1 # This program displays an empty window.
2
3 import tkinter
4
5 class MyGUI:
6 def __init__(self):
7 # Create the main window widget.
8 self.main_window = tkinter.Tk()
9
10 # Display a title.
11 self.main_window.title('My First GUI')
12
13 # Enter the tkinter main loop.
14 tkinter.mainloop()
15
16 # Create an instance of the MyGUI class.
17 if __name__ == '__main__':
18 my_gui = MyGUI()

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 11
Display Text with Label Widgets (1 of 2)
• Label widget: displays a single line of text in a
window
– Made by creating an instance of tkinter module’s
Label class
– Format: tkinter.Label(self.main_window,
text = 'my text')
 First argument references the root widget, second argument
shows text that should appear in label

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 12
Display Text with Label Widgets (2 of 2)
• pack method: determines where a widget should be
positioned and makes it visible when the main window
is displayed
– Called for each widget in a window
– Receives an argument to specify positioning
 Positioning depends on the order in which widgets were
added to the main window
 Valid arguments: side='top', side='left',
side='right'

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 13
Example (2 of 6)

self.label = tkinter.Label(self.main_window,
text='Hello World!')
self.label.pack()

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 14
Example (3 of 6)

self.label1 = tkinter.Label(self.main_window,
text='Hello World!')
self.label2 = tkinter.Label(self.main_window,
text='This is my GUI
program.')
self.label.pack()

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 15
Example (4 of 6)

self.label1 = tkinter.Label(self.main_window,
text='Hello World!')
self.label2 = tkinter.Label(self.main_window,
text='This is my GUI program.')
self.label1.pack(side='left')
self.label2.pack(side='left')

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 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

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 17
Example (5 of 6)

self.label = tkinter.Label(self.main_window,
text='Hello World',
borderwidth=1,
relief='solid'

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 18
Example (6 of 6)

self.label = tkinter.Label(self.main_window,
text='Hello World',
borderwidth=4,
relief='solid'

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 19
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.

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 20
Values for relief Argument (2 of 2)

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 21
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

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 22
Internal Padding (1 of 3)
• 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

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 23
Internal Padding (2 of 3)
1 # This program demonstrates internal padding.
2 import tkinter
3
4 class MyGUI:
5 def __init__(self):
6 # Create the main window widget.
7 self.main_window = tkinter.Tk()
8
9 # Create two Label widgets with solid borders.
10 self.label1 = tkinter.Label(self.main_window,
11 text='Hello World!',
12 borderwidth=1,
13 relief='solid')
14
15 self.label2 = tkinter.Label(self.main_window,
16 text='This is my GUI program.',
17 borderwidth=1,
18 relief='solid')
19

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 24
Internal Padding (3 of 3)
20 # Display the Labels with 20 pixels of horizontal
21 # and vertical internal padding.
22 self.label1.pack(ipadx=20, ipady=20)
23 self.label2.pack(ipadx=20, ipady=20)
24
25 # Enter the tkinter main loop.
26 tkinter.mainloop()
27
28 # Create an instance of the MyGUI class.
29 if __name__ == '__main__':
30 my_gui = MyGUI()

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 25
External Padding (1 of 3)
• 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

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 26
External Padding (2 of 3)
1 # This program demonstrates external padding.
2 import tkinter
3
4 class MyGUI:
5 def __init__(self):
6 # Create the main window widget.
7 self.main_window = tkinter.Tk()
8
9 # Create two Label widgets with solid borders.
10 self.label1 = tkinter.Label(self.main_window,
11 text='Hello World!',
12 borderwidth=1,
13 relief='solid')
14
15 self.label2 = tkinter.Label(self.main_window,
16 text='This is my GUI program.',
17 borderwidth=1,
18 relief='solid')
19
20 # Display the Labels with 20 pixels of horizontal
21 # and vertical external padding.
22 self.label1.pack(padx=20, pady=20)
23 self.label2.pack(padx=20, pady=20)
24
25 # Enter the tkinter main loop.
26 tkinter.mainloop()
27
28 # Create an instance of the MyGUI class.
29 if __name__ == '__main__':
30 my_gui = MyGUI()

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 27
External Padding (3 of 3)
1 # This program demonstrates both internal and external padding.
2 import tkinter
3
4 class MyGUI:
5 def __init__(self):
6 # Create the main window widget.
7 self.main_window = tkinter.Tk()
8
9 # Create two Label widgets with solid borders.
10 self.label1 = tkinter.Label(self.main_window,
11 text='Hello World!',
12 borderwidth=1,
13 relief='solid')
14
15 self.label2 = tkinter.Label(self.main_window,
16 text='This is my GUI program.',
17 borderwidth=1,
18 relief='solid')
19
20 # Display the Labels with 20 pixels of horizontal
21 # and vertical external padding.
22 self.label1.pack(ipadx=20, ipady=20, padx=20, pady=20)
23 self.label2.pack(ipadx=20, ipady=20, padx=20, pady=20)
24
25 # Enter the tkinter main loop.
26 tkinter.mainloop()
27
28 # Create an instance of the MyGUI class.
29 if __name__ == '__main__':
30 my_gui = MyGUI()

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 28
Organizing Widgets with Frames (1 of 2)
• Frame widget: container that holds other widgets
– Useful for organizing and arranging groups of widgets
in a window
– The contained widgets are added to the frame widget
which contains them
 Example:
tkinter.Label(self.top_frame,
text = 'hi')

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 29
Organizing Widgets with Frames (2 of 2)

Figure 13-19 Arrangement of widgets

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 30
Button Widgets and Info Dialog Boxes
(1 of 4)

• 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: function or method that executes


when the user clicks the button
– Also known as an event handler

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 31
Button Widgets and Info Dialog Boxes
(2 of 4)

• 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

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 32
Button Widgets and Info Dialog Boxes
(3 of 4)

Figure 13-20 The main window displayed by Program 13-10

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 33
Button Widgets and Info Dialog Boxes
(4 of 4)

Figure 13-21 The info dialog box displayed by Program 13-10

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 34
Creating a Quit Button
• Quit button: closes the program when the user clicks it
• To create a quit button in Python:
– Create a Button widget
– Set the root widget’s destroy method as the callback
function
 When the user clicks the button the destroy method is
called and the program ends

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 35
Getting Input with the Entry Widget
(1 of 2)

• Entry widget: 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

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 36
Getting Input with the Entry Widget
(2 of 2)

Figure 13-25 The info dialog box

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 37
Using Labels as Output Fields (1 of 3)
• Can use Label widgets to dynamically display output
– Used to replace info dialog box
– Create empty Label widget in main window, and write
code that displays desired data in the label when a
button is clicked

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 38
Using Labels as Output Fields (2 of 3)
• 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

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 39
Using Labels as Output Fields (3 of 3)

Figure 13-26 The window initially displayed

Figure 13-27 The window showing 1000 kilometers converted to miles

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 40
Radio Buttons and Check Buttons (1 of 2)
• Radio button: small circle that appears filled when it is
selected and appears empty when it is deselected
– Useful when you want the user to select one choice
from several possible options
• Radiobutton widgets: created using tkinter
module’s Radiobutton class
– Radiobutton widgets are mutually exclusive
 Only one radio button in a container may be selected at
any given time

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 41
Radio Buttons and Check Buttons (2 of 2)
• IntVar class: a tkinter module class that can be
used along with Radiobutton widgets
– Steps for use:
 Associate group of Radiobutton widgets with the same
IntVar object
 Assign unique integer to each Radiobutton
 When a Radiobutton widgets is selected, its unique
integer is stored in the IntVar object
– Can be used to select a default radio button

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 42
Using Callback Functions with
Radiobuttons
• You can specify a callback function with
Radiobutton widgets
– Provide an argument command=self.my_method
when creating the Radiobutton widget
– The command will execute immediately when the radio
button is selected
– Replaces the need for a user to click OK or submit
before determining which Radiobutton is selected

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 43
Check Buttons
• Check button: small box with a label appearing next to
it; check mark indicates when it is selected
– User is allowed to select any or all of the check buttons
that are displayed in a group
 Not mutually exclusive

• Checkbutton widgets: created using tkinter


module’s Checkbutton class
– Associate different IntVar object with each
Checkbutton widget

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 44
Listbox Widgets
• A Listbox widget displays a list of items and allows
the user to select one or more items

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 45
Example
1 # This program demonstrates a simple Listbox.
2 import tkinter
3
4 class ListboxExample:
5 def __init__(self):
6 # Create the main window.
7 self.main_window = tkinter.Tk()
8
9 # Create a Listbox widget.
10 self.listbox = tkinter.Listbox(self.main_window)
11 self.listbox.pack(padx=10, pady=10)
12
13 # Populate the Listbox with the data.
14 self.listbox.insert(0, 'Monday')
15 self.listbox.insert(1, 'Tuesday')
16 self.listbox.insert(2, 'Wednesday')
17 self.listbox.insert(3, 'Thursday')
18 self.listbox.insert(4, 'Friday')
19 self.listbox.insert(5, 'Saturday')
20 self.listbox.insert(6, 'Sunday')
21
22 # Start the main loop.
23 tkinter.mainloop()
24
25 # Create an instance of the ListboxExample class.
26 if __name__ == '__main__':
27 listbox_example = ListboxExample()

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 46
Specifying the Size of a Listbox
1 # This program demonstrates a simple Listbox.
2 import tkinter
3
4 class ListboxExample:
5 def __init__(self):
6 # Create the main window.
7 self.main_window = tkinter.Tk()
8
9 # Create a Listbox widget.
10 self.listbox = tkinter.Listbox(
11 self.main_window, height=0, width=0)
12 self.listbox.pack(padx=10, pady=10)
13
14 # Create a list with the days of the week.
15 days = ['Monday', 'Tuesday', 'Wednesday',
16 'Thursday', 'Friday', 'Saturday',
17 'Sunday']
18
19 # Populate the Listbox with the data.
20 for day in days:
21 self.listbox.insert(tkinter.END, day)
22
23 # Start the main loop.
24 tkinter.mainloop()
25
26 # Create an instance of the ListboxExample class.
27 if __name__ == '__main__':
28 listbox_example = ListboxExample()

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 47
Selection Modes
Mode Description
tkinter.BROWSE The user can select one item at a time by clicking in the Listbox.
Additionally, if the user clicks and drags the mouse inside the
(This is the default mode) Listbox, the item that is currently under the cursor will be
selected.

tkinter.EXTENDED The user can select a group of adjacent items by clicking on the
first item and dragging the mouse to the last item.

tkinter.MULTIPLE Multiple items can be selected. When you click an unselected


item, the item becomes selected. When you click a selected item,
the item becomes unselected.

tkinter.SINGLE The user can select one item at a time by clicking in the Listbox.

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 48
Retrieving the Selected Item(s) (1 of 2)
• The curselection method returns a tuple
containing the indexes of the items that are currently
selected in the Listbox
– If no item is selected, the tuple will be empty
– If an item is selected and the selection mode is
tkinter.BROWSE or tkinter.SINGLE, the tuple will
contain only one element
– If the Listbox's selection mode is
tkinter.EXTENDED or tkinter.MULTIPLE, the
tuple can contain multiple elements because those
selection modes allow the user to select multiple items

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 49
Retrieving the Selected Item(s) (2 of 2)
• Once you have the index of the selected item, you can
use the get method to retrieve the selected item or
items from the Listbox
• The get method accepts an integer index as its
argument and returns the item that is located at that
index in the Listbox

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 50
Examples
self.listbox = tkinter.Listbox(self.main_window)

(etc…)

index = self.listbox.curselection()
tkinter.messagebox.showinfo(self.listbox.get(index))

self.listbox = tkinter.Listbox(self.main_window,
selectmode=tkinter.EXTENDED)

(etc…)

indexes = self.listbox.curselection()
for i in indexes:
tkinter.messagebox.showinfo(self.listbox.get(i))

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 51
Listboxes and Callback Functions
(1 of 3)

• You can optionally bind a callback function to a


Listbox
• When the user clicks an item in the Listbox, the
callback function is immediately executed

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 52
Listboxes and Callback Functions
(2 of 3)

• Example callback function:


– Assume listbox is a Listbox widget
– You must provide a parameter to accept an event
object as an argument

def show_item(self, event):


index = self.listbox.curselection()
item = self.listbox.get(index)
tkinter.messagebox.showinfo('Selected Item', item)

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 53
Listboxes and Callback Functions
(3 of 3)

• To bind the show_item function to the listbox


widget:

self.listbox.bind('<<ListboxSelect>>', self.show_item)

• Once done, the show_item function will execute


whenever the user clicks an item in the listbox
widget

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 54
Adding a Vertical Scrollbar to a Listbox
1. Create a frame to hold the Listbox and the scrollbar
2. Pack the frame
3. Create a Listbox inside the frame
4. Pack the Listbox to the left side of the frame
5. Create the vertical scrollbar inside the frame
6. Pack the scrollbar to the right side of the frame
7. Configure the scrollbar to call the Listbox's yview
method when the slider knob is moved
8. Configure the Listbox to call the scrollbar's set
method any time the Listbox is updated

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 55
Example (1 of 4)
# Create the main window.
self.main_window = tkinter.Tk()

# Create a frame for the Listbox and vertical scrollbar.


self.listbox_frame = tkinter.Frame(self.main_window)
self.listbox_frame.pack(padx=20, pady=20)

# Create a Listbox widget in the listbox_frame.


self.listbox = tkinter.Listbox(
self.listbox_frame, height=6, width=0)
self.listbox.pack(side='left')

# Create a vertical Scrollbar in the listbox_frame.


self.scrollbar = tkinter.Scrollbar(
self.listbox_frame, orient=tkinter.VERTICAL)
self.scrollbar.pack(side='right', fill=tkinter.Y)

# Configure the Scrollbar and Listbox to work together.


self.scrollbar.config(command=self.listbox.yview)
self.listbox.config(yscrollcommand=self.scrollbar.set)

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 56
Adding a Horizontal Scrollbar to a
Listbox
1. Create a frame to hold the Listbox and the scrollbar
2. Pack the frame
3. Create a Listbox inside the frame
4. Pack the Listbox to the top of the frame
5. Create the horizontal scrollbar inside the frame
6. Pack the scrollbar to the bottom of the frame
7. Configure the scrollbar to call the Listbox's xview
method when the slider knob is moved
8. Configure the Listbox to call the scrollbar's set
method any time the Listbox is updated

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 57
Example (2 of 4)
# Create the main window.
self.main_window = tkinter.Tk()

# Create a frame for the Listbox and scrollbar.


self.listbox_frame = tkinter.Frame(self.main_window)
self.listbox_frame.pack(padx=20, pady=20)

# Create a Listbox widget in the listbox_frame.


self.listbox = tkinter.Listbox(
self.listbox_frame, height=0, width=30)
self.listbox.pack(side='top')

# Create a horizontal Scrollbar in the listbox_frame.


self.scrollbar = tkinter.Scrollbar(
self.listbox_frame, orient=tkinter.HORIZONTAL)
self.scrollbar.pack(side='bottom', fill=tkinter.X)

# Configure the Scrollbar and Listbox to work together.


self.scrollbar.config(command=self.listbox.xview)
self.listbox.config(xscrollcommand=self.scrollbar.set)

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 58
Adding Vertical and Horizontal Scrollbars
to a Listbox (1 of 2)
1. Create the outer frame to hold the inner frame and the
horizontal scrollbar
2. Pack the outer frame
3. Create the inner frame to hold the Listbox and the
vertical scrollbar
4. Pack the inner frame
5. Create a Listbox inside the inner frame
6. Pack the Listbox to the left side of the inner frame
7. Create a vertical scrollbar inside the inner frame
8. Pack the scrollbar to the right side of the inner frame
9. Create the horizontal scrollbar inside the outer frame
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 59
Adding Vertical and Horizontal Scrollbars
to a Listbox (2 of 2)
10. Pack the horizontal scrollbar to the bottom of the outer
frame
11. Configure the vertical scrollbar to call the Listbox's
yview method when the slider knob is moved
12. Configure the horizontal scrollbar to call the Listbox's
xview method when the slider knob is moved
13. Configure the Listbox to call both scrollbar's set
method any time the Listbox is updated

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 60
Example (3 of 4)
# Create the main window.
self.main_window = tkinter.Tk()

# Create an outer frame to hold the inner frame


# and the horizontal scrollbar.
self.outer_frame = tkinter.Frame(self.main_window)
self.outer_frame.pack(padx=20, pady=20)

# Create an inner frame for the Listbox and vertical scrollbar.


self.inner_frame = tkinter.Frame(self.outer_frame)
self.inner_frame.pack()

# Create a Listbox widget in the inner_frame.


self.listbox = tkinter.Listbox(
self.inner_frame, height=5, width=30)
self.listbox.pack(side='left')

# Create a vertical Scrollbar in the inner_frame.


self.v_scrollbar = tkinter.Scrollbar(
self.inner_frame, orient=tkinter.VERTICAL)
self.v_scrollbar.pack(side='right', fill=tkinter.Y)

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 61
Example (4 of 4)

# Create a horizontal Scrollbar in the outer_frame.


self.h_scrollbar = tkinter.Scrollbar(
self.outer_frame, orient=tkinter.HORIZONTAL)
self.h_scrollbar.pack(side='bottom', fill=tkinter.X)

# Configure the Scrollbars and the Listbox to work together.


self.v_scrollbar.config(command=self.listbox.yview)
self.h_scrollbar.config(command=self.listbox.xview)
self.listbox.config(yscrollcommand=self.v_scrollbar.set,
xscrollcommand=self.h_scrollbar.set)

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 62
Drawing Shapes with the Canvas
Widget (1 of 4)
• The Canvas widget is a blank, rectangular area that allows
you to draw simple 2D shapes.
• You use the Canvas widget’s screen coordinate system to
specify the location of your graphics.
• The coordinates of the pixel in the upper-left corner of the
screen are (0, 0).
– The X coordinates increase from left to right
– The Y coordinates increase from top to bottom.

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 63
Drawing Shapes with the Canvas
Widget (2 of 4)

Figure 13-45 Various pixel locations in a 640 by 480 window

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 64
Drawing Shapes with the Canvas
Widget (3 of 4)
• Creating a Canvas widget:

# Create the main window.


self.main_window = tkinter.Tk()

# Create the Canvas widget.


self.canvas = tkinter.Canvas(self.main_window, width=200, height=200)

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 65
Drawing Shapes with the Canvas
Widget (4 of 4)
• The Canvas widget has numerous methods for
drawing graphical shapes on the surface of the
widget.
• The methods that we will discuss are:
– create_line
– create_rectangle
– create_oval
– create_arc
– create_polygon
– create_text

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 66
Drawing a Line (1 of 2)

Coordinates of
the line's ending
point

canvas_name.create_line(x1, y1, x2, y2, options…)

Coordinates of Optional arguments


the line's starting (See Table 13-2)
point

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 67
Drawing a Line (2 of 2)
1 # This program demonstrates the Canvas widget.
2 import tkinter
3
4 class MyGUI:
5 def _ _init_ _(self):
6 # Create the main window.
7 self.main_window = tkinter.Tk()
8
9 # Create the Canvas widget.
10 self.canvas = tkinter.Canvas(self.main_window,
width=200,height=200)
11
12 # Draw two lines.
13 self.canvas.create_line(0, 0, 199, 199)
14 self.canvas.create_line(199, 0, 0, 199)
15
16 # Pack the canvas.
17 self.canvas.pack()
18
19 # Start the mainloop.
20 tkinter.mainloop()
21
22 # Create an instance of the MyGUI class.
22 if _ _name_ _ == '_ _main_ _':
23 my_gui = MyGUI()

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 68
Drawing a Rectangle (1 of 2)

Coordinates of
the lower-right
corner

canvas_name.create_rectangle(x1, y1, x2, y2, options…)

Coordinates of Optional arguments


the upper-left (See Table 13-3)
corner

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 69
Drawing a Rectangle (2 of 2)
1 # This program draws a rectangle on a Canvas.
2 import tkinter
3
4 class MyGUI:
5 def _ _init_ _(self):
6 # Create the main window.
7 self.main_window = tkinter.Tk()
8
9 # Create the Canvas widget.
10 self.canvas = tkinter.Canvas(self.main_window,
width=200,height=200)
11
12 # Draw two lines.
13 self.canvas.create_line(0, 0, 199, 199)
14 self.canvas.create_line(199, 0, 0, 199)
15
16 # Pack the canvas.
17 self.canvas.pack()
18
19 # Start the mainloop.
20 tkinter.mainloop()
21
22 # Create an instance of the MyGUI class.
23 my_gui = MyGUI()

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 70
Drawing an Oval (1 of 2)
Coordinates of
the lower-right
corner of
bounding rectangle

canvas_name.create_oval(x1, y1, x2, y2, options…)

Coordinates of Optional arguments


the upper-left (See Table 13-4)
corner of
bounding rectangle

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 71
Drawing an Oval (2 of 2)
1 # This program draws a rectangle on a Canvas.
2 import tkinter
3
4 class MyGUI:
5 def _ _init_ _(self):
6 # Create the main window.
7 self.main_window = tkinter.Tk()
8
9 # Create the Canvas widget.
10 self.canvas = tkinter.Canvas(self.main_window,
width=200,height=200)
11
12 # Draw two ovals.
13 self.canvas.create_oval(20, 20, 70, 70)
14 self.canvas.create_oval(100, 100, 180, 130)
15
16 # Pack the canvas.
17 self.canvas.pack()
18
19 # Start the mainloop.
20 tkinter.mainloop()
21
22 # Create an instance of the MyGUI class.
23 if _ _name_ _ == '_ _main_ _':
24 my_gui = MyGUI()

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 72
Drawing an Arc (1 of 2)
Coordinates of Coordinates of
the upper-left the lower-right
corner of corner of
bounding rectangle bounding rectangle

canvas_name.create_arc(x1, y1, x2, y2,


Starting angle start=angle, extent=width,
options…)
Counter clockwise
extent of the arc
Optional arguments
(See Table 13-5)

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 73
Drawing an Arc (2 of 2)
1 # This program draws an arc on a Canvas.
2 import tkinter
3
4 class MyGUI:
5 def _ _init_ _(self):
6 # Create the main window.
7 self.main_window = tkinter.Tk()
8
9 # Create the Canvas widget.
10 self.canvas = tkinter.Canvas(self.main_window,
width=200,height=200)
11
12 # Draw an arc.
13 self.canvas.create_arc(10, 10, 190, 190, start=45, extent=30)
14
15 # Pack the canvas.
16 self.canvas.pack()
17
18 # Start the mainloop.
19 tkinter.mainloop()
20
21 # Create an instance of the MyGUI class.
22 if _ _name_ _ == '_ _main_ _':
23 my_gui = MyGUI()

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 74
Drawing a Polygon (1 of 3)

Coordinates of
the second vertex

canvas_name.create_polygon(x1, y1, x2, y2, …,options…)

Coordinates of
the first vertex Optional arguments
(See Table 13-7)

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 75
Drawing a Polygon (2 of 3)

self.canvas.create_polygon(60, 20, 100, 20, 140, 60, 140, 100,


100, 140, 60, 140, 20, 100, 20, 60)

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 76
Drawing a Polygon (3 of 3)
1 # This program draws a polygon on a Canvas.
2 import tkinter
3
4 class MyGUI:
5 def _ _init_ _(self):
6 # Create the main window.
7 self.main_window = tkinter.Tk()
8
9 # Create the Canvas widget.
10 self.canvas = tkinter.Canvas(self.main_window, width=160,
height=160)
11
12 # Draw a polygon.
13 self.canvas.create_polygon(60, 20, 100100, 140, 60, 140, 20,
100, 20, 60, 20, 140, 60, 140, 100,)
14
15
16 # Pack the canvas.
17 self.canvas.pack()
18
19 # Start the mainloop.
20 tkinter.mainloop()
21
22 # Create an instance of the MyGUI class.
23 if _ _name_ _ == '_ _main_ _’:
24 my_gui = MyGUI()

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 77
Displaying Text on the Canvas (1 of 2)

Text to display

canvas_name.create_text(x, y, text=text, options…)

Coordinates of
the text's insertion Optional arguments
point (See Table 13-8)

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 78
Displaying Text on the Canvas (2 of 2)
1 # This program draws a polygon on a Canvas.
2 import tkinter
3
4 class MyGUI:
5 def _ _init_ _(self):
6 # Create the main window.
7 self.main_window = tkinter.Tk()
8
9 # Create the Canvas widget.
10 self.canvas = tkinter.Canvas(self.main_window, width=160,
height=160)
11
12 # Display text in the center of the window.
13 self.canvas.create_text(100, 100, text='Hello World')
14
15 # Pack the canvas.
16 self.canvas.pack()
17
18 # Start the mainloop.
19 tkinter.mainloop()
20
21 # Create an instance of the MyGUI class.
22 if _ _name_ _ == '_ _main_ _’:
23 my_gui = MyGUI()

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 79
Summary
• This chapter covered:
– Graphical user interfaces and their role as event-driven
programs
– The tkinter module, including:
 Creating a GUI window
 Adding widgets to a GUI window
 Organizing widgets in frames
 Receiving input and providing output using widgets
 Creating buttons, check buttons, and radio buttons
 Drawing simple shapes with the Canvas widget

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 13 - 80

You might also like