打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
wxPython:文件对话框wx.FileDialog

本节看一下文件对话框的使用,先看实例,再介绍具体知识点。

代码:

  1. #!/usr/bin/env python  
  2. # -*- coding: utf-8 -*-  
  3.   
  4. ''''' 
  5.     Function:绘图 
  6.     Input:NONE 
  7.     Output: NONE 
  8.     author: socrates 
  9.     blog:http://www.cnblogs.com/dyx1024/ 
  10.     date:2012-07-14 
  11. '''    
  12.   
  13. import wx  
  14. import cPickle  
  15. import os  
  16.   
  17. class PaintWindow(wx.Window):  
  18.         def __init__(self, parent, id):  
  19.             wx.Window.__init__(self, parent, id)  
  20.             self.SetBackgroundColour("Red")  
  21.             self.color = "Green"  
  22.             self.thickness = 10  
  23.           
  24.             #创建一个画笔  
  25.             self.pen = wx.Pen(self.color, self.thickness, wx.SOLID)  
  26.             self.lines = []  
  27.             self.curLine = []  
  28.             self.pos = (00)  
  29.             self.InitBuffer()  
  30.           
  31.             #连接事件  
  32.             self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)  
  33.             self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)  
  34.             self.Bind(wx.EVT_MOTION, self.OnMotion)  
  35.             self.Bind(wx.EVT_SIZE, self.OnSize)  
  36.             self.Bind(wx.EVT_IDLE, self.OnIdle)  
  37.             self.Bind(wx.EVT_PAINT, self.OnPaint)  
  38.           
  39.         def InitBuffer(self):  
  40.             size = self.GetClientSize()  
  41.               
  42.             #创建缓存的设备上下文  
  43.             self.buffer = wx.EmptyBitmap(size.width, size.height)  
  44.             dc = wx.BufferedDC(Noneself.buffer)  
  45.               
  46.             #使用设备上下文  
  47.             dc.SetBackground(wx.Brush(self.GetBackgroundColour()))  
  48.             dc.Clear()  
  49.             self.DrawLines(dc)  
  50.             self.reInitBuffer = False  
  51.               
  52.         def GetLinesData(self):  
  53.             return self.lines[:]  
  54.           
  55.         def SetLinesData(self, lines):  
  56.             self.lines = lines[:]  
  57.             self.InitBuffer()  
  58.             self.Refresh()  
  59.               
  60.         def OnLeftDown(self, event):  
  61.             self.curLine = []  
  62.               
  63.             #获取鼠标位置  
  64.             self.pos = event.GetPositionTuple()  
  65.             self.CaptureMouse()  
  66.               
  67.         def OnLeftUp(self, event):  
  68.             if self.HasCapture():  
  69.                 self.lines.append((self.color,  
  70.                                    self.thickness,  
  71.                                    self.curLine))  
  72.                 self.curLine = []  
  73.                 self.ReleaseMouse()  
  74.                   
  75.         def OnMotion(self, event):  
  76.             if event.Dragging() and event.LeftIsDown():  
  77.                 dc = wx.BufferedDC(wx.ClientDC(self), self.buffer)  
  78.                 self.drawMotion(dc, event)  
  79.             event.Skip()  
  80.           
  81.         def drawMotion(self, dc, event):  
  82.             dc.SetPen(self.pen)  
  83.             newPos = event.GetPositionTuple()  
  84.             coords = self.pos + newPos  
  85.             self.curLine.append(coords)  
  86.             dc.DrawLine(*coords)  
  87.             self.pos = newPos  
  88.               
  89.         def OnSize(self, event):  
  90.             self.reInitBuffer = True  
  91.           
  92.         def OnIdle(self, event):  
  93.             if self.reInitBuffer:  
  94.                 self.InitBuffer()  
  95.                 self.Refresh(False)  
  96.           
  97.         def OnPaint(self, event):  
  98.             dc = wx.BufferedPaintDC(selfself.buffer)  
  99.               
  100.         def DrawLines(self, dc):  
  101.             for colour, thickness, line in self.lines:  
  102.                 pen = wx.Pen(colour, thickness, wx.SOLID)  
  103.                 dc.SetPen(pen)  
  104.                 for coords in line:  
  105.                     dc.DrawLine(*coords)  
  106.           
  107.         def SetColor(self, color):  
  108.             self.color = color  
  109.             self.pen = wx.Pen(self.color, self.thickness, wx.SOLID)  
  110.               
  111.         def SetThickness(self, num):  
  112.             self.thickness = num  
  113.             self.pen = wx.Pen(self.color, self.thickness, wx.SOLID)  
  114.               
  115. class PaintFrame(wx.Frame):  
  116.       
  117.     def __init__(self, parent):  
  118.         self.title = "Paint Frame"  
  119.         wx.Frame.__init__(self, parent, -1self.title, size = (800600))  
  120.         self.paint = PaintWindow(self, -1)  
  121.           
  122.         #状态栏  
  123.         self.paint.Bind(wx.EVT_MOTION, self.OnPaintMotion)  
  124.         self.InitStatusBar()  
  125.           
  126.         #创建菜单  
  127.         self.CreateMenuBar()  
  128.           
  129.         self.filename = ""  
  130.   
  131.           
  132.     def InitStatusBar(self):  
  133.         self.statusbar = self.CreateStatusBar()  
  134.         #将状态栏分割为3个区域,比例为1:2:3  
  135.         self.statusbar.SetFieldsCount(3)  
  136.         self.statusbar.SetStatusWidths([-1, -2, -3])     
  137.           
  138.     def OnPaintMotion(self, event):  
  139.           
  140.         #设置状态栏1内容  
  141.         self.statusbar.SetStatusText(u"鼠标位置:" + str(event.GetPositionTuple()), 0)  
  142.           
  143.         #设置状态栏2内容  
  144.         self.statusbar.SetStatusText(u"当前线条长度:%s" % len(self.paint.curLine), 1)  
  145.           
  146.         #设置状态栏3内容  
  147.         self.statusbar.SetStatusText(u"线条数目:%s" % len(self.paint.lines), 2)     
  148.                
  149.         event.Skip()  
  150.           
  151.     def MenuData(self):  
  152.         ''''' 
  153.                    菜单数据 
  154.         '''  
  155.         #格式:菜单数据的格式现在是(标签, (项目)),其中:项目组成为:标签, 描术文字, 处理器, 可选的kind  
  156.         #标签长度为2,项目的长度是3或4  
  157.         return [("&File", (             #一级菜单项  
  158.                            ("&New""New paint file"self.OnNew),             #二级菜单项  
  159.                            ("&Open""Open paint file"self.OnOpen),  
  160.                            ("&Save""Save paint file"self.OnSave),  
  161.                            ("", "", ""),                                       #分隔线  
  162.                            ("&Color", (  
  163.                                        ("&Black", "", self.OnColor, wx.ITEM_RADIO),  #三级菜单项,单选  
  164.                                        ("&Red", "", self.OnColor, wx.ITEM_RADIO),  
  165.                                        ("&Green", "", self.OnColor, wx.ITEM_RADIO),   
  166.                                        ("&Blue", "", self.OnColor, wx.ITEM_RADIO))),  
  167.                            ("", "", ""),  
  168.                            ("&Quit""Quit"self.OnCloseWindow)))  
  169.                ]    
  170.     def CreateMenuBar(self):  
  171.         ''''' 
  172.         创建菜单 
  173.         '''  
  174.         menuBar = wx.MenuBar()  
  175.         for eachMenuData in self.MenuData():  
  176.             menuLabel = eachMenuData[0]  
  177.             menuItems = eachMenuData[1]  
  178.             menuBar.Append(self.CreateMenu(menuItems), menuLabel)   
  179.         self.SetMenuBar(menuBar)  
  180.           
  181.     def CreateMenu(self, menuData):  
  182.         ''''' 
  183.         创建一级菜单 
  184.         '''  
  185.         menu = wx.Menu()  
  186.         for eachItem in menuData:  
  187.             if len(eachItem) == 2:  
  188.                 label = eachItem[0]  
  189.                 subMenu = self.CreateMenu(eachItem[1])  
  190.                 menu.AppendMenu(wx.NewId(), label, subMenu) #递归创建菜单项  
  191.             else:  
  192.                 self.CreateMenuItem(menu, *eachItem)  
  193.         return menu  
  194.       
  195.     def CreateMenuItem(self, menu, label, status, handler, kind = wx.ITEM_NORMAL):  
  196.         ''''' 
  197.         创建菜单项内容 
  198.         '''  
  199.         if not label:  
  200.             menu.AppendSeparator()  
  201.             return  
  202.         menuItem = menu.Append(-1, label, status, kind)  
  203.         self.Bind(wx.EVT_MENU, handler,menuItem)  
  204.       
  205.     def OnNew(self, event):  
  206.         pass  
  207.       
  208.     def OnOpen(self, event):  
  209.         ''''' 
  210.         打开开文件对话框 
  211.         '''  
  212.         file_wildcard = "Paint files(*.paint)|*.paint|All files(*.*)|*.*"   
  213.         dlg = wx.FileDialog(self"Open paint file...",  
  214.                             os.getcwd(),   
  215.                             style = wx.OPEN,  
  216.                             wildcard = file_wildcard)  
  217.         if dlg.ShowModal() == wx.ID_OK:  
  218.             self.filename = dlg.GetPath()  
  219.             self.ReadFile()  
  220.             self.SetTitle(self.title + '--' + self.filename)  
  221.         dlg.Destroy()  
  222.           
  223.           
  224.       
  225.     def OnSave(self, event):   
  226.         ''''' 
  227.         保存文件 
  228.         '''  
  229.         if not self.filename:  
  230.             self.OnSaveAs(event)  
  231.         else:  
  232.             self.SaveFile()  
  233.               
  234.     def OnSaveAs(self, event):  
  235.         ''''' 
  236.         弹出文件保存对话框 
  237.         '''  
  238.         file_wildcard = "Paint files(*.paint)|*.paint|All files(*.*)|*.*"   
  239.         dlg = wx.FileDialog(self,   
  240.                             "Save paint as ...",  
  241.                             os.getcwd(),  
  242.                             style = wx.SAVE | wx.OVERWRITE_PROMPT,  
  243.                             wildcard = file_wildcard)  
  244.         if dlg.ShowModal() == wx.ID_OK:  
  245.             filename = dlg.GetPath()  
  246.             if not os.path.splitext(filename)[1]: #如果没有文件名后缀  
  247.                 filename = filename + '.paint'  
  248.             self.filename = filename  
  249.             self.SaveFile()  
  250.             self.SetTitle(self.title + '--' + self.filename)  
  251.         dlg.Destroy()      
  252.                      
  253.       
  254.     def OnColor(self, event):  
  255.         ''''' 
  256.         更改画笔内容 
  257.         '''  
  258.         menubar = self.GetMenuBar()  
  259.         itemid = event.GetId()  
  260.         item = menubar.FindItemById(itemid)  
  261.         color = item.GetLabel() #获取菜单项内容  
  262.         self.paint.SetColor(color)  
  263.           
  264.     def OnCloseWindow(self, event):  
  265.         self.Destroy()  
  266.           
  267.     def SaveFile(self):  
  268.         ''''' 
  269.         保存文件 
  270.         '''  
  271.         if self.filename:  
  272.             data = self.paint.GetLinesData()  
  273.             f = open(self.filename, 'w')  
  274.             cPickle.dump(data, f)  
  275.             f.close()  
  276.                        
  277.     def ReadFile(self):  
  278.         if self.filename:  
  279.             try:  
  280.                 f = open(self.filename, 'r')  
  281.                 data = cPickle.load(f)  
  282.                 f.close()  
  283.                 self.paint.SetLinesData(data)  
  284.             except cPickle.UnpicklingError:  
  285.                 wx.MessageBox("%s is not a paint file."  
  286.                               % self.filename, "error tip",  
  287.                               style = wx.OK | wx.ICON_EXCLAMATION)  
  288.        
  289.   
  290.               
  291. if __name__ == '__main__':  
  292.     app = wx.PySimpleApp()  
  293.     frame = PaintFrame(None)  
  294.     frame.Show(True)  
  295.     app.MainLoop()  

