- Trending Categories
- Data Structure
- Operating System
- C Programming
- 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
Call a Function with a Button or a Key in Tkinter
Let assume that we want to call a function whenever a button or a key is pressed for a particular application. We can bind the function that contains the operation with a button or key using the bind('<button or Key>,' callback_function) method. Here, you can bind any key to the event or function that needs to be called.
In this example, we have created a function that will open a dialog box whenever we click a button.
#Import the required libraries from tkinter import * from tkinter import ttk from tkinter import messagebox #Create an instance of Tkinter Frame win = Tk() #Set the geometry of Tkinter Frame win.geometry("700x350") #Define a function for opening the Dialog box def open_prompt(): messagebox.showinfo("Message", "Click Okay to Proceed") #Create a Label widget Label(win, text= "Click to Open the MessageBox").pack(pady=15) #Create a Button for opening a dialog Box ttk.Button(win, text= "Open", command= open_prompt).pack() win.mainloop()
Running the above code will display a window containing a label and a button.
Upon clicking the "Open" button", it will call a function to open a dialog box.
- Related Articles
- Call the same function when clicking a Button and pressing Enter in Tkinter
- How to bind a key to a button in Tkinter?
- Creating a Browse Button with Tkinter
- How to call a function using the OptionMenu widget in Tkinter?
- How to stop a loop with a stop button in Tkinter?
- How do I bind the enter key to a function in Tkinter?
- Creating a button in tkinter in Python
- Tkinter binding a function with arguments to a widget
- How to Disable / Enable a Button in TKinter?
- How to update a Button widget in Tkinter?
- How to highlight a tkinter button in macOS?
- How to call a function with argument list in Python?