Computer basic knowledge
Computer basic knowledge
PA05 Unit4
GUI Programming
with tkinter
4.1 About GUI Programs
• 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.
_____________________________________
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.
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:
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
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.
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
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.
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
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.
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.
5. Button, Entry and Label are three common GUI widget classes in
tkinter.
A. s c a l e
B. s i d e
C. s t i c k B
D. s t o p
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'
_______________________________________________________
Back
Contents
Back
Contents
Back
Contents
Program file: u4_task3.py
Back
Contents
Program file: u4_q2.py
Back
Contents
Back
Contents
Program file: u4_q3.py
Back
Contents
Program file: u4_q4.py
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