top

Search

Python Tutorial

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.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.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.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:PyQt is the Python interface to Qt, a very popular cross-platform GUI framework.PyGTK module ports Python to another popular GUI widget toolkit called GTK.WxPython is a Python wrapper around WxWidgets, another cross-platform graphics library.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:tkinter.scrolledtextText widget with a vertical scroll bar built in.tkinter.colorchooserDialog to let the user choose a color.tkinter.commondialogBase class for the dialogs defined in the other modules listed here.tkinter.filedialogCommon dialogs to allow the user to specify a file to open or save.tkinter.fontUtilities to help work with fonts.tkinter.messageboxAccess to standard Tk dialog boxes.tkinter.simpledialogBasic dialogs and convenience functions.tkinter.dndDrag-and-drop support for tkinter.tkinter.ttkprovides access to the Tk themed widget setPython'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.import tkinter top=tkinter.Tk() top.mainloop()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.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.The top level application object has title() method which displays a text in its title bar.top.title("Hello World")The geometry() method defines the width, height and coordinates of top left corner of the frame as below (all values are in pixels):top.geometry("widthxheight+XPOS+YPOS")Following code snippet displays an empty top level window.import tkinter top=tkinter.Tk() top.title("Hello World") top.geometry("300x200+10+10") top.mainloop()Output:Tkinter library defines provides various GUI widgets.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:B1 = Button(top, text ="OK", command = Add)The Button() function requires reference to top level window. Its other important properties of Button object are:textcaption of buttonbgbackground colourfgforeground colourfontfont name and sizeimageto be displayed instead of textcommandevent handler function to be called when clickedLabel : This widget displays a non-editable text, or an image. Normally it is a passive widget and is not associated with event handler function.Label widget properties are similar to Button object. However, textvariable parameter is an addition.textvariable : It acts as slave to text property. This is useful to dynamically read or assign label’s caption.Following statement adds a Label in top level window:L1=Label(top, text="Enter name", fg='blue', font=("Helvetica", 16))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:bd border size of the text box. Default is 2 pixels.show set show = "*" to convert text box into a password field.To add an entry widget in top window, use following statement:T1=Entry(top, text="This is Entry Widget", bg='black',fg='white', bd=5)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.Geometry ManagersThe geometry() function determines the dimensions of Tk window. Placement of other widgets inside the window is controlled by geometry manager functions.pack() 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.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.In following example, a button, a label and an Entry widget are arranged in a top level window using pack() manager.from tkinter import * top=Tk() top.title("Hello World") B1 = Button(top, text ="OK") L1=Label(top, text="Enter name", fg='blue') T1=Entry(top, text="This is Entry Widget", fg='red', bd=3) L1.pack(fill=X, padx=10) T1.pack(fill=X, padx=10) B1.pack(fill=X, padx=10) top.mainloop()Output:grid()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.In following example, the application window is a 2X2 table. First column holds two labels and second column contains Entry boxes.from  tkinter import * import random top = Tk() for r in range(2):   for c in range(2):      Label(top, text='Label '+str(r+1)).grid(row=r, column=0)      Entry(top, bd=3).grid(row=r, column=1) top.mainloop()Output:place()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.Following code displays three labels, three entry boxes and a button widget by putting at specified coordinates.from tkinter import * top = Tk() L1 = Label(top, text = "price") L1.place(x = 10,y = 10) E1 = Entry(top, bd = 3) E1.place(x = 60,y = 10) L2 = Label(top,text = "quantity") L2.place(x = 10,y = 50) E2 = Entry(top,bd = 3) E2.place(x = 60,y = 50) L3 = Label(top,text = "Amount") L3.place(x = 10,y = 150) E3 = Entry(top,bd = 3) E3.place(x = 60,y = 150) B = Button(top, text = "Calculate") B.place(x = 100, y = 100) top.geometry("250x200+10+10") top.mainloop()Output:Event handling: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.Event is identified by its type, modifier and qualifier in the string format as <modifier-type-qualifier>Here is a list of different tkinter events:eventmodifiertypequalifieraction<Button-1>Button1mouse left button click.<Button-2>Button2mouse middle button click.<Destroy>DestroyWindow is being destroyed<Double-Button-1>DoubleButton1Double-click mouse button 1.<Enter>EnterCursor enters window/widget<Expose>ExposeWindow fully or partially exposed.<KeyPress-a>KeyPressaAny key pressed.<KeyRelease>KeyReleaseAny key released.<Leave>LeaveCursor leaves window.<Print>PrintPRINT key has been pressed<FocusIn>FocusInWidget gains focus<FocusOut>FocusOutwidget loses focusAny 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.bind() function: This function associates an event to an event handler function.Widget.bind(event, handler)For example to invoke hello() function in left button clickfrom tkinter import * def hello(event):    print("Hello World") top=Tk() B = Button(top, text='Say Hello') B.bind('<Button-1>', hello) B.pack() top.mainloop()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 <Button-1>) is clicked.Output:'Hello World' message is printed on Python console.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.command attributeAnother 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.B = Button(top, text='Say Hello', command=hello)Following example uses command attribute to call hello() event handler function when button click event occurs.from tkinter import * def hello():    print("Hello World") top=Tk() B = Button(top, text='Say Hello', command=hello) B.pack() top.mainloop()Some of the other useful widgets in tkinter API are explained here.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:variableThe 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.valueWhen a radio button is clicked to be ON, the control variable is set to this parameter.Following statements add two radiobuttons to the window:from tkinter import * def handler():   print ("Radio button selected: " + str(var.get())) top = Tk() var = StringVar() R1 = Radiobutton(top, text = "male", variable = var, value = 'male',                  command = handler) R2 = Radiobutton(top, text = "female", variable = var, value = 'female',                  command = handler) R1.pack() R2.pack() top.mainloop()Output:When any radio button is pressed, appropriate message will be displayed on Python shell.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.Following example shows two check box buttons. Their states are identified by handler function.from tkinter import * def handler():   if v1.get()==1: print ("I play Guitar. ", end='')   if v2.get()==1: print ("I play Cricket. ")   print() top = Tk() v1 = IntVar() v2 = IntVar() C1 = Checkbutton(top, text = "Guitar", variable = v1, command=handler) C2 = Checkbutton(top, text = "Cricket", variable = v2, command=handler) C1.pack() C2.pack() top.mainloop()Output:When upper check box is ticked following line is displayed. I play Guitar. When only lower box is ticked, following output is displayed.I play Cricket.When both boxes have ticks, output is as follows:I play Guitar. I play Cricket.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.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.from tkinter import * from tkinter.ttk import Combobox def handler():   print("I love {}.".format(var.get())) top = Tk() var = StringVar() langs=("C", "C++", "Java", "Python") cb=Combobox( top,values=langs, textvariable=var) cb.pack(side=LEFT) b=Button(text='ok', command=handler) b.pack(side=LEFT) top.mainloop()Output:After making selection, click on the 'ok' button. Python console shows following line printed:I love Python.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:SelectmodeSINGLE – only one item selectable. MULTIPLE - one or more items selectable. EXTENDED – adjacent group of items selectableHeightNumber of items to be displayed.WidthWidth of box in characters (default 20)Listbox object supports following methods:curselection() Returns line numbers of the selected element or elements.insert() inserts an item at given line index. Use END if new item is to be appended.get() returns one or more selected itemsIn following example, a listbox is populated with names of computer languages. There is also a button which retrieves the name of selected language.from tkinter import * def handler():        index=int(lb.curselection()[0])        lang=lb.get(index)        print("I love {}.".format(lang)) top = Tk() langs=("C", "C++", "Java", "Python") lb=Listbox( top, height=5) for i in range(len(langs)):        lb.insert(i+1, langs[i]) lb.pack(side=LEFT) b=Button(text='ok', command=handler) b.pack(side=LEFT) top.mainloop()Output:Make a selection and click on 'ok' button. Following line will be printed on Python console:I love Python.MenuWe can provide a comprehensive menu system to tkinter GUI application with the help of Menu widget so that it gets a professional look.First of all create a Menu object to be displayed at the default menubar location of top level window.menubar = Menu(top)You can now set up a vertical pull-down File menu by following statement:file = Menu(menubar, tearoff = 0)The tearoff=0 parameter will display a dotted line above the choices. Individual menu items in File menu are placed using add_command() function.file.add_command(label="New", command = New) file.add_command(label = "Open", command = Open) file.add_command(label = "Save", command = Save) file.add_command(label = "Exit", command = top.quit)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.The File menu is now designed. It is then added to menubar by add_cascade() functionmenubar.add_cascade(label = "File", menu = file)Use similar procedure to set up Edit menu. A dummy noop() function is bound to each menu item in edit menu.Finally the menubar is registered with the application object by following statement:top.config(menu = menubar) Complete code is as follows:from tkinter import * def New():   print ("'New' option clicked") def Open():        print ("'Open' option clicked") def Save():        print ("'Save' option clicked") def noop():        pass top = Tk() menubar = Menu(top) file = Menu(menubar, tearoff = 0) file.add_command(label="New", command = New) file.add_command(label = "Open", command = Open) file.add_command(label = "Save", command = Save) file.add_command(label = "Exit", command = top.quit) menubar.add_cascade(label = "File", menu = file) edit = Menu(menubar, tearoff=0) edit.add_command(label = "Cut", command = noop) edit.add_command(label = "Copy", command = noop) edit.add_command(label = "Paste", command = noop) menubar.add_cascade(label = "Edit", menu = edit) top.config(menu = menubar) top.mainloop()Output: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.'New' option clicked 'Open' option clicked 'Save' option clickedCanvas 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:create_lineDraws a straight line from x1,y1 to x2,y2. Color is specified with fill parameter and thickness by width parameter.create_rectangleDraws 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.create_ovalDisplays 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.create_textDisplays 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.Following example uses above canvas methodsfrom tkinter import * top=Tk() cv = Canvas(top, height = 300, width = 300) coord = 10, 10, 250, 250 cv.create_rectangle(coord,  outline = "red", fill='blue') cv.create_line(1,275,260,275,fill = 'orange', width=5) cv.create_oval(200,200,50,50, fill='yellow') cv.create_text(125,225,text='Hello World',font=("Arial",20),fill='white') cv.pack() top.title('Hello Python') top.mainloop()Output:
logo

