Search code examples
pythontkintereventsclickmouse

Is there a click event handler in tkinter?


Guys I'm writing a GUI in tkinter. I wanted to handle click events like whenever a user use the 'left' mouse button on the GUI. This is for playing a sound when a user clicks. So is there any functions like:

onClick(lambda: play()) #call a function

Thanks in advance :)


Solution

  • You can add a click event to a canvas.

    Something like this should work:

    root = Tk()
    
    def on_click(event):
        print("you clicked")
    
    canvas = Canvas(root, width=800, height=600)
    canvas.bind("<Button-1>", on_click)
    canvas.pack()
    
    # Canvas.focus_set is required if the window already contains a widget that has keyboard/input focus
    canvas.focus_set()
    
    root.mainloop()
    

    Here are some examples of using this method: https://python-course.eu/tkinter/events-and-binds-in-tkinter.php