This commit was manufactured by cvs2svn to create tag

'DEBIAN_2_4_3_1_SARGE_v_2_4_2_4'.

git-svn-id: https://svn.wxwidgets.org/svn/wx/wxWidgets/tags/DEBIAN_2_4_3_1_SARGE_v_2_4_2_4@34395 c3d73ce0-8a6f-49c7-b76d-6d57e0e08775
This commit is contained in:
Bryan Petty
2005-05-29 09:56:16 +00:00
parent 86118733af
commit cfd794784f
4010 changed files with 349688 additions and 169530 deletions

View File

@@ -1,6 +1,10 @@
*.pyc
.DS_Store
._demo.py
.emacs.desktop
.gdb_history
.setup.bat
.setup.sh
b.bat
hangman_dict.txt
mimetypes_wdr

View File

@@ -1,12 +1,12 @@
import sys, string
import sys
from wxPython.wx import *
from wxPython.html import *
import wxPython.lib.wxpTag
import wx # This module uses the new wx namespace
import wx.html
import wx.lib.wxpTag
#---------------------------------------------------------------------------
class MyAboutBox(wxDialog):
class MyAboutBox(wx.Dialog):
text = '''
<html>
<body bgcolor="#AC76DE">
@@ -29,36 +29,40 @@ sit back and enjoy. Be sure to take a peek at the source code for each
demo item so you can learn how to use the classes yourself.</p>
<p><b>wxPython</b> is brought to you by <b>Robin Dunn</b> and<br>
<b>Total Control Software,</b> Copyright (c) 1997-2002.</p>
<b>Total Control Software,</b> Copyright (c) 1997-2003.</p>
<p>
<font size="-1">Please see <i>license.txt</i> for licensing information.</font>
</p>
<p><wxp class="wxButton">
<p><wxp module="wx" class="Button">
<param name="label" value="Okay">
<param name="id" value="wxID_OK">
<param name="id" value="ID_OK">
</wxp></p>
</center>
</body>
</html>
'''
def __init__(self, parent):
wxDialog.__init__(self, parent, -1, 'About the wxPython demo',)
html = wxHtmlWindow(self, -1, size=(420, -1))
py_version = string.split(sys.version)[0]
html.SetPage(self.text % (wx.__version__, py_version))
btn = html.FindWindowById(wxID_OK)
wx.Dialog.__init__(self, parent, -1, 'About the wxPython demo',)
html = wx.html.HtmlWindow(self, -1, size=(420, -1))
py_version = sys.version.split()[0]
html.SetPage(self.text % (wx.VERSION_STRING, py_version))
btn = html.FindWindowById(wx.ID_OK)
btn.SetDefault()
ir = html.GetInternalRepresentation()
html.SetSize( (ir.GetWidth()+5, ir.GetHeight()+5) )
html.SetSize( (ir.GetWidth()+25, ir.GetHeight()+25) )
self.SetClientSize(html.GetSize())
self.CentreOnParent(wxBOTH)
self.CentreOnParent(wx.BOTH)
#---------------------------------------------------------------------------
if __name__ == '__main__':
app = wx.PySimpleApp()
dlg = MyAboutBox(None)
dlg.ShowModal()
dlg.Destroy()
app.MainLoop()

View File

@@ -62,7 +62,7 @@ class TestPanel(wxPanel):
sizer.Add(btnSizer, 0, wxEXPAND)
self.SetSizer(sizer)
self.SetAutoLayout(true)
self.SetAutoLayout(True)
EVT_WINDOW_DESTROY(self, self.OnDestroy)
@@ -121,7 +121,7 @@ if __name__ == '__main__':
app = wxPySimpleApp()
frame = TestFrame()
frame.Show(true)
frame.Show(True)
app.MainLoop()

View File

@@ -11,7 +11,7 @@ you can use just like wxWindow, (set the size and position, use in a
sizer, etc.) except its contents will be the COM control.
<p>
This demo embeds the Internet Exploer WebBrowser control, and shows
This demo embeds the Internet Explorer WebBrowser control, and shows
how to receive events from the COM control. (The title bar and status
bar are updated as pages change, in addition to the log messages being
shown.)
@@ -101,12 +101,18 @@ class TestPanel(wxWindow):
self.location.Append(self.current)
self.SetSizer(sizer)
self.SetAutoLayout(true)
self.SetAutoLayout(True)
EVT_SIZE(self, self.OnSize)
EVT_WINDOW_DESTROY(self, self.OnDestroy)
def ShutdownDemo(self):
# put the frame title back
if self.frame:
self.frame.SetTitle(self.titleBase)
def OnDestroy(self, evt):
if self.ie:
self.ie.Cleanup()
@@ -224,7 +230,7 @@ if __name__ == '__main__':
app = wxPySimpleApp()
frame = TestFrame()
frame.Show(true)
frame.Show(True)
app.MainLoop()

View File

@@ -0,0 +1,79 @@
from wxPython.wx import *
from wxPython.lib.analogclock import AnalogClockWindow
#----------------------------------------------------------------------
class TestPanel(wxPanel):
def __init__(self, parent, log):
self.log = log
wxPanel.__init__(self, parent, -1)
c1 = AnalogClockWindow(self)
c1.SetBackgroundColour("RED")
c1.SetHandsColour("BLUE")
c1.SetTickMarkColours("WHITE")
c2 = AnalogClockWindow(self)
c2.SetBackgroundColour("WHITE")
c2.SetHandsColour("RED")
c2.SetTickMarkColours("BLUE")
c3 = AnalogClockWindow(self)
c3.SetBackgroundColour("BLUE")
c3.SetHandsColour("WHITE")
c3.SetTickMarkColours("RED")
c4 = AnalogClockWindow(self, style=wxRAISED_BORDER)
c4.SetTickMarkStyle(AnalogClockWindow.TICKS_CIRCLE)
c5 = AnalogClockWindow(self)
c5.SetTickMarkStyle(AnalogClockWindow.TICKS_NONE)
c6 = AnalogClockWindow(self, style=wxSUNKEN_BORDER)
# layout the clocks in a grid
gs = wxGridSizer(2, 3, 4, 4)
gs.Add(c1, 0, wxEXPAND)
gs.Add(c2, 0, wxEXPAND)
gs.Add(c3, 0, wxEXPAND)
gs.Add(c4, 0, wxEXPAND)
gs.Add(c5, 0, wxEXPAND)
gs.Add(c6, 0, wxEXPAND)
# put it in another sizer for a border
sizer = wxBoxSizer(wxVERTICAL)
sizer.Add(gs, 1, wxEXPAND|wxALL, 10)
self.SetSizer(sizer)
#----------------------------------------------------------------------
def runTest(frame, nb, log):
win = TestPanel(nb, log)
return win
#----------------------------------------------------------------------
overview = """<html><body>
<h2><center>AnalogClockWindow</center></h2>
This is a nice little clock class that was contributed to by several
members of the wxPython-users group.
</body></html>
"""
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -28,7 +28,7 @@ class TestWindow(wxScrolledWindow):
dc = wxClientDC(self)
dc.SetFont(self.font)
w,h,d,e = dc.GetFullTextExtent("Wy") # a wide character and one that decends
w,h,d,e = dc.GetFullTextExtent("Wy") # a wide character and one that descends
self.textHeight = h + d
self.lineHeight = self.textHeight + 5
self.cellWidth = w
@@ -127,3 +127,10 @@ def runTest(frame, nb, log):
overview = """
"""
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -18,7 +18,6 @@
from wxPython.wx import *
from wxPython.lib.colourselect import *
import string
#----------------------------------------------------------------------------
@@ -26,7 +25,7 @@ class TestColourSelect(wxPanel):
def __init__(self, parent, log):
self.log = log
wxPanel.__init__(self, parent, -1)
self.SetAutoLayout(true)
self.SetAutoLayout(True)
mainSizer = wxBoxSizer(wxVERTICAL)
self.SetSizer(mainSizer)
t = wxStaticText(self, -1,
@@ -86,7 +85,7 @@ class TestColourSelect(wxPanel):
colour = button.GetColour() # get the colour selection button result
result.append(name + ": " + str(colour)) # create string list for easy viewing of results
out_result = string.joinfields(result, ', ')
out_result = ', '.join(result)
self.log.WriteText("Colour Results: " + out_result + "\n")
#---------------------------------------------------------------------------

View File

@@ -53,7 +53,7 @@ class TestPanel(wxPanel):
border = wxBoxSizer(wxVERTICAL)
border.Add(sizer, 0, wxALL, 25)
self.SetAutoLayout(true)
self.SetAutoLayout(True)
self.SetSizer(border)
self.Layout()
@@ -81,8 +81,8 @@ def runTest(frame, nb, log):
overview = """
This demo shows how to encorporate Context Sensitive
help into your applicaiton using the wxSimpleHelpProvider class.
This demo shows how to incorporate Context Sensitive
help into your application using the wxSimpleHelpProvider class.
"""
@@ -90,3 +90,10 @@ help into your applicaiton using the wxSimpleHelpProvider class.
#----------------------------------------------------------------------
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -124,7 +124,8 @@ class DoodleDropTarget(wxPyDropTarget):
self.dv = window
# specify the type of data we will accept
self.data = wxCustomDataObject(wxCustomDataFormat("DoodleLines"))
self.df = wxCustomDataFormat("DoodleLines")
self.data = wxCustomDataObject(self.df)
self.SetDataObject(self.data)
@@ -138,7 +139,7 @@ class DoodleDropTarget(wxPyDropTarget):
def OnDrop(self, x, y):
self.log.WriteText("OnDrop: %d %d\n" % (x, y))
return true
return True
def OnDragOver(self, x, y, d):
#self.log.WriteText("OnDragOver: %d, %d, %d\n" % (x, y, d))
@@ -153,7 +154,7 @@ class DoodleDropTarget(wxPyDropTarget):
# Called when OnDrop returns true. We need to get the data and
# Called when OnDrop returns True. We need to get the data and
# do something with it.
def OnData(self, x, y, d):
self.log.WriteText("OnData: %d, %d, %d\n" % (x, y, d))
@@ -205,7 +206,7 @@ class CustomDnDPanel(wxPanel):
def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1)
self.SetFont(wxFont(10, wxSWISS, wxNORMAL, wxBOLD, false))
self.SetFont(wxFont(10, wxSWISS, wxNORMAL, wxBOLD, False))
# Make the controls
text1 = wxStaticText(self, -1,
@@ -217,9 +218,9 @@ class CustomDnDPanel(wxPanel):
)
rb1 = wxRadioButton(self, -1, "Draw", style=wxRB_GROUP)
rb1.SetValue(true)
rb1.SetValue(True)
rb2 = wxRadioButton(self, -1, "Drag")
rb2.SetValue(false)
rb2.SetValue(False)
text2 = wxStaticText(self, -1,
"The lower window is accepting a\n"
@@ -249,7 +250,7 @@ class CustomDnDPanel(wxPanel):
sizer.Add(dndsizer, 1, wxEXPAND)
self.SetAutoLayout(true)
self.SetAutoLayout(True)
self.SetSizer(sizer)
# Events
@@ -269,12 +270,12 @@ class TestPanel(wxPanel):
def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1)
self.SetAutoLayout(true)
self.SetAutoLayout(True)
sizer = wxBoxSizer(wxVERTICAL)
msg = "Custom Drag-And-Drop"
text = wxStaticText(self, -1, "", style=wxALIGN_CENTRE)
text.SetFont(wxFont(24, wxSWISS, wxNORMAL, wxBOLD, false))
text.SetFont(wxFont(24, wxSWISS, wxNORMAL, wxBOLD, False))
text.SetLabel(msg)
w,h = text.GetTextExtent(msg)
text.SetSize(wxSize(w,h+1))
@@ -303,8 +304,9 @@ if __name__ == '__main__':
class TestApp(wxApp):
def OnInit(self):
wxInitAllImageHandlers()
self.MakeFrame()
return true
return True
def MakeFrame(self, event=None):
frame = wxFrame(None, -1, "Custom Drag and Drop", size=(550,400))
@@ -315,7 +317,7 @@ if __name__ == '__main__':
frame.SetMenuBar(mb)
EVT_MENU(frame, 6543, self.MakeFrame)
panel = TestPanel(frame, DummyLog())
frame.Show(true)
frame.Show(True)
self.SetTopWindow(frame)
@@ -326,21 +328,20 @@ if __name__ == '__main__':
#----------------------------------------------------------------------
overview = """<html><body>
This demo shows Drag and Drop using a custom data type and a custom
data object. A type called "DoodleLines" is created and a Python
Pickle of a list is actually transfered in the drag and drop
opperation.
A second data object is also created containing a bitmap of the image
and is made available to any drop target that accepts bitmaps, such as
MS Word.
overview = """\
This demo shows Drag and Drop using a custom data type and a custom data object. A type called "DoodleLines" is created and a Python Pickle of a list is actually transfered in the drag and drop opperation.
A second data object is also created containing a bitmap of the image and is made available to any drop target that accepts bitmaps, such as MS Word.
The two data objects are combined in a wxDataObjectComposite and the rest is handled by the framework.
The two data objects are combined in a wxDataObjectComposite and the
rest is handled by the framework.
</body></html>
"""

View File

@@ -88,13 +88,13 @@ if __name__ == "__main__":
# Create an instance of our customized Frame class
frame = MyFrame(None, -1, "This is a test")
frame.Show(true)
frame.Show(True)
# Tell wxWindows that this is our main window
self.SetTopWindow(frame)
# Return a success flag
return true
return True
app = MyApp(0) # Create an instance of the application class
@@ -107,7 +107,7 @@ if __name__ == "__main__":
def runTest(frame, nb, log):
win = MyFrame(frame, -1, "This is a test")
frame.otherWin = win
win.Show(true)
win.Show(True)
overview = """\

View File

