wxPython 菜单事件 - 新建文件

wxPython Menu event - New File

我正在尝试制作一个简单的 wxpython GUI 程序,它具有基本的菜单功能,例如新建、打开和保存。 我能够创建带有正确标签的 GUI,但是当我单击“新建文件”时,程序不会打开新的 window。我在想这是我将新文件功能绑定到菜单的方式。

这是我的代码:

import wx

class david(wx.Frame):

  def __init__(self,parent,id):
    wx.Frame.__init__(self,parent,id,'wxPython Window',size=(300,200))
    panel=wx.Panel(self)

    status=self.CreateStatusBar()
    menubar=wx.MenuBar()
    file=wx.Menu()
    edit=wx.Menu()
    file.Append(wx.NewId(),"New File","This opens a new file")
    file.Append(wx.NewId(),"Open...","This opens an existing file")
    file.Append(wx.NewId(),"Save","Save the current file")
    menubar.Append(file,"File")
    menubar.Append(edit,"Edit")
    self.Bind(wx.EVT_MENU, self.NewFile, id=wx.ID_NEW)
    self.SetMenuBar(menubar)

  def NewFile(self,parent,id):
    wx.Frame.__init__(self,parent,id,'wxPython Window',size=(300,200))
    panel=wx.Panel(self)

    status=self.CreateStatusBar()
    menubar=wx.MenuBar()
    file=wx.Menu()
    edit=wx.Menu()
    file.Append(wx.NewId(),"New File","This opens a new file")
    file.Append(wx.NewId(),"Open...","This opens an existing file")
    file.Append(wx.NewId(),"Save","Save the current file")
    menubar.Append(file,"File")
    menubar.Append(edit,"Edit")
    self.SetMenuBar(menubar)


if __name__=='__main__':
  app=wx.App()
  frame=david(parent=None,id=-1)
  frame.Show()
  app.MainLoop()

看来您使用 Bind 的方式不正确。 id=wx.ID_NEW 将使事件绑定到一个不引用任何内容的新 ID。但是你想为文件使用菜单栏项目的ID,你可以在使用Append方法时得到它。

  ...
  newFileID = file.Append(wx.NewId(), "New File", "This opens a new file")
  ...
  self.Bind(wx.EVT_MENU, self.NewFile, newFileID)
  ...

此外,事件处理程序方法 NewFile 应该有两个只有一个参数 event,描述 here。 现在打开一个新的 window,有很多方法可以做到这一点,但最简单的方法是使用您已经编写的框架。请注意我使用的函数参数。

  def NewFile(self, event):
    frame = david(parent=None, id=-1)
    frame.Show()

关于样式的注意事项:在括号中分配值和值时尝试使用空格。 请参阅 this 了解 wxPython 的精彩介绍。