TkInter keypress, keyrelease events


Tkinter Events are generally used to provide an interface that works as a bridge between the User and the application logic. We can use Events in any Tkinter application to make it more interactive and functional. Events like <Key Press> and <KeyRelease> are used to call a specific function only when a key is pressed or released.

Example

In this example, we will create a script that will show some message on the screen whenever we press a key. The message gets disappeared when we release the same key.

# 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 display the message
def key_press(e):
   label.config(text="Welcome to TutorialsPoint")

def key_released(e):
   label.config(text="Press any Key...")
# Create a label widget to add some text
label= Label(win, text= "", font= ('Helvetica 17 bold'))
label.pack(pady= 50)

# Bind the Mouse button event
win.bind('<KeyPress>',key_press)
win.bind('<KeyRelease>',key_released )
win.mainloop()

Output

Running the above code will display a window with a label.

When you press a key from the keyboard, it will display some message on the screen. At the same time, the message will get updated whenever you lift off the key.

Updated on: 07-Jun-2021

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements