简体   繁体   English

如何检查是否在tkinter中右键单击按钮?

[英]How to check if button was pressed with right click in tkinter?

I'm trying to make a minesweeper game, and for that the user needs to be able to set flags.我正在尝试制作扫雷游戏,为此用户需要能够设置标志。 In every minesweeperr game, it works with right click.在每个扫雷游戏中,它都可以通过右键单击来工作。 I tried googling and know how to get coordinates of my mouse cursor, but it works weirdly with buttons.我尝试使用谷歌搜索并知道如何获取鼠标光标的坐标,但它与按钮一起工作很奇怪。 Anywhere else, it gives normal coordinates, but when the cursor is over buttons, it gives me coordiantes between 10 and 30. Why is this?在其他任何地方,它都会给出正常坐标,但是当光标在按钮上时,它会给出 10 到 30 之间的坐标。这是为什么呢? I place the buttons in a loop using .place() .我使用.place()将按钮放在一个循环中。 Here's the code:这是代码:

def rightclick(event):
    x, y = event.x, event.y
    print('{}, {}'.format(x, y))
root.bind('<Button-3>', rightclick)

When I'm not hovering over buttons, it returns normal coordinates like: 452, 539 and 311, 523当我没有将鼠标悬停在按钮上时,它会返回正常坐标452, 539311, 523

But when I am, it returns: 11, 16 and 30, 11但是当我在时,它会返回: 11, 1630, 11

Can someone explain what is going on?有人可以解释发生了什么吗?

As @acw1668 writes in the comment section the event.x and event.y return the relative coordinates of Button widget due to the inheritance.正如@acw1668 在评论部分中所写, event.xevent.y由于继承而返回Button小部件的相对坐标。

You can get the coordinates of root with event.x_root and event.y_root methods and the event.widget returns the widget where the trigger comes from.您可以使用event.x_rootevent.y_root方法获取 root 的坐标,并且event.widget返回触发器来自的小部件。

Code:代码:

"""
Example for root/relative mouse coordinates in Tkinter
"""

import tkinter


class App(tkinter.Tk):
    """
    App class from tkinter.Tk
    """

    def __init__(self):
        super().__init__()
        button_obj = tkinter.Button(width=10, height=10, background="black")
        button_obj.pack(padx=10, pady=10)
        button_obj.bind("<Button-3>", self.right_click)

    @staticmethod
    def right_click(event):
        """
        Callback method for Right Click on mouse

        Args:
            event: Event object

        Returns: None

        """

        print("Coordinates on the button widget: {}, {}".format(event.x, event.y))
        print("Coordinates on the root: {}, {}".format(event.x_root, event.y_root))
        print("Triggered widget: {}\n".format(event.widget))

root = App()
root.mainloop()

GUI:图形用户界面:

图形用户界面

Console output after some right clicks:一些右键单击后的控制台输出:

>>> python3 test.py 
Coordinates on the button widget: 18, 131
Coordinates on the root: 30, 223
Triggered widget: .!button

Coordinates on the button widget: 27, 57
Coordinates on the root: 39, 149
Triggered widget: .!button

Coordinates on the button widget: 64, 68
Coordinates on the root: 76, 160
Triggered widget: .!button

Coordinates on the button widget: 67, 118
Coordinates on the root: 79, 210
Triggered widget: .!button

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM