简体   繁体   English

从类的__init__中调用Button委托者

[英]Call the Button contrustor from inside a class' __init__

My GUI program uses a number of buttons that have a couple very specific features, so I'm writing a class that wraps these methods around a button so I don't need to keep rewriting simple functions for each button. 我的GUI程序使用了许多具有几个非常特定功能的按钮,因此,我正在编写一个类,将这些方法包装在一个按钮周围,因此不需要继续为每个按钮重写简单的函数。 I have the class: 我上课:

class ToggleableButton(Button):     
    __isToggled = False
    __root = None
    __bindMap = []

    # how do I correctly structure the init ?
    def __init__(self, master=None, cnf={}, **kw):
        Button.__init__(self, master, cnf, kw)

    def bind(self, root, bindKey, func):
        # doing stuff

    def Toggle(self, toggle=False):
        # doing stuff

and I want to be able to create the object just like I'd create a button: 并且我希望能够像创建按钮一样创建对象:

drawButton = ToggleableButton(frame, image=img, width=30, command=func)
drawButton = ToggleableButton(frame, image=anotherimg)

how can I declare the class __init__ method to mimic that of the button? 如何声明类__init__方法来模仿按钮的方法? Currently if I write test = ToggleableButton(frame, text="hi", width=10, command=func) I'll get the error: 当前,如果我编写test = ToggleableButton(frame, text="hi", width=10, command=func)我将得到错误:

tools.py, line 59, in __init__
    Button.__init__(self, master, cnf, kw)
TypeError: __init__() takes at most 3 arguments (4 given)

You need to apply (splat) the extra keyword arguments: 您需要应用(附加)额外的关键字参数:

Button.__init__(self, master, cnf, **kw)
                                   ^^

Otherwise, you will be passing the whole kw dict as a single positional argument. 否则,您将把整个kw dict作为单个位置参数传递。 This raises an error since Button.__init__ only accepts three positional arguments ( self , master , and cnf ), not four. 由于Button.__init__仅接受三个位置参数( selfmastercnf ),而不接受四个位置参数,因此会引发错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM