【问题标题】:Call the Button contrustor from inside a class' __init__从类' __init__ 中调用 Button contrustor
【发布时间】:2015-06-04 00:39:28
【问题描述】:

我的 GUI 程序使用了许多按钮,这些按钮具有几个非常具体的功能,所以我正在编写一个类,将这些方法包装在一个按钮周围,这样我就不需要为每个按钮重写简单的功能。我有课:

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

我希望能够像创建按钮一样创建对象:

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

如何声明类__init__ 方法来模仿按钮的方法?目前如果我写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)

【问题讨论】:

    标签: python class python-2.7 tkinter


    【解决方案1】:

    您需要应用(splat)额外的关键字参数:

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

    否则,您会将整个 kw dict 作为单个位置参数传递。这会引发错误,因为 Button.__init__ 只接受三个位置参数(selfmastercnf),而不是四个。

    【讨论】:

      猜你喜欢
      • 2017-12-13
      • 2014-03-07
      • 2018-12-02
      • 2017-08-26
      • 1970-01-01
      • 2010-11-26
      • 1970-01-01
      • 2012-09-20
      • 2012-08-30
      相关资源
      最近更新 更多