Javaexercise.com

How To Pass Arguments to Tkinter Button Command

To pass an argument to the Python Tkinter Button command, Python provides two ways: partial() and lambda function. We can use any of these as per the need. 

While working with Tkinter Button, we can set its height, width, text, etc, but along with all these Tkinter Button provides one more argument command that can be used to pass value/argument based on some event like click.

Let's get started with some examples. 

 

Pass argument to Tkinter Button Command using partial() method

We can use the partial() method of functools module in Python to pass argument or value to the button. The Tkinter button takes one argument as a command that can be used to pass value to the button based on click event. 

"""
How to Pass Arguments to Tkinter Button

"""

# import tkinter and functools
import tkinter as tk
from functools import partial

app = tk.Tk()
mylabel = tk.Button(app, text="Button")

def change_label_name():
    mylabel.config(text="Button Clicked")
    
mybutton = tk.Button(app, text="Click", width=50, height=8, command=partial(change_label_name))
mybutton.pack()
mylabel.pack()
app.mainloop()

Output:

tkinter-button

 

Pass argument to Tkinter Button Command using lambda function 

This is another solution where we can use the lambda function in place of the partial() function and can pass the argument to the Tkinter button command. It is one of the easy ways to pass value to a button.

"""
How to Pass Arguments to Tkinter Button

"""

# import tkinter
import tkinter as tk

app = tk.Tk()
mylabel = tk.Button(app, text="Button")

def change_label_name():
    mylabel.config(text="Button Clicked")    
    
mybutton = tk.Button(app, text="Click", width=50,command=lambda: change_label_name())
mybutton.pack()
mylabel.pack()
app.mainloop()

Output:

tkinter-button

 

Useful Resource: