2017-10-07 58 views
0

我想将Button的子类化为OPButtun。 OPButton是一个常规的Button,当鼠标悬停时可以编写帮助消息。 OPButton必须接受任何可能的参数列表THRE常规按钮构造函数会接受,加上两个我自己的:消息和STRINGVAR哪里把它写在Tkinter:使用附加参数创建子类化按钮

这是我的代码(据说可运行)

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() 

回答

1

我敢肯定你所定义的__init__()功能被拼写为___init___()

+0

谢谢。我没有找到正确的方向。我在原帖的末尾发布了调试过的代码。再次感谢。虽然错误是一个微不足道的错字,但我被困了好几个小时。 – quickbug

+0

@quickbug没问题。 :) –