【问题标题】:Python TypeError when using Bind for a wx.Button为 wx.Button 使用 Bind 时出现 Python TypeError
【发布时间】:2011-12-05 10:21:41
【问题描述】:

我有一个名为 WxFrame 的类,它创建一个 wxPython 框架。我添加了一个名为 createRunButton 的方法,它接收 self 和 pydepp,它是 PyDEPP 类的对象

import wx

class WxFrame(wx.Frame):
    def __init__(self, parent, title):
        super(WxFrame, self).__init__(parent, title=title)
        self.Maximize()
        self.Show()

    def createRunButton(self,pydepp):
        #pydepp.run()
        self.runButton = wx.Button(self, label="Run")
        self.Bind(wx.EVT_BUTTON, pydepp.run, self.runButton

这是 PyDEPP 类:

class PyDEPP:
    def run(self):
        print "running"

我实例化并运行它:

import wx
from gui.gui import WxFrame
from Depp.Depp import PyDEPP

class PyDEPPgui():
    """PyDEPPgui create doc string here ...."""
    def __init__(self,pydepp):
        self.app = wx.App(False)
         ##Create a wxframe and show it
        self.frame = WxFrame(None, "Cyclic Depp Data Collector - Ver. 0.1")
        self.frame.createRunButton(pydepp)
        self.frame.SetStatusText('wxPython GUI successfully initialised')

if __name__=='__main__':
    #Launch the program by calling the PyDEPPgui __init__ constructor
    pydepp = PyDEPP()
    pydeppgui = PyDEPPgui(pydepp)
    pydeppgui.app.MainLoop()

运行上述代码时出现的错误是: TypeError: run() 只需要 1 个参数(给定 2 个)

但是,如果我注释掉绑定并取消注释 pydepp.run() 行,那么它可以正常工作。

我敢肯定,答案很明显,但我从未研究过 CompSci 或 OO 编码。

【问题讨论】:

    标签: python wxpython bind argument-passing typeerror


    【解决方案1】:

    事件作为参数传递给回调函数。这应该有效:

    class PyDEPP:
        def run(self, event):
            print "running"
    

    【讨论】:

      【解决方案2】:

      当事件被触发时,两个参数被传递给回调函数run():触发事件的对象和wxEvent 对象。由于 run 在您的代码中只接受一个参数,因此解释器会给出该错误,告诉您您提供了太多参数。

      替换

      run(self):  # Expects one argument, but is passed two. TypeError thrown
      

      run(self, event): # Expects two arguments, gets two arguments.  All is well
      

      它应该可以工作。

      这是错误告诉您很多关于代码有什么问题的一个实例。鉴于“run() 只需要 1 个参数(给定 2 个)”,您会立即知道您不小心传递了一个额外的参数,或者 run 应该期待另一个。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-16
        • 2017-06-15
        • 1970-01-01
        • 1970-01-01
        • 2019-05-31
        • 2016-12-06
        • 2018-12-13
        • 1970-01-01
        相关资源
        最近更新 更多