How to bind the Enter key to a tkinter window?

TkinterPythonGUI-Programming

Tkinter events are executed at runtime and when we bind these events with a button or key, then we will get access to prioritize the event in the application.

To bind the <Enter> key with an event in Tkinter window, we can use bind('<Return>', callback) by specifying the key and the callback function as the arguments. Once we bind the key to an event, we can get full control over the events.

Example

# Import the required libraries
from tkinter import *
from PIL import Image, ImageTk

# Create an instance of tkinter frame or window
win=Tk()

# Set the size of the window
win.geometry("700x350")

def show_msg(event):
   label["text"]="Sale Up to 50% Off!"

# Create a label widget
label=Label(win, text="Press Enter Key" ,font="TkMenuFont 20")
label.pack(pady=30)

# Bind the Enter Key to the window
win.bind('<Return>', show_msg)

win.mainloop()

Output

Running the above code will display a window that will trigger the event when we press the <Enter> Key.

Now, press the <Enter> key and observe the output.

raja
Published on 05-Aug-2021 13:57:20
Advertisements