测试:

1、保存对话框:


2、打开对话框:


知识点介绍:

wx.FileDialog原型:

wxFileDialog(wxWindowparentconst wxStringmessage = "Choose a file"const wxStringdefaultDir = ""const wxString&defaultFile = ""const wxStringwildcard = "*.*"long style = wxFD_DEFAULT_STYLEconst wxPointpos = wxDefaultPosition,const wxSizesz = wxDefaultSizeconst wxStringname = "filedlg")

方法:

  • wxFileDialog::wxFileDialog
  • wxFileDialog::~wxFileDialog
  • wxFileDialog::GetDirectory
  • wxFileDialog::GetFilename
  • wxFileDialog::GetFilenames
  • wxFileDialog::GetFilterIndex
  • wxFileDialog::GetMessage
  • wxFileDialog::GetPath
  • wxFileDialog::GetPaths
  • wxFileDialog::GetWildcard
  • wxFileDialog::SetDirectory
  • wxFileDialog::SetFilename
  • wxFileDialog::SetFilterIndex
  • wxFileDialog::SetMessage
  • wxFileDialog::SetPath
  • wxFileDialog::SetWildcard
  • wxFileDialog::ShowModal

参数:

  • parentParent window.
  • messageMessage to show on the dialog.
  • defaultDirThe default directory, or the empty string.
  • defaultFileThe default filename, or the empty string.
  • wildcard
      A wildcard, such as "*.*" or "BMP files (*.bmp)|*.bmp|GIF files (*.gif)|*.gif".

                Note that the native Motif dialog has some limitations with respect to wildcards; see the Remarks section above.

  • styleA dialog style. See wxFD_* styles for more info.
  • posDialog position. Not implemented.
  • sizeDialog size. Not implemented.
  • name
      Dialog name. Not implemented.
                                          附:Style取值
wxFD_DEFAULT_STYLEEquivalent to wxFD_OPEN.
wxFD_OPENThis is an open dialog; usually this means that the default button's label of the dialog is "Open". Cannot be combined with wxFD_SAVE.
wxFD_SAVEThis is a save dialog; usually this means that the default button's label of the dialog is "Save". Cannot be combined with wxFD_OPEN.
wxFD_OVERWRITE_PROMPTFor save dialog only: prompt for a confirmation if a file will be overwritten.
wxFD_FILE_MUST_EXISTFor open dialog only: the user may only select files that actually exist.
wxFD_MULTIPLEFor open dialog only: allows selecting multiple files.
wxFD_CHANGE_DIRChange the current working directory to the directory where the file(s) chosen by the user are.
wxFD_PREVIEWShow the preview of the selected files (currently only supported by wxGTK using GTK+ 2.4 or later). 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
使用wxpython实现的一个简单图片浏览器实例
Linux wxPyhton指南(1)
wxPython中文教程 简单入门加实例
Python实例讲解- 定时播放
wxPython事件
wxPython:python 首选的 GUI 库
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服