2011-12-05 31 views
0

我有一個名爲WxFrame的類,它創建了一個wxPython框架。我添加了一個稱爲createRunButton方法,其接收自和pydepp,這是一個PyDEPP類的對象使用綁定爲wx.Button時的Python TypeError

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編碼。

回答

2

該事件作爲參數傳遞給回調函數。這應該工作:

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

當事件被觸發時,兩個參數傳遞給回調函數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個參數)」,那麼您立即知道您是不小心傳遞了一個額外的參數,或者運行應該期待另一個參數。

相關問題