How to Bind Multiple Commands to Tkinter Button?
The button widget in Tkinter provides a way to interact with the application. The user presses a button to perform certain actions that are attached to that button. In general, we user provides a single action to a button but what if the user wants to attach more than one action to a button.
In this article, we are going to see how we can bind more than one action/command to a single button.
To create a button in Tkinter please follow the below syntax.
Syntax: Button(master, text=”Button”, command=function, options, …)
- master: refers to the top-level window in which button is placed
- text: Text to show button
- command: An action which will be called on button press
There are other options as well but they are rarely used.
- compound: To show both image and text
- image: To show image
- pady: To provide vertical padding
- padx: To provide horizontal padding
Method 1: By using the lambda function and list
In this method, we are going to pass a list of functions to lambda, and then that lambda will be passed to command.
Method 2: By creating our own generic function that will call functions for us.
In the above method, you may be wondering how we are going to pass arguments to fun1 and fun2 because if we do the following
It will immediately call the functions as soon as the application runs, but we want that these functions should be called only when the button is pressed. So the answer is simple if you want to pass arguments to fun1 or fun2 use the below syntax:
combine_funcs(lambda: fun1(arguments), lambda: fun2(arguments))
Let see the below example where we actually have parameters to fun1 and fun2.