Tkinter button widget is quite similar to the Tkinter Label widget. It has almost the same options as those in the label, except it has one extra
default option. We will give details of this
default after one basic button example.
You could generate two basic buttons using the demo codes below.
You could see the window with two buttons adjacent to each other.
default option in the button tells the button is the default button in the GUI, for example, the one invoked automatically when the user presses the
The callback command of the default button is not created automatically but needs to be created manually.
Tkinter Button Command Callback
command option invokes the callback function when the button is pressed.
The button state should be active when its command option is enabled; otherwise, no callback is invoked.
It creates a button and a label widget in the main window. The number in the label text is increased by one every time the button is clicked.
def change_label_number(): counter = int(str(labelExample['text'])) counter += 1 labelExample.config(text=str(counter))
change_label_number is the function invoked when the button is clicked. It gets the number of the label and then sets the label increased by one.
buttonExample = tk.Button(app, text="Increase", width=30, command=change_label_number)
It builds the binding between the button and its callback function.
The function name in the button options is without parenthesis.
Tkinter Button Command Callback Function With Arguments
You need a
partial object from
functools if you need to pass arguments to the callback functions.
partial objects are callable objects with the positional arguments
args and keyword arguments
The below code snippet demonstrates how to use this
partial function in the button command.
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))