wxPython中标准文件选择框

 1 #/usr/bin/python

 2 #-*-<coding=UTF-8>-*-

 3 

 4 """

 5 本例为一个基本的wxPython GUI程序,主要展示了文件对话框是如何工作的.

 6 """

 7 

 8 import wx

 9 import os

10 

11 class GuiMainFrame(wx.Frame):

12     

13     def __init__(self):

14     wx.Frame.__init__(self,parent=None,id=-1,title="",pos=wx.DefaultPosition,size=wx.DefaultSize)

15     panel = wx.Panel(self)

16     panel.SetBackgroundColour("White")

17 

18     #menu bar

19     menubar = wx.MenuBar()

20     

21     #File menu

22     fileMenu = wx.Menu()

23     fileMenu.Append(-1,"&Open","")

24     menubar.Append(fileMenu,"&File")

25     self.Bind(wx.EVT_MENU,self.OnFileOpen)

26 

27     #Edit menu

28     editMenu = wx.Menu()

29     editMenu.Append(-1,"&Copy","")

30     menubar.Append(editMenu,"&Edit")

31 

32     #Help/About menu

33     helpMenu = wx.Menu()

34     helpMenu.Append(-1,"About","")

35     menubar.Append(helpMenu,"&Help")

36     

37     #调用SetMenuBar,使其在框架中显示出来

38     self.SetMenuBar(menubar)

39     

40     #添加工具栏,注意:用toolbar = wx.ToolBar()创建不行,会被其它的控件盖掉,这是为什么?

41     #toolbar = wx.ToolBar(self)

42     toolbar = self.CreateToolBar()

43     tsize = (24,24)

44     new_bmp = wx.ArtProvider.GetBitmap(wx.ART_NEW,wx.ART_TOOLBAR,tsize)

45     toolbar.AddSimpleTool(-1,new_bmp,"Long Help for 'New'")

46     toolbar.Realize()

47     

48     #添加状态栏

49     statusbar = self.CreateStatusBar()

50 

51     def OnFileOpen(self,event): 52     #创建标准文件对话框

53     dialog = wx.FileDialog(self,"Open file...",os.getcwd(),style=wx.OPEN,wildcard="*.py") 54     #这里有个概念:模态对话框和非模态对话框. 它们主要的差别在于模态对话框会阻塞其它事件的响应,

55     #而非模态对话框显示时,还可以进行其它的操作. 此处是模态对话框显示. 其返回值有wx.ID_OK,wx.ID_CANEL;

56     if dialog.ShowModal() == wx.ID_OK: 57         self.filename = dialog.GetPath() 58  self.OnFileRead() 59         #在TopWindow中更新标题为文件名.

60  self.SetTitle(self.filename) 61     #销毁对话框,释放资源.

62  dialog.Destroy() 63 

64     def OnFileRead(self): 65     if self.filename: 66         try: 67         fd = open(self.filename,'r') 68         line = fd.read() 69         #这里只是在终端显示文件内容. 可以实现在多行文本控件中显示. 这是下一步的工作.

70         print line 71  fd.close() 72         except: 73         wx.MessageBox("%s is not a match file." %self.filename,"oops!",style=wx.OK|wx.ICON_EXCLAMATION) 74 

75 if __name__ == "__main__":

76     app = wx.PySimpleApp()

77     frame = GuiMainFrame()

78     frame.Show()

79     app.MainLoop()

你可能感兴趣的:(wxPython)