将类方法绑定到Tkinter信号

Asi*_*ics 4 python tkinter

我正在尝试使用Tkinter将类方法绑定到信号,但出现以下错误:

TypeError:event_foo()恰好接受1个参数(给定2个)

过去我经常使用绑定,但是没有任何问题,但是我不明白第二个参数(我显然不知道该给出的)来自何处。

代码示例:(简体)

class Controller:
    def__init__(self, myVar, myWidget):
        self.myVar = myVar
        self.myWidget = myWidget

        self.connect(self, myWidget, "<Double-Button-1>", event_foo)

    def event_foo(self):
        """ Does stuff """

    #Simplified to a wrapper, real function does other actions
    def connect(self, widget, signal, event) 
        widget.bind(signal, event)
Run Code Online (Sandbox Code Playgroud)

Asi*_*ics 5

我在输入问题时就知道了这一点,所以我会回答自己,以防其他人遇到这个问题。这是修复示例的代码:

class Controller:
    def__init__(self, myVar, myWidget):
        self.myVar = myVar
        self.myWidget = myWidget

        self.connect(self, myWidget, "<Double-Button-1>", event_foo)

    def event_foo(self, event=None): ###event was the implicit argument, I set it to None because I handle my own events and don't use the Tkinter events
        """ Does stuff """

    #Simplified to a wrapper, real function does other actions
    def connect(self, widget, signal, event) 
        widget.bind(signal, event)
Run Code Online (Sandbox Code Playgroud)

尽管如此,对它如何工作的澄清将是高度赞赏的。这是可靠的方法还是我正在使用危险的丑陋变通方案,迟早会突然出现在我的脸上?

  • 您的回答是正确的。当您使用`bind`时,tkinter总是将事件对象传递给函数。 (3认同)