0% found this document useful (0 votes)
0 views44 pages

Computer basic knowledge

This document provides an overview of GUI programming using the tkinter module in Python. It covers the basics of GUI programs, the creation and layout of GUI widgets, and includes practical tasks for building interactive applications. The document emphasizes the importance of event handling and layout management methods such as pack() and grid() for effective GUI design.
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)
0 views44 pages

Computer basic knowledge

This document provides an overview of GUI programming using the tkinter module in Python. It covers the basics of GUI programs, the creation and layout of GUI widgets, and includes practical tasks for building interactive applications. The document emphasizes the importance of event handling and layout management methods such as pack() and grid() for effective GUI design.
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/ 44

(Teacher’s Version)

PA05 Unit4
GUI Programming
with tkinter
4.1 About GUI Programs

4.2 GUI Programming with the t k i n t e r Module

4.3 Creation, Setting and p a c k ( ) Layout of GUI


Widgets

4.4 g r i d ( ) Layout of GUI Widgets


Content
s Learning Objectives
4.1 1. About GUI programs.

4.2 2. GUI Programming With the t k i n t e r Module.

4.3 3 . Creation, Setting and p a c k ( ) Layout of GUI Widgets

4.4 4. g r i d ( ) Layout of GUI Widgets

Practice 1. Consolidation 2. Practical exercise 3. Enrichment


Zone
Contents
Now I’ve learned the
basics of Python
programming for
automatic execution of
some Arduino projects. You can create graphical
How can I write a use rinterface (GUI)
program for simple, real programs with Python.
- time interactions These programs enable
between the user and the user to interact with
the project? an Arduino project in a
real-time manner, such
as hardware on/off
control and adjusting
control values.
Contents
4.1 About GUI programs
• In terms of the operating method, computer programs fall into
two types: command line interface (CLI) programs and
命令行界面interface (GUI) ones.
graphical user 圖形用户界面

• Early computer programs are all CLI ones, which only allow
input of commands from the keyboard to be executed by the
computer.

• CLI is also known as CUI (character user interface). An example is the Python Shell.

• GUI programs have not been developed until the 1980s.


Nowadays, most programs we use in our daily life (computer
software or mobile apps) are predominantly GUI ones which
contain an interface made up of various image elements that
enable real-time interaction between the user and the
program.
• Some image elements in a GUI program serve to display a real-time message or value while some
others (e.g. buttons, slides) allow the user to instruct the program to do specific tasks through an
event trigger by, say, pressing a button or dragging a slider.
Contents
1. Figure 4.1 shows a GUI of an audio recorder app. How many image elements
is it made up of? What is the function of each image element?

_____________________________________
A total of four image elements for: (1) a real-
_____________________________________
time display of the volume level, (2) a real-
_____________________________________
time display of the recording duration, (3)
_____________________________________
pausing the recording when pressed, and (4)
_____________________________________
ending the recording when pressed.
4.1

• Think: Which image elements in the interface display a real-time message or value? Which
ones allow the user to trigger an event?
Contents
4.2 GUI Programming with the
tkinter Module
tkinter is a module in the Python Standard Library that enables GUI
programming across different platforms (e.g. Windows, Mac OS) using Python
code. Tk is an open-source and cross-platform widget library, whereas tkinter
部件
is the Python’s interface to Tk which makes GUI widgets available to GUI
programs.

tkinter (pronounced as tee-kay-inter) is short for “Tk interface”.

The advantages of GUI programming with the tkinter module lies in its
simplicity for learning, conciseness of its code and its beginner-friendliness.

tkinter is the most popular tool for Python GUI programming. Two other popular tools are JPython
and wxPython.
Contents
Four steps are involved in creating a tkinter GUI program:

1. Import the tkinter module. e.g. “import tkinter as tk”;

2. Create the GUI main window object with the Tk() method and assign it to a
variable. e.g. “root=tk.Tk()”;

• Assigning tkinter to the variable tk simplifies the program for easy maintenance.

3. Create GUI widgets and arrange their layout in the main window and set
up each widget;

4. Run the mainloop() method (e.g. “root.mainloop()”) for the main window.
The method generates an infinite loop in which the program keeps waiting
for any event from the user to be responded by refreshing the related
widget(s). The loop only terminates when the user closes the main window.

• Example of an event from the user and refreshing of the related widget(s): Once the user clicks
a text input box (event trigger), text input to it is made ready instantly. Any input text is
instantly shown in the box (refreshing the widget).
Contents
 Task 1: Creating a blank GUI program

Create the following program, save it as “u4_task1.py” and run it.

4.2
A GUI program created with the
tkinter module must at least
Draw the GUI that appears in the box below. include Steps 1, 2 and 4 above.

Common methods for main


