Merge pull request #124 from RobinD42/wip-demo

WIP: Various tweaks and fixes for issues discovered in the demo
This commit is contained in:
Robin Dunn
2016-08-10 19:58:25 -07:00
committed by GitHub
74 changed files with 447 additions and 2495 deletions

View File

@@ -203,5 +203,11 @@ Other Dev Stuff
self-contained instead of some relying on files generated by others. This
won't work if we want to run tests in parallel.
* Port these modules from gizmos in wxCode to a pure-python wx.lib implementation?
* DynamicSashWindow
* LEDNumberCtrl
* SplitTree ??
* TreeListCtrl ?? (We have a treelist ctrl in dataview now)
* The Masked controls modules and demos need some help with Py3 compatibility.

View File

@@ -416,7 +416,7 @@ class PrintCalend:
printout2 = SetPrintout(self)
self.preview = wx.PrintPreview(printout, printout2, self.printData)
if not self.preview.Ok():
if not self.preview.IsOk():
wx.MessageBox("There was a problem printing!", "Printing", wx.OK)
return

View File

@@ -2,7 +2,7 @@
import wx
import wx.adv
from wx.adv import CalendarCtrl
from wx.adv import CalendarCtrl, GenericCalendarCtrl, CalendarDateAttr
#----------------------------------------------------------------------
@@ -28,13 +28,13 @@ class TestPanel(wx.Panel):
txt = wx.StaticText(self, -1, description)
txt.Wrap(300)
# cal = self.cal = GenericCalendarCtrl(self, -1, wx.DateTime().Today(),
# style = wx.adv.CAL_SHOW_HOLIDAYS
# | wx.adv.CAL_SUNDAY_FIRST
# | wx.adv.CAL_SEQUENTIAL_MONTH_SELECTION
# )
cal = GenericCalendarCtrl(self, -1, wx.DateTime().Today(),
style = wx.adv.CAL_SHOW_HOLIDAYS
| wx.adv.CAL_SUNDAY_FIRST
| wx.adv.CAL_SEQUENTIAL_MONTH_SELECTION
)
# cal2 = wxcal.GenericCalendarCtrl(self, -1, wx.DateTime().Today())
cal2 = GenericCalendarCtrl(self, -1, wx.DateTime().Today())
# Track a few holidays
@@ -43,9 +43,9 @@ class TestPanel(wx.Panel):
# bind some event handlers to each calendar
for c in [native]:#, cal, cal2
for c in [native, cal, cal2]:
c.Bind(wx.adv.EVT_CALENDAR, self.OnCalSelected)
## c.Bind(wx.adv.EVT_CALENDAR_MONTH, self.OnChangeMonth)
c.Bind(wx.adv.EVT_CALENDAR_MONTH, self.OnChangeMonth)
c.Bind(wx.adv.EVT_CALENDAR_SEL_CHANGED, self.OnCalSelChanged)
c.Bind(wx.adv.EVT_CALENDAR_WEEKDAY_CLICKED, self.OnCalWeekdayClicked)
@@ -53,15 +53,17 @@ class TestPanel(wx.Panel):
fgs = wx.FlexGridSizer(cols=2, hgap=50, vgap=50)
fgs.Add(native)
fgs.Add(txt)
# fgs.Add(cal)
# fgs.Add(cal2)
fgs.Add(cal)
fgs.Add(cal2)
box = wx.BoxSizer()
box.Add(fgs, 1, wx.EXPAND|wx.ALL, 25)
self.SetSizer(box)
def OnCalSelected(self, evt):
self.log.write('OnCalSelected: %s\n' % evt.GetDate())
self.log.write('OnCalSelected: %s\n' % evt.Date)
if evt.Date.month == wx.DateTime.Aug and evt.Date.day == 14:
self.log.write("HAPPY BIRTHDAY!")
def OnCalWeekdayClicked(self, evt):
self.log.write('OnCalWeekdayClicked: %s\n' % evt.GetWeekDay())
@@ -86,7 +88,7 @@ class TestPanel(wx.Panel):
# August 14th is a special day, mark it with a blue square...
if cur_month == 8:
attr = wxcal.CalendarDateAttr(border=wx.adv.CAL_BORDER_SQUARE,
attr = CalendarDateAttr(border=wx.adv.CAL_BORDER_SQUARE,
colBorder="blue")
cal.SetAttr(14, attr)
else:

View File

@@ -36,7 +36,7 @@ class TestColourSelect(wx.Panel):
"and wxColourDialog Classes. Click Button to get Colour Values")
mainSizer.Add(t, 0, wx.ALL, 3)
b = wx.Button(self, -1, "Show All Colours")
b = wx.Button(self, -1, "Log All Current Colours")
self.Bind(wx.EVT_BUTTON, self.OnShowAll, id=b.GetId())
mainSizer.Add(b, 0, wx.ALL, 3)
@@ -55,7 +55,7 @@ class TestColourSelect(wx.Panel):
# build several examples of buttons with different colours and sizes
buttonData = [
("Default Size", (255, 255, 0), wx.DefaultSize, ""),
("Another Size", (255, 0, 255), (60, 20), ""),
("Another Size", (255, 0, 255), (60, 22), ""),
("Another Colour", (0, 255, 0), wx.DefaultSize, ""),
("Larger Size", (0, 0, 255), (60, 60), ""),
("With a Label", (127, 0, 255), wx.DefaultSize, "Colour..."),

View File

@@ -112,7 +112,7 @@ class TestPanel(wx.Panel):
self.log = log
wx.Panel.__init__(self, parent, -1)
comboCtrl = wx.ComboCtrl(self, wx.ID_ANY, "")
comboCtrl = wx.ComboCtrl(self, wx.ID_ANY, "", (20,20))
popupCtrl = ListCtrlComboPopup()

View File

@@ -2,6 +2,7 @@
import wx
import wx.adv
from textwrap import dedent
#----------------------------------------------------------------------
@@ -10,14 +11,14 @@ class TestPanel(wx.Panel):
self.log = log
wx.Panel.__init__(self, parent, -1)
cmd = wx.adv.CommandLinkButton(self, -1,
"wx.CommandLinkButton",
"""\
This type of button includes both a main label and a 'note' that is meant to
contain a description of what the button does or what it is used for. On
Windows 7 it is a new native widget type, on the other platforms it is
implemented generically.""",
pos=(25,25))
cmd = wx.adv.CommandLinkButton(self, -1, "wx.CommandLinkButton",
dedent("""\
This type of button includes both a main label and a 'note' that
is meant to contain a description of what the button does or
what is used for. On Windows 7 it is a new native widget type,
on the other platforms it is implemented generically.
"""),
pos=(25,25), size=(500,-1))
#----------------------------------------------------------------------

View File

@@ -63,7 +63,6 @@ class TestPanel(wx.Panel):
sizer.Add(text)
text.Bind(wx.EVT_HELP, self.OnCtxHelp2, text)
border = wx.BoxSizer(wx.VERTICAL)
border.Add(sizer, 0, wx.ALL, 25)
@@ -74,7 +73,8 @@ class TestPanel(wx.Panel):
# On the second text control above, we intercept the help event. This is where
# we process it. Anything could happen here. In this case we're just printing
# some stuff about it, then passing it on, at which point we see the help tip.
# some stuff about it, then passing it on with Skip(), at which point we
# see the help tip.
def OnCtxHelp(self, evt):
self.log.write("OnCtxHelp: %s" % evt)
evt.Skip()

View File

@@ -94,7 +94,7 @@ class TestPanel(wx.Panel):
image.SetOption(wx.IMAGE_OPTION_CUR_HOTSPOT_Y, 1)
# make the image into a cursor
cursor = wx.CursorFromImage(image)
cursor = wx.Cursor(image)
else:
# create one of the stock (built-in) cursors

View File

@@ -25,20 +25,19 @@ class FrameSimpleDelayedBase(wx.Frame):
def __init__(self, *args, **kwds):
wx.Frame.__init__(self, *args, **kwds)
pnl = wx.Panel(self)
self.checkboxUseDelayed = wx.CheckBox(pnl, -1, "Using delayedresult")
self.textUseDelayed = wx.StaticText(pnl, -1, "NOT using delayedresult")
self.buttonGet = wx.Button(pnl, -1, "Get")
self.buttonAbort = wx.Button(pnl, -1, "Abort")
self.slider = wx.Slider(pnl, -1, 0, 0, 10, size=(100,-1),
style=wx.SL_HORIZONTAL|wx.SL_AUTOTICKS)
self.textCtrlResult = wx.TextCtrl(pnl, -1, "", style=wx.TE_READONLY)
self.checkboxUseDelayed.SetValue(1)
self.checkboxUseDelayed.Enable(False)
self.buttonAbort.Enable(False)
vsizer = wx.BoxSizer(wx.VERTICAL)
vsizer = wx.BoxSizer(wx.VERTICAL)
hsizer = wx.BoxSizer(wx.HORIZONTAL)
vsizer.Add(self.checkboxUseDelayed, 0, wx.ALL, 10)
vsizer.Add(self.textUseDelayed, 0, wx.ALL, 10)
hsizer.Add(self.buttonGet, 0, wx.ALL, 5)
hsizer.Add(self.buttonAbort, 0, wx.ALL, 5)
hsizer.Add(self.slider, 0, wx.ALL, 5)
@@ -52,7 +51,6 @@ class FrameSimpleDelayedBase(wx.Frame):
class FrameSimpleDelayed(FrameSimpleDelayedBase):
"""This demos simplistic use of delayedresult module."""
@@ -61,14 +59,19 @@ class FrameSimpleDelayed(FrameSimpleDelayedBase):
self.jobID = 0
self.abortEvent = delayedresult.AbortEvent()
self.Bind(wx.EVT_CLOSE, self.handleClose)
self.textUseDelayed.SetLabel("USING delayedresult")
def setLog(self, log):
self.log = log
def handleClose(self, event):
"""Only needed because in demo, closing the window does not kill the
"""
Only needed because in demo, closing the window does not kill the
app, so worker thread continues and sends result to dead frame; normally
your app would exit so this would not happen."""
your app would exit so this would not happen.
"""
if self.buttonAbort.IsEnabled():
self.log( "Exiting: Aborting job %s" % self.jobID )
self.abortEvent.set()
@@ -88,9 +91,11 @@ class FrameSimpleDelayed(FrameSimpleDelayedBase):
def _resultProducer(self, jobID, abortEvent):
"""Pretend to be a complex worker function or something that takes
"""
Pretend to be a complex worker function or something that takes
long time to run due to network access etc. GUI will freeze if this
method is not called in separate thread."""
method is not called in separate thread.
"""
import time
count = 0
while not abortEvent() and count < 50:
@@ -112,7 +117,7 @@ class FrameSimpleDelayed(FrameSimpleDelayedBase):
assert jobID == self.jobID
try:
result = delayedResult.get()
except Exception, exc:
except Exception as exc:
self.log( "Result for job %s raised exception: %s" % (jobID, exc) )
return
@@ -125,6 +130,7 @@ class FrameSimpleDelayed(FrameSimpleDelayedBase):
self.buttonAbort.Enable(False)
class FrameSimpleDirect(FrameSimpleDelayedBase):
"""This does not use delayedresult so the GUI will freeze while
the GET is taking place."""
@@ -132,15 +138,17 @@ class FrameSimpleDirect(FrameSimpleDelayedBase):
def __init__(self, *args, **kwargs):
self.jobID = 1
FrameSimpleDelayedBase.__init__(self, *args, **kwargs)
self.checkboxUseDelayed.SetValue(False)
def setLog(self, log):
self.log = log
def handleGet(self, event):
"""Use delayedresult, this will compute result in separate
thread, and will affect GUI response because a thread is not
used."""
"""
Not using delayedresult, this will compute result in the same thread,
and will affect GUI response because a thread is not used.
"""
self.buttonGet.Enable(False)
self.buttonAbort.Enable(True)
@@ -148,18 +156,23 @@ class FrameSimpleDirect(FrameSimpleDelayedBase):
result = self._resultProducer(self.jobID)
self._resultConsumer( result )
def _resultProducer(self, jobID):
"""Pretend to be a complex worker function or something that takes
"""
Pretend to be a complex worker function or something that takes
long time to run due to network access etc. GUI will freeze if this
method is not called in separate thread."""
method is not called in separate thread.
"""
import time
time.sleep(5)
return jobID
def handleAbort(self, event):
"""can never be called"""
pass
def _resultConsumer(self, result):
# output result
self.log( "Got result for job %s: %s" % (self.jobID, result) )

View File

@@ -15,8 +15,6 @@ class ClipTextPanel(wx.Panel):
wx.Panel.__init__(self, parent, -1)
self.log = log
#self.SetFont(wx.Font(10, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, False))
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(
wx.StaticText(
@@ -42,7 +40,6 @@ class ClipTextPanel(wx.Panel):
self.Bind(wx.EVT_BUTTON, self.OnPaste, id=ID_PasteBtn)
self.Bind(wx.EVT_BUTTON, self.OnCopyBitmap, id=ID_BitmapBtn)
self.SetAutoLayout(True)
self.SetSizer(sizer)
@@ -71,6 +68,7 @@ class ClipTextPanel(wx.Panel):
"Error"
)
def OnCopyBitmap(self, evt):
dlg = wx.FileDialog(self, "Choose a bitmap to copy", wildcard="*.bmp")
@@ -120,7 +118,7 @@ class OtherDropTarget(wx.DropTarget):
def OnData(self, x, y, d):
self.log.WriteText("OnData: %d, %d, %d\n" % (x, y, d))
self.GetData()
self.log.WriteText("%s\n" % self.do.GetFilenames())
self.log.SetLabel("%s\n" % self.do.GetFilenames())
return d
@@ -131,12 +129,10 @@ class MyFileDropTarget(wx.FileDropTarget):
self.log = log
def OnDropFiles(self, x, y, filenames):
self.window.SetInsertionPointEnd()
self.window.WriteText("\n%d file(s) dropped at %d,%d:\n" %
(len(filenames), x, y))
for file in filenames:
self.window.WriteText(file + '\n')
txt = "\n%d file(s) dropped at %d,%d:\n" % (len(filenames), x, y)
txt += '\n'.join(filenames)
self.window.SetLabel(txt)
return True
class MyTextDropTarget(wx.TextDropTarget):
@@ -146,7 +142,8 @@ class MyTextDropTarget(wx.TextDropTarget):
self.log = log
def OnDropText(self, x, y, text):
self.window.WriteText("(%d, %d)\n%s\n" % (x, y, text))
self.window.SetLabel("(%d, %d)\n%s\n" % (x, y, text))
return True
def OnDragOver(self, x, y, d):
return wx.DragCopy
@@ -164,38 +161,32 @@ class FileDropPanel(wx.Panel):
0, wx.EXPAND|wx.ALL, 2
)
self.text = wx.TextCtrl(
self, -1, "",
style = wx.TE_MULTILINE|wx.HSCROLL|wx.TE_READONLY
)
self.text = wx.StaticText(self, -1, "", style=wx.ST_NO_AUTORESIZE|wx.BORDER_SIMPLE)
self.text.SetWindowVariant(wx.WINDOW_VARIANT_SMALL)
dt = MyFileDropTarget(self, log)
self.text.SetDropTarget(dt)
sizer.Add(self.text, 1, wx.EXPAND)
sizer.Add(self.text, 1, wx.EXPAND|wx.ALL, 5)
sizer.Add(
wx.StaticText(self, -1, " \nDrag some text here:"),
0, wx.EXPAND|wx.ALL, 2
)
self.text2 = wx.TextCtrl(
self, -1, "",
style = wx.TE_MULTILINE|wx.HSCROLL|wx.TE_READONLY
)
self.text2 = wx.StaticText(self, -1, "", style=wx.ST_NO_AUTORESIZE|wx.BORDER_SIMPLE)
self.text2.SetWindowVariant(wx.WINDOW_VARIANT_SMALL)
dt = MyTextDropTarget(self.text2, log)
self.text2.SetDropTarget(dt)
sizer.Add(self.text2, 1, wx.EXPAND)
sizer.Add(self.text2, 1, wx.EXPAND|wx.ALL, 5)
self.SetAutoLayout(True)
self.SetSizer(sizer)
def WriteText(self, text):
self.text.WriteText(text)
def SetLabel(self, text):
self.text.SetLabel(text)
def SetInsertionPointEnd(self):
self.text.SetInsertionPointEnd()
#----------------------------------------------------------------------

View File

@@ -13,7 +13,7 @@ class TestPanel(wx.Panel):
self.elb = wx.adv.EditableListBox(
self, -1, "List of Stuff", (50,50), (250, 250),
style=wx.adv.EL_DEFAULT_STYLE |
wx.adv.EL_NO_REORDER |
#wx.adv.EL_NO_REORDER |
wx.adv.EL_ALLOW_NEW |
wx.adv.EL_ALLOW_EDIT |
wx.adv.EL_ALLOW_DELETE)

View File

@@ -2,12 +2,13 @@
#---------------------------------------------------------------------------
# Name: EventManager.py
# Purpose: A module to demonstrate wxPython.lib.evtmgr.EventManager.
# Purpose: A module to demonstrate wx.lib.evtmgr.EventManager.
#
# Author: Robb Shecter (robb@acm.org)
#
# Created: 16-December-2002
# Copyright: (c) 2002 by Robb Shecter (robb@acm.org)
# Copyright: (c) 2002-2016 by Robb Shecter (robb@acm.org),
# Total Control Software
# Licence: wxWindows license
#---------------------------------------------------------------------------
@@ -136,7 +137,7 @@ class InnerTile(wx.Window):
FINAL_COLOR = wx.Colour( 20, 80,240)
OFF_COLOR = wx.Colour(185,190,185)
# Some pre-computation.
DELTAS = map(lambda a,b: b-a, START_COLOR.Get(), FINAL_COLOR.Get())
DELTAS = list(map(lambda a,b: b-a, START_COLOR.Get(), FINAL_COLOR.Get()))
START_COLOR_TUPLE = START_COLOR.Get()
"""
@@ -185,7 +186,8 @@ class InnerTile(wx.Window):
self.makeColorFromTuple(mouseEvent.GetPosition())
def makeColorFromTuple(self, (x, y)):
def makeColorFromTuple(self, xy):
x, y = xy
MAX = 180.0
scaled = min((x + y) * self.factor, MAX) # In range [0..MAX]
percent = scaled / MAX

View File

@@ -18,9 +18,7 @@ class FileCtrl(wx.FileCtrl):
pos=wx.DefaultPosition, size=wx.DefaultSize, name="filectrl", log=None):
wx.FileCtrl.__init__(self, parent, id, defaultDirectory, defaultFilename,
wildCard, style, pos, size, name)
self.BackgroundColour = 'pink'
self.log = log
self.Bind(wx.EVT_FILECTRL_FILEACTIVATED, self.OnFileActivated)
self.Bind(wx.EVT_FILECTRL_SELECTIONCHANGED, self.OnSelectionChanged)
@@ -49,8 +47,12 @@ class TestPanel(wx.Panel):
self.log = log
wx.Panel.__init__(self, parent)
fc = FileCtrl(self, pos=(15,15), log=log)
wx.StaticText(self, -1,
"This is a generic control with features like a file dialog",
pos=(10,10))
fc = FileCtrl(self, pos=(10,35), log=log)
fc.SetSize((500,350))
fc.BackgroundColour = 'sky blue'
#---------------------------------------------------------------------------

View File

@@ -6,12 +6,11 @@ import wx
#----------------------------------------------------------------------
text = """\
Right-click on the panel above the line to get a menu. This menu will
be managed by a FileHistory object and so the files you select will
automatically be added to the end of the menu and will be selectable
the next time the menu is viewed. The filename selected, either via the
Open menu item, or from the history, will be displayed in the log
window below.
Right-click on this panel to get a menu. This menu will be managed by a
FileHistory object and so the files you select will automatically be added to
the end of the menu and will be selectable the next time the menu is viewed.
The filename selected, either via the Open menu item, or from the history,
will be displayed in the log window below.
"""
#----------------------------------------------------------------------

View File

@@ -1,61 +0,0 @@
#!/usr/bin/env python
import wx
from wx.animate import GIFAnimationCtrl
from Main import opj
GIFNames = [
'bitmaps/AG00178_.gif',
'bitmaps/BD13656_.gif',
'bitmaps/AG00185_.gif',
'bitmaps/AG00039_.gif',
'bitmaps/AG00183_.gif',
'bitmaps/AG00028_.gif',
]
#----------------------------------------------------------------------
class TestPanel(wx.Panel):
def __init__(self, parent, log):
self.log = log
wx.Panel.__init__(self, parent, -1)
sizer = wx.FlexGridSizer(cols=3, hgap=5, vgap=5)
for name in GIFNames:
ani = GIFAnimationCtrl(self, -1, opj(name))
ani.GetPlayer().UseBackgroundColour(True)
ani.Play()
sizer.Add(ani, 0, wx.ALL, 10)
border = wx.BoxSizer()
border.Add(sizer, 1, wx.EXPAND|wx.ALL, 20)
self.SetSizer(border)
#----------------------------------------------------------------------
def runTest(frame, nb, log):
win = TestPanel(nb, log)
return win
#----------------------------------------------------------------------
overview = """<html><body>
<h2><center>wx.animate.GIFAnimationCtrl</center></h2>
wx.animate.GIFAnimationCtrl is like a wx.StaticBitmap but is able to
display an animation by extracing frames from a multi-images GIF file.
</body></html>
"""
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])

View File

@@ -12,11 +12,11 @@ class TestPanel(wx.Panel):
wx.StaticText(self, -1, "This example shows the wx.Gauge control.", (45, 15))
self.g1 = wx.Gauge(self, -1, 50, (110, 50), (250, 25))
self.g2 = wx.Gauge(self, -1, 75, (110, 95), (250, 25))
self.g3 = wx.Gauge(self, -1, 100, (110, 135), (25, 100), wx.GA_VERTICAL)
# self.g3.SetBezelFace(12)
# self.g3.SetShadowWidth(8)
self.g1 = wx.Gauge(self, -1, 50, (110, 50), (250, -1))
self.g2 = wx.Gauge(self, -1, 75, (110, 95), (250, -1))
if 'wxMac' not in wx.PlaformInfo:
self.g3 = wx.Gauge(self, -1, 100, (110, 135), (-1, 100), wx.GA_VERTICAL)
self.Bind(wx.EVT_TIMER, self.TimerHandler)
self.timer = wx.Timer(self)
@@ -33,7 +33,8 @@ class TestPanel(wx.Panel):
self.g1.SetValue(self.count)
self.g2.Pulse()
self.g3.Pulse()
if 'wxMac' not in wx.PlaformInfo:
self.g3.Pulse()
#----------------------------------------------------------------------

View File

@@ -32,6 +32,8 @@ class GridFileDropTarget(wx.FileDropTarget):
self.grid.AutoSizeColumn(col)
self.grid.Refresh()
return True
class FooTable(gridlib.GridTableBase):

View File

@@ -63,7 +63,7 @@ class CustomDataTable(gridlib.GridTableBase):
def GetValue(self, row, col):
id = self.identifiers[col]
return self.data[row][id]
return str(self.data[row][id])
def SetValue(self, row, col, value):
id = self.identifiers[col]

View File

@@ -53,21 +53,30 @@ class ItemsPickerDialog(wx.Dialog):
'Stuff:', 'Selected stuff:',ipStyle = style)
self.ip.Bind(EVT_IP_SELECTION_CHANGED, self.OnSelectionChange)
self.ip._source.SetMinSize((-1,150))
self.ip.bAdd.SetBitmap(_bp_btn2.GetBitmap(), dir=wx.RIGHT)
self.ip.bAdd.SetLabel('Add')
self.ip.bRemove.SetBitmap(_bp_btn1.GetBitmap(), dir=wx.LEFT)
self.ip.bRemove.SetLabel('Remove')
# Customize the buttons for this example.
if 'wxMac' not in wx.PlatformInfo:
# NOTE: wx.Button on OSX does not modify the button size when adding a
# bitmap after the fact like this, and these bitmaps are a little too
# large and look funny in OSX, so we won't do this customization there.
self.ip.bAdd.SetBitmap(_bp_btn2.GetBitmap(), dir=wx.RIGHT)
self.ip.bAdd.SetLabel('Add')
self.ip.bRemove.SetBitmap(_bp_btn1.GetBitmap(), dir=wx.LEFT)
self.ip.bRemove.SetLabel('Remove')
sizer.Add(self.ip, 0, wx.ALL, 10)
self.SetSizer(sizer)
self.itemCount = 3
self.Fit()
def OnAdd(self,e):
items = self.ip.GetItems()
self.itemCount += 1
newItem = "item%d" % self.itemCount
self.ip.SetItems(items + [newItem])
def OnSelectionChange(self, e):
self.log.write("EVT_IP_SELECTION_CHANGED %s\n" % \
",".join(e.GetItems()))

View File

@@ -888,7 +888,7 @@ class JoystickDemoPanel(wx.Panel):
# Calibrate our controls
wx.CallAfter(self.Calibrate)
wx.CallAfter(self.OnJoystick)
except NotImplementedError, v:
except NotImplementedError as v:
wx.MessageBox(str(v), "Exception Message")
self.stick = None

View File

@@ -40,6 +40,7 @@ class TestListCtrl(wx.ListCtrl,
self.Populate()
listmix.TextEditMixin.__init__(self)
def Populate(self):
# for normal, simple columns, you can add them like this:
self.InsertColumn(0, "Column 1")
@@ -62,6 +63,7 @@ class TestListCtrl(wx.ListCtrl,
self.currentItem = 0
def SetStringItem(self, index, col, data):
if col in range(3):
wx.ListCtrl.SetItem(self, index, col, data)
@@ -100,6 +102,7 @@ class TestListCtrlPanel(wx.Panel):
style=wx.LC_REPORT
| wx.BORDER_NONE
| wx.LC_SORT_ASCENDING
| wx.LC_HRULES | wx.LC_VRULES
)
sizer.Add(self.list, 1, wx.EXPAND)

View File

@@ -76,7 +76,6 @@ class MyParentFrame(wx.MDIParentFrame):
if __name__ == '__main__':
class MyApp(wx.App):
def OnInit(self):
wx.InitAllImageHandlers()
frame = MyParentFrame()
frame.Show(True)
self.SetTopWindow(frame)

View File

@@ -140,7 +140,6 @@ class MyParentFrame(wx.MDIParentFrame):
if __name__ == '__main__':
class MyApp(wx.App):
def OnInit(self):
wx.InitAllImageHandlers()
frame = MyParentFrame()
frame.Show(True)
self.SetTopWindow(frame)

View File

@@ -36,21 +36,8 @@ class TestPanel(wx.Panel):
exe, spawn = self.GetPyExecutable()
spawn(os.P_NOWAIT, exe, exe, "MDISashDemo.py")
# TODO: This hack can be removed once we fix the way the Python
# app bundles are generated so that they are not bundling and
# pointing to an otherwise unused and non-GUI-friendly version of
# Python on OS X.
def GetPyExecutable(self):
if 'wxMac' in wx.PlatformInfo:
# sys.executable will be wrong if running the demo from
# an app bundle. But the bundle is always using a system
# framework so just hardcode the path to it.
if sys.version[:3] == "2.4":
return '/usr/local/bin/pythonw', os.spawnl
else:
return '/usr/bin/pythonw', os.spawnl
else:
return sys.executable, os.spawnl
return sys.executable, os.spawnl
#----------------------------------------------------------------------

View File

@@ -1,79 +0,0 @@
#!/usr/bin/env python
import os
import sys
import wx
import wx.lib.mvctree as tree
logger = None
def selchanging(evt):
logger.write("SelChanging!\n")
def selchanged(evt):
logger.write("SelChange!\n")
logger.write(str(evt.node))
def expanded(evt):
logger.write("Expanded\n")
def closed(evt):
logger.write("Closed!\n")
def key(evt):
logger.write("Key\n")
def add(evt):
logger.write("Add\n")
def delitem(evt):
logger.write("Delete\n")
def runTest(frame, nb, log):
#f = wx.Frame(frame, -1, "MVCTree", (0,0), (200,500))
global logger
logger = log
p = tree.MVCTree(nb, -1)
#f = wx.Frame(frame, -1, "MVCTree")
#p = tree.MVCTree(f, -1)
p.SetAssumeChildren(True)
p.SetModel(tree.LateFSTreeModel(os.path.normpath(os.getcwd() + os.sep +'..')))
#Uncomment this to enable live filename editing!
# p.AddEditor(FileEditor(p))
p.SetMultiSelect(True)
p.Bind(tree.EVT_MVCTREE_SEL_CHANGING, selchanging)
p.Bind(tree.EVT_MVCTREE_SEL_CHANGED, selchanged)
p.Bind(tree.EVT_MVCTREE_ITEM_EXPANDED, expanded)
p.Bind(tree.EVT_MVCTREE_ITEM_COLLAPSED, closed)
p.Bind(tree.EVT_MVCTREE_ADD_ITEM, add)
p.Bind(tree.EVT_MVCTREE_DELETE_ITEM, delitem)
p.Bind(tree.EVT_MVCTREE_KEY_DOWN, key)
return p
#frame.otherWin = f
#f.Show(True)
#return None
overview = """\
MVCTree is a control which handles hierarchical data. It is
constructed in model-view-controller architecture, so the display of
that data, and the content of the data can be changed greatly without
affecting the other parts.
Multiple selections are possible by holding down the Ctrl key.
This demo shows the wxPython directory structure. The interesting part
is that the tree model is late-bound to the filesystem, so the
filenames are not retrieved until the directory is expanded. In
mvctree.py are models for generic data, and both the early and
late-bound filesystem models.
There is also support for editing, though it's not enabled in this
demo, to avoid accidentally renaming files!
"""
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])

View File

@@ -23,11 +23,10 @@ logicList = [
('wx.XOR', wx.XOR),
]
if 'mac-cg' in wx.PlatformInfo:
if 'wxMac' in wx.PlatformInfo:
# that's all, folks!
logicList = [
('wx.COPY', wx.COPY),
('wx.INVERT', wx.INVERT),
('wx.XOR', wx.XOR),
]

View File

@@ -1,5 +1,3 @@
#!/usr/bin/env python
#----------------------------------------------------------------------
# Name: wxMimeTypesManager
# Purpose: Demonstrate use of wx.MimeTypesManager, wx.FileType
@@ -299,21 +297,21 @@ class MimeTypesDemoPanel(wx.Panel):
mime = ft.GetMimeType() or ""
#------- OPEN command
cmd = ft.GetOpenCommand(filename, mime)
params = wx.FileType.MessageParameters(filename, mime)
cmd = ft.GetOpenCommand(params)
self.opencommand.SetValue(convert(cmd))
#------- PRINT command
cmd = ft.GetPrintCommand(filename, mime)
cmd = ft.GetPrintCommand(params)
self.printcommand.SetValue(convert(cmd))
#------- All commands
all = ft.GetAllCommands(filename, mime)
verbs, commands = ft.GetAllCommands(params)
if all is None:
if not verbs and not commands:
self.allcommands.SetValue("")
else:
verbs, commands = all
text = pprint.pformat(map(None, verbs, commands))
text = pprint.pformat(list(zip(verbs, commands)))
self.allcommands.SetValue(text)

View File

@@ -47,11 +47,11 @@ class TestWindow(stc.StyledTextCtrl):
wx.Font(fSize, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)
)
## if self.doc:
## self.SetDocPointer(self.doc)
## else:
self.SetText(sampleText)
TestWindow.doc = self.GetDocPointer()
if self.doc:
self.SetDocPointer(self.doc)
else:
self.SetText(sampleText)
TestWindow.doc = self.GetDocPointer()
def ShutDownDemo(self):

View File

@@ -1 +1 @@
#!/usr/bin/env python
#!/usr/bin/env python

View File

@@ -26,7 +26,8 @@ class TestPanel(wx.Panel):
self.endPos = None
self.overlay = wx.Overlay()
self.cropbitmap = wx.Bitmap('bitmaps/cropshot24x20.png', wx.BITMAP_TYPE_PNG)
self.cropbitmap = wx.Bitmap('bitmaps/cropshot24x20.png')
self.honeyBitmap = wx.Bitmap('bitmaps/honeycomb300.png')
self.wxPenStylesDict = OrderedDict([
('Solid' , wx.PENSTYLE_SOLID),
@@ -36,39 +37,47 @@ class TestPanel(wx.Panel):
('Dot Dash' , wx.PENSTYLE_DOT_DASH),
('User Dash' , wx.PENSTYLE_USER_DASH),
('Transparent' , wx.PENSTYLE_TRANSPARENT),
('Stipple' , wx.PENSTYLE_STIPPLE),
#('Stipple' , wx.PENSTYLE_STIPPLE),
('BDiagonal Hatch' , wx.PENSTYLE_BDIAGONAL_HATCH),
('CrossDiag Hatch' , wx.PENSTYLE_CROSSDIAG_HATCH),
('FDiagonal Hatch' , wx.PENSTYLE_FDIAGONAL_HATCH),
('Cross Hatch' , wx.PENSTYLE_CROSS_HATCH),
('Horizontal Hatch' , wx.PENSTYLE_HORIZONTAL_HATCH),
('Vertical Hatch' , wx.PENSTYLE_VERTICAL_HATCH),
('First Hatch' , wx.PENSTYLE_FIRST_HATCH),
('Last Hatch' , wx.PENSTYLE_LAST_HATCH),
])
list = []
for key, value in self.wxPenStylesDict.items():
list.append(key)
self.penstylesCombo = wx.ComboBox(self, -1, choices=list,
pos=(10, 5), size=(100, -1),
size=(150, -1),
style=wx.CB_READONLY)
self.penstylesCombo.SetSelection(0)
self.penstylesCombo.SetToolTip('Pen Style')
self.overlayPenWidth = wx.SpinCtrl(self, -1, value='',
pos=(120, 5),
size=(100, -1),
size=(75, -1),
style=wx.SP_ARROW_KEYS,
min=1, max=24, initial=1)
self.overlayPenWidth.SetToolTip('Pen Width')
self.overlayPenColor = wx.ColourPickerCtrl(self, -1, colour=wx.BLUE,
pos=(230, 5), size=(100, -1))
from wx.lib.colourselect import ColourSelect
self.overlayPenColor = ColourSelect(self, -1, colour=wx.BLUE)
self.overlayPenColor.SetToolTip('Pen Color')
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(self.penstylesCombo, 0, wx.ALL, 5)
sizer.Add(self.overlayPenWidth, 0, wx.ALL, 5)
sizer.Add(self.overlayPenColor, 0, wx.ALL, 5)
box = wx.BoxSizer(wx.VERTICAL)
box.Add(sizer, 0)
box.Add((1,1), 1)
self.SetSizer(box)
self.OnSize()
def OnLeftDown(self, event):
# Capture the mouse and save the starting posiiton for the rubber-band
self.CaptureMouse()
@@ -77,6 +86,7 @@ class TestPanel(wx.Panel):
self.SetFocus()
## print('OnLeftDown')
def OnMouseMove(self, event):
if event.Dragging() and event.LeftIsDown():
evtPos = event.GetPosition()
@@ -128,6 +138,7 @@ class TestPanel(wx.Panel):
del odc # Make sure the odc is destroyed before the dc is.
## print('OnMouseMove')
def OnLeftUp(self, event):
if self.HasCapture():
self.ReleaseMouse()
@@ -146,7 +157,11 @@ class TestPanel(wx.Panel):
self.overlay.Reset()
## print('OnLeftUp')
def OnSize(self, event=None):
if event:
event.Skip()
x, y = self.GetSize()
if x <= 0 or y <= 0:
return
@@ -158,8 +173,9 @@ class TestPanel(wx.Panel):
dc.SetBackground(self.background)
dc.Clear()
dc.DrawBitmap(wx.Bitmap('bitmaps/snakey_render.png'), 10, 35)
dc.DrawBitmap(wx.Bitmap('bitmaps/honeycomb300.png'), 100, 210)
dc.DrawBitmap(self.honeyBitmap, 40, 40)
dc.SetFont(wx.Font(wx.FontInfo(18)))
dc.DrawText('Drag the mouse on this window.', 325, 100)
del dc
self.Refresh()

View File

@@ -69,7 +69,7 @@ class TestPopup(wx.PopupWindow):
def OnRightUp(self, evt):
self.Show(False)
self.Destroy()
wx.CallAfter(self.Destroy)

View File

@@ -34,7 +34,7 @@ class MyPrintout(wx.Printout):
def HasPage(self, page):
self.log.WriteText("MyPrintout.HasPage: %d\n" % page)
if page <= 2:
if page <= 2: # we only have 2 pages in this document
return True
else:
return False
@@ -80,7 +80,6 @@ class MyPrintout(wx.Printout):
dc.SetDeviceOrigin(int(posX), int(posY))
#-------------------------------------------
self.canvas.DoDrawing(dc, True)
dc.DrawText("Page: %d" % page, marginX/2, maxY-marginY)

View File

@@ -87,7 +87,8 @@ class TestPanel(wx.Panel):
text = self.inp.GetValue()
self.inp.SetValue('')
self.log.write('OnSendText: "%s"\n' % text)
self.process.GetOutputStream().write(text + '\n')
text += '\n'
self.process.GetOutputStream().write(text.encode('utf-8'))
self.inp.SetFocus()

View File

@@ -1,64 +0,0 @@
#!/usr/bin/env python
#####################################################################\
# Note: This control is deprecated because wx.TextCtrl now supports |
# the wx.TE_RIGHT style flag, which makes this control completely |
# superfluous. |
#####################################################################/
import wx
import wx.lib.rightalign as right
#----------------------------------------------------------------------
class TestPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, -1)
fgs = wx.FlexGridSizer(cols=2, vgap=5, hgap=5)
txt = wx.StaticText(
self, -1,
"These text controls will align their contents to\n"
"the right (on wxMSW) when they don't have focus.",
style=wx.ALIGN_RIGHT
)
fgs.Add(txt)
fgs.Add(right.RightTextCtrl(self, -1, "", size=(75, -1)))
fgs.Add((10,10))
fgs.Add(right.RightTextCtrl(self, -1, "123.45", size=(75, -1)))
fgs.Add((10,10))
fgs.Add(right.RightTextCtrl(self, -1, "234.56", size=(75, -1)))
fgs.Add((10,10))
fgs.Add(right.RightTextCtrl(self, -1, "345.67", size=(75, -1)))
fgs.Add((10,10))
fgs.Add(right.RightTextCtrl(self, -1, "456.78", size=(75, -1)))
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(fgs, 0, wx.ALL, 25)
self.SetSizer(sizer)
self.SetAutoLayout(True)
#----------------------------------------------------------------------
def runTest(frame, nb, log):
win = TestPanel(nb)
return win
#----------------------------------------------------------------------
overview = right.__doc__
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])

View File

@@ -1,93 +0,0 @@
#!/usr/bin/env python
import wx
import wx.lib.rcsizer as rcs
#----------------------------------------------------------------------
class TestPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, -1)
sizer = rcs.RowColSizer()
text = "This sizer lays out it's items by row and column "\
"that are specified explicitly when the item is \n"\
"added to the sizer. Grid cells with nothing in "\
"them are supported and column- or row-spanning is \n"\
"handled as well. Growable rows and columns are "\
"specified just like the wxFlexGridSizer."
sizer.Add(wx.StaticText(self, -1, text), row=1, col=1, colspan=5)
sizer.Add(wx.TextCtrl(self, -1, "(3,1)"), flag=wx.EXPAND, row=3, col=1)
sizer.Add(wx.TextCtrl(self, -1, "(3,2)"), row=3, col=2)
sizer.Add(wx.TextCtrl(self, -1, "(3,3)"), row=3, col=3)
sizer.Add(wx.TextCtrl(self, -1, "(3,4)"), row=3, col=4)
sizer.Add(
wx.TextCtrl(self, -1, "(4,2) span:(2,2)"),
flag=wx.EXPAND, row=4, col=2, rowspan=2, colspan=2
)
sizer.Add(wx.TextCtrl(self, -1, "(6,4)"), row=6, col=4)
sizer.Add(wx.TextCtrl(self, -1, "(7,2)"), row=7, col=2)
sizer.Add(wx.TextCtrl(self, -1, "(8,3)"), row=8, col=3)
sizer.Add(
wx.TextCtrl(self, -1, "(10,1) colspan: 4"),
flag=wx.EXPAND, pos=(10,1), colspan=4
)
sizer.Add(
wx.TextCtrl(self, -1, "(3,5) rowspan: 8, growable col", style=wx.TE_MULTILINE),
flag=wx.EXPAND, pos=(3,5), size=(8,1)
)
box = wx.BoxSizer(wx.VERTICAL)
box.Add(wx.Button(self, -1, "A vertical box"), flag=wx.EXPAND)
box.Add(wx.Button(self, -1, "sizer put in the"), flag=wx.EXPAND)
box.Add(wx.Button(self, -1, "RowColSizer at (12,1)"), flag=wx.EXPAND)
sizer.Add(box, pos=(12,1))
sizer.Add(
wx.TextCtrl(self, -1, "(12,2) align bottom"),
flag=wx.ALIGN_BOTTOM, pos=(12,2)
)
sizer.Add(
wx.TextCtrl(self, -1, "(12,3) align center"),
flag=wx.ALIGN_CENTER_VERTICAL, pos=(12,3)
)
sizer.Add(wx.TextCtrl(self, -1, "(12,4)"),pos=(12,4))
sizer.Add(
wx.TextCtrl(self, -1, "(12,5) full border"),
flag=wx.EXPAND|wx.ALL, border=15, pos=(12,5)
)
sizer.AddGrowableCol(5)
sizer.AddGrowableRow(9)
sizer.AddSpacer(10,10, pos=(1,6))
sizer.AddSpacer(10,10, pos=(13,1))
self.SetSizer(sizer)
self.SetAutoLayout(True)
#----------------------------------------------------------------------
def runTest(frame, nb, log):
win = TestPanel(nb)
return win
#----------------------------------------------------------------------
overview = rcs.__doc__
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])

View File

@@ -149,7 +149,7 @@ class MyCanvas(wx.ScrolledWindow):
dc.SetPen(wx.Pen('MEDIUM FOREST GREEN', 4))
for line in self.lines:
for coords in line:
apply(dc.DrawLine, coords)
dc.DrawLine(*coords)
def SetXY(self, event):

View File

@@ -551,37 +551,35 @@ class TestSelectionPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.list = wx.ListBox(self, -1,
(-1, -1), (-1, -1),
[])
self.list.Fit()
self.list = wx.ListBox(self, size=(300,150))
self.Bind(wx.EVT_LISTBOX, self.OnSelect, self.list)
self.Bind(wx.EVT_LISTBOX_DCLICK, self.OnDClick, self.list)
btn = wx.Button(self, -1, "Try it!", (120, 10))
btn.Bind(wx.EVT_BUTTON, self.OnDClick)
self.text = wx.TextCtrl(self, -1, "",
(10, 115),
(200, 50),
wx.TE_MULTILINE | wx.TE_READONLY)
self.text = wx.TextCtrl(self, style = wx.TE_MULTILINE | wx.TE_READONLY)
for item in theTests:
self.list.Append(item[0])
self.list.SetSelection(0)
wx.CallAfter(self.list.EnsureVisible, 0)
hsizer = wx.BoxSizer(wx.HORIZONTAL)
hsizer.Add(self.list, 1, wx.ALL, 8)
hsizer.Add(btn, 0, wx.ALL, 8)
vsizer = wx.BoxSizer(wx.VERTICAL)
vsizer.Add(hsizer)
vsizer.Add(self.text, 1, wx.EXPAND | wx.ALL, 8)
self.SetSizerAndFit(vsizer)
self.SetSizer(vsizer)
def OnSelect(self, event):
pos = self.list.GetSelection()
self.text.SetValue(theTests[pos][2])
def OnDClick(self, event):
pos = self.list.GetSelection()
title = theTests[pos][0]

View File

@@ -10,15 +10,22 @@ class TestPanel(wx.Panel):
self.log = log
self.count = 0
wx.StaticText(self, -1, "This is a wx.Slider.", (45, 15))
label = wx.StaticText(self, -1, "This is a wx.Slider.")
slider = wx.Slider(
self, 100, 25, 1, 100, (30, 60), (250, -1),
wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_LABELS
self, 100, 25, 1, 100, size=(250, -1),
style=wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_LABELS
)
slider.SetTickFreq(5)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add((1,20))
sizer.Add(label, 0, wx.LEFT, 20)
sizer.Add((1,10))
sizer.Add(slider, 0, wx.LEFT, 20)
self.SetSizer(sizer)
#----------------------------------------------------------------------
@@ -35,10 +42,6 @@ def runTest(frame, nb, log):
overview = """\
A slider is a control with a handle which can be pulled back and forth to
change the value.
In Windows versions below Windows 95, a scrollbar is used to simulate the slider.
In Windows 95, the track bar control is used.
"""

View File

@@ -27,7 +27,7 @@ class TestPanel(wx.Panel):
self.log.write("before Play...\n")
sound.Play(wx.adv.SOUND_SYNC)
self.log.write("...after Play\n")
except NotImplementedError, v:
except NotImplementedError as v:
wx.MessageBox(str(v), "Exception Message")
@@ -45,7 +45,7 @@ class TestPanel(wx.Panel):
self.sound = sound # save a reference (This shoudln't be needed, but there seems to be a bug...)
# wx.YieldIfNeeded()
self.log.write("...after Play\n")
except NotImplementedError, v:
except NotImplementedError as v:
wx.MessageBox(str(v), "Exception Message")
@@ -62,7 +62,7 @@ class TestPanel(wx.Panel):
# another way to do it.
wx.adv.Sound.PlaySound(dlg.GetPath(), wx.adv.SOUND_SYNC)
except NotImplementedError, v:
except NotImplementedError as v:
wx.MessageBox(str(v), "Exception Message")
dlg.Destroy()

View File

@@ -32,7 +32,6 @@ class TestPanel(wx.Panel):
bmp = images.Robin.GetBitmap()
StaticBitmap(self, -1, bmp, (80, 150))
StaticText(self, -1, "Hey, if Ousterhout can do it, so can I.", (200, 175))
#----------------------------------------------------------------------

View File

@@ -1,15 +1,7 @@
#!/usr/bin/env python
# 11/21/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o wx.TheClipboard.Flush() generates a warning on program exit.
import wx
import wx.stc as stc
import images
#----------------------------------------------------------------------
debug = 1
@@ -171,43 +163,20 @@ def runTest(frame, nb, log):
p.SetAutoLayout(True)
#ed.SetBufferedDraw(False)
#ed.StyleClearAll()
#ed.SetScrollWidth(800)
#ed.SetWrapMode(True)
#ed.SetUseAntiAliasing(False)
#ed.SetViewEOL(True)
#ed.CmdKeyClear(stc.STC_KEY_BACK,
# stc.STC_SCMOD_CTRL)
#ed.CmdKeyAssign(stc.STC_KEY_BACK,
# stc.STC_SCMOD_CTRL,
# stc.STC_CMD_DELWORDLEFT)
ed.SetText(demoText)
# if wx.USE_UNICODE:
import codecs
decode = codecs.lookup("utf-8")[1]
ed.GotoPos(ed.GetLength())
ed.AddText("\n\nwx.StyledTextCtrl can also do Unicode:\n")
uniline = ed.GetCurrentLine()
unitext, l = decode('\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd - '
'\xd0\xbb\xd1\x83\xd1\x87\xd1\x88\xd0\xb8\xd0\xb9 '
'\xd1\x8f\xd0\xb7\xd1\x8b\xd0\xba \xd0\xbf\xd1\x80\xd0\xbe\xd0\xb3\xd1\x80\xd0\xb0\xd0\xbc\xd0\xbc\xd0\xb8\xd1\x80\xd0\xbe\xd0\xb2\xd0\xb0\xd0\xbd\xd0\xb8\xd1\x8f!\n\n')
unitext, l = decode(b'\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd - ' +
b'\xd0\xbb\xd1\x83\xd1\x87\xd1\x88\xd0\xb8\xd0\xb9 ' +
b'\xd1\x8f\xd0\xb7\xd1\x8b\xd0\xba \xd0\xbf\xd1\x80\xd0\xbe\xd0\xb3\xd1\x80\xd0\xb0\xd0\xbc\xd0\xbc\xd0\xb8\xd1\x80\xd0\xbe\xd0\xb2\xd0\xb0\xd0\xbd\xd0\xb8\xd1\x8f!\n\n')
ed.AddText('\tRussian: ')
ed.AddText(unitext)
ed.GotoPos(0)
#else:
# #ed.StyleSetFontEncoding(stc.STC_STYLE_DEFAULT, wx.FONTENCODING_KOI8)
# #text = u'\u041f\u0438\u0442\u043e\u043d - \u043b\u0443\u0447\u0448\u0438\u0439 \u044f\u0437\u044b\u043a \n\u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f!'
# #text = text.encode('koi8-r')
# #ed.StyleSetFontEncoding(stc.STC_STYLE_DEFAULT, wx.FONTENCODING_BIG5)
# #text = u'Python \u662f\u6700\u597d\u7684\u7de8\u7a0b\u8a9e\u8a00\uff01'
# #text = text.encode('big5')
# ed.GotoPos(ed.GetLength())
# ed.AddText('\n\n' + text)
ed.EmptyUndoBuffer()

View File

@@ -24,7 +24,7 @@ class TablePanel(wx.Panel):
box = wx.BoxSizer(wx.VERTICAL)
box.Add((20, 30))
keys = buttonDefs.keys()
keys = list(buttonDefs.keys())
keys.sort()
for k in keys:
@@ -38,8 +38,8 @@ class TablePanel(wx.Panel):
def OnButton(self, evt):
funct = buttonDefs[evt.GetId()][0]
code = 'self.' + funct + '()'
eval(code)
funct = getattr(self, funct)
funct()
def ReadData(self):
test_file = "./data/testtable.txt"

View File

@@ -1,11 +1,9 @@
#!/usr/bin/env python
import random
import time
from six.moves import _thread
import random
import time
import thread
import wx
import wx.lib.newevent
import wx
import wx.lib.newevent
#----------------------------------------------------------------------
@@ -23,7 +21,7 @@ class CalcBarThread:
def Start(self):
self.keepGoing = self.running = True
thread.start_new_thread(self.Run, ())
_thread.start_new_thread(self.Run, ())
def Stop(self):
self.keepGoing = False

View File

@@ -126,31 +126,31 @@ class VirtualTreeCtrl(DemoTreeMixin, wx.TreeCtrl):
pass
class VirtualTreeListCtrl(DemoTreeMixin, wx.adv.TreeListCtrl):
def __init__(self, *args, **kwargs):
kwargs['style'] = wx.TR_DEFAULT_STYLE | wx.TR_FULL_ROW_HIGHLIGHT
super(VirtualTreeListCtrl, self).__init__(*args, **kwargs)
self.AppendColumn('Column 0')
self.AppendColumn('Column 1')
for art in wx.ART_TIP, wx.ART_WARNING:
self.imageList.Add(wx.ArtProvider.GetBitmap(art, wx.ART_OTHER,
(16, 16)))
def OnGetItemText(self, indices, column=0):
# Return a different label depending on column.
return '%s, column %d'%\
(super(VirtualTreeListCtrl, self).OnGetItemText(indices), column)
def OnGetItemImage(self, indices, which, column=0):
# Also change the image of the other columns when the item has
# children.
if column == 0:
return super(VirtualTreeListCtrl, self).OnGetItemImage(indices,
which)
elif self.OnGetChildrenCount(indices):
return 4
else:
return 3
# class VirtualTreeListCtrl(DemoTreeMixin, wx.adv.TreeListCtrl):
# def __init__(self, *args, **kwargs):
# kwargs['style'] = wx.TR_DEFAULT_STYLE | wx.TR_FULL_ROW_HIGHLIGHT
# super(VirtualTreeListCtrl, self).__init__(*args, **kwargs)
# self.AppendColumn('Column 0')
# self.AppendColumn('Column 1')
# for art in wx.ART_TIP, wx.ART_WARNING:
# self.imageList.Add(wx.ArtProvider.GetBitmap(art, wx.ART_OTHER,
# (16, 16)))
#
# def OnGetItemText(self, indices, column=0):
# # Return a different label depending on column.
# return '%s, column %d'%\
# (super(VirtualTreeListCtrl, self).OnGetItemText(indices), column)
#
# def OnGetItemImage(self, indices, which, column=0):
# # Also change the image of the other columns when the item has
# # children.
# if column == 0:
# return super(VirtualTreeListCtrl, self).OnGetItemImage(indices,
# which)
# elif self.OnGetChildrenCount(indices):
# return 4
# else:
# return 3
class VirtualCustomTreeCtrl(DemoTreeMixin,
@@ -192,7 +192,7 @@ class TreeNotebook(wx.Notebook):
super(TreeNotebook, self).__init__(*args, **kwargs)
self.trees = []
for class_, title in [(VirtualTreeCtrl, 'TreeCtrl'),
(VirtualTreeListCtrl, 'TreeListCtrl'),
#(VirtualTreeListCtrl, 'TreeListCtrl'),
(VirtualCustomTreeCtrl, 'CustomTreeCtrl')]:
tree = class_(self, treemodel=treemodel, log=log)
self.trees.append(tree)

View File

@@ -1,109 +0,0 @@
#!/usr/bin/env python
import sys
import wx
from xml.parsers import expat
#----------------------------------------------------------------------
class XMLTree(wx.TreeCtrl):
def __init__(self, parent, ID):
wx.TreeCtrl.__init__(self, parent, ID)
self._root = self.AddRoot("Root")
self.nodeStack = [self._root]
# Trees need an image list to do DnD...
self.il = wx.ImageList(16,16)
self.SetImageList(self.il)
# event handlers for DnD
self.Bind(wx.EVT_TREE_BEGIN_DRAG, self.OnBeginDrag)
self.Bind(wx.EVT_TREE_END_DRAG, self.OnEndDrag)
def OnBeginDrag(self, event):
item = event.GetItem()
if item != self.GetRootItem():
self.draggingItem = item
event.Allow() # if DnD of this item is okay Allow it.
def IsDescendant(self, firstItem, secondItem):
"Recursive check if firstItem is a descendant of a secondItem."
if firstItem == self._root:
return False
parentItem = self.GetItemParent(firstItem)
if parentItem == secondItem:
return True
else:
return self.IsDescendant(parentItem, secondItem)
def OnEndDrag(self, evt):
itemSrc = self.draggingItem
itemDst = evt.GetItem()
self.draggingItem = None
if not itemDst.IsOk():
print("Can't drag to here...")
return
if self.IsDescendant(itemDst, itemSrc):
print("Can't move item to its descendant")
return
# For this simple example just take the text of the source item
# and append it to the destination item. In real life you would
# possibly want to copy subtrees...
text = self.GetItemText(itemSrc)
self.AppendItem(itemDst, text)
self.Delete(itemSrc)
# Define a handler for start element events
def StartElement(self, name, attrs ):
name = name.encode()
id = self.AppendItem(self.nodeStack[-1], name)
self.nodeStack.append(id)
def EndElement(self, name ):
self.nodeStack = self.nodeStack[:-1]
def CharacterData(self, data ):
if data.strip():
data = data.encode()
self.AppendItem(self.nodeStack[-1], data)
def LoadTree(self, filename):
# Create a parser
Parser = expat.ParserCreate()
# Tell the parser what the start element handler is
Parser.StartElementHandler = self.StartElement
Parser.EndElementHandler = self.EndElement
Parser.CharacterDataHandler = self.CharacterData
# Parse the XML File
ParserStatus = Parser.Parse(open(filename,'r').read(), 1)
def runTest(frame, nb, log):
win = XMLTree(nb, -1)
win.LoadTree("paper.xml")
return win
#----------------------------------------------------------------------
overview = """\
"""
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])

View File

@@ -18,8 +18,10 @@ class TestPanel(wx.Panel):
label = wx.StaticText(self, -1, "The lower panel was built from this XML:")
label.SetFont(wx.Font(12, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD))
resourceText = open(RESFILE).read()
text = wx.TextCtrl(self, -1, resourceText,
with open(RESFILE, 'rb') as f:
resourceBytes = f.read()
text = wx.TextCtrl(self, -1, resourceBytes,
style=wx.TE_READONLY|wx.TE_MULTILINE)
text.SetInsertionPoint(0)
@@ -33,13 +35,14 @@ class TestPanel(wx.Panel):
elif 1:
# or from a Virtual FileSystem:
wx.FileSystem.AddHandler(wx.MemoryFSHandler())
wx.MemoryFSHandler().AddFile("XRC_Resources/data_file", resourceText)
res = xrc.XmlResource("memory:XRC_Resources/data_file")
wx.MemoryFSHandler.AddFile("my_XRC_data", resourceBytes)
# notice the matching filename
res = xrc.XmlResource("memory:my_XRC_data")
else:
# or from a string, like this:
res = xrc.EmptyXmlResource()
res.LoadFromString(resourceText)
# or from a buffer compatible object, like this:
res = xrc.XmlResource()
res.LoadFromBuffer(resourceBytes)
# Now create a panel from the resource data

View File

@@ -5,7 +5,7 @@ import wx.xrc as xrc
#----------------------------------------------------------------------
resourceText = r'''<?xml version="1.0"?>
resourceText = br'''<?xml version="1.0"?>
<resource>
<!-- Notice that the class is NOT a standard wx class -->
@@ -48,8 +48,7 @@ class MyCustomPanel(wx.Panel):
# the different requirements are.
class PreMyCustomPanel(wx.Panel):
def __init__(self):
p = wx.PrePanel()
self.PostCreate(p)
wx.Panel.__init__(self)
def Create(self, parent, id, pos, size, style, name):
wx.Panel.Create(self, parent, id, pos, size, style, name)
@@ -84,12 +83,10 @@ class MyCustomPanelXmlHandler(xrc.XmlResourceHandler):
def DoCreateResource(self):
# NOTE: wxWindows can be created in either a single-phase or
# in a two-phase way. Single phase is what you normally do,
# and two-phase creates the instnace first, and then later
# and two-phase creates the instance first, and then later
# creates the actual window when the Create method is called.
# (In wxPython the first phase is done using the wxPre*
# function, for example, wxPreFrame, wxPrePanel, etc.)
#
# wxXmlResource supports either method, a premade instance can
# wxXmlResource supports either method, a pre-made instance can
# be created and populated by xrc using the appropriate
# LoadOn* method (such as LoadOnPanel) or xrc can create the
# instance too, using the Load* method. However this makes
@@ -98,7 +95,7 @@ class MyCustomPanelXmlHandler(xrc.XmlResourceHandler):
# instance, then you can make the handle much simpler. I'll
# show both methods below.
if 1:
if 0:
# The simple method assumes that there is no existing
# instance. Be sure of that with an assert.
assert self.GetInstance() is None
@@ -156,9 +153,9 @@ class TestPanel(wx.Panel):
line = wx.StaticLine(self, -1)
# Load the resource
res = xrc.EmptyXmlResource()
res = xrc.XmlResource()
res.InsertHandler(MyCustomPanelXmlHandler())
res.LoadFromString(resourceText)
res.LoadFromBuffer(resourceText)
# Now create a panel from the resource data
panel = res.LoadObject(self, "MyPanel", "MyCustomPanel")
@@ -171,7 +168,6 @@ class TestPanel(wx.Panel):
sizer.Add(panel, 1, wx.EXPAND|wx.ALL, 5)
self.SetSizer(sizer)
self.SetAutoLayout(True)
#----------------------------------------------------------------------

View File

@@ -5,7 +5,7 @@ import wx.xrc as xrc
#----------------------------------------------------------------------
resourceText = r'''<?xml version="1.0"?>
resourceText = br'''<?xml version="1.0"?>
<resource>
<!-- Notice that the class IS a standard wx class, and a custom
@@ -26,9 +26,8 @@ resourceText = r'''<?xml version="1.0"?>
class MyCustomPanel(wx.Panel):
def __init__(self):
p = wx.PrePanel()
wx.Panel.__init__(self)
# the Create step is done by XRC.
self.PostCreate(p)
self.Bind(wx.EVT_WINDOW_CREATE, self.OnCreate)
self.Bind(wx.EVT_SIZE, self.OnSize)
@@ -75,8 +74,8 @@ class TestPanel(wx.Panel):
line = wx.StaticLine(self, -1)
# Load the resource
res = xrc.EmptyXmlResource()
res.LoadFromString(resourceText)
res = xrc.XmlResource()
res.LoadFromBuffer(resourceText)
# Now create a panel from the resource data
panel = res.LoadPanel(self, "MyPanel")
@@ -89,7 +88,6 @@ class TestPanel(wx.Panel):
sizer.Add(panel, 1, wx.EXPAND|wx.ALL, 5)
self.SetSizer(sizer)
self.SetAutoLayout(True)
#----------------------------------------------------------------------

View File

@@ -12,7 +12,7 @@
<h2>Mixing wxPython and wxHTML</h2>
The widgets on this page were created dynamically on the fly by a
custom wxTagHandler found in wxPython.lib.wxpTag. You can look at the
custom wxTagHandler found in wx.lib.wxpTag. You can look at the
sources and doc-string in the wxPython library at wx/lib/wxpTag.py.
<p>
@@ -45,10 +45,10 @@ parameter value. Source code is <a href="../widgetTest.py">here</a>.
<p>
<wxp module="widgetTest" class="TestPanel" width=180 height=100>
<param name="bgcolor" value="#CC00FF">
</wxp>
<wxp module="widgetTest" class="TestPanel" width=180 height=100>
<param name="bgcolor" value="#00CCFF">
</wxp>
<wxp module="widgetTest" class="TestPanel" width=180 height=100>

View File

@@ -1,5 +1,3 @@
#!/usr/bin/env python
# demodata.py
"""
@@ -151,12 +149,12 @@ _treeList = [
'GenericButtons',
'GenericDirCtrl',
'ItemsPicker',
'LEDNumberCtrl',
#'LEDNumberCtrl', # TODO
'MultiSash',
'PlateButton',
'PopupControl',
'PyColourChooser',
'TreeListCtrl',
#'TreeListCtrl', # TODO or toss it?
]),
# controls coming from other libraries
@@ -172,7 +170,7 @@ _treeList = [
'ComboCtrl',
'ContextHelp',
'DatePickerCtrl',
'DynamicSashWindow',
#'DynamicSashWindow', # TODO
'EditableListBox',
'ExpandoTextCtrl',
'FancyText',
@@ -183,7 +181,6 @@ _treeList = [
'HTML2_WebView',
'InfoBar',
'IntCtrl',
'MVCTree',
'MaskedEditControls',
'MaskedNumCtrl',
'MediaCtrl',
@@ -197,7 +194,7 @@ _treeList = [
'ResizeWidget',
'RichTextCtrl',
'ScrolledPanel',
'SplitTree',
#'SplitTree', # TODO or toss it?
'StyledTextCtrl_1',
'StyledTextCtrl_2',
'TablePrint',
@@ -215,7 +212,6 @@ _treeList = [
'LayoutAnchors',
'LayoutConstraints',
'Layoutf',
'RowColSizer',
'ScrolledPanel',
'SizedControls',
'Sizers',

View File

@@ -1,85 +0,0 @@
<?xml version="1.0"?>
<!DOCTYPE gcapaper SYSTEM "gcapap-X.dtd" [
<!ENTITY footprint SYSTEM "footprint.tif" NDATA tiff >
<!ENTITY footprint SYSTEM "footprint.eps" NDATA eps >
<!ENTITY shoes SYSTEM "shoes.tif" NDATA tiff >
<!ENTITY super1 "&#90;">
]>
<gcapaper><front><title>Using SGML to make footprints in the sand
</title><keyword>footprints</keyword><keyword>sand</keyword>
<author><fname>Jane</fname><surname>Doe</surname>
<jobtitle>Empress</jobtitle>
<address><affil>Universe Corporation</affil>
<aline>1 Main Street</aline>
<city>Perfect City</city>
<province>Dorado</province>
<cntry>Neutral</cntry><postcode>999999</postcode>
<phone>+55 555 555 5550</phone>
<fax>+55 555 555 5555</fax>
<email>jane@universe.com</email>
<web>www.universe.com</web>
</address>
<bio><para>Jane Doe is the Empress of the Universe <bibref refloc="jd000"/>, a position to which she has always aspired.</para></bio>
</author>
<author><fname>Fred</fname><surname>Bloggs</surname>
<jobtitle>Designer</jobtitle>
<address><affil>Fred (The Shoe) Bloggs Ltd</affil>
<aline>1 Shoe Lane</aline>
<city>Perfect City</city>
<province>Dorado</province>
<cntry>Neutral</cntry><postcode>999999</postcode>
<phone>+55 555 555 1122</phone>
<fax>+55 555 555 1133</fax>
<email>fred@shoebloggs.com</email>
<web>www.shoebloggs.com</web></address>
<bio><para>Fred has always wanted to create the perfect shoe for making footprints in the sand. Now with SGML and XML, he has been able to document his design.</para></bio>
</author>
<abstract>
<para><keyword>ease</keyword><keyword>documentation</keyword>It's not easy being an Empress of the Universe (<a href="http://www.universe.com"/>), but with the right pair of shoes and the right documentation on how to make footprints in the sand of life, it's easier than it was. Since the introduction of <acronym.grp><acronym>SGML</acronym><expansion>Standard Generalized Markup Language</expansion></acronym.grp> and <acronym.grp><acronym>XML</acronym><expansion>Extensible Markup Language</expansion></acronym.grp> it is now possible to identify and manage the key bits of information on this process.</para>
</abstract>
</front>
<body><section id="jd001"><title>Introduction</title>
<para><keyword>documentation</keyword>Since its inception, the Universe has always had sand, now it has an Empress, a good shoe design, and <acronym>SGML</acronym> / <acronym>XML</acronym> documentation. The time is now ripe for making <highlight style="ital">footprints</highlight> in the sand.</para></section>
<section id="jd002"><title>Footprints - truly a push technology</title><keyword>push</keyword>
<para>One could safely say that making footprints is a push technology. This is even more true when the footprint maker is the Empress of the Universe. </para>
<subsec1 id="jd003"><title>The sands of time</title><keyword>time</keyword>
<para>The 1<super>st</super> think to remember about the Universe is the time/space continuum to which it conforms. This then confuses the sands of time to be something more like the sands of time/space continuum because if you wait on those sands long enough they may be somewhere else - not necessarily because of the time/space continuum but because the winds will <highlight style="ital">push</highlight> them down the beach.</para></subsec1>
<subsec1 id="jd004"><title>Identifying the footprints</title>
<para>In order to truly understand who has walked on the sands and left the footprints, it is important to identify the <keyword>characteristics</keyword>characteristics of the footprint. In the graphic <xref refloc="jd005" type="title"/>, we can see the footprints are large, well shaped, and evenly distributed from front to back and side to side.</para>
<figure id="jd005"><title>Footprint in Sand</title><caption><para>Note the evenly distributed shape and indention</para></caption><graphic figname="footprint"/></figure>
<para>This footprint begs the question, 'What kind of remarkable <keyword>shoe</keyword>shoe could make such a wonderful footprint?'</para>
<table id="t1">
<tgroup cols="2">
<thead><row><entry>Shoe Type</entry><entry>Remarkability Rating</entry></row></thead>
<tbody><row><entry>Acme Shoe</entry><entry>Unremarkable</entry></row>
<row><entry>Budget Shoe</entry><entry>Not worth remarking on</entry></row>
<row><entry>Super Duper Shoe</entry><entry>Absolutely Remarkable</entry></row></tbody>
</tgroup></table></subsec1>
<subsec1 id="jd006"><title>The Shoe What Made the Footprint</title>
<para>The remarkable footprint is made by a combination of a terrific shoe worn on a fantastic foot propelled by a one-of-a-kind Empress. As can be seen in Figure <xref refloc="jd007" type="number"/>, the shoe is worthy of an Empress.</para>
<figure id="jd007"><title>The Terrific Shoe</title><graphic figname="shoes"/></figure>
<para>The design goals of the shoe were:
<randlist style = "bulleted">
<li><para>to minimize time-consuming manual tasks such as shoelace tying;</para></li>
<li><para>to allow different decorations to be placed on the toes; and</para></li>
<li><para>to enforce a good arch.</para></li></randlist></para></subsec1></section>
<section id="jd008"><title>Documenting the Shoe</title>
<para>Documenting the shoe was the best part for Fred Bloggs. His superior design could be captured for all time in a neutrally-encoded, content-specific manner. An excerpt from his DTD gives an insight into the type of information he captured in his documentation.</para>
<code.block>&lt;!DOCTYPE shoedoc [
&lt;!ELEMENT shoedoc - - (design, mfg, care, recycle) >
&lt;!ATTLIST shoedoc designer CDATA #REQUIRED
date CDATA #REQUIRED>
&lt;!ELEMENT design - - (specs, desc) >
etc.
</code.block>
<para>An excerpt from the documentation also gives us insights.</para>
<code.block><![CDATA[<design>
<specs sizerange="4-12" widthrange="aa-d" color="navy black white red taupe">
<para>The arch shall be high. The toe shall be narrow, but not pinch. The heel shall not come off in grates. Sand shall not get in.</para></specs>]]>
</code.block>
</section></body>
<rear><acknowl>
<para>The authors wish to express our thanks to the Universe for being there and to gravity for holding the sand down long enough to see the footprints.</para></acknowl>
<bibliog>
<bibitem id="jd000"><bib>Barrett 00</bib><pub>Barrett, B., Being Empress Made Easy, Galaxy Division of Universal Publishers. 0000</pub></bibitem></bibliog></rear></gcapaper>

View File

@@ -1,231 +0,0 @@
#!/usr/bin/env python
"""
Hello, and welcome to this test of the wxTreeItemData
class.
The wxTreeItemData class can be used to associate a python
object with a wxTreeCtrl item. In this sample, its use is
demonstrated via a tree control that shows the contents of a
python namespace according to the standard dir()
command. Every item in the tree has its label taken from the
dir() output, and 'behind it' a reference to the python
object is stored in a wxTreeItemData object.
As you may have guessed by now, this sample automatically
displays '__doc__' strings if the selected python object
happens to have one. Please expand the pyTree object to
learn more about the implementation.
Version 1.0, April 4 1999.
Harm van der Heijden (H.v.d.Heijden@phys.tue.nl)
P.S. Check out the string module. It's imported in this
sample not because it's used, but because it's so
beautifully documented...
"""
import string # Used for demo purposes, nothing more. :-)
import sys
import wx
#----------------------------------------------------------------------
def _getindent(line):
"""Returns the indentation level of the given line."""
indent = 0
for c in line:
if c == ' ': indent = indent + 1
elif c == '\t': indent = indent + 8
else: break
return indent
def _sourcefinder(func):
"""Given a func_code object, this function tries to find and return
the python source code of the function."""
try:
f = open(func.co_filename,"r")
except:
return "(could not open file %s)" % (func.co_filename,)
for i in range(func.co_firstlineno):
line = f.readline()
ind = _getindent(line)
msg = ""
while line:
msg = msg + line
line = f.readline()
# the following should be <= ind, but then we get
# confused by multiline docstrings. Using == works most of
# the time... but not always!
if _getindent(line) == ind: break
return msg
#----------------------------------------------------------------------
class pyTree(wx.TreeCtrl):
"""
This wx.TreeCtrl derivative displays a tree view of a Python namespace.
Anything from which the dir() command returns a non-empty list is a branch
in this tree.
"""
def __init__(self, parent, id, root):
"""
Initialize function; because we insert branches into the tree
as needed, we use the ITEM_EXPANDING event handler. The
ITEM_COLLAPSED handler removes the stuff afterwards. The
SEL_CHANGED handler attempts to display interesting
information about the selected object.
"""
wx.TreeCtrl.__init__(self, parent, id)
self.root = self.AddRoot(str(root), -1, -1, wx.TreeItemData(root))
if dir(root):
self.SetItemHasChildren(self.root, True)
self.Bind(wx.EVT_TREE_ITEM_EXPANDING, self.OnItemExpanding, id=self.GetId())
self.Bind(wx.EVT_TREE_ITEM_COLLAPSED, self.OnItemCollapsed, id=self.GetId())
self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged, id=self.GetId())
self.output = None
self.Expand(self.root)
def SetOutput(self, output):
"""
Set output function (accepts single string). Used to display string
representation of the selected object by OnSelChanged.
"""
self.output = output
def OnItemExpanding(self,event):
"""
The real workhorse of this class. First we retrieve the object
(parent) belonging to the branch that is to be expanded. This
is done by calling GetPyData(parent), which is a short-cut for
GetPyItemData(parent).Get().
Then we get the dir() list of that object. For each item in
this list, a tree item is created with associated
wxTreeItemData referencing the child object. We get this
object using child = getattr(parent, item).
Finally, we check wether the child returns a non-empty dir()
list. If so, it is labeled as 'having children', so that it
may be expanded. When it actually is expanded, this function
will again figure out what the offspring is.
"""
item = event.GetItem()
if self.IsExpanded(item): # This event can happen twice in the self.Expand call
return
obj = self.GetPyData( item )
lst = dir(obj)
for key in lst:
new_obj = getattr(obj,key)
new_item = self.AppendItem( item, key, -1, -1,
wx.TreeItemData(new_obj) )
if dir(new_obj):
self.SetItemHasChildren(new_item, True)
def OnItemCollapsed(self, event):
"""
We need to remove all children here, otherwise we'll see all
that old rubbish again after the next expansion.
"""
item = event.GetItem()
self.DeleteChildren(item)
def OnSelChanged(self, event):
"""
If an output function is defined, we try to print some
informative, interesting and thought-provoking stuff to it.
If it has a __doc__ string, we print it. If it's a function or
unbound class method, we attempt to find the python source.
"""
if not self.output:
return
obj = self.GetPyData( event.GetItem() )
msg = str(obj)
if hasattr(obj, '__doc__'):
msg = msg+"\n\nDocumentation string:\n\n%s" % ( getattr(obj, '__doc__'),)
# Is it a function?
func = None
if hasattr(obj, "func_code"): # normal function
func = getattr(obj, "func_code")
elif hasattr(obj, "im_func"): # unbound class method
func = getattr(getattr(obj, "im_func"), "func_code")
if func: # if we found one, let's try to print the source
msg = msg+"\n\nFunction source:\n\n" + _sourcefinder(func)
apply(self.output, (msg,))
#----------------------------------------------------------------------
overview = __doc__
def runTest(frame, nb, log):
"""
This method is used by the wxPython Demo Framework for integrating
this demo with the rest.
"""
thisModule = sys.modules[__name__]
win = wx.Frame(frame, -1, "PyTreeItemData Test")
split = wx.SplitterWindow(win, -1)
tree = pyTree(split, -1, thisModule)
text = wx.TextCtrl(split, -1, "", style=wx.TE_MULTILINE)
split.SplitVertically(tree, text, 200)
tree.SetOutput(text.SetValue)
tree.SelectItem(tree.root)
win.SetSize((800,500))
frame.otherWin = win
win.Show(1)
#----------------------------------------------------------------------
if __name__ == '__main__':
class MyFrame(wx.Frame):
"""Very standard Frame class. Nothing special here!"""
def __init__(self):
"""Make a splitter window; left a tree, right a textctrl. Wow."""
import __main__
wx.Frame.__init__(self, None, -1, "PyTreeItemData Test", size=(800,500))
split = wx.SplitterWindow(self, -1)
tree = pyTree(split, -1, __main__)
text = wx.TextCtrl(split, -1, "", style=wx.TE_MULTILINE)
split.SplitVertically(tree, text, 200)
tree.SetOutput(text.SetValue)
tree.SelectItem(tree.root)
class MyApp(wx.App):
"""This class is even less interesting than MyFrame."""
def OnInit(self):
"""OnInit. Boring, boring, boring!"""
frame = MyFrame()
frame.Show(True)
self.SetTopWindow(frame)
return True
app = MyApp(False)
app.MainLoop()

View File

@@ -1,13 +0,0 @@
<?xml version="1.0"?>
<!DOCTYPE quotations [
<!ELEMENT collection (quotation)*>
<!ELEMENT em (#PCDATA) >
<!ELEMENT foreign (#PCDATA) >
<!ELEMENT cite (#PCDATA) >
<!ELEMENT author (#PCDATA)>
<!ELEMENT source (#PCDATA|cite)*>
<!ELEMENT quotation (#PCDATA|author|source)* >
]>
<collection><quotation>We will perhaps eventually be writing only small modules which are identified by name as they are used to build larger ones, so that devices like indentation, rather than delimiters, might become feasible for expressing local structure in the source language. <source>Donald E. Knuth, "Structured Programming with goto Statements", Computing Surveys, Vol 6 No 4, Dec. 1974</source> </quotation> <quotation> The infinities aren't contagious except in that they often appear that way due to to their large size. <source>Tim Peters on the IEEE 754 floating point standard, 27 Apr 1998</source> </quotation> </collection>

View File

@@ -1,6 +1,6 @@
#!/usr/bin/env python
# This file is used for the wx.HtmlWindow demo.
# This file is used for the HtmlWindow demo.
import sys

View File

@@ -15,6 +15,9 @@ MODULE = "_xml"
NAME = "_xml" # Base name of the file to generate to for this script
DOCSTRING = """\
Some simple XML classes for use with XRC.
For more advanced XML needs it would be better to use one of the XML packages
provided by Python.
"""
# The classes and/or the basename of the Doxygen XML files to be processed by

View File

@@ -98,8 +98,8 @@ def run():
c.addPublic()
c.addCppMethod('bool', 'LoadFromString', '(wxPyBuffer* data)',
doc="Load the resource from a string or other data buffer compatible object.",
c.addCppMethod('bool', 'LoadFromBuffer', '(wxPyBuffer* data)',
doc="Load the resource from a bytes string or other data buffer compatible object.",
#protection='public',
body="""\
static int s_memFileIdx = 0;
@@ -125,6 +125,7 @@ def run():
bool retval = self->Load(wxT("memory:") + filename );
return retval;
""")
c.addPyCode("XmlResource.LoadFromString = wx.deprecated(XmlResource.LoadFromBuffer, 'Use LoadFromBuffer instead')")
c.find('AddHandler.handler').transfer = True
c.find('InsertHandler.handler').transfer = True

View File

@@ -38,7 +38,7 @@ def run():
c = module.find('wxContextHelpButton')
assert isinstance(c, etgtools.ClassDef)
tools.fixWindowClass(c)
c = module.find('wxHelpProvider')
c.abstract = True

View File

@@ -58,27 +58,48 @@ def run():
c = module.find('wxArchiveFSHandler')
c.addPrivateCopyCtor();
c.addPrivateCopyCtor()
module.addPyCode('ZipFSHandler = wx.deprecated(ArchiveFSHandler, "Use ArchiveFSHandler instead.")')
_fixHandlerClass(c)
c = module.find('wxFSFile')
c.addPrivateCopyCtor();
c.addPrivateCopyCtor()
_fixHandlerClass(c)
c = module.find('wxFilterFSHandler')
c.addPrivateCopyCtor();
c.addPrivateCopyCtor()
_fixHandlerClass(c)
c = module.find('wxInternetFSHandler')
c.addPrivateCopyCtor();
_fixHandlerClass(c)
c = module.find('wxMemoryFSHandler')
c.addPrivateCopyCtor();
c.addPrivateCopyCtor()
_fixHandlerClass(c)
c = module.find('wxMemoryFSHandler')
c.addPrivateCopyCtor()
_fixHandlerClass(c)
# Make some more python-friendly versions of the AddFile methods accepting raw data
c.find('AddFile').findOverload('binarydata').ignore()
c.find('AddFileWithMimeType').findOverload('binarydata').ignore()
c.addCppMethod('void', 'AddFile', '(const wxString& filename, wxPyBuffer* binarydata)',
isStatic=True,
doc="Add a file from raw data in a python buffer compatible object.",
body="""\
wxMemoryFSHandler::AddFile(*filename, binarydata->m_ptr, binarydata->m_len);
""")
c.addCppMethod('void', 'AddFileWithMimeType',
'(const wxString& filename, wxPyBuffer* binarydata, const wxString& mimetype)',
isStatic=True,
doc="Add a file from raw data in a python buffer compatible object.",
body="""\
wxMemoryFSHandler::AddFileWithMimeType(
*filename, binarydata->m_ptr, binarydata->m_len, *mimetype);
""")
#-----------------------------------------------------------------
tools.doCommonTweaks(module)
tools.runGenerators(module)

View File

@@ -115,7 +115,8 @@ def run():
""")
c.find('GetOpenCommand').findOverload('command').ignore()
for m in c.find('GetOpenCommand').all():
m.ignore()
c.addCppMethod('wxString', 'GetOpenCommand', '(const wxFileType::MessageParameters& params)',
doc="""\
Returns the command which must be executed (see wx.Execute()) in order
@@ -126,6 +127,16 @@ def run():
self->GetOpenCommand(&rv, *params);
return new wxString(rv);
""")
c.addCppMethod('wxString', 'GetOpenCommand', '(const wxString& filename)',
doc="""\
Returns the command which should be used to open the given
filename. An empty string is returned to indicate that an error
occurred (typically meaning that there is no standard way to open
this kind of files).""",
body="""\
return new wxString( self->GetOpenCommand(*filename) );
""")
c.find('GetPrintCommand').ignore()
c.addCppMethod('wxString', 'GetPrintCommand', '(const wxFileType::MessageParameters& params)',
@@ -139,8 +150,15 @@ def run():
return new wxString(rv);
""")
c.find('GetAllCommands.verbs').out = True
c.find('GetAllCommands.commands').out = True
m = c.find('GetAllCommands')
m.find('verbs').out = True
m.find('commands').out = True
m.type = 'void'
m.briefDoc = \
"Returns a tuple containing the `verbs` and `commands` arrays, " \
"corresponding for the registered information for this mime type."
c.addCppMethod('PyObject*', 'GetIconInfo', '()',
doc="""\

View File

@@ -36,6 +36,8 @@ def run():
c.addProperty("x GetX SetX")
c.addProperty("y GetY SetY")
c.addProperty("X GetX SetX")
c.addProperty("Y GetY SetY")
c.addProperty("leftIsDown LeftIsDown SetLeftDown")
c.addProperty("middleIsDown MiddleIsDown SetMiddleDown")
c.addProperty("rightIsDown RightIsDown SetRightDown")

View File

@@ -179,17 +179,16 @@ def run():
static PyObject* _readlinesHelper(wxInputStream* self,
bool useSizeHint=false, ulong sizehint=0) {
PyObject* pylist;
// init list
wxPyBlock_t blocked = wxPyBeginBlockThreads();
pylist = PyList_New(0);
wxPyEndBlockThreads(blocked);
if (!pylist) {
wxPyBlock_t blocked = wxPyBeginBlockThreads();
PyErr_NoMemory();
wxPyEndBlockThreads(blocked);
return NULL;
{
wxPyThreadBlocker blocker;
pylist = PyList_New(0);
if (!pylist) {
PyErr_NoMemory();
return NULL;
}
}
// read sizehint bytes or until EOF
@@ -197,24 +196,21 @@ def run():
for (i=0; (self->CanRead()) && (useSizeHint || (i < sizehint));) {
PyObject* s = _wxInputStream_readline(self);
if (s == NULL) {
wxPyBlock_t blocked = wxPyBeginBlockThreads();
wxPyThreadBlocker blocker;
Py_DECREF(pylist);
wxPyEndBlockThreads(blocked);
return NULL;
}
wxPyBlock_t blocked = wxPyBeginBlockThreads();
wxPyThreadBlocker blocker;
PyList_Append(pylist, s);
i += PyBytes_Size(s);
wxPyEndBlockThreads(blocked);
}
// error check
wxStreamError err = self->GetLastError();
if (err != wxSTREAM_NO_ERROR && err != wxSTREAM_EOF) {
wxPyBlock_t blocked = wxPyBeginBlockThreads();
wxPyThreadBlocker blocker;
Py_DECREF(pylist);
PyErr_SetString(PyExc_IOError,"IOError in wxInputStream");
wxPyEndBlockThreads(blocked);
return NULL;
}
return pylist;
@@ -271,15 +267,15 @@ def run():
return false; //self->Eof();
""")
c.addCppMethod('void', 'write', '(PyObject* data)', """\
// We use only strings for the streams, not unicode
PyObject* str = PyObject_Bytes(data);
if (! str) {
PyErr_SetString(PyExc_TypeError, "Unable to convert to string");
return;
c.addCppMethod('PyObject*', 'write', '(PyObject* data)', """\
// We use only bytes objects (strings in 2.7) for the streams, never unicode
wxPyThreadBlocker blocker;
if (!PyBytes_Check(data)) {
PyErr_SetString(PyExc_TypeError, "Bytes object expected");
return NULL;
}
self->Write(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str));
Py_DECREF(str);
self->Write(PyBytes_AS_STRING(data), PyBytes_GET_SIZE(data));
RETURN_NONE();
""")
# TODO: Add a writelines(sequence) method

View File

@@ -54,6 +54,8 @@ class BaseDef(object):
def __iter__(self):
return iter(self.items)
def __repr__(self):
return "{}: '{}', '{}'".format(self.__class__.__name__, self.name, self.pyName)
def extract(self, element):
# Pull info from the ElementTree element that is pertinent to this
@@ -391,11 +393,19 @@ class FunctionDef(BaseDef, FixWxPrefix):
return item
def ignore(self, val=True):
# If the item being ignored has overloads then try to reorder the
# items so the primary item is not an ignored one.
def ignore(self, val=True):
# In addition to ignoring this item, reorder any overloads to ensure
# the primary overload is not ignored, if possible.
super(FunctionDef, self).ignore(val)
if val and self.overloads:
self.reorderOverloads()
return self
def reorderOverloads(self):
# Reorder a set of overloaded functions such that the primary
# FunctionDef is one that is not ignored.
if self.overloads and self.ignored:
all = [self] + self.overloads
all.sort(key=lambda item: item.ignored)
first = all[0]
@@ -408,8 +418,7 @@ class FunctionDef(BaseDef, FixWxPrefix):
first.overloads = all[1:]
idx = parent.items.index(self)
parent.items[idx] = first
return self
def _findItems(self):
items = list(self.items)
@@ -576,7 +585,7 @@ class ParamDef(BaseDef):
self.arraySize = False # the param is the size of the array
self.transfer = False # transfer ownership of arg to C++?
self.transferBack = False # transfer ownership of arg from C++ to Python?
self.transferThis = False # ownership of 'this' pointer transfered to this arg
self.transferThis = False # ownership of 'this' pointer transferred to this arg
self.keepReference = False # an extra reference to the arg is held
self.__dict__.update(kw)
if element is not None:
@@ -919,10 +928,13 @@ class ClassDef(BaseDef):
def _addMethod(self, md, overloadOkay=True):
md.klass = self
if overloadOkay and self.findItem(md.name):
self.findItem(md.name).overloads.append(md)
item = self.findItem(md.name)
item.overloads.append(md)
item.reorderOverloads()
else:
self.items.append(md)
def addCppMethod(self, type, name, argsString, body, doc=None, isConst=False,
cppSignature=None, overloadOkay=True, **kw):
"""
@@ -1180,7 +1192,7 @@ class CppMethodDef(MethodDef):
so it can be used to write the code for a new wrapper function.
TODO: It might be better to just refactor the code in the generator
so it can be shared more easily intstead of using a hack like this...
so it can be shared more easily instead of using a hack like this...
"""
m = CppMethodDef('', '', '', '')
m.__dict__.update(method.__dict__)

View File

@@ -117,6 +117,7 @@ class DataObjTests(wtc.WidgetTestCase):
def test_DataObject2(self):
# More-or-less a duplicate of the above, but with a custom data format
class MyDataObject(wx.DataObject):
def __init__(self, value=''):
wx.DataObject.__init__(self)
@@ -211,6 +212,7 @@ class DataObjTests(wtc.WidgetTestCase):
def test_DataObjectSimple3(self):
# More-or-less a duplicate of the above, but with a custom data format
class MyDataObject(wx.DataObjectSimple):
def __init__(self, value=''):
wx.DataObjectSimple.__init__(self)

View File

@@ -180,10 +180,10 @@ class ColourSelect(wx.lib.buttons.GenBitmapButton):
if label:
mdc = wx.MemoryDC(wx.Bitmap(1,1))
w, h = mdc.GetTextExtent(label)
w += 6
h += 6
w += 8
h += 8
else:
w, h = 20, 20
w, h = 22, 22
size.width = size.width if size.width != -1 else w
size.height = size.height if size.height != -1 else h

View File

@@ -213,7 +213,7 @@ class BasePopupFrame(wx.Frame):
def _layoutInterior(self):
frameSizer = wx.BoxSizer(wx.HORIZONTAL)
frameSizer.Add(self._tree, flag=wx.EXPAND, proportion=1)
self.SetSizerAndFit(frameSizer)
self.SetSizerAndFit(frameSizer) #****
def _bindEventHandlers(self):
self._tree.Bind(wx.EVT_CHAR, self.OnChar)
@@ -870,21 +870,6 @@ class MSWComboTreeBox(NativeComboTreeBox):
super(MSWComboTreeBox, self).NotifyNoItemSelected(*args, **kwargs)
class MACComboTreeBox(NativeComboTreeBox):
def _createPopupFrame(self):
return MACPopupFrame(self)
def _createButton(self):
return self.GetChildren()[0] # The choice button
def _keyShouldNavigate(self, keyEvent):
return False # No navigation with up and down on wxMac
def _keyShouldPopUpTree(self, keyEvent):
return super(MACComboTreeBox, self)._keyShouldPopUpTree(keyEvent) or \
keyEvent.GetKeyCode() == wx.WXK_DOWN
class GTKComboTreeBox(BaseComboTreeBox, wx.Panel):
"""
The ComboTreeBox widget for wxGTK. This is actually a work
@@ -917,6 +902,26 @@ class GTKComboTreeBox(BaseComboTreeBox, wx.Panel):
self.SetSizerAndFit(panelSizer)
# class MACComboTreeBox(NativeComboTreeBox):
# def _createPopupFrame(self):
# return MACPopupFrame(self)
#
# def _createButton(self):
# return self.GetChildren()[0] # The choice button
#
# def _keyShouldNavigate(self, keyEvent):
# return False # No navigation with up and down on wxMac
#
# def _keyShouldPopUpTree(self, keyEvent):
# return super(MACComboTreeBox, self)._keyShouldPopUpTree(keyEvent) or \
# keyEvent.GetKeyCode() == wx.WXK_DOWN
# The MAC implementation based on the NativeComboTreeBox is no longer working,
# so let's use the GTKComboTreeBox instead.
MACComboTreeBox = GTKComboTreeBox
# ---------------------------------------------------------------------------

View File

@@ -1,11 +1,11 @@
#----------------------------------------------------------------------
# Name: wx.lib.editor
# Purpose: A package containing a colourizable text editror
# Purpose: A package containing a colourizable text editor
#
# Author: Robin Dunn
#
# Created: 30-Dec-1999
# Copyright: (c) 1999 by Total Control Software
# Copyright: (c) 1999-2016 by Total Control Software
# Licence: wxWindows license
#----------------------------------------------------------------------
# 12/14/2003 - Jeff Grimmett (grimmtooth@softhome.net)
@@ -21,4 +21,4 @@
# import the main classes into the package namespace.
from editor import Editor
from .editor import Editor

View File

@@ -16,7 +16,7 @@
#
#
# Created: 15-Dec-1999
# Copyright: (c) 1999 by Dirk Holtwick, 1999
# Copyright: (c) 1999-2016 by Dirk Holtwick, 1999
# Licence: wxWindows license
#----------------------------------------------------------------------
# 12/14/2003 - Jeff Grimmett (grimmtooth@softhome.net)
@@ -33,8 +33,8 @@ import time
import wx
import selection
import images
from . import selection
from . import images
#----------------------------
@@ -133,8 +133,6 @@ class Editor(wx.ScrolledWindow):
font = wx.Font(10, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)
else:
font = wx.Font(12, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
if wx.Platform == "__WXMAC__":
font.SetNoAntiAliasing()
return font
def UnixKeyHack(self, key):
@@ -162,18 +160,18 @@ class Editor(wx.ScrolledWindow):
self.bw, self.bh = self.GetClientSize()
if wx.Platform == "__WXMSW__":
self.sh = self.bh / self.fh
self.sw = (self.bw / self.fw) - 1
self.sh = int(self.bh / self.fh)
self.sw = int(self.bw / self.fw) - 1
else:
self.sh = self.bh / self.fh
self.sh = int(self.bh / self.fh)
if self.LinesInFile() >= self.sh:
self.bw = self.bw - wx.SystemSettings.GetMetric(wx.SYS_VSCROLL_X)
self.sw = (self.bw / self.fw) - 1
self.sw = int(self.bw / self.fw) - 1
self.sw = (self.bw / self.fw) - 1
self.sw = int(self.bw / self.fw) - 1
if self.CalcMaxLineLen() >= self.sw:
self.bh = self.bh - wx.SystemSettings.GetMetric(wx.SYS_HSCROLL_Y)
self.sh = self.bh / self.fh
self.sh = int(self.bh / self.fh)
def UpdateView(self, dc = None):
@@ -246,6 +244,7 @@ class Editor(wx.ScrolledWindow):
dc.SetBackgroundMode(wx.SOLID)
dc.SetTextBackground(self.bgColor)
dc.SetTextForeground(self.fgColor)
dc.SetBackground(wx.Brush(self.bgColor))
dc.Clear()
for line in range(self.sy, self.sy + self.sh):
self.DrawLine(line, dc)
@@ -291,7 +290,7 @@ class Editor(wx.ScrolledWindow):
szy = self.fh
x = xp * szx
y = yp * szy
dc.Blit(x,y, szx,szy, dc, x,y, wx.SRC_INVERT)
dc.Blit(x,y, szx,szy, dc, x,y, wx.XOR)
self.sco_x = xp
self.sco_y = yp
@@ -448,7 +447,7 @@ class Editor(wx.ScrolledWindow):
##------------------------ mousing functions
def MouseToRow(self, mouseY):
row = self.sy + (mouseY/ self.fh)
row = self.sy + int(mouseY / self.fh)
if self.AboveScreen(row):
self.HandleAboveScreen(row)
elif self.BelowScreen(row):
@@ -457,7 +456,7 @@ class Editor(wx.ScrolledWindow):
self.cy = min(row, self.LinesInFile() - 1)
def MouseToCol(self, mouseX):
col = self.sx + (mouseX / self.fw)
col = self.sx + int(mouseX / self.fw)
if self.LeftOfScreen(col):
self.HandleLeftOfScreen(col)
elif self.RightOfScreen(col):

View File

@@ -121,7 +121,7 @@ class ColDragWindow(wx.Window):
if x == pos:
self.Refresh() # Need to display insertion point
else:
self.MoveXY(pos,y)
self.Move(pos,y)
def GetMoveColumn(self):
return self.moveColumn
@@ -184,7 +184,7 @@ class RowDragWindow(wx.Window):
if y == pos:
self.Refresh() # Need to display insertion point
else:
self.MoveXY(x,pos)
self.Move(x,pos)
def GetMoveRow(self):
return self.moveRow
@@ -248,6 +248,13 @@ class GridColMover(wx.EvtHandler):
self.Bind(wx.EVT_MOTION, self.OnMouseMove)
self.Bind(wx.EVT_LEFT_DOWN, self.OnPress)
self.Bind(wx.EVT_LEFT_UP, self.OnRelease)
self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
def OnDestroy(self, evt):
assert self.lwin.GetEventHandler() is self
self.lwin.PopEventHandler(True)
def OnMouseMove(self,evt):
if not self.isDragging:
@@ -373,6 +380,13 @@ class GridRowMover(wx.EvtHandler):
self.Bind(wx.EVT_MOTION, self.OnMouseMove)
self.Bind(wx.EVT_LEFT_DOWN, self.OnPress)
self.Bind(wx.EVT_LEFT_UP, self.OnRelease)
self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
def OnDestroy(self, evt):
assert self.lwin.GetEventHandler() is self
self.lwin.PopEventHandler(True)
def OnMouseMove(self,evt):
if not self.isDragging:

View File

@@ -10,7 +10,7 @@
# Licence: wxPython license
# Tags: phoenix-port
#----------------------------------------------------------------------------
'''
"""
Created on Oct 3, 2010
@authors: Daphna Rosenbom,Gitty Zinger,Moshe Cohavi and Yoav Glazner
@@ -22,7 +22,8 @@ items_picker.ItemsPicker:
- De-Selection is done by the Remove button or Double Click,</LI>
Derived from wxPanel
'''
"""
import wx
__version__ = 0.1
@@ -48,18 +49,18 @@ class IpSelectionChanged(wx.PyCommandEvent):
class ItemsPicker(wx.Panel):
'''
"""
ItemsPicker is a widget that allows the user to form a set of picked
items out of a given list
'''
"""
def __init__(self, parent, id=wx.ID_ANY, choices = [],
label = '', selectedLabel = '',
ipStyle = IP_DEFAULT_STYLE,
*args, **kw):
'''
"""
ItemsPicker(parent, choices = [], label = '', selectedLabel = '',
ipStyle = IP_DEFAULT_STYLE)
'''
"""
wx.Panel.__init__(self, parent, id, *args, **kw)
self._ipStyle = ipStyle
sizer = wx.BoxSizer(wx.HORIZONTAL)
@@ -72,14 +73,14 @@ class ItemsPicker(wx.Panel):
def SetItems(self, items):
'''SetItems(self, items)=> None
items - Sequence of strings that the user can pick from'''
"""SetItems(self, items)=> None
items - Sequence of strings that the user can pick from"""
return self._source.SetItems(items)
def GetItems(self):
'''GetItems(self)=> items
returns list of strings that the user can pick from'''
"""GetItems(self)=> items
returns list of strings that the user can pick from"""
return self._source.GetItems()
@@ -89,16 +90,16 @@ class ItemsPicker(wx.Panel):
def GetSelections(self):
'''GetSelections(self)=>items
"""GetSelections(self)=>items
returns list of strings that were selected
'''
"""
return self._dest.GetItems()
def SetSelections(self, items):
'''SetSelections(self, items)=>None
"""SetSelections(self, items)=>None
items - Sequence of strings to be selected
The items are displayed in the selection part of the widget'''
The items are displayed in the selection part of the widget"""
assert len(items)==len(set(items)),"duplicate items are not allowed"
if items != self._dest.GetItems():
self._dest.SetItems(items)

File diff suppressed because it is too large Load Diff

View File

@@ -38,12 +38,8 @@ class Diagram(object):
def Redraw(self, dc):
"""Redraw the shapes in the diagram on the specified device context."""
if self._shapeList:
if self.GetCanvas():
self.GetCanvas().SetCursor(wx.HOURGLASS_CURSOR)
for object in self._shapeList:
object.Draw(dc)
if self.GetCanvas():
self.GetCanvas().SetCursor(wx.STANDARD_CURSOR)
def Clear(self, dc):
"""Clear the specified device context."""

View File

@@ -27,6 +27,8 @@ import copy
import types
import wx
import six
class PrintBase(object):
def SetPrintFont(self, font): # set the DC font parameters
fattr = font["Attr"]
@@ -271,7 +273,7 @@ class PrintTableDraw(wx.ScrolledWindow, PrintBase):
self.column.append(pos_x)
#module logic expects two dimensional data -- fix input if needed
if isinstance(self.data,types.StringTypes):
if isinstance(self.data, six.string_types):
self.data = [[copy.copy(self.data)]] # a string becomes a single cell
try:
rows = len(self.data)
@@ -280,7 +282,7 @@ class PrintTableDraw(wx.ScrolledWindow, PrintBase):
rows = 1
first_value = self.data[0]
if isinstance(first_value, types.StringTypes): # a sequence of strings
if isinstance(first_value, six.string_types): # a sequence of strings
if self.label == [] and self.set_column == []:
data = []
for x in self.data: #becomes one column
@@ -560,7 +562,7 @@ class PrintTableDraw(wx.ScrolledWindow, PrintBase):
self.col = 0
max_y = 0
for vtxt in row_val:
if not isinstance(vtxt,types.StringTypes):
if not isinstance(vtxt, six.string_types):
vtxt = str(vtxt)
self.region = self.column[self.col+1] - self.column[self.col]
self.indent = self.column[self.col]
@@ -681,7 +683,10 @@ class PrintTable(object):
self.row_line_colour = {}
self.parentFrame = parentFrame
self.SetPreviewSize()
if parentFrame:
self.SetPreviewSize(parentFrame.GetPosition(), parentFrame.GetSize())
else:
self.SetPreviewSize()
self.printData = wx.PrintData()
self.scale = 1.0

View File

@@ -1,229 +0,0 @@
#----------------------------------------------------------------------
# Name: wx.lib.rcsizer
# Purpose: RowColSizer:
#
# Author: Robin Dunn, adapted from code by Niki Spahiev
#
# Created: 26-Feb-2002
# Copyright: (c) 2002 by Total Control Software
# Licence: wxWindows license
#----------------------------------------------------------------------
# 12/10/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o 2.5 compatability update.
# o There appears to be a prob with the wx.Sizer.GetSize() method.
#
# 12/23/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o wx.Sizer.GetSize() method working right now.
#
"""
A pure-Python Sizer that lays out items in a grid similar to
wx.FlexGridSizer but item position is not implicit but explicitly
specified by row and col, and row/col spanning is supported.
Adapted from code by Niki Spahiev.
NOTE: There is now a C++ version of this class that has been wrapped
as wx.GridBagSizer. It is quicker and more capable so you are
encouraged to switch.
"""
import operator
import wx
import six
if six.PY3:
from functools import reduce as reduce
# After the lib and demo no longer uses this sizer enable this warning...
## import warnings
## warningmsg = r"""\
## #####################################################\
## # THIS MODULE IS NOW DEPRECATED |
## # |
## # The core wx library now contains a similar class |
## # wrapped as wx.GridBagSizer. |
## #####################################################/
## """
## warnings.warn(warningmsg, DeprecationWarning, stacklevel=2)
#----------------------------------------------------------------------
class RowColSizer(wx.Sizer):
# default sizes for cells with no item
col_w = 10
row_h = 22
def __init__(self):
wx.Sizer.__init__(self)
self.growableRows = []
self.growableCols = []
def AddGrowableRow(self, idx):
self.growableRows.append(idx)
def AddGrowableCol(self, idx):
self.growableCols.append(idx)
#--------------------------------------------------
def Add(self, item, option=0, flag=0, border=0,
# row, col and spanning can be specified individually...
row=-1, col=-1,
rowspan=1, colspan=1,
# or as tuples (row,col) and (rowspan,colspan)
pos=None, size=None,
):
if pos is not None:
row, col = pos
if size is not None:
rowspan, colspan = size
assert row != -1, "Row must be specified"
assert col != -1, "Column must be specified"
# Do I really want to do this? Probably not...
#if rowspan > 1 or colspan > 1:
# flag = flag | wx.EXPAND
return wx.Sizer.Add(self, item, option, flag, border,
userData=(row, col, row+rowspan, col+colspan))
#AddWindow = Add
#AddSizer = Add
def AddSpacer(self, width, height, option=0, flag=0, border=0,
row=-1, col=-1,
rowspan=1, colspan=1,
pos=None, size=None,
):
if pos is not None:
row, col = pos
if size is not None:
rowspan, colspan = size
assert row != -1, "Row must be specified"
assert col != -1, "Column must be specified"
return wx.Sizer.Add(self, (width, height), option, flag, border,
userData=(row, col, row+rowspan, col+colspan))
#--------------------------------------------------
def _add( self, size, dim ):
r, c, r2, c2 = dim # unpack coords and spanning
# are the widths and heights lists long enough?
if r2 > len(self.rowHeights):
x = [self.row_h] * (r2-len(self.rowHeights))
self.rowHeights.extend( x )
if c2 > len(self.colWidths):
x = [self.col_w] * (c2-len(self.colWidths))
self.colWidths.extend( x )
# set the widths and heights lists for this item
scale = (r2 - r)
for i in range(r, r2):
self.rowHeights[i] = max( self.rowHeights[i], size.height / scale )
scale = (c2 - c)
for i in range(c, c2):
self.colWidths[i] = max( self.colWidths[i], size.width / scale )
#--------------------------------------------------
def CalcMin( self ):
self.rowHeights = []
self.colWidths = []
items = self.GetChildren()
if not items:
return wx.Size(10, 10)
for item in items:
self._add( item.CalcMin(), item.GetUserData() )
size = wx.Size( reduce( operator.add, self.colWidths),
reduce( operator.add, self.rowHeights) )
return size
#--------------------------------------------------
def RecalcSizes( self ):
# save current dimensions, etc.
curWidth, curHeight = self.GetSize()
px, py = self.GetPosition()
minWidth, minHeight = self.CalcMin()
# Check for growables
if self.growableRows and curHeight > minHeight:
delta = (curHeight - minHeight) / len(self.growableRows)
extra = (curHeight - minHeight) % len(self.growableRows)
for idx in self.growableRows:
self.rowHeights[idx] += delta
self.rowHeights[self.growableRows[0]] += extra
if self.growableCols and curWidth > minWidth:
delta = (curWidth - minWidth) / len(self.growableCols)
extra = (curWidth - minWidth) % len(self.growableCols)
for idx in self.growableCols:
self.colWidths[idx] += delta
self.colWidths[self.growableCols[0]] += extra
rpos = [0] * len(self.rowHeights)
cpos = [0] * len(self.colWidths)
for i in range(len(self.rowHeights)):
height = self.rowHeights[i]
rpos[i] = py
py += height
for i in range(len(self.colWidths)):
width = self.colWidths[i]
cpos[i] = px
px += width
# iterate children and set dimensions...
for item in self.GetChildren():
r, c, r2, c2 = item.GetUserData()
width = reduce( operator.add, self.colWidths[c:c2] )
height = reduce( operator.add, self.rowHeights[r:r2] )
self.SetItemBounds( item, cpos[c], rpos[r], width, height )
#--------------------------------------------------
def SetItemBounds(self, item, x, y, w, h):
# calculate the item's actual size and position within
# its grid cell
ipt = wx.Point(x, y)
isz = item.CalcMin()
flag = item.GetFlag()
if flag & wx.EXPAND or flag & wx.SHAPED:
isz = wx.Size(w, h)
else:
if flag & wx.ALIGN_CENTER_HORIZONTAL:
ipt.x = x + (w - isz.width) / 2
elif flag & wx.ALIGN_RIGHT:
ipt.x = x + (w - isz.width)
if flag & wx.ALIGN_CENTER_VERTICAL:
ipt.y = y + (h - isz.height) / 2
elif flag & wx.ALIGN_BOTTOM:
ipt.y = y + (h - isz.height)
item.SetDimension(ipt, isz)
#----------------------------------------------------------------------
#----------------------------------------------------------------------