wx.FileHistory

The FileHistory is a menu item that displays a list of the most recently accessed files (from your application). This page will describe how to use it.

recent.png

Usage

   1 #!/usr/bin/env python
   2 
   3 import wx
   4 
   5 class Example(wx.Frame):
   6     def __init__(self):
   7         wx.Frame.__init__(self, parent=None, title="wx.FileHistory example")
   8         self.filehistory = wx.FileHistory(8)
   9         self.config = wx.Config("Your-Programs-Name", style=wx.CONFIG_USE_LOCAL_FILE)
  10         self.filehistory.Load(self.config)
  11 
  12         self.menu = wx.MenuBar()
  13         _file = wx.Menu()
  14         recent = wx.Menu()
  15         self.filehistory.UseMenu(recent)
  16         self.filehistory.AddFilesToMenu()
  17 
  18         _file.Append(wx.ID_OPEN, "&Open")
  19         _file.AppendMenu(wx.ID_ANY, "&Recent Files", recent)
  20         self.menu.Append(_file, "&File")
  21         self.SetMenuBar(self.menu)
  22 
  23         self.Bind(wx.EVT_MENU, self.do_open, id=wx.ID_OPEN)
  24         self.Bind(wx.EVT_MENU_RANGE, self.on_file_history, id=wx.ID_FILE1, id2=wx.ID_FILE9)
  25 
  26     def do_open(self, event):
  27         dlg = wx.FileDialog(self, "Open file...", style=wx.OPEN)
  28 
  29         if dlg.ShowModal() == wx.ID_OK:
  30             self.filehistory.AddFileToHistory(dlg.GetPath())
  31             self.filehistory.Save(self.config)
  32             self.config.Flush()
  33         else:
  34             dlg.Destroy()
  35 
  36 
  37     def on_file_history(self, event):
  38         fileNum = event.GetId() - wx.ID_FILE1
  39         path = self.filehistory.GetHistoryFile(fileNum)
  40         self.filehistory.AddFileToHistory(path)  # move up the list
  41         # do whatever you want with the file path...
  42 
  43 app = wx.App(False)
  44 frame = Example()
  45 frame.Show()
  46 app.MainLoop()

The integer parameter to the FileHistory is the maximum number of files to remember. We set up a wx.Config attribute that the FileHistory can read and write to. The call to Load() will ensure the file history is filled up with the last saved items when the application starts.

We then create a sub-menu for the FileHistory to be displayed in, and tell the filehistory attribute to use that menu. The call to AddFilesToMenu actually fills the menu, without this it would be empty.

When a user chooses a file from the open dialog, its path is added to the history list, and the config file is saved. Note the call to config.Flush() - the sample wouldn't work on Linux, otherwise.

To handle a click on the menu items, we bind to EVT_MENU_RANGE. I'm not sure why exactly we Bind to wx.ID_FILE1 and wx.ID_FILE9, but it works. :p

Well, that's about it!

Cheers,

StevenSproat -- 18 Jan 2010

Comments

FileHistory (last edited 2010-01-18 18:53:07 by 79-65-133-135)

NOTE: To edit pages in this wiki you must be a member of the TrustedEditorsGroup.