I'm trying to write a gui in WxPython, but I can't seem to figure out how to bind methods to events. Here is my current code:
class nlp_gui_class(wx.Frame):
def __init__(self, *args, **kw):
# ensure the parent's __init__ is called
super(nlp_gui_class, self).__init__(*args, **kw)
self.file_menu = wx.Menu()
self.setting_menu = wx.Menu()
self.menubar = None
self.filenames = []
self.createMenuBar()
self.createFileMenu()
self.CreateStatusBar()
self.SetStatusText("Corpus linguistics in Python")
def createFileMenu(self):
OPEN_FILE_ID = 101
open_file_item = self.file_menu.Append(OPEN_FILE_ID, "Open File(s)", "Open file(s)")
about_item = self.file_menu.Append(wx.ID_ABOUT, "About", "About")
self.file_menu.Append(wx.ID_EXIT, "Exit", "Close")
self.Bind(wx.EVT_MENU, self.open_files, open_file_item)
def createMenuBar(self):
menuBar = wx.MenuBar()
menuBar.Append(self.file_menu, "File") # Adding the "file_menu" to the MenuBar
self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content.
def open_files(self):
openFileDialog = wx.FileDialog(frame, "Choose corpus files",
wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.FD_MULTIPLE)
openFileDialog.ShowModal()
self.filenames.extend(openFileDialog.GetPaths())
openFileDialog.Destroy()
app = wx.App()
# Setting up the menu.
frame = nlp_gui_class(None, -1, 'nlp_gui')
frame.SetSize(0, 0, 200, 50)
# Creating the menubar.
frame.Show()
app.MainLoop()
When I run the program, The frame and menu look like what I expect. However, as soon as I click the menu item "Open File(s)", I get this error:
TypeError: open_files() takes 1 positional argument but 2 were given
It seems that some extra parameter is being passed when the menu item is being clicked, but I don't know what that item is and how I modify my code so that it runs correctly (i.e., the function is called successfully). What do I need to change here?
Edit: thanks to Patrick Artner for his solution. That solved the problem I posted about, and then I realized I had also called wx.FileDialog incorrectly. Here is the corrected code with both problems solved:
def open_files(self, event=None):
openFileDialog = wx.FileDialog(frame, message="Choose corpus files", style= wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.FD_MULTIPLE)
openFileDialog.ShowModal()
self.filenames.extend(openFileDialog.GetPaths())
openFileDialog.Destroy()
On aktivate of the button the event is passed into the handle-function.
See dynamic-event-handling for some easy recipies to follow and general Event blubbering.
Change the function to :
def open_files(self, event=None):
openFileDialog = wx.FileDialog(frame, "Choose corpus files",
wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.FD_MULTIPLE)
openFileDialog.ShowModal()
self.filenames.extend(openFileDialog.GetPaths())
openFileDialog.Destroy()