window (root) setup:
1. root.title(string) Setting the title
of root to a string
2. root.minsize(w,h)
Setting the width and height of root
to w and h pixels respectively.
3. root.resizable(0,0)
4.3 Fixing the width and height of root
Note: each setup command above
must be placed before the
root.mainloop() command.
Contents
4.3 Creation, Setting and
p ack() Layout of GUI Widgets
類別
An object in a Python program belong to a class. In a GUI program, each GUI
widget is an object belonging to a widget class. Below are three common GUI
widget classes in tkinter, with their descriptions:

1. Button: A button that triggers an event when pressed

2. Entry: A single-line text input box

3. Label: A label that displays a single line of text or an image

Creating a GUI widget means creating an object of a GUI widget class.

Other common GUI widget classes in the tkinter module include Frame (container), Message
(message box), Scale (slider) and Text (multiple-line text input box).
Contents
For example, to create an object of the Label class, label_1, in
the main window root, the command we need is (Suppose the
variable tk denotes the imported tkinter module):
label_1=tk.Label(root)
Common parameters of a Label object:
We may define parameters of an object being created. For bg background colour
example, to create the above object label_1 and define its text fg text colour
and background colour parameters as “Hello!” and red text displayed text
width width in characters
respectively, use the command: borderwidth border thickness
label_1=tk.Label(root,text='Hello!',bg= 'red') relief border style

To change the value of a parameter of an existing object, we Common parameters of a Button


object:
can use the config() method. For example, to change the text text displayed text
colour of the object label_1 to blue, use the command: command the function called when
label_1.config(fg='blue') pressing it

The location of each created GUI object (object) in the main


windows must be specified by a layout management method. Common parameters of an Entry
A common layout management command is: object:
object.pack() - width width in characters
- If no layout management command is
used after GUI objects are created, the
A pack() method that omits parameters denotes a top-down, objects will not appear in the GUI.
centre-aligned layout arrangement of objects.
Contents
Below is a program with three GUI objects and its execution result.

4.4
Figure 4.4 shows a trial program that only serves to display the code for the
creation of three common types of GUI widgets (Button, Entry and Label)
provided by tkinter and the code for their simple setup and layout with its
execution result. Otherwise it has no practical use. Besides, the program has not
defined a function to handle the “Press” event for the Button widget. It also
involved no interaction between text input to the Entry widget and the program,
and no complex widget layout (e.g. left-to-right layout).

In the following tasks and exercises, by writing some simple and practical
programs, we will learn interactive programming with Button and Entry widgets
as well as the creation of more complex widget layouts.
 Task 2: Testing a weight unit converter GUI program
Contents
Create the following kilogram-to-pound converter GUI program, save it
as “u4_task2.py” and run it. Test it with different input values.

4.5

• 1 kg = 2.2 lb
• The command parameter of button_1 is defined to call Convert() when the button is pressed. Note:
the value of the command is a function name without brackets.
• The get() method obtains the user’s input value (string data) through the Entry object.
• float() converts the string to a floating-point number.
• round(number,n) converts a numerical value (number) into a floating-point number of n decimal
places.
• The config() method of label_2 changes the value of the text parameter to display the numerical
value output of the converter.
Contents
Draw the GUI (initial appearance, testing appearance) that appears in
the box below.

Initial appearance Testing appearance

4.6a 4.6b
Contents
 Task 3: Completing and testing a colour selector GUI program
Add in the missing code in the following colour
selector GUI program which displays the colour as Hint: Define three functions that
selected by the user. Save the program as “u4_ change the background colour of
task3.py”. Then run and test it. the Label object to 'red', 'blue'
and 'green' respectively.
import tkinter as tk
root=tk.Tk() Common parameters of pack():
root.title('Colour Selector') fill horizontal filling ('x') or
root.minsize(280,100) vertical filling ('y')
root.resizable(0,0) padx horizontal padding
(default: 0 px)
pady vertical padding
(default: 0 px)
side layout relationship with the
next object ('left': left to
label_1=tk.Label(root,width=20) right;
button_1=tk.Button(root,text='Red',command=R 'top': top to bottom [default])
ed)
button_2=tk.Button(root,text='Blue',command=
Blue)
button_3=tk.Button(root,text='Green',command
=Green)
label_1.pack(fill='y',side='left')
button_1.pack(fill='x',padx=5,pady=5) 4.7 Execution result of “u4_task3.py”
button_2.pack(fill='x',padx=5,pady=5)
Contents
2. Figure 4.8 shows the graphical output of a trigonometry calculator GUI
program in execution. The layout management portion of the program is
shown below. Add in the missing code.