Python Tutorial

Python – Tkinter GUI Programming

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.

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.

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.

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:

  • PyQt is the Python interface to Qt, a very popular cross-platform GUI framework.
  • PyGTK module ports Python to another popular GUI widget toolkit called GTK.
  • WxPython is a Python wrapper around WxWidgets, another cross-platform graphics library.

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:

tkinter.scrolledtextText widget with a vertical scroll bar built in.
tkinter.colorchooserDialog to let the user choose a color.
tkinter.commondialogBase class for the dialogs defined in the other modules listed here.
tkinter.filedialogCommon dialogs to allow the user to specify a file to open or save.
tkinter.fontUtilities to help work with fonts.
tkinter.messageboxAccess to standard Tk dialog boxes.
tkinter.simpledialogBasic dialogs and convenience functions.
tkinter.dndDrag-and-drop support for tkinter.
tkinter.ttkprovides access to the Tk themed widget set

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.

import tkinter
top=tkinter.Tk()
top.mainloop()

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.

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.

The top level application object has title() method which displays a text in its title bar.

top.title("Hello World")

The geometry() method defines the width, height and coordinates of top left corner of the frame as below (all values are in pixels):

top.geometry("widthxheight+XPOS+YPOS")

Following code snippet displays an empty top level window.

import tkinter
top=tkinter.Tk()
top.title("Hello World")
top.geometry("300x200+10+10")
top.mainloop()

Output:Python output

Tkinter library defines provides various GUI widgets.

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:

B1 = Button(top, text ="OK", command = Add)

The Button() function requires reference to top level window. Its other important properties of Button object are:

textcaption of button
bgbackground colour
fgforeground colour
fontfont name and size
imageto be displayed instead of text
commandevent handler function to be called when clicked

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.

Label widget properties are similar to Button object. However, textvariable parameter is an addition.

textvariable : It acts as slave to text property. This is useful to dynamically read or assign label’s caption.

Following statement adds a Label in top level window:

L1=Label(top, text="Enter name", fg='blue', font=("Helvetica", 16))

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:

bd border size of the text box. Default is 2 pixels.
show set show = "*" to convert text box into a password field.

To add an entry widget in top window, use following statement:

T1=Entry(top, text="This is Entry Widget", bg='black',fg='white', bd=5)

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.

Geometry Managers

The geometry() function determines the dimensions of Tk window. Placement of other widgets inside the window is controlled by geometry manager functions.

pack() 

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.

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.

In following example, a button, a label and an Entry widget are arranged in a top level window using pack() manager.

from tkinter import *
top=Tk()
top.title("Hello World")
B1 = Button(top, text ="OK")
L1=Label(top, text="Enter name", fg='blue')
T1=Entry(top, text="This is Entry Widget", fg='red', bd=3)
L1.pack(fill=X, padx=10)
T1.pack(fill=X, padx=10)
B1.pack(fill=X, padx=10)
top.mainloop()

Output:Python output

grid()

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.

In following example, the application window is a 2X2 table. First column holds two labels and second column contains Entry boxes.

from  tkinter import *
import random
top = Tk()
for r in range(2):
  for c in range(2):
     Label(top, text='Label '+str(r+1)).grid(row=r, column=0)
     Entry(top, bd=3).grid(row=r, column=1)
