Event Handling In Tkinter Python means to bind the keyboard or mouse buttons to the Tkinter and use them to call some functions.
We use bind() function to bind keys and functions to each other.
Here, functions can be in-built or made by the programmer.
Let’s see the code to call the in-built function and self made function using the gui.
Code
# importing tkinter from tkinter import * # initializing root root = Tk() # width and height variables can_width = 300 can_height = 200 # setting geometry of gui root.geometry(f"{can_width}x{can_height}") # setting title of gui root.title("Event handling") # creating a label Label(root, text="Click anywhere").pack() # initializing variable i = 0 # defining a function def me(event): global i Label(root, text=f"You clicked me {i} time").pack() Label(root, text="Double click to exit screen").pack() i=i+1 # binding mouse left button to root and calling me function root.bind("<Button-1>", me) # binding double click mouse left button to root and calling # in-built quit function root.bind("<Double-1>", quit) # calling mainloop root.mainloop()
Output
Now, here is the code to call the previous functions using the button.
Code
# importing tkinter from tkinter import * # initializing root root = Tk() # width and height variables can_width = 300 can_height = 200 # setting geometry of gui root.geometry(f"{can_width}x{can_height}") # setting title of gui root.title("Event handling") # creating a button win = Button(root, text="Click me") # packing the button to gui to show it on screen win.pack() # initializing variable i = 0 # defining a function def me(event): global i Label(root, text=f"You clicked me {i} time").pack() Label(root, text="Double click to exit screen").pack() i=i+1 # binding mouse left button to win and calling me function win.bind("<Button-1>", me) # binding double click mouse left button to win and calling # in-built quit function win.bind("<Double-1>", quit) # calling mainloop root.mainloop()
Output
Also Read:
- Game in Python Assignment Expert
- Guessing number in python assignment expertHello friends, here is the code for Guessing number in python assignment expert, you can check the code and you can run this code as…
- Make it equal in Python assignment expertIn this blog post, we will see how to make it equal in Python assignment expert means how to compare and make 2 variables equal…
- New Internship for Python Freshers | Apply NowWith the demand for Python software engineers on the rise, companies are looking for new ways to hire. Some have even turned to internships as…
- Naive Bayes in Machine LearningIn the Machine Learning series, following a bunch of articles, in this article, we are going to learn about the Naive Bayes Algorithm in detail….
Hey very cool site!! Man .. Excellent .. Amazing .. Ill bookmark your web site and take the feeds alsoI am happy to find so many useful info here in the post, we need work out more strategies in this regard, thanks for sharing. . . . . .