Tkinter:使用附加参数对 Button 进行子类化
Tkinter: subclassing Button with additional arguments
我想将 Button 子类化为 OPButtun。 OPButton 是一个普通的 Button,具有在鼠标悬停时编写帮助消息的功能。 OPButton 必须接受常规 Button 构造函数可以接受的任何可能的参数列表,加上我自己的两个:一条消息和将其写入的 Stringvar。
这是我的代码(应该是可运行的)
from tkinter import *
from tkinter import ttk
class OPButton(Button):
""" """
def ___init___(self, parent, string, message, *args, **kwargs):
ttk.Button.__init__(self, parent, *args, **kwargs)
self.bind("<Enter>", command=lambda e: string.set(message))
self.bind("<Leave>", command=lambda e: string.set(""))
if __name__ == '__main__':
root = Tk()
root.str= StringVar()
OPButton(root, root.str, "hovering the button", text="click here").pack()
ttk.Label(root, textvariable=root.str).pack()
root.mainloop()
和错误信息:
Traceback (most recent call last):
File "C:\Users\planchoo\oPButton.py", line 19, in <module>
OPButton(root, "Hello World", "Bouton", text="Hello").pack()
TypeError: __init__() takes from 1 to 3 positional arguments but 4 were given
编辑: 以下是 Bryan 回复后的更正代码。工作完美(谢谢)。
from tkinter import *
from tkinter import ttk
class OPButton(Button):
""" """
def __init__(self, parent, string, message, *args, **kwargs):
ttk.Button.__init__(self, parent, *args, **kwargs)
self.bind("<Enter>", lambda e: string.set(message))
self.bind("<Leave>", lambda e: string.set(""))
if __name__ == '__main__':
root = Tk()
root.chaine = StringVar()
OPButton(root, root.chaine, "Bouton", text="Hello").pack()
ttk.Label(root, textvariable=root.chaine).pack()
root.mainloop()
我很确定您定义的 __init__()
函数拼写为 ___init___()
。
我想将 Button 子类化为 OPButtun。 OPButton 是一个普通的 Button,具有在鼠标悬停时编写帮助消息的功能。 OPButton 必须接受常规 Button 构造函数可以接受的任何可能的参数列表,加上我自己的两个:一条消息和将其写入的 Stringvar。
这是我的代码(应该是可运行的)
from tkinter import *
from tkinter import ttk
class OPButton(Button):
""" """
def ___init___(self, parent, string, message, *args, **kwargs):
ttk.Button.__init__(self, parent, *args, **kwargs)
self.bind("<Enter>", command=lambda e: string.set(message))
self.bind("<Leave>", command=lambda e: string.set(""))
if __name__ == '__main__':
root = Tk()
root.str= StringVar()
OPButton(root, root.str, "hovering the button", text="click here").pack()
ttk.Label(root, textvariable=root.str).pack()
root.mainloop()
和错误信息:
Traceback (most recent call last):
File "C:\Users\planchoo\oPButton.py", line 19, in <module>
OPButton(root, "Hello World", "Bouton", text="Hello").pack()
TypeError: __init__() takes from 1 to 3 positional arguments but 4 were given
编辑: 以下是 Bryan 回复后的更正代码。工作完美(谢谢)。
from tkinter import *
from tkinter import ttk
class OPButton(Button):
""" """
def __init__(self, parent, string, message, *args, **kwargs):
ttk.Button.__init__(self, parent, *args, **kwargs)
self.bind("<Enter>", lambda e: string.set(message))
self.bind("<Leave>", lambda e: string.set(""))
if __name__ == '__main__':
root = Tk()
root.chaine = StringVar()
OPButton(root, root.chaine, "Bouton", text="Hello").pack()
ttk.Label(root, textvariable=root.chaine).pack()
root.mainloop()
我很确定您定义的 __init__()
函数拼写为 ___init___()
。