· 6 years ago · Oct 06, 2019, 04:26 AM
1Python – Tkinter GUI Programming
2
3'''
4
5Modern computing devices are equipped with powerful processors and advanced graphics hardware. This makes it possible for different versions of Windows OS, and desktop distributions of Linux to provide a user friendly graphical interface to the user. The older operating systems like MSDOS had a command line interface and user is only able to interact with it in the form of text input. Today user can interact with computer application through mouse clicks. He can select from alternatives with the help of radio buttons, dropdowns etc. called GUI widgets.
6
7Various graphics libraries are available for use with programming languages. A graphics library is an application programming interface (API) that defines functionality of various GUI elements. Many such libraries have been made available to Python in the form of importable modules.
8
9When a computer program that is executed in text based console mode, it follows a sequential path by default. In contrast, the GUI based program runs in an infinite event loop. Functions in the program are called depending upon the event generated by user's action such as clicking a button, selecting an item, or a mouse action.
10
11The Tk toolkit from Tcl is a cross platform and open source GUI toolkit. It is ported to Python in the form of TKinter module. Tkinter has been developed by Fredrik Lundh. This module is bundled with standard distributions of python for all platforms, and hence it need not be installed. Other installable GUI toolkit modules are:
12
13 PyQt is the Python interface to Qt, a very popular cross-platform GUI framework.
14 PyGTK module ports Python to another popular GUI widget toolkit called GTK.
15 WxPython is a Python wrapper around WxWidgets, another cross-platform graphics library.
16
17We shall learn use of Tkinter in developing GUI based Python programs. Tkinter is actually a package consisting of many modules. They are listed below:
18tkinter.scrolledtext Text widget with a vertical scroll bar built in.
19tkinter.colorchooser Dialog to let the user choose a color.
20tkinter.commondialog Base class for the dialogs defined in the other modules listed here.
21tkinter.filedialog Common dialogs to allow the user to specify a file to open or save.
22tkinter.font Utilities to help work with fonts.
23tkinter.messagebox Access to standard Tk dialog boxes.
24tkinter.simpledialog Basic dialogs and convenience functions.
25tkinter.dnd Drag-and-drop support for tkinter.
26tkinter.ttk provides access to the Tk themed widget set
27
28Python's Tkinter module contains Tk class. Its object forms a top level window. Other widgets such as Label, Button, Entry etc. can be placed on this top level window.
29
30import tkinter
31top=tkinter.Tk()
32top.mainloop()
33
34The top level window represented by this application object is having a frame with title bar, control box with maximize, minimize and close buttons, and inner client area to hold other widgets. The application object then enters an event listening loop by calling its mainloop() method.
35
36The application is now constantly waiting for any event generated on elements in it. The event could be text entered in a text field, selection made from drop down or radio button, single/double click actions of mouse etc. The application executes appropriate callback functions in response to a particular type of event. The event loop will terminate as and when the close button on title bar is clicked.
37
38The top level application object has title() method which displays a text in its title bar.
39
40top.title("Hello World")
41
42The geometry() method defines the width, height and coordinates of top left corner of the frame as below (all values are in pixels):
43
44top.geometry("widthxheight+XPOS+YPOS")
45
46Following code snippet displays an empty top level window.
47
48import tkinter
49top=tkinter.Tk()
50top.title("Hello World")
51top.geometry("300x200+10+10")
52top.mainloop()
53
54Output:Python output
55
56Tkinter library defines provides various GUI widgets.
57
58Button: Almost every GUI based application uses Button control. Even a novice computer user knows that a mouse click on it triggers a certain process. A button displays caption or an icon and can be linked to a callback function to be triggered when pressed. Following statement creates a Button object and puts it inside top level window:
59
60B1 = Button(top, text ="OK", command = Add)
61
62The Button() function requires reference to top level window. Its other important properties of Button object are:
63text caption of button
64bg background colour
65fg foreground colour
66font font name and size
67image to be displayed instead of text
68command event handler function to be called when clicked
69
70Label : This widget displays a non-editable text, or an image. Normally it is a passive widget and is not associated with event handler function.
71
72Label widget properties are similar to Button object. However, textvariable parameter is an addition.
73
74textvariable : It acts as slave to text property. This is useful to dynamically read or assign label’s caption.
75
76Following statement adds a Label in top level window:
77
78L1=Label(top, text="Enter name", fg='blue', font=("Helvetica", 16))
79
80Entry : This is a very popular GUI control for accepting user input in a single line text box. For multi-line text input use Text widget. Entry object has two important properties:
81bd border size of the text box. Default is 2 pixels.
82show set show = "*" to convert text box into a password field.
83
84To add an entry widget in top window, use following statement:
85
86T1=Entry(top, text="This is Entry Widget", bg='black',fg='white', bd=5)
87
88Entry object also has get() method to read its content and insert() method to populate the text in it. In subsequent example we shall use these methods.
89Geometry Managers
90
91The geometry() function determines the dimensions of Tk window. Placement of other widgets inside the window is controlled by geometry manager functions.
92pack()
93
94This function returns a geometry manager which organizes the widgets relative to each other. This type of arrangement is useful for placing controls side by side or vertically.
95
96The pack() function uses fill option to make a widget as wide as possible (fill=X) or as tall as possible (fill=Y). You can also specify padx and/or pady options to leave certain space along width or height.
97
98In following example, a button, a label and an Entry widget are arranged in a top level window using pack() manager.
99
100from tkinter import *
101top=Tk()
102top.title("Hello World")
103B1 = Button(top, text ="OK")
104L1=Label(top, text="Enter name", fg='blue')
105T1=Entry(top, text="This is Entry Widget", fg='red', bd=3)
106L1.pack(fill=X, padx=10)
107T1.pack(fill=X, padx=10)
108B1.pack(fill=X, padx=10)
109top.mainloop()
110
111Output:Python output
112grid()
113
114The grid() geometry manager treats the application window as a table with equal sized cells arranged in rows and columns. Each widget is placed in the grid by specifying row and column of the cell in which it is placed.
115
116In following example, the application window is a 2X2 table. First column holds two labels and second column contains Entry boxes.
117
118from tkinter import *
119import random
120top = Tk()
121for r in range(2):
122 for c in range(2):
123 Label(top, text='Label '+str(r+1)).grid(row=r, column=0)
124 Entry(top, bd=3).grid(row=r, column=1)
125top.mainloop()
126
127Output:Python output
128place()
129
130This geometry manager arranges the controls according to absolute positioning of controls in the application window. The absolute coordinates of the widget are with respect to dimensions of window.
131
132Following code displays three labels, three entry boxes and a button widget by putting at specified coordinates.
133
134from tkinter import *
135top = Tk()
136L1 = Label(top, text = "price")
137L1.place(x = 10,y = 10)
138E1 = Entry(top, bd = 3)
139E1.place(x = 60,y = 10)
140L2 = Label(top,text = "quantity")
141L2.place(x = 10,y = 50)
142E2 = Entry(top,bd = 3)
143E2.place(x = 60,y = 50)
144L3 = Label(top,text = "Amount")
145L3.place(x = 10,y = 150)
146E3 = Entry(top,bd = 3)
147E3.place(x = 60,y = 150)
148B = Button(top, text = "Calculate")
149B.place(x = 100, y = 100)
150top.geometry("250x200+10+10")
151top.mainloop()
152
153Output:Python output
154Event handling:
155
156As mentioned earlier, the Application object is always anticipating events as it runs an event listening loop. Each type of GUI widget is capable of identifying certain type of user interaction called event. User’s actions such as mouse button click or double click, text typed in entry box, a widget comes in or goes out of focus etc. creates an event object. This event is notified to the application object which maps it to a user-defined event handler function.
157
158Event is identified by its type, modifier and qualifier in the string format as
159
160Here is a list of different tkinter events:
161event modifier type qualifier action
162
163 Button 1 mouse left button click.
164
165 Button 2 mouse middle button click.
166
167 Destroy
168 Window is being destroyed
169 Double Button 1 Double-click mouse button 1.
170 Enter
171
172 Cursor enters window/widget
173
174 Expose
175 Window fully or partially exposed.
176
177 KeyPress a Any key pressed.
178
179 KeyRelease
180 Any key released.
181
182 Leave
183 Cursor leaves window.
184
185
186 Print PRINT key has been pressed
187
188 FocusIn
189 Widget gains focus
190
191 FocusOut
192 widget loses focus
193
194Any event should be registered with one or more GUI widgets for it to be processed. Otherwise, it will be ignored. In tkinter, there are two ways to register event with a widget.
195bind() function:
196
197This function associates an event to an event handler function.
198
199Widget.bind(event, handler)
200
201For example to invoke hello() function in left button click
202
203from tkinter import *
204def hello(event):
205 print("Hello World")
206top=Tk()
207B = Button(top, text='Say Hello')
208B.bind('', hello)
209B.pack()
210top.mainloop()
211
212The handler function event object as the argument and is bound with button object. the function gets called when left button of mouse (identified as ) is clicked.
213
214Output:Python output
215
216'Hello World' message is printed on Python console.
217
218The event object carries properties of the widget that captured respective event. Details such as position coordinates, and event type etc. can be processed by the handler function if required.
219command attribute
220
221Another convenient way to register event is using 'command' parameter. Each type of widget is designed to capture an event of particular type. For example, Button recognizes click event. So it is by default bound to it. The handler function registered as value of 'command' attribute while setting up the widget will be invoked whenever its bound event occurs.
222
223B = Button(top, text='Say Hello', command=hello)
224
225Following example uses command attribute to call hello() event handler function when button click event occurs.
226
227from tkinter import *
228def hello():
229 print("Hello World")
230top=Tk()
231B = Button(top, text='Say Hello', command=hello)
232B.pack()
233top.mainloop()
234
235Some of the other useful widgets in tkinter API are explained here.
236
237Radiobutton : This widget is a toggle button having ON/OFF state. There may be more than one buttons, only one of them will be ON at a given time. Following important properties configure the Radiobutton widget:
238variable The control variable has same value for all radiobuttons in a group so that only one of them is ON. It's type may be IntVar or StringVar as defined in tkinter.
239value When a radio button is clicked to be ON, the control variable is set to this parameter.
240
241Following statements add two radiobuttons to the window:
242
243from tkinter import *
244def handler():
245 print ("Radio button selected: " + str(var.get()))
246top = Tk()
247var = StringVar()
248R1 = Radiobutton(top, text = "male", variable = var, value = 'male',
249 command = handler)
250R2 = Radiobutton(top, text = "female", variable = var, value = 'female',
251 command = handler)
252R1.pack()
253R2.pack()
254top.mainloop()
255
256Output:Python output
257
258When any radio button is pressed, appropriate message will be displayed on Python shell.
259
260Checkbutton : This is also a toggle button producing a checkable rectangle before its caption. When selected, a tick mark is displayed in the box which disappears when it is clicked again. The variable property of each check button is set to different IntVar so that more than one checkboxes can be selected.
261
262Following example shows two check box buttons. Their states are identified by handler function.
263
264from tkinter import *
265def handler():
266 if v1.get()==1: print ("I play Guitar. ", end='')
267 if v2.get()==1: print ("I play Cricket. ")
268 print()
269top = Tk()
270v1 = IntVar()
271v2 = IntVar()
272C1 = Checkbutton(top, text = "Guitar", variable = v1, command=handler)
273C2 = Checkbutton(top, text = "Cricket", variable = v2, command=handler)
274C1.pack()
275C2.pack()
276top.mainloop()
277
278Output:Python output
279
280When upper check box is ticked following line is displayed.
281
282I play Guitar.
283
284When only lower box is ticked, following output is displayed.
285
286I play Cricket.
287
288When both boxes have ticks, output is as follows:
289
290I play Guitar. I play Cricket.
291
292Combobox: This class is defined in ttk module of tkinter package. It populates drop-down data from a collection data type such as tuple or list as values parameter. The selected item from the combobox is assigned to a variable of StringVar type.
293
294Following example shows a Combobox populated with names of computer languages, and a Button. When the button is clicked, it reads name of selected language from combobox.
295
296from tkinter import *
297from tkinter.ttk import Combobox
298def handler():
299 print("I love {}.".format(var.get()))
300top = Tk()
301var = StringVar()
302langs=("C", "C++", "Java", "Python")
303cb=Combobox( top,values=langs, textvariable=var)
304cb.pack(side=LEFT)
305b=Button(text='ok', command=handler)
306b.pack(side=LEFT)
307top.mainloop()
308
309Output:Python output
310
311After making selection, click on the 'ok' button. Python console shows following line printed:
312
313I love Python.
314
315Listbox: Listbox widget is not a drop-down. Instead it shows multiple string items contained in it. User can select one or multiple items. Following table shows important attributes of Listbox object:
316Selectmode SINGLE – only one item selectable. MULTIPLE - one or more items selectable. EXTENDED – adjacent group of items selectable
317Height Number of items to be displayed.
318Width Width of box in characters (default 20)
319
320Listbox object supports following methods:
321curselection() Returns line numbers of the selected element or elements.
322insert() inserts an item at given line index. Use END if new item is to be appended.
323get() returns one or more selected items
324
325In following example, a listbox is populated with names of computer languages. There is also a button which retrieves the name of selected language.
326
327from tkinter import *
328def handler():
329 index=int(lb.curselection()[0])
330 lang=lb.get(index)
331 print("I love {}.".format(lang))
332top = Tk()
333langs=("C", "C++", "Java", "Python")
334lb=Listbox( top, height=5)
335for i in range(len(langs)):
336 lb.insert(i+1, langs[i])
337lb.pack(side=LEFT)
338b=Button(text='ok', command=handler)
339b.pack(side=LEFT)
340top.mainloop()
341
342Output:Python output
343
344Make a selection and click on 'ok' button. Following line will be printed on Python console:
345
346I love Python.
347
348Menu
349
350We can provide a comprehensive menu system to tkinter GUI application with the help of Menu widget so that it gets a professional look.
351
352First of all create a Menu object to be displayed at the default menubar location of top level window.
353
354menubar = Menu(top)
355
356You can now set up a vertical pull-down File menu by following statement:
357
358file = Menu(menubar, tearoff = 0)
359
360The tearoff=0 parameter will display a dotted line above the choices. Individual menu items in File menu are placed using add_command() function.
361
362file.add_command(label="New", command = New)
363file.add_command(label = "Open", command = Open)
364file.add_command(label = "Save", command = Save)
365file.add_command(label = "Exit", command = top.quit)
366
367Each menu item is similar to a Button widget with command parameter to attach a callback handler function. The New(), Open() and Save() user-defined functions need to be defined. For 'Exit' item, 'quit' function of application object is used as event handler.
368
369The File menu is now designed. It is then added to menubar by add_cascade() function
370
371menubar.add_cascade(label = "File", menu = file)
372
373Use similar procedure to set up Edit menu. A dummy noop() function is bound to each menu item in edit menu.
374
375Finally the menubar is registered with the application object by following statement:
376
377top.config(menu = menubar)
378
379Complete code is as follows:
380
381from tkinter import *
382def New():
383 print ("'New' option clicked")
384def Open():
385 print ("'Open' option clicked")
386def Save():
387 print ("'Save' option clicked")
388def noop():
389 pass
390top = Tk()
391menubar = Menu(top)
392file = Menu(menubar, tearoff = 0)
393file.add_command(label="New", command = New)
394file.add_command(label = "Open", command = Open)
395file.add_command(label = "Save", command = Save)
396file.add_command(label = "Exit", command = top.quit)
397menubar.add_cascade(label = "File", menu = file)
398edit = Menu(menubar, tearoff=0)
399edit.add_command(label = "Cut", command = noop)
400edit.add_command(label = "Copy", command = noop)
401edit.add_command(label = "Paste", command = noop)
402menubar.add_cascade(label = "Edit", menu = edit)
403top.config(menu = menubar)
404top.mainloop()
405
406Output:
407
408Try clicking on menu items in File menu. First three items will display corresponding text on Python console, click on 'Exit' will close the application.
409
410'New' option clicked
411'Open' option clicked
412'Save' option clicked
413
414Canvas widget: Tkinter provides this widget as a drawable panel. Different shapes, text, frames, image or other widgets can be placed on a canvas. This object has following methods to display shapes and text as below:
415create_line Draws a straight line from x1,y1 to x2,y2. Color is specified with fill parameter and thickness by width parameter.
416create_rectangle Draws rectangle shape where x1,y1 denote coordinates of top left corner and x2,y2 are coordinates of right bottom corner. The fill parameter is used to display solid rectangle with specified colour.
417create_oval Displays an ellipse. X1,y1 represents coordinates of center. r1 and r2 stand for x radius and y radius. If r1 and r2 same, circle is drawn.
418create_text Displays a string value of text parameter at x1,y1 coordinates. Font parameter decides font name and size and fill parameter is given to apply font colour.
419
420Following example uses above canvas methods
421
422from tkinter import *
423top=Tk()
424cv = Canvas(top, height = 300, width = 300)
425coord = 10, 10, 250, 250
426cv.create_rectangle(coord, outline = "red", fill='blue')
427cv.create_line(1,275,260,275,fill = 'orange', width=5)
428cv.create_oval(200,200,50,50, fill='yellow')
429cv.create_text(125,225,text='Hello World',font=("Arial",20),fill='white')
430cv.pack()
431top.title('Hello Python')
432top.mainloop()
433
434'''