Tkinter Widgets

Button Widget

The Button is a tkinter class that the user can view and interact with. We will explain the function of the Button class by writing a program using the Button class. 

The Buttons are tkinter widgets that do something when they are clicked using the mouse or by pressing a key (RETURN, UP/DOWN arrow key, etc.). The buttons normally have text written on them.

We will do the button programming in two steps.  The first program will create button tkinter widget that will not do anything when it is clicked. 

Next, we will modify the program to make the button change its color when you click it. As explained earlier, all tkinter widgets have certain methods (functions) associated with them.  We will use a method to cause the button to change its color when clicked by the mouse. Below is a static Button program that displays a button with the text “Example Button”.

PROGRAM EXAMPLE: BUTTON WIDGET (STATIC)
>>> from tkinter import *               	# 1)
>>> root = Tk()                                 # 2)
>>> frame1 = Frame(root)                   	# 3)
>>> frame1.pack()                               # 4)
>>> btn = Button(frame1, text = 'Example Button', bg = 'lightgreen')  # 5)
>>> btn.pack()                                  # 6)
>>> root.mainloop                               # 7)

You will see a small window with a light green button when you run this program.  It is a static button. Nothing will happen if you click on it with a mouse.

A later program will add a method (function). This method will make the button do something when you click on it.

Tkinter Widgets Button with Text Procedural Programming
Tkinter_Button Widget With Text Procedural Programming

Detailed line-by-line Explanation of the Program:

  1. This step is the same as the Label program done earlier.
  2. This step is the same as the Label program done earlier.
    • frame1 = Frame(root) In this step, we create an instance of the container Frame. This statement names this instance ‘frame1’and associates it with the ‘top’ level (root).
    • The “frame1” instance is a child of the parent “root”. As described earlier, the Frame class is a container widget used to put other widgets like buttons inside it in the application program’s layout. In the following steps, we will put our button widget in the container called “frame1”.
  3. frame1.pack() This statement runs the pack() method on “frame1” object instance.   The bigger window you saw after step 2) will become small and will show just the window heading, maximize, minimize, and close icons.
  4. btn = Button(frame1, text = ‘Example Button’, bg = ‘lightgreen’).
    • This statement creates an instance of Button class and names it “btn”.
    • The parenthesis has three parameters to define the attributes of the ‘btn’ widget. 
      • The first parameter always needs to be the parent (in this case, it is “frame1”). Thus, the “btn” instance is a child of parent “frame1”.
      • The second parameter is the text to be displayed on the button. (“Example Button” in this case).
      • The third parameter is the background color of the button. We chose the “lightgreen” option for this parameter. 
  5. btn.pack() We run the pack() method on object “btn” The button will shrink or expand to the size of the text.
  6. root.mainloop
    • Finally, we run the event loop. The mainloop runs continuously watching for events.  In this program, we do not have any events, so the event loop will keep on running until stopped by the user.  Clicking the button with a mouse will not do anything.

Button Tkinter Widget With Events

When a program needs user input, it displays a dialog box on the screen. The dialog box is meant to request inputs from the user. The program is expecting the user to click on a button such as “OK”, “Cancel”, etc.

The program we have written so far displays a button on the screen, but it does not do anything if you click on it.

This section will develop programs that display buttons that do something when they are clicked. These programs use the events to make the buttons respond to user input. We introduced the concept of events in the Tkinter Graphical Programming chapter.

The action of clicking a mouse button or pressing a keyboard key is called an event.

We also saw in the Tkinter Graphical Programming chapter that we need to bind the event, event handler, and widget to enable the application to respond to external events. 

In this section, we will write an application (an event handler) that responds to external events like mouse clicks.

Button Widget Program Event Handler

The following program example is a Button class tkinter widget program using events. The button will do something interesting when clicked.

 This program is a modification of the Button program from the previous section.

The functionality of the program is”

  • The Button widget will change the color of the button from light green to red when clicked.
  • When the Button widget is clicked again, the button widget will go back to its original light green color.

To achieve the above program feature, we will define a function and name it “changeColor”.  This function’s code tests if the button widget’s color is light green. If it is light green, it changes the button widget’s color to red, when clicked.

The following program is the same as the previous program, except for the addition of the “command” keyword parameter in the statement that creates an instance object of the Button class. The “command” parameter calls the function “changeColor”, which handles the mouse click event.

