Skip to content

Commit 95dc3fb

Browse files
added wxpython talk -- stil not fully converted
1 parent 604070a commit 95dc3fb

20 files changed

Lines changed: 3260 additions & 0 deletions
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+
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
[
2+
{
3+
"phone": "123-456-8888",
4+
"first_name": "Chris",
5+
"last_name": "Barker",
6+
"email": "PythonCHB@gmail.com"
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": "Wilson.Nancy@gmail.com"
19+
},
20+
{
21+
"phone": "555-555-5555",
22+
"first_name": "Charles",
23+
"last_name": "Dickens",
24+
"email": "chuck@victorian.england.com"
25+
}
26+
]
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
#!/usr/bin/env python
2+
3+
"""
4+
Example of a very basic, minimal wxPython address book application
5+
6+
This module defines the main Frame
7+
8+
"""
9+
10+
import os
11+
12+
import wx
13+
from address_book_data import AddressBook
14+
from entry_form import AddBookForm
15+
from switcher import Switcher
16+
17+
class AddBookFrame(wx.Frame):
18+
def __init__(self, add_book, *args, **kwargs):
19+
"""
20+
initilizer for the main from for the AddressBook app.
21+
22+
:param add_book: the address book class to manipulate
23+
:type add_book: A address_book_data.AddressBook instance
24+
25+
"""
26+
27+
kwargs.setdefault('title', "Micro Address Book")
28+
wx.Frame.__init__(self, *args, **kwargs)
29+
30+
self.add_book = add_book
31+
self.current_index = 0
32+
33+
# creae a status bar for messages...
34+
self.CreateStatusBar()
35+
36+
# create the entryPanel
37+
self.entryPanel = AddBookForm(add_book.book[self.current_index], self)
38+
39+
# put them in a Sizer to lay out
40+
S = wx.BoxSizer(wx.VERTICAL)
41+
S.Add(wx.StaticLine(self,style=wx.LI_HORIZONTAL), 0, wx.EXPAND)
42+
S.Add(self.entryPanel, 0, wx.ALL|wx.EXPAND, 4)
43+
S.Add((1,5))
44+
S.Add(wx.StaticLine(self,style=wx.LI_HORIZONTAL), 0, wx.EXPAND)
45+
46+
self.SetSizerAndFit(S)
47+
48+
# Build up the menu bar:
49+
menuBar = wx.MenuBar()
50+
51+
fileMenu = wx.Menu()
52+
53+
closeMenuItem = fileMenu.Append(wx.ID_EXIT, "&Close", "Close the file" )
54+
self.Bind(wx.EVT_MENU, self.onClose, closeMenuItem)
55+
56+
exitMenuItem = fileMenu.Append(wx.ID_EXIT, "Exit", "Exit the application")
57+
self.Bind(wx.EVT_MENU, self.onExit, exitMenuItem)
58+
menuBar.Append(fileMenu, "&File")
59+
60+
helpMenu = wx.Menu()
61+
helpMenuItem = helpMenu.Append(wx.ID_HELP, "Help", "Get help")
62+
menuBar.Append(helpMenu, "&Help")
63+
64+
self.SetMenuBar(menuBar)
65+
66+
def next(self):
67+
"""
68+
move to the next record in the address book
69+
"""
70+
try:
71+
self.entryPanel.entry = self.add_book.book[self.current_index+1]
72+
self.current_index+=1
73+
except IndexError:
74+
print "At end of records...."
75+
76+
def previous(self):
77+
"""
78+
move to the next record in the address book
79+
"""
80+
if self.current_index > 0:
81+
self.current_index-=1
82+
self.entryPanel.entry = self.add_book.book[self.current_index]
83+
84+
def onNewRecord(self, evt=None):
85+
index = self.add_book.new_record()
86+
self.entryPanel.entry = self.add_book.book[index]
87+
88+
def onOpen(self, evt=None):
89+
"""This method opens an existing file"""
90+
dlg = wx.FileDialog(
91+
self, message="Choose a file",
92+
defaultDir=os.getcwd(),
93+
defaultFile="",
94+
wildcard="*.json",
95+
style=wx.OPEN | wx.CHANGE_DIR
96+
)
97+
98+
# Show the dialog and retrieve the user response. If it is the OK response,
99+
# process the data.
100+
if dlg.ShowModal() == wx.ID_OK:
101+
# This returns a Python list of files that were selected.
102+
path = dlg.GetPath()
103+
print "I'd be opening file in onOpen ", path
104+
self.add_book.load_from_file(filename=path)
105+
else :
106+
print "The file dialog was canceled"
107+
dlg.Destroy()
108+
109+
110+
def onClose(self, evt=None):
111+
print "close menu selected"
112+
self.add_book.close()
113+
114+
def onExit(self, evt=None):
115+
print "Exit the program here"
116+
print "The event passed to onExit is type ", type(evt),
117+
self.Close()
118+
119+
120+
class AddBookApp(wx.App):
121+
def OnInit(self):
122+
"""
123+
App initilization goes here -- not much to do, in this case
124+
"""
125+
a_book = AddressBook()
126+
a_book.load_from_file()
127+
128+
f = AddBookFrame(a_book, parent=None)
129+
f.Show()
130+
131+
return True
132+
133+
if __name__ == "__main__":
134+
135+
app = AddBookApp(False)
136+
137+
138+
139+
## set up the WIT -- to help debug sizers
140+
import wx.lib.inspection
141+
wx.lib.inspection.InspectionTool().Show()
142+
app.MainLoop()
143+
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
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+
fields = [ "phone",
17+
"first_name",
18+
"last_name",
19+
"email",
20+
]
21+
22+
def __init__(self, filename="a_book.json"):
23+
self.filename = filename
24+
self.book = []
25+
self.new_record()
26+
27+
def new_record(self):
28+
"""
29+
and a new, empty record
30+
31+
:returns index: index of the new, empty record
32+
"""
33+
self.book.append(dict.fromkeys(self.fields, ""))
34+
return len(self.book) - 1
35+
36+
def save_to_file(self, filename=None):
37+
if filename is not None :
38+
self.filename = filename
39+
json.dump(self.book, open(self.filename, 'wb'), indent=4 )
40+
41+
def load_from_file(self, filename=None):
42+
if filename is not None :
43+
self.filename = filename
44+
self.book = json.load( open(self.filename, 'rb') )
45+
46+
def close(self):
47+
"""
48+
clear out the data...
49+
leave it with one empty dict
50+
"""
51+
del self.book[:]
52+
self.book.append({})
53+
54+
if __name__ == "__main__":
55+
import pprint
56+
a_book = AddressBook()
57+
a_book.load_from_file()
58+
59+
print "the data in the address book is:"
60+
pprint.pprint(a_book.book)
61+
62+
print
63+
print "the first entry is:"
64+
entry = a_book.book[0]
65+
print entry
66+
print "the first entry's name is:"
67+
print entry['first_name'], entry['last_name']
68+
69+
70+

0 commit comments

Comments
 (0)