1##Andrea Gavana
2#!/usr/bin/env python
3
4# This sample creates a "File->Open" menu, and lets the user select
5# a Python file. Upon selection, the file is read in memory and a new
6# wx.TextCtrl showing the file content is added as a page of a wx.Notebook
7
8import wx
9import os
10
11class NotebookFrame(wx.Frame):
12
13    def __init__(self, parent, title):
14
15        wx.Frame.__init__(self, parent, title=title)
16
17        # Create the notebook
18        self.notebook = wx.Notebook(self, style=wx.NB_BOTTOM)
19
20        # Setting up the menu
21        file_menu = wx.Menu()
22
23        # wx.ID_OPEN
24        menu_item = file_menu.Append(wx.ID_OPEN, '&Open...', 'Open and read a new Python file')
25        # Bind the "select menu item" event to the OnOpen event handler
26        self.Bind(wx.EVT_MENU, self.OnOpen, menu_item)
27
28        # Creating the menubar
29        menu_bar = wx.MenuBar()
30
31        # Adding the 'file_menu' to the menu bar
32        menu_bar.Append(file_menu, '&File')
33
34        # Adding the menu bar to the frame content
35        self.SetMenuBar(menu_bar)
36
37        self.Show()
38
39
40    def OnOpen(self, event):
41
42        # This is how you pre-establish a file filter so that the dialog
43        # only shows the extension(s) you want it to.
44        wildcard = 'Python source (*.py)|*.py'
45
46        dlg = wx.FileDialog(None, message="Choose a Python file", defaultDir=os.getcwd(),
47                            defaultFile="", wildcard=wildcard, style=wx.FD_OPEN)
48
49        # Show the dialog and retrieve the user response. If it is the OK response,
50        # process the data.
51        if dlg.ShowModal() == wx.ID_OK:
52            # This returns the file that was selected
53            path = dlg.GetPath()
54
55            # Open the file as read-only and slurp its content
56            fid = open(path, 'rt')
57            text = fid.read()
58            fid.close()
59
60            # Create the notebook page as a wx.TextCtrl and
61            # add it as a page of the wx.Notebook
62            text_ctrl = wx.TextCtrl(self.notebook, style=wx.TE_MULTILINE)
63            text_ctrl.SetValue(text)
64
65            filename = os.path.split(os.path.splitext(path)[0])[1]
66            self.notebook.AddPage(text_ctrl, filename, select=True)
67
68        # Destroy the dialog. Don't do this until you are done with it!
69        # BAD things can happen otherwise!
70        dlg.Destroy()
71
72
73app = wx.App(False)
74frame = NotebookFrame(None, 'Notebook example')
75app.MainLoop()
76