After you have run this program, click on the button and watch its color change from light green to red.

PROGRAM EXAMPLE: BUTTON WIDGET WITH EVENT
>>> # Define a function ‘changeColor’ that tests if the button widget is light green. 
>>> # If it is light green, then change the color of the button to red, if clicked.
>>> def changeColor():				#0
	if btn["background"] == "lightgreen":
		btn["background"] = "red"
	else:
		btn["background"] = "lightgreen"

		
>>> from tkinter import *                      # 1
>>> root = Tk()                                # 2
>>> frame1 = Frame(root)                       # 3
>>> frame1.pack()                              # 4
>>>
>>> btn = Button(frame1, text = 'Example Button', bg = 'lightgreen', command = changeColor) #5
>>> btn.pack()                                 # 6
>>> root.mainloop()                            # 7

Detailed line-by-line Explanation of the Program:

Step 0)

  • We define a function and name it “changeColor”.
  • Its functionality is:
    • if the Button widget is light green, it changes to red when clicked, else it stays light green.
    • We call this function.in step 5.

Steps 1) through step 4) are the same as in the earlier Button program.

Step 5) btn = Button(frame1, text = 'Example Button', bg = 'lightgreen', command = changeColor)

  • This statement is the same as in the previous program, except for the addition of the parameter ‘command = changeColor’. This command handles the mouse click event when the button ‘btn’ is clicked.

Developing Tkinter Widgets GUI using Class, Objects and Methods

The focus of this section is to apply the techniques we learned in the Object Oriented Programming chapter to develop Tkinter widgets UI programs.

We will modify the Button widget programs from the previous section to incorporate the Classes, Objects, and Methods techniques from the Object-Oriented Programming chapter.

Object-Oriented Programming based programs are said to have a ‘class structure’. The technique using the class structure is called Structured Programming.

Why use Structured Programming?

 Structured programming is necessary for programs that are large and complex. The programs using ‘class structure’ can be maintained better and debugged easier in case of errors.

The program below has the same functionality as the Button Widget program we wrote earlier but it uses structured programming techniques from the Object Oriented Programming Chapter.  We will explain the details of how the program with class structure works below.

PROGRAM EXAMPLE: BUTTON EXAMPLE USING CLASS STRUCTURE
>>> from tkinter import *	           # 1
>>> root = Tk()				   # 2
>>> class buttonApp:			   # 3
	def __init__(self, root):	   # 4
		self.frame1 = Frame(root)  # 5
		self.frame1.pack()	   # 6
		self.btn = Button(self.frame1, text = 'Example Button', bg = 'lightgreen') #7
		self.btn.pack()		   # 8

		
>>> app = buttonApp(root)		   # 9
>>> root.mainloop()                        # 10

Detailed line-by-line Program Explanation of Tkinter Widgets (Static Button) Using the class Structure:

  1. Step 1) is the same as in all previous tkinter application programs
  2. Step 2) is the same as in all previous tkinter application programs
  3. class buttonApp:
    • This line of code defines a class method and names it “buttonApp”.
  4. def __init__(self, root):
    • This line of code defines the initializer method (__init__) followed by two class attributes (“self” and “root”). 
    • Note the use of the “self” parameter. The __init__ method can have several parameters, but the “self” parameter is required and must be the first one.  The second parameter “root” is the top-level container in which we will put the container “frame1”
  5. self.frame1 = Frame(root) This line of code creates an instance of widget Frame and names it “frame1”. The instance “frame1” is an object of class Frame.
  6. self.frame1.pack() This line uses pack() method on object “frame1”.
  7. self.btn = Button(self.frame1, text = 'Example Button', bg = 'lightgreen')
    • This line of code creates an instance of the widget class “Button” and names it “btn”. 
    • The object “btn” is a child of the parent “frame1”.
    • The first parameter within the parenthesis MUST be the parent (“frame1” in this case).
    • The other parameter in the parenthesis is the keywords text, which specifies what you want to write on the button.
    • The second keyword is bg which specifies the color of the background of the button (in this case we select ‘lightgreen’). 
    • There are many other parameter options available like foreground (fg), etc., which we are not using in this example.
  8. self.btn.pack()
    • Run the pack() method on the object “btn”. The pack() method adjusts the button size to conform to the width and height of the text we wrote in step 7.
  9. app = buttonApp(root)
    • This step creates an instance of the class “buttonApp” that we defined in step 3).  The instance is named “app”.
  10. root.mainloop()
    • Run mainloop() method on object “root”.  

