2017-01-01 193 views
0

我是Python新手,但我想了解使用wxpython的GUI。我正在使用模板創建框架,並添加了菜單。顯示菜單,但不會觸發任何操作,所以我需要將操作綁定到我創建的不同菜單項。問題是,我不知道如何。綁定菜單事件wxpython

我開始菜單保存,我把它叫做「menu_open」,並關聯到我使用相關聯的動作方法

filemenu.Append(wx.ID_OPEN, "Open")

self.Bind(wx.EVT_MENU, self.Open, menu_open)

,但我得到了錯誤:

AttributeError: 'MainWindow' object has no attribute 'Open'

如果我嘗試'OnOpen'(因爲有'OnExit'屬性),我得到的錯誤:

frame = MainWindow(None, "Sample editor")

AttributeError: 'MainWindow'object has no attribute 'OnOpen'

所以問題是:

  1. self.Bind語法正確,並分配到一個菜單中選擇操作的正確方法?
  2. 是否有wxPython中可用菜單的完整屬性列表?

我在報告整個代碼以供參考。謝謝。 G.

#!/usr/bin/python 
# -*- coding: utf-8 -*- 
from __future__ import print_function 

import wx 


class MainWindow(wx.Frame): 
    def __init__(self, parent, title): 
     wx.Frame.__init__(self, parent, title=title, size=(200, 100)) 
     self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE) 
     # A Statusbar in the bottom of the window 
     self.CreateStatusBar() 

     # Setting up the menus 
     '''Define main items''' 
     filemenu = wx.Menu() 
     editmenu = wx.Menu() 
     infomenu = wx.Menu() 
     '''Items''' 
     # file menu 
     menu_open = filemenu.Append(wx.ID_OPEN, "Open") 
     filemenu.Append(wx.ID_NEW, "New") 
     filemenu.Append(wx.ID_SAVE, "Save") 
     filemenu.Append(wx.ID_SAVEAS, "Save as") 
     filemenu.Append(wx.ID_EXIT, "Exit") 
     filemenu.AppendSeparator() 
     filemenu.Append(wx.ID_PRINT, "&Print") 
     filemenu.Append(wx.ID_PRINT_SETUP, "Print setup") 
     filemenu.Append(wx.ID_PREVIEW, "Preview") 
     # edit menu 
     editmenu.Append(wx.ID_COPY, "Copy") 
     editmenu.Append(wx.ID_CUT, "Cut") 
     editmenu.Append(wx.ID_PASTE, "Paste") 
     editmenu.AppendSeparator() 
     editmenu.Append(wx.ID_UNDO, "Undo") 
     editmenu.Append(wx.ID_REDO, "Re-do it") 
     # info menu 
     infomenu.Append(wx.ID_ABOUT, "About") 
     '''Bind items for activation''' 
     # bind file menu 
     self.Bind(wx.EVT_MENU, self.OnOpen, menu_open) 

     # Creating the menubar. 
     menuBar = wx.MenuBar() 
     # Add menus 
     menuBar.Append(filemenu, "&File") 
     menuBar.Append(editmenu, "&Edit") 
     menuBar.Append(infomenu, "&Help") 
     # Adding the MenuBar to the Frame content. 
     self.SetMenuBar(menuBar) 
     self.Show(True) 

app = wx.App(False) 
frame = MainWindow(None, "Sample editor") 
app.MainLoop() 

回答

2

您只需使用

self.Bind(wx.EVT_MENU, self.OnOpen, menu_open) 

時沒有創建事件處理方法,所以你需要一個將被調用添加到類主窗口

def OnOpen(self, event): 
    print('OnOpen') 
+0

我認爲這些方法'onOpen'等是從wx.MENU派生的標準方法,這就是爲什麼我也在尋找一個完整的方法列表... – Gigiux

+0

有一些標準的方法爲各種小部件,像'wx.Frame',但他們不不會自動映射到菜單事件 –

+0

是否有列表可獲取標準菜單項所需的操作代碼,如打開,保存,另存爲,新建等? – Gigiux