How to Call Function on Tkinter Button Click?

Python Tkinter – Call Function on Button Click

When a Tkinter Button is clicked, you can call a function using command option. Assign the command option with the function name you would like to call when the button is clicked.

Pseudo Code – Call Function on Button Click

Following is a pseudo code to call a function when the button is clicked.

def someFunction:
    function body

tkWindow = Tk()

button = Button(tkWindow, command=someFunction)

Or you can also assign the command after defining the button.

def someFunction:
    function body

tkWindow = Tk()

button = Button(tkWindow)
button['command'] = someFunction

Examples

1. Call function to show message on button click

In this example, we will create a function, a Tkinter Button, and assign the function to Button, such that when user clicks on the Button, the function is called.

Python Program

from tkinter import *
from tkinter import messagebox

tkWindow = Tk()  
tkWindow.geometry('400x150')  
tkWindow.title('PythonExamples.org - Tkinter Example')

def showMsg():  
    messagebox.showinfo('Message', 'You clicked the Submit button!')

button = Button(tkWindow,
	text = 'Submit',
	command = showMsg)  
button.pack()  
  
tkWindow.mainloop()
Copy

Output

Please remember these things while providing a function to be called when the user clicks the button.

  • Define the function prior to the button definition.
  • The value to the command option should be the function name as is and not as a string with any quotes around it.

Summary

Concluding this tutorial of Python Examples, we learned how to call a function when Tkinter Button is clicked.

Related Tutorials

Code copied to clipboard successfully 👍