command
option in Tkinter Button
widget is triggered when the user presses the button. In some scenarios, you need to pass arguments to the attached command function, but you couldn’t simply pass the arguments like below,
1 2 3 |
button = tk.Button(app, text="Press Me", command=action(args)) |
We will introduce two ways to pass the arguments to the command function.
Pass Arguments to command in Tkinter Button With partials
As demonstrated in Python Tkinter tutorial, you have the option to use the partial
object from the functools
module.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
from sys import version_info if version_info.major == 2: import Tkinter as tk elif version_info.major == 3: import tkinter as tk from functools import partial app = tk.Tk() labelExample = tk.Button(app, text="0") def change_label_number(num): counter = int(str(labelExample['text'])) counter += num labelExample.config(text=str(counter)) buttonExample = tk.Button(app, text="Increase", width=30, command=partial(change_label_number, 2)) buttonExample.pack() labelExample.pack() app.mainloop() |
1 2 3 4 |
buttonExample = tk.Button(app, text="Increase", width=30, command=partial(change_label_number, 2)) |
Pass Arguments to command in Tkinter Button With lambda Function
You could also use Python lambda
operator or function to create a temporary, one-time simple function to be called when the Button
is clicked.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
from sys import version_info if version_info.major == 2: import Tkinter as tk elif version_info.major == 3: import tkinter as tk app = tk.Tk() labelExample = tk.Button(app, text="0") def change_label_number(num): counter = int(str(labelExample['text'])) counter += num labelExample.config(text=str(counter)) buttonExample = tk.Button(app, text="Increase", width=30, command=lambda: change_label_number(2)) buttonExample.pack() labelExample.pack() app.mainloop() |
The syntax of lambda
function is
1 2 3 |
lambda: argument_list: expression |
You don’t need any arguments in this example, therefore, you could leave the argument list empty and only give the expression.
1 2 3 4 |
buttonExample = tk.Button(app, text="Increase", width=30, command=lambda: change_label_number(2)) |