Tkinter Button

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.

Tkinter Button_Basic.py
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()
button1 = tk.Button(app, text="Python Label 1")
button2 = tk.Button(app, text="Python Label 2")
button1.pack(side=tk.LEFT)
button2.pack(side=tk.LEFT)
app.mainloop()

The window with two buttons adjacent to each other shows after you run the codes.

Tkinter Tutorial_Basic Label

Tkinter Button default option

The 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.

Tkinter Button_command callback.py
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():
    counter = int(str(labelExample['text']))
    counter += 1
    labelExample.config(text=str(counter))
    
buttonExample = tk.Button(app, text="Increase", width=30,
                          command=change_label_number)

buttonExample.pack()
labelExample.pack()
app.mainloop()

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.

Tkinter Tutorial_Button Command Callback

def change_label_number():
    counter = int(str(labelExample['text']))
    counter += 1
    labelExample.config(text=str(counter))

The 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 keywords.

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))