label_angle.pack ()
fill='x'
angleEntry.pack ( __________ )
padx
bt_sin.pack ( __________ =5,side='left')
padx
bt_cos.pack ( __________ =5,side='left')
padx
label_ans.pack ( __________ =5,side='left')
4.8
Contents
 Task 4: Completing and testing an LED on/off controller GUI
program

Complete the following LED on/off controller GUI program (cf. Task 8 of Unit
1, p.16, Figure 1.17). This program generates a main window with a label
and two buttons. The label is for displaying the LED status as “LED On” or
“LED Off”. The two buttons “On” and “Off” are for LED on/off control.
Pressing the “On” button generates white text against red background on
the label. By pressing the “Off” button again, red text against white
background will reappear on the label. (Figure 4.9)

4.9
import tkinter as tk
import pyfirmata
Contents
from time import sleep

comport="COM6"
board=pyfirmata.Arduino(comport)
LED=board.get_pin('d:6:o')

root=tk.Tk()
root.title('LED Control GUI')
root.minsize(300,100)
root.resizable(0,0)

label_1=tk.Label(root,text='LED Off',bg='white',fg='black')
Hint: Define two functions so
that pressing different buttons
results in different words and
text/background colour pairs on
the label and use the write()
method to turn on or turn off
bt_on=tk.Button(root,text='On',command=clickOn) the LED.
bt_off=tk.Button(root,text='Off',command=clickOff)

label_1.pack()
Hint: Arrange the two buttons
from left to right with 5 px
padding.
Save the program as “u4_task4.py”. Then run and test
Contents
4.4 g rid ( ) Layout of GUI Widgets
The pack() layout management method is suitable for simple layouts like
horizontal and vertical arrangements of objects, the default layout being
top-to-bottom and centre-aligned. Another method, grid(), is preferable
for more complex layouts, as it precisely arranges objects in a grid made
up of rows and columns.

In addition to pack() and grid(), there is a layout management method, place(), that arranges
widgets by their exact x,y coordinates, such as:
label0.place(x=20,y=30)
Contents
3. Figure 4.10 shows a GUI program using the grid() layout management
method and its execution result. By relating the two, write down the
descriptions for the value assignments of grid() parameters in the program.

4.10

(a) row=0 first row


_______________________ Meaning of other sticky parameters
second column 'w' left-aligned
(b) column=1 two rows spanned
_______________________ 'e' right-aligned
'n' top-aligned
(c) rowspan=2 _______________________
horizontal fill 's' bottom-aligned
(d) sticky='w'+'e' _______________________
2px vertical padding 'n'+'s' vertical fill
(e) pady=2 _______________________
Contents
4. Figure 4.11 shows a GUI for
controlling the servo arm rotation
angle and LED brightness. The
program̓s layout management
section is in the following. Add in the
missing code.
4.11

label_angle.grid( row=0,column=0,sticky='w' )
angleEntry.grid( row=1,column=0,sticky='w' )
bt_set.grid( row=1,column=1 )
label_brightness.grid( row=2,column=0,columnspan=2, • This label has a long
sticky='w' ) character length. So
columnspan is used
brightness_Scale.grid( row=3,column=0,sticky='w' ) to merge two cells.
5. Referring to the previous question, below is another section of
the program. Add in the missing code.
Contents
root=tk.Tk()
'Arduino GUI'
root.title( _________________________ )
root.minsize(300,100)
root.resizable(0,0)

def set_servo():
angleEntry.get()
angle= _________________________ • The user-input value is obtained through
angle=float(angle) the object angleEntry. The float() function
servo.write(angle) converts the string into a floating-point
sleep(1) number.

• The Scale object passes the value to the


updateValue
def _________________________ (val):
parameter val. Then the float() function
led_brightness=float(val) converts the string to a floating-point
pLED.write(led_brightness/100.0) number.
• led_brightness is divided by 100, as the
label_angle=tk.Label(root, parameter value of the write() function
'Input angle of servo 0-180: '
text= ____________________________ ) must fall between 0 and 1.

