【问题标题】:TypeError: __init__() takes at least 3 arguments (1 given)TypeError: __init__() 至少需要 3 个参数(1 个给定)
【发布时间】:2014-01-20 19:22:52
【问题描述】:

这是我的 GUI 代码:

import wx
import os.path


class MainWindow(wx.Frame):
    #def __init__(self, filename=''):
        #super(MainWindow, self).__init__(None, size=(800,600))
    def __init__(self, parent, title, *args, **kwargs):
        super(MainWindow,self).__init__(parent, title = title, size = (800,600))
        wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos =  wx.DefaultPosition, size = wx.Size( 800,608 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
        self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
        grid = wx.GridSizer( 2, 2, 0, 0 )

        self.filename = filename
        self.dirname = '.'
        self.CreateInteriorWindowComponents()
        self.CreateExteriorWindowComponents()

    def CreateInteriorWindowComponents(self):


        staticbox = wx.StaticBoxSizer( wx.StaticBox( self, wx.ID_ANY, u"Enter text" ), wx.VERTICAL )
        staticbox.Add( self.m_textCtrl1, 0, wx.ALL|wx.EXPAND, 5 )
        self.m_textCtrl1 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( -1,250 ), wx.TE_MULTILINE)
        self.m_textCtrl1.SetMaxLength(10000)

        self.Submit = wx.Button( self, wx.ID_ANY, u"Submit", wx.DefaultPosition, wx.DefaultSize, 0 )
        staticbox.Add( self.Submit, 0, wx.ALL, 5 )

    def CreateExteriorWindowComponents(self):
        ''' Create "exterior" window components, such as menu and status
            bar. '''
        self.CreateMenu()
        self.CreateStatusBar()
        self.SetTitle()

    def CreateMenu(self):
        fileMenu = wx.Menu()
        for id, label, helpText, handler in \
            [(wx.ID_ABOUT, '&About', 'Storyteller 1.0 -',
                self.OnAbout),
             (wx.ID_OPEN, '&Open', 'Open a new file', self.OnOpen),
             (wx.ID_SAVE, '&Save', 'Save the current file', self.OnSave),
             (wx.ID_SAVEAS, 'Save &As', 'Save the file under a different name',
                self.OnSaveAs),
             (None, None, None, None),
             (wx.ID_EXIT, 'E&xit', 'Terminate the program', self.OnExit)]:
            if id == None:
                fileMenu.AppendSeparator()
            else:
                item = fileMenu.Append(id, label, helpText)
                self.Bind(wx.EVT_MENU, handler, item)

        menuBar = wx.MenuBar()
        menuBar.Append(fileMenu, '&File') # Add the fileMenu to the MenuBar
        self.SetMenuBar(menuBar)  # Add the menuBar to the Frame

    def SetTitle(self):
        # MainWindow.SetTitle overrides wx.Frame.SetTitle, so we have to
        # call it using super:
        super(MainWindow, self).SetTitle('Editor %s'%self.filename)


    # Helper methods:

    def defaultFileDialogOptions(self):
        ''' Return a dictionary with file dialog options that can be
            used in both the save file dialog as well as in the open
            file dialog. '''
        return dict(message='Choose a file', defaultDir=self.dirname,
                    wildcard='*.*')

    def askUserForFilename(self, **dialogOptions):
        dialog = wx.FileDialog(self, **dialogOptions)
        if dialog.ShowModal() == wx.ID_OK:
            userProvidedFilename = True
            self.filename = dialog.GetFilename()
            self.dirname = dialog.GetDirectory()
            self.SetTitle() # Update the window title with the new filename
        else:
            userProvidedFilename = False
        dialog.Destroy()
        return userProvidedFilename

    # Event handlers:

    def OnAbout(self, event):
        dialog = wx.MessageDialog(self, 'A sample editor\n'
            'in wxPython', 'About Sample Editor', wx.OK)
        dialog.ShowModal()
        dialog.Destroy()

    def OnExit(self, event):
        self.Close()  # Close the main window.

    def OnSave(self, event):
        textfile = open(os.path.join(self.dirname, self.filename), 'w')
        textfile.write(self.control.GetValue())
        textfile.close()

    def OnOpen(self, event):
        if self.askUserForFilename(style=wx.OPEN,
                                   **self.defaultFileDialogOptions()):
            textfile = open(os.path.join(self.dirname, self.filename), 'r')
            self.control.SetValue(textfile.read())
            textfile.close()

    def OnSaveAs(self, event):
        if self.askUserForFilename(defaultFile=self.filename, style=wx.SAVE,
                                   **self.defaultFileDialogOptions()):
            self.OnSave(event)


app = wx.App()
frame = MainWindow()
frame.Show()
app.MainLoop()

我收到了

TypeError:: __init__() takes at least 3 arguments (1 given)

3号最后一行frame = MainWindow()

如何确保参数列表匹配?我想我对传递自己,父母或其他东西有点困惑。

请帮忙!

编辑:@mhlester:我做了你建议的改变,但现在我有一个不同的错误:

TypeError: in method 'new_Frame', expected argument 1 of type 'wxWindow *'

事实上这就是完整的文本的样子:

 Traceback (most recent call last):
  File "C:\Users\BT\Desktop\BEt\gui2.py", line 115, in <module>
    frame = MainWindow(app,'Storyteller')
  File "C:\Users\BT\Desktop\BE\gui2.py", line 9, in __init__
    super(MainWindow,self).__init__(parent, title = title, size = (800,600))
  File "C:\Python27\lib\site-packages\wx-3.0-msw\wx\_windows.py", line 580, in __init__
    _windows_.Frame_swiginit(self,_windows_.new_Frame(*args, **kwargs))
TypeError: in method 'new_Frame', expected argument 1 of type 'wxWindow *'

【问题讨论】:

    标签: python user-interface wxpython wxformbuilder


    【解决方案1】:

    您将 init 设置为接受 3 个值,然后您什么也不传递。因为这个框架将是一个顶级窗口,你可以传递一个 None 的父级和某种标题字符串:

    frame = MainWindow(None, "test")
    

    下一个问题是您尝试同时使用两个初始化例程:超级例程和常规例程。您只能使用其中一种,但不能同时使用!我保留了 super 一个完整的,因为它更短并注释掉了后者。我还将 self.filename 更改为空字符串,因为“文件名”显然没有定义,并且由于代码不完整,我注释掉了构建其他小部件的调用。

    import wx
    import os.path
    
    
    class MainWindow(wx.Frame):
    
        def __init__(self, parent, title, *args, **kwargs):
            super(MainWindow,self).__init__(parent, title = title, size = (800,600))
            #wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos =  wx.DefaultPosition, size = wx.Size( 800,608 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
            self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
            grid = wx.GridSizer( 2, 2, 0, 0 )
    
            self.filename = ""
            self.dirname = '.'
            #self.CreateInteriorWindowComponents()
            #self.CreateExteriorWindowComponents()
    
        def CreateInteriorWindowComponents(self):
    
    
            staticbox = wx.StaticBoxSizer( wx.StaticBox( self, wx.ID_ANY, u"Enter text" ), wx.VERTICAL )
            staticbox.Add( self.m_textCtrl1, 0, wx.ALL|wx.EXPAND, 5 )
            self.m_textCtrl1 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( -1,250 ), wx.TE_MULTILINE)
            self.m_textCtrl1.SetMaxLength(10000)
    
            self.Submit = wx.Button( self, wx.ID_ANY, u"Submit", wx.DefaultPosition, wx.DefaultSize, 0 )
            staticbox.Add( self.Submit, 0, wx.ALL, 5 )
    
        def CreateExteriorWindowComponents(self):
            ''' Create "exterior" window components, such as menu and status
                bar. '''
            self.CreateMenu()
            self.CreateStatusBar()
            self.SetTitle()
    
        def CreateMenu(self):
            fileMenu = wx.Menu()
            for id, label, helpText, handler in \
                [(wx.ID_ABOUT, '&About', 'Storyteller 1.0 -',
                    self.OnAbout),
                 (wx.ID_OPEN, '&Open', 'Open a new file', self.OnOpen),
                 (wx.ID_SAVE, '&Save', 'Save the current file', self.OnSave),
                 (wx.ID_SAVEAS, 'Save &As', 'Save the file under a different name',
                    self.OnSaveAs),
                 (None, None, None, None),
                 (wx.ID_EXIT, 'E&xit', 'Terminate the program', self.OnExit)]:
                if id == None:
                    fileMenu.AppendSeparator()
                else:
                    item = fileMenu.Append(id, label, helpText)
                    self.Bind(wx.EVT_MENU, handler, item)
    
            menuBar = wx.MenuBar()
            menuBar.Append(fileMenu, '&File') # Add the fileMenu to the MenuBar
            self.SetMenuBar(menuBar)  # Add the menuBar to the Frame
    
        def SetTitle(self):
            # MainWindow.SetTitle overrides wx.Frame.SetTitle, so we have to
            # call it using super:
            super(MainWindow, self).SetTitle('Editor %s'%self.filename)
    
    
        # Helper methods:
    
        def defaultFileDialogOptions(self):
            ''' Return a dictionary with file dialog options that can be
                used in both the save file dialog as well as in the open
                file dialog. '''
            return dict(message='Choose a file', defaultDir=self.dirname,
                        wildcard='*.*')
    
        def askUserForFilename(self, **dialogOptions):
            dialog = wx.FileDialog(self, **dialogOptions)
            if dialog.ShowModal() == wx.ID_OK:
                userProvidedFilename = True
                self.filename = dialog.GetFilename()
                self.dirname = dialog.GetDirectory()
                self.SetTitle() # Update the window title with the new filename
            else:
                userProvidedFilename = False
            dialog.Destroy()
            return userProvidedFilename
    
        # Event handlers:
    
        def OnAbout(self, event):
            dialog = wx.MessageDialog(self, 'A sample editor\n'
                'in wxPython', 'About Sample Editor', wx.OK)
            dialog.ShowModal()
            dialog.Destroy()
    
        def OnExit(self, event):
            self.Close()  # Close the main window.
    
        def OnSave(self, event):
            textfile = open(os.path.join(self.dirname, self.filename), 'w')
            textfile.write(self.control.GetValue())
            textfile.close()
    
        def OnOpen(self, event):
            if self.askUserForFilename(style=wx.OPEN,
                                       **self.defaultFileDialogOptions()):
                textfile = open(os.path.join(self.dirname, self.filename), 'r')
                self.control.SetValue(textfile.read())
                textfile.close()
    
        def OnSaveAs(self, event):
            if self.askUserForFilename(defaultFile=self.filename, style=wx.SAVE,
                                       **self.defaultFileDialogOptions()):
                self.OnSave(event)
    
    
    app = wx.App()
    frame = MainWindow(None, "test")
    frame.Show()
    app.MainLoop()
    

    【讨论】:

      【解决方案2】:

      来自MainWindow 声明:

      def __init__(self, parent, title, *args, **kwargs):
      

      self 会在您实例化类时自动传递,但您需要将 parenttitle 传递给您的 MainWindow() 调用:

      frame = MainWindow(app, 'Window Title') # i'm not sure if app is right for parent, but i assume it is
      

      您可以忽略*args**kwargs,因为通读__init__ 函数根本不会用到它们...

      【讨论】:

      • @Bhavika 看来我对 parent 的需要有什么误解。它说它需要是另一个wxWindow。这就是我所知道的,对不起。也许其他人有这个新问题的答案。
      • 是的,我试过你说的,但是没有用。请参阅下面的解决方案!
      • @Bhavika,太棒了!很高兴有人知道他们在做什么。
      猜你喜欢
      • 1970-01-01
      • 2015-08-12
      • 1970-01-01
      • 1970-01-01
      • 2012-10-08
      • 2013-08-15
      • 1970-01-01
      • 1970-01-01
      • 2013-08-03
      相关资源
      最近更新 更多