SlideShare a Scribd company logo
Programming with Python
Guide to Programming with Python 2
Objectives
• Work with a GUI toolkit
• Create and fill frames
• Create and use buttons
• Create and use text entries and text boxes
• Create and use check buttons
• Create and use radio buttons
Guide to Programming with Python 3
The Mad Lib Program
Figure 10.1: Sample run of the Mad Lib program
A nicely laid-out GUI awaits the user’s creativity.
Guide to Programming with Python 4
The Mad Lib Program (continued)
Figure 10.2: Sample run of the Mad Lib program
The user has entered all of the necessary information.
Guide to Programming with Python 5
The Mad Lib Program (continued)
Figure 10.3: Sample run of the Mad Lib program
After clicking Click for story button, text box displays masterpiece.
Guide to Programming with Python 6
Examining A GUI
Figure 10.4: Examining a GUI
You’ll learn to create all of these GUI elements.
Guide to Programming with Python 7
Examining A GUI (continued)
Table 10.1: Selected GUI Elements
Guide to Programming with Python 8
Understanding Event-Driven
Programming
• Event-driven program: A program that responds
to actions regardless of the order in which they
occur
• Event: Something that happens involving a
program's objects
• Event handler: Code that runs when a specific
event occurs
• Bind: To associate an event with an event handler
• Event loop: A loop that checks for events and calls
appropriate event handlers when they occur
Guide to Programming with Python 9
Understanding Event-Driven
Programming (continued)
• GUI programs traditionally event-driven
• Mad Lib without event-driven programming
– Ask series of questions with raw_input() function
– Ask for name of a person, plural noun...
– User must provide each piece of information, in order
• Mad Lib with event-driven programming
– Can use a GUI
– User can enter the information in any order
Guide to Programming with Python 10
Using A Root Window
• Root Window
– Foundation of GUI program
– Foundation upon which to add all other GUI
elements
– Like root of tree, anchors all other parts
Guide to Programming with Python 11
The Simple GUI Program
Figure 10.5: Sample run of the Simple GUI program
The program creates only a lone window. simple_gui.py
Guide to Programming with Python 12
The Simple GUI Program (continued)
• GUI programs can generate console window too
• Console window helpful to see error messages
• On Windows machine can suppress console
window by changing program extension from py to
pyw
Guide to Programming with Python 13
Importing the Tkinter Module
from Tkinter import *
• Tkinter is a GUI module
• Imports all Tkinter into global scope
• Normally, avoid this kind of import
• Some modules designed to be imported this way
• Saves typing and makes for cleaner code
Guide to Programming with Python 14
Creating a Root Window
root = Tk()
• To create a root window, instantiate object of the
Tkinter class Tk
• Because of from Tkinter import *, no need to prefix
the module name
Guide to Programming with Python 15
Modifying a Root Window
root.title("Simple GUI")
root.geometry("200x100")
• title()
– Sets title of root window
– Takes string
• geometry()
– Sets size of the root window
– Takes string (not integers) for window’s width and
height, separated by the "x" character
Guide to Programming with Python 16
Entering a Root Window’s Event Loop
root.mainloop()
• Root window's event loop entered
• Window stays open, waiting to handle events
Guide to Programming with Python 17
Using Labels
• Widget: GUI elements (short for "window gadget")
• Label widget
– Uneditable text or icons (or both)
– Often used to label other widgets
– Unlike most other widgets, labels aren’t interactive
Guide to Programming with Python 18
The Labeler Program
Figure 10.7: Sample run of the Labeler program
A label can provide information about a GUI.
labeler.py
Guide to Programming with Python 19
Creating a Frame
app = Frame(root)
• Master: A widget that contains other widgets
• Layout Manager: Controls arrangement of widgets
• Frame is widget that can hold other widgets
• When creating widget, must pass its master to
constructor of new object
• Here, root is master that contains app
Guide to Programming with Python 20
Creating a Frame (continued)
app.grid()
• grid()
– Method that all widgets have
– Associated with grid layout manager
– Can be used to create desired layout of widgets
Guide to Programming with Python 21
Creating a Label
lbl = Label(app, text = "I'm a label!")
lbl.grid()
• Label Class
– For a label widget
– Master is first argument passed to constructor
– text parameter for widget's text
– grid() method invoked ensures widget visible
(places widget at a default location in frame if called
with no arguments)
Guide to Programming with Python 22
Using Buttons
• Button widget
– Is a button in GUI
– Can be activated by user to perform some action
Guide to Programming with Python 23
The Lazy Buttons Program
Figure 10.8: Sample run of the Lazy Buttons program
You can click these lazy buttons all you want; they won’t do a thing.
lazy_buttons.py
Guide to Programming with Python 24
Creating Buttons
bttn1 = Button(app, text = "I do nothing!")
bttn1.grid()
• Button Class
– For a button widget
– Master is first argument passed to constructor
– text parameter for widget's text
– grid() method invoked ensures widget visible
Guide to Programming with Python 25
Creating Buttons (continued)
bttn2 = Button(app)
bttn2.grid()
bttn2.configure(text = "Me too!")
• Can add blank button to the frame
• configure() method sets or changes widget options
– Useful for changing widget after it has been
instantiated
Guide to Programming with Python 26
Creating Buttons (continued)
bttn3 = Button(app)
bttn3.grid()
bttn3["text"] = "Same here!"
• Can access widget's options through dictionary-like
interface
• Key for option is name of the option as a string
• Here, set third button's text option to "Same here!”
• Useful for changing widget after it has been
instantiated (like .config())
Guide to Programming with Python 27
Creating a GUI Using a Class
• Organizing code into classes can make
programming easier
• Often beneficial to write larger GUI programs in
OOP style
Guide to Programming with Python 28
The Lazy Buttons 2 Program
Figure 10.9: Sample run of the Lazy Buttons 2 program
Program appears the same but significant changes under the hood.
Guide to Programming with Python 29
Defining the Application Class
class Application(Frame):
""" A GUI application with three buttons. """
def __init__(self, master):
• Instead of instantiating Frame object, will instantiate
Application object
• Application object becomes just a specialized
type of Frame object
• master will be the Tk window that the frame
belongs to (root in all our examples so far)
Guide to Programming with Python 30
Defining a Constructor Method
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.create_widgets()
• Frame constructor called first
– This is what is used instead of super() for old object classes
• Pass Application object’s master, so it gets
properly set as master
• Invoke Application object’s create_widgets()
method
Guide to Programming with Python 31
Defining a Method to Create the
Widgets
def create_widgets(self):
self.bttn1 = Button(self,
text = "I do nothing!")
self.bttn1.grid()
self.bttn2 = Button(self)
self.bttn2.grid()
self.bttn2.configure(text = "Me too!")
self.bttn3 = Button(self)
self.bttn3.grid()
self.bttn3["text"] = "Same here!"
Guide to Programming with Python 32
Creating the Application Object
# main
root = Tk()
root.title("Lazy Buttons 2")
root.geometry("200x85")
app = Application(root)
root.mainloop()
• Application object created here, not Frame object
• root is still master of object
• root.mainloop() still invoked
lazy_buttons2.py
Guide to Programming with Python 33
Binding Widgets and Event Handlers
• So far, GUI programs haven't had event handlers
• Widgets are like light fixtures without electrical
wiring
• Write event handlers and bind them with events
Guide to Programming with Python 34
The Click Counter Program
Figure 10.10: Sample run of the Click Counter program
Button’s event handler updates number of times button clicked.
Guide to Programming with Python 35
Setting Up the Program
from Tkinter import *
class Application(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.bttn_clicks = 0 # number clicks
self.create_widget()
Guide to Programming with Python 36
Binding the Event Handler
def create_widget(self):
self.bttn = Button(self)
self.bttn["text"]= "Total Clicks: 0"
self.bttn["command"] = self.update_count
self.bttn.grid()
• Set widget’s command option to bind activation of
widget with event handler
• command option bound to update_count() method
• When button clicked, update_count() invoked
Guide to Programming with Python 37
Creating the Event Handler
def update_count(self):
self.bttn_clicks += 1
self.bttn["text"] = "Total Clicks: " +
str(self.bttn_clicks)
• update_count() increments total number of button
clicks and changes text to reflect new total
click_counter.py
Guide to Programming with Python 38
Using Text and Entry Widgets and
the Grid Layout Manager
• Entry widget is good for single line of text
• Text widget is great for multi-line blocks of text
• Can read contents of either
• Can insert text into either
• Grid layout manager lets you place widgets at
specific locations by treating frame as a grid
Guide to Programming with Python 39
The Longevity Program
Figure 10.11: Sample run of the Longevity Program
With incorrect password, program politely refuses to divulge its secret.
Guide to Programming with Python 40
The Longevity Program (continued)
Figure 10.12: Sample run of the Longevity Program
With correct password, program shares its knowledge to long life.
Guide to Programming with Python 41
Placing a Widget with the Grid Layout
Manager
Figure 10.13: Illustrates placement of button widgets
Frame can be seen as a grid of cells at row and column numbers.
Guide to Programming with Python 42
Placing a Widget with the
Grid Layout Manager
def create_widgets(self):
self.inst_lbl = Label(self, text = "Enter
password for the secret of longevity")
self.inst_lbl.grid(row = 0, column = 0,
columnspan = 2, sticky = W)
• grid() method
– row takes integer; defines the row in which the object
is placed (within the widget’s master)
– column takes integer; defines the column in which
the object is placed (within the widget’s master)
– columnspan takes integer; defines width in columns
– sticky takes constants (N, S, E, W); positions
widget at specified edge of cell (centered by default)
Guide to Programming with Python 43
Placing a Widget with the
Grid Layout Manager
# create label for password
self.pw_lbl = Label(self, text = "Password: ")
self.pw_lbl.grid(row = 1, column = 0, sticky = W)
• Creates a label that appears in row 1, left-justified
Guide to Programming with Python 44
Creating an Entry Widget
# create entry widget to accept password
self.pw_ent = Entry(self)
self.pw_ent.grid(row = 1, column = 1, sticky = W)
• Entry widget accepts and displays line of text
Guide to Programming with Python 45
Creating a Button Widget
# create submit button
self.submit_bttn = Button(self, text = "Submit",
command = self.reveal)
self.submit_bttn.grid(row = 2, column = 0,
sticky = W)
• Bind the activation of button with reveal() method
• Place button in next row, left-justified
Guide to Programming with Python 46
Creating a Text Widget
# create text widget to display message
self.secret_txt = Text(self, width = 35,
height = 5, wrap = WORD)
self.secret_txt.grid(row = 3, column = 0,
columnspan = 2, sticky = W)
• wrap parameter determines how text in the box is
wrapped
– WORD wraps entire words
– CHAR wraps characters
– NONE no wrapping (can only write text on the first line)
Guide to Programming with Python 47
Getting and Inserting Text with Text-
Based Widgets
def reveal(self):
""" Display message based on password. """
contents = self.pw_ent.get()
if contents == "secret":
message = "Here's the secret..."
else:
message = "That's not the correct..."
self.secret_txt.delete(0.0, END)
self.secret_txt.insert(0.0, message)
Guide to Programming with Python 48
Getting and Inserting Text with Text-
Based Widgets (continued)
• get() returns text from text-based widget
• delete() deletes text from text-based widget
– Can take single index or beginning and ending point
– Pass floating-point number for row and column
– Tkinter provides constants, such as END
• insert() inserts a string into a text-based widget
– Takes an insertion position and a string
– Pass floating-point number for row and column
longevity.py
Guide to Programming with Python 49
Using Check Buttons
• Check buttons allow user to select any number of
choices from a group
• Provides flexibility for user and control of limiting
choices for programmer
Guide to Programming with Python 50
The Movie Chooser Program
Figure 10.14: Sample run of the Movie Chooser program
The results of the user’s selections show up in the text box.
Guide to Programming with Python 51
Allowing a Widget’s Master to Be Its
Only Reference
def create_widgets(self):
Label(self,
text = "Choose your favorite movie types"
).grid(row = 0, column = 0, sticky = W)
• Label object
– Not assigned to variable
– Can't be directly accessed
– Connected to the program by its master
Guide to Programming with Python 52
Creating Check Buttons
# create Comedy check button
self.likes_comedy = BooleanVar()
• BooleanVar
– Special class from Tkinter module
– Can reflect check button’s status
– Required by Checkbutton object
Guide to Programming with Python 53
Creating Check Buttons (continued)
Checkbutton(self,
text = "Comedy",
variable = self.likes_comedy,
command = self.update_text
).grid(row = 2, column = 0, sticky = W)
• variable takes BooleanVar for status of check button
• command takes function or method to call when
check button is checked or unchecked
Guide to Programming with Python 54
Getting the Status of a Check Button
def update_text(self):
likes = ""
if self.likes_comedy.get():
likes += "You like comedic movies.n"
• BooleanVar
– Can’t access the value directly
– Must invoke object’s get() method
movie_chooser.py
Guide to Programming with Python 55
Using Radio Buttons
• Radio buttons allow user to select one from a
group of choices
• Provides programmer control by limiting range of
choices and allowing only single choice
Guide to Programming with Python 56
The Movie Chooser 2 Program
Figure 10.15: Sample run of the Movie Chooser program
The user can select only a single movie type.
Guide to Programming with Python 57
Creating Radio Buttons
# create variable for single, favorite type
self.favorite = StringVar()
• StringVar
– Special class from Tkinter module
– Can reflect status of a group of radio buttons
– Required by Radiobutton objects
Guide to Programming with Python 58
Creating Radio Buttons (continued)
Radiobutton(self,
text = "Comedy",
variable = self.favorite,
value = "comedy.",
command = self.update_text
).grid(row = 2, column = 0, sticky = W)
• variable parameter gets StringVar self.favorite
• When radio button is selected, StringVar assigned
string referenced by object’s value option
• When Comedy radio button selected, StringVar
self.favorite assigned "comedy."
Guide to Programming with Python 59
Getting a Value from a Group of Radio
Buttons
message = "Your favorite type of movie is "
message += self.favorite.get()
• get() method returns string referenced by the
StringVar that all Radiobutton objects share
• When Comedy radio button selected,
self.favorite.get() returns "comedy "
movie_chooser2.py
Guide to Programming with Python 60
The Mad Lib Program
mad_lib.py
Guide to Programming with Python 61
Summary
• A GUI is a graphical user interface
• A widget, short for window gadget, is a GUI
element
• A master widget contains other widgets
• A layout manager controls the arrangement of
widgets
• An event-driven program responds to actions
regardless of the order in which they occur
• An event is something that happens involving a
program’s objects
Guide to Programming with Python 62
Summary (continued)
• An event handler is code that runs when a specific
event occurs
• To bind is to associate an event with an event
handler
• An event loop checks for events and, based on
them, calls the appropriate event handlers
• Tkinter is a GUI module
• A Label object represents a label widget
• A Frame object represents a frame widget
Guide to Programming with Python 63
Summary (continued)
• A Button object represents a button widget
• An Entry object represents a text entry widget
• A Text object represents a text box widget
• A Checkbutton object represents a check button
widget
• A Radiobutton object represents a radio button
widget

More Related Content

PPTX
GUI Programming using Tkinter-converted.pptx
PDF
GUI In Python.pdf By : Sangeeta M Chauhan , Gwalior
PDF
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
PPTX
ITS-16163-Module 8-Graphic User Interface (GUI)
PPTX
d1c70870-58fb-4da8-ae54-28d1c44a7347.pptx
PPTX
Chapter - 6.pptx
PDF
GUIDE TO PROGRAMMING WITH PYTHON
PDF
A Complete seminar on GUI Development in python
GUI Programming using Tkinter-converted.pptx
GUI In Python.pdf By : Sangeeta M Chauhan , Gwalior
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
ITS-16163-Module 8-Graphic User Interface (GUI)
d1c70870-58fb-4da8-ae54-28d1c44a7347.pptx
Chapter - 6.pptx
GUIDE TO PROGRAMMING WITH PYTHON
A Complete seminar on GUI Development in python

Similar to Python is a high-level, general-purpose programming language. Its design philosophy emphasizes code readability with the use of significant indentation (20)

PDF
Unit 5-Introduction of GUI Programming-Part1.pdf
PPTX
Gui programming
PPTX
Tkinter_GUI_Programming_in_Pythovvn.pptx
PDF
GUI Programming with TKinter and Tkinter Widgets.pdf
PPTX
Introduction to Graphics
PPT
Python Programming
PPT
PYTHON - TKINTER - GUI - PART 1.ppt
PDF
Tkinter_GUI_Programming_in_ Python.pdf
PDF
Tkinter_GUI_Programming_in_Python.pdf
PDF
Python GUI Programming Tkinter and.pdf
PDF
Exploring Python GUI Programming_ Creating User-Friendly Applications
PPTX
PYTHON - EXTRA Chapter GUI - MAULIK BORSANIYA
PPTX
tkinterpptxguipythonImport it is named ‘tkinter
PPTX
Python Graphical User Interface and design
PDF
Programming Python 3rd ed Edition Mark Lutz
PDF
Python - gui programming (tkinter)
PPTX
Introduction to GUIs with guizero
PPTX
Introduction-to-Python-for-better-knowledge-
PPT
Graphical Programming in Python Using Tkinter
PPT
graphical user interface using python easy
Unit 5-Introduction of GUI Programming-Part1.pdf
Gui programming
Tkinter_GUI_Programming_in_Pythovvn.pptx
GUI Programming with TKinter and Tkinter Widgets.pdf
Introduction to Graphics
Python Programming
PYTHON - TKINTER - GUI - PART 1.ppt
Tkinter_GUI_Programming_in_ Python.pdf
Tkinter_GUI_Programming_in_Python.pdf
Python GUI Programming Tkinter and.pdf
Exploring Python GUI Programming_ Creating User-Friendly Applications
PYTHON - EXTRA Chapter GUI - MAULIK BORSANIYA
tkinterpptxguipythonImport it is named ‘tkinter
Python Graphical User Interface and design
Programming Python 3rd ed Edition Mark Lutz
Python - gui programming (tkinter)
Introduction to GUIs with guizero
Introduction-to-Python-for-better-knowledge-
Graphical Programming in Python Using Tkinter
graphical user interface using python easy
Ad

More from bhargavi804095 (20)

PPTX
Reinforcement learning ppt in machine learning.pptx
PPTX
Presentation-lokesh IMAGES for research.pptx
PPT
concept on arrays and pointers with examples arrays-pointers.ppt
PPT
Lec3-coa give sthe information abt instruction set.ppt
PDF
computerregisters during data and address communication.pdf
PPT
Computer forensics and cyber security powerpoint presentation
PPT
chapter1-basic-structure-of-computers.ppt
PPTX
Ch10_The_STACK_and_Subroutines_Slides.pptx
PDF
Pointers are one of the core components of the C programming language.
PPTX
Lec26.pptx An array is a linear data structure
DOCX
08-Pointers.docx An array is a linear data structure
PDF
The Greibach normal form is referred to as GNF gnf1.pdf
PPT
java1.pptjava is programming language, having core and advanced java
PDF
Big Data Analytics is not something which was just invented yesterday!
PPT
Apache Spark™ is a multi-language engine for executing data-S5.ppt
PPTX
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
PPT
A File is a collection of data stored in the secondary memory. So far data wa...
PPTX
C++ helps you to format the I/O operations like determining the number of dig...
PPT
While writing program in any language, you need to use various variables to s...
PPT
cpp-streams.ppt,C++ is the top choice of many programmers for creating powerf...
Reinforcement learning ppt in machine learning.pptx
Presentation-lokesh IMAGES for research.pptx
concept on arrays and pointers with examples arrays-pointers.ppt
Lec3-coa give sthe information abt instruction set.ppt
computerregisters during data and address communication.pdf
Computer forensics and cyber security powerpoint presentation
chapter1-basic-structure-of-computers.ppt
Ch10_The_STACK_and_Subroutines_Slides.pptx
Pointers are one of the core components of the C programming language.
Lec26.pptx An array is a linear data structure
08-Pointers.docx An array is a linear data structure
The Greibach normal form is referred to as GNF gnf1.pdf
java1.pptjava is programming language, having core and advanced java
Big Data Analytics is not something which was just invented yesterday!
Apache Spark™ is a multi-language engine for executing data-S5.ppt
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
A File is a collection of data stored in the secondary memory. So far data wa...
C++ helps you to format the I/O operations like determining the number of dig...
While writing program in any language, you need to use various variables to s...
cpp-streams.ppt,C++ is the top choice of many programmers for creating powerf...
Ad

Recently uploaded (20)

PPTX
Lecture Notes Electrical Wiring System Components
PPTX
Lesson 3_Tessellation.pptx finite Mathematics
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PDF
composite construction of structures.pdf
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PDF
Digital Logic Computer Design lecture notes
DOCX
573137875-Attendance-Management-System-original
PPT
Drone Technology Electronics components_1
PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPT
Mechanical Engineering MATERIALS Selection
PDF
Structs to JSON How Go Powers REST APIs.pdf
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPTX
Construction Project Organization Group 2.pptx
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
Lecture Notes Electrical Wiring System Components
Lesson 3_Tessellation.pptx finite Mathematics
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
composite construction of structures.pdf
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Operating System & Kernel Study Guide-1 - converted.pdf
Digital Logic Computer Design lecture notes
573137875-Attendance-Management-System-original
Drone Technology Electronics components_1
Arduino robotics embedded978-1-4302-3184-4.pdf
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Mechanical Engineering MATERIALS Selection
Structs to JSON How Go Powers REST APIs.pdf
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Construction Project Organization Group 2.pptx
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
bas. eng. economics group 4 presentation 1.pptx
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...

Python is a high-level, general-purpose programming language. Its design philosophy emphasizes code readability with the use of significant indentation

  • 2. Guide to Programming with Python 2 Objectives • Work with a GUI toolkit • Create and fill frames • Create and use buttons • Create and use text entries and text boxes • Create and use check buttons • Create and use radio buttons
  • 3. Guide to Programming with Python 3 The Mad Lib Program Figure 10.1: Sample run of the Mad Lib program A nicely laid-out GUI awaits the user’s creativity.
  • 4. Guide to Programming with Python 4 The Mad Lib Program (continued) Figure 10.2: Sample run of the Mad Lib program The user has entered all of the necessary information.
  • 5. Guide to Programming with Python 5 The Mad Lib Program (continued) Figure 10.3: Sample run of the Mad Lib program After clicking Click for story button, text box displays masterpiece.
  • 6. Guide to Programming with Python 6 Examining A GUI Figure 10.4: Examining a GUI You’ll learn to create all of these GUI elements.
  • 7. Guide to Programming with Python 7 Examining A GUI (continued) Table 10.1: Selected GUI Elements
  • 8. Guide to Programming with Python 8 Understanding Event-Driven Programming • Event-driven program: A program that responds to actions regardless of the order in which they occur • Event: Something that happens involving a program's objects • Event handler: Code that runs when a specific event occurs • Bind: To associate an event with an event handler • Event loop: A loop that checks for events and calls appropriate event handlers when they occur
  • 9. Guide to Programming with Python 9 Understanding Event-Driven Programming (continued) • GUI programs traditionally event-driven • Mad Lib without event-driven programming – Ask series of questions with raw_input() function – Ask for name of a person, plural noun... – User must provide each piece of information, in order • Mad Lib with event-driven programming – Can use a GUI – User can enter the information in any order
  • 10. Guide to Programming with Python 10 Using A Root Window • Root Window – Foundation of GUI program – Foundation upon which to add all other GUI elements – Like root of tree, anchors all other parts
  • 11. Guide to Programming with Python 11 The Simple GUI Program Figure 10.5: Sample run of the Simple GUI program The program creates only a lone window. simple_gui.py
  • 12. Guide to Programming with Python 12 The Simple GUI Program (continued) • GUI programs can generate console window too • Console window helpful to see error messages • On Windows machine can suppress console window by changing program extension from py to pyw
  • 13. Guide to Programming with Python 13 Importing the Tkinter Module from Tkinter import * • Tkinter is a GUI module • Imports all Tkinter into global scope • Normally, avoid this kind of import • Some modules designed to be imported this way • Saves typing and makes for cleaner code
  • 14. Guide to Programming with Python 14 Creating a Root Window root = Tk() • To create a root window, instantiate object of the Tkinter class Tk • Because of from Tkinter import *, no need to prefix the module name
  • 15. Guide to Programming with Python 15 Modifying a Root Window root.title("Simple GUI") root.geometry("200x100") • title() – Sets title of root window – Takes string • geometry() – Sets size of the root window – Takes string (not integers) for window’s width and height, separated by the "x" character
  • 16. Guide to Programming with Python 16 Entering a Root Window’s Event Loop root.mainloop() • Root window's event loop entered • Window stays open, waiting to handle events
  • 17. Guide to Programming with Python 17 Using Labels • Widget: GUI elements (short for "window gadget") • Label widget – Uneditable text or icons (or both) – Often used to label other widgets – Unlike most other widgets, labels aren’t interactive
  • 18. Guide to Programming with Python 18 The Labeler Program Figure 10.7: Sample run of the Labeler program A label can provide information about a GUI. labeler.py
  • 19. Guide to Programming with Python 19 Creating a Frame app = Frame(root) • Master: A widget that contains other widgets • Layout Manager: Controls arrangement of widgets • Frame is widget that can hold other widgets • When creating widget, must pass its master to constructor of new object • Here, root is master that contains app
  • 20. Guide to Programming with Python 20 Creating a Frame (continued) app.grid() • grid() – Method that all widgets have – Associated with grid layout manager – Can be used to create desired layout of widgets
  • 21. Guide to Programming with Python 21 Creating a Label lbl = Label(app, text = "I'm a label!") lbl.grid() • Label Class – For a label widget – Master is first argument passed to constructor – text parameter for widget's text – grid() method invoked ensures widget visible (places widget at a default location in frame if called with no arguments)
  • 22. Guide to Programming with Python 22 Using Buttons • Button widget – Is a button in GUI – Can be activated by user to perform some action
  • 23. Guide to Programming with Python 23 The Lazy Buttons Program Figure 10.8: Sample run of the Lazy Buttons program You can click these lazy buttons all you want; they won’t do a thing. lazy_buttons.py
  • 24. Guide to Programming with Python 24 Creating Buttons bttn1 = Button(app, text = "I do nothing!") bttn1.grid() • Button Class – For a button widget – Master is first argument passed to constructor – text parameter for widget's text – grid() method invoked ensures widget visible
  • 25. Guide to Programming with Python 25 Creating Buttons (continued) bttn2 = Button(app) bttn2.grid() bttn2.configure(text = "Me too!") • Can add blank button to the frame • configure() method sets or changes widget options – Useful for changing widget after it has been instantiated
  • 26. Guide to Programming with Python 26 Creating Buttons (continued) bttn3 = Button(app) bttn3.grid() bttn3["text"] = "Same here!" • Can access widget's options through dictionary-like interface • Key for option is name of the option as a string • Here, set third button's text option to "Same here!” • Useful for changing widget after it has been instantiated (like .config())
  • 27. Guide to Programming with Python 27 Creating a GUI Using a Class • Organizing code into classes can make programming easier • Often beneficial to write larger GUI programs in OOP style
  • 28. Guide to Programming with Python 28 The Lazy Buttons 2 Program Figure 10.9: Sample run of the Lazy Buttons 2 program Program appears the same but significant changes under the hood.
  • 29. Guide to Programming with Python 29 Defining the Application Class class Application(Frame): """ A GUI application with three buttons. """ def __init__(self, master): • Instead of instantiating Frame object, will instantiate Application object • Application object becomes just a specialized type of Frame object • master will be the Tk window that the frame belongs to (root in all our examples so far)
  • 30. Guide to Programming with Python 30 Defining a Constructor Method def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() • Frame constructor called first – This is what is used instead of super() for old object classes • Pass Application object’s master, so it gets properly set as master • Invoke Application object’s create_widgets() method
  • 31. Guide to Programming with Python 31 Defining a Method to Create the Widgets def create_widgets(self): self.bttn1 = Button(self, text = "I do nothing!") self.bttn1.grid() self.bttn2 = Button(self) self.bttn2.grid() self.bttn2.configure(text = "Me too!") self.bttn3 = Button(self) self.bttn3.grid() self.bttn3["text"] = "Same here!"
  • 32. Guide to Programming with Python 32 Creating the Application Object # main root = Tk() root.title("Lazy Buttons 2") root.geometry("200x85") app = Application(root) root.mainloop() • Application object created here, not Frame object • root is still master of object • root.mainloop() still invoked lazy_buttons2.py
  • 33. Guide to Programming with Python 33 Binding Widgets and Event Handlers • So far, GUI programs haven't had event handlers • Widgets are like light fixtures without electrical wiring • Write event handlers and bind them with events
  • 34. Guide to Programming with Python 34 The Click Counter Program Figure 10.10: Sample run of the Click Counter program Button’s event handler updates number of times button clicked.
  • 35. Guide to Programming with Python 35 Setting Up the Program from Tkinter import * class Application(Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.bttn_clicks = 0 # number clicks self.create_widget()
  • 36. Guide to Programming with Python 36 Binding the Event Handler def create_widget(self): self.bttn = Button(self) self.bttn["text"]= "Total Clicks: 0" self.bttn["command"] = self.update_count self.bttn.grid() • Set widget’s command option to bind activation of widget with event handler • command option bound to update_count() method • When button clicked, update_count() invoked
  • 37. Guide to Programming with Python 37 Creating the Event Handler def update_count(self): self.bttn_clicks += 1 self.bttn["text"] = "Total Clicks: " + str(self.bttn_clicks) • update_count() increments total number of button clicks and changes text to reflect new total click_counter.py
  • 38. Guide to Programming with Python 38 Using Text and Entry Widgets and the Grid Layout Manager • Entry widget is good for single line of text • Text widget is great for multi-line blocks of text • Can read contents of either • Can insert text into either • Grid layout manager lets you place widgets at specific locations by treating frame as a grid
  • 39. Guide to Programming with Python 39 The Longevity Program Figure 10.11: Sample run of the Longevity Program With incorrect password, program politely refuses to divulge its secret.
  • 40. Guide to Programming with Python 40 The Longevity Program (continued) Figure 10.12: Sample run of the Longevity Program With correct password, program shares its knowledge to long life.
  • 41. Guide to Programming with Python 41 Placing a Widget with the Grid Layout Manager Figure 10.13: Illustrates placement of button widgets Frame can be seen as a grid of cells at row and column numbers.
  • 42. Guide to Programming with Python 42 Placing a Widget with the Grid Layout Manager def create_widgets(self): self.inst_lbl = Label(self, text = "Enter password for the secret of longevity") self.inst_lbl.grid(row = 0, column = 0, columnspan = 2, sticky = W) • grid() method – row takes integer; defines the row in which the object is placed (within the widget’s master) – column takes integer; defines the column in which the object is placed (within the widget’s master) – columnspan takes integer; defines width in columns – sticky takes constants (N, S, E, W); positions widget at specified edge of cell (centered by default)
  • 43. Guide to Programming with Python 43 Placing a Widget with the Grid Layout Manager # create label for password self.pw_lbl = Label(self, text = "Password: ") self.pw_lbl.grid(row = 1, column = 0, sticky = W) • Creates a label that appears in row 1, left-justified
  • 44. Guide to Programming with Python 44 Creating an Entry Widget # create entry widget to accept password self.pw_ent = Entry(self) self.pw_ent.grid(row = 1, column = 1, sticky = W) • Entry widget accepts and displays line of text
  • 45. Guide to Programming with Python 45 Creating a Button Widget # create submit button self.submit_bttn = Button(self, text = "Submit", command = self.reveal) self.submit_bttn.grid(row = 2, column = 0, sticky = W) • Bind the activation of button with reveal() method • Place button in next row, left-justified
  • 46. Guide to Programming with Python 46 Creating a Text Widget # create text widget to display message self.secret_txt = Text(self, width = 35, height = 5, wrap = WORD) self.secret_txt.grid(row = 3, column = 0, columnspan = 2, sticky = W) • wrap parameter determines how text in the box is wrapped – WORD wraps entire words – CHAR wraps characters – NONE no wrapping (can only write text on the first line)
  • 47. Guide to Programming with Python 47 Getting and Inserting Text with Text- Based Widgets def reveal(self): """ Display message based on password. """ contents = self.pw_ent.get() if contents == "secret": message = "Here's the secret..." else: message = "That's not the correct..." self.secret_txt.delete(0.0, END) self.secret_txt.insert(0.0, message)
  • 48. Guide to Programming with Python 48 Getting and Inserting Text with Text- Based Widgets (continued) • get() returns text from text-based widget • delete() deletes text from text-based widget – Can take single index or beginning and ending point – Pass floating-point number for row and column – Tkinter provides constants, such as END • insert() inserts a string into a text-based widget – Takes an insertion position and a string – Pass floating-point number for row and column longevity.py
  • 49. Guide to Programming with Python 49 Using Check Buttons • Check buttons allow user to select any number of choices from a group • Provides flexibility for user and control of limiting choices for programmer
  • 50. Guide to Programming with Python 50 The Movie Chooser Program Figure 10.14: Sample run of the Movie Chooser program The results of the user’s selections show up in the text box.
  • 51. Guide to Programming with Python 51 Allowing a Widget’s Master to Be Its Only Reference def create_widgets(self): Label(self, text = "Choose your favorite movie types" ).grid(row = 0, column = 0, sticky = W) • Label object – Not assigned to variable – Can't be directly accessed – Connected to the program by its master
  • 52. Guide to Programming with Python 52 Creating Check Buttons # create Comedy check button self.likes_comedy = BooleanVar() • BooleanVar – Special class from Tkinter module – Can reflect check button’s status – Required by Checkbutton object
  • 53. Guide to Programming with Python 53 Creating Check Buttons (continued) Checkbutton(self, text = "Comedy", variable = self.likes_comedy, command = self.update_text ).grid(row = 2, column = 0, sticky = W) • variable takes BooleanVar for status of check button • command takes function or method to call when check button is checked or unchecked
  • 54. Guide to Programming with Python 54 Getting the Status of a Check Button def update_text(self): likes = "" if self.likes_comedy.get(): likes += "You like comedic movies.n" • BooleanVar – Can’t access the value directly – Must invoke object’s get() method movie_chooser.py
  • 55. Guide to Programming with Python 55 Using Radio Buttons • Radio buttons allow user to select one from a group of choices • Provides programmer control by limiting range of choices and allowing only single choice
  • 56. Guide to Programming with Python 56 The Movie Chooser 2 Program Figure 10.15: Sample run of the Movie Chooser program The user can select only a single movie type.
  • 57. Guide to Programming with Python 57 Creating Radio Buttons # create variable for single, favorite type self.favorite = StringVar() • StringVar – Special class from Tkinter module – Can reflect status of a group of radio buttons – Required by Radiobutton objects
  • 58. Guide to Programming with Python 58 Creating Radio Buttons (continued) Radiobutton(self, text = "Comedy", variable = self.favorite, value = "comedy.", command = self.update_text ).grid(row = 2, column = 0, sticky = W) • variable parameter gets StringVar self.favorite • When radio button is selected, StringVar assigned string referenced by object’s value option • When Comedy radio button selected, StringVar self.favorite assigned "comedy."
  • 59. Guide to Programming with Python 59 Getting a Value from a Group of Radio Buttons message = "Your favorite type of movie is " message += self.favorite.get() • get() method returns string referenced by the StringVar that all Radiobutton objects share • When Comedy radio button selected, self.favorite.get() returns "comedy " movie_chooser2.py
  • 60. Guide to Programming with Python 60 The Mad Lib Program mad_lib.py
  • 61. Guide to Programming with Python 61 Summary • A GUI is a graphical user interface • A widget, short for window gadget, is a GUI element • A master widget contains other widgets • A layout manager controls the arrangement of widgets • An event-driven program responds to actions regardless of the order in which they occur • An event is something that happens involving a program’s objects
  • 62. Guide to Programming with Python 62 Summary (continued) • An event handler is code that runs when a specific event occurs • To bind is to associate an event with an event handler • An event loop checks for events and, based on them, calls the appropriate event handlers • Tkinter is a GUI module • A Label object represents a label widget • A Frame object represents a frame widget
  • 63. Guide to Programming with Python 63 Summary (continued) • A Button object represents a button widget • An Entry object represents a text entry widget • A Text object represents a text box widget • A Checkbutton object represents a check button widget • A Radiobutton object represents a radio button widget