@@ -8,7 +8,7 @@ class ClipTextPanel(wxPanel):
wxPanel.__init__(self, parent, -1)
self.log = log
#self.SetFont(wxFont(10, wxSWISS, wxNORMAL, wxBOLD, false))
#self.SetFont(wxFont(10, wxSWISS, wxNORMAL, wxBOLD, False))
sizer = wxBoxSizer(wxVERTICAL)
sizer.Add(wxStaticText(self, -1,
@@ -28,7 +28,7 @@ class ClipTextPanel(wxPanel):
EVT_BUTTON(self, 6051, self.OnPaste)
EVT_BUTTON(self, 6052, self.OnCopyBitmap)
self.SetAutoLayout(true)
self.SetAutoLayout(True)
self.SetSizer(sizer)
@@ -86,7 +86,7 @@ class OtherDropTarget(wxPyDropTarget):
def OnDrop(self, x, y):
self.log.WriteText("OnDrop: %d %d\n" % (x, y))
return true
return True
def OnData(self, x, y, d):
self.log.WriteText("OnData: %d, %d, %d\n" % (x, y, d))
@@ -128,7 +128,7 @@ class FileDropPanel(wxPanel):
def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1)
#self.SetFont(wxFont(10, wxSWISS, wxNORMAL, wxBOLD, false))
#self.SetFont(wxFont(10, wxSWISS, wxNORMAL, wxBOLD, False))
sizer = wxBoxSizer(wxVERTICAL)
sizer.Add(wxStaticText(self, -1, " \nDrag some files here:"),
@@ -148,7 +148,7 @@ class FileDropPanel(wxPanel):
self.text2.SetDropTarget(dt)
sizer.Add(self.text2, 1, wxEXPAND)
self.SetAutoLayout(true)
self.SetAutoLayout(True)
self.SetSizer(sizer)
@@ -166,12 +166,12 @@ class TestPanel(wxPanel):
def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1)
self.SetAutoLayout(true)
self.SetAutoLayout(True)
outsideSizer = wxBoxSizer(wxVERTICAL)
msg = "Clipboard / Drag-And-Drop"
text = wxStaticText(self, -1, "", style=wxALIGN_CENTRE)
text.SetFont(wxFont(24, wxSWISS, wxNORMAL, wxBOLD, false))
text.SetFont(wxFont(24, wxSWISS, wxNORMAL, wxBOLD, False))
text.SetLabel(msg)
w,h = text.GetTextExtent(msg)
text.SetSize(wxSize(w,h+1))
@@ -206,11 +206,38 @@ def runTest(frame, nb, log):
overview = """\
This demo shows some examples of data transfer through clipboard or drag and drop. In wxWindows, these two ways to transfer data (either between different applications or inside one and the same) are very similar which allows to implement both of them using almost the same code - or, in other words, if you implement drag and drop support for your application, you get clipboard support for free and vice versa.
At the heart of both clipboard and drag and drop operations lies the wxDataObject class. The objects of this class (or, to be precise, classes derived from it) represent the data which is being carried by the mouse during drag and drop operation or copied to or pasted from the clipboard. wxDataObject is a "smart" piece of data because it knows which formats it supports (see GetFormatCount and GetAllFormats) and knows how to render itself in any of them (see GetDataHere). It can also receive its value from the outside in a format it supports if it implements the SetData method. Please see the documentation of this class for more details.
Both clipboard and drag and drop operations have two sides: the source and target, the data provider and the data receiver. These which may be in the same application and even the same window when, for example, you drag some text from one position to another in a word processor. Let us describe what each of them should do.
overview = """<html><body>\
This demo shows some examples of data transfer through clipboard or
drag and drop. In wxWindows, these two ways to transfer data (either
between different applications or inside one and the same) are very
similar which allows to implement both of them using almost the same
code - or, in other words, if you implement drag and drop support for
your application, you get clipboard support for free and vice versa.
<p>
At the heart of both clipboard and drag and drop operations lies the
wxDataObject class. The objects of this class (or, to be precise,
classes derived from it) represent the data which is being carried by
the mouse during drag and drop operation or copied to or pasted from
the clipboard. wxDataObject is a "smart" piece of data because it
knows which formats it supports (see GetFormatCount and GetAllFormats)
and knows how to render itself in any of them (see GetDataHere). It
can also receive its value from the outside in a format it supports if
it implements the SetData method. Please see the documentation of this
class for more details.
<p>
Both clipboard and drag and drop operations have two sides: the source
and target, the data provider and the data receiver. These which may
be in the same application and even the same window when, for example,
you drag some text from one position to another in a word
processor. Let us describe what each of them should do.
</body></html>
"""
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -46,6 +46,43 @@ def makeRandomLines(num, w, h):
return pnts
def makeRandomRectangles(num, W, H):
rects = []
for i in range(num):
w = whrandom.randint(10, W/2)
h = whrandom.randint(10, H/2)
x = whrandom.randint(0, W - w)
y = whrandom.randint(0, H - h)
rects.append( (x, y, w, h) )
return rects
def makeRandomText(num):
Np = 8 # number of characters in text
text = []
for i in range(num):
word = []
for i in range(Np):
c = chr( whrandom.randint(48, 122) )
word.append( c )
text.append( "".join(word) )
return text
def makeRandomPolygons(num, W, H):
Np = 8 # number of points per polygon
polys = []
for i in range(num):
poly = []
for i in range(Np):
x = whrandom.randint(0, W)
y = whrandom.randint(0, H)
poly.append( (x,y) )
polys.append( poly )
return polys
def makeRandomPens(num, cache):
pens = []
for i in range(num):
@@ -57,62 +94,278 @@ def makeRandomPens(num, cache):
return pens
class TestPanel(wxPanel):
def __init__(self, parent, size, log):
wxPanel.__init__(self, parent, -1, size=size)
def makeRandomBrushes(num, cache):
brushes = []
for i in range(num):
c = whrandom.choice(colours)
if not cache.has_key(c):
cache[c] = wxBrush(c)
brushes.append( cache[c] )
return brushes
def makeRandomColors(num):
colors = []
for i in range(num):
c = whrandom.choice(colours)
colors.append(wxNamedColor(c))
return colors
pencache = {}
brushcache = {}
points = None
lines = None
rectangles = None
polygons = None
text = None
pens = None
brushes = None
colors1 = None
colors2 = None
def Init(w, h, n):
global pencache
global brushcache
global points
global lines
global rectangles
global polygons
global text
global pens
global brushes
global colors1
global colors2
# make some lists of random shapes
points = makeRandomPoints(n, w, h)
try:
import Numeric
Apoints = Numeric.array(points)
except:
pass
lines = makeRandomLines(n, w, h)
rectangles = makeRandomRectangles(n, w, h)
polygons = makeRandomPolygons(n, w, h)
text = makeRandomText(n)
# make some random pens and brushes
pens = makeRandomPens(n, pencache)
brushes = makeRandomBrushes(n, brushcache)
# make some random color lists
colors1 = makeRandomColors(n)
colors2 = makeRandomColors(n)
def TestPoints(dc,log):
dc.BeginDrawing()
start = time.time()
dc.SetPen(wxPen("BLACK", 4))
dc.DrawPointList(points)
dc.DrawPointList(points, wxPen("RED", 2))
dc.DrawPointList(points, pens)
dc.EndDrawing()
log.write("DrawTime: %s seconds with DrawPointList\n" % (time.time() - start))
def TestArrayPoints(dc,log):
try:
import Numeric
dc.BeginDrawing()
start = time.time()
dc.SetPen(wxPen("BLACK", 1))
for i in range(1):
dc.DrawPointList(Apoints)
#dc.DrawPointList(Apoints, wxPen("RED", 2))
#dc.DrawPointList(Apoints, pens)
dc.EndDrawing()
log.write("DrawTime: %s seconds with DrawPointList an Numpy Array\n" % (time.time() - start))
except ImportError:
log.write("Couldn't import Numeric")
pass
def TestLines(dc,log):
dc.BeginDrawing()
start = time.time()
dc.SetPen(wxPen("BLACK", 2))
dc.DrawLineList(lines)
dc.DrawLineList(lines, wxPen("RED", 2))
dc.DrawLineList(lines, pens)
dc.EndDrawing()
log.write("DrawTime: %s seconds with DrawLineList\n" % (time.time() - start))
def TestRectangles(dc,log):
dc.BeginDrawing()
start = time.time()
dc.SetPen( wxPen("BLACK",1) )
dc.SetBrush( wxBrush("RED") )
dc.DrawRectangleList(rectangles)
dc.DrawRectangleList(rectangles,pens)
dc.DrawRectangleList(rectangles,pens[0],brushes)
dc.DrawRectangleList(rectangles,pens,brushes[0])
dc.DrawRectangleList(rectangles,None,brushes)
## for i in range(10):
## #dc.DrawRectangleList(rectangles,pens,brushes)
## dc.DrawRectangleList(rectangles)
dc.EndDrawing()
log.write("DrawTime: %s seconds with DrawRectanglesList\n" % (time.time() - start))
def TestEllipses(dc,log):
dc.BeginDrawing()
start = time.time()
dc.SetPen( wxPen("BLACK",1) )
dc.SetBrush( wxBrush("RED") )
dc.DrawEllipseList(rectangles)
dc.DrawEllipseList(rectangles,pens)
dc.DrawEllipseList(rectangles,pens[0],brushes)
dc.DrawEllipseList(rectangles,pens,brushes[0])
dc.DrawEllipseList(rectangles,None,brushes)
dc.DrawEllipseList(rectangles,pens,brushes)
dc.EndDrawing()
log.write("DrawTime: %s seconds with DrawEllipsesList\n" % (time.time() - start))
def TestRectanglesArray(dc,log):
try:
import Numeric
Apoints = Numeric.array(rectangles)
dc.BeginDrawing()
start = time.time()
dc.SetPen(wxPen("BLACK", 1))
dc.DrawRectangleList(rectangles)
dc.DrawRectangleList(rectangles,pens)
dc.DrawRectangleList(rectangles,pens[0],brushes)
dc.DrawRectangleList(rectangles,pens,brushes[0])
dc.DrawRectangleList(rectangles,None,brushes)
## for i in range(10):
## #dc.DrawRectangleList(rectangles,pens,brushes)
## dc.DrawRectangleList(rectangles)
dc.EndDrawing()
log.write("DrawTime: %s seconds with DrawRectangleList and Numpy Array\n" % (time.time() - start))
except ImportError:
log.write("Couldn't import Numeric")
pass
def TestRectanglesLoop(dc,log):
dc.BeginDrawing()
start = time.time()
dc.DrawRectangleList(rectangles,pens,brushes)
log.write("DrawTime: %s seconds with DrawRectanglesList\n" % (time.time() - start))
start = time.time()
for i in range(len(rectangles)):
dc.SetPen( pens[i] )
dc.SetBrush( brushes[i] )
dc.DrawRectangle(rectangles[i][0],rectangles[i][1],rectangles[i][2],rectangles[i][3])
dc.EndDrawing()
log.write("DrawTime: %s seconds with Python loop\n" % (time.time() - start))
def TestPolygons(dc,log):
dc.BeginDrawing()
start = time.time()
dc.SetPen(wxPen("BLACK", 1))
dc.DrawPolygonList(polygons)
dc.DrawPolygonList(polygons,pens)
dc.DrawPolygonList(polygons,pens[0],brushes)
dc.DrawPolygonList(polygons,pens,brushes[0])
dc.DrawPolygonList(polygons,None,brushes)
log.write("DrawTime: %s seconds with DrawPolygonList\n" % (time.time() - start))
dc.EndDrawing()
def TestText(dc,log):
dc.BeginDrawing()
start = time.time()
# NOTE: you need to set BackgroundMode for the background colors to be used.
dc.SetBackgroundMode(wxSOLID)
foreground = colors1
background = colors2
dc.DrawTextList(text, points, foreground, background)
log.write("DrawTime: %s seconds with DrawTextList\n" % (time.time() - start))
dc.EndDrawing()
class TestNB(wxNotebook):
def __init__(self, parent, id, log):
style = wxNB_BOTTOM
if wxPlatform == "__WXMAC__":
style = 0
wxNotebook.__init__(self, parent, id, style=style)
self.log = log
win = DrawPanel(self, TestEllipses, log)
self.AddPage(win, 'Ellipses')
win = DrawPanel(self, TestText, log)
self.AddPage(win, 'Text')
win = DrawPanel(self, TestPolygons, log)
self.AddPage(win, 'Polygons')
win = DrawPanel(self, TestPoints, log)
self.AddPage(win, 'Points')
win = DrawPanel(self, TestLines, log)
self.AddPage(win, 'Lines')
win = DrawPanel(self, TestRectangles, log)
self.AddPage(win, 'Rectangles')
class DrawPanel(wxPanel):
def __init__(self, parent, drawFun, log):
wxPanel.__init__(self, parent, -1)
self.SetBackgroundColour(wxWHITE)
w = size.width
h = size.height
pencache = {}
# make some lists of random points
self.pnts1 = makeRandomPoints(1000, w, h)
self.pnts2 = makeRandomPoints(1000, w, h)
self.pnts3 = makeRandomPoints(1000, w, h)
self.pens1 = makeRandomPens(1000, pencache)
# and now some lines
self.lines1 = makeRandomLines(500, w, h)
self.lines2 = makeRandomLines(500, w, h)
self.lines3 = makeRandomLines(500, w, h)
self.pens2 = makeRandomPens(500, pencache)
self.log = log
self.drawFun = drawFun
EVT_PAINT(self, self.OnPaint)
def OnPaint(self, evt):
dc = wxPaintDC(self)
dc.BeginDrawing()
start = time.time()
dc.Clear()
self.drawFun(dc,self.log)
dc.SetPen(wxPen("BLACK", 1))
dc.DrawPointList(self.pnts1)
dc.DrawPointList(self.pnts2, wxPen("RED", 2))
dc.DrawPointList(self.pnts3, self.pens1)
dc.SetPen(wxPen("BLACK", 1))
dc.DrawLineList(self.lines1)
dc.DrawLineList(self.lines2, wxPen("RED", 2))
dc.DrawLineList(self.lines3, self.pens2)
dc.EndDrawing()
self.log.write("DrawTime: %s seconds\n" % (time.time() - start))
self.log.write("GetBoundingBox: %s\n" % (dc.GetBoundingBox(), ))
#----------------------------------------------------------------------
def runTest(frame, nb, log):
w = nb.GetClientSize().width
h = nb.GetClientSize().height
if w < 300: w = 300
if h < 300: h = 300
win = wxPanel(nb, -1)
tp = TestPanel(win, wxSize(w, h), log)
def OnPanelSize(evt, tp=tp):
tp.SetSize(evt.GetSize())
EVT_SIZE(win, OnPanelSize)
if w < 600: w = 600
if h < 400: h = 400
Init(w, h, 200)
win = TestNB(nb, -1, log)
return win
#----------------------------------------------------------------------
@@ -133,7 +386,33 @@ drawing routines. Currently they are:
DrawLineList(sequence, pens=None)
</pre>
Where sequence is a tuple, list, whatever of 4 element tuples
(x1,y1, x2,y2) andd pens is either None, a single pen or a list
(x1,y1, x2,y2) and pens is either None, a single pen or a list
of pens.
<pre>
DrawRectangleList(rectangles, pens=None, brushes=None)
</pre>
<pre>
DrawEllipseList(ellipses, pens=None, brushes=None)
</pre>
<pre>
DrawPolygonList(polygons, pens=None, brushes=None)
</pre>
<pre>
DrawTextList(textList, coords, foregrounds = None, backgrounds = None)
</pre>
"""
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -14,14 +14,14 @@ ID_BUTTON_wxPyNonFatalErrorDialog = 10004
ID_BUTTON_wxPyFatalErrorDialogWithTraceback = 10005
ID_BUTTON_wxPyNonFatalErrorDialogWithTraceback = 10006
def ErrorDialogsDemoPanelFunc( parent, call_fit = true, set_sizer = true ):
def ErrorDialogsDemoPanelFunc( parent, call_fit = True, set_sizer = True ):
item0 = wxBoxSizer( wxVERTICAL )
item1 = wxStaticText( parent, ID_TEXT, "Please select one of the buttons below for an example using explicit errors...", wxDefaultPosition, wxDefaultSize, 0 )
item0.AddWindow( item1, 0, wxALIGN_CENTRE|wxALL, 5 )
item2 = wxFlexGridSizer( 0, 2, 0, 0 )
item3 = wxButton( parent, ID_BUTTON_wxPyNonFatalError, "wxPyNonFatalError", wxDefaultPosition, wxDefaultSize, 0 )
item2.AddWindow( item3, 0, wxALIGN_CENTRE|wxALL, 5 )
@@ -34,7 +34,7 @@ def ErrorDialogsDemoPanelFunc( parent, call_fit = true, set_sizer = true ):
item0.AddWindow( item5, 0, wxALIGN_CENTRE|wxALL, 5 )
item6 = wxFlexGridSizer( 0, 2, 0, 0 )
item7 = wxButton( parent, ID_BUTTON_wxPyFatalErrorDialog, "wxPyFatalErrorDialog", wxDefaultPosition, wxDefaultSize, 0 )
item6.AddWindow( item7, 0, wxALIGN_CENTRE|wxALL, 5 )
@@ -51,16 +51,16 @@ def ErrorDialogsDemoPanelFunc( parent, call_fit = true, set_sizer = true ):
item0.AddSizer( item6, 0, wxALIGN_CENTRE|wxALL, 5 )
item11 = wxFlexGridSizer( 0, 2, 0, 0 )
item0.AddSizer( item11, 0, wxALIGN_CENTRE|wxALL, 5 )
if set_sizer == true:
parent.SetAutoLayout( true )
if set_sizer == True:
parent.SetAutoLayout( True )
parent.SetSizer( item0 )
if call_fit == true:
if call_fit == True:
item0.Fit( parent )
item0.SetSizeHints( parent )
return item0
# Menu bar functions
@@ -105,8 +105,8 @@ class MyPanel(wxPanel):
EVT_BUTTON(self,
ID_BUTTON_wxPyNonFatalErrorDialogWithTraceback,
self.DoDialog)
EVT_CLOSE(self,self.OnClose)
IndexFromID = {
ID_BUTTON_wxPyFatalErrorDialog: 3,
ID_BUTTON_wxPyFatalErrorDialogWithTraceback: 2,
@@ -138,10 +138,11 @@ class MyPanel(wxPanel):
print "%s.DoDialog(): testing %s..." % (self,sys.stderr)
this_will_generate_a_NameError_exception
def OnClose(self,evt):
def ShutdownDemo(self):
for d in self.dialogs:
d.Destroy ()
self.Destroy ()
d.Destroy()
class MyFrame(wxFrame):
def __init__(self,parent=None):
@@ -158,9 +159,9 @@ class MyFrame(wxFrame):
class MyApp(wxApp):
def OnInit(self):
frame = MyFrame()
frame.Show(true)
frame.Show(True)
self.SetTopWindow(frame)
return true
return True
def runTest(pframe, nb, log):
panel = MyPanel(nb)

View File

@@ -0,0 +1,287 @@
#---------------------------------------------------------------------------
# Name: EventManager.py
# Purpose: A module to demonstrate wxPython.lib.evtmgr.EventManager.
#
# Author: Robb Shecter (robb@acm.org)
#
# Created: 16-December-2002
# Copyright: (c) 2002 by Robb Shecter (robb@acm.org)
# Licence: wxWindows license
#---------------------------------------------------------------------------
from wxPython.wx import *
from wxPython.lib.evtmgr import eventManager
#----------------------------------------------------------------------
class TestPanel(wxPanel):
def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1)
self.log = log
fsize = self.GetFont().GetPointSize()
f1 = wxFont(fsize+0, wxSWISS, wxNORMAL, wxNORMAL)
f2 = wxFont(fsize+2, wxSWISS, wxNORMAL, wxBOLD)
f3 = wxFont(fsize+6, wxSWISS, wxNORMAL, wxBOLD)
title1 = wxStaticText(self, -1, 'EventManager')
title1.SetFont(f3)
txt = """\
This demo shows (1) basic uses and features of the EventManager, as well
as (2) how it helps with a real-world task: creating independent, object-
oriented components."""
message0 = wxStaticText(self, -1, txt)
message0.SetFont(f1)
title2 = wxStaticText(self, -1, 'Event Listeners')
title2.SetFont(f2)
txt = """\
These objects listen to motion events from the target window, using the ability
to register one event with multiple listeners. They also register for mouse events
on themselves to implement toggle-button functionality."""
message1 = wxStaticText(self, -1, txt)
message1.SetFont(f1)
title3 = wxStaticText(self, -1, 'Target Window')
title3.SetFont(f2)
txt = """\
A passive window that's used as an event generator. Move the mouse over it to
send events to the listeners above."""
message2 = wxStaticText(self, -1, txt)
message2.SetFont(f1)
targetPanel = Tile(self, log, bgColor=wxColor(80,10,10), active=0)
buttonPanel = wxPanel(self ,-1)
sizer = wxBoxSizer(wxHORIZONTAL)
target = targetPanel.tile
sizer.Add(0,0,1)
for factor in [0.2, 0.3, 0.4, 0.5, 0.6, 0.7]:
sizer.Add(Tile(buttonPanel, log, factor-0.05, target), 0, wxALIGN_CENTER)
sizer.Add(0,0,1)
sizer.Add(Tile(buttonPanel, log, factor, target), 0, wxALIGN_CENTER)
sizer.Add(0,0,1)
buttonPanel.SetAutoLayout(1)
buttonPanel.SetSizer(sizer)
sizer.Fit(buttonPanel)
sizer = wxBoxSizer(wxVERTICAL)
sizer.Add(title1, 0, wxALIGN_CENTER | wxTOP | wxBOTTOM, 6)
sizer.Add(message0, 0, wxALIGN_CENTER | wxALL, 6)
sizer.Add(title2, 0, wxALIGN_CENTER | wxLEFT | wxTOP | wxRIGHT, 16)
sizer.Add(message1, 0, wxALIGN_CENTER | wxALL, 6)
sizer.Add(buttonPanel, 0, wxEXPAND | wxLEFT | wxBOTTOM | wxRIGHT, 16)
sizer.Add(title3, 0, wxALIGN_CENTER | wxLEFT | wxRIGHT, 16)
sizer.Add(message2, 0, wxALIGN_CENTER | wxALL, 6)
sizer.Add(targetPanel, 2, wxEXPAND | wxLEFT | wxBOTTOM | wxRIGHT, 16)
self.SetAutoLayout(1)
self.SetSizer(sizer)
class Tile(wxPanel):
"""
This outer class is responsible for changing
its border color in response to certain mouse
events over its contained 'InnerTile'.
"""
normal = wxColor(150,150,150)
active = wxColor(250,245,245)
hover = wxColor(210,220,210)
def __init__(self, parent, log, factor=1, thingToWatch=None, bgColor=None, active=1, size=(38,38), borderWidth=3):
wxPanel.__init__(self, parent, -1, size=size, style=wxCLIP_CHILDREN)
self.tile = InnerTile(self, log, factor, thingToWatch, bgColor)
self.log = log
sizer = wxBoxSizer(wxHORIZONTAL)
sizer.Add(self.tile, 1, wxEXPAND | wxALL, borderWidth)
self.SetAutoLayout(1)
self.SetSizer(sizer)
self.Layout()
self.SetBackgroundColour(Tile.normal)
if active:
# Register myself for mouse events over self.tile in order to
# create typical button/hyperlink visual effects.
eventManager.Register(self.setHover, EVT_ENTER_WINDOW, self.tile)
eventManager.Register(self.setNormal, EVT_LEAVE_WINDOW, self.tile)
eventManager.Register(self.setActive, EVT_LEFT_DOWN, self.tile)
eventManager.Register(self.setHover, EVT_LEFT_UP, self.tile)
def setHover(self, event):
self.SetBackgroundColour(Tile.hover)
self.Refresh()
def setActive(self, event):
self.SetBackgroundColour(Tile.active)
self.Refresh()
def setNormal(self, event):
self.SetBackgroundColour(Tile.normal)
self.Refresh()
class InnerTile(wxPanel):
IDLE_COLOR = wxColor( 80, 10, 10)
START_COLOR = wxColor(200, 70, 50)
FINAL_COLOR = wxColor( 20, 80,240)
OFF_COLOR = wxColor(185,190,185)
# Some pre-computation.
DELTAS = map(lambda a,b: b-a, START_COLOR.Get(), FINAL_COLOR.Get())
START_COLOR_TUPLE = START_COLOR.Get()
"""
This inner panel changes its color in reaction to mouse
events over the 'thingToWatch'.
"""
def __init__(self, parent, log, factor, thingToWatch=None, bgColor=None):
wxPanel.__init__(self, parent, -1)
self.log=log
if bgColor:
self.SetBackgroundColour(bgColor)
if thingToWatch:
self.factor = factor
self.thingToWatch = thingToWatch
self.state = 0
self.toggleOnOff()
# Watch for the mouse click to enable/disable myself.
eventManager.Register(self.toggleOnOff, EVT_LEFT_UP, self)
def toggleOnOff(self, event=None):
# Implement being on or off by registering and
# de-registering self.makeColor() from the event manager.
if self.state:
eventManager.DeregisterListener(self.makeColor)
else:
eventManager.Register(self.makeColor, EVT_MOTION, self.thingToWatch)
self.state = 1 - self.state
self.resetColor()
def resetColor(self, event=None):
if self.state:
self.setColor(InnerTile.IDLE_COLOR)
else:
self.setColor(InnerTile.OFF_COLOR)
def setColor(self, color):
self.SetBackgroundColour(color)
self.Refresh()
def makeColor(self, mouseEvent):
self.makeColorFromTuple(mouseEvent.GetPositionTuple())
def makeColorFromTuple(self, (x, y)):
MAX = 180.0
scaled = min((x + y) * self.factor, MAX) # In range [0..MAX]
percent = scaled / MAX
r = InnerTile.START_COLOR_TUPLE[0] + (InnerTile.DELTAS[0] * percent)
g = InnerTile.START_COLOR_TUPLE[1] + (InnerTile.DELTAS[1] * percent)
b = InnerTile.START_COLOR_TUPLE[2] + (InnerTile.DELTAS[2] * percent)
self.setColor(wxColor(int(r), int(g), int(b)))
#----------------------------------------------------------------------
def runTest(frame, nb, log):
win = TestPanel(nb, log)
return win
#----------------------------------------------------------------------
overview = """<html><body>
<h2>EventManager</h2>
<p> The goal of the EventManager is to make wxWindows events more
'Pythonic' (ie. object-oriented) and easier to work with, without
impacting performance. It offers these features:
<p>
<ul>
<li> Allows any number of listeners to register for a single
event. (In addition to the standard wxPython feature of a single
listener being able to respond to many events.)
<li> Makes it easy to disconnect and reconnect listeners. This
has the effect of reducing the need for case-based branching in
application code.
<li> Has an object-oriented API. Programmers register to get
events directly from the objects that generate them, instead of
using ID numbers.
</ul>
<h3>Usage</h3>
<p>The EventManager class has three public methods. First get a
reference to it:
<PRE>
from wxPython.lib.evtmgr import eventManager
</PRE>
<p>...and then invoke any of the following methods. These methods are
'safe'; duplicate registrations or de-registrations will have no
effect.
<p><b>Registering a listener:</b>
<PRE>
eventManager.Register(listener, event, event-source)
</PRE>
<p><b>De-registering by window:</b>
<PRE>
eventManager.DeregisterWindow(event-source)
</PRE>
<p><b>De-registering by listener:</b>
<PRE>
eventManager.DeregisterListener(listener)
</PRE>
<p><b>Simple Example:</b>
<PRE>
from wxPython.lib.evtmgr import eventManager
aButton = wxButton(somePanel, -1, 'Click me')
eventManager.Register(self.someMethod, EVT_BUTTON, aButton)
</PRE>
<p> See the demo code as well as the documentation in the source of
<tt>wxPython.lib.evtmgr</tt> for more details.
<p>
by Robb Shecter (robb@acm.org)
</body></html>
"""
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -36,6 +36,13 @@ def runTest(frame, nb, log):
import string
overview = string.replace(fancytext.__doc__, "<", "&lt;")
overview = fancytext.__doc__.replace("<", "&lt;")
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -74,3 +74,12 @@ overview = """<html><body>
""" % ( FileBrowseButton.__doc__,
FileBrowseButtonWithHistory.__doc__ ,
str(DirBrowseButton.__doc__) )
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -0,0 +1,443 @@
from wxPython.wx import *
## Stuff to integrate FloatCanvas into wxPython Demo
try:
import Numeric
haveNumeric = True
except ImportError:
haveNumeric = False
if not haveNumeric:
errorText = """\
The FloatCanvas requires the Numeric module:
You can get it at:
http://sourceforge.net/projects/numpy
"""
def runTest(frame, nb, log):
dlg = wxMessageDialog(frame, errorText,
'Sorry', wxOK | wxICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
overview = ""
else:
def runTest(frame, nb, log):
"""
This method is used by the wxPython Demo Framework for integrating
this demo with the rest.
"""
win = DrawFrame(NULL, -1, "FloatCanvas Drawing Window",wxDefaultPosition,wxSize(500,500))
frame.otherWin = win
win.Show(True)
from wxPython.lib import floatcanvas
import wxPython.lib.colourdb
ID_ABOUT_MENU = wxNewId()
ID_EXIT_MENU = wxNewId()
ID_ZOOM_TO_FIT_MENU = wxNewId()
ID_DRAWTEST_MENU = wxNewId()
ID_LINETEST_MENU = wxNewId()
ID_DRAWMAP_MENU = wxNewId()
ID_DRAWMAP2_MENU = wxNewId()
ID_CLEAR_MENU = wxNewId()
wxPython.lib.colourdb.updateColourDB()
colors = wxPython.lib.colourdb.getColourList()
LineStyles = floatcanvas.draw_object.LineStyleList.keys()
class DrawFrame(wxFrame):
"""
A frame used for the FloatCanvas Demo
"""
def __init__(self,parent, id,title,position,size):
wxFrame.__init__(self,parent, id,title,position, size)
## Set up the MenuBar
MenuBar = wxMenuBar()
file_menu = wxMenu()
file_menu.Append(ID_EXIT_MENU, "&Close","Close this frame")
EVT_MENU(self, ID_EXIT_MENU, self.OnQuit)
MenuBar.Append(file_menu, "&File")
draw_menu = wxMenu()
draw_menu.Append(ID_DRAWTEST_MENU, "&Draw Test","Run a test of drawing random components")
EVT_MENU(self, ID_DRAWTEST_MENU,self.DrawTest)
draw_menu.Append(ID_LINETEST_MENU, "&Line Test","Run a test of drawing random lines")
EVT_MENU(self, ID_LINETEST_MENU,self.LineTest)
draw_menu.Append(ID_DRAWMAP_MENU, "Draw &Map","Run a test of drawing a map")
EVT_MENU(self, ID_DRAWMAP_MENU,self.DrawMap)
draw_menu.Append(ID_CLEAR_MENU, "&Clear","Clear the Canvas")
EVT_MENU(self, ID_CLEAR_MENU,self.Clear)
MenuBar.Append(draw_menu, "&Draw")
view_menu = wxMenu()
view_menu.Append(ID_ZOOM_TO_FIT_MENU, "Zoom to &Fit","Zoom to fit the window")
EVT_MENU(self, ID_ZOOM_TO_FIT_MENU,self.ZoomToFit)
MenuBar.Append(view_menu, "&View")
help_menu = wxMenu()
help_menu.Append(ID_ABOUT_MENU, "&About",
"More information About this program")
EVT_MENU(self, ID_ABOUT_MENU, self.OnAbout)
MenuBar.Append(help_menu, "&Help")
self.SetMenuBar(MenuBar)
self.CreateStatusBar()
self.SetStatusText("")
EVT_CLOSE(self, self.OnCloseWindow)
# Other event handlers:
EVT_RIGHT_DOWN(self, self.RightButtonEvent)
# Add the Canvas
self.Canvas = floatcanvas.FloatCanvas(self,-1,(500,500),
ProjectionFun = 'FlatEarth',
Debug = 0,
EnclosingFrame = self,
BackgroundColor = "DARK SLATE BLUE",
UseBackground = 0,
UseToolbar = 1)
self.Show(True)
self.object_list = []
return None
def RightButtonEvent(self,event):
print "Right Button has been clicked in DrawFrame"
print "coords are: %i, %i"%(event.GetX(),event.GetY())
event.Skip()
def OnAbout(self, event):
dlg = wxMessageDialog(self, "This is a small program to demonstrate\n"
"the use of the FloatCanvas\n",
"About Me", wxOK | wxICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
def SetMode(self,event):
for id in [ID_ZOOM_IN_BUTTON,ID_ZOOM_OUT_BUTTON,ID_MOVE_MODE_BUTTON]:
self.ToolBar.ToggleTool(id,0)
self.ToolBar.ToggleTool(event.GetId(),1)
if event.GetId() == ID_ZOOM_IN_BUTTON:
self.Canvas.SetGUIMode("ZoomIn")
elif event.GetId() == ID_ZOOM_OUT_BUTTON:
self.Canvas.SetGUIMode("ZoomOut")
elif event.GetId() == ID_MOVE_MODE_BUTTON:
self.Canvas.SetGUIMode("Move")
def ZoomToFit(self,event):
self.Canvas.ZoomToBB()
def Clear(self,event = None):
self.Canvas.RemoveObjects(self.object_list)
self.object_list = []
self.Canvas.Draw()
def OnQuit(self,event):
self.Close(True)
def OnCloseWindow(self, event):
self.Destroy()
def DrawTest(self,event):
wxGetApp().Yield()
import random
import RandomArray
Range = (-10,10)
Canvas = self.Canvas
object_list = self.object_list
## Random tests of everything:
# Rectangles
for i in range(5):
x,y = (random.uniform(Range[0],Range[1]),random.uniform(Range[0],Range[1]))
lw = random.randint(1,5)
cf = random.randint(0,len(colors)-1)
h = random.randint(1,5)
w = random.randint(1,5)
object_list.append(Canvas.AddRectangle(x,y,h,w,LineWidth = lw,FillColor = colors[cf]))
# Ellipses
for i in range(5):
x,y = (random.uniform(Range[0],Range[1]),random.uniform(Range[0],Range[1]))
lw = random.randint(1,5)
cf = random.randint(0,len(colors)-1)
h = random.randint(1,5)
w = random.randint(1,5)
object_list.append(Canvas.AddEllipse(x,y,h,w,LineWidth = lw,FillColor = colors[cf]))
# Dots
for i in range(5):
x,y = (random.uniform(Range[0],Range[1]),random.uniform(Range[0],Range[1]))
D = random.randint(1,50)
lw = random.randint(1,5)
cf = random.randint(0,len(colors)-1)
cl = random.randint(0,len(colors)-1)
object_list.append(Canvas.AddDot(x,y,D,LineWidth = lw,LineColor = colors[cl],FillColor = colors[cf]))
# Circles
for i in range(5):
x,y = (random.uniform(Range[0],Range[1]),random.uniform(Range[0],Range[1]))
D = random.randint(1,5)
lw = random.randint(1,5)
cf = random.randint(0,len(colors)-1)
cl = random.randint(0,len(colors)-1)
object_list.append(Canvas.AddCircle(x,y,D,LineWidth = lw,LineColor = colors[cl],FillColor = colors[cf]))
self.object_list.append(self.Canvas.AddText("Circle # %i"%(i),x,y,Size = 12,BackGround = None,Position = "cc"))
# Lines
for i in range(5):
points = []
for j in range(random.randint(2,10)):
point = (random.randint(Range[0],Range[1]),random.randint(Range[0],Range[1]))
points.append(point)
lw = random.randint(1,10)
cf = random.randint(0,len(colors)-1)
cl = random.randint(0,len(colors)-1)
self.object_list.append(self.Canvas.AddLine(points, LineWidth = lw, LineColor = colors[cl]))
# Polygons
for i in range(3):
points = []
for j in range(random.randint(2,6)):
point = (random.uniform(Range[0],Range[1]),random.uniform(Range[0],Range[1]))
points.append(point)
lw = random.randint(1,6)
cf = random.randint(0,len(colors)-1)
cl = random.randint(0,len(colors)-1)
self.object_list.append(self.Canvas.AddPolygon(points,
LineWidth = lw,
LineColor = colors[cl],
FillColor = colors[cf],
FillStyle = 'Solid'))
## Pointset
for i in range(4):
points = []
points = RandomArray.uniform(Range[0],Range[1],(100,2))
cf = random.randint(0,len(colors)-1)
D = random.randint(1,4)
self.object_list.append(self.Canvas.AddPointSet(points, Color = colors[cf], Diameter = D))
# Text
String = "Some text"
for i in range(10):
ts = random.randint(10,40)
cf = random.randint(0,len(colors)-1)
x,y = (random.uniform(Range[0],Range[1]),random.uniform(Range[0],Range[1]))
self.object_list.append(self.Canvas.AddText(String,x,y,Size = ts,ForeGround = colors[cf],Position = "cc"))
self.Canvas.ZoomToBB()
def DrawMap(self,event = None):
wxGetApp().Yield()
import os, time
## Test of Actual Map Data
self.Clear()
start = time.clock()
Shorelines = Read_MapGen(os.path.join("data",'world.dat'),stats = 0)
print "It took %f seconds to load %i shorelines"%(time.clock() - start,len(Shorelines) )
start = time.clock()
for segment in Shorelines:
self.object_list.append(self.Canvas.AddLine(segment))
print "It took %f seconds to add %i shorelines"%(time.clock() - start,len(Shorelines) )
start = time.clock()
self.Canvas.ZoomToBB()
print "It took %f seconds to draw %i shorelines"%(time.clock() - start,len(Shorelines) )
## def LineTest(self,event = None):
## wxGetApp().Yield()
## import os, time
## import random
## Range = (-10,10)
## ## Test of drawing lots of lines
## self.Clear()
## start = time.clock()
## linepoints = []
## linecolors = []
## linewidths = []
## linestyles = []
## for i in range(500):
## points = (random.randint(Range[0],Range[1]),
## random.randint(Range[0],Range[1]))
## linepoints.append(points)
## points = (random.randint(Range[0],Range[1]),
## random.randint(Range[0],Range[1]))
## linepoints.append(points)
## linewidths.append(random.randint(1,10) )
## linecolors.append(colors[random.randint(0,len(colors)-1) ])
## linestyles.append(LineStyles[random.randint(0, len(LineStyles)-1)])
## self.object_list.append(self.Canvas.AddLineSet(linepoints, LineWidths = linewidths, LineColors = linecolors, LineStyles = linestyles))
## print "It took %f seconds to add %i lines"%(time.clock() - start,len(linepoints) )
## start = time.clock()
## self.Canvas.ZoomToBB()
## print "It took %f seconds to draw %i lines"%(time.clock() - start,len(linepoints) )
def LineTest(self,event = None):
wxGetApp().Yield()
import os, time
import random
Range = (-10,10)
## Test of drawing lots of lines
self.Clear()
start = time.clock()
linepoints = []
linecolors = []
linewidths = []
for i in range(2000):
points = (random.randint(Range[0],Range[1]),
random.randint(Range[0],Range[1]),
random.randint(Range[0],Range[1]),
random.randint(Range[0],Range[1]))
linepoints.append(points)
linewidths.append(random.randint(1,10) )
linecolors.append(random.randint(0,len(colors)-1) )
for (points,color,width) in zip(linepoints,linecolors,linewidths):
self.object_list.append(self.Canvas.AddLine((points[0:2],points[2:4]), LineWidth = width, LineColor = colors[color]))
print "It took %f seconds to add %i lines"%(time.clock() - start,len(linepoints) )
start = time.clock()
self.Canvas.ZoomToBB()
print "It took %f seconds to draw %i lines"%(time.clock() - start,len(linepoints) )
class DemoApp(wxApp):
"""
How the demo works:
Under the Draw menu, there are three options:
*Draw Test: will put up a picture of a bunch of randomly generated
objects, of each kind supported.
*Draw Map: will draw a map of the world. Be patient, it is a big map,
with a lot of data, and will take a while to load and draw (about 10 sec
on my 450Mhz PIII). Redraws take about 2 sec. This demonstrates how the
performance is not very good for large drawings.
*Clear: Clears the Canvas.
Once you have a picture drawn, you can zoom in and out and move about
the picture. There is a tool bar with three tools that can be
selected.
The magnifying glass with the plus is the zoom in tool. Once selected,
if you click the image, it will zoom in, centered on where you
clicked. If you click and drag the mouse, you will get a rubber band
box, and the image will zoom to fit that box when you release it.
The magnifying glass with the minus is the zoom out tool. Once selected,
if you click the image, it will zoom out, centered on where you
clicked. (note that this takes a while when you are looking at the map,
as it has a LOT of lines to be drawn. The image is double buffered, so
you don't see the drawing in progress)
The hand is the move tool. Once selected, if you click and drag on the
image, it will move so that the part you clicked on ends up where you
release the mouse. Nothing is changed while you are dragging. The
drawing is too slow for that.
I'd like the cursor to change as you change tools, but the stock
wxCursors didn't include anything I liked, so I stuck with the
pointer. Please let me know if you have any nice cursor images for me to
use.
Any bugs, comments, feedback, questions, and especially code are welcome:
-Chris Barker
Chris.Barker@noaa.gov
"""
def OnInit(self):
frame = DrawFrame(NULL, -1, "FloatCanvas Demo App",wxDefaultPosition,wxSize(700,700))
self.SetTopWindow(frame)
return True
def Read_MapGen(filename,stats = 0,AllLines=0):
"""
This function reads a MapGen Format file, and
returns a list of NumPy arrays with the line segments in them.
Each NumPy array in the list is an NX2 array of Python Floats.
The demo should have come with a file, "world.dat" that is the
shorelines of the whole world, in MapGen format.
"""
import string
from Numeric import array
file = open(filename,'rt')
data = file.readlines()
data = map(string.strip,data)
Shorelines = []
segment = []
for line in data:
if line:
if line == "# -b": #New segment beginning
if segment: Shorelines.append(array(segment))
segment = []
else:
segment.append(map(float,string.split(line)))
if segment: Shorelines.append(array(segment))
if stats:
NumSegments = len(Shorelines)
NumPoints = 0
for segment in Shorelines:
NumPoints = NumPoints + len(segment)
AvgPoints = NumPoints / NumSegments
print "Number of Segments: ", NumSegments
print "Average Number of Points per segment: ",AvgPoints
if AllLines:
Lines = []
for segment in Shorelines:
Lines.append(segment[0])
for point in segment[1:-1]:
Lines.append(point)
Lines.append(point)
Lines.append(segment[-1])
#print Shorelines
#for point in Lines: print point
return Lines
else:
return Shorelines
## for the wxPython demo:
overview = floatcanvas.FloatCanvas.__doc__
if __name__ == "__main__":
if not haveNumeric:
print errorText
else:
app = DemoApp(0)
app.MainLoop()

View File

@@ -3,46 +3,56 @@ from wxPython.wx import *
#----------------------------------------------------------------------
## class MyFontEnumerator(wxFontEnumerator):
## def __init__(self, list):
## wxFontEnumerator.__init__(self)
## self.list = list
## def OnFacename(self, face):
## self.list.append(face)
## return true
class TestPanel(wxPanel):
def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1)
## list = []
## e = MyFontEnumerator(list)
## e.EnumerateFacenames()
e = wxFontEnumerator()
e.EnumerateFacenames()
list = e.GetFacenames()
list.sort()
wxStaticText(self, -1, "Face names:", (15, 50), (65, 18))
self.lb1 = wxListBox(self, -1, (80, 50), (200, 250),
s1 = wxStaticText(self, -1, "Face names:")
self.lb1 = wxListBox(self, -1, wxDefaultPosition, (200, 250),
list, wxLB_SINGLE)
EVT_LISTBOX(self, self.lb1.GetId(), self.OnSelect)
self.txt = wxStaticText(self, -1, "Sample text...", (285, 50))
row = wxBoxSizer(wxHORIZONTAL)
row.Add(s1, 0, wxALL, 5)
row.Add(self.lb1, 0, wxALL, 5)
row.Add(self.txt, 0, wxALL|wxADJUST_MINSIZE, 5)
sizer = wxBoxSizer(wxVERTICAL)
sizer.Add(row, 0, wxALL, 30)
self.SetSizer(sizer)
self.Layout()
self.lb1.SetSelection(0)
self.OnSelect(None)
wxFutureCall(300, self.SetTextSize)
def SetTextSize(self):
self.txt.SetSize(self.txt.GetBestSize())
def OnSelect(self, evt):
#print "OnSelect: "
face = self.lb1.GetStringSelection()
font = wxFont(28, wxDEFAULT, wxNORMAL, wxNORMAL, false, face)
#print '\t '+face
font = wxFont(28, wxDEFAULT, wxNORMAL, wxNORMAL, False, face)
#print "\t got font"
self.txt.SetLabel(face)
#print "\t set label"
self.txt.SetFont(font)
self.txt.SetSize(self.txt.GetBestSize())
#print "\t set font"
#self.txt.SetSize(self.txt.GetBestSize())
#print "\t set size"
## st = font.GetNativeFontInfo().ToString()
## ni2 = wxNativeFontInfo()
@@ -64,9 +74,12 @@ def runTest(frame, nb, log):
overview = """\
wxFontEnumerator enumerates either all available fonts on the system or only the ones with given attributes - either only fixed-width (suited for use in programs such as terminal emulators and the like) or the fonts available in the given encoding.
overview = """<html><body>
wxFontEnumerator enumerates either all available fonts on the system or only
the ones with given attributes - either only fixed-width (suited for use in
programs such as terminal emulators and the like) or the fonts available in
the given encoding.
</body></html>
"""

View File

@@ -28,12 +28,12 @@ class TestPanel(wxPanel):
b = wxGenButton(self, -1, 'disabled')
EVT_BUTTON(self, b.GetId(), self.OnButton)
b.Enable(false)
b.Enable(False)
sizer.Add(b)
b = wxGenButton(self, -1, 'bigger')
EVT_BUTTON(self, b.GetId(), self.OnBiggerButton)
b.SetFont(wxFont(20, wxSWISS, wxNORMAL, wxBOLD, false))
b.SetFont(wxFont(20, wxSWISS, wxNORMAL, wxBOLD, False))
b.SetBezelWidth(5)
###b.SetBestSize()
b.SetBackgroundColour("Navy")
@@ -46,6 +46,12 @@ class TestPanel(wxPanel):
EVT_BUTTON(self, b.GetId(), self.OnButton)
sizer.Add(b)
bmp = images.getTest2Bitmap()
b = wxGenBitmapButton(self, -1, bmp)
EVT_BUTTON(self, b.GetId(), self.OnButton)
sizer.Add(b)
b.Enable(False)
b = wxGenBitmapButton(self, -1, None)
EVT_BUTTON(self, b.GetId(), self.OnButton)
bmp = images.getBulb1Bitmap()
@@ -58,7 +64,6 @@ class TestPanel(wxPanel):
b.SetBitmapSelected(bmp)
b.SetBestSize()
sizer.Add(b)
sizer.Add(10,10)
b = wxGenToggleButton(self, -1, "Toggle Button")
EVT_BUTTON(self, b.GetId(), self.OnToggleButton)
@@ -74,7 +79,7 @@ class TestPanel(wxPanel):
mask = wxMaskColour(bmp, wxBLUE)
bmp.SetMask(mask)
b.SetBitmapSelected(bmp)
b.SetToggle(true)
b.SetToggle(True)
b.SetBestSize()
sizer.Add(b)
@@ -88,7 +93,7 @@ class TestPanel(wxPanel):
mask = wxMaskColour(bmp, wxBLUE)
bmp.SetMask(mask)
b.SetBitmapSelected(bmp)
b.SetUseFocusIndicator(false)
b.SetUseFocusIndicator(False)
b.SetBestSize()
sizer.Add(b)
@@ -128,3 +133,11 @@ def runTest(frame, nb, log):
import wxPython.lib.buttons
overview = wxPython.lib.buttons.__doc__
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -2,6 +2,7 @@
from wxPython.wx import *
from wxPython.grid import *
import string
#---------------------------------------------------------------------------
class MyCellEditor(wxPyGridCellEditor):
"""
@@ -86,16 +87,16 @@ class MyCellEditor(wxPyGridCellEditor):
def EndEdit(self, row, col, grid):
"""
Complete the editing of the current cell. Returns true if the value
Complete the editing of the current cell. Returns True if the value
has changed. If necessary, the control may be destroyed.
*Must Override*
"""
self.log.write("MyCellEditor: EndEdit (%d,%d)\n" % (row, col))
changed = false
changed = False
val = self._tc.GetValue()
if val != self.startValue:
changed = true
changed = True
grid.GetTable().SetValue(row, col, val) # update the table
self.startValue = ''
@@ -115,7 +116,7 @@ class MyCellEditor(wxPyGridCellEditor):
def IsAcceptedKey(self, evt):
"""
Return TRUE to allow the given key to start editing: the base class
Return True to allow the given key to start editing: the base class
version only checks that the event has no modifiers. F2 is special
and will always start the editor.
"""
@@ -143,12 +144,13 @@ class MyCellEditor(wxPyGridCellEditor):
elif key < 256 and key >= 0 and chr(key) in string.printable:
ch = chr(key)
if not evt.ShiftDown():
ch = string.lower(ch)
ch = ch.lower()
if ch is not None:
# For this example, replace the text. Normally we would append it.
#self._tc.AppendText(ch)
self._tc.SetValue(ch)
self._tc.SetInsertionPointEnd()
else:
evt.Skip()
@@ -226,7 +228,7 @@ if __name__ == '__main__':
import sys
app = wxPySimpleApp()
frame = TestFrame(None, sys.stdout)
frame.Show(true)
frame.Show(True)
app.MainLoop()

View File

@@ -1,8 +1,6 @@
from wxPython.wx import *
from wxPython.grid import *
import string
#---------------------------------------------------------------------------
class CustomDataTable(wxPyGridTableBase):
@@ -45,7 +43,10 @@ class CustomDataTable(wxPyGridTableBase):
return len(self.data[0])
def IsEmptyCell(self, row, col):
return not self.data[row][col]
try:
return not self.data[row][col]
except IndexError:
return true
# Get/Set values in the table. The Python version of these
# methods can handle any data-type, (as long as the Editor and
@@ -82,7 +83,7 @@ class CustomDataTable(wxPyGridTableBase):
# Called to determine the kind of editor/renderer to use by
# default, doesn't necessarily have to be the same type used
# nativly by the editor/renderer if they know how to convert.
# natively by the editor/renderer if they know how to convert.
def GetTypeName(self, row, col):
return self.dataTypes[col]
@@ -90,11 +91,11 @@ class CustomDataTable(wxPyGridTableBase):
# editor and renderer. This allows you to enforce some type-safety
# in the grid.
def CanGetValueAs(self, row, col, typeName):
colType = string.split(self.dataTypes[col], ':')[0]
colType = self.dataTypes[col].split(':')[0]
if typeName == colType:
return true
else:
return false
return False
def CanSetValueAs(self, row, col, typeName):
return self.CanGetValueAs(row, col, typeName)
@@ -120,7 +121,7 @@ class CustTableGrid(wxGrid):
self.SetRowLabelSize(0)
self.SetMargins(0,0)
self.AutoSizeColumns(false)
self.AutoSizeColumns(False)
EVT_GRID_CELL_LEFT_DCLICK(self, self.OnLeftDClick)
@@ -138,8 +139,22 @@ class CustTableGrid(wxGrid):
class TestFrame(wxFrame):
def __init__(self, parent, log):
wxFrame.__init__(self, parent, -1, "Custom Table, data driven Grid Demo", size=(640,480))
grid = CustTableGrid(self, log)
p = wxPanel(self, -1, style=0)
grid = CustTableGrid(p, log)
b = wxButton(p, -1, "Another Control...")
b.SetDefault()
EVT_BUTTON(self, b.GetId(), self.OnButton)
EVT_SET_FOCUS(b, self.OnButtonFocus)
bs = wxBoxSizer(wxVERTICAL)
bs.Add(grid, 1, wxGROW|wxALL, 5)
bs.Add(b)
p.SetSizer(bs)
def OnButton(self, evt):
print "button selected"
def OnButtonFocus(self, evt):
print "button focus"
#---------------------------------------------------------------------------

View File

@@ -0,0 +1,104 @@
"""
Example showing how to make a grid a drop target for files.
"""
from wxPython.wx import *
from wxPython.grid import *
#---------------------------------------------------------------------------
# Set VIRTUAL to 1 to use a virtual grid
VIRTUAL = 1
class GridFileDropTarget(wxFileDropTarget):
def __init__(self, grid):
wxFileDropTarget.__init__(self)
self.grid = grid
def OnDropFiles(self, x, y, filenames):
# the x,y coordinates here are Unscrolled coordinates. They must be changed
# to scrolled coordinates.
x, y = self.grid.CalcUnscrolledPosition(x, y)
# now we need to get the row and column from the grid
# but we need to first remove the RowLabel and ColumnLabel
# bounding boxes
# Why this isn't done for us, I'll never know...
x = x - self.grid.GetGridRowLabelWindow().GetRect().width
y = y - self.grid.GetGridColLabelWindow().GetRect().height
col = self.grid.XToCol(x)
row = self.grid.YToRow(y)
if row > -1 and col > -1:
self.grid.SetCellValue(row, col, filenames[0])
self.grid.AutoSizeColumn(col)
self.grid.Refresh()
class FooTable(wxPyGridTableBase):
def __init__(self):
wxPyGridTableBase.__init__(self)
self.dropTargets = {(0,0):"Drag",
(1,0):"A",
(2,0):"File",
(3,0):"To",
(4,0):"A",
(5,0):"Cell"}
def GetNumberCols(self):
return 100
def GetNumberRows(self):
return 100
def GetValue(self, row, col):
return self.dropTargets.get((row, col), "")
class SimpleGrid(wxGrid):
def __init__(self, parent, log):
wxGrid.__init__(self, parent, -1)
self.log = log
self.moveTo = None
if VIRTUAL:
self.table = FooTable()
self.SetTable(self.table)
else:
self.CreateGrid(25, 25)
# set the drag and drop target
dropTarget = GridFileDropTarget(self)
self.SetDropTarget(dropTarget)
self.EnableDragRowSize()
self.EnableDragColSize()
def SetCellValue(self, row, col, value):
if VIRTUAL:
self.table.dropTargets[row, col] = value
else:
wxGrid.SetCellValue(self, row, col, value)
class TestFrame(wxFrame):
def __init__(self, parent, log):
wxFrame.__init__(self, parent, -1, "DragAndDrop Grid", size=(640,480))
grid = SimpleGrid(self, log)
#---------------------------------------------------------------------------
if __name__ == '__main__':
import sys
app = wxPySimpleApp()
frame = TestFrame(None, sys.stdout)
frame.Show(True)
app.MainLoop()
#---------------------------------------------------------------------------

View File

@@ -0,0 +1,193 @@
from wxPython.wx import *
from wxPython.grid import *
from wxPython.lib.gridmovers import wxGridColMover, EVT_GRID_COL_MOVE
from wxPython.lib.gridmovers import wxGridRowMover, EVT_GRID_ROW_MOVE
#---------------------------------------------------------------------------
class CustomDataTable(wxPyGridTableBase):
"""
"""
def __init__(self, log):
wxPyGridTableBase.__init__(self)
self.log = log
self.identifiers = ['id','ds','sv','pr','pl','op','fx','ts']
self.rowLabels = ['Row1','Row2','Row3']
self.colLabels = {'id':'ID','ds':'Description','sv':'Severity',
'pr':'Priority','pl':'Platform','op':'Opened?',
'fx':'Fixed?','ts':'Tested?'}
self.data = [{'id':1010,
'ds':"The foo doesn't bar",
'sv':"major",
'pr':1,
'pl':'MSW',
'op':1,
'fx':1,
'ts':1
},
{'id':1011,
'ds':"I've got a wicket in my wocket",
'sv':"wish list",
'pr':2,
'pl':'other',
'op':0,
'fx':0,
'ts':0
},
{'id':1012,
'ds':"Rectangle() returns a triangle",
'sv':"critical",
'pr':5,
'pl':'all',
'op':0,
'fx':0,
'ts':0
}
]
#--------------------------------------------------
# required methods for the wxPyGridTableBase interface
def GetNumberRows(self):
return len(self.data)
def GetNumberCols(self):
return len(self.identifiers)
def IsEmptyCell(self, row, col):
id = self.identifiers[col]
return not self.data[row][id]
def GetValue(self, row, col):
id = self.identifiers[col]
return self.data[row][id]
def SetValue(self, row, col, value):
id = self.identifiers[col]
self.data[row][id] = value
#--------------------------------------------------
# Some optional methods
# Called when the grid needs to display column labels
def GetColLabelValue(self, col):
id = self.identifiers[col]
return self.colLabels[id]
# Called when the grid needs to display row labels
def GetRowLabelValue(self,row):
return self.rowLabels[row]
#--------------------------------------------------
# Methods added for demo purposes.
# The physical moving of the cols/rows is left to the implementer.
# Because of the dynamic nature of a wxGrid the physical moving of
# columns differs from implementation to implementation
# Move the column
def MoveColumn(self,frm,to):
grid = self.GetView()
if grid:
# Move the identifiers
old = self.identifiers[frm]
del self.identifiers[frm]
if to > frm:
self.identifiers.insert(to-1,old)
else:
self.identifiers.insert(to,old)
# Notify the grid
grid.BeginBatch()
msg = wxGridTableMessage(self,wxGRIDTABLE_NOTIFY_COLS_DELETED,
frm,1)
grid.ProcessTableMessage(msg)
msg = wxGridTableMessage(self,wxGRIDTABLE_NOTIFY_COLS_INSERTED,
to,1)
grid.ProcessTableMessage(msg)
grid.EndBatch()
# Move the row
def MoveRow(self,frm,to):
grid = self.GetView()
if grid:
# Move the rowLabels and data rows
oldLabel = self.rowLabels[frm]
oldData = self.data[frm]
del self.rowLabels[frm]
del self.data[frm]
if to > frm:
self.rowLabels.insert(to-1,oldLabel)
self.data.insert(to-1,oldData)
else:
self.rowLabels.insert(to,oldLabel)
self.data.insert(to,oldData)
# Notify the grid
grid.BeginBatch()
msg = wxGridTableMessage(self,wxGRIDTABLE_NOTIFY_ROWS_DELETED,
frm,1)
grid.ProcessTableMessage(msg)
msg = wxGridTableMessage(self,wxGRIDTABLE_NOTIFY_ROWS_INSERTED,
to,1)
grid.ProcessTableMessage(msg)
grid.EndBatch()
#---------------------------------------------------------------------------
class DragableGrid(wxGrid):
def __init__(self, parent, log):
wxGrid.__init__(self, parent, -1)
table = CustomDataTable(log)
# The second parameter means that the grid is to take ownership of the
# table and will destroy it when done. Otherwise you would need to keep
# a reference to it and call it's Destroy method later.
self.SetTable(table, True)
# Enable Column moving
wxGridColMover(self)
EVT_GRID_COL_MOVE(self,self.GetId(),self.OnColMove)
# Enable Row moving
wxGridRowMover(self)
EVT_GRID_ROW_MOVE(self,self.GetId(),self.OnRowMove)
# Event method called when a column move needs to take place
def OnColMove(self,evt):
frm = evt.GetMoveColumn() # Column being moved
to = evt.GetBeforeColumn() # Before which column to insert
self.GetTable().MoveColumn(frm,to)
# Event method called when a row move needs to take place
def OnRowMove(self,evt):
frm = evt.GetMoveRow() # Row being moved
to = evt.GetBeforeRow() # Before which row to insert
self.GetTable().MoveRow(frm,to)
#---------------------------------------------------------------------------
class TestFrame(wxFrame):
def __init__(self, parent, log):
wxFrame.__init__(self, parent, -1, "Custom Table, data driven Grid Demo", size=(640,480))
grid = DragableGrid(self, log)
#---------------------------------------------------------------------------
if __name__ == '__main__':
import sys
app = wxPySimpleApp()
frame = TestFrame(None, sys.stdout)
frame.Show(True)
app.MainLoop()
#---------------------------------------------------------------------------

View File

@@ -55,7 +55,7 @@ if __name__ == '__main__':
import sys
app = wxPySimpleApp()
frame = TestFrame(None, sys.stdout)
frame.Show(true)
frame.Show(True)
app.MainLoop()

View File

@@ -16,14 +16,24 @@ class HugeTable(wxPyGridTableBase):
wxPyGridTableBase.__init__(self)
self.log = log
def GetNumberRows(self):
self.odd=wxGridCellAttr()
self.odd.SetBackgroundColour("sky blue")
self.even=wxGridCellAttr()
self.even.SetBackgroundColour("sea green")
def GetAttr(self, row, col, kind):
attr = [self.even,self.odd][row%2]
attr.IncRef()
return attr
def GetNumberRows(self):
return 10000
def GetNumberCols(self):
return 10000
def IsEmptyCell(self, row, col):
return false
return False
def GetValue(self, row, col):
return str( (row, col) )
@@ -45,7 +55,15 @@ class HugeTableGrid(wxGrid):
# The second parameter means that the grid is to take ownership of the
# table and will destroy it when done. Otherwise you would need to keep
# a reference to it and call it's Destroy method later.
self.SetTable(table, true)
self.SetTable(table, True)
EVT_GRID_CELL_RIGHT_CLICK(self, self.OnRightDown) #added
def OnRightDown(self, event): #added
print "hello"
print self.GetSelectedRows() #added
@@ -56,7 +74,7 @@ class TestFrame(wxFrame):
wxFrame.__init__(self, parent, -1, "Huge (virtual) Table Demo", size=(640,480))
grid = HugeTableGrid(self, log)
grid.SetReadOnly(5,5, true)
grid.SetReadOnly(5,5, True)
#---------------------------------------------------------------------------
@@ -64,7 +82,7 @@ if __name__ == '__main__':
import sys
app = wxPySimpleApp()
frame = TestFrame(None, sys.stdout)
frame.Show(true)
frame.Show(True)
app.MainLoop()

View File

@@ -13,8 +13,8 @@ class SimpleGrid(wxGrid): ##, wxGridAutoEditMixin):
EVT_IDLE(self, self.OnIdle)
self.CreateGrid(25, 25)
##self.EnableEditing(false)
self.CreateGrid(25, 25) #, wxGrid.wxGridSelectRows)
##self.EnableEditing(False)
# simple cell formatting
self.SetColSize(3, 200)
@@ -26,9 +26,9 @@ class SimpleGrid(wxGrid): ##, wxGridAutoEditMixin):
self.SetCellFont(0, 0, wxFont(12, wxROMAN, wxITALIC, wxNORMAL))
self.SetCellTextColour(1, 1, wxRED)
self.SetCellBackgroundColour(2, 2, wxCYAN)
self.SetReadOnly(3, 3, true)
self.SetReadOnly(3, 3, True)
self.SetCellEditor(5, 0, wxGridCellNumberEditor())
self.SetCellEditor(5, 0, wxGridCellNumberEditor(1,1000))
self.SetCellValue(5, 0, "123")
self.SetCellEditor(6, 0, wxGridCellFloatEditor())
self.SetCellValue(6, 0, "123.34")
@@ -53,6 +53,23 @@ class SimpleGrid(wxGrid): ##, wxGridAutoEditMixin):
self.SetColLabelAlignment(wxALIGN_LEFT, wxALIGN_BOTTOM)
#self.SetDefaultCellOverflow(False)
#r = wxGridCellAutoWrapStringRenderer()
#self.SetCellRenderer(9, 1, r)
# overflow cells
self.SetCellValue( 9, 1, "This default cell will overflow into neighboring cells, but not if you turn overflow off.");
self.SetCellSize(11, 1, 3, 3);
self.SetCellAlignment(11, 1, wxALIGN_CENTRE, wxALIGN_CENTRE);
self.SetCellValue(11, 1, "This cell is set to span 3 rows and 3 columns");
editor = wxGridCellTextEditor()
editor.SetParameters('10')
self.SetCellEditor(0, 4, editor)
self.SetCellValue(0, 4, "Limited text")
# test all the events
EVT_GRID_CELL_LEFT_CLICK(self, self.OnCellLeftClick)
EVT_GRID_CELL_RIGHT_CLICK(self, self.OnCellRightClick)
@@ -141,7 +158,7 @@ class SimpleGrid(wxGrid): ##, wxGridAutoEditMixin):
# Show how to stay in a cell that has bad data. We can't just
# call SetGridCursor here since we are nested inside one so it
# won't have any effect. Instead, set coordinants to move to in
# won't have any effect. Instead, set coordinates to move to in
# idle time.
value = self.GetCellValue(evt.GetRow(), evt.GetCol())
if value == 'no good':
@@ -216,7 +233,7 @@ if __name__ == '__main__':
import sys
app = wxPySimpleApp()
frame = TestFrame(None, sys.stdout)
frame.Show(true)
frame.Show(True)
app.MainLoop()

View File

@@ -1,7 +1,7 @@
from wxPython.wx import *
from wxPython.grid import *
import string, random
import random
#---------------------------------------------------------------------------
@@ -60,7 +60,7 @@ editorDemoData = [
('wxGridCellBoolEditor', '1', wxGridCellBoolEditor, ()),
('wxGridCellChoiceEditor', 'one', wxGridCellChoiceEditor, (['one', 'two', 'three', 'four',
'kick', 'Microsoft', 'out the',
'door'], false)),
'door'], False)),
]
@@ -139,15 +139,15 @@ Renderers used together.
attr = wxGridCellAttr()
attr.SetFont(font)
attr.SetBackgroundColour(wxLIGHT_GREY)
attr.SetReadOnly(true)
attr.SetReadOnly(True)
attr.SetAlignment(wxRIGHT, -1)
self.SetColAttr(renCol, attr)
attr.IncRef()
self.SetColAttr(edCol, attr)
# There is a bug in wxGTK for this method...
self.AutoSizeColumns(true)
self.AutoSizeRows(true)
self.AutoSizeColumns(True)
self.AutoSizeRows(True)
EVT_GRID_CELL_LEFT_DCLICK(self, self.OnLeftDClick)
@@ -174,7 +174,7 @@ if __name__ == '__main__':
import sys
app = wxPySimpleApp()
frame = TestFrame(None, sys.stdout)
frame.Show(true)
frame.Show(True)
app.MainLoop()