Button Events GUI using Class, Object, and Method

In the Button Widgets With Event section earlier in this chapter, we wrote an application that responds to external events like mouse clicks.

Let’s modify the Button Widget With Events program to make it structured using the class, object, and methods techniques.

The button will respond to events (mouse clicks) using the Event handler that we will define in the program.

To recap….

Event Handler Routines: The Event Handler responds to the events as they occur. For the application to respond to the events, the GUI needs to have an event handler routine that will do the work that we want the GUI to do.

The event handler routine contains the code that takes the action that we want the GUI to take. When an event occurs, the event handler, which is part of the app responds to the event.  The Event Handler is a method.

Binding: We introduced the concept of binding earlier in the chapter. For the event handler routine to perform the actions that the GUI needs to do, we must associate the event handler with the widget and the event. The process of associating these three is called binding.

The bind() method associates the event handler routines with the widget and the event.  The syntax for bind() method is:

>>> Widget_name.bind(event_type_name, event_handler_name)

The program below illustrates the use of event handlers and binding to handle mouse events using the class structure.

How to Code class Structure Programs with Event Handlers in Tkinter Widgets Programs

This section explains the underlying theory for writing class structure programs with Event Handlers. These programs respond to the user-initiated mouse clicks using the class structure

The explanation in this section uses the lines in the program below.

Any class structure program that handles mouse-initiated events needs to create a class.

The program first creates a class called “changeColorApp” that defines two functions. The class defines a method for what GUI should do.

The “changeColorAppclass defines two functions:

1) def __init__(self, root):

  • The __init__ method creates a container called “frm”. The instance “frm” is a child of the parent “root.
  • Secondly, it creates an instance of the class Button and names it “btn”. The object “btn” is a child of the parent “frm”.
  • This method defines what the GUI should do.  The initializer method (__init__) has two class attributes “self” and “root”. 
  • As noted earlier, the “self” parameter is required and must be the first one in the parameter list.  The second parameter “root” is the top-level container, in which we will put the container named “frm”. (Refer to the program below for the “frm” container.
  • The  __init__ method first creates an instance of Frame class and names it “frm”.  In the program example below “frm” is a child of parent “root”.
  • This method then creates an instance of Button widget (named “btn”).  This instance “btn” is  a child of parent “frm”.
  • In this step, we also use keyword parameters text (to show the text on the button). The text on the button will read ‘Button Example’. The second keyword parameter is ‘bg’ to set the button background color to light green.
  • The  __init__ method  binds the “btn” object to the event <Button_1> and event handler “mouseLeftClick” defined below.

2) mouseLeftClick(self, event):

  • The second function in the classcolorChangeApp” is the event handler function named “mouseLeftClick”.  This function checks if the button’s background color is “lightgreen”, if so, it turns the background to “red” when the mouse is clicked on the button.
  • The mouseLeftClick function defines an EVENT as the left mouse button click and binds the left mouse button click to the object button “btn”.
  • The keyword for the left-mouse button event is “<Button-1>“.
  • <Button-1>” is the event type name. We bind the left-mouse button click Event type name “<Button-1>” to the Event Handler routine “self.mouseLeftClick” and the Button widget instance “btn“. 

The syntax for the bind() method is:

Widget_name.bind(event_type_name, event_handler_name)

So, our bind statement is:

>>> btn.bind(‘<Button-1>’, self.mouseLeftClick)

See Table for mouse clicks event type names (Table: Mouse Button Event Types for Widgets) in the following section.

Below is the complete program with an explanation of each code line at the end.

PROGRAM EXAMPLE: BUTTON EVENTS (STRUCTURED PROGRAMMING)
>>> from tkinter import *			# 1)
>>> root = Tk()					# 2)
>>> class changeColorApp:			# 3)
>>> # Define a method for what GUI should do    # 4)
	def __init__(self, root):      
		self.frm = Frame(root) # Top level frame (root)			# 5)
		self.frm.pack()			# 6)
		self.btn = Button(self.frm, text = 'Button Example', bg = 'lightgreen')  # 7) 
