Bind a function to a Tkinter button – Python GUI
In this post, I am going to tell you how to bind a function to a Tkinter button. That means we will see how to add an event to the button. So let’s begin…
Adding an event to a Tkinter button is quite easy. We are going to see it with the code snippet.
When we install Python on Windows, the Tkinter also come with it. So we don’t have to install it. We can start by importing Tkinter.
Python program to bind a function to Tkinter button
Now below is our Python program:
from tkinter import * def my_fun(): print("Function called") win = Tk() button = Button(win, text="Click me", command = my_fun) button.pack() win.mainloop()
Now we are going to describe our code.
In our code, we have created out Python function that will be called when we click our Tkinter button. In our button, we have added our function to the command just like you can see below:
button = Button(win, text="Click me", command = my_fun) button.pack()
Here we have to pass our function name that we want to bind with our button. The function we have passed to our command will hold all the code that we want to run when our button will be clicked. But here in this example, we are just printing a message to see if it is working or not.
If you want to see it on your computer, then you can copy the code from this post and test it by yourself.
- Play mp3 audio in Python
- Remove spaces from a string in Python
- Tkinter pack() and grid() Method In Python
An alternative way to bind event with Tkinter button
Another way to bind a function with the button of Tkinter is given below:
button = Button(win, text="Click me") button.bind("<Button-1>", my_fun) button.pack()
Below is the complete code:
from tkinter import * def my_fun(event): print("Function called") win = Tk() button = Button(win, text="Click me") button.bind("<Button-1>", my_fun) button.pack() win.mainloop()
In this way, we have to write another line of code to call the function when the button clicked:
Here “<Button-1>” refers to the left click. If we want to call the function on clicking the right click then we had to use “<Button-2>”.
I hope you have understood how to call a function on clicking a Tkinter button.