I recently picked up an excellent book titled "Beginning Python, From Novice to Professional" by Magnus Lie Hetland. So far, this book has turned out to be a very practical read with some solid examples. While I will certainly be churning out some original code in the near future, I thought this might be a very helpful starting place for many people out there, as it gives a small glimpse at many concepts for this language, including functions, event handlers, and button/textbox declarations using the lovely wxPython GUI Toolkit. For my own sanity, I have made some slight changes to the original source and placed my own embedded comments throughout the code to help explain each line of the code.
If you're curious, this miniature notepad application does indeed work! :)
1: #! /usr/bin/env python
2:
3: #Library imports
4: import wx
5:
6: #Open file function
7: def openFile(event):
8: file = open(filename.GetValue())
9: contents.SetValue(file.read())
10: file.close()
11:
12: #Save file function
13: def saveFile(event):
14: file = open(filename.GetValue(),'w')
15: file.write(contents.GetValue())
16: file.close()
17:
18: #Application object initialization
19: app = wx.App()
20:
21: #Creating main window frame that contains everything
22: win = wx.Frame(None, title="Chris' Notepad", size=(410, 335))
23:
24: #Creating a child background panel of our main window
25: bkg = wx.Panel(win)
26:
27: #Declaring the buttons and textboxes for the notepad application
28: loadButton = wx.Button(bkg, label='Open')
29: loadButton.Bind(wx.EVT_BUTTON, openFile)
30:
31: saveButton = wx.Button(bkg, label='Save')
32: saveButton.Bind(wx.EVT_BUTTON, saveFile)
33:
34: filename = wx.TextCtrl(bkg)
35: contents = wx.TextCtrl(bkg, style=wx.TE_MULTILINE | wx.HSCROLL)
36:
37: #Creating a boxsizer container to hold some objects for alignment
38: hbox = wx.BoxSizer()
39: hbox.Add(filename, proportion=1, flag=wx.EXPAND)
40: hbox.Add(loadButton, proportion=0, flag=wx.LEFT, border=5)
41: hbox.Add(saveButton, proportion=0, flag=wx.LEFT, border=5)
42:
43: #Creating a second boxsizer container to hold the hbox in addition to the contents object.
44: #This enables us to align everything into the vbox boxsizer, which we'll then bind.
45: vbox = wx.BoxSizer(wx.VERTICAL)
46: vbox.Add(hbox, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
47: vbox.Add(contents, proportion=1, flag=wx.EXPAND | wx.LEFT | wx.BOTTOM | wx.RIGHT, border=5)
48:
49: #Setting the window to make use of the vbox layout sizer.
50: bkg.SetSizer(vbox)
51:
52: #Makes sure the window is shown when the application is started.
53: win.Show()
54:
55: #Executing the main GUI event loop
56: app.MainLoop()
0 comments:
Post a Comment