我正在尝试用 WxPython 编写一个图形用户界面,但我似乎无法弄清楚如何将方法绑定(bind)到事件。这是我当前的代码:
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()
当我运行程序时,框架和菜单看起来像我期望的那样。但是,只要单击菜单项“打开文件”,就会出现此错误:
TypeError: open_files() takes 1 positional argument but 2 were given
似乎在单击菜单项时传递了一些额外的参数,但我不知道该项目是什么以及我如何修改我的代码以使其正确运行(即函数被成功调用) .我需要在这里更改什么?
编辑:感谢 Patrick Artner 的解决方案。这解决了我发布的问题,然后我意识到我也错误地调用了 wx.FileDialog。这是解决了两个问题的更正代码:
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()
最佳答案
激活按钮 event被传递到句柄函数中。
参见 dynamic-event-handling一些容易遵循的食谱和一般的事件哭泣。
将函数更改为:
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()
关于python - self.Bind 上的 wxPython 方法 "takes 1 positional argument but 2 were given",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49870254/