Change command Method for Tkinter Button in Python

TkinterServer Side ProgrammingProgrammingPython

The significance of Button widget is that it is used for handling events to perform certain operations in the application. In order to handle such events, we generally define a method which contains certain operations.

Let us suppose we want to change the event method after initializing the button. We can configure the Button and its handler using configure(options) method. Thus, by defining a new method and configuring the button we can trigger a new event with the same button.

Example

#Import tkinter library
from tkinter import *

#Create an instance of tkinter frame
win = Tk()

#Set the geometry
win.geometry("750x250")
#Define a function to show the text label
def text_label():
   Label(win, text= "Woohoo! An Event has occurred!", font= ('Helvetica 10 bold')).pack(pady=20)

   #Configure the Button to trigger a new event
   button.configure(command= close_win)
#Define a function to close the event
def close_win():
   win.destroy()
#Create a Button widget
button= Button(win, text= "Click", font= ('Helvetica 10 bold'), command= text_label)
button.pack(side= TOP)
win.mainloop()

Output

Running the above code will display a window that contains a button.

When the Button is pressed for the first time, it will display a text label.

Now click the button for a second time and it will terminate the TCL interpreter.

raja
Published on 15-Apr-2021 13:10:17
Advertisements