Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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.
Example
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()
Output
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.
Advertisements