>>> # Create instance of class Button and name it ‘btn’. 
		self.btn.pack()			# 8)
		self.btn.bind('<Button-1>', self.mouseLeftClick)  #9) 
>>> # Define the EVENT as the left mouse button click 
>>> # and bind left mouse button click to object button (btn).

	def mouseLeftClick(self, event):    	#10) 
>>> # Mouse left click Event Handler defines what it should do.
		if self.btn["background"] == "lightgreen": #11)
			self.btn["background"] = "red"
		else:
			self.btn["background"] = "lightgreen"

			
>>> testChangeColorPgm = changeColorApp(root) #12) 
>>> # Create an instance of class ‘changeColorApp’ 
>>> root.mainloop()    			      #13) 
>>> # Run mainloop() method on object ‘root’.

If you run this program, you will see the following frame with a light green button inside with the text “Button Example”. If you click on the button, the button color will change to red.

Tkinter Widgets Button with Text and Event Handling - Class Structure
Tkinter_Button_Widget with Text and Event Handling
Class Structure Program Result

Detailed Line-by-line Explanation of Button Tkinter Widgets Program Using class Structure:

Steps 1) through 8) are the same as in the program with class structure.

Step 9: self.btn.bind('<Button-1>', self.mouseLeftClick)

  • This statement binds the object “btn” with the left-mouse button press event “<Button-1” , and the event handler “mouseLeftClick”

Step 10: def mouseLeftClick(self, event):

  • In this step, we define a function ‘mouseLeftClick’ (Event Handler) for the left-mouse click event.

Step 11: if self.btn[“background”] == “lightgreen”: self.btn[“background”] = “red” else: self.btn[“background”] = “lightgreen”

  • This section of the code is the logic of the event handler.

Step 12: testChangeColorPgm = changeColorApp(root)

  • We create an instance of the class “changeColorApp” and name it testChangeColorPgm.

Step 13: root.mainloop()

  • Run the “changeColorApp” method on ‘root’.
  • mainloop() runs the application continuously until closed by the user.  This step is common to all programs we write.

Table: Mouse Button Event Types for Tkinter Widgets

The following are the mouse events that the tkinter widgets respond to.
EVENT TYPE NAMEDESCRIPTION
<Button-1>Left Mouse Button Pressed
<Button-2>Middle Mouse Button Pressed
<Button-3>Right Mouse Button Pressed
<Button-4>Scroll up using Mouse Wheel
<Button-5>Scroll down using Mouse Wheel
Mouse Button Event Types

Below is another simple program for the Button widget using class and object structured programming.

PROGRAM EXAMPLE: SIMPLE BUTTON WIDGET PROGRAM USING CLASS STRUCTURE
>>> from tkinter import * 
>>> class App:                                #1)
	def __init__(self, top): #2)  __init__ method to define GUI look
		self.cntnr = Frame(top)      #2)
		self.cntnr.pack()
		self.btn1 = Button(self.cntnr, text = 'Hello!', bg = 'green')
		self.btn1.pack()             #3)

		
>>> root = Tk()
>>> application = App(root) # Create instance of class App
>>> root.mainloop()

Copy and run this program. You will see the following GUI on your screen.

Tininter Button Widget Class Structure Simple Program

Detailed Line-by-line Explanation of the Button Tkinter Widget ProgramUsing class Structure:

Step 1): class App:

  • This line of code defines a class method and names it “App”.

Step 2): def __init__(self, root):

  • This line of code defines the initializer method (__init__) that has two class attributes (“self” and “root”). 
  • Note the use of the “self” parameter. The __init__ method can have several parameters, but the “self” parameter is required and must be the first one.  The second parameter “root” is the top-level container in which we will put the container “frame1”

Step 2): self.cntnr = Frame(top) _

  • Create an instance of the Frame class and name it “top” and associate it with the object “top”. The instance “cntnr” is a child of parent “top”.

Stap 3) self.btn1 = Button(self.cntnr, text = ‘Hello!’, bg = ‘green’)

  • Create a instance of the class Button and name it “btn1”.
  • This statement adds ‘btn1’ attributes text “Hello!” and background color “green”.

Copyright © 2019 – 2021 softwareprogramming4kids.com

All Rights Reserved

Verified by MonsterInsights