• There is NO official Otland's Discord server and NO official Otland's server list. The Otland's Staff does not manage any Discord server or server list. Moderators or administrator of any Discord server or server lists have NO connection to the Otland's Staff. Do not get scammed!

Simple text editor.

Shiimi

I don't...
Joined
May 1, 2010
Messages
485
Reaction score
2
This is a tutorial for python when used with wx.

Too tired, I'll finish later.


I'll start with the source code.
Code:
import wx
import os.path

class MainWindow(wx.Frame):
    def __init__(self, filename='noname.txt'):
        super(MainWindow, self).__init__(None, size=(400,200))
        self.filename = filename
        self.dirname = '.'
        self.CreateInteriorWindowComponents()
        self.CreateExteriorWindowComponents()
    def CreateInteriorWindowComponents(self):
        ''' Create "interior" window components. In this case it is just a
            simple multiline text control. '''
        self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE)
    def CreateExteriorWindowComponents(self):
        ''' Create "exterior" window components, such as menu and status
            bar. '''
        self.CreateMenu()
        self.CreateStatusBar()
        self.SetTitle()
    def CreateMenu(self):
        fileMenu = wx.Menu()
        for id, label, helpText, handler in \
            [(wx.ID_ABOUT, '&About', 'Information about this program',
                self.OnAbout),
             (wx.ID_OPEN, '&Open', 'Open a new file', self.OnOpen),
             (wx.ID_SAVE, '&Save', 'Save the current file', self.OnSave),
             (wx.ID_SAVEAS, 'Save &As', 'Save the file under a different name',
                self.OnSaveAs),
             (None, None, None, None),
             (wx.ID_EXIT, 'E&xit', 'Terminate the program', self.OnExit)]:
            if id == None:
                fileMenu.AppendSeparator()
            else:
                item = fileMenu.Append(id, label, helpText)
                self.Bind(wx.EVT_MENU, handler, item)
        menuBar = wx.MenuBar()
        menuBar.Append(fileMenu, '&File') # Add the fileMenu to the MenuBar
        self.SetMenuBar(menuBar)  # Add the menuBar to the Frame
    def SetTitle(self):
        # MainWindow.SetTitle overrides wx.Frame.SetTitle, so we have to
        # call it using super:
        super(MainWindow, self).SetTitle('Editor %s'%self.filename)

    # Helper methods:
    def defaultFileDialogOptions(self):
        ''' Return a dictionary with file dialog options that can be
            used in both the save file dialog as well as in the open
            file dialog. '''
        return dict(message='Choose a file', defaultDir=self.dirname,
                    wildcard='*.*')
    def askUserForFilename(self, **dialogOptions):
        dialog = wx.FileDialog(self, **dialogOptions)
        if dialog.ShowModal() == wx.ID_OK:
            userProvidedFilename = True
            self.filename = dialog.GetFilename()
            self.dirname = dialog.GetDirectory()
            self.SetTitle() # Update the window title with the new filename
        else:
            userProvidedFilename = False
        dialog.Destroy()
        return userProvidedFilename
    # Event handlers:
    def OnAbout(self, event):
        dialog = wx.MessageDialog(self, 'A sample editor\n'
            'in wxPython', 'About Sample Editor', wx.OK)
        dialog.ShowModal()
        dialog.Destroy()
    def OnExit(self, event):
        self.Close()  # Close the main window.
    def OnSave(self, event):
        textfile = open(os.path.join(self.dirname, self.filename), 'w')
        textfile.write(self.control.GetValue())
        textfile.close()
    def OnOpen(self, event):
        if self.askUserForFilename(style=wx.OPEN,
                                   **self.defaultFileDialogOptions()):
            textfile = open(os.path.join(self.dirname, self.filename), 'r')
            self.control.SetValue(textfile.read())
            textfile.close()
    def OnSaveAs(self, event):
        if self.askUserForFilename(defaultFile=self.filename, style=wx.SAVE,
                                   **self.defaultFileDialogOptions()):
            self.OnSave(event)

app = wx.App()
frame = MainWindow()
frame.Show()
app.MainLoop()


First we start with a simple frame. To make a text box we use the wx.TextCtrl widget. By default, it is only a single-line input, but the wx.TE_MULTILINE parameter lets us enter multiple lines.

Code:
   1 #!/usr/bin/env python 
   2 import wx
   3 class MyFrame(wx.Frame):
   4     """ We simply derive a new class of Frame. """
   5     def __init__(self, parent, title):
   6         wx.Frame.__init__(self, parent, title=title, size=(200,100))
   7         self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE)
   8         self.Show(True)
   9 
  10 app = wx.App(False)
  11 frame = MyFrame(None, 'Small editor')
  12 app.MainLoop()

Now let's add a few menu bars. They are all pretty self explanatory and shouldn't really give much trouble.

Code:
   1 import wx
   2 
   3 class MainWindow(wx.Frame):
   4     def __init__(self, parent, title):
   5         wx.Frame.__init__(self, parent, title=title, size=(200,100))
   6         self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE)
   7         self.CreateStatusBar() # A Statusbar in the bottom of the window
   8 
   9         # Setting up the menu.
  10         filemenu= wx.Menu()
  11 
  12         # wx.ID_ABOUT and wx.ID_EXIT are standard IDs provided by wxWidgets.
  13         filemenu.Append(wx.ID_ABOUT, "&About"," Information about this program")
  14         filemenu.AppendSeparator()
  15         filemenu.Append(wx.ID_EXIT,"E&xit"," Terminate the program")
  16 
  17         # Creating the menubar.
  18         menuBar = wx.MenuBar()
  19         menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar
  20         self.SetMenuBar(menuBar)  # Adding the MenuBar to the Frame content.
  21         self.Show(True)
  22 
  23 app = wx.App(False)
  24 frame = MainWindow(None, "Sample editor")
  25 app.MainLoop()
 
Last edited:
I don't see any explainations here, just pasted code, sry.
 
First we start with a simple frame. To make a text box we use the wx.TextCtrl widget. By default, it is only a single-line input, but the wx.TE_MULTILINE parameter lets us enter multiple lines.

Now let's add a few menu bars. They are all pretty self explanatory and shouldn't really give much trouble.

Apparently you didn't read.
 
1) Nope, i don't know Python, but I know what Python and wxWidgets are.
2) If you aren't ready to make a tutorial, just wait 'till you will be ready to release complete tutorial.

Oh, and code seems simple cuz most of code is wxPython related. But atleast you should post some links to functions docs or describe them by yourself. What's the point of posting smth like this when none can learn from this? -.-

Imho. /thread.
 
1) Nope, i don't know Python, but I know what Python and wxWidgets are.
2) If you aren't ready to make a tutorial, just wait 'till you will be ready to release complete tutorial.

Oh, and code seems simple cuz most of code is wxPython related. But atleast you should post some links to functions docs or describe them by yourself. What's the point of posting smth like this when none can learn from this? -.-

Imho. /thread.

Because it's a tutorial for people who know python already. :thumbup:

It's called a gateway to real programming. Not the noob scripts that all the little skids on this forum think they can do, when in reality all they understand is how to edit existing code.
 
Back
Top