Tkinter Button Widget
Tkinter button widget is quite similar to 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 simplest buttons using demo codes below.
The window with two buttons adjacent to each other shows after you run the codes.
default option in button tells the button is the default button in the GUI, for example, the one that is invoked automatically when user press Enter or Return key.
Tkinter Button Command Callback
The “command” option invokes the callback function when the button is pressed.
It creates a button and a label widget in the main window. The number in the label text is increased by 1 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 button is clicked. It gets the number of label and then set the label increased by one.
buttonExample = tk.Button(app, text="Increase", width=30, command=change_label_number)
It builds the binding between button and its callback function.
Tkinter Button Command Callback Function with Arguments
You need a
partial object from functools if you need pass arguments to the callback functions.
partial objects are callable objects with the positional arguments
args and keyword arguments
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))