T eaching L C
ondon omputing
A Level Computer Science
Programming GUI in Python
William Marsh
School of Electronic Engineering and Computer Science
Queen Mary University of London
Outline
• A first program
• Concepts in Graphical User Interface
• Components / widgets and attributes
• Events / actions
• Layout
• Practical examples
• Challenges of GUI programming
• Choosing a GUI library
• Using Object-Oriented programming
First Program – Click the Button
• Code provided but not yet explained
• Use ‘pattern matching’ (i.e. intelligent guessing)
to modify it
Key Concepts
Explained Using the Button Example
Key Concepts
• A widget / component
• E.g. a button, a frame
• Attributes e.g. the button text
• Actions
• E.g. what happens when you press the button
• Layout
• Positioning widgets
AppInventor
Code for
events Hierarchy of
components
Widgets,
called Attributes
components called
properties
Widgets
• A GUI is made up frame
from widgets
• A widget is created button
• Widget has attributes
• One widget may contain
another:
• Frame contains the button
Create a Widget
• Constructor # Create a main frame with
• Name same as widget # - a title
# - size 200 by 200 pixels
• Hierarchy of widget app = Tk()
app.title("GUI Example 1")
• Optional arguments app.geometry('200x200')
Constructor
Optional
Parent
argument
widget
# Create the button
# - with suitable text
# - a command to call when the button is pressed
button1 = Button(app, text="Click Here", command=clicked)
Widgets have Attributes
• E.g. a name, size # Create a main frame with
# - a title
• Any property of the # - size 200 by 200 pixels
widget that makes it app = Tk()
app.title("GUI Example 1")
specific app.geometry('200x200')
Attributes set by
Methods to
constructor (note use of
set attributes
keyword arguments)
# Create the button
# - with suitable text
# - a command to call when the button is pressed
button1 = Button(app, text="Click Here", command=clicked)
How to Set / Get an Attribute
• Method 1 (setting):
• Set value with the constructor
• Method 2 (setting and getting):
• Widget is a dictionary
# Change button text
mText = button1['text']
button1['text'] = mText.upper()
• Method 3 (sometimes) Other
• Call a suitable method methods exist
Aside: Dictionaries
• Dictionary: a map from a key to a value
• Unique key
• Built in (Python) versus library (many other languages)
Standard Array Python Dictionary
Index by number Key can be a string, pair, …
Indices continuous e.g. 0 à 10 Gaps ok
Holds only number, character Any value – even a dictionary
# Change button text Lookup
mText = button1['text']
button1['text'] = mText.upper() Update
Handle an Event
# This method is called when the button is pressed
def clicked():
print("Clicked")
# Create the button with
# - a command to call when the button is pressed
button1 = Button(app, text="Click Here", command=clicked)
• Events
• Button, mouse click, key press Name of a
Method
• Action
• Event ‘bound’ to function
Layout the Widget
# Make the button visible at the bottom of the frame
button1.pack(side='bottom')
• Where does the widget go?
• Hierarchy
• Top-level window
• Layout manager
• Several available
• Problem of resizing
• The ‘pack’ layout manager is simplest
• Widget is not visible until packed
A Minimal Application
# Import the Tkinter package
# Note in Python 3 it is all lowercase
from tkinter import *
# Create a main frame import with
app = Tk() prefix
# Start the application running
app.mainloop() # Import the Tkinter package
# Note in Python 3 it is all lowercase
import tkinter as tk
Loop to # Create a main frame
handle events app = tk.Tk()
# Start the application running
app.mainloop()
(Some) tkinter Widgets
Widget Use
Button A button
Canvas For drawing graphics
Entry Entry a line of text
Frame A rectangular area containing other widgets
Label Display a single line of text
Menu A set of options shown when on a menu bar
Radiobutton Select one of a number of choices
Scrollbar Horizontal or vertical scrolling of a window
Text A multi-line text entry
Toplevel A top-level frame
Further Practical Exercises
• See practical sheet
• A sequence of exercises introduce other
widgets and apply the core concepts
• Answers included
• … probably too many to finish now
Further Concepts
• Dialog
• Top-level window
• Control variables
Dialogs
• You must respond to a dialog
• Messages
• File choosing
Top-Level Windows
• At least one top-level window
• Conveniently created using Tk()!
• Like a frame but …
• Menu bar
• Standard buttons
• Borders
Control Variables
• Variables linking …
• Entry widget to its text
• Choices in a RadioButton
• These are objects in the framework
Challenges in GUI
• Which framework?
• How to design a GUI
• How much OOP?
GUI Framework
• A GUI framework defines a set of widgets
• Windows has it’s own GUI framework
• Python uses a portable GUI framework
• tkinter, depends on Tk and TCL
• PyQT, depends on QT
• Tkinter
• Pro: simple, easy to install
• Cons: a bit limited; documentation weak
• PyQT: more complex
Designing a GUI
• What am I trying to do?
• What widgets do I need?
• Where will they go?
• How do they behave?
screen. Later we will talk about how to connect the face—the “front panel”—of the ap
logic behind it.
The OOP Problem
2. A minimal application
Here is a trivial Tkinter program containing only a Quit button:
#!/usr/bin/env python 1
• Why OO and GUI import Tkinter as tk 2
3
• Widgets are classes class Application(tk.Frame):
def __init__(self, master=None):
4
• Default behaviour tk.Frame.__init__(self, master)
self.grid() 5
self.createWidgets()
• GUI programs are
def createWidgets(self):
often organised self.quitButton = tk.Button(self, text='Quit',
command=self.quit) 6
using classes self.quitButton.grid() 7
app = Application() 8
app.master.title('Sample application') 9
app.mainloop() 10
• Practical Problem: most
1
2
This line makes the script self-executing, assuming that your system has Python co
examples use OOP
This line imports the Tkinter module into your program's namespace, but rename
3 Your application class must inherit from Tkinter's Frame class.
4 Calls the constructor for the parent class, Frame.
5 Necessary to make the application actually appear on the screen.
6 Creates a button labeled “Quit”.
7 Places the button on the application.
8 The main program starts here by instantiating the Application class.
Summary
• Core concepts common to all framework
• Understand principles
• Learn about available widgets
• Look up attributes and methods
• After programming … interface design