gpt4 book ai didi

python - 如何在 Tkinter 中用一个 "bind"绑定(bind)多个小部件?

转载 作者:太空狗 更新时间:2023-10-30 00:30:08 24 4
gpt4 key购买 nike

我想知道如何使用一个“绑定(bind)”来绑定(bind)多个小部件。

例如:

我有三个按钮,我想在悬停后更改它们的颜色。

from Tkinter import *

def SetColor(event):
event.widget.config(bg="red")
return

def ReturnColor(event):
event.widget.config(bg="white")
return

root = Tk()

B1 = Button(root,text="Button 1", bg="white")
B1.pack()

B2 = Button(root, text="Button2", bg="white")
B2.pack()

B3 = Button(root, text= "Button 3", bg="white")
B3.pack()

B1.bind("<Enter>",SetColor)
B2.bind("<Enter>",SetColor)
B3.bind("<Enter>",SetColor)

B1.bind("<Leave>",ReturnColor)
B2.bind("<Leave>",ReturnColor)
B3.bind("<Leave>",ReturnColor)

root.mainloop()

我的目标是只有两个绑定(bind)(用于“进入”和“离开”事件)而不是上面的六个。

谢谢你的想法

最佳答案

要回答您关于是否可以将单个绑定(bind)应用于多个小部件的具体问题,答案是肯定的。这可能会导致更多而不是更少的代码行,但这很容易做到。

所有 tkinter 小部件都有一个叫做“bindtags”的东西。绑定(bind)标签是附加绑定(bind)的“标签”列表。你一直在使用它而不自知。当您绑定(bind)到一个小部件时,绑定(bind)实际上并不是在小部件本身上,而是在一个与小部件的低级名称同名的标签上。默认绑定(bind)位于与小部件类(底层类,不一定是 python 类)同名的标签上。当您调用 bind_all 时,您将绑定(bind)到标签 "all"

bindtags 的伟大之处在于您可以随意添加和删除标签。因此,您可以添加自己的标签,然后使用 bind_class 将绑定(bind)分配给它(我不知道为什么 Tkinter 作者选择了那个名称......)。

要记住的一件重要事情是绑定(bind)标签有一个顺序,事件是按这个顺序处理的。如果事件处理程序返回字符串 "break",则在检查任何剩余绑定(bind)标签的绑定(bind)之前,事件处理将停止。

这样做的实际结果是,如果您希望其他绑定(bind)能够覆盖这些新绑定(bind),请将您的绑定(bind)标签添加到末尾。如果您希望您的绑定(bind)不可能被其他绑定(bind)覆盖,请将其放在开头。

例子

import Tkinter as tk

class Example(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)

# add bindings to a new tag that we're going to be using
self.bind_class("mytag", "<Enter>", self.on_enter)
self.bind_class("mytag", "<Leave>", self.on_leave)

# create some widgets and give them this tag
for i in range(5):
l = tk.Label(self, text="Button #%s" % i, background="white")
l.pack(side="top")
new_tags = l.bindtags() + ("mytag",)
l.bindtags(new_tags)

def on_enter(self, event):
event.widget.configure(background="bisque")

def on_leave(self, event):
event.widget.configure(background="white")

if __name__ == "__main__":
root = tk.Tk()
view = Example()
view.pack(side="top", fill="both", expand=True)
root.mainloop()

可以在这个答案中找到更多关于绑定(bind)标签的信息:https://stackoverflow.com/a/11542200/7432

此外,bindtags 方法本身记录在 effbot Basic Widget Methods 上其他地方的页面。

关于python - 如何在 Tkinter 中用一个 "bind"绑定(bind)多个小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15362011/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com