Change command Method for Tkinter Button in Python

The Button widget in Tkinter is crucial for handling events and performing operations in GUI applications. Sometimes you need to change what a button does after it's been created and displayed.

To change a button's command method after initialization, use the configure() method. This allows you to reassign the button's functionality dynamically during program execution.

Syntax

button.configure(command=new_function)

Example

Here's a complete example showing how to change a button's command method ?

# 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 window
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()

How It Works

The program demonstrates a two-stage button behavior:

  • First click: Executes text_label() function which displays a label and reconfigures the button
  • Second click: Executes close_win() function which closes the application

Output

Initially, the window displays a single button ?

Click Initial Window

After the first click, a label appears and the button's function changes ?

Click Woohoo! An Event has occurred! After First Click

Clicking the button a second time will close the application window.

Key Points

  • Use configure(command=function_name) to change button behavior
  • The new command function should be defined before reconfiguring
  • This technique is useful for multi-step workflows or state-dependent operations

Conclusion

The configure() method provides flexibility to change button commands dynamically. This technique is valuable for creating interactive applications with context-dependent button behaviors.

Updated on: 2026-03-25T18:52:27+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements