0

This code is a tutorial from youtube. The given code is supposed to print right on the right click of the mouse on the console and same for the left click but it is not doing so. I think the problem is with the bind function.

I am using python 3.7 which already have tkinter package in it, what can I do to make it work, thank you very much.

from tkinter import *

root = Tk()

def leftclick(event):
    print("left")

def rightclick(event):
    print("right")

frame = Frame(root, width=300, height=300)    
frame.bind("button-1", leftclick)    
frame.bind("button-2", rightclick)
frame.pack()

root.mainloop()

I expect the program to print 'left' in the console on the left click of the mouse inside the tk window and same for right click

4
  • 3
    Should be '<Button-1>' and '<Button-2>'. Commented Jun 24, 2019 at 11:31
  • thank u sir button 1 is working for the left click but nothing is happening for the right click Commented Jun 24, 2019 at 11:35
  • 3
    I think "Button-2" is the middle mouse button. Try "<Button-3>" Commented Jun 24, 2019 at 11:41
  • yes u are right, it is working now, thanks Commented Jun 24, 2019 at 11:48

1 Answer 1

2

First, as already noted in comments, the mouse button events need <...>. About the rightclick not working: This is because the even for the right mouse button is actually <Button-3>, whereas <Button-2> is the middle mouse button (or pressing down on the mouse wheel).

frame.bind("<Button-1>", leftclick)
frame.bind("<Button-3>", rightclick)

This may be a bit unintuitive if you think of the right mouse button as the "secondary" button, but makes sense if you just enumerate the buttons from left to right. This is AFAIK also consistent with all (most?) other UI frameworks and languages.

Sign up to request clarification or add additional context in comments.

1 Comment

thank u sir, actually i am using laptop mouse pad so i thought button 2 will be the right click thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.