当你的鼠标被按下并悬停在它上面时,你如何改变多个 tkinter 按钮的状态?
How do you change the state of multiple tkinter buttons when your mouse is pressed and hovering over it?
我有一个二维数组的 tkinter 按钮。
看起来像这样:
我希望能够单击一个按钮,按住鼠标,按下鼠标时悬停在上方的每个按钮都会改变颜色。到目前为止,如果您将鼠标悬停在任何正方形上,无论是否按下鼠标按钮,它都会改变颜色。
到目前为止,代码如下所示:
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()
获取鼠标位置并使用 .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)
我有一个二维数组的 tkinter 按钮。
看起来像这样:
我希望能够单击一个按钮,按住鼠标,按下鼠标时悬停在上方的每个按钮都会改变颜色。到目前为止,如果您将鼠标悬停在任何正方形上,无论是否按下鼠标按钮,它都会改变颜色。
到目前为止,代码如下所示:
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()
获取鼠标位置并使用 .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)