View File

@@ -4,7 +4,7 @@
#
# Author: Lorne White (email: lorne.white@telusplanet.net)
#
# Version 0.5
# Version 0.5
# Date: Feb 26, 2001
# Licence: wxWindows license
#----------------------------------------------------------------------------
@@ -20,11 +20,11 @@ def runTest(frame, nb, log):
initial_dir = os.path.join(dir, 'bitmaps') # set the initial directory for the demo bitmaps
win = ImageDialog(frame, initial_dir) # open the image browser dialog
win.Centre()
if win.ShowModal() == wxID_OK:
if win.ShowModal() == wxID_OK:
log.WriteText("You Selected File: " + win.GetFile()) # show the selected file
else:
log.WriteText("You pressed Cancel\n")
#---------------------------------------------------------------------------
@@ -38,3 +38,12 @@ def runTest(frame, nb, log):
overview = """\
"""
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -21,38 +21,38 @@ class AnchorsDemoFrame(wxFrame):
self._init_utils()
self.mainPanel = wxPanel(size = wxSize(320, 160), parent = self, id = wxID_ANCHORSDEMOFRAMEMAINPANEL, name = 'panel1', style = wxTAB_TRAVERSAL | wxCLIP_CHILDREN, pos = wxPoint(0, 0))
self.mainPanel.SetAutoLayout(true)
self.mainPanel.SetAutoLayout(True)
self.okButton = wxButton(label = 'OK', id = wxID_ANCHORSDEMOFRAMEOKBUTTON, parent = self.mainPanel, name = 'okButton', size = wxSize(72, 24), style = 0, pos = wxPoint(240, 128))
self.okButton.SetConstraints(LayoutAnchors(self.okButton, false, false, true, true))
self.okButton.SetConstraints(LayoutAnchors(self.okButton, False, False, True, True))
EVT_BUTTON(self.okButton, wxID_ANCHORSDEMOFRAMEOKBUTTON, self.OnOkButtonButton)
self.backgroundPanel = wxPanel(size = wxSize(304, 80), parent = self.mainPanel, id = wxID_ANCHORSDEMOFRAMEBACKGROUNDPANEL, name = 'backgroundPanel', style = wxSIMPLE_BORDER | wxCLIP_CHILDREN, pos = wxPoint(8, 40))
self.backgroundPanel.SetBackgroundColour(wxColour(255, 255, 255))
self.backgroundPanel.SetConstraints(LayoutAnchors(self.backgroundPanel, true, true, true, true))
self.backgroundPanel.SetConstraints(LayoutAnchors(self.backgroundPanel, True, True, True, True))
self.anchoredPanel = wxPanel(size = wxSize(88, 48), id = wxID_ANCHORSDEMOFRAMEANCHOREDPANEL, parent = self.backgroundPanel, name = 'anchoredPanel', style = wxSIMPLE_BORDER, pos = wxPoint(104, 16))
self.anchoredPanel.SetBackgroundColour(wxColour(0, 0, 222))
self.anchoredPanel.SetConstraints(LayoutAnchors(self.anchoredPanel, false, false, false, false))
self.anchoredPanel.SetConstraints(LayoutAnchors(self.anchoredPanel, False, False, False, False))
self.leftCheckBox = wxCheckBox(label = 'Left', id = wxID_ANCHORSDEMOFRAMELEFTCHECKBOX, parent = self.mainPanel, name = 'leftCheckBox', size = wxSize(40, 16), style = 0, pos = wxPoint(8, 8))
self.leftCheckBox.SetConstraints(LayoutAnchors(self.leftCheckBox, false, true, false, false))
self.leftCheckBox.SetConstraints(LayoutAnchors(self.leftCheckBox, False, True, False, False))
EVT_CHECKBOX(self.leftCheckBox, wxID_ANCHORSDEMOFRAMELEFTCHECKBOX, self.OnCheckboxCheckbox)
self.topCheckBox = wxCheckBox(label = 'Top', id = wxID_ANCHORSDEMOFRAMETOPCHECKBOX, parent = self.mainPanel, name = 'topCheckBox', size = wxSize(40, 16), style = 0, pos = wxPoint(88, 8))
self.topCheckBox.SetConstraints(LayoutAnchors(self.topCheckBox, false, true, false, false))
self.topCheckBox.SetConstraints(LayoutAnchors(self.topCheckBox, False, True, False, False))
EVT_CHECKBOX(self.topCheckBox, wxID_ANCHORSDEMOFRAMETOPCHECKBOX, self.OnCheckboxCheckbox)
self.rightCheckBox = wxCheckBox(label = 'Right', id = wxID_ANCHORSDEMOFRAMERIGHTCHECKBOX, parent = self.mainPanel, name = 'rightCheckBox', size = wxSize(48, 16), style = 0, pos = wxPoint(168, 8))
self.rightCheckBox.SetConstraints(LayoutAnchors(self.rightCheckBox, false, true, false, false))
self.rightCheckBox.SetConstraints(LayoutAnchors(self.rightCheckBox, False, True, False, False))
EVT_CHECKBOX(self.rightCheckBox, wxID_ANCHORSDEMOFRAMERIGHTCHECKBOX, self.OnCheckboxCheckbox)
self.bottomCheckBox = wxCheckBox(label = 'Bottom', id = wxID_ANCHORSDEMOFRAMEBOTTOMCHECKBOX, parent = self.mainPanel, name = 'bottomCheckBox', size = wxSize(56, 16), style = 0, pos = wxPoint(248, 8))
self.bottomCheckBox.SetConstraints(LayoutAnchors(self.bottomCheckBox, false, true, false, false))
self.bottomCheckBox.SetConstraints(LayoutAnchors(self.bottomCheckBox, False, True, False, False))
EVT_CHECKBOX(self.bottomCheckBox, wxID_ANCHORSDEMOFRAMEBOTTOMCHECKBOX, self.OnCheckboxCheckbox)
self.helpStaticText = wxStaticText(label = 'Select anchor options above, then resize window to see the effect', id = wxID_ANCHORSDEMOFRAMEHELPSTATICTEXT, parent = self.mainPanel, name = 'helpStaticText', size = wxSize(224, 24), style = wxST_NO_AUTORESIZE, pos = wxPoint(8, 128))
self.helpStaticText.SetConstraints(LayoutAnchors(self.helpStaticText, true, false, true, true))
self.helpStaticText.SetConstraints(LayoutAnchors(self.helpStaticText, True, False, True, True))
def __init__(self, parent):
self._init_ctrls(parent)
@@ -71,7 +71,7 @@ class AnchorsDemoFrame(wxFrame):
def runTest(frame, nb, log):
win = AnchorsDemoFrame(frame)
frame.otherWin = win
win.Show(true)
win.Show(True)
@@ -136,5 +136,8 @@ overview = """<html><body>
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -8,7 +8,7 @@ class TestLayoutf(wxPanel):
def __init__(self, parent):
wxPanel.__init__(self, parent, -1)
self.SetAutoLayout(true)
self.SetAutoLayout(True)
EVT_BUTTON(self, 100, self.OnButton)
self.panelA = wxWindow(self, -1, wxPyDefaultPosition, wxPyDefaultSize, wxSIMPLE_BORDER)
@@ -60,3 +60,12 @@ def runTest(frame, nb, log):
overview = Layoutf.__doc__
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -3,6 +3,9 @@
from wxPython.wx import *
from wxScrolledWindow import MyCanvas
import images
SHOW_BACKGROUND = 1
#----------------------------------------------------------------------
class MyParentFrame(wxMDIParentFrame):
@@ -24,16 +27,38 @@ class MyParentFrame(wxMDIParentFrame):
EVT_MENU(self, 5000, self.OnNewWindow)
EVT_MENU(self, 5001, self.OnExit)
if SHOW_BACKGROUND:
self.bg_bmp = images.getGridBGBitmap()
EVT_ERASE_BACKGROUND(self.GetClientWindow(), self.OnEraseBackground)
def OnExit(self, evt):
self.Close(true)
self.Close(True)
def OnNewWindow(self, evt):
self.winCount = self.winCount + 1
win = wxMDIChildFrame(self, -1, "Child Window: %d" % self.winCount)
canvas = MyCanvas(win)
win.Show(true)
win.Show(True)
def OnEraseBackground(self, evt):
dc = evt.GetDC()
if not dc:
dc = wxClientDC(self.GetClientWindow())
# tile the background bitmap
sz = self.GetClientSize()
w = self.bg_bmp.GetWidth()
h = self.bg_bmp.GetHeight()
x = 0
while x < sz.width:
y = 0
while y < sz.height:
dc.DrawBitmap(self.bg_bmp, x, y)
y = y + h
x = x + w
#----------------------------------------------------------------------
@@ -43,9 +68,9 @@ if __name__ == '__main__':
def OnInit(self):
wxInitAllImageHandlers()
frame = MyParentFrame()
frame.Show(true)
frame.Show(True)
self.SetTopWindow(frame)
return true
return True
app = MyApp(0)

View File

@@ -44,7 +44,7 @@ class MyParentFrame(wxMDIParentFrame):
win.SetOrientation(wxLAYOUT_HORIZONTAL)
win.SetAlignment(wxLAYOUT_TOP)
win.SetBackgroundColour(wxColour(255, 0, 0))
win.SetSashVisible(wxSASH_BOTTOM, true)
win.SetSashVisible(wxSASH_BOTTOM, True)
self.topWindow = win
@@ -55,7 +55,7 @@ class MyParentFrame(wxMDIParentFrame):
win.SetOrientation(wxLAYOUT_HORIZONTAL)
win.SetAlignment(wxLAYOUT_BOTTOM)
win.SetBackgroundColour(wxColour(0, 0, 255))
win.SetSashVisible(wxSASH_TOP, true)
win.SetSashVisible(wxSASH_TOP, True)
self.bottomWindow = win
@@ -66,7 +66,7 @@ class MyParentFrame(wxMDIParentFrame):
win.SetOrientation(wxLAYOUT_VERTICAL)
win.SetAlignment(wxLAYOUT_LEFT)
win.SetBackgroundColour(wxColour(0, 255, 0))
win.SetSashVisible(wxSASH_RIGHT, TRUE)
win.SetSashVisible(wxSASH_RIGHT, True)
win.SetExtraBorderSize(10)
textWindow = wxTextCtrl(win, -1, "", wxDefaultPosition, wxDefaultSize,
wxTE_MULTILINE|wxSUNKEN_BORDER)
@@ -81,7 +81,7 @@ class MyParentFrame(wxMDIParentFrame):
win.SetOrientation(wxLAYOUT_VERTICAL)
win.SetAlignment(wxLAYOUT_LEFT)
win.SetBackgroundColour(wxColour(0, 255, 255))
win.SetSashVisible(wxSASH_RIGHT, TRUE)
win.SetSashVisible(wxSASH_RIGHT, True)
self.leftWindow2 = win
@@ -113,14 +113,14 @@ class MyParentFrame(wxMDIParentFrame):
def OnExit(self, evt):
self.Close(true)
self.Close(True)
def OnNewWindow(self, evt):
self.winCount = self.winCount + 1
win = wxMDIChildFrame(self, -1, "Child Window: %d" % self.winCount)
canvas = MyCanvas(win)
win.Show(true)
win.Show(True)
#----------------------------------------------------------------------
@@ -130,9 +130,9 @@ if __name__ == '__main__':
def OnInit(self):
wxInitAllImageHandlers()
frame = MyParentFrame()
frame.Show(true)
frame.Show(True)
self.SetTopWindow(frame)
return true
return True
app = MyApp(0)

View File

@@ -11,35 +11,33 @@
# Licence: wxWindows license
#----------------------------------------------------------------------------
import sys, os, time, string
from wxPython.wx import *
from wxPython.html import wxHtmlWindow
import sys, os, time
##from wxPython.stc import *
import wx # This module uses the new wx namespace
import wx.html
import images
# Use Python's bool constants if available, make aliases if not
try:
True
except NameError:
True = 1==1
False = 1==0
#---------------------------------------------------------------------------
_treeList = [
# new stuff
('New since last release', [
'RowColSizer',
'Unicode',
'wxFileHistory',
'wxGenericDirCtrl',
'wxImageFromStream',
'wxArtProvider',
'ScrolledPanel',
'wxMenu',
'wxIEHtmlWin',
'wxKeyEvents',
'wxWizard',
'wxXmlResourceHandler',
('Recent Additions', [
'wxMaskedNumCtrl',
'FloatCanvas',
'wxXmlResourceSubclass',
]),
# managed windows == things with a caption you can close
# managed windows == things with a (optional) caption you can close
('Base Frames and Dialogs', [
'wxDialog',
'wxFrame',
@@ -53,6 +51,7 @@ _treeList = [
'wxColourDialog',
'wxDirDialog',
'wxFileDialog',
'wxFileDialog_Save',
'wxFindReplaceDialog',
'wxFontDialog',
'wxMessageDialog',
@@ -73,6 +72,7 @@ _treeList = [
# core controls
('Core Windows/Controls', [
'PopupMenu',
'wxButton',
'wxCheckBox',
'wxCheckListBox',
@@ -81,6 +81,7 @@ _treeList = [
'wxGauge',
'wxGenericDirCtrl',
'wxGrid',
'wxGrid_MegaExample',
'wxListBox',
'wxListCtrl',
'wxListCtrl_virtual',
@@ -88,14 +89,15 @@ _treeList = [
'wxNotebook',
'wxPopupWindow',
'wxRadioBox',
'wxRadioButton',
'wxSashWindow',
'wxSlider',
'wxScrolledWindow',
'wxSplitterWindow',
'wxSlider',
'wxSpinButton',
'wxSpinCtrl',
'wxStaticText',
'wxSplitterWindow',
'wxStaticBitmap',
'wxStaticText',
'wxStatusBar',
'wxTextCtrl',
'wxToggleButton',
@@ -104,31 +106,42 @@ _treeList = [
'wxValidator',
]),
# controls coming from other librairies
# controls coming from other libraries
('More Windows/Controls', [
#'wxFloatBar', deprecated
#'wxMVCTree', deprecated
#'wxRightTextCtrl', deprecated as we have wxTE_RIGHT now.
'AnalogClockWindow',
'ColourSelect',
'ContextHelp',
'FancyText',
'FloatCanvas',
'FileBrowseButton',
'GenericButtons',
'MaskedEditControls',
'PyShell',
'PyCrust',
'PyCrustWithFilling',
'SplitTree',
'TablePrint',
'Throbber',
'wxCalendar',
'wxCalendarCtrl',
'wxPyColourChooser',
'wxDynamicSashWindow',
'wxEditableListBox',
'wxEditor',
#'wxFloatBar', deprecated
'wxHtmlWindow',
'wxIEHtmlWin',
'wxIntCtrl',
'wxLEDNumberCtrl',
'wxMimeTypesManager',
#'wxMVCTree', deprecated
'wxRightTextCtrl',
'wxMaskedNumCtrl',
'wxMultiSash',
'wxPopupControl',
'wxStyledTextCtrl_1',
'wxStyledTextCtrl_2',
'wxTimeCtrl',
'wxTreeListCtrl',
]),
# How to lay out the controls in a frame/dialog
@@ -136,22 +149,24 @@ _treeList = [
'LayoutAnchors',
'Layoutf',
'RowColSizer',
'ScrolledPanel',
'Sizers',
'wxLayoutConstraints',
'wxScrolledPanel',
'wxXmlResource',
'wxXmlResourceHandler',
'wxXmlResourceSubclass',
]),
# ditto
('Process and Events', [
'EventManager',
'infoframe',
'OOR',
'PythonEvents',
'Threads',
'wxKeyEvents',
'wxProcess',
'wxTimer',
'wxKeyEvents',
]),
# Clipboard and DnD
@@ -162,12 +177,13 @@ _treeList = [
]),
# Images
('Images', [
('Using Images', [
'Throbber',
'wxArtProvider',
'wxDragImage',
'wxImage',
'wxImageFromStream',
'wxMask',
'wxArtProvider',
]),
# Other stuff
@@ -176,7 +192,10 @@ _treeList = [
'DialogUnits',
'DrawXXXList',
'FontEnumerator',
'NewNamespace',
'PrintFramework',
'ShapedWindow',
'Throbber',
'Unicode',
'wxFileHistory',
'wxJoystick',
@@ -201,10 +220,11 @@ _treeList = [
#---------------------------------------------------------------------------
# Show how to derive a custom wxLog class
class MyLog(wxPyLog):
class MyLog(wx.PyLog):
def __init__(self, textCtrl, logTime=0):
wxPyLog.__init__(self)
wx.PyLog.__init__(self)
self.tc = textCtrl
self.logTime = logTime
@@ -212,108 +232,182 @@ class MyLog(wxPyLog):
if self.logTime:
message = time.strftime("%X", time.localtime(timeStamp)) + \
": " + message
self.tc.AppendText(message + '\n')
if self.tc:
self.tc.AppendText(message + '\n')
class MyTP(wxPyTipProvider):
class MyTP(wx.PyTipProvider):
def GetTip(self):
return "This is my tip"
#---------------------------------------------------------------------------
# A class to be used to display source code in the demo. Try using the
# wxSTC in the wxStyledTextCtrl_2 sample first, fall back to wxTextCtrl
# if there is an error, such as the stc module not being present.
#
try:
##raise ImportError
from wx import stc
from wxStyledTextCtrl_2 import PythonSTC
class DemoCodeViewer(PythonSTC):
def __init__(self, parent, ID):
PythonSTC.__init__(self, parent, ID)
self.SetEdgeMode(stc.STC_EDGE_NONE)
self.SetSelBackground(True, wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT))
self.SetSelForeground(True, wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT))
# Some methods to make it compatible with how the wxTextCtrl is used
def SetValue(self, value):
self.SetReadOnly(False)
self.SetText(value)
self.SetReadOnly(True)
def Clear(self):
self.ClearAll()
def SetInsertionPoint(self, pos):
self.SetCurrentPos(pos)
def ShowPosition(self, pos):
self.GotoPos(pos)
def GetLastPosition(self):
return self.GetLength()
def GetRange(self, start, end):
return self.GetTextRange(start, end)
def GetSelection(self):
return self.GetAnchor(), self.GetCurrentPos()
def SetSelection(self, start, end):
self.SetSelectionStart(start)
self.SetSelectionEnd(end)
except ImportError:
class DemoCodeViewer(wx.TextCtrl):
def __init__(self, parent, ID):
wx.TextCtrl.__init__(self, parent, ID, style =
wx.TE_MULTILINE | wx.TE_READONLY |
wx.HSCROLL | wx.TE_RICH2 | wx.TE_NOHIDESEL)
#---------------------------------------------------------------------------
def opj(path):
"""Convert paths to the platform-specific separator"""
return apply(os.path.join, tuple(string.split(path, '/')))
return apply(os.path.join, tuple(path.split('/')))
#---------------------------------------------------------------------------
class wxPythonDemo(wxFrame):
class wxPythonDemo(wx.Frame):
overviewText = "wxPython Overview"
def __init__(self, parent, id, title):
wxFrame.__init__(self, parent, -1, title, size = (800, 600),
style=wxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE)
wx.Frame.__init__(self, parent, -1, title, size = (800, 600),
style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE)
self.cwd = os.getcwd()
self.curOverview = ""
self.window = None
icon = images.getMondrianIcon()
self.SetIcon(icon)
if wxPlatform == '__WXMSW__':
if wx.Platform == '__WXMSW__':
# setup a taskbar icon, and catch some events from it
self.tbicon = wxTaskBarIcon()
self.tbicon = wx.TaskBarIcon()
self.tbicon.SetIcon(icon, "wxPython Demo")
EVT_TASKBAR_LEFT_DCLICK(self.tbicon, self.OnTaskBarActivate)
EVT_TASKBAR_RIGHT_UP(self.tbicon, self.OnTaskBarMenu)
EVT_MENU(self.tbicon, self.TBMENU_RESTORE, self.OnTaskBarActivate)
EVT_MENU(self.tbicon, self.TBMENU_CLOSE, self.OnTaskBarClose)
wx.EVT_TASKBAR_LEFT_DCLICK(self.tbicon, self.OnTaskBarActivate)
wx.EVT_TASKBAR_RIGHT_UP(self.tbicon, self.OnTaskBarMenu)
wx.EVT_MENU(self.tbicon, self.TBMENU_RESTORE, self.OnTaskBarActivate)
wx.EVT_MENU(self.tbicon, self.TBMENU_CLOSE, self.OnTaskBarClose)
wx.CallAfter(self.ShowTip)
self.otherWin = None
self.showTip = true
EVT_IDLE(self, self.OnIdle)
EVT_CLOSE(self, self.OnCloseWindow)
EVT_ICONIZE(self, self.OnIconfiy)
EVT_MAXIMIZE(self, self.OnMaximize)
wx.EVT_IDLE(self, self.OnIdle)
wx.EVT_CLOSE(self, self.OnCloseWindow)
wx.EVT_ICONIZE(self, self.OnIconfiy)
wx.EVT_MAXIMIZE(self, self.OnMaximize)
self.Centre(wxBOTH)
self.CreateStatusBar(1, wxST_SIZEGRIP)
self.Centre(wx.BOTH)
self.CreateStatusBar(1, wx.ST_SIZEGRIP)
splitter = wxSplitterWindow(self, -1, style=wxNO_3D|wxSP_3D)
splitter2 = wxSplitterWindow(splitter, -1, style=wxNO_3D|wxSP_3D)
splitter = wx.SplitterWindow(self, -1, style=wx.NO_3D|wx.SP_3D)
splitter2 = wx.SplitterWindow(splitter, -1, style=wx.NO_3D|wx.SP_3D)
def EmptyHandler(evt): pass
EVT_ERASE_BACKGROUND(splitter, EmptyHandler)
EVT_ERASE_BACKGROUND(splitter2, EmptyHandler)
wx.EVT_ERASE_BACKGROUND(splitter, EmptyHandler)
wx.EVT_ERASE_BACKGROUND(splitter2, EmptyHandler)
# Prevent TreeCtrl from displaying all items after destruction when true
self.dying = false
# Prevent TreeCtrl from displaying all items after destruction when True
self.dying = False
# Make a File menu
self.mainmenu = wxMenuBar()
menu = wxMenu()
exitID = wxNewId()
self.mainmenu = wx.MenuBar()
menu = wx.Menu()
exitID = wx.NewId()
menu.Append(exitID, 'E&xit\tAlt-X', 'Get the heck outta here!')
EVT_MENU(self, exitID, self.OnFileExit)
wx.EVT_MENU(self, exitID, self.OnFileExit)
wx.App_SetMacExitMenuItemId(exitID)
self.mainmenu.Append(menu, '&File')
# Make a Demo menu
menu = wxMenu()
menu = wx.Menu()
for item in _treeList:
submenu = wxMenu()
submenu = wx.Menu()
for childItem in item[1]:
mID = wxNewId()
mID = wx.NewId()
submenu.Append(mID, childItem)
EVT_MENU(self, mID, self.OnDemoMenu)
menu.AppendMenu(wxNewId(), item[0], submenu)
wx.EVT_MENU(self, mID, self.OnDemoMenu)
menu.AppendMenu(wx.NewId(), item[0], submenu)
self.mainmenu.Append(menu, '&Demo')
# Make a Help menu
helpID = wxNewId()
menu = wxMenu()
helpID = wx.NewId()
findID = wx.NewId()
findnextID = wx.NewId()
menu = wx.Menu()
menu.Append(findID, '&Find\tCtrl-F', 'Find in the Demo Code')
menu.Append(findnextID, 'Find &Next\tF3', 'Find Next')
menu.AppendSeparator()
menu.Append(helpID, '&About\tCtrl-H', 'wxPython RULES!!!')
EVT_MENU(self, helpID, self.OnHelpAbout)
wx.App_SetMacAboutMenuItemId(helpID)
wx.EVT_MENU(self, helpID, self.OnHelpAbout)
wx.EVT_MENU(self, findID, self.OnHelpFind)
wx.EVT_MENU(self, findnextID, self.OnFindNext)
wx.EVT_COMMAND_FIND(self, -1, self.OnFind)
wx.EVT_COMMAND_FIND_NEXT(self, -1, self.OnFind)
wx.EVT_COMMAND_FIND_CLOSE(self, -1 , self.OnFindClose)
self.mainmenu.Append(menu, '&Help')
self.SetMenuBar(self.mainmenu)
# set the menu accellerator table...
aTable = wxAcceleratorTable([(wxACCEL_ALT, ord('X'), exitID),
(wxACCEL_CTRL, ord('H'), helpID)])
self.SetAcceleratorTable(aTable)
self.finddata = wx.FindReplaceData()
if 0:
# This is another way to set Accelerators, in addition to
# using the '\t<key>' syntax in the menu items.
aTable = wx.AcceleratorTable([(wx.ACCEL_ALT, ord('X'), exitID),
(wx.ACCEL_CTRL, ord('H'), helpID),
(wx.ACCEL_CTRL, ord('F'), findID),
(wx.ACCEL_NORMAL, WXK_F3, findnextID)
])
self.SetAcceleratorTable(aTable)
# Create a TreeCtrl
tID = wxNewId()
tID = wx.NewId()
self.treeMap = {}
self.tree = wxTreeCtrl(splitter, tID,
style=wxTR_HAS_BUTTONS |
wxTR_HAS_VARIABLE_ROW_HEIGHT
self.tree = wx.TreeCtrl(splitter, tID,
style=wx.TR_HAS_BUTTONS |
wx.TR_HAS_VARIABLE_ROW_HEIGHT
)
#self.tree.SetBackgroundColour(wxNamedColour("Pink"))
root = self.tree.AddRoot("wxPython Overview")
firstChild = None
for item in _treeList:
@@ -325,67 +419,65 @@ class wxPythonDemo(wxFrame):
self.tree.Expand(root)
self.tree.Expand(firstChild)
EVT_TREE_ITEM_EXPANDED (self.tree, tID, self.OnItemExpanded)
EVT_TREE_ITEM_COLLAPSED (self.tree, tID, self.OnItemCollapsed)
EVT_TREE_SEL_CHANGED (self.tree, tID, self.OnSelChanged)
EVT_LEFT_DOWN (self.tree, self.OnTreeLeftDown)
wx.EVT_TREE_ITEM_EXPANDED (self.tree, tID, self.OnItemExpanded)
wx.EVT_TREE_ITEM_COLLAPSED (self.tree, tID, self.OnItemCollapsed)
wx.EVT_TREE_SEL_CHANGED (self.tree, tID, self.OnSelChanged)
wx.EVT_LEFT_DOWN (self.tree, self.OnTreeLeftDown)
# Create a Notebook
self.nb = wxNotebook(splitter2, -1, style=wxCLIP_CHILDREN)
self.nb = wx.Notebook(splitter2, -1, style=wx.CLIP_CHILDREN)
# Set up a wxHtmlWindow on the Overview Notebook page
# Set up a wx.html.HtmlWindow on the Overview Notebook page
# we put it in a panel first because there seems to be a
# refresh bug of some sort (wxGTK) when it is directly in
# the notebook...
if 0: # the old way
self.ovr = wxHtmlWindow(self.nb, -1, size=(400, 400))
self.ovr = wx.html.HtmlWindow(self.nb, -1, size=(400, 400))
self.nb.AddPage(self.ovr, self.overviewText)
else: # hopefully I can remove this hacky code soon, see bug #216861
panel = wxPanel(self.nb, -1, style=wxCLIP_CHILDREN)
self.ovr = wxHtmlWindow(panel, -1, size=(400, 400))
else: # hopefully I can remove this hacky code soon, see SF bug #216861
panel = wx.Panel(self.nb, -1, style=wx.CLIP_CHILDREN)
self.ovr = wx.html.HtmlWindow(panel, -1, size=(400, 400))
self.nb.AddPage(panel, self.overviewText)
def OnOvrSize(evt, ovr=self.ovr):
ovr.SetSize(evt.GetSize())
EVT_SIZE(panel, OnOvrSize)
EVT_ERASE_BACKGROUND(panel, EmptyHandler)
wx.EVT_SIZE(panel, OnOvrSize)
wx.EVT_ERASE_BACKGROUND(panel, EmptyHandler)
self.SetOverview(self.overviewText, overview)
# Set up a TextCtrl on the Demo Code Notebook page
self.txt = wxTextCtrl(self.nb, -1,
style = wxTE_MULTILINE|wxTE_READONLY|wxHSCROLL)
# Set up a notebook page for viewing the source code of each sample
self.txt = DemoCodeViewer(self.nb, -1)
self.nb.AddPage(self.txt, "Demo Code")
self.GetDemoFile('Main.py')
# Set up a log on the View Log Notebook page
self.log = wxTextCtrl(splitter2, -1,
style = wxTE_MULTILINE|wxTE_READONLY|wxHSCROLL)
self.log = wx.TextCtrl(splitter2, -1,
style = wx.TE_MULTILINE|wx.TE_READONLY|wx.HSCROLL)
# Set the wxWindows log target to be this textctrl
#wxLog_SetActiveTarget(wxLogTextCtrl(self.log))
#wx.Log_SetActiveTarget(wx.LogTextCtrl(self.log))
# But instead of the above we want to show how to use our own wxLog class
wxLog_SetActiveTarget(MyLog(self.log))
# But instead of the above we want to show how to use our own wx.Log class
wx.Log_SetActiveTarget(MyLog(self.log))
# for serious debugging
#wxLog_SetActiveTarget(wxLogStderr())
#wxLog_SetTraceMask(wxTraceMessages)
#wx.Log_SetActiveTarget(wx.LogStderr())
#wx.Log_SetTraceMask(wx.TraceMessages)
self.Show(true)
self.Show(True)
# add the windows to the splitter and split it.
splitter2.SplitHorizontally(self.nb, self.log)
splitter.SplitVertically(self.tree, splitter2)
splitter2.SplitHorizontally(self.nb, self.log, 425)
splitter.SplitVertically(self.tree, splitter2, 180)
splitter.SetSashPosition(180, true)
splitter.SetMinimumPaneSize(20)
splitter2.SetSashPosition(450, true)
splitter2.SetMinimumPaneSize(20)
@@ -404,14 +496,14 @@ class wxPythonDemo(wxFrame):
self.tree.EnsureVisible(selectedDemo)
wxLogMessage('window handle: %s' % self.GetHandle())
wx.LogMessage('window handle: %s' % self.GetHandle())
#---------------------------------------------
def WriteText(self, text):
if text[-1:] == '\n':
text = text[:-1]
wxLogMessage(text)
wx.LogMessage(text)
def write(self, txt):
@@ -420,13 +512,13 @@ class wxPythonDemo(wxFrame):
#---------------------------------------------
def OnItemExpanded(self, event):
item = event.GetItem()
wxLogMessage("OnItemExpanded: %s" % self.tree.GetItemText(item))
wx.LogMessage("OnItemExpanded: %s" % self.tree.GetItemText(item))
event.Skip()
#---------------------------------------------
def OnItemCollapsed(self, event):
item = event.GetItem()
wxLogMessage("OnItemCollapsed: %s" % self.tree.GetItemText(item))
wx.LogMessage("OnItemCollapsed: %s" % self.tree.GetItemText(item))
event.Skip()
#---------------------------------------------
@@ -453,6 +545,11 @@ class wxPythonDemo(wxFrame):
if self.nb.GetPageCount() == 3:
if self.nb.GetSelection() == 2:
self.nb.SetSelection(0)
# inform the window that it's time to quit if it cares
if self.window is not None:
if hasattr(self.window, "ShutdownDemo"):
self.window.ShutdownDemo()
wx.SafeYield() # in case the page has pending events
self.nb.DeletePage(2)
if itemText == self.overviewText:
@@ -463,22 +560,22 @@ class wxPythonDemo(wxFrame):
else:
if os.path.exists(itemText + '.py'):
wxBeginBusyCursor()
wxLogMessage("Running demo %s.py..." % itemText)
wx.BeginBusyCursor()
wx.LogMessage("Running demo %s.py..." % itemText)
try:
self.GetDemoFile(itemText + '.py')
module = __import__(itemText, globals())
self.SetOverview(itemText + " Overview", module.overview)
finally:
wxEndBusyCursor()
wx.EndBusyCursor()
self.tree.Refresh()
# in case runTest is modal, make sure things look right...
self.nb.Refresh();
wxSafeYield()
wx.SafeYield()
self.window = module.runTest(self, self.nb, self) ###
if self.window:
if self.window is not None:
self.nb.AddPage(self.window, 'Demo')
self.nb.SetSelection(2)
self.nb.Refresh() # without this wxMac has troubles showing the just added page
@@ -497,7 +594,7 @@ class wxPythonDemo(wxFrame):
try:
self.txt.SetValue(open(filename).read())
except IOError:
self.txt.WriteText("Cannot open %s file." % filename)
self.txt.SetValue("Cannot open %s file." % filename)
self.txt.SetInsertionPoint(0)
self.txt.ShowPosition(0)
@@ -507,7 +604,7 @@ class wxPythonDemo(wxFrame):
self.curOverview = text
lead = text[:6]
if lead != '<html>' and lead != '<HTML>':
text = string.join(string.split(text, '\n'), '<br>')
text = '<br>'.join(text.split('\n'))
self.ovr.SetPage(text)
self.nb.SetPageText(0, name)
@@ -516,17 +613,61 @@ class wxPythonDemo(wxFrame):
def OnFileExit(self, *event):
self.Close()
def OnHelpAbout(self, event):
from About import MyAboutBox
about = MyAboutBox(self)
about.ShowModal()
about.Destroy()
def OnHelpFind(self, event):
self.nb.SetSelection(1)
self.finddlg = wx.FindReplaceDialog(self, self.finddata, "Find",
wx.FR_NOUPDOWN |
wx.FR_NOMATCHCASE |
wx.FR_NOWHOLEWORD)
self.finddlg.Show(True)
def OnFind(self, event):
self.nb.SetSelection(1)
end = self.txt.GetLastPosition()
textstring = self.txt.GetRange(0, end).lower()
start = self.txt.GetSelection()[1]
findstring = self.finddata.GetFindString().lower()
loc = textstring.find(findstring, start)
if loc == -1 and start != 0:
# string not found, start at beginning
start = 0
loc = textstring.find(findstring, start)
if loc == -1:
dlg = wx.MessageDialog(self, 'Find String Not Found',
'Find String Not Found in Demo File',
wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
if self.finddlg:
if loc == -1:
self.finddlg.SetFocus()
return
else:
self.finddlg.Destroy()
self.txt.ShowPosition(loc)
self.txt.SetSelection(loc, loc + len(findstring))
def OnFindNext(self, event):
if self.finddata.GetFindString():
self.OnFind(event)
else:
self.OnHelpFind(event)
def OnFindClose(self, event):
event.GetDialog().Destroy()
#---------------------------------------------
def OnCloseWindow(self, event):
self.dying = true
self.dying = True
self.window = None
self.mainmenu = None
if hasattr(self, "tbicon"):
@@ -541,10 +682,6 @@ class wxPythonDemo(wxFrame):
self.window = self.otherWin
self.otherWin = None
if self.showTip:
self.ShowTip()
self.showTip = false
#---------------------------------------------
def ShowTip(self):
@@ -554,9 +691,9 @@ class wxPythonDemo(wxFrame):
except IOError:
showTip, index = (1, 0)
if showTip:
tp = wxCreateFileTipProvider(opj("data/tips.txt"), index)
tp = wx.CreateFileTipProvider(opj("data/tips.txt"), index)
##tp = MyTP(0)
showTip = wxShowTip(self, tp)
showTip = wx.ShowTip(self, tp)
index = tp.GetCurrentTip()
open(opj("data/showTips"), "w").write(str( (showTip, index) ))
@@ -575,9 +712,9 @@ class wxPythonDemo(wxFrame):
#---------------------------------------------
def OnTaskBarActivate(self, evt):
if self.IsIconized():
self.Iconize(false)
self.Iconize(False)
if not self.IsShown():
self.Show(true)
self.Show(True)
self.Raise()
#---------------------------------------------
@@ -586,7 +723,7 @@ class wxPythonDemo(wxFrame):
TBMENU_CLOSE = 1001
def OnTaskBarMenu(self, evt):
menu = wxMenu()
menu = wx.Menu()
menu.Append(self.TBMENU_RESTORE, "Restore wxPython Demo")
menu.Append(self.TBMENU_CLOSE, "Close")
self.tbicon.PopupMenu(menu)
@@ -596,19 +733,19 @@ class wxPythonDemo(wxFrame):
def OnTaskBarClose(self, evt):
self.Close()
# because of the way wxTaskBarIcon.PopupMenu is implemented we have to
# because of the way wx.TaskBarIcon.PopupMenu is implemented we have to
# prod the main idle handler a bit to get the window to actually close
wxGetApp().ProcessIdle()
wx.GetApp().ProcessIdle()
#---------------------------------------------
def OnIconfiy(self, evt):
wxLogMessage("OnIconfiy")
wx.LogMessage("OnIconfiy")
evt.Skip()
#---------------------------------------------
def OnMaximize(self, evt):
wxLogMessage("OnMaximize")
wx.LogMessage("OnMaximize")
evt.Skip()
@@ -617,31 +754,36 @@ class wxPythonDemo(wxFrame):
#---------------------------------------------------------------------------
#---------------------------------------------------------------------------
class MySplashScreen(wxSplashScreen):
class MySplashScreen(wx.SplashScreen):
def __init__(self):
bmp = wxImage(opj("bitmaps/splash.gif")).ConvertToBitmap()
wxSplashScreen.__init__(self, bmp,
wxSPLASH_CENTRE_ON_SCREEN|wxSPLASH_TIMEOUT,
bmp = wx.Image(opj("bitmaps/splash.png")).ConvertToBitmap()
wx.SplashScreen.__init__(self, bmp,
wx.SPLASH_CENTRE_ON_SCREEN|wx.SPLASH_TIMEOUT,
4000, None, -1,
style = wxSIMPLE_BORDER|wxFRAME_NO_TASKBAR|wxSTAY_ON_TOP)
EVT_CLOSE(self, self.OnClose)
style = wx.SIMPLE_BORDER|wx.FRAME_NO_TASKBAR|wx.STAY_ON_TOP)
wx.EVT_CLOSE(self, self.OnClose)
def OnClose(self, evt):
frame = wxPythonDemo(None, -1, "wxPython: (A Demonstration)")
frame.Show(true)
frame.Show()
evt.Skip() # Make sure the default handler runs too...
class MyApp(wxApp):
class MyApp(wx.App):
def OnInit(self):
"""
Create and show the splash screen. It will then create and show
the main frame when it is time to do so.
"""
wxInitAllImageHandlers()
#import locale
#self.locale = wx.Locale(wx.LANGUAGE_FRENCH)
#locale.setlocale(locale.LC_ALL, 'fr')
wx.InitAllImageHandlers()
splash = MySplashScreen()
splash.Show()
return true
return True
@@ -653,7 +795,7 @@ def main():
os.chdir(demoPath)
except:
pass
app = MyApp(wxPlatform == "__WXMAC__")
app = MyApp(wx.Platform == "__WXMAC__")
app.MainLoop()
@@ -662,76 +804,36 @@ def main():
overview = """<html><body>
<h2>Python</h2>
<h2>wxPython</h2>
Python is an interpreted, interactive, object-oriented programming
language often compared to Tcl, Perl, Scheme, or Java.
<p> wxPython is a <b>GUI toolkit</b> for the <a
href="http://www.python.org/">Python</a> programming language. It
allows Python programmers to create programs with a robust, highly
functional graphical user interface, simply and easily. It is
implemented as a Python extension module (native code) that wraps the
popular <a href="http://wxwindows.org/front.htm">wxWindows</a> cross
platform GUI library, which is written in C++.
<p> Python combines remarkable power with very clear syntax. It has
modules, classes, exceptions, very high level dynamic data types, and
dynamic typing. There are interfaces to many system calls and
libraries, and new built-in modules are easily written in C or
C++. Python is also usable as an extension language for applications
that need a programmable interface. <p>
<p> Like Python and wxWindows, wxPython is <b>Open Source</b> which
means that it is free for anyone to use and the source code is
available for anyone to look at and modify. Or anyone can contribute
fixes or enhancements to the project.
<h2>wxWindows</h2>
<p> wxPython is a <b>cross-platform</b> toolkit. This means that the
same program will run on multiple platforms without modification.
Currently supported platforms are 32-bit Microsoft Windows, most Unix
or unix-like systems, and Macintosh OS X. Since the language is
Python, wxPython programs are <b>simple, easy</b> to write and easy to
understand.
wxWindows is a free C++ framework designed to make cross-platform
programming child's play. Well, almost. wxWindows 2 supports Windows
3.1/95/98/NT, Unix with GTK/Motif/Lesstif, with a Mac version
underway. Other ports are under consideration. <p>
<p> <b>This demo</b> is not only a collection of test cases for
wxPython, but is also designed to help you learn about and how to use
wxPython. Each sample is listed in the tree control on the left.
When a sample is selected in the tree then a module is loaded and run
(usually in a tab of this notebook,) and the source code of the module
is loaded in another tab for you to browse and learn from.
wxWindows is a set of libraries that allows C++ applications to
compile and run on several different types of computers, with minimal
source code changes. There is one library per supported GUI (such as
Motif, or Windows). As well as providing a common API (Application
Programming Interface) for GUI functionality, it provides
functionality for accessing some commonly-used operating system
facilities, such as copying or deleting files. wxWindows is a
'framework' in the sense that it provides a lot of built-in
functionality, which the application can use or replace as required,
thus saving a great deal of coding effort. Basic data structures such
as strings, linked lists and hash tables are also supported.
<p>
<h2>wxPython</h2>
wxPython is a Python extension module that encapsulates the wxWindows
GUI classes. Currently it is only available for the Win32 and GTK
ports of wxWindows, but as soon as the other ports are brought up to
the same level as Win32 and GTK, it should be fairly trivial to
enable wxPython to be used with the new GUI.
<p>
The wxPython extension module attempts to mirror the class heiarchy
of wxWindows as closely as possible. This means that there is a
wxFrame class in wxPython that looks, smells, tastes and acts almost
the same as the wxFrame class in the C++ version. Unfortunately,
because of differences in the languages, wxPython doesn't match
wxWindows exactly, but the differences should be easy to absorb
because they are natural to Python. For example, some methods that
return multiple values via argument pointers in C++ will return a
tuple of values in Python.
<p>
There is still much to be done for wxPython, many classes still need
to be mirrored. Also, wxWindows is still somewhat of a moving target
so it is a bit of an effort just keeping wxPython up to date. On the
other hand, there are enough of the core classes completed that
useful applications can be written.
<p>
wxPython is close enough to the C++ version that the majority of
the wxPython documentation is actually just notes attached to the C++
documents that describe the places where wxPython is different. There
is also a series of sample programs included, and a series of
documentation pages that assist the programmer in getting started
with wxPython.
"""
"""
#----------------------------------------------------------------------------

