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.


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

# 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('<KeyRelease>',key_released )


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 11:18:36