0% found this document useful (0 votes)
35 views17 pages

Tkinter

This document provides an introduction to GUI programming in Python using the Tkinter library, covering key concepts such as widgets, event handling, and geometry management. It details various Tkinter widgets including Label, Button, Checkbutton, and Radiobutton, along with their functionalities and examples of how to implement them. The document aims to equip students with the skills to create interactive GUI applications using Tkinter.

Uploaded by

rockstarutsav693
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
35 views17 pages

Tkinter

This document provides an introduction to GUI programming in Python using the Tkinter library, covering key concepts such as widgets, event handling, and geometry management. It details various Tkinter widgets including Label, Button, Checkbutton, and Radiobutton, along with their functionalities and examples of how to implement them. The document aims to equip students with the skills to create interactive GUI applications using Tkinter.

Uploaded by

rockstarutsav693
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 17
“a CHAPTER GUI Python Programming using Tkinter I 5 LEARNING OUTCOMES Aer completing this chapter, students wit be able to + Create simple GUI applications using Tkinter + Process events by. Introduction to Tkinter using call back fu; Getting Started With Tkinter tions that are Tkinter Widgets bound to widgets’ command option The Label Widget * Use diferent widgets such as Label, Button, Entry, check buttons, radi The Button Widget Ho buttons, etc. to create Sul Tkinter Processing Events - CallBacks applications The Checkbutton Widget The Radiobutton Widget Frame ~ The Contain, Entry Widget Text Widget Create applications that contain menus * Use different geometry mana or place to specify the posit Create canvas within GUI diferent geometric shay igeTS Such as pack, grid fer Widget ion of widget applications to draw Pes such as “Rectangle The Listbox Widget “Citcle’ ‘Line’, Oval’, ete Geometry Manager The Tkinter Scrollbar. Widget. 51 INTRODUCTION To TKINTER at The Tkinter is an abbreviation for "TK interface" It Tkinter Standard Dialog Boxes — ‘San open source, Portable graphical user interface Messagebox Module Guy library. In. shott, it is a Python interface to the TK GUI library and it has been a part of the Python's standard Il Version 1, L.Itis Suitable for developing variety of applications Scientific, 364 nto activate th Program 15.1 Write a progr 4 Imp import tkinter as TK root = TK.Tk() root .mainloop() Output [ie . N ts all classes, attributes and methods into the tion I ‘above program, the first line impor! comerwer * The second ie ot = TK.TKO, creates an instance ofthe Tk class. This line creates soot window whi , ine root .mainloop() is used to keep the root window which is shown in the above figure. The third li root window visible. Note: 1. Tkinter also exposes thi mainloop(). 2. The root window in Tkinter is usually called "root 3. The significant change to Tkinter while moving has been removed (Tkinter is renamed as tkinter). different versions of Python. ¢ mainloop as tkinter:mainloop(). So, we can call root.mainloop() directly as but you can call it by any name. from version 2.X to 3.X is just that the capitalization The following is the syntax to make use of tkinter in _ | import Tkinter #Python 2.x | import tkinter Python 3.x 15.3 TKINTER WIDGETS The widget 7 a aphical object that exists within the Tkinter library. Widgets are implemented as class in Tkinter. Each of the widget has a constructor, destructor, i aris widgets are given in Table 15.1. , set of methods and properties. The ¥ Button Creates button and used to execute a command, Canvas Us ; en sed to draw graphs and plots, Creates graphics editor and implements custom widgets. yutton Clicking the button, toggles between the values, “Entry A text entry field also called text box. Frame, Container widget that can hold other widgets, 4 Label Displays text or an image. gut Python Programming using Tkinter 388 iaget Class Description iisbox Displays a list of alternatives. z i enw ‘ menu pane is used to implement pull-down and pop-up menus. Menubutton mana {s used to implement pull-down menus. sage Displays at Message plays a text. It is similar to the label widget, but can automatically wrap text to a given width or aspect ratio, jadiobutton Clicking the buttot ane ce puiton set the variable to that value, and cleus ll ther radjobuttons associated Displ. Text oc oe formatted text. Allows to display and edit text with various styles and attributes. oe les scrolling functionality to supporting widgets such as Text, Canvas, Listbox and Entry. oF Allows to select numerical values by dragging a slider. Table 15.1 Tkinter Widget Class All . oo widgets are derived from the Widget class. Apart from the methods inherited from the ee - is ie 7 ca oe bine has distinct options and methods suitable for configuration of particular fables 15.2 and 15.3 describe the common opti ae options and common methods present Option Value Effect igoreground) Color ‘Changes the foreground color. Color can be specified using RGB values or using predefined keywords. bgtbackground) Color Changes the background color. Color can be specified using RGB values or using predefined keywords. bd (border width) _ Integer ‘Specifies the width of the widget border Specifies which method isto be executed when the widget is selected Command Callback type Font Fonttype Specifies the font used by the widget. Often represented in 2 tuple (family, size, weight) padx, pady_ Integer Specifies the width between the current widget and the neighboring widgets. Text String Specifies the text appearing on the widget at run time Table 15.2. Widget common options Interface Return Type Effect Creates an instance of this widget using the given options. Widgetclass(master, “kwargs, -) Sting : ° rent value of the specified option. get(option) Returns the curt configuretiwargs,-) “Configures options forthe widget, Keys) — Returns @ list of all options that are available within the particular widget. Table 15.3. Widget common methods Each one of the above widgets, when instantiated, don't immediately appear on the screen. Geometric sje on the screen. ‘Managers (pack, grid and place) have to be called in order to make the widgets visib! * Programming and Problem Solving with Python Therefore, Tkinter widgets not only provide a tool to build a graphical interface but they also alloy Programmer to create a fully functional application. 15.4 THE LABEL WIDGET The label widget isa standard Tkinter widget used to display a text or image onto the screen. Itcan display multiple lines of text onto the screen in a single font. In addition, one character in text can be underlined, indicating keyboard shortcut. It is a passive widget, ie, it does not support any interaction with the user nor it has any event handler function associated with it. The syntax to create Label widget is as follows: Syntax Label (ref_parent_ iget, **kwargs) where **kwargs isa dictionary with optional values. Inthe above syntax, the first argument is a reference to parent widget. The text argument is used to di: the text. Label widget also provides the following options to configure the label mentioned in Table 15.4. Option Background Anchor Controls how the text within the label should be placed. Use one of N, NE, E, SE, S, SW, W. NW, or CENTER. By default anchor is CENTER. ss Justify Defines how to align multiple lines of text. Use LEFT, RIGHT ot CENTER. _ Image The image to display in the widget. If specified, this takes precedence over the text and bitmap spans, : e Bitmap __ Specifies the bitmap to be displayed by the widget. Ifthe image option is given, this option is ignored. Table 15.4 Label configuration options Program 15.2 demonstrates the use of Label class to create the Label widget. Program 15.2 Create label widget and display the text "Hello WorldiIl!" import tkinter as TK mport all definitio: Programming and Problem Solving with Py, Ima Font name and size an Image to be placed instead of text Event handler function to be called when clicked For butons, only the function name shouldbe used, Using function cll suchas functonargument wil not work Program 15.4 demonstrates the use of Button widgets for creating multiple buttons. Program 15.4 Create multiple buttons by making use of the Button widget. import tkinter as TK # Import all definitions from Tkinter Foot = TK.Tk() # Create drawing window bl = TK.Button(root, text = "Ok") b2 = TK.Button(root, {"text": "Cancel"}) bl.pack() # Pack button 1 to parent b2.pack() # Pack button 2 to parent root.mainloop() Explanation In the above program, we have created two buttons bl and b2. The class Button takes the parent window as the first argument while rest of the arguments are optional and are passed as keyword as argument, 15.6 TKINTER PROCESSING EVENTS - CALLBACKS In the above examples, we have learnt how to add common widgets such as labels and buttons to S screen. But just adding widgets on to the screen will not make the widgets functional. Thus, it — the question of how to make the widgets more functional? Making widgets functonal caro them more responsive such as performing action on pressing of a button or Pressing of es kyo 2 or performing actions on a mouse click. The Button widget is a good way eres i a event-driven programming, so we will make use of Button widget to demonst ona click ofa button. GUI Python Programming using Tkinter - Adding functionality to a button is called command binding. The syntax to tigger a function on a patticular event is as follows: syntax putton(ref_parent_widget, command = Name_of Function) Here ‘Name of function’ is a user-defined function definition which is to be Processed on trigger of a particular event. All such functions are bound to the buttons when the buttons are created. These fenctions are known as “Callback” functions or “handlers'. Program 15.5 demonstrates action to be performed on a click of a button by making use of ‘command’ option Present within the Button widget. Program 15.5 Create a ‘Ok’ button. When the button is clicked, it should print out "Ok Button is clicked". import tkinter as TK # Import all definitions from Tkinter def functionOk(): print("Ok Button is clicked") root = TK.Tk() # Create drawing window butOk = TK.Button(root, text = "Ok", command = functionOk) butOk.pack() root.mainloop() Output output is displayed on to the terminal. Explanation In the above program, we have created button “OK" and defined thefunction "sunction0k”. The line Ok", command = functionOk) butok = TK.Button(root, text 1." which will be called when the button is clicked. binds the “OK" button to the function "funct iono! Era ee csofobfecrodenied oe The above program can also be written as follows by using tl 370 programming and Problem Solving with Python vox’ button. When the butt Program 15.6 Using concepts of object-oriented programming, create a ‘Ok’ bu : is clicked, it should Print out "Ok Button is clicked" import tkinter as TK class ButtonEventHandler: def init__(self): mae Sane putton(root, text = "Ok", command = self.functionok) elf. . self.butOk.pack() root.mainloop() def functionOk(self): eee print("Ok Button is clicked") if _name_ == "_main_": ButtonEventHandler() Output on press of "OK" button the following ee 5 Sy wos fe Ok button is clicked Explanation The program defines a class for creating GUI in the is a method within the class "ButtonEventHandler". So it is called by self. functionOk. 15.7. THE CHECKBUTTON WIDGET ‘The checkbutton widget is a standard Tkinter ‘widget used to implement on-off selections. It consists of a small box that can either contain a check mark or not. There isa label associated with each check box. Youcan chan the state of the check box by clicking on it. You can also associate a Python function or method ee button. When the button is pressed, Tkinter automatically calls that function or method, Each Chee widget should be associated with a variable. The syntax to create the simple checkbox is as follows: Syntax Checkbutton(ref_parent_widget, text = value, variable = value, other option = value, command = name_of_function) GUI Python Programming using Tkinter a Other than common features, t CheckButton has following other methods and features present and they are described in Table 15.5. Options Supported by Checkbutt options Suppo by chectbaton wage Command A function that i called when the button is pressed. text The text associated with each button Offvalue The value corresponds to a non-checked or checked button, Tespectively. Defaults are O and | Onvalue Variable__Associates a Tkinter variable to the button. When the button is pressed, the variable is set to the value. Methods Supported by CheckButton Widget Select) Selects the button deselect) —_Deselects the button. Invoke) _Calls the function, associated with the button, toggle) ‘Toggles the selected state, ie, clears if set, sets it if cleared. Table 15.5 Methods and different options of CheckButton widget Program 15.7 demonstrates creating two simple check box buttons. Program 15.7 Create two simple check-boxes, "Python Programming’ and "R Programming? import tkinter as TK # Import all definitions from Tkinter root = TK.Tk() # Create drawing window cl = TK.Checkbutton(root, text = "Python Programming") 2 = TK.Checkbutton(root, text = "R Programming") cl.pack() c2.pack() root.mainloop() Output area eeeiog I Python Programming TF RProgramming 15.7.1 Handling Checkbuttons ton is selected or deselected, an event is generated, It ‘whether the checkbutton was selected or desel of each button, the event is triggered and hand! Each time a checkbut the event (for example, checkbuttons. On click Contains the information about lected). Program 15.8 creates two led through command option of reckby checkbutton is displayed oo the status is updated "*ogtamming and problem Solving with Python Wie’ initial state of the checkb dF, ate of the cl Uuttons Ach time you change the state of a checkbos Pon clicking them, display theig status, class CheckBut tonClickEvent; def _init (seis); * Initializing Tkinter Foot = TK.Tk() ‘9 Plank Tcl variables | TK.Intvar() TK.Intvar() * Creating buttons ol * TK-Checkbuttoniroot, text « "Python Programming" roe opie S8lt.vaxi,f commana'e Self.boxl details) 3K-Checkbutton(root, tent = R Programming", Sei aS eh colt vero aemare te self.box2_details) # Packing buttons for display e cl.pack() c2-pack() * Executing mainloop Foot.mainloop() Get boxl_detaiis (seis); Print("You have clicked on python Programming" F Self-varl.get() retrives the value oF the created variable, Print("Current value of the check button: ") self.vari.get()) def box2_details(se1fy: Brinc("You have clicked on R Programming") f Selfwvar2.get() retrives the value of the created variable. print("Current value of the check button self.var2.get()) ‘ {Pame__is the name of the Python script sent to the interpreter : # "main is the instance loaded in memory when Python is executed. if name == "main CheckButtonClickEvent () Output #Initial i os T Python Programming T Programming GUI Python p, rogramming using Tkinter —— 373 oat poubeurier Click of checkbutton nena Ci [oss F Python Programming F Programming You have clicked on Python Programming current value of the CheckButton: 1 You have clicked on R Programming Current value of the CheckButton: 1 Explanation In the above program, we have created two check buttons, ie, "Python Programming" and “R Programming’. On click of each of the checkbutton, the respective functions are called. The functions display the status of the buttons through get() method. The lines self.varl = TK.tntVar() and sei var2 = TK.IntVar() are used to keep track about the value of check button. By default the initial values of check buttons are set to 0. 15.8 THE RADIOBUTTON WIDGET Radio buttons are also known as “Option buttons’. The radio buttons are used in groups. Only one radio button can be selected at a time. When the user selects another button in the same group, then the previously selected button in the group is automatically deselected. With respect to appearance, a radio button contains a circle that is either filied (if selected) or blank (if not selected). The following is the syntax used to create the radio button. It is a good programming habit to consider radio buttons as returning a single value, and hence it is better to add them to a class. Syntax Radiobutton(parent_widget, text = value, variable = value, command = name_of_function, other_option = value) Other than common features, radio button has the following other methods and features present and they are described in Table 15.6. ‘Options Supported by Radiobutton widget ‘command “A function that is called when the button is pressed. ac umaarl text ‘The text associated with each button. book ‘Value is assigned to the associated variable when the button is pressed. variable ‘Associates a Tkinter variable to the button. When the button is pressed, the variable is set to the value, ttn (Conta) a 1m Solving with Python programming and Proble OO — i ree ‘Methods Supported by Radiobutton Widge select() Select the button, deselect() Deselects the button. invoke) Calls the function associated with the button. Table 15.6 Methods and features supported by RadioButton Program 15.9 demonstrates creating multiple radio buttons. Programs 15.9 Write a program to create radio buttons. import tkinter as TK class RadioButtonDemo: def __init_ (self): ¥ Exposing the root window outside the class, for other classes to # interact with it self.root = TK.Tk() self.var = TK.IntVar() cl = TK.Radiobutton(self.root, text value = 1000) c2 = TK.Radiobutton(self.root, text = value = 10000) c3 = TK.Radiobutton(self.root, text = value = 3000) conomy Class", variable = self.var, irst Class", variable = self.var, "Business Class", variable = self.var, # Packing buttons for di cl.pack() c2.pack() c3.pack() # Displaying, and running mainloop self.root.mainloop() if _name__ =: Main RadioButtonDemo() Output ¢ tk oo | © Economy Class © First Class © Business Class 374 Programming and Problem Soving yay on select() deselect() invoke() ‘Methods Supported by Radiobutton Widget Select the button. Deselects the button. Calls the function associated with the button. Table 15.6 Methods and features supported by RadioButton Program 15.9 demonstrates creating multiple radio buttons. Programs 15.9 Write a program to create radio buttons. def Output Ok import tkinter as TK class RadioButtonDem: if _name_ == RadioButtonDemo() init__(self): # Exposing the root window outside the class, for other classes te # interact with it self.root = TK.Tk() self.var = TK.IntVar() cl = Tk.Radiobutton(self.root, text = "Economy Class", variable = se} value = 1000) 2 = TK.Radiobutton(self.root, text = "First Class", variable = sel£.var, value = 10000) c3 = TK.Radiobutton(self.root, text = “Business Class", value = 3000) fwvar, '» variable = self.var, # Packing buttons for display cl.pack() ©2.pack() ¢3.pack() * Displaying, and running mainloop self.root mainloop() “main om oe © Economy Class © First Class © Business Class Soy GUI Python Programming using Tkinter ” 15.9 FRAME — THE CONTAINER WIDGET The Tkinter module supplies wid a rectangular area on th only purpose is to cont; Syntax igets whose purpose is to contain other widgets. The class Frame represents screen contained at top level window ot contained in other frames. The frames’ ain the other widget. The syntax to create frame is as follows: Frame(ref_parent_widget, **options) “options isa Keyword argument. Keyword arguments are optional, and ‘when invoking the Frame function, the following statement can be used be added tothe arguments a a dictionary For example, Frame(parent_widget, ("property": "opt ion™}) When defining functions or classes that take Keyword arguments, the convention i to use “*kwargs as the last argument Program 15.10 demonstrates how we can create the frame and Place it on the drawing board, Program 15.10 Write a program to create a frame and add a label "Welcome to Programming!" to the frame. import tkinter as TK class AddFrameDemo: def _init_ (self): # Create window instance window = TK.Tk() | # Set window title | window.title("Adding a Frame") # Creating and adding a frame framel = TK.Frame (window) framel.pack() # Adding label self.1bl = TK.Label(framel, text self.1bl.pack() "Welcome to Programming") # Executing event loop for window window.mainloop() = "_ main # Executing the class AddFrameDemo() Output if _name_ ¢ Adding Frame - o x Welcome to Programminglt! 378 progtamming and Problem Solving with Phy, 15.10 ENTRY WIDGET Entry widget allows user to type and edit single line of text. In tkinter, typically ie Jn ren pox is called Entry widget, But asa programmer if you want to add multiple Hines of ext that can 0 ef © EN £0 aheag with Text widget explained in the following section. The following syntax is us TY widget, Syntax Entry(ref_parent_widget, **kwargs) Example: #create a window i : fCreate Entry widget, i.e., Single line te #Create an event loop | Other than common features (Tables 15.2 and 15.3), entry widget has following other methods and features present and they are described in Table 157. Options Supported by Entry widget show Displays the content of the widget. Ifnon empty, then it displays a string of characters. You can make use of "to geta password entry widget. state state = NORMAL responds to keyboard and mouse event. state = DISABLED will not respond to keyboard and mouse event. State = DISABLED will not respond to keyboard and mouse event, Methods Supported by Entry Widget = gett) Gets the contents from the entry widgets. insert(index, text) Inserts text at the given index, delete(index!, index2 = None) Deletes text starting at the position after index1. If only index! is used, it ee single character. Ifindex2 is used, it deletes characters from index! to before index? String indices start from zero. Table 15.7 Options and features supported by Entry widget In the above example, we have written simple lines of code to create a simple entry box and display iton to the window. Program 15.11 creates an entry widget and displays the contents of the widget oe the console. GUL Pyth Python Programming using Tkinter Explanati aa hes In the above Program, we have created label, button and one entry widget. On click of ae Aes ‘unction "Change Label" is called. The line within the function seif.1abel ("text") ON"=¥-3E“O, fetches the text present in entry widget and changes the content of the label, 15.11 TEXT WIDGET Text widgets are a much more generalised method for handling multiple lines of text th: By making use of text widget you can mix text in different fonts, colors and si: widgets, i.e, you can intersperse, embedded images with text. As an image, it is Following is the syntax to create the text widget. Syntax Text(ref_parent_widget, **options) 379 an the Label widget izes. You can add embedded treated asa single character, Other than common features (Tables 15.2 and 15.3), text widget has other methods and features, Table 15.8 covers the most important methods and features supported by text widget. Options supported by Text Widget 3 ‘The 3D appearance of the text widget. The default is SUNKEN j spacing 1, This option specifies how much extra vertical space is put above each line of text. If spacing 2, a line wraps, this space is added only before the first line it occupies on the display. spacing 3, Default is 0. : _ state Text widget responds to keyboard and mouse events. In order to support this behavior, the state option is set to NORMAL as parameter, If you set state option to DISABLED then text widget wil not respond to keyboard. __. and mouse events. j xscrolleommand Option xscrollcommand = horizontal is used to make the text widget horizontally scrollable, Similarly, xscrollcommand - vertical isusedtomake the ext widget vertically scrollable. : ) ‘word that will ft wrap Option wrap = WORD will break the line after the last By default wrap is set to CHAR, Le, any line thatis too long will breakatany character ‘Methods supported by Text widget —, then only one character deletelindext, index2 = None) Deletes text starting just after index!.Ifonly index! is given Is deleted, If index2 is specified then the deletion of character proceeds but not i i _». deletes the character after index 2, si getlinde: x2 = None) Retrieves the text from the widget. Ifonly index! is provided then only one c eee you provide second index then you will get the text between the indexes. Table 15.8 Features and methods supported by Text widget on 380 class Createnotepa: def _init_(selg # Create a window instan window = TK.Tk() window.title("Notepaa") # Create a frame instance self.frame_1 = TK.Frame(window) self.frame_1.pack() # Create a Label instance self.label = TX.Label. self.label.pack() # Create a text-bo: # Height and width me. self.txt = TK.Text(sel£ self.txt.pack() # Instantiate the window window.mainloop() ce and set a title (self.frame_1, (text “fou can write here.m) if name ==" main CreateNotepad() welcome to pychon GUT ‘time to interact with you. lbyehon Programmes, Explanation In the above program we have created a frame and add rd. The line : tae ("height": 24, “width' led one label and Text widget on to 80, "wrap"; TK.WORD}) ed to create text widget of size 24 * 80. The option wrap = TK WORD is used to break the line after isus the last word that will fit. 15.12 THE LISTBOX WIDGET : lection. list of items in an application form, from which user can make a se ‘A Listbox estes sid allies net have tune fork colot. The following syntax is used 0 tains only tex cm a a the listbox widget inside a root crea GuTFython Programming using Tkintey one 381 Listbox(ref_paren Eaent window, **9p¢ ions) Other than commo; n feat described in Table 15,9. '°® listbox has following other methods and features present and they are Cee z Values Effect of Options ae {int value Number of items in listbox. Selectmode SINGLE. MULTIPLE, Determines how many items can be selected. Default is BROWSE. Use EXTENDED, baa to get checklist behavior. EXTENDED if the user usually , Selects one item but sometime would like to select or Bowe mec yne or more ranges ommal ‘ xscrollet ind Scrolls listbox horizontally. You can make use of set() method of scrollbar to link listbox widget to a horizontal scrollbar, yscrollcommand Scrolls listbox vertically. You can make use of .set() method of scrollbar to link listbox widget to a vertical scrollbar. ‘Methods Supported by listbox widget ‘Method Name Description delete(index) Deletes one or tore items, Use delete(0, END) to delete all items of the list. delete(first, last) getinden) Gets one or more items from thelist Use get(0, END) to get alist of al tems inthe list. Tg make the listbox vertically scrolabe ser the command option ofthe associated vert scrollbar to this method. Table 15.9. Listbox ~ Methods and Options As discussed in the above table, in Program 15.14 we will first create listbox and by making use of s discus: h insert () function will insert the items into the listbox. jes ina list-box Program 15.14 Write a program to insert three countries in a lis (Contd.)

You might also like