angleEntry=tk.Entry(root, width=20)
Common parameters of a Scale object:
text='SET', command=set_servo )
bt_set=tk.Button(root, _____________________________ from initial slider value
to value of another slider end*
(*horizontally: rightward
label_brightness=tk.Label(root,
vertically: downward)
text= __________________________________
'Adjust the brightness of LED with slide.' ) orient slider orientation
(default:'vertical')
brightness_Scale=tk.Scale(root,from_=0,to=100, command the event handler function to be
orient='horizontal',command=updateValue) called whenever the slider is moved
Contents
6. Modify the layout management section of the GUI program in Activity
Window 2 (p.42) by replacing the pack() method with the grid() method to
generate the GUI as shown in Figure 4.12. Add in the missing code.

4.12

row=0,column=0
label_angle.grid( _________________________ )
angleEntry.grid(row=0,column=1)
row=1,column=0,sticky='e'
bt_sin.grid( ___________________________________ )
row=2,column=0,sticky='e'
bt_cos.grid( ___________________________________ )
label_ans.grid(padx=2, _____________________________
row=1,column=1,rowspan=2,
sticky='w')
Contents
7. Modify the layout management section of the GUI program in Task 3
(p.42) by replacing the pack() method with the grid() method to
generate a similar GUI (Figure 4.13). Add in the missing code.

4.13

label_1=tk.Label(root,width=20)
button_1=tk.Button(root,text='Red',command=Red)
button_2=tk.Button(root,text='Blue',command=Blue)
button_3=tk.Button(root,text='Green',command=Green)
label_1.grid( row=0,column=0,rowspan=3,sticky='n'+'s' )
button_1.grid(padx=5,pady=5, row=0,column=1,sticky='w' )
button_2.grid(padx=5,pady=5, row=1,column=1,sticky='w' )
button_3.grid(padx=5,pady=5, row=2,column=1,sticky='w' )
Contents
About GUI Programs
1. In terms of the operating method, computer programs fall into
two types:
command line interface (CLI) programs and graphical user
interface
(GUI) ones.

GUI Programming with tkinter Module


2. tkinter is a module in the Python Standard Library as Python’s
interface
to Tk which makes GUI widgets available to GUI programs.
Contents
Creation, Setting and pack () Layout of GUI
Widgets
3. Four steps are involved in creating a tkinter GUI program:
(a) Import the tkinter module;
(b) Create the GUI main window object with the Tk() method and
assign
it to a variable;
(c) Create GUI widgets and arrange their layout in the main
window and
set up each widget;
(d) Run the mainloop() method for the main window.

4. In a GUI program, each GUI widget is an object belonging to a


widget
class.

5. Button, Entry and Label are three common GUI widget classes in
tkinter.

6. We may define parameters of an object being created.


Contents
7. To change the value of a parameter of an existing object, we
can use
the config() method.

8. The location of each created GUI object in the main windows


must be
specified by a layout management method.

9. A pack() method that omits parameters denotes a top-down,


centre-
aligned layout arrangement of objects.

10. Common parameters of the pack() method include fill, padx,


pady
and side.
Contents
grid () Layout of GUI Widgets
11. The grid() layout management method precisely arranges
objects in a
grid made up of rows and columns.

12. Common parameters of the grid() method include padx,


pady, row,
column, rowspan, columnspan and sticky.
Contents
A. Consolidation
1. Which of the following is a parameter of the layout management
method
pack ()?

A. s c a l e
B. s i d e
C. s t i c k B
D. s t o p

2. Which of the following is NOT a GUI widget class in tkinter?

A. Frame
B. Message
C. Scale D
D. Textbox
Contents
3. Which of the following GUI classes has command as a
parameter?
(i) Button (ii) Entry (iii) Label
A. ( i ) o n l y
B. ( i i ) o n l y A
C. ( i ) a n d ( i i ) o n l y
D. All of the above
Contents
B. Practical Exercise
1. What values can the orient parameter of a Scale object take?
'horizontal' and 'vertical'
_______________________________________________________

2. Briefly describe the GUI object created by the following code


label_message=tk.Label(root,text='It is a test.', bg='white',fg='black',width=40)
A Label object displaying the text “It is a test.” in white against a black
________________________________________________________________
________________________________________________________________
background and having 40-character length.
Contents
C. Enrichment
Build the circuit in Task 6 of Unit 3 (p.33) and write a GUI program that
displays the readings from the LDR.
-End-
Contents

Program file: u4_task1.py

Back
Contents

Program file: u4_fig4.4.py

Back
Contents

Program file: u4_task2.py

Back
Contents
Program file: u4_task3.py

Back
Contents
Program file: u4_q2.py

The teacher may show the different answers outputted by


the program when different values are input, or when
different buttons are pressed. For students with higher
ability, the teacher may show the whole program and
gauge the students’ mastery of GUI programming by
asking them about some of the program code.

Back
Contents

Program file: u4_task4.py

Back
Contents
Program file: u4_q3.py

Back
Contents
Program file: u4_q4.py

In the project, the servo motor and LED are connected to p i n


s D 1 0 a n d D 6 o f t h e A r d u i n o b o a r d respectively.
The teacher may control the servo rotation angle and LED
brightness by inputting different values.
If the teacher just wants to demonstrate the GUI effect
without connecting up the circuit, simply insert # on the left
of the Arduino-related code lines so that the program skips
executing those code.

Back
Contents
The program file is the same as that of the previous question.

Back
Contents
Program file: u4_q6.py

Back
Contents
Program file: u4_q7.py

Back
Contents
Program file: u4_ex1.py

Back

You might also like