- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Tkinter binding a function with arguments to a widget
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.
- Related Articles
- Binding function in Python Tkinter
- How to call a function using the OptionMenu widget in Tkinter?
- How to center a Tkinter widget?
- Printing a list to a Tkinter Text widget
- How to make a Tkinter widget invisible?
- Passing arguments to a Tkinter button command
- How to change the Entry Widget Value with a Scale in Tkinter?
- Add advanced features to a tkinter Text widget
- How to update a Python/tkinter label widget?
- How to remove focus from a Tkinter widget?
- How to update a Button widget in Tkinter?
- How to add a column to a Tkinter TreeView widget?
- How to center a Tkinter widget in a sticky frame?
- How to attach a Scrollbar to a Text widget in Tkinter?
- How to highlight text in a tkinter Text widget?
