Graphical user interfaces in Python
So far we have talked to the program through text; many programs have a graphical interface made of windows, buttons and text fields. The tkinter module, which comes with Python, creates such windows (on some systems it may need to be added separately). The order is: import tkinter as tk; the main window is created with oyna = tk.Tk(); oyna.title() and oyna.geometry("250x100") give the title and the size; widgets are created: tk.Label is a text label, tk.Entry is a text entry field, tk.Button is a button; we put them into grid cells with grid(row=…, column=…); finally oyna.mainloop() opens the window and waits for the user’s actions. The function that runs when the button is pressed is given with command= and written without brackets: command=salom; if it is written with brackets the function runs at once, without the button being pressed. The text in an Entry is taken with get() and is a string; if a number is needed it is turned with int(). The text of a label is changed with config(text=…).
| Widget | Job |
|---|---|
| tk.Label | text label |
| tk.Entry | text entry field |
| tk.Button | button |
A ticket machine has a screen: a person presses a button and the result appears. This is a graphical interface. A programmer first draws on paper how to place the button, label and field.
Designers, programmers and user-experience specialists plan windows to be handy and clear.
Look at any paper form or card you have, such as a library card or a timetable slip, and mark which parts work like a label and which like an entry field. What would the button be?
1import tkinter as tk 2def salom(): 3 yorliq.config(text="Salom!") 4oyna = tk.Tk() 5oyna.title("Mening ilovam") 6oyna.geometry("250x100") 7yorliq = tk.Label(oyna, text="") 8yorliq.grid(row=0, column=0) 9tugma = tk.Button(oyna, text="Bos", command=salom) 10tugma.grid(row=1, column=0) 11oyna.mainloop()
1import tkinter as tk 2def ikki(): 3 n = int(maydon.get()) 4 natija.config(text=str(n * 2)) 5oyna = tk.Tk() 6oyna.title("Ikkilantirish") 7maydon = tk.Entry(oyna, width=10) 8maydon.grid(row=0, column=0) 9tugma = tk.Button(oyna, text="x 2", command=ikki) 10tugma.grid(row=0, column=1) 11natija = tk.Label(oyna, text="") 12natija.grid(row=1, column=0) 13oyna.mainloop()
“Design the window on paper”: the group draws a window on paper (label, field, button) and marks their places in the grid (row, column); another group writes the code from this drawing.