繁体   English   中英

按下鼠标并将鼠标悬停在多个 tkinter 按钮上时,如何更改 state?

[英]How do you change the state of multiple tkinter buttons when your mouse is pressed and hovering over it?

我有一个二维 tkinter 按钮数组。

它看起来像这样: 在此处输入图像描述

我希望能够单击一个按钮,按住鼠标,然后在按下鼠标时悬停在上面的每个按钮都会更改 colors。 到目前为止,我已经达到了这样的程度,如果您在任何正方形上使用 hover,无论是否按下鼠标按钮,它都会更改 colors。

到目前为止,代码看起来像这样:

def draw(self, i, j):
    button = self.buttons[i][j] 
    button.bind('<Enter>', lambda event: self.on_enter(event, button))


def on_enter(self, e, button):
    button['background'] = 'green'

需要明确的是,我希望能够在按住左键并同时悬停一个按钮时更改按钮的颜色。

谢谢你帮助我。

编辑:删除了代码图片并提供了可以复制和粘贴的内容。

第二次编辑:代码大约有 100 行,但要点是有一个 tkinter 按钮的二维数组,我提供的代码显示了负责更改按钮颜色的 2 个函数。 如果需要更多代码,我会把它放进去。

您可以将根 window 上的<B1-Motion>绑定到回调。 然后在回调内部,使用.winfo_pointerxy()获取鼠标 position 和.winfo_containing()查找鼠标指针下方的按钮并更改其背景颜色:

例子:

def on_drag(event):
    x, y = root.winfo_pointerxy()
    btn = root.winfo_containing(x, y)
    if btn:
        btn.config(bg="green")

# root is the root window
root.bind('<B1-Motion>', on_drag)

暂无
暂无

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

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