Skip to content

Commit f773ec8

Browse files
Added code, etc, cleaned up presentation.
1 parent 1c9e67a commit f773ec8

18 files changed

+2912
-1
lines changed

week-08.5/Readme.rst

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,16 @@ Documentation and Examples:
5353

5454
There are many sources of documentation and examples. Start with the wxpython.org web site, but here are a few other pointers:
5555

56+
57+
Learning wxPython
58+
-------------------
59+
60+
This page is a good place to start:
61+
62+
http://wiki.wxpython.org/How%20to%20Learn%20wxPython
63+
64+
It has a lot of good hints for getting started.
65+
5666
The Demo
5767
----------
5868

@@ -73,7 +83,7 @@ http://www.blog.pythonlibrary.org/
7383
My Demo Collection
7484
--------------------
7585

76-
Over the years, I've built up a substantial collection of small wxPthon demos. Most of them are tiny stand-alone apps that test or demonstrate individual fetures of teh toolkit. you can find it on gitHub here:
86+
Over the years, I've built up a substantial collection of small wxPthon demos. Most of them are tiny stand-alone apps that test or demonstrate individual features of teh toolkit. you can find it on gitHub here:
7787

7888
https://github.com/PythonCHB/wxPythonDemos
7989

week-08.5/code/CalculatorDemo.py

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
#!/usr/bin/env python
2+
3+
"""
4+
wxPython Calculator Demo in 50 lines of code
5+
6+
This demo was pulled from the wxPython Wiki:
7+
8+
http://wiki.wxpython.org/CalculatorDemo
9+
by Miki Tebeka
10+
11+
It has been altered to allow it to be "driven" by an external script,
12+
plus a little layout improvement
13+
"""
14+
15+
16+
# Calculator GUI:
17+
18+
# ___________v
19+
# [7][8][9][/]
20+
# [4][5][6][*]
21+
# [1][2][3][-]
22+
# [0][.][C][+]
23+
# [ = ]
24+
25+
from __future__ import division # So that 8/3 will be 2.6666 and not 2
26+
27+
import wx
28+
29+
class Calculator(wx.Panel):
30+
'''Main calculator dialog'''
31+
def __init__(self, *args, **kwargs):
32+
wx.Panel.__init__(self, *args, **kwargs)
33+
sizer = wx.BoxSizer(wx.VERTICAL) # Main vertical sizer
34+
35+
self.display = wx.ComboBox(self) # Current calculation
36+
sizer.Add(self.display, 0, wx.EXPAND|wx.BOTTOM, 8) # Add to main sizer
37+
38+
# [7][8][9][/]
39+
# [4][5][6][*]
40+
# [1][2][3][-]
41+
# [0][.][C][+]
42+
gsizer = wx.GridSizer(4, 4, 8, 8)
43+
for row in (("7", "8", "9", "/"),
44+
("4", "5", "6", "*"),
45+
("1", "2", "3", "-"),
46+
("0", ".", "C", "+")):
47+
for label in row:
48+
b = wx.Button(self, label=label, size=(40,-1))
49+
gsizer.Add(b)
50+
b.Bind(wx.EVT_BUTTON, self.OnButton)
51+
sizer.Add(gsizer, 1, wx.EXPAND)
52+
53+
# [ = ]
54+
b = wx.Button(self, label="=")
55+
b.Bind(wx.EVT_BUTTON, self.OnButton)
56+
sizer.Add(b, 0, wx.EXPAND|wx.ALL, 8)
57+
self.equal = b
58+
59+
# Set sizer and center
60+
self.SetSizerAndFit(sizer)
61+
62+
def OnButton(self, evt):
63+
'''Handle button click event'''
64+
65+
# Get title of clicked button
66+
label = evt.GetEventObject().GetLabel()
67+
68+
if label == "=": # Calculate
69+
self.Calculate()
70+
elif label == "C": # Clear
71+
self.display.SetValue("")
72+
73+
else: # Just add button text to current calculation
74+
self.display.SetValue(self.display.GetValue() + label)
75+
self.display.SetInsertionPointEnd()
76+
self.equal.SetFocus() # Set the [=] button in focus
77+
78+
def Calculate(self):
79+
"""
80+
do the calculation itself
81+
82+
in a separate method, so it can be called outside of a button event handler
83+
"""
84+
try:
85+
compute = self.display.GetValue()
86+
# Ignore empty calculation
87+
if not compute.strip():
88+
return
89+
90+
# Calculate result
91+
result = eval(compute)
92+
93+
# Add to history
94+
self.display.Insert(compute, 0)
95+
96+
# Show result
97+
self.display.SetValue(str(result))
98+
except Exception, e:
99+
wx.LogError(str(e))
100+
return
101+
102+
def ComputeExpression(self, expression):
103+
"""
104+
Compute the expression passed in.
105+
106+
This can be called from another class, module, etc.
107+
"""
108+
print "ComputeExpression called with:", expression
109+
self.display.SetValue(expression)
110+
self.Calculate()
111+
112+
class MainFrame(wx.Frame):
113+
def __init__(self, *args, **kwargs):
114+
kwargs.setdefault('title', "Calculator")
115+
wx.Frame.__init__(self, *args, **kwargs)
116+
117+
self.calcPanel = Calculator(self)
118+
119+
# put the panel on -- in a sizer to give it some space
120+
S = wx.BoxSizer(wx.VERTICAL)
121+
S.Add(self.calcPanel, 1, wx.GROW|wx.ALL, 10)
122+
self.SetSizerAndFit(S)
123+
self.CenterOnScreen()
124+
125+
126+
if __name__ == "__main__":
127+
# Run the application
128+
app = wx.App(False)
129+
frame = MainFrame(None)
130+
frame.Show()
131+
app.MainLoop()
132+
6 KB
Binary file not shown.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
[
2+
{
3+
"phone": "123-456-7890",
4+
"first_name": "Chris",
5+
"last_name": "Barker",
6+
"email": "[email protected]"
7+
},
8+
{
9+
"phone": "510-555-1234",
10+
"first_name": "Fred",
11+
"last_name": "Jones",
12+
"email": "FredJones@some_company.com"
13+
},
14+
{
15+
"phone": "423-321-9876",
16+
"first_name": "Nancy",
17+
"last_name": "Wilson",
18+
"email": "[email protected]"
19+
}
20+
]
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
[
2+
{
3+
"first_name": "Chris",
4+
"last_name": "Barker",
5+
"office_phone": "123-456-7890",
6+
"home_phone": "206-555-1234",
7+
"address": {
8+
"line_1": "835 NE 33rd St",
9+
"city": "Seattle",
10+
"state": "WA",
11+
"line_2": "",
12+
"zip": "96543"
13+
},
14+
"cell_phone": "234-567-8901",
15+
"email": "[email protected]"
16+
},
17+
{
18+
"first_name": "Fred",
19+
"last_name": "Jones",
20+
"office_phone": "564-466-7990",
21+
"home_phone": "510-555-1234",
22+
"address": {
23+
"line_1": "123 SE 13th St",
24+
"city": "Tacoma",
25+
"state": "WA",
26+
"line_2": "Apt. 43",
27+
"zip": "93465"
28+
},
29+
"cell_phone": "403-561-8911",
30+
"email": "FredJones@some_company.com"
31+
},
32+
{
33+
"first_name": "Nancy",
34+
"last_name": "Wilson",
35+
"office_phone": "123-765-9877",
36+
"home_phone": "423-321-9876",
37+
"address": {
38+
"line_1": "8654 Walnut St",
39+
"city": "Pasadena",
40+
"state": "CA",
41+
"line_2": "Suite 567",
42+
"zip": "12345"
43+
},
44+
"cell_phone": "432-567-8466",
45+
"email": "[email protected]"
46+
}
47+
]
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
#!/usr/bin/env python
2+
3+
"""
4+
Example of the very basic, minimal wxPython address book application
5+
6+
This module defines the main Frame
7+
"""
8+
9+
import os
10+
11+
import wx
12+
from address_book_data import AddressBook
13+
from entry_form import AddBookForm
14+
15+
class AddBookFrame(wx.Frame):
16+
def __init__(self, add_book, *args, **kwargs):
17+
kwargs.setdefault('title', "Micro Address Book")
18+
wx.Frame.__init__(self, *args, **kwargs)
19+
20+
self.add_book = add_book
21+
self.current_index = 1
22+
23+
# put the Panel on the frame
24+
self.entryPanel = AddBookForm(add_book.book[self.current_index], self)
25+
26+
# Build up the menu bar:
27+
menuBar = wx.MenuBar()
28+
29+
fileMenu = wx.Menu()
30+
openMenuItem = fileMenu.Append(wx.ID_ANY, "&Open", "Open a file" )
31+
self.Bind(wx.EVT_MENU, self.onOpen, openMenuItem)
32+
33+
closeMenuItem = fileMenu.Append(wx.ID_ANY, "&Close", "Close a file" )
34+
self.Bind(wx.EVT_MENU, self.onClose, closeMenuItem)
35+
36+
exitMenuItem = fileMenu.Append(wx.ID_EXIT, "Exit", "Exit the application")
37+
self.Bind(wx.EVT_MENU, self.onExit, exitMenuItem)
38+
menuBar.Append(fileMenu, "&File")
39+
40+
helpMenu = wx.Menu()
41+
helpMenuItem = helpMenu.Append(wx.ID_HELP, "Help", "Get help")
42+
menuBar.Append(helpMenu, "&Help")
43+
44+
self.SetMenuBar(menuBar)
45+
46+
def onOpen(self, evt=None):
47+
"""This method opens an existing file"""
48+
print "Open a file: "
49+
# Create the dialog. In this case the current directory is forced as the starting
50+
# directory for the dialog, and no default file name is forced. This can easily
51+
# be changed in your program. This is an 'open' dialog, and allows multiple
52+
# file selections as well.
53+
#
54+
# Finally, if the directory is changed in the process of getting files, this
55+
# dialog is set up to change the current working directory to the path chosen.
56+
dlg = wx.FileDialog(
57+
self, message="Choose a file",
58+
defaultDir=os.getcwd(),
59+
defaultFile="",
60+
wildcard="*.json",
61+
style=wx.OPEN | wx.CHANGE_DIR
62+
)
63+
64+
# Show the dialog and retrieve the user response. If it is the OK response,
65+
# process the data.
66+
if dlg.ShowModal() == wx.ID_OK:
67+
# This returns a Python list of files that were selected.
68+
path = dlg.GetPath()
69+
print "I'd be opening file in onOpen ", path
70+
self.add_book.save_to_file( path )
71+
else :
72+
print "The file dialog was canceled before anything was selected"
73+
74+
# Destroy the dialog. Don't do this until you are done with it!
75+
# BAD things can happen otherwise!
76+
dlg.Destroy()
77+
78+
def onClose(self, evt=None):
79+
print "close menu selected"
80+
self.add_book.close()
81+
82+
def onExit(self, evt=None):
83+
print "Exit the program here"
84+
print "The event passed to onExit is type ", type(evt),
85+
self.Close()
86+
87+
88+
class AddBookApp(wx.App):
89+
def OnInit(self):
90+
"""
91+
App initilization goes here -- not much to do, in this case
92+
"""
93+
a_book = AddressBook()
94+
a_book.load_from_file()
95+
96+
f = AddBookFrame(a_book, parent=None)
97+
f.Show()
98+
99+
return True
100+
101+
if __name__ == "__main__":
102+
103+
app = AddBookApp(False)
104+
105+
106+
107+
## set up the WIT -- to help debug sizers
108+
# import wx.lib.inspection
109+
# wx.lib.inspection.InspectionTool().Show()
110+
app.MainLoop()
111+
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#!/usr/bin/env python
2+
3+
"""
4+
application logic code for ultra simple
5+
address book app...
6+
"""
7+
8+
import json
9+
10+
class AddressBook(object):
11+
"""
12+
very simple data model -- just a list of dicts
13+
14+
each dict represents an entry in the address book
15+
"""
16+
def __init__(self):
17+
self.book = [{},]
18+
self.filename = "a_book.json"
19+
20+
def save_to_file(self, filename=None):
21+
if filename is not None :
22+
self.filename = filename
23+
json.dump(self.book, open(self.filename, 'wb'), indent=4 )
24+
25+
def load_from_file(self, filename=None):
26+
if filename is not None :
27+
self.filename = filename
28+
self.book = json.load( open(self.filename, 'rb') )
29+
30+
def close(self):
31+
"""
32+
clear out the data...
33+
leave it with one empty dict
34+
"""
35+
del self.book[:]
36+
self.book.append({})
37+
38+
if __name__ == "__main__":
39+
import pprint
40+
a_book = AddressBook()
41+
a_book.load_from_file()
42+
43+
print "the data in the address book is:"
44+
pprint.pprint(a_book.book)
45+

0 commit comments

Comments
 (0)