top.mainloop()

Output:Python output

place()

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.

Following code displays three labels, three entry boxes and a button widget by putting at specified coordinates.

from tkinter import *
top = Tk()
L1 = Label(top, text = "price")
L1.place(x = 10,y = 10)
E1 = Entry(top, bd = 3)
E1.place(x = 60,y = 10)
L2 = Label(top,text = "quantity")
L2.place(x = 10,y = 50)
E2 = Entry(top,bd = 3)
E2.place(x = 60,y = 50)
L3 = Label(top,text = "Amount")
L3.place(x = 10,y = 150)
E3 = Entry(top,bd = 3)
E3.place(x = 60,y = 150)
B = Button(top, text = "Calculate")
B.place(x = 100, y = 100)
top.geometry("250x200+10+10")
top.mainloop()

Output:Python output

Event handling:

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.

Event is identified by its type, modifier and qualifier in the string format as <modifier-type-qualifier>

Here is a list of different tkinter events:

eventmodifiertypequalifieraction
<Button-1>
Button1mouse left button click.
<Button-2>
Button2mouse middle button click.
<Destroy>
Destroy
Window is being destroyed
<Double-Button-1>DoubleButton1Double-click mouse button 1.
<Enter>Enter

Cursor enters window/widget
<Expose>
Expose
Window fully or partially exposed.
<KeyPress-a>
KeyPressaAny key pressed.
<KeyRelease>
KeyRelease
Any key released.
<Leave>
Leave
Cursor leaves window.
<Print>

PrintPRINT key has been pressed
<FocusIn>
FocusIn
Widget gains focus
<FocusOut>
FocusOut
widget loses focus

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.

bind() function: 

This function associates an event to an event handler function.

Widget.bind(event, handler)

For example to invoke hello() function in left button click

from tkinter import *
def hello(event):
   print("Hello World")
top=Tk()
B = Button(top, text='Say Hello')
B.bind('<Button-1>', hello)
B.pack()
top.mainloop()

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 <Button-1>) is clicked.

Output:Python output

'Hello World' message is printed on Python console.

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.

command attribute

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.

B = Button(top, text='Say Hello', command=hello)

Following example uses command attribute to call hello() event handler function when button click event occurs.

from tkinter import *
def hello():
   print("Hello World")
top=Tk()
B = Button(top, text='Say Hello', command=hello)
B.pack()
top.mainloop()

Some of the other useful widgets in tkinter API are explained here.

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:

variableThe 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.
valueWhen a radio button is clicked to be ON, the control variable is set to this parameter.

Following statements add two radiobuttons to the window:

from tkinter import *
def handler():
  print ("Radio button selected: " + str(var.get()))
top = Tk()
var = StringVar()
R1 = Radiobutton(top, text = "male", variable = var, value = 'male',
                 command = handler)
R2 = Radiobutton(top, text = "female", variable = var, value = 'female',
                 command = handler)
R1.pack()
R2.pack()
top.mainloop()

Output:Python output

When any radio button is pressed, appropriate message will be displayed on Python shell.

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.

Following example shows two check box buttons. Their states are identified by handler function.

from tkinter import *
def handler():
  if v1.get()==1: print ("I play Guitar. ", end='')
  if v2.get()==1: print ("I play Cricket. ")
  print()
top = Tk()
v1 = IntVar()
v2 = IntVar()
C1 = Checkbutton(top, text = "Guitar", variable = v1, command=handler)
C2 = Checkbutton(top, text = "Cricket", variable = v2, command=handler)
C1.pack()
C2.pack()
top.mainloop()

Output:Python output

When upper check box is ticked following line is displayed. 

I play Guitar. 

When only lower box is ticked, following output is displayed.

I play Cricket.

When both boxes have ticks, output is as follows:

I play Guitar. I play Cricket.

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.

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.

from tkinter import *
from tkinter.ttk import Combobox
def handler():
  print("I love {}.".format(var.get()))
top = Tk()
var = StringVar()
langs=("C", "C++", "Java", "Python")
cb=Combobox( top,values=langs, textvariable=var)
cb.pack(side=LEFT)
b=Button(text='ok', command=handler)
b.pack(side=LEFT)
top.mainloop()

Output:Python output

After making selection, click on the 'ok' button. Python console shows following line printed:

I love Python.

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:

SelectmodeSINGLE – only one item selectable. MULTIPLE - one or more items selectable. EXTENDED – adjacent group of items selectable
HeightNumber of items to be displayed.
WidthWidth of box in characters (default 20)

Listbox object supports following methods:

