Advertisement
here2share

Python – Tkinter GUI

Oct 5th, 2019
1,926
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 18.82 KB | None | 0 0
  1. Python – Tkinter GUI Programming
  2.  
  3. '''
  4.  
  5. Modern 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.  
  7. Various 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.  
  9. When 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.  
  11. The 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.  
  17. We shall learn use of Tkinter in developing GUI based Python programs. Tkinter is actually a package consisting of many modules. They are listed below:
  18. tkinter.scrolledtext    Text widget with a vertical scroll bar built in.
  19. tkinter.colorchooser    Dialog to let the user choose a color.
  20. tkinter.commondialog    Base class for the dialogs defined in the other modules listed here.
  21. tkinter.filedialog  Common dialogs to allow the user to specify a file to open or save.
  22. tkinter.font    Utilities to help work with fonts.
  23. tkinter.messagebox  Access to standard Tk dialog boxes.
  24. tkinter.simpledialog    Basic dialogs and convenience functions.
  25. tkinter.dnd Drag-and-drop support for tkinter.
  26. tkinter.ttk provides access to the Tk themed widget set
  27.  
  28. Python'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.  
  30. import tkinter
  31. top=tkinter.Tk()
  32. top.mainloop()
  33.  
  34. The 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.  
  36. The 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.  
  38. The top level application object has title() method which displays a text in its title bar.
  39.  
  40. top.title("Hello World")
  41.  
  42. The geometry() method defines the width, height and coordinates of top left corner of the frame as below (all values are in pixels):
  43.  
  44. top.geometry("widthxheight+XPOS+YPOS")
  45.  
  46. Following code snippet displays an empty top level window.
  47.  
  48. import tkinter
  49. top=tkinter.Tk()
  50. top.title("Hello World")
  51. top.geometry("300x200+10+10")
  52. top.mainloop()
  53.  
  54. Output:Python output
  55.  
  56. Tkinter library defines provides various GUI widgets.
  57.  
  58. Button: 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.  
  60. B1 = Button(top, text ="OK", command = Add)
  61.  
  62. The Button() function requires reference to top level window. Its other important properties of Button object are:
  63. text    caption of button
  64. bg  background colour
  65. fg  foreground colour
  66. font    font name and size
  67. image   to be displayed instead of text
  68. command event handler function to be called when clicked
  69.  
  70. Label : 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.  
  72. Label widget properties are similar to Button object. However, textvariable parameter is an addition.
  73.  
  74. textvariable : It acts as slave to text property. This is useful to dynamically read or assign label’s caption.
  75.  
  76. Following statement adds a Label in top level window:
  77.  
  78. L1=Label(top, text="Enter name", fg='blue', font=("Helvetica", 16))
  79.  
  80. Entry : 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:
  81. bd   border size of the text box. Default is 2 pixels.
  82. show     set show = "*" to convert text box into a password field.
  83.  
  84. To add an entry widget in top window, use following statement:
  85.  
  86. T1=Entry(top, text="This is Entry Widget", bg='black',fg='white', bd=5)
  87.  
  88. Entry 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.
  89. Geometry Managers
  90.  
  91. The geometry() function determines the dimensions of Tk window. Placement of other widgets inside the window is controlled by geometry manager functions.
  92. pack()
  93.  
  94. This 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.  
  96. The 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.  
  98. In following example, a button, a label and an Entry widget are arranged in a top level window using pack() manager.
  99.  
  100. from tkinter import *
  101. top=Tk()
  102. top.title("Hello World")
  103. B1 = Button(top, text ="OK")
  104. L1=Label(top, text="Enter name", fg='blue')
  105. T1=Entry(top, text="This is Entry Widget", fg='red', bd=3)
  106. L1.pack(fill=X, padx=10)
  107. T1.pack(fill=X, padx=10)
  108. B1.pack(fill=X, padx=10)
  109. top.mainloop()
  110.  
  111. Output:Python output
  112. grid()
  113.  
  114. The 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.  
  116. In following example, the application window is a 2X2 table. First column holds two labels and second column contains Entry boxes.
  117.  
  118. from  tkinter import *
  119. import random
  120. top = Tk()
  121. for 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)
  125. top.mainloop()
  126.  
  127. Output:Python output
  128. place()
  129.  
  130. This 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.  
  132. Following code displays three labels, three entry boxes and a button widget by putting at specified coordinates.
  133.  
  134. from tkinter import *
  135. top = Tk()
  136. L1 = Label(top, text = "price")
  137. L1.place(x = 10,y = 10)
  138. E1 = Entry(top, bd = 3)
  139. E1.place(x = 60,y = 10)
  140. L2 = Label(top,text = "quantity")
  141. L2.place(x = 10,y = 50)
  142. E2 = Entry(top,bd = 3)
  143. E2.place(x = 60,y = 50)
  144. L3 = Label(top,text = "Amount")
  145. L3.place(x = 10,y = 150)
  146. E3 = Entry(top,bd = 3)
  147. E3.place(x = 60,y = 150)
  148. B = Button(top, text = "Calculate")
  149. B.place(x = 100, y = 100)
  150. top.geometry("250x200+10+10")
  151. top.mainloop()
  152.  
  153. Output:Python output
  154. Event handling:
  155.  
  156. As 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.  
  158. Event is identified by its type, modifier and qualifier in the string format as
  159.  
  160. Here is a list of different tkinter events:
  161. event   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.  
  194. Any 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.
  195. bind() function:
  196.  
  197. This function associates an event to an event handler function.
  198.  
  199. Widget.bind(event, handler)
  200.  
  201. For example to invoke hello() function in left button click
  202.  
  203. from tkinter import *
  204. def hello(event):
  205.   print("Hello World")
  206. top=Tk()
  207. B = Button(top, text='Say Hello')
  208. B.bind('', hello)
  209. B.pack()
  210. top.mainloop()
  211.  
  212. The 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.  
  214. Output:Python output
  215.  
  216. 'Hello World' message is printed on Python console.
  217.  
  218. The 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.
  219. command attribute
  220.  
  221. Another 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.  
  223. B = Button(top, text='Say Hello', command=hello)
  224.  
  225. Following example uses command attribute to call hello() event handler function when button click event occurs.
  226.  
  227. from tkinter import *
  228. def hello():
  229.   print("Hello World")
  230. top=Tk()
  231. B = Button(top, text='Say Hello', command=hello)
  232. B.pack()
  233. top.mainloop()
  234.  
  235. Some of the other useful widgets in tkinter API are explained here.
  236.  
  237. Radiobutton : 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:
  238. variable    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.
  239. value   When a radio button is clicked to be ON, the control variable is set to this parameter.
  240.  
  241. Following statements add two radiobuttons to the window:
  242.  
  243. from tkinter import *
  244. def handler():
  245.  print ("Radio button selected: " + str(var.get()))
  246. top = Tk()
  247. var = StringVar()
  248. R1 = Radiobutton(top, text = "male", variable = var, value = 'male',
  249.                 command = handler)
  250. R2 = Radiobutton(top, text = "female", variable = var, value = 'female',
  251.                 command = handler)
  252. R1.pack()
  253. R2.pack()
  254. top.mainloop()
  255.  
  256. Output:Python output
  257.  
  258. When any radio button is pressed, appropriate message will be displayed on Python shell.
  259.  
  260. Checkbutton : 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.  
  262. Following example shows two check box buttons. Their states are identified by handler function.
  263.  
  264. from tkinter import *
  265. def handler():
  266.  if v1.get()==1: print ("I play Guitar. ", end='')
  267.  if v2.get()==1: print ("I play Cricket. ")
  268.  print()
  269. top = Tk()
  270. v1 = IntVar()
  271. v2 = IntVar()
  272. C1 = Checkbutton(top, text = "Guitar", variable = v1, command=handler)
  273. C2 = Checkbutton(top, text = "Cricket", variable = v2, command=handler)
  274. C1.pack()
  275. C2.pack()
  276. top.mainloop()
  277.  
  278. Output:Python output
  279.  
  280. When upper check box is ticked following line is displayed.
  281.  
  282. I play Guitar.
  283.  
  284. When only lower box is ticked, following output is displayed.
  285.  
  286. I play Cricket.
  287.  
  288. When both boxes have ticks, output is as follows:
  289.  
  290. I play Guitar. I play Cricket.
  291.  
  292. Combobox: 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.  
  294. Following 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.  
  296. from tkinter import *
  297. from tkinter.ttk import Combobox
  298. def handler():
  299.  print("I love {}.".format(var.get()))
  300. top = Tk()
  301. var = StringVar()
  302. langs=("C", "C++", "Java", "Python")
  303. cb=Combobox( top,values=langs, textvariable=var)
  304. cb.pack(side=LEFT)
  305. b=Button(text='ok', command=handler)
  306. b.pack(side=LEFT)
  307. top.mainloop()
  308.  
  309. Output:Python output
  310.  
  311. After making selection, click on the 'ok' button. Python console shows following line printed:
  312.  
  313. I love Python.
  314.  
  315. Listbox: 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:
  316. Selectmode  SINGLE – only one item selectable. MULTIPLE - one or more items selectable. EXTENDED – adjacent group of items selectable
  317. Height  Number of items to be displayed.
  318. Width   Width of box in characters (default 20)
  319.  
  320. Listbox object supports following methods:
  321. curselection()   Returns line numbers of the selected element or elements.
  322. insert()     inserts an item at given line index. Use END if new item is to be appended.
  323. get()    returns one or more selected items
  324.  
  325. In following example, a listbox is populated with names of computer languages. There is also a button which retrieves the name of selected language.
  326.  
  327. from tkinter import *
  328. def handler():
  329.       index=int(lb.curselection()[0])
  330.       lang=lb.get(index)
  331.       print("I love {}.".format(lang))
  332. top = Tk()
  333. langs=("C", "C++", "Java", "Python")
  334. lb=Listbox( top, height=5)
  335. for i in range(len(langs)):
  336.       lb.insert(i+1, langs[i])
  337. lb.pack(side=LEFT)
  338. b=Button(text='ok', command=handler)
  339. b.pack(side=LEFT)
  340. top.mainloop()
  341.  
  342. Output:Python output
  343.  
  344. Make a selection and click on 'ok' button. Following line will be printed on Python console:
  345.  
  346. I love Python.
  347.  
  348. Menu
  349.  
  350. We can provide a comprehensive menu system to tkinter GUI application with the help of Menu widget so that it gets a professional look.
  351.  
  352. First of all create a Menu object to be displayed at the default menubar location of top level window.
  353.  
  354. menubar = Menu(top)
  355.  
  356. You can now set up a vertical pull-down File menu by following statement:
  357.  
  358. file = Menu(menubar, tearoff = 0)
  359.  
  360. The tearoff=0 parameter will display a dotted line above the choices. Individual menu items in File menu are placed using add_command() function.
  361.  
  362. file.add_command(label="New", command = New)
  363. file.add_command(label = "Open", command = Open)
  364. file.add_command(label = "Save", command = Save)
  365. file.add_command(label = "Exit", command = top.quit)
  366.  
  367. Each 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.  
  369. The File menu is now designed. It is then added to menubar by add_cascade() function
  370.  
  371. menubar.add_cascade(label = "File", menu = file)
  372.  
  373. Use similar procedure to set up Edit menu. A dummy noop() function is bound to each menu item in edit menu.
  374.  
  375. Finally the menubar is registered with the application object by following statement:
  376.  
  377. top.config(menu = menubar)
  378.  
  379. Complete code is as follows:
  380.  
  381. from tkinter import *
  382. def New():
  383.  print ("'New' option clicked")
  384. def Open():
  385.       print ("'Open' option clicked")
  386. def Save():
  387.       print ("'Save' option clicked")
  388. def noop():
  389.       pass
  390. top = Tk()
  391. menubar = Menu(top)
  392. file = Menu(menubar, tearoff = 0)
  393. file.add_command(label="New", command = New)
  394. file.add_command(label = "Open", command = Open)
  395. file.add_command(label = "Save", command = Save)
  396. file.add_command(label = "Exit", command = top.quit)
  397. menubar.add_cascade(label = "File", menu = file)
  398. edit = Menu(menubar, tearoff=0)
  399. edit.add_command(label = "Cut", command = noop)
  400. edit.add_command(label = "Copy", command = noop)
  401. edit.add_command(label = "Paste", command = noop)
  402. menubar.add_cascade(label = "Edit", menu = edit)
  403. top.config(menu = menubar)
  404. top.mainloop()
  405.  
  406. Output:
  407.  
  408. Try 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.  
  414. Canvas 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:
  415. create_line Draws a straight line from x1,y1 to x2,y2. Color is specified with fill parameter and thickness by width parameter.
  416. create_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.
  417. create_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.
  418. create_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.  
  420. Following example uses above canvas methods
  421.  
  422. from tkinter import *
  423. top=Tk()
  424. cv = Canvas(top, height = 300, width = 300)
  425. coord = 10, 10, 250, 250
  426. cv.create_rectangle(coord,  outline = "red", fill='blue')
  427. cv.create_line(1,275,260,275,fill = 'orange', width=5)
  428. cv.create_oval(200,200,50,50, fill='yellow')
  429. cv.create_text(125,225,text='Hello World',font=("Arial",20),fill='white')
  430. cv.pack()
  431. top.title('Hello Python')
  432. top.mainloop()
  433.  
  434. '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement