2015-11-14 68 views
0

因此,我對編程很新穎。我目前正在Mac上的wxPython中製作一個簡單的文本編輯器(claaaassic)。我有一個綁定到事件saveFile()的「Save」菜單項,它將一個自定義類文件()作爲指定文件的目錄和文件類型的參數。一切看起來很正常,但由於某種原因,該方法在啓動時自動調用,並且在我實際單擊保存菜單項時不運行。任何幫助將非常感激!wxPython在啓動時自動執行事件,當它不應該

此外,下面的代碼只是我的程序的一個示例。

import wx 

# Custom class file 
class file(): 
    def __init__(self, directory, file_type): 
     self.directory = directory #location of file 
     self.file_type = file_type #type of file (text, HTML, etc.) 

# Main Frame 
class Frame1(wx.Frame): 
    def __init__(self, *args, **kwargs): 
     wx.Frame.__init__(self, None, -1, 'Text Program', size=(500, 700)) 
     self.Bind(wx.EVT_CLOSE, self.Exit) 
     self.f1 = file("/Users/Sasha/Desktop/File.txt", "Text File") # an example file 
     self.InitUI() 

    def InitUI(self): 
     self.text = wx.TextCtrl(self, style=wx.TE_MULTILINE) 
     self.CreateStatusBar() 
     # the reason we use "self.text" instead of just "text", is because if we want to use multiple windows, I believe 
     self.menu() 
     # Last. Centers and shows the window. 
     self.Centre() 
     self.Show() 

    # Save file, WHERE I HAVE PROBLEMS 
    def saveFile(self, a, file): 
     directory = file.directory 
     file_type = file.file_type 
     file = open(directory, "r+") #r+ is reading and writing, so if file is same, no need to write 
     print file.name + ",", file_type 
     l = file.read() 
     print l 
     file.close() 

    # Exit method, pops up with dialog to confirm quit 
    def Exit(self, a): 
     b = wx.MessageDialog(self, "Do you really want to close this application?", 'Confirm Exit', wx.CANCEL | wx.OK) 
     result = b.ShowModal() 
     if result == wx.ID_OK: 
      self.Destroy() 
     b.Destroy() 

    def menu(self): 
     # A shortcut method to bind a menu item to a method 
     def bindMethod(item, method): 
      self.Bind(wx.EVT_MENU, method, item) 

     # FILE 
     fileMenu = wx.Menu() 
     new = fileMenu.Append(wx.ID_NEW, "New") 
     save = fileMenu.Append(wx.ID_SAVE, "Save") 
     saveAs = fileMenu.Append(wx.ID_SAVEAS, "Save As") 
     bindMethod(new, self.newFile) 
     bindMethod(save, self.saveFile(self, self.f1)) # WHERE I MAY HAVE PROBLEMS 
     bindMethod(saveAs, self.saveAs) 

     menuBar = wx.MenuBar() 
     menuBar.Append(fileMenu, "&File") # Adding the "filemenu" to the MenuBar 
     self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content. 


if __name__ == '__main__': 
    app = wx.App() 
    frame = Frame1() 
    app.MainLoop() 

回答

0

你可以在你認爲你綁定它的同一行上調用該方法。不是傳遞方法,而是傳遞所調用方法的返回值。

在這一行,第二個參數是這樣的方法:

bindMethod(new, self.newFile) 

在這一行中,所述方法被調用,第二個參數是被返回的任何,例如無:

bindMethod(save, self.saveFile(self, self.f1)) 

當你,讓你綁定到方法名稱,並在那個地方不叫綁定方​​法,參數和未使用。當事件觸發時,wxPython應該使用正確的參數調用綁定的方法。

這也可能意味着您不能使用您擁有的參數,因爲給出了wx.EVT_MENU的回調。您需要創建某種文件對話框以獲取saveFile方法中的這些參數。

+0

所以基本上,當我調用綁定,我不能調用參數,因爲這實際上是做的方法,而不是綁定它?那麼你的意思是,我必須找到一種在'saveFile'方法中選擇'self.f1'文件的方法嗎? –

+0

@SashaAhrestani準確。 – Fenikso

相關問題