curselection() Returns line numbers of the selected element or elements.
insert() inserts an item at given line index. Use END if new item is to be appended.
get() returns one or more selected items

In following example, a listbox is populated with names of computer languages. There is also a button which retrieves the name of selected language.

from tkinter import *
def handler():
       index=int(lb.curselection()[0])
       lang=lb.get(index)
       print("I love {}.".format(lang))
top = Tk()
langs=("C", "C++", "Java", "Python")
lb=Listbox( top, height=5)
for i in range(len(langs)):
       lb.insert(i+1, langs[i])
lb.pack(side=LEFT)
b=Button(text='ok', command=handler)
b.pack(side=LEFT)
top.mainloop()

Output:Python output

Make a selection and click on 'ok' button. Following line will be printed on Python console:

I love Python.

Menu

We can provide a comprehensive menu system to tkinter GUI application with the help of Menu widget so that it gets a professional look.

First of all create a Menu object to be displayed at the default menubar location of top level window.

menubar = Menu(top)

You can now set up a vertical pull-down File menu by following statement:

file = Menu(menubar, tearoff = 0)

The tearoff=0 parameter will display a dotted line above the choices. Individual menu items in File menu are placed using add_command() function.

file.add_command(label="New", command = New)
file.add_command(label = "Open", command = Open)
file.add_command(label = "Save", command = Save)
file.add_command(label = "Exit", command = top.quit)

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.

The File menu is now designed. It is then added to menubar by add_cascade() function

menubar.add_cascade(label = "File", menu = file)

Use similar procedure to set up Edit menu. A dummy noop() function is bound to each menu item in edit menu.

Finally the menubar is registered with the application object by following statement:

top.config(menu = menubar) 

Complete code is as follows:

from tkinter import *
def New():
  print ("'New' option clicked")
def Open():
       print ("'Open' option clicked")
def Save():
       print ("'Save' option clicked")
def noop():
       pass
top = Tk()
menubar = Menu(top)
file = Menu(menubar, tearoff = 0)
file.add_command(label="New", command = New)
file.add_command(label = "Open", command = Open)
file.add_command(label = "Save", command = Save)
file.add_command(label = "Exit", command = top.quit)
menubar.add_cascade(label = "File", menu = file)
edit = Menu(menubar, tearoff=0)
edit.add_command(label = "Cut", command = noop)
edit.add_command(label = "Copy", command = noop)
edit.add_command(label = "Paste", command = noop)
menubar.add_cascade(label = "Edit", menu = edit)
top.config(menu = menubar)
top.mainloop()

Output:

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.

'New' option clicked
'Open' option clicked
'Save' option clicked

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:

create_lineDraws a straight line from x1,y1 to x2,y2. Color is specified with fill parameter and thickness by width parameter.
create_rectangleDraws 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.
create_ovalDisplays 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.
create_textDisplays 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.

Following example uses above canvas methods

from tkinter import *
top=Tk()
cv = Canvas(top, height = 300, width = 300)
coord = 10, 10, 250, 250
cv.create_rectangle(coord,  outline = "red", fill='blue')
cv.create_line(1,275,260,275,fill = 'orange', width=5)
cv.create_oval(200,200,50,50, fill='yellow')
cv.create_text(125,225,text='Hello World',font=("Arial",20),fill='white')
cv.pack()
top.title('Hello Python')
top.mainloop()

Output:Python output

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

Eula

This is my first time here. I am truly impressed to read all this in one place.

Jaypee Dela Cruz

Thank you for your wonderful codes and website, you helped me a lot especially in this socket module. Thank you again!

lucky verma

Thank you for taking the time to share your knowledge about using python to find the path! Your insight and guidance is greatly appreciated.

Pre Engineered Metal Building

Usually I by no means touch upon blogs however your article is so convincing that I by no means prevent myself to mention it here.

Pre Engineered Metal Building

Usually, I never touch upon blogs; however, your article is so convincing that I could not prevent myself from mentioning how nice it is written.

Suggested Tutorials

Swift Tutorial

Introduction to Swift Tutorial
Swift Tutorial

Introduction to Swift Tutorial

Read More

R Programming Tutorial

R Programming

C# Tutorial

C# is an object-oriented programming developed by Microsoft that uses the .Net Framework. It utilizes the Common Language Interface (CLI) that describes the executable code as well as the runtime environment. C# can be used for various applications such as web applications, distributed applications, database applications, window applications etc.For greater understanding of this tutorial, a basic knowledge of object-oriented languages such as C++, Java etc. would be beneficial.
C# Tutorial

C# is an object-oriented programming developed by Microsoft that uses ...

Read More