Tkinter widgets are the building blocks that come with some predefined operations. To handle a specific functionality of an application, we bind the keys to some widgets.
We can bind an event to widgets using the bind(‘key’, callback function) method. Key represents the event through which we target a particular event, whereas callable function activates the event. To create a callback function, we switch to a specific widget as the argument and then add the particular event.
Example
Let us understand this with an example where we have to bind the <Enter> key with a function that displays some text on the window. Whenever the button is clicked or <Enter> key is pressed, the callback function executes and the event happens.
#Import the Tkinter library from tkinter import * #Create an instance of Tkinter frame win= Tk() #Define the geometry win.geometry("750x250") #Define Event handlers with arguments def event_show(event): button.config(bg="red", fg= "white") label.config(text="Hello World") #Create a Label label= Label(win, text="",font=('Helvetica 15 underline')) label.pack() #Create a frame frame= Frame(win) #Create Buttons in the frame button= Button(frame, text="Click",command=lambda:event_show(button)) button.pack(pady=10) frame.pack() #Bind the function win.bind('<Return>',lambda event:event_show(event)) win.mainloop()
Output
Running the above code will display a window that contains a button. The button event can bed triggered through two ways − Enter Key and Click Event.
Now, press Enter or click the button to display the output on the screen.