Call the same function when clicking a Button and pressing Enter in Tkinter
Tkinter is the standard GUI library for Python. This tutorial will show you how to create a Tkinter button that can trigger a function when clicked, and also execute the same function when pressing enter in an entry field.
In Tkinter, you can create buttons using the Button widget. The Button widget has a command parameter that you can use to assign a function to execute when the button is clicked.
from tkinter import *
root = Tk()
def print_func(event=None):
print("Button Clicked")
button = Button(root, text="Click Me", command=print_func)
button.pack()
root.mainloop()
The above code will create a Tkinter window with a button labeled “Click Me”. When the button is clicked, the print_func
function is executed and the message “Button Clicked” is printed to the console.
Now, let’s modify the code to execute the same function when pressing enter in an entry field.
from tkinter import *
root = Tk()
def print_func(event=None):
print("Button Clicked")
entry = Entry(root)
entry.pack()
button = Button(root, text="Click Me", command=print_func)
button.pack()
root.bind('<Return>', print_func)
root.mainloop()
In the above code, we added an Entry widget to the GUI. The Entry widget creates a field where the user can enter text. We also added a binding to the <Return>
event. This binding will call the print_func
function when the user presses the Enter key.
The event=None
parameter in the function definition allows us to execute the function both when the button is clicked and when Enter is pressed in the entry field.
You can also pass arguments to the function by using the lambda
function. Here is an example:
from tkinter import *
root = Tk()
def print_message(message):
print(message)
entry = Entry(root)
entry.pack()
button = Button(root, text="Print Message", command=lambda: print_message(entry.get()))
button.pack()
root.bind('<Return>', lambda event: print_message(entry.get()))
root.mainloop()
In this example, we added an entry field and a button. The button calls the print_message
function, passing the text entered in the entry field as an argument.
The binding to the <Return>
event also calls the print_message
function, passing the text entered in the entry field as an argument.
Conclusion
In this tutorial, we showed you how to execute the same function when clicking a button and pressing Enter in an entry field in Tkinter. We also demonstrated how to pass arguments to functions using the command
parameter and the lambda
function. Using these techniques, you can create more interactive and user-friendly GUI applications.