我正在使用 tk.Label 和我自己的类制作一个自定义按钮,这样我就可以在项目的单独模块中导入使用它,我不知道如何复制 command=
按钮对象的函数,这是回调函数的实现吗?如果不是,我应该在哪里查找有关如何完成此操作的信息
import tkinter as tk
class Main(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.geometry(self, "800x400")
tk.Tk.config(self, bg="black")
container = tk.Frame(self)
container.config(bg="black")
container.pack(side="top", fill="both", expand="true", pady=30)
this = Nav(container, text="Button 1")
this.bind("<Button>", lambda event: print("HELLO"))
this.pack()
Nav(container, text="Button 2")
class Nav(tk.Label):
def __init__(self, *args, **kwargs):
btn = tk.Label.__init__(self, *args, **kwargs, bg="green")
def on_enter(event, ref):
ref.config(text="enter", bg="#990000")
def on_leave(event, ref):
ref.config(text="leave", bg="black")
def left_click(event, ref):
ref.config(text="left click")
return True;
def release(event, ref):
ref.config(text="release")
app = Main()
app.mainloop()
最佳答案
你需要做四件事:
- 让调用者传入
command
参数,就像您对Button
所做的那样, - 让您的新类将此命令保存在变量中
- 在
Nav
内实现绑定(bind)调用内部函数 - 让该内部函数调用已保存的命令
例如,首先将命令添加到 Main
,并将该命令传递给 Nav
就像您对 Button
所做的那样:
class Main(tk.Tk):
def __init__(self, *args, **kwargs):
...
this = Nav(container, text="Button 1", command=self.do_something)
...
def do_something(self):
print("do_something was called")
接下来,定义Nav
接受这个参数。
注意:您错误地同时使用了继承和组合(从 Label
继承并创建了第二个 Label
),这是不必要的,因此我将在以下示例中删除第二个标签。
自 Label
不支持command
关键字 arg,我们需要将其从 kwargs
中取出并将其保存到变量中,然后将其余参数传递给 __init__
的Label
,
class Nav(tk.Label):
def __init__(self, *args, **kwargs):
self.command = kwargs.pop("command", None)
super().__init__(*args, **kwargs, bg="green")
您的原始代码调用 bind
在Main
,但是如果您尝试模仿小部件,则绑定(bind)需要位于小部件内部。这样,通过指定command
,这个新的小部件将像按钮一样工作。而不是绑定(bind)。
这就是定义 <Enter>
的方式, <Leave>
, <ButtonPress>
和<ButtonRelease>
事件。我已重命名了原始代码中的函数,以便彼此更加一致。
class Nav(tk.Label):
def __init__(self, *args, **kwargs):
...
self.bind("<Enter>", self.on_enter)
self.bind("<Leave>", self.on_leave)
self.bind("<ButtonPress>", self.on_press)
self.bind("<ButtonRelease>", self.on_release)
最后,您需要定义这些方法。这是您特别询问的实现 command
的那个功能:
class Nav(tk.label):
...
def on_release(self, event):
if self.command is not None:
self.command()
以下是其他方法,替换 ref
与 self
,并将参数按正确的顺序排列:
def on_enter(self, event):
self.config(text="enter", bg="#990000")
def on_leave(self, event):
self.config(text="leave", bg="black")
def left_click(self, event):
self.config(text="left click")
关于python - 重新创建按钮 Command=函数回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59513262/