Lessons 53–54 · 2 lessons · M. R. Fayziyeva, D. M. Sayfurov, N. S. Xaytullayeva. Informatics and Information Technologies, Grade 9. “Nashriyot uyi Tasvir”, Tashkent, 2020
54
Practical lesson: a graphical application
Textbook: p. 107
GoalIn the practical lesson, builds small apps with tkinter: a random number button and a window that adds two numbers, and checks the typed text.
New words
Entry.get(): returns the text typed in the field as a string · Entry.get()config(text=…): changes the text of a label · config(text=…)isdigit(): True if a string consists only of digits · isdigit()event: an action of the user, such as pressing a button · voqea
Explanation
A GUI program responds to events: the user presses a button and the matching function runs. In the die window the button calls random.randint(1, 6) and writes the result into a label. In the addition window there are two Entry fields and the function takes their text with get(). The user may type letters instead of numbers, so we first check with a.isdigit() and b.isdigit() that the text consists only of digits; without the check int("abc") gives a ValueError and the app fails. According to the result of the check the label shows either the sum or the message “Son kiriting”. When making an app do not ask for real personal data (a password, an address, a phone number): a study app should have only numbers and plain text. Before running the app check the place of every widget in the grid, otherwise they may fall on top of each other.
Worked examples
Rolling a die: import tkinter as tk ⏎ import random ⏎ def tashla(): ⏎ natija.config(text=str(random.randint(1, 6))) ⏎ oyna = tk.Tk() ⏎ oyna.title("Kubik") ⏎ natija = tk.Label(oyna, text="") ⏎ natija.grid(row=0, column=0) ⏎ tugma = tk.Button(oyna, text="Tashla", command=tashla) ⏎ tugma.grid(row=1, column=0) ⏎ oyna.mainloop() When the button is pressed, one number from 1 to 6 appears in the label.
Adding two numbers: import tkinter as tk ⏎ def qosh(): ⏎ a = maydon1.get() ⏎ b = maydon2.get() ⏎ if a.isdigit() and b.isdigit(): ⏎ natija.config(text=str(int(a) + int(b))) ⏎ else: ⏎ natija.config(text="Son kiriting") ⏎ oyna = tk.Tk() ⏎ oyna.title("Qo‘shish") ⏎ maydon1 = tk.Entry(oyna, width=8) ⏎ maydon1.grid(row=0, column=0) ⏎ maydon2 = tk.Entry(oyna, width=8) ⏎ maydon2.grid(row=0, column=1) ⏎ tugma = tk.Button(oyna, text="Qo‘sh", command=qosh) ⏎ tugma.grid(row=1, column=0) ⏎ natija = tk.Label(oyna, text="") ⏎ natija.grid(row=1, column=1) ⏎ oyna.mainloop() If 7 and 5 are typed, the label shows 12; if letters are typed in the fields, the label shows Son kiriting.
Class activity
“App tester”: pairs give their apps to each other; the tester types correct and wrong data (a number, letters, empty) into the fields and writes in a table how the app responds.
Practice
1
Which values can appear in the label in the die app?
1, 2, 3, 4, 5 or 6
2
Write a function that shows in the label the product of the numbers in two Entry fields (35 for 7 and 5).