- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Call the same function when clicking a Button and pressing Enter in Tkinter
There are various built-in functions, widgets and methods available in the tkinter toolkit library which you can use to build robust and powerful desktop applications. The Button widget in tkinter helps users in creating buttons and performing different actions with the help of its functions. You can also bind the buttons to perform some specific events or callback by using the bind("button", callback) method.
Example
Consider the following example. to create a function that prints a message on the screen whenever the user presses the <Enter> key. To bind the <Enter> key with the function, you can use the bind("<Return>", callback) method.
# Import the required libraries from tkinter import * # Create an instance of tkinter frame or window win = Tk() # Set the size of the window win.geometry("700x350") # Define a function to print the message def print_msg(): Label(win, text="Hello World!", font=('11')).pack() # Create a button widget and bind with the given function win.bind("<Return>", lambda e: print_msg()) button = Button(win, text="Click Me", command=print_msg) button.pack() win.mainloop()
Output
Running the above code will display a window that contains a button. Clicking the button will display the Label widget containing the text in the main window.
Pressing the <Enter> key too would produce the same result. So, we are calling the same function by clicking the button as well as pressing the <Enter> key.