View File

@@ -0,0 +1,645 @@
from wxPython.wx import *
from wxPython.lib.maskededit import Field, wxMaskedTextCtrl, wxMaskedComboBox, wxIpAddrCtrl, states, state_names, months
from wxPython.lib.maskededit import __doc__ as maskededit_doc
from wxPython.lib.maskededit import autoformats
from wxPython.lib.maskedctrl import wxMaskedCtrl, controlTypes, MASKEDCOMBO
from wxPython.lib.scrolledpanel import wxScrolledPanel
import string, sys, traceback
class demoMixin:
"""
Centralized routines common to demo pages, to remove repetition.
"""
def labelGeneralTable(self, sizer):
description = wxStaticText( self, -1, "Description", )
mask = wxStaticText( self, -1, "Mask Value" )
formatcode = wxStaticText( self, -1, "Format" )
regex = wxStaticText( self, -1, "Regexp Validator(opt.)" )
ctrl = wxStaticText( self, -1, "wxMaskedTextCtrl" )
description.SetFont( wxFont(9, wxSWISS, wxNORMAL, wxBOLD))
mask.SetFont( wxFont(9, wxSWISS, wxNORMAL, wxBOLD))
formatcode.SetFont( wxFont(9, wxSWISS, wxNORMAL, wxBOLD) )
regex.SetFont( wxFont(9, wxSWISS, wxNORMAL, wxBOLD))
ctrl.SetFont( wxFont(9, wxSWISS, wxNORMAL, wxBOLD))
sizer.Add(description)
sizer.Add(mask)
sizer.Add(formatcode)
sizer.Add(regex)
sizer.Add(ctrl)
def layoutGeneralTable(self, controls, sizer):
for control in controls:
sizer.Add( wxStaticText( self, -1, control[0]) )
sizer.Add( wxStaticText( self, -1, control[1]) )
sizer.Add( wxStaticText( self, -1, control[3]) )
sizer.Add( wxStaticText( self, -1, control[4]) )
if control in controls:
newControl = wxMaskedTextCtrl( self, -1, "",
mask = control[1],
excludeChars = control[2],
formatcodes = control[3],
includeChars = "",
validRegex = control[4],
validRange = control[5],
choices = control[6],
choiceRequired = True,
defaultValue = control[7],
demo = True,
name = control[0])
self.editList.append(newControl)
sizer.Add(newControl)
def changeControlParams(self, event, parameter, checked_value, notchecked_value):
if event.Checked(): value = checked_value
else: value = notchecked_value
kwargs = {parameter: value}
for control in self.editList:
control.SetCtrlParameters(**kwargs)
control.Refresh()
self.Refresh()
#----------------------------------------------------------------------------
class demoPage1(wxScrolledPanel, demoMixin):
def __init__(self, parent, log):
wxScrolledPanel.__init__(self, parent, -1)
self.sizer = wxBoxSizer( wxVERTICAL )
self.editList = []
label = wxStaticText( self, -1, """\
Here are some basic wxMaskedTextCtrls to give you an idea of what you can do
with this control. Note that all controls have been auto-sized by including 'F' in
the format codes.
Try entering nonsensical or partial values in validated fields to see what happens.
Note that the State and Last Name fields are list-limited (valid last names are:
Smith, Jones, Williams). Signs on numbers can be toggled with the minus key.
""")
label.SetForegroundColour( "Blue" )
header = wxBoxSizer( wxHORIZONTAL )
header.Add( label, 0, flag=wxALIGN_LEFT|wxALL, border = 5 )
highlight = wxCheckBox( self, -1, "Highlight Empty" )
disallow = wxCheckBox( self, -1, "Disallow Empty" )
showFill = wxCheckBox( self, -1, "change fillChar" )
vbox = wxBoxSizer( wxVERTICAL )
vbox.Add( highlight, 0, wxALIGN_LEFT|wxALL, 5 )
vbox.Add( disallow, 0, wxALIGN_LEFT|wxALL, 5 )
vbox.Add( showFill, 0, wxALIGN_LEFT|wxALL, 5 )
header.AddSpacer(15, 0)
header.Add(vbox, 0, flag=wxALIGN_LEFT|wxALL, border=5 )
EVT_CHECKBOX( self, highlight.GetId(), self.onHighlightEmpty )
EVT_CHECKBOX( self, disallow.GetId(), self.onDisallowEmpty )
EVT_CHECKBOX( self, showFill.GetId(), self.onShowFill )
grid = wxFlexGridSizer( 0, 5, vgap=10, hgap=10 )
self.labelGeneralTable(grid)
# The following list is of the controls for the demo. Feel free to play around with
# the options!
controls = [
#description mask excl format regexp range,list,initial
("Phone No", "(###) ###-#### x:###", "", 'F^-', "^\(\d{3}\) \d{3}-\d{4}", '','',''),
("Social Sec#", "###-##-####", "", 'F', "\d{3}-\d{2}-\d{4}", '','',''),
("Full Name", "C{14}", "", 'F_', '^[A-Z][a-zA-Z]+ [A-Z][a-zA-Z]+', '','',''),
("Last Name Only", "C{14}", "", 'F {list}', '^[A-Z][a-zA-Z]+', '',('Smith','Jones','Williams'),''),
("Zip plus 4", "#{5}-#{4}", "", 'F', "\d{5}-(\s{4}|\d{4})", '','',''),
("Customer No", "\CAA-###", "", 'F!', "C[A-Z]{2}-\d{3}", '','',''),
("Invoice Total", "#{9}.##", "", 'F-_,', "", '','',''),
("Integer", "#{9}", "", 'F-_', "", '','',''),
]
self.layoutGeneralTable(controls, grid)
self.sizer.Add( header, 0, flag=wxALIGN_LEFT|wxALL, border=5 )
self.sizer.Add( grid, 0, flag= wxALIGN_LEFT|wxLEFT, border=5 )
self.SetSizer(self.sizer)
self.SetupScrolling()
self.SetAutoLayout(1)
def onDisallowEmpty( self, event ):
""" Set emptyInvalid parameter on/off """
self.changeControlParams( event, "emptyInvalid", True, False )
def onHighlightEmpty( self, event ):
""" Highlight empty values"""
self.changeControlParams( event, "emptyBackgroundColour", "Blue", "White" )
def onShowFill( self, event ):
""" Set fillChar parameter to '?' or ' ' """
self.changeControlParams( event, "fillChar", '?', ' ' )
class demoPage2(wxScrolledPanel, demoMixin):
def __init__( self, parent, log ):
self.log = log
wxScrolledPanel.__init__( self, parent, -1 )
self.sizer = wxBoxSizer( wxVERTICAL )
label = wxStaticText( self, -1, """\
All these controls have been created by passing a single parameter, the autoformat code,
and use the factory class wxMaskedCtrl with its default controlType.
The maskededit module contains an internal dictionary of types and formats (autoformats).
Many of these already do complicated validation; To see some examples, try
29 Feb 2002 vs. 2004 for the date formats, or email address validation.
""")
label.SetForegroundColour( "Blue" )
self.sizer.Add( label, 0, wxALIGN_LEFT|wxALL, 5 )
description = wxStaticText( self, -1, "Description")
autofmt = wxStaticText( self, -1, "AutoFormat Code")
ctrl = wxStaticText( self, -1, "wxMaskedCtrl")
description.SetFont( wxFont( 9, wxSWISS, wxNORMAL, wxBOLD ) )
autofmt.SetFont( wxFont( 9, wxSWISS, wxNORMAL, wxBOLD ) )
ctrl.SetFont( wxFont( 9, wxSWISS, wxNORMAL, wxBOLD ) )
grid = wxFlexGridSizer( 0, 3, vgap=10, hgap=5 )
grid.Add( description, 0, wxALIGN_LEFT )
grid.Add( autofmt, 0, wxALIGN_LEFT )
grid.Add( ctrl, 0, wxALIGN_LEFT )
for autoformat, desc in autoformats:
grid.Add( wxStaticText( self, -1, desc), 0, wxALIGN_LEFT )
grid.Add( wxStaticText( self, -1, autoformat), 0, wxALIGN_LEFT )
grid.Add( wxMaskedCtrl( self, -1, "",
autoformat = autoformat,
demo = True,
name = autoformat),
0, wxALIGN_LEFT )
self.sizer.Add( grid, 0, wxALIGN_LEFT|wxALL, border=5 )
self.SetSizer( self.sizer )
self.SetAutoLayout( 1 )
self.SetupScrolling()
class demoPage3(wxScrolledPanel, demoMixin):
def __init__(self, parent, log):
self.log = log
wxScrolledPanel.__init__(self, parent, -1)
self.sizer = wxBoxSizer( wxVERTICAL )
self.editList = []
label = wxStaticText( self, -1, """\
Here wxMaskedTextCtrls that have default values. The states
control has a list of valid values, and the unsigned integer
has a legal range specified.
""")
label.SetForegroundColour( "Blue" )
requireValid = wxCheckBox( self, -1, "Require Valid Value" )
EVT_CHECKBOX( self, requireValid.GetId(), self.onRequireValid )
header = wxBoxSizer( wxHORIZONTAL )
header.Add( label, 0, flag=wxALIGN_LEFT|wxALL, border = 5)
header.AddSpacer(75, 0)
header.Add( requireValid, 0, flag=wxALIGN_LEFT|wxALL, border=10 )
grid = wxFlexGridSizer( 0, 5, vgap=10, hgap=10 )
self.labelGeneralTable( grid )
controls = [
#description mask excl format regexp range,list,initial
("U.S. State (2 char)", "AA", "", 'F!_', "[A-Z]{2}", '',states, states[0]),
("Integer (signed)", "#{6}", "", 'F-_', "", '','', ' 0 '),
("Integer (unsigned)\n(1-399)","######", "", 'F_', "", (1,399),'', '1 '),
("Float (signed)", "#{6}.#{9}", "", 'F-_R', "", '','', '000000.000000000'),
("Date (MDY) + Time", "##/##/#### ##:##:## AM", 'BCDEFGHIJKLMNOQRSTUVWXYZ','DF!',"", '','', wxDateTime_Now().Format("%m/%d/%Y %I:%M:%S %p")),
]
self.layoutGeneralTable( controls, grid )
self.sizer.Add( header, 0, flag=wxALIGN_LEFT|wxALL, border=5 )
self.sizer.Add( grid, 0, flag=wxALIGN_LEFT|wxALL, border=5 )
self.SetSizer( self.sizer )
self.SetAutoLayout( 1 )
self.SetupScrolling()
def onRequireValid( self, event ):
""" Set validRequired parameter on/off """
self.changeControlParams( event, "validRequired", True, False )
class demoPage4(wxScrolledPanel, demoMixin):
def __init__( self, parent, log ):
self.log = log
wxScrolledPanel.__init__( self, parent, -1 )
self.sizer = wxBoxSizer( wxVERTICAL )
label = wxStaticText( self, -1, """\
These controls have field-specific choice lists and allow autocompletion.
Down arrow or Page Down in an uncompleted field with an auto-completable field will attempt
to auto-complete a field if it has a choice list.
Page Down and Shift-Down arrow will also auto-complete, or cycle through the complete list.
Page Up and Shift-Up arrow will similarly cycle backwards through the list.
""")
label.SetForegroundColour( "Blue" )
self.sizer.Add( label, 0, wxALIGN_LEFT|wxALL, 5 )
description = wxStaticText( self, -1, "Description" )
autofmt = wxStaticText( self, -1, "AutoFormat Code" )
fields = wxStaticText( self, -1, "Field Objects" )
ctrl = wxStaticText( self, -1, "wxMaskedTextCtrl" )
description.SetFont( wxFont( 9, wxSWISS, wxNORMAL, wxBOLD ) )
autofmt.SetFont( wxFont( 9, wxSWISS, wxNORMAL, wxBOLD ) )
fields.SetFont( wxFont( 9, wxSWISS, wxNORMAL, wxBOLD ) )
ctrl.SetFont( wxFont( 9, wxSWISS, wxNORMAL, wxBOLD ) )
grid = wxFlexGridSizer( 0, 4, vgap=10, hgap=10 )
grid.Add( description, 0, wxALIGN_LEFT )
grid.Add( autofmt, 0, wxALIGN_LEFT )
grid.Add( fields, 0, wxALIGN_LEFT )
grid.Add( ctrl, 0, wxALIGN_LEFT )
autoformat = "USPHONEFULLEXT"
fieldsDict = {0: Field(choices=["617","781","508","978","413"], choiceRequired=True)}
fieldsLabel = """\
{0: Field(choices=[
"617","781",
"508","978","413"],
choiceRequired=True)}"""
grid.Add( wxStaticText( self, -1, "Restricted Area Code"), 0, wxALIGN_LEFT )
grid.Add( wxStaticText( self, -1, autoformat), 0, wxALIGN_LEFT )
grid.Add( wxStaticText( self, -1, fieldsLabel), 0, wxALIGN_LEFT )
grid.Add( wxMaskedTextCtrl( self, -1, "",
autoformat = autoformat,
fields = fieldsDict,
demo = True,
name = autoformat),
0, wxALIGN_LEFT )
autoformat = "EXPDATEMMYY"
fieldsDict = {1: Field(choices=["03", "04", "05"], choiceRequired=True)}
fieldsLabel = """\
{1: Field(choices=[
"03", "04", "05"],
choiceRequired=True)}"""
exp = wxMaskedTextCtrl( self, -1, "",
autoformat = autoformat,
fields = fieldsDict,
demo = True,
name = autoformat)
grid.Add( wxStaticText( self, -1, "Restricted Expiration"), 0, wxALIGN_LEFT )
grid.Add( wxStaticText( self, -1, autoformat), 0, wxALIGN_LEFT )
grid.Add( wxStaticText( self, -1, fieldsLabel), 0, wxALIGN_LEFT )
grid.Add( exp, 0, wxALIGN_LEFT )
fieldsDict = {0: Field(choices=["02134","02155"], choiceRequired=True),
1: Field(choices=["1234", "5678"], choiceRequired=False)}
fieldsLabel = """\
{0: Field(choices=["02134","02155"],
choiceRequired=True),
1: Field(choices=["1234", "5678"],
choiceRequired=False)}"""
autoformat = "USZIPPLUS4"
zip = wxMaskedTextCtrl( self, -1, "",
autoformat = autoformat,
fields = fieldsDict,
demo = True,
name = autoformat)
grid.Add( wxStaticText( self, -1, "Restricted Zip + 4"), 0, wxALIGN_LEFT )
grid.Add( wxStaticText( self, -1, autoformat), 0, wxALIGN_LEFT )
grid.Add( wxStaticText( self, -1, fieldsLabel), 0, wxALIGN_LEFT )
grid.Add( zip, 0, wxALIGN_LEFT )
self.sizer.Add( grid, 0, wxALIGN_LEFT|wxALL, border=5 )
self.SetSizer( self.sizer )
self.SetAutoLayout(1)
self.SetupScrolling()
class demoPage5(wxScrolledPanel, demoMixin):
def __init__( self, parent, log ):
self.log = log
wxScrolledPanel.__init__( self, parent, -1 )
self.sizer = wxBoxSizer( wxVERTICAL )
labelMaskedCombos = wxStaticText( self, -1, """\
These are some examples of wxMaskedComboBox:""")
labelMaskedCombos.SetForegroundColour( "Blue" )
label_statecode = wxStaticText( self, -1, """\
A state selector; only
"legal" values can be
entered:""")
statecode = wxMaskedComboBox( self, -1, states[0],
choices = states,
autoformat="USSTATE")
label_statename = wxStaticText( self, -1, """\
A state name selector,
with auto-select:""")
# Create this one using factory function:
statename = wxMaskedCtrl( self, -1, state_names[0],
controlType = controlTypes.MASKEDCOMBO,
choices = state_names,
autoformat="USSTATENAME",
autoSelect=True)
statename.SetCtrlParameters(formatcodes = 'F!V_')
numerators = [ str(i) for i in range(1, 4) ]
denominators = [ string.ljust(str(i), 2) for i in [2,3,4,5,8,16,32,64] ]
fieldsDict = {0: Field(choices=numerators, choiceRequired=False),
1: Field(choices=denominators, choiceRequired=True)}
choices = []
for n in numerators:
for d in denominators:
if n != d:
choices.append( '%s/%s' % (n,d) )
label_fraction = wxStaticText( self, -1, """\
A masked ComboBox for fraction selection.
Choices for each side of the fraction can
be selected with PageUp/Down:""")
fraction = wxMaskedCtrl( self, -1, "",
controlType = MASKEDCOMBO,
choices = choices,
choiceRequired = True,
mask = "#/##",
formatcodes = "F_",
validRegex = "^\d\/\d\d?",
fields = fieldsDict )
label_code = wxStaticText( self, -1, """\
A masked ComboBox to validate
text from a list of numeric codes:""")
choices = ["91", "136", "305", "4579"]
code = wxMaskedComboBox( self, -1, choices[0],
choices = choices,
choiceRequired = True,
formatcodes = "F_r",
mask = "####")
label_selector = wxStaticText( self, -1, """\
Programmatically set
choice sets:""")
self.list_selector = wxComboBox(self, -1, '', choices = ['list1', 'list2', 'list3'])
self.dynamicbox = wxMaskedCtrl( self, -1, ' ',
controlType = controlTypes.MASKEDCOMBO,
mask = 'XXXX',
formatcodes = 'F_',
# these are to give dropdown some initial height,
# as base control apparently only sets that size
# during initial construction <sigh>:
choices = ['', '1', '2', '3', '4', '5'] )
self.dynamicbox.Clear() # get rid of initial choices used to size the dropdown
labelIpAddrs = wxStaticText( self, -1, """\
Here are some examples of wxIpAddrCtrl, a control derived from wxMaskedTextCtrl:""")
labelIpAddrs.SetForegroundColour( "Blue" )
label_ipaddr1 = wxStaticText( self, -1, "An empty control:")
ipaddr1 = wxIpAddrCtrl( self, -1, style = wxTE_PROCESS_TAB )
label_ipaddr2 = wxStaticText( self, -1, "A restricted mask:")
ipaddr2 = wxIpAddrCtrl( self, -1, mask=" 10. 1.109.###" )
label_ipaddr3 = wxStaticText( self, -1, """\
A control with restricted legal values:
10. (1|2) . (129..255) . (0..255)""")
ipaddr3 = wxMaskedCtrl( self, -1,
controlType = controlTypes.IPADDR,
mask=" 10. #.###.###")
ipaddr3.SetFieldParameters(0, validRegex="1|2",validRequired=False ) # requires entry to match or not allowed
# This allows any value in penultimate field, but colors anything outside of the range invalid:
ipaddr3.SetFieldParameters(1, validRange=(129,255), validRequired=False )
labelNumerics = wxStaticText( self, -1, """\
Here are some useful configurations of a wxMaskedTextCtrl for integer and floating point input that still treat
the control as a text control. (For a true numeric control, check out the wxMaskedNumCtrl class!)""")
labelNumerics.SetForegroundColour( "Blue" )
label_intctrl1 = wxStaticText( self, -1, """\
An integer entry control with
shifting insert enabled:""")
self.intctrl1 = wxMaskedTextCtrl(self, -1, name='intctrl', mask="#{9}", formatcodes = '_-,F>')
label_intctrl2 = wxStaticText( self, -1, """\
Right-insert integer entry:""")
self.intctrl2 = wxMaskedTextCtrl(self, -1, name='intctrl', mask="#{9}", formatcodes = '_-,Fr')
label_floatctrl = wxStaticText( self, -1, """\
A floating point entry control
with right-insert for ordinal:""")
self.floatctrl = wxMaskedTextCtrl(self, -1, name='floatctrl', mask="#{9}.#{2}", formatcodes="F,_-R", useParensForNegatives=False)
self.floatctrl.SetFieldParameters(0, formatcodes='r<', validRequired=True) # right-insert, require explicit cursor movement to change fields
self.floatctrl.SetFieldParameters(1, defaultValue='00') # don't allow blank fraction
label_numselect = wxStaticText( self, -1, """\
<= Programmatically set the value
of the float entry ctrl:""")
numselect = wxComboBox(self, -1, choices = [ '', '111', '222.22', '-3', '54321.666666666', '-1353.978',
'1234567', '-1234567', '123456789', '-123456789.1',
'1234567890.', '-1234567890.1' ])
parens_check = wxCheckBox(self, -1, "Use () to indicate negatives in above controls")
gridCombos = wxFlexGridSizer( 0, 4, vgap=10, hgap = 10 )
gridCombos.Add( label_statecode, 0, wxALIGN_LEFT )
gridCombos.Add( statecode, 0, wxALIGN_LEFT )
gridCombos.Add( label_fraction, 0, wxALIGN_LEFT )
gridCombos.Add( fraction, 0, wxALIGN_LEFT )
gridCombos.Add( label_statename, 0, wxALIGN_LEFT )
gridCombos.Add( statename, 0, wxALIGN_LEFT )
gridCombos.Add( label_code, 0, wxALIGN_LEFT )
gridCombos.Add( code, 0, wxALIGN_LEFT )
gridCombos.Add( label_selector, 0, wxALIGN_LEFT)
hbox = wxBoxSizer( wxHORIZONTAL )
hbox.Add( self.list_selector, 0, wxALIGN_LEFT )
hbox.Add(wxStaticText(self, -1, ' => '), 0, wxALIGN_LEFT)
hbox.Add( self.dynamicbox, 0, wxALIGN_LEFT )
gridCombos.Add( hbox, 0, wxALIGN_LEFT )
gridIpAddrs = wxFlexGridSizer( 0, 4, vgap=10, hgap = 15 )
gridIpAddrs.Add( label_ipaddr1, 0, wxALIGN_LEFT )
gridIpAddrs.Add( ipaddr1, 0, wxALIGN_LEFT )
gridIpAddrs.Add( label_ipaddr2, 0, wxALIGN_LEFT )
gridIpAddrs.Add( ipaddr2, 0, wxALIGN_LEFT )
gridIpAddrs.Add( label_ipaddr3, 0, wxALIGN_LEFT )
gridIpAddrs.Add( ipaddr3, 0, wxALIGN_LEFT )
gridNumerics = wxFlexGridSizer( 0, 4, vgap=10, hgap = 10 )
gridNumerics.Add( label_intctrl1, 0, wxALIGN_LEFT )
gridNumerics.Add( self.intctrl1, 0, wxALIGN_LEFT )
gridNumerics.Add( label_intctrl2, 0, wxALIGN_RIGHT )
gridNumerics.Add( self.intctrl2, 0, wxALIGN_LEFT )
gridNumerics.Add( label_floatctrl, 0, wxALIGN_LEFT )
gridNumerics.Add( self.floatctrl, 0, wxALIGN_LEFT )
gridNumerics.Add( label_numselect, 0, wxALIGN_RIGHT )
gridNumerics.Add( numselect, 0, wxALIGN_LEFT )
self.sizer.Add( labelMaskedCombos, 0, wxALIGN_LEFT|wxALL, 5 )
self.sizer.Add( gridCombos, 0, wxALIGN_LEFT|wxALL, border=5 )
self.sizer.Add( wxStaticLine(self, -1), 0, wxEXPAND|wxTOP|wxBOTTOM, border=8 )
self.sizer.Add( labelIpAddrs, 0, wxALIGN_LEFT|wxALL, 5 )
self.sizer.Add( gridIpAddrs, 0, wxALIGN_LEFT|wxALL, border=5 )
self.sizer.Add( wxStaticLine(self, -1), 0, wxEXPAND|wxTOP|wxBOTTOM, border=8 )
self.sizer.Add( labelNumerics, 0, wxALIGN_LEFT|wxALL, 5 )
self.sizer.Add( gridNumerics, 0, wxALIGN_LEFT|wxALL, border=5 )
self.sizer.Add( parens_check, 0, wxALIGN_LEFT|wxALL, 5 )
self.SetSizer( self.sizer )
self.SetAutoLayout(1)
self.SetupScrolling()
EVT_COMBOBOX( self, fraction.GetId(), self.OnComboSelection )
EVT_COMBOBOX( self, code.GetId(), self.OnComboSelection )
EVT_COMBOBOX( self, statecode.GetId(), self.OnComboSelection )
EVT_COMBOBOX( self, statename.GetId(), self.OnComboSelection )
EVT_TEXT( self, fraction.GetId(), self.OnTextChange )
EVT_TEXT( self, code.GetId(), self.OnTextChange )
EVT_TEXT( self, statecode.GetId(), self.OnTextChange )
EVT_TEXT( self, statename.GetId(), self.OnTextChange )
EVT_COMBOBOX( self, self.list_selector.GetId(), self.OnListSelection )
EVT_TEXT( self, self.intctrl1.GetId(), self.OnTextChange )
EVT_TEXT( self, self.intctrl2.GetId(), self.OnTextChange )
EVT_TEXT( self, self.floatctrl.GetId(), self.OnTextChange )
EVT_COMBOBOX( self, numselect.GetId(), self.OnNumberSelect )
EVT_CHECKBOX( self, parens_check.GetId(), self.OnParensCheck )
EVT_TEXT( self, ipaddr1.GetId(), self.OnIpAddrChange )
EVT_TEXT( self, ipaddr2.GetId(), self.OnIpAddrChange )
EVT_TEXT( self, ipaddr3.GetId(), self.OnIpAddrChange )
def OnComboSelection( self, event ):
ctl = self.FindWindowById( event.GetId() )
if not ctl.IsValid():
self.log.write('current value not a valid choice')
self.log.write('new value = %s' % ctl.GetValue())
def OnTextChange( self, event ):
ctl = self.FindWindowById( event.GetId() )
if ctl.IsValid():
self.log.write('new value = %s\n' % ctl.GetValue() )
def OnNumberSelect( self, event ):
value = event.GetString()
# Format choice to fit into format for #{9}.#{2}, with sign position reserved:
# (ordinal + fraction == 11 + decimal point + sign == 13)
if value:
floattext = "%13.2f" % float(value)
else:
floattext = value # clear the value again
try:
self.floatctrl.SetValue(floattext)
except:
type, value, tb = sys.exc_info()
for line in traceback.format_exception_only(type, value):
self.log.write(line)
def OnParensCheck( self, event ):
self.intctrl1.SetCtrlParameters(useParensForNegatives=event.Checked())
self.intctrl2.SetCtrlParameters(useParensForNegatives=event.Checked())
self.floatctrl.SetCtrlParameters(useParensForNegatives=event.Checked())
def OnIpAddrChange( self, event ):
ipaddr = self.FindWindowById( event.GetId() )
if ipaddr.IsValid():
self.log.write('new addr = %s\n' % ipaddr.GetAddress() )
def OnListSelection( self, event ):
list = self.list_selector.GetStringSelection()
formatcodes = 'F_'
if list == 'list1':
choices = ['abc', 'defg', 'hi']
mask = 'aaaa'
elif list == 'list2':
choices = ['1', '2', '34', '567']
formatcodes += 'r'
mask = '###'
else:
choices = states
mask = 'AA'
formatcodes += '!'
self.dynamicbox.SetCtrlParameters( mask = mask,
choices = choices,
choiceRequired=True,
autoSelect=True,
formatcodes=formatcodes)
self.dynamicbox.SetValue(choices[0])
# ---------------------------------------------------------------------
class TestMaskedTextCtrls(wxNotebook):
def __init__(self, parent, id, log):
wxNotebook.__init__(self, parent, id)
self.log = log
win = demoPage1(self, log)
self.AddPage(win, "General examples")
win = demoPage2(self, log)
self.AddPage(win, 'Auto-formatted controls')
win = demoPage3(self, log)
self.AddPage(win, "Using default values")
win = demoPage4(self, log)
self.AddPage(win, 'Using auto-complete fields')
win = demoPage5(self, log)
self.AddPage(win, 'Other masked controls')
#----------------------------------------------------------------------------
def runTest(frame, nb, log):
testWin = TestMaskedTextCtrls(nb, -1, log)
return testWin
def RunStandalone():
app = wxPySimpleApp()
frame = wxFrame(None, -1, "Test wxMaskedTextCtrl", size=(640, 480))
win = TestMaskedTextCtrls(frame, -1, sys.stdout)
frame.Show(True)
app.MainLoop()
#----------------------------------------------------------------------------
if __name__ == "__main__":
RunStandalone()
overview = """<html>
<PRE><FONT SIZE=-1>
""" + maskededit_doc + """
</FONT></PRE>
"""
if __name__ == "__main__":
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -0,0 +1,47 @@
import wx # This module uses the new wx namespace
from wx import html
from Main import opj
#----------------------------------------------------------------------
class TestPanel(wx.Panel):
def __init__(self, parent, log):
self.log = log
wx.Panel.__init__(self, parent, -1)
hwin = html.HtmlWindow(self, -1)
hwin.LoadFile(opj('data/wxPackage.html'))
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(hwin, 1, wx.EXPAND)
self.SetSizer(sizer)
#----------------------------------------------------------------------
def runTest(frame, nb, log):
win = TestPanel(nb, log)
return win
#----------------------------------------------------------------------
overview = """<html><body>
<h2><center>Using the New Namespace</center></h2>
This sample isn't really a demo, but rather a place to display the
introductory doc for using the new namespace.
</body></html>
"""
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -30,7 +30,7 @@ class TestPanel(wxPanel):
sizer.Add(btns, 0, wxEXPAND|wxALL, 15)
self.SetSizer(sizer)
self.SetAutoLayout(true)
self.SetAutoLayout(True)
self.sizer = sizer # save it for testing later
@@ -136,3 +136,12 @@ and the second will show #2 (<i>working as of 2.3.2</i>)
</body></html>
"""
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

148
wxPython/demo/PopupMenu.py Normal file
View File

@@ -0,0 +1,148 @@
from wxPython.wx import *
import images
#----------------------------------------------------------------------
text = """\
Right-click on the panel (or Ctrl-click on the Mac) to show a popup
menu. Then look at the code for this sample. Notice how the
PopupMenu method is similar to the ShowModal method of a wxDialog in
that it doesn't return until the popup menu has been dismissed. The
event handlers for the popup menu items can either be attached to the
menu itself, or to the window that invokes PopupMenu.
"""
#----------------------------------------------------------------------
class TestPanel(wxPanel):
def __init__(self, parent, log):
self.log = log
wxPanel.__init__(self, parent, -1)
box = wxBoxSizer(wxVERTICAL)
# Make and layout the controls
fs = self.GetFont().GetPointSize()
bf = wxFont(fs+4, wxSWISS, wxNORMAL, wxBOLD)
nf = wxFont(fs+2, wxSWISS, wxNORMAL, wxNORMAL)
t = wxStaticText(self, -1, "PopupMenu")
t.SetFont(bf)
box.Add(t, 0, wxCENTER|wxALL, 5)
box.Add(wxStaticLine(self, -1), 0, wxEXPAND)
box.Add(10,20)
t = wxStaticText(self, -1, text)
t.SetFont(nf)
box.Add(t, 0, wxCENTER|wxALL, 5)
self.SetSizer(box)
EVT_RIGHT_UP(self, self.OnRightClick)
def OnRightClick(self, event):
self.log.WriteText("OnRightClick\n")
# only do this part the first time so the events are only bound once
if not hasattr(self, "popupID1"):
self.popupID1 = wxNewId()
self.popupID2 = wxNewId()
self.popupID3 = wxNewId()
self.popupID4 = wxNewId()
self.popupID5 = wxNewId()
self.popupID6 = wxNewId()
self.popupID7 = wxNewId()
self.popupID8 = wxNewId()
self.popupID9 = wxNewId()
EVT_MENU(self, self.popupID1, self.OnPopupOne)
EVT_MENU(self, self.popupID2, self.OnPopupTwo)
EVT_MENU(self, self.popupID3, self.OnPopupThree)
EVT_MENU(self, self.popupID4, self.OnPopupFour)
EVT_MENU(self, self.popupID5, self.OnPopupFive)
EVT_MENU(self, self.popupID6, self.OnPopupSix)
EVT_MENU(self, self.popupID7, self.OnPopupSeven)
EVT_MENU(self, self.popupID8, self.OnPopupEIght)
EVT_MENU(self, self.popupID9, self.OnPopupNine)
# make a menu
menu = wxMenu()
# Show how to put an icon in the menu
item = wxMenuItem(menu, self.popupID1,"One")
item.SetBitmap(images.getSmilesBitmap())
menu.AppendItem(item)
# add some other items
menu.Append(self.popupID2, "Two")
menu.Append(self.popupID3, "Three")
menu.Append(self.popupID4, "Four")
menu.Append(self.popupID5, "Five")
menu.Append(self.popupID6, "Six")
# make a submenu
sm = wxMenu()
sm.Append(self.popupID8, "sub item 1")
sm.Append(self.popupID9, "sub item 1")
menu.AppendMenu(self.popupID7, "Test Submenu", sm)
# Popup the menu. If an item is selected then its handler
# will be called before PopupMenu returns.
self.PopupMenu(menu, event.GetPosition())
menu.Destroy()
def OnPopupOne(self, event):
self.log.WriteText("Popup one\n")
def OnPopupTwo(self, event):
self.log.WriteText("Popup two\n")
def OnPopupThree(self, event):
self.log.WriteText("Popup three\n")
def OnPopupFour(self, event):
self.log.WriteText("Popup four\n")
def OnPopupFive(self, event):
self.log.WriteText("Popup five\n")
def OnPopupSix(self, event):
self.log.WriteText("Popup six\n")
def OnPopupSeven(self, event):
self.log.WriteText("Popup seven\n")
def OnPopupEIght(self, event):
self.log.WriteText("Popup eight\n")
def OnPopupNine(self, event):
self.log.WriteText("Popup nine\n")
#----------------------------------------------------------------------
def runTest(frame, nb, log):
win = TestPanel(nb, log)
return win
#----------------------------------------------------------------------
overview = """<html><body>
<h2><center>PopupMenu</center></h2>
""" + text + """
</body></html>
"""
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -33,9 +33,9 @@ class MyPrintout(wxPrintout):
def HasPage(self, page):
self.log.WriteText("wxPrintout.HasPage: %d\n" % page)
if page <= 2:
return true
return True
else:
return false
return False
def GetPageInfo(self):
self.log.WriteText("wxPrintout.GetPageInfo\n")
@@ -69,7 +69,7 @@ class MyPrintout(wxPrintout):
# Use x or y scaling factor, whichever fits on the DC
actualScale = min(scaleX, scaleY)
# Calculate the position on the DC for centring the graphic
# Calculate the position on the DC for centering the graphic
posX = (w - (self.canvas.getWidth() * actualScale)) / 2.0
posY = (h - (self.canvas.getHeight() * actualScale)) / 2.0
@@ -79,10 +79,10 @@ class MyPrintout(wxPrintout):
#-------------------------------------------
self.canvas.DoDrawing(dc)
self.canvas.DoDrawing(dc, True)
dc.DrawText("Page: %d" % page, marginX/2, maxY-marginY)
return true
return True
#----------------------------------------------------------------------
@@ -117,14 +117,14 @@ class TestPrintPanel(wxPanel):
self.box.Add(subbox, 0, wxGROW)
self.SetAutoLayout(true)
self.SetAutoLayout(True)
self.SetSizer(self.box)
def OnPrintSetup(self, event):
printerDialog = wxPrintDialog(self)
printerDialog.GetPrintDialogData().SetPrintData(self.printData)
printerDialog.GetPrintDialogData().SetSetupDialog(true)
printerDialog.GetPrintDialogData().SetSetupDialog(True)
printerDialog.ShowModal();
self.printData = printerDialog.GetPrintDialogData().GetPrintData()
printerDialog.Destroy()
@@ -144,7 +144,7 @@ class TestPrintPanel(wxPanel):
frame.Initialize()
frame.SetPosition(self.frame.GetPosition())
frame.SetSize(self.frame.GetSize())
frame.Show(true)
frame.Show(True)
@@ -176,3 +176,12 @@ def runTest(frame, nb, log):
overview = """\
"""
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -1,20 +1,18 @@
from wxPython.lib.PyCrust import shell, version
from wx import py
#----------------------------------------------------------------------
intro = 'Welcome To PyCrust %s - The Flakiest Python Shell' % version.VERSION
intro = 'Welcome To PyCrust %s - The Flakiest Python Shell' % py.version.VERSION
def runTest(frame, nb, log):
win = shell.Shell(nb, -1, introText=intro)
win = py.crust.Crust(nb, intro=intro)
return win
#----------------------------------------------------------------------
overview = shell.__doc__
overview = py.filling.__doc__ + "\n\n" + py.crust.__doc__
if __name__ == '__main__':
import sys,os

View File

@@ -1,28 +0,0 @@
from wxPython.wx import wxSplitterWindow
from wxPython.lib.PyCrust import shell, version, filling
#----------------------------------------------------------------------
intro = 'Welcome To PyCrust %s - The Flakiest Python Shell' % version.VERSION
def runTest(frame, nb, log):
win = wxSplitterWindow(nb, -1, size=(640, 480))
shellWin = shell.Shell(win, -1, introText=intro)
fillingWin = filling.Filling(win, -1, size=(640, 480),
rootObject=shellWin.interp.locals,
rootIsNamespace=1
)
win.SplitHorizontally(shellWin, fillingWin)
return win
#----------------------------------------------------------------------
overview = filling.__doc__
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

23
wxPython/demo/PyShell.py Normal file
View File

@@ -0,0 +1,23 @@
from wx import py
#----------------------------------------------------------------------
intro = 'Welcome To PyCrust %s - The Flakiest Python Shell' % py.version.VERSION
def runTest(frame, nb, log):
win = py.shell.Shell(nb, -1, introText=intro)
return win
#----------------------------------------------------------------------
overview = py.shell.__doc__
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -77,9 +77,16 @@ def runTest(frame, nb, log):
overview = """\
This demo is a contrived example of defining an event class in wxPython and sending it up the containment heirachy for processing.
This demo is a contrived example of defining an event class in wxPython and sending it up the containment hierarchy for processing.
"""
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -50,7 +50,7 @@ class TestPanel(wxPanel):
sizer.AddSpacer(10,10, pos=(13,1))
self.SetSizer(sizer)
self.SetAutoLayout(true)
self.SetAutoLayout(True)
#----------------------------------------------------------------------
@@ -67,3 +67,9 @@ import wxPython.lib.rcsizer
overview = wxPython.lib.rcsizer.__doc__
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -1,97 +0,0 @@
from wxPython.wx import *
#----------------------------------------------------------------------
text = "one two buckle my shoe three four shut the door five six pick up sticks seven eight lay them straight nine ten big fat hen"
class ScrolledPanel(wxScrolledWindow):
def __init__(self, parent, log):
self.log = log
wxScrolledWindow.__init__(self, parent, -1,
style = wxTAB_TRAVERSAL)
box = wxBoxSizer(wxVERTICAL)
box.Add(wxStaticText(self, -1,
"This sample shows how to make a scrollable data entry \n"
"form by using a wxSizer in a wxScrolledWindow."),
0, wxCENTER|wxALL, 5)
box.Add(wxStaticLine(self, -1), 0, wxEXPAND|wxALL, 5)
fgs = wxFlexGridSizer(cols=2, vgap=4, hgap=4)
fgs.AddGrowableCol(1)
# Add some spacers
fgs.Add(75, 10)
fgs.Add(150, 10)
for word in text.split():
label = wxStaticText(self, -1, word+":")
tc = wxTextCtrl(self, -1, word)
fgs.Add(label, flag=wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL)
fgs.Add(tc, flag=wxEXPAND)
box.Add(fgs, 1)
box.Add(10, 40) # some more empty space at the bottom
self.SetSizer(box)
# The following is all that is needed to integrate the sizer and the
# scrolled window. In this case we will only support vertical scrolling.
self.EnableScrolling(false, true)
self.SetScrollRate(0, 20)
box.SetVirtualSizeHints(self)
EVT_CHILD_FOCUS(self, self.OnChildFocus)
wxCallAfter(self.Scroll, 0, 0) # scroll back to top after initial events
def OnChildFocus(self, evt):
# If the child window that gets the focus is not visible,
# this handler will try to scroll enough to see it. If you
# need to handle horizontal auto-scrolling too then this will
# need adapted.
evt.Skip()
child = evt.GetWindow()
sppu_y = self.GetScrollPixelsPerUnit()[1]
vs_y = self.GetViewStart()[1]
cpos = child.GetPosition()
csz = child.GetSize()
# is it above the top?
if cpos.y < 0:
new_vs = cpos.y / sppu_y
self.Scroll(-1, new_vs)
# is it below the bottom ?
if cpos.y + csz.height > self.GetClientSize().height:
diff = (cpos.y + csz.height - self.GetClientSize().height) / sppu_y
self.Scroll(-1, vs_y + diff + 1)
#----------------------------------------------------------------------
def runTest(frame, nb, log):
win = ScrolledPanel(nb, log)
return win
#----------------------------------------------------------------------
overview = """<html><body>
This sample shows how to make a scrollable data entry form by
using a wxSizer in a wxScrolledWindow.
</body></html>
"""
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -0,0 +1,122 @@
from wxPython.wx import *
import images
#----------------------------------------------------------------------
class TestFrame(wxFrame):
def __init__(self, parent, log):
self.log = log
wxFrame.__init__(self, parent, -1, "Shaped Window",
style =
wxFRAME_SHAPED
| wxSIMPLE_BORDER
| wxFRAME_NO_TASKBAR
| wxSTAY_ON_TOP
)
self.hasShape = False
self.delta = wxPoint(0,0)
EVT_LEFT_DCLICK(self, self.OnDoubleClick)
EVT_LEFT_DOWN(self, self.OnLeftDown)
EVT_LEFT_UP(self, self.OnLeftUp)
EVT_MOTION(self, self.OnMouseMove)
EVT_RIGHT_UP(self, self.OnExit)
EVT_PAINT(self, self.OnPaint)
self.bmp = images.getVippiBitmap()
w, h = self.bmp.GetWidth(), self.bmp.GetHeight()
self.SetClientSize( (w, h) )
if wxPlatform != "__WXMAC__":
# wxMac clips the tooltip to the window shape, YUCK!!!
self.SetToolTipString("Right-click to close the window\n"
"Double-click the image to set/unset the window shape")
if wxPlatform == "__WXGTK__":
# wxGTK requires that the window be created before you can
# set its shape, so delay the call to SetWindowShape until
# this event.
EVT_WINDOW_CREATE(self, self.SetWindowShape)
else:
# On wxMSW and wxMac the window has already been created, so go for it.
self.SetWindowShape()
dc = wxClientDC(self)
dc.DrawBitmap(self.bmp, 0,0, True)
def SetWindowShape(self, *evt):
# Use the bitmap's mask to determine the region
r = wxRegionFromBitmap(self.bmp)
self.hasShape = self.SetShape(r)
def OnDoubleClick(self, evt):
if self.hasShape:
self.SetShape(wxRegion())
self.hasShape = False
else:
self.SetWindowShape()
def OnPaint(self, evt):
dc = wxPaintDC(self)
dc.DrawBitmap(self.bmp, 0,0, True)
def OnExit(self, evt):
self.Close()
def OnLeftDown(self, evt):
self.CaptureMouse()
pos = self.ClientToScreen(evt.GetPosition())
origin = self.GetPosition()
dx = pos.x - origin.x
dy = pos.y - origin.y
self.delta = wxPoint(dx, dy)
def OnLeftUp(self, evt):
if self.HasCapture():
self.ReleaseMouse()
def OnMouseMove(self, evt):
if evt.Dragging() and evt.LeftIsDown():
pos = self.ClientToScreen(evt.GetPosition())
fp = (pos.x - self.delta.x, pos.y - self.delta.y)
self.Move(fp)
#----------------------------------------------------------------------
def runTest(frame, nb, log):
win = TestFrame(nb, log)
frame.otherWin = win
win.Show(True)
#----------------------------------------------------------------------
overview = """<html><body>
<h2><center>Shaped Window</center></h2>
Top level windows now have a SetShape method that lets you set a
non-rectangular shape for the window using a wxRegion. All pixels
outside of the region will not be drawn and the window will not be
sensitive to the mouse in those areas either.
</body></html>
"""
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -141,11 +141,11 @@ def makeBoxInBox(win):
box.Add(wxButton(win, 1010, "one"), 0, wxEXPAND)
box2 = wxBoxSizer(wxHORIZONTAL)
box2.AddMany([ (wxButton(win, 1010, "two"), 0, wxEXPAND),
(wxButton(win, 1010, "three"), 0, wxEXPAND),
(wxButton(win, 1010, "four"), 0, wxEXPAND),
(wxButton(win, 1010, "five"), 0, wxEXPAND),
])
box2.Add(wxButton(win, 1010, "two"), 0, wxEXPAND)
btn3 = wxButton(win, 1010, "three")
box2.Add(btn3, 0, wxEXPAND)
box2.Add(wxButton(win, 1010, "four"), 0, wxEXPAND)
box2.Add(wxButton(win, 1010, "five"), 0, wxEXPAND)
box3 = wxBoxSizer(wxVERTICAL)
box3.AddMany([ (wxButton(win, 1010, "six"), 0, wxEXPAND),
@@ -159,6 +159,8 @@ def makeBoxInBox(win):
box.Add(wxButton(win, 1010, "ten"), 0, wxEXPAND)
##box.Hide(btn3)
return box
#----------------------------------------------------------------------
@@ -360,7 +362,7 @@ theTests = [
),
("Add a stretchable", makeSimpleBox3,
"We've added one more button with the strechable flag turned on. Notice "
"We've added one more button with the stretchable flag turned on. Notice "
"how it grows to fill the extra space in the otherwise fixed dimension."
),
@@ -370,7 +372,7 @@ theTests = [
),
("Weighting factor", makeSimpleBox5,
"This one shows more than one strechable, but one of them has a weighting "
"This one shows more than one stretchable, but one of them has a weighting "
"factor so it gets more of the free space."
),
@@ -419,7 +421,7 @@ theTests = [
),
("Boxes inside a Border", makeBoxInBorder,
"Sizers of different types can be nested withing each other as well. "
"Sizers of different types can be nested within each other as well. "
"Here is a box sizer with several buttons embedded within a border sizer."
),
@@ -432,7 +434,7 @@ theTests = [
("Simple Grid", makeGrid1,
"This is an example of the wxGridSizer. In this case all row heights "
"and column widths are kept the same as all the others and all items "
"fill their available space. The horzontal and vertical gaps are set to "
"fill their available space. The horizontal and vertical gaps are set to "
"2 pixels each."
),
@@ -459,7 +461,7 @@ theTests = [
("Proportional resize", makeSimpleBoxShaped,
"Managed items can preserve their original aspect ratio. The last item has the "
"wxSHAPED flag set and will resize proportional to its origingal size."
"wxSHAPED flag set and will resize proportional to its original size."
),
("Proportional resize with Alignments", makeShapes,
@@ -479,16 +481,16 @@ class TestFrame(wxFrame):
self.SetStatusText("Resize this frame to see how the sizers respond...")
self.sizer.Fit(self)
self.SetAutoLayout(true)
self.SetAutoLayout(True)
self.SetSizer(self.sizer)
EVT_CLOSE(self, self.OnCloseWindow)
def OnCloseWindow(self, event):
self.MakeModal(false)
self.MakeModal(False)
self.Destroy()
def OnButton(self, event):
self.Close(true)
self.Close(True)
#----------------------------------------------------------------------
@@ -531,8 +533,8 @@ class TestSelectionPanel(wxPanel):
if func:
win = TestFrame(self, title, func)
win.CentreOnParent(wxBOTH)
win.Show(true)
win.MakeModal(true)
win.Show(True)
win.MakeModal(True)
#----------------------------------------------------------------------
@@ -555,12 +557,12 @@ if __name__ == '__main__':
def __init__(self):
wxFrame.__init__(self, None, -1, "Testing...")
self.CreateStatusBar()
mainmenu = wxMenuBar()
menu = wxMenu()
menu.Append(200, 'E&xit', 'Get the heck outta here!')
mainmenu.Append(menu, "&File")
self.SetMenuBar(mainmenu)
self.CreateStatusBar()
mainmenu = wxMenuBar()
menu = wxMenu()
menu.Append(200, 'E&xit', 'Get the heck outta here!')
mainmenu.Append(menu, "&File")
self.SetMenuBar(mainmenu)
EVT_MENU(self, 200, self.OnExit)
self.panel = TestSelectionPanel(self, self)
self.SetSize(wxSize(400, 380))
@@ -570,15 +572,15 @@ if __name__ == '__main__':
self.Destroy()
def OnExit(self, event):
self.Close(true)
self.Close(True)
class TestApp(wxApp):
def OnInit(self):
frame = MainFrame()
frame.Show(true)
frame.Show(True)
self.SetTopWindow(frame)
return true
return True
app = TestApp(0)
app.MainLoop()

View File

@@ -1,379 +0,0 @@
#!/usr/bin/python
"""This is SlashDot 1.2
It's the obligatory Slashdot.org headlines reader that
any modern widget set/library must have in order to be taken
seriously :-)
Usage is quite simple; wxSlash attempts to download the
'ultramode.txt' file from http://slashdot.org, which
contains the headlines in a computer friendly format. It
then displays said headlines in a wxWindows list control.
You can read articles using either Python's html library
or an external browser. Uncheck the 'browser->internal' menu
item to use the latter option. Use the settings dialog box
to set which external browser is started.
This code is available under the wxWindows license, see
elsewhere. If you modify this code, be aware of the fact
that slashdot.org's maintainer, CmdrTaco, explicitly asks
'ultramode.txt' downloaders not to do this automatically
more than twice per hour. If this feature is abused,
CmdrTaco may remove the ultramode file completely and that
will make a *lot* of people unhappy.
I want to thank Alex Shnitman whose slashes.pl
(Perl/GTK) script gave me the idea for this applet.
Have fun with it,
Harm van der Heijden (H.v.d.Heijden@phys.tue.nl)
"""
from wxPython.wx import *
from httplib import HTTP
from htmllib import HTMLParser
import os
import re
import formatter
class HTMLTextView(wxFrame):
def __init__(self, parent, id, title='HTMLTextView', url=None):
wxFrame.__init__(self, parent, id, title, wxPyDefaultPosition,
wxSize(600,400))
EVT_CLOSE(self, self.OnCloseWindow)
self.mainmenu = wxMenuBar()
menu = wxMenu()
menu.Append(201, '&Open URL...', 'Open URL')
EVT_MENU(self, 201, self.OnFileOpen)
menu.Append(209, 'E&xit', 'Exit viewer')
EVT_MENU(self, 209, self.OnFileExit)
self.mainmenu.Append(menu, '&File')
self.SetMenuBar(self.mainmenu)
self.CreateStatusBar(1)
self.text = wxTextCtrl(self, -1, "", wxPyDefaultPosition,
wxPyDefaultSize, wxTE_MULTILINE | wxTE_READONLY)
if (url):
self.OpenURL(url)
def logprint(self, x):
self.SetStatusText(x)
def OpenURL(self, url):
self.url = url
m = re.match('file:(\S+)\s*', url)
if m:
f = open(m.groups()[0],'r')
else:
m = re.match('http://([^/]+)(/\S*)\s*', url)
if m:
host = m.groups()[0]
path = m.groups()[1]
else:
m = re.match('http://(\S+)\s*', url)
if not m:
# Invalid URL
self.logprint("Invalid or unsupported URL: %s" % (url))
return
host = m.groups()[0]
path = ''
f = RetrieveAsFile(host,path,self.logprint)
if not f:
self.logprint("Could not open %s" % (url))
return
self.logprint("Receiving data...")
data = f.read()
tmp = open('tmphtml.txt','w')
fmt = formatter.AbstractFormatter(formatter.DumbWriter(tmp))
p = HTMLParser(fmt)
self.logprint("Parsing data...")
p.feed(data)
p.close()
tmp.close()
tmp = open('tmphtml.txt', 'r')
self.text.SetValue(tmp.read())
self.SetTitle(url)
self.logprint(url)
def OnFileOpen(self, event):
dlg = wxTextEntryDialog(self, "Enter URL to open:", "")
if dlg.ShowModal() == wxID_OK:
url = dlg.GetValue()
else:
url = None
if url:
self.OpenURL(url)
def OnFileExit(self, event):
self.Close()
def OnCloseWindow(self, event):
self.Destroy()
def ParseSlashdot(f):
art_sep = re.compile('%%\r?\n')
line_sep = re.compile('\r?\n')
data = f.read()
list = art_sep.split(data)
art_list = []
for i in range(1,len(list)-1):
art_list.append(line_sep.split(list[i]))
return art_list
def myprint(x):
print x
def RetrieveAsFile(host, path='', logprint = myprint):
try:
h = HTTP(host)
except:
logprint("Failed to create HTTP connection to %s... is the network available?" % (host))
return None
h.putrequest('GET',path)
h.putheader('Accept','text/html')
h.putheader('Accept','text/plain')
h.endheaders()
errcode, errmsg, headers = h.getreply()
if errcode != 200:
logprint("HTTP error code %d: %s" % (errcode, errmsg))
return None
f = h.getfile()
# f = open('/home/harm/ultramode.txt','r')
return f
class AppStatusBar(wxStatusBar):
def __init__(self, parent):
wxStatusBar.__init__(self,parent, -1)
self.SetFieldsCount(2)
self.SetStatusWidths([-1, 100])
self.but = wxButton(self, 1001, "Refresh")
EVT_BUTTON(self, 1001, parent.OnViewRefresh)
EVT_SIZE(self, self.OnSize)
self.OnSize(None)
def logprint(self,x):
self.SetStatusText(x,0)
def OnSize(self, event):
rect = self.GetFieldRect(1)
self.but.SetPosition(wxPoint(rect.x+2, rect.y+2))
self.but.SetSize(wxSize(rect.width-4, rect.height-4))
# This is a simple timer class to start a function after a short delay;
class QuickTimer(wxTimer):
def __init__(self, func, wait=100):
wxTimer.__init__(self)
self.callback = func
self.Start(wait); # wait .1 second (.001 second doesn't work. why?)
def Notify(self):
self.Stop();
apply(self.callback, ());
class AppFrame(wxFrame):
def __init__(self, parent, id, title):
wxFrame.__init__(self, parent, id, title, wxPyDefaultPosition,
wxSize(650, 250))
# if the window manager closes the window:
EVT_CLOSE(self, self.OnCloseWindow);
# Now Create the menu bar and items
self.mainmenu = wxMenuBar()
menu = wxMenu()
menu.Append(209, 'E&xit', 'Enough of this already!')
EVT_MENU(self, 209, self.OnFileExit)
self.mainmenu.Append(menu, '&File')
menu = wxMenu()
menu.Append(210, '&Refresh', 'Refresh headlines')
EVT_MENU(self, 210, self.OnViewRefresh)
menu.Append(211, '&Slashdot Index', 'View Slashdot index')
EVT_MENU(self, 211, self.OnViewIndex)
menu.Append(212, 'Selected &Article', 'View selected article')
EVT_MENU(self, 212, self.OnViewArticle)
self.mainmenu.Append(menu, '&View')
menu = wxMenu()
menu.Append(220, '&Internal', 'Use internal text browser',TRUE)
menu.Check(220, true)
self.UseInternal = 1;
EVT_MENU(self, 220, self.OnBrowserInternal)
menu.Append(222, '&Settings...', 'External browser Settings')
EVT_MENU(self, 222, self.OnBrowserSettings)
self.mainmenu.Append(menu, '&Browser')
menu = wxMenu()
menu.Append(230, '&About', 'Some documentation');
EVT_MENU(self, 230, self.OnAbout)
self.mainmenu.Append(menu, '&Help')
self.SetMenuBar(self.mainmenu)
if wxPlatform == '__WXGTK__':
# I like lynx. Also Netscape 4.5 doesn't react to my cmdline opts
self.BrowserSettings = "xterm -e lynx %s &"
elif wxPlatform == '__WXMSW__':
# netscape 4.x likes to hang out here...
self.BrowserSettings = '\\progra~1\\Netscape\\Communicator\\Program\\netscape.exe %s'
else:
# a wild guess...
self.BrowserSettings = 'netscape %s'
# A status bar to tell people what's happening
self.sb = AppStatusBar(self)
self.SetStatusBar(self.sb)
self.list = wxListCtrl(self, 1100, style=wxLC_REPORT)
self.list.InsertColumn(0, 'Subject')
self.list.InsertColumn(1, 'Date')
self.list.InsertColumn(2, 'Posted by')
self.list.InsertColumn(3, 'Comments')
self.list.SetColumnWidth(0, 300)
self.list.SetColumnWidth(1, 150)
self.list.SetColumnWidth(2, 100)
self.list.SetColumnWidth(3, 100)
EVT_LIST_ITEM_SELECTED(self, 1100, self.OnItemSelected)
EVT_LEFT_DCLICK(self.list, self.OnLeftDClick)
self.logprint("Connecting to slashdot... Please wait.")
# wxYield doesn't yet work here. That's why we use a timer
# to make sure that we see some GUI stuff before the slashdot
# file is transfered.
self.timer = QuickTimer(self.DoRefresh, 1000)
def logprint(self, x):
self.sb.logprint(x)
def OnFileExit(self, event):
self.Destroy()
def DoRefresh(self):
f = RetrieveAsFile('slashdot.org','/ultramode.txt',self.sb.logprint)
art_list = ParseSlashdot(f)
self.list.DeleteAllItems()
self.url = []
self.current = -1
i = 0;
for article in art_list:
self.list.InsertStringItem(i, article[0])
self.list.SetStringItem(i, 1, article[2])
self.list.SetStringItem(i, 2, article[3])
self.list.SetStringItem(i, 3, article[6])
self.url.append(article[1])
i = i + 1
self.logprint("File retrieved OK.")
def OnViewRefresh(self, event):
self.logprint("Connecting to slashdot... Please wait.");
wxYield()
self.DoRefresh()
def DoViewIndex(self):
if self.UseInternal:
self.view = HTMLTextView(self, -1, 'slashdot.org',
'http://slashdot.org')
self.view.Show(true)
else:
self.logprint(self.BrowserSettings % ('http://slashdot.org'))
#os.system(self.BrowserSettings % ('http://slashdot.org'))
wxExecute(self.BrowserSettings % ('http://slashdot.org'))
self.logprint("OK")
def OnViewIndex(self, event):
self.logprint("Starting browser... Please wait.")
wxYield()
self.DoViewIndex()
def DoViewArticle(self):
if self.current<0: return
url = self.url[self.current]
if self.UseInternal:
self.view = HTMLTextView(self, -1, url, url)
self.view.Show(true)
else:
self.logprint(self.BrowserSettings % (url))
os.system(self.BrowserSettings % (url))
self.logprint("OK")
def OnViewArticle(self, event):
self.logprint("Starting browser... Please wait.")
wxYield()
self.DoViewArticle()
def OnBrowserInternal(self, event):
if self.mainmenu.Checked(220):
self.UseInternal = 1
else:
self.UseInternal = 0
def OnBrowserSettings(self, event):
dlg = wxTextEntryDialog(self, "Enter command to view URL.\nUse %s as a placeholder for the URL.", "", self.BrowserSettings);
if dlg.ShowModal() == wxID_OK:
self.BrowserSettings = dlg.GetValue()
def OnAbout(self, event):
dlg = wxMessageDialog(self, __doc__, "wxSlash", wxOK | wxICON_INFORMATION)
dlg.ShowModal()
def OnItemSelected(self, event):
self.current = event.m_itemIndex
self.logprint("URL: %s" % (self.url[self.current]))
def OnLeftDClick(self, event):
(x,y) = event.Position();
# Actually, we should convert x,y to logical coords using
# a dc, but only for a wxScrolledWindow widget.
# Now wxGTK derives wxListCtrl from wxScrolledWindow,
# and wxMSW from wxControl... So that doesn't work.
#dc = wxClientDC(self.list)
##self.list.PrepareDC(dc)
#x = dc.DeviceToLogicalX( event.GetX() )
#y = dc.DeviceToLogicalY( event.GetY() )
id = self.list.HitTest(wxPoint(x,y))
#print "Double click at %d %d" % (x,y), id
# Okay, we got a double click. Let's assume it's the current selection
wxYield()
self.OnViewArticle(event)
def OnCloseWindow(self, event):
self.Destroy()
#---------------------------------------------------------------------------
# if running standalone
if __name__ == '__main__':
class MyApp(wxApp):
def OnInit(self):
frame = AppFrame(None, -1, "Slashdot Breaking News")
frame.Show(true)
self.SetTopWindow(frame)
return true
app = MyApp(0)
app.MainLoop()
#---------------------------------------------------------------------------
# if running as part of the Demo Framework...
def runTest(frame, nb, log):
win = AppFrame(None, -1, "Slashdot Breaking News")
frame.otherWin = win
win.Show(true)
overview = __doc__
#----------------------------------------------------------------------------

View File

@@ -76,23 +76,26 @@ class TestPanel(wxPanel):
wxNO_BORDER )
valueWindow = TestValueWindow(splitter, -1, style=wxNO_BORDER)
splitter.SplitVertically(tree, valueWindow)
splitter.SetSashPosition(150)
splitter.SplitVertically(tree, valueWindow, 150)
scroller.SetTargetWindow(tree)
scroller.EnableScrolling(FALSE, FALSE)
scroller.EnableScrolling(False, False)
valueWindow.SetTreeCtrl(tree)
tree.SetCompanionWindow(valueWindow)
sizer = wxBoxSizer(wxVERTICAL)
sizer.Add(scroller, 1, wxEXPAND|wxALL, 25)
self.SetAutoLayout(true)
self.SetAutoLayout(True)
self.SetSizer(sizer)
#----------------------------------------------------------------------
def runTest(frame, nb, log):
if wxPlatform == "__WXMAC__":
wxMessageBox("This demo currently fails on the Mac. The problem is being looked into...", "Sorry")
return
win = TestPanel(nb, log)
return win

View File

@@ -31,7 +31,7 @@ class TablePanel(wxPanel):
box.Add(btn, 0, wxALIGN_CENTER|wxALL, 15)
EVT_BUTTON(self, k, self.OnButton)
self.SetAutoLayout(true)
self.SetAutoLayout(True)
self.SetSizer(box)
def OnButton(self, evt):
@@ -47,11 +47,11 @@ class TablePanel(wxPanel):
data = []
while 1:
text = file.readline()
text = string.strip(text)
text = text.strip()
if not text:
break
list_val = string.splitfields(text,'\t')
list_val = text.split('\t')
data.append(list_val)
file.close()
@@ -187,7 +187,7 @@ This demo shows various ways of using the <b><i>new
</i></b> PrintOut class. To understand the class you need to examine the demo examples
and the library <a href="%s">printout.py</a> module classes.
<p>
The initial class primarily contains a Table preview/printing class. There is alot of flexibility
The initial class primarily contains a Table preview/printing class. There is a lot of flexibility
in manipulating the placement, sizing, colours, alignment of the table text and cell background colors.
There are also a number of options for printing Header and Footer information on the page.
<p>
@@ -205,3 +205,12 @@ when the framework allows for it.
""" % os.path.join(os.path.dirname(wxPython.lib.printout.__file__), "printout.py")
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -1,5 +1,6 @@
from wxPython.wx import *
from wxPython.lib import newevent
import thread
import time
@@ -7,18 +8,8 @@ from whrandom import random
#----------------------------------------------------------------------
wxEVT_UPDATE_BARGRAPH = wxNewEventType()
def EVT_UPDATE_BARGRAPH(win, func):
win.Connect(-1, -1, wxEVT_UPDATE_BARGRAPH, func)
class UpdateBarEvent(wxPyEvent):
def __init__(self, barNum, value):
wxPyEvent.__init__(self)
self.SetEventType(wxEVT_UPDATE_BARGRAPH)
self.barNum = barNum
self.value = value
# This creates a new Event class and a EVT binder function
UpdateBarEvent, EVT_UPDATE_BARGRAPH = newevent.NewEvent()
#----------------------------------------------------------------------
@@ -30,18 +21,18 @@ class CalcBarThread:
self.val = val
def Start(self):
self.keepGoing = self.running = true
self.keepGoing = self.running = True
thread.start_new_thread(self.Run, ())
def Stop(self):
self.keepGoing = false
self.keepGoing = False
def IsRunning(self):
return self.running
def Run(self):
while self.keepGoing:
evt = UpdateBarEvent(self.barNum, int(self.val))
evt = UpdateBarEvent(barNum = self.barNum, value = int(self.val))
wxPostEvent(self.win, evt)
#del evt
@@ -57,7 +48,7 @@ class CalcBarThread:
if self.val < 0: self.val = 0
if self.val > 300: self.val = 300
self.running = false
self.running = False
#----------------------------------------------------------------------
@@ -172,7 +163,7 @@ class TestFrame(wxFrame):
sizer.Add(self.graph, 1, wxEXPAND)
self.SetSizer(sizer)
self.SetAutoLayout(true)
self.SetAutoLayout(True)
sizer.Fit(self)
EVT_UPDATE_BARGRAPH(self, self.OnUpdate)
@@ -194,7 +185,7 @@ class TestFrame(wxFrame):
def OnUpdate(self, evt):
self.graph.SetValue(evt.barNum, evt.value)
self.graph.Refresh(false)
self.graph.Refresh(False)
def OnCloseWindow(self, evt):
@@ -217,7 +208,7 @@ class TestFrame(wxFrame):
def runTest(frame, nb, log):
win = TestFrame(frame, log)
frame.otherWin = win
win.Show(true)
win.Show(True)
return None
#----------------------------------------------------------------------
@@ -232,7 +223,7 @@ so any cross platform GUI Toolkit and applications written with it
need to take that into account.
The solution is to only allow interaction with the GUI from a single
thread, but this often severly limits what can be done in an
thread, but this often severely limits what can be done in an
application and makes it difficult to use additional threads at all.
Since wxPython already makes extensive use of event handlers, it is a
@@ -244,3 +235,11 @@ ProcessEvent does, it processes it later from the context of the GUI
thread.
"""
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

158
wxPython/demo/Throbber.py Normal file
View File

@@ -0,0 +1,158 @@
#
# Throbber.py - Cliff Wells <clifford.wells@attbi.com>
#
from wxPython.wx import *
from wxPython.lib.rcsizer import RowColSizer
from wxPython.lib.throbber import Throbber, __doc__ as docString
import throbImages # this was created using a modified version of img2py
#----------------------------------------------------------------------
class TestPanel(wxPanel):
def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1)
self.log = log
# create the throbbers
self.throbbers = {
'plain': { 'throbber': None,
'text': "Plain throbber." },
'reverse': { 'throbber': None,
'text': "This throbber runs in reverse and faster." },
'autoreverse': { 'throbber': None,
'text': "This throbber switches direction." },
'label': { 'throbber': None,
'text': "With a label." },
'overlay': { 'throbber': None,
'text': "With an overlayed image." },
'overlay+text': { 'throbber': None,
'text': "With a label and an overlayed image." },
}
images = [throbImages.catalog[i].getBitmap()
for i in throbImages.index
if i not in ['logo']]
self.throbbers['plain']['throbber'] = Throbber(self, -1,
images, size=(36, 36),
frameDelay = 0.1)
self.throbbers['reverse']['throbber'] = Throbber(self, -1, images, #size=(36, 36),
frameDelay = 0.07)
self.throbbers['reverse']['throbber'].Reverse()
self.throbbers['autoreverse']['throbber'] = Throbber(self, -1,
images, #size=(36, 36),
frameDelay = 0.1,
reverse = True)
self.throbbers['autoreverse']['throbber'].sequence.append(0)
self.throbbers['label']['throbber'] = Throbber(self, -1,
images, #size=(36, 36),
frameDelay = 0.1,
label = 'Label')
self.throbbers['label']['throbber'].SetFont(wxFont(pointSize = 10,
family = wxDEFAULT,
style = wxNORMAL,
weight = wxBOLD))
self.throbbers['overlay']['throbber'] = Throbber(self, -1,
images, #size=(36, 36),
frameDelay = 0.1,
overlay = throbImages.catalog['logo'].getBitmap())
self.throbbers['overlay+text']['throbber'] = Throbber(self, -1,
images, #size=(36, 36),
frameDelay = 0.1,
overlay = throbImages.catalog['logo'].getBitmap(),
label = "Python!")
self.throbbers['overlay+text']['throbber'].SetFont(wxFont(pointSize = 8,
family = wxDEFAULT,
style = wxNORMAL,
weight = wxBOLD))
box = wxBoxSizer(wxVERTICAL)
sizer = RowColSizer()
box.Add(sizer, 1, wxEXPAND|wxALL, 5)
sizer.AddGrowableCol(1)
row = 2
# use a list so we can keep our order
for t in ['plain', 'reverse', 'autoreverse', 'label', 'overlay', 'overlay+text']:
sizer.Add(self.throbbers[t]['throbber'], row = row, col = 0, flag = wxALIGN_CENTER|wxALL, border=2)
sizer.Add(wxStaticText(self, -1, self.throbbers[t]['text']), row = row, col = 1,
flag = wxALIGN_CENTER_VERTICAL | wxALIGN_LEFT)
row += 1
# start and stop buttons
startButton = wxButton(self, -1, "Start")
EVT_BUTTON(self, startButton.GetId(), self.OnStartAnimation)
stopButton = wxButton(self, -1, "Stop")
EVT_BUTTON(self, stopButton.GetId(), self.OnStopAnimation)
buttonBox = wxBoxSizer(wxHORIZONTAL)
buttonBox.AddMany([
(startButton, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5),
(stopButton, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5),
])
sizer.Add(buttonBox,
row = len(self.throbbers) + 3,
col = 0,
colspan = 3,
flag = wxALIGN_CENTER)
self.SetSizer(box)
self.SetAutoLayout(True)
self.Layout()
sizer.SetSizeHints(self)
sizer.Fit(self)
for t in self.throbbers.keys():
self.throbbers[t]['throbber'].Start()
EVT_WINDOW_DESTROY(self, self.OnDestroy)
def OnDestroy(self, event):
self.log.write("got destroy event")
event.Skip()
def OnStartAnimation(self, event):
for t in self.throbbers.keys():
self.throbbers[t]['throbber'].Start()
def OnStopAnimation(self, event):
for t in self.throbbers.keys():
self.throbbers[t]['throbber'].Rest()
def ShutdownDemo(self):
for t in self.throbbers.keys():
self.throbbers[t]['throbber'].Rest()
#----------------------------------------------------------------------
def runTest(frame, nb, log):
if wxPlatform == "__WXMAC__":
wxMessageBox("This demo currently fails on the Mac.",
"Sorry")
return
else:
win = TestPanel(nb, log)
return win
#----------------------------------------------------------------------
overview = """<html><body>
<h4><center>Throbber</center></h4>
<p>%s</p>
</body></html>
""" % docString
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -30,12 +30,12 @@ class TestPanel(wxPanel):
def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1)
self.SetAutoLayout(true)
self.SetAutoLayout(True)
outsideSizer = wxBoxSizer(wxVERTICAL)
msg = "Drag-And-Drop of URLs"
text = wxStaticText(self, -1, "", style=wxALIGN_CENTRE)
text.SetFont(wxFont(24, wxSWISS, wxNORMAL, wxBOLD, false))
text.SetFont(wxFont(24, wxSWISS, wxNORMAL, wxBOLD, False))
text.SetLabel(msg)
w,h = text.GetTextExtent(msg)
text.SetSize(wxSize(w,h+1))
@@ -44,7 +44,7 @@ class TestPanel(wxPanel):
outsideSizer.Add(wxStaticLine(self, -1), 0, wxEXPAND)
outsideSizer.Add(20,20)
self.SetFont(wxFont(10, wxSWISS, wxNORMAL, wxBOLD, false))
self.SetFont(wxFont(10, wxSWISS, wxNORMAL, wxBOLD, False))
inSizer = wxFlexGridSizer(2, 2, 5, 5)
inSizer.AddGrowableCol(0)
@@ -121,3 +121,12 @@ def runTest(frame, nb, log):
overview = """\
"""
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -56,7 +56,7 @@ class TestPanel(wxPanel):
else:
f = self.GetFont()
font = wxFont(14, f.GetFamily(), f.GetStyle(), wxBOLD, false,
font = wxFont(14, f.GetFamily(), f.GetStyle(), wxBOLD, False,
f.GetFaceName(), f.GetEncoding())
self.AddLine(box)
@@ -79,7 +79,7 @@ class TestPanel(wxPanel):
border = wxBoxSizer(wxVERTICAL)
border.Add(box, 1, wxEXPAND|wxALL, 10)
self.SetAutoLayout(true)
self.SetAutoLayout(True)
self.SetSizer(border)
@@ -139,3 +139,12 @@ and then pass the unicode to the wxPython method.
</body></html>
"""
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -1,5 +1,5 @@
import string, sys
import sys
py2 = sys.version[0] == '2'
@@ -11,9 +11,9 @@ try:
else:
from xml.parsers import pyexpat
parsermodule = pyexpat
haveXML = true
haveXML = True
except ImportError:
haveXML = false
haveXML = False
#----------------------------------------------------------------------
@@ -76,7 +76,7 @@ else:
self.nodeStack = self.nodeStack[:-1]
def CharacterData(self, data ):
if string.strip(data):
if data.strip():
if py2:
data = data.encode()
self.AppendItem(self.nodeStack[-1], data)
@@ -110,3 +110,11 @@ else:
overview = """\
"""
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 545 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 990 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 630 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

View File

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

Before

Width:  |  Height:  |  Size: 4.7 KiB

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 246 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 453 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 246 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 30 KiB

Some files were not shown because too many files have changed in this diff Show More