Trim trailing space samples directory

This commit is contained in:
Metallicow
2016-12-05 16:34:47 -06:00
parent 067569d785
commit 01f8f09f60
58 changed files with 692 additions and 693 deletions

View File

@@ -19,19 +19,19 @@ class NullLog:
def write(self, *args): def write(self, *args):
#print(' '.join(args)) #print(' '.join(args))
pass pass
#---------------------------------------------------------------------- #----------------------------------------------------------------------
# This class is used to provide an interface between a ComboCtrl and the # This class is used to provide an interface between a ComboCtrl and the
# ListCtrl that is used as the popoup for the combo widget. # ListCtrl that is used as the popoup for the combo widget.
class ListCtrlComboPopup(wx.ComboPopup): class ListCtrlComboPopup(wx.ComboPopup):
def __init__(self): def __init__(self):
wx.ComboPopup.__init__(self) wx.ComboPopup.__init__(self)
self.log = NullLog() self.log = NullLog()
self.lc = None self.lc = None
def AddItem(self, txt): def AddItem(self, txt):
self.lc.InsertItem(self.lc.GetItemCount(), txt) self.lc.InsertItem(self.lc.GetItemCount(), txt)
@@ -130,12 +130,12 @@ class ListCtrlComboPopup(wx.ComboPopup):
# Return true if you want delay the call to Create until the popup # Return true if you want delay the call to Create until the popup
# is shown for the first time. It is more efficient, but note that # is shown for the first time. It is more efficient, but note that
# it is often more convenient to have the control created # it is often more convenient to have the control created
# immediately. # immediately.
# Default returns false. # Default returns false.
def LazyCreate(self): def LazyCreate(self):
self.log.write("ListCtrlComboPopup.LazyCreate") self.log.write("ListCtrlComboPopup.LazyCreate")
return wx.ComboPopup.LazyCreate(self) return wx.ComboPopup.LazyCreate(self)
@@ -149,7 +149,7 @@ class TestFrame(wx.Frame):
# Create a ComboCtrl # Create a ComboCtrl
cc = self.cc = wx.ComboCtrl(pnl, pos=(10,10), size=(275,-1)) cc = self.cc = wx.ComboCtrl(pnl, pos=(10,10), size=(275,-1))
cc.SetHint('Click the button -->') cc.SetHint('Click the button -->')
# Create a Popup # Create a Popup
popup = ListCtrlComboPopup() popup = ListCtrlComboPopup()
@@ -160,11 +160,11 @@ class TestFrame(wx.Frame):
# Add some items to the listctrl. # Add some items to the listctrl.
for x in range(75): for x in range(75):
popup.AddItem("Item-%02d" % x) popup.AddItem("Item-%02d" % x)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
if __name__ == '__main__': if __name__ == '__main__':
app = wx.App(False) app = wx.App(False)
frm = TestFrame(None) frm = TestFrame(None)

View File

@@ -114,17 +114,17 @@ class TestPanel(wx.Panel):
# Create a dataview control # Create a dataview control
self.dvc = dv.DataViewCtrl(self, style=wx.BORDER_THEME self.dvc = dv.DataViewCtrl(self, style=wx.BORDER_THEME
| dv.DV_ROW_LINES | dv.DV_ROW_LINES
#| dv.DV_HORIZ_RULES #| dv.DV_HORIZ_RULES
| dv.DV_VERT_RULES | dv.DV_VERT_RULES
| dv.DV_MULTIPLE | dv.DV_MULTIPLE
) )
# Create an instance of the model # Create an instance of the model
if model is None: if model is None:
self.model = TestModel(data, log) self.model = TestModel(data, log)
else: else:
self.model = model self.model = model
self.dvc.AssociateModel(self.model) self.dvc.AssociateModel(self.model)
# Now we create some columns. # Now we create some columns.
@@ -140,24 +140,24 @@ class TestPanel(wx.Panel):
column = dv.DataViewColumn(title, renderer, col, width=width) column = dv.DataViewColumn(title, renderer, col, width=width)
column.Alignment = wx.ALIGN_LEFT column.Alignment = wx.ALIGN_LEFT
self.dvc.AppendColumn(column) self.dvc.AppendColumn(column)
# Layout # Layout
self.Sizer = wx.BoxSizer(wx.VERTICAL) self.Sizer = wx.BoxSizer(wx.VERTICAL)
self.Sizer.Add(self.dvc, 1, wx.EXPAND) self.Sizer.Add(self.dvc, 1, wx.EXPAND)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def main(): def main():
from data import musicdata from data import musicdata
app = wx.App() app = wx.App()
frm = wx.Frame(None, title="CustomRenderer sample", size=(700,500)) frm = wx.Frame(None, title="CustomRenderer sample", size=(700,500))
pnl = TestPanel(frm, sys.stdout, data=musicdata) pnl = TestPanel(frm, sys.stdout, data=musicdata)
frm.Show() frm.Show()
app.MainLoop() app.MainLoop()

View File

@@ -32,16 +32,16 @@ class Song(object):
m = random.choice(range(12)) m = random.choice(range(12))
y = random.choice(range(1980, 2005)) y = random.choice(range(1980, 2005))
self.date = wx.DateTime.FromDMY(d,m,y) self.date = wx.DateTime.FromDMY(d,m,y)
def __repr__(self): def __repr__(self):
return 'Song: %s-%s' % (self.artist, self.title) return 'Song: %s-%s' % (self.artist, self.title)
class Genre(object): class Genre(object):
def __init__(self, name): def __init__(self, name):
self.name = name self.name = name
self.songs = [] self.songs = []
def __repr__(self): def __repr__(self):
return 'Genre: ' + self.name return 'Genre: ' + self.name
@@ -49,7 +49,7 @@ class Genre(object):
# This model acts as a bridge between the DataViewCtrl and the music data, and # This model acts as a bridge between the DataViewCtrl and the music data, and
# organizes it hierarchically as a collection of Genres, each of which is a # organizes it hierarchically as a collection of Genres, each of which is a
# collection of songs. # collection of songs.
# This model provides these data columns: # This model provides these data columns:
# #
@@ -66,7 +66,7 @@ class MyTreeListModel(dv.PyDataViewModel):
dv.PyDataViewModel.__init__(self) dv.PyDataViewModel.__init__(self)
self.data = data self.data = data
self.log = log self.log = log
# The PyDataViewModel derives from both DataViewModel and from # The PyDataViewModel derives from both DataViewModel and from
# DataViewItemObjectMapper, which has methods that help associate # DataViewItemObjectMapper, which has methods that help associate
# data view items with Python objects. Normally a dictionary is used # data view items with Python objects. Normally a dictionary is used
@@ -75,20 +75,20 @@ class MyTreeListModel(dv.PyDataViewModel):
# WeakValueDictionary instead. # WeakValueDictionary instead.
self.UseWeakRefs(True) self.UseWeakRefs(True)
# Report how many columns this model provides data for. # Report how many columns this model provides data for.
def GetColumnCount(self): def GetColumnCount(self):
return 6 return 6
def GetChildren(self, parent, children): def GetChildren(self, parent, children):
# The view calls this method to find the children of any node in the # The view calls this method to find the children of any node in the
# control. There is an implicit hidden root node, and the top level # control. There is an implicit hidden root node, and the top level
# item(s) should be reported as children of this node. A List view # item(s) should be reported as children of this node. A List view
# simply provides all items as children of this hidden root. A Tree # simply provides all items as children of this hidden root. A Tree
# view adds additional items as children of the other items, as needed, # view adds additional items as children of the other items, as needed,
# to provide the tree hierachy. # to provide the tree hierachy.
# If the parent item is invalid then it represents the hidden root # If the parent item is invalid then it represents the hidden root
# item, so we'll use the genre objects as its children and they will # item, so we'll use the genre objects as its children and they will
# end up being the collection of visible roots in our tree. # end up being the collection of visible roots in our tree.
@@ -96,7 +96,7 @@ class MyTreeListModel(dv.PyDataViewModel):
for genre in self.data: for genre in self.data:
children.append(self.ObjectToItem(genre)) children.append(self.ObjectToItem(genre))
return len(self.data) return len(self.data)
# Otherwise we'll fetch the python object associated with the parent # Otherwise we'll fetch the python object associated with the parent
# item and make DV items for each of it's child objects. # item and make DV items for each of it's child objects.
node = self.ItemToObject(parent) node = self.ItemToObject(parent)
@@ -105,11 +105,11 @@ class MyTreeListModel(dv.PyDataViewModel):
children.append(self.ObjectToItem(song)) children.append(self.ObjectToItem(song))
return len(node.songs) return len(node.songs)
return 0 return 0
def IsContainer(self, item): def IsContainer(self, item):
# Return True if the item has children, False otherwise. # Return True if the item has children, False otherwise.
# The hidden root is a container # The hidden root is a container
if not item: if not item:
return True return True
@@ -118,33 +118,33 @@ class MyTreeListModel(dv.PyDataViewModel):
if isinstance(node, Genre): if isinstance(node, Genre):
return True return True
# but everything else (the song objects) are not # but everything else (the song objects) are not
return False return False
def GetParent(self, item): def GetParent(self, item):
# Return the item which is this item's parent. # Return the item which is this item's parent.
##self.log.write("GetParent\n") ##self.log.write("GetParent\n")
if not item: if not item:
return dv.NullDataViewItem return dv.NullDataViewItem
node = self.ItemToObject(item) node = self.ItemToObject(item)
if isinstance(node, Genre): if isinstance(node, Genre):
return dv.NullDataViewItem return dv.NullDataViewItem
elif isinstance(node, Song): elif isinstance(node, Song):
for g in self.data: for g in self.data:
if g.name == node.genre: if g.name == node.genre:
return self.ObjectToItem(g) return self.ObjectToItem(g)
def GetValue(self, item, col): def GetValue(self, item, col):
# Return the value to be displayed for this item and column. For this # Return the value to be displayed for this item and column. For this
# example we'll just pull the values from the data objects we # example we'll just pull the values from the data objects we
# associated with the items in GetChildren. # associated with the items in GetChildren.
# Fetch the data object for this item. # Fetch the data object for this item.
node = self.ItemToObject(item) node = self.ItemToObject(item)
if isinstance(node, Genre): if isinstance(node, Genre):
# We'll only use the first column for the Genre objects, # We'll only use the first column for the Genre objects,
# for the other columns lets just return empty values # for the other columns lets just return empty values
@@ -156,8 +156,8 @@ class MyTreeListModel(dv.PyDataViewModel):
5 : False, 5 : False,
} }
return mapper[col] return mapper[col]
elif isinstance(node, Song): elif isinstance(node, Song):
mapper = { 0 : node.genre, mapper = { 0 : node.genre,
1 : node.artist, 1 : node.artist,
@@ -167,10 +167,10 @@ class MyTreeListModel(dv.PyDataViewModel):
5 : node.like, 5 : node.like,
} }
return mapper[col] return mapper[col]
else: else:
raise RuntimeError("unknown node type") raise RuntimeError("unknown node type")
def GetAttr(self, item, col, attr): def GetAttr(self, item, col, attr):
@@ -181,14 +181,14 @@ class MyTreeListModel(dv.PyDataViewModel):
attr.SetBold(True) attr.SetBold(True)
return True return True
return False return False
def SetValue(self, value, item, col): def SetValue(self, value, item, col):
self.log.write("SetValue: col %d, %s\n" % (col, value)) self.log.write("SetValue: col %d, %s\n" % (col, value))
# We're not allowing edits in column zero (see below) so we just need # We're not allowing edits in column zero (see below) so we just need
# to deal with Song objects and cols 1 - 5 # to deal with Song objects and cols 1 - 5
node = self.ItemToObject(item) node = self.ItemToObject(item)
if isinstance(node, Song): if isinstance(node, Song):
if col == 1: if col == 1:
@@ -218,17 +218,17 @@ class TestPanel(wx.Panel):
| dv.DV_VERT_RULES | dv.DV_VERT_RULES
| dv.DV_MULTIPLE | dv.DV_MULTIPLE
) )
# Create an instance of our model... # Create an instance of our model...
if model is None: if model is None:
self.model = MyTreeListModel(data, log) self.model = MyTreeListModel(data, log)
else: else:
self.model = model self.model = model
# Tel the DVC to use the model # Tel the DVC to use the model
self.dvc.AssociateModel(self.model) self.dvc.AssociateModel(self.model)
# Define the columns that we want in the view. Notice the # Define the columns that we want in the view. Notice the
# parameter which tells the view which col in the data model to pull # parameter which tells the view which col in the data model to pull
# values from for each view column. # values from for each view column.
if 0: if 0:
@@ -240,46 +240,46 @@ class TestPanel(wx.Panel):
self.dvc.AppendColumn(c0) self.dvc.AppendColumn(c0)
else: else:
self.dvc.AppendTextColumn("Genre", 0, width=80) self.dvc.AppendTextColumn("Genre", 0, width=80)
c1 = self.dvc.AppendTextColumn("Artist", 1, width=170, mode=dv.DATAVIEW_CELL_EDITABLE) c1 = self.dvc.AppendTextColumn("Artist", 1, width=170, mode=dv.DATAVIEW_CELL_EDITABLE)
c2 = self.dvc.AppendTextColumn("Title", 2, width=260, mode=dv.DATAVIEW_CELL_EDITABLE) c2 = self.dvc.AppendTextColumn("Title", 2, width=260, mode=dv.DATAVIEW_CELL_EDITABLE)
c3 = self.dvc.AppendDateColumn('Acquired', 4, width=100, mode=dv.DATAVIEW_CELL_ACTIVATABLE) c3 = self.dvc.AppendDateColumn('Acquired', 4, width=100, mode=dv.DATAVIEW_CELL_ACTIVATABLE)
c4 = self.dvc.AppendToggleColumn('Like', 5, width=40, mode=dv.DATAVIEW_CELL_ACTIVATABLE) c4 = self.dvc.AppendToggleColumn('Like', 5, width=40, mode=dv.DATAVIEW_CELL_ACTIVATABLE)
# Notice how we pull the data from col 3, but this is the 6th col # Notice how we pull the data from col 3, but this is the 6th col
# added to the DVC. The order of the view columns is not dependent on # added to the DVC. The order of the view columns is not dependent on
# the order of the model columns at all. # the order of the model columns at all.
c5 = self.dvc.AppendTextColumn("id", 3, width=40, mode=dv.DATAVIEW_CELL_EDITABLE) c5 = self.dvc.AppendTextColumn("id", 3, width=40, mode=dv.DATAVIEW_CELL_EDITABLE)
c5.Alignment = wx.ALIGN_RIGHT c5.Alignment = wx.ALIGN_RIGHT
# Set some additional attributes for all the columns # Set some additional attributes for all the columns
for c in self.dvc.Columns: for c in self.dvc.Columns:
c.Sortable = True c.Sortable = True
c.Reorderable = True c.Reorderable = True
self.Sizer = wx.BoxSizer(wx.VERTICAL) self.Sizer = wx.BoxSizer(wx.VERTICAL)
self.Sizer.Add(self.dvc, 1, wx.EXPAND) self.Sizer.Add(self.dvc, 1, wx.EXPAND)
b1 = wx.Button(self, label="New View", name="newView") b1 = wx.Button(self, label="New View", name="newView")
self.Bind(wx.EVT_BUTTON, self.OnNewView, b1) self.Bind(wx.EVT_BUTTON, self.OnNewView, b1)
self.Sizer.Add(b1, 0, wx.ALL, 5) self.Sizer.Add(b1, 0, wx.ALL, 5)
def OnNewView(self, evt): def OnNewView(self, evt):
f = wx.Frame(None, title="New view, shared model", size=(600,400)) f = wx.Frame(None, title="New view, shared model", size=(600,400))
TestPanel(f, self.log, model=self.model) TestPanel(f, self.log, model=self.model)
b = f.FindWindowByName("newView") b = f.FindWindowByName("newView")
b.Disable() b.Disable()
f.Show() f.Show()
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def main(): def main():
from data import musicdata from data import musicdata
# our data structure will be a collection of Genres, each of which is a # our data structure will be a collection of Genres, each of which is a
# collection of Songs # collection of Songs
data = dict() data = dict()
@@ -297,11 +297,11 @@ def main():
pnl = TestPanel(frm, sys.stdout, data=data) pnl = TestPanel(frm, sys.stdout, data=data)
frm.Show() frm.Show()
app.MainLoop() app.MainLoop()
#---------------------------------------------------------------------- #----------------------------------------------------------------------
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@@ -46,7 +46,7 @@ class TestModel(dv.DataViewIndexListModel):
def GetCount(self): def GetCount(self):
#self.log.write('GetCount') #self.log.write('GetCount')
return len(self.data) return len(self.data)
# Called to check if non-standard attributes should be used in the # Called to check if non-standard attributes should be used in the
# cell at (row, col) # cell at (row, col)
def GetAttrByRow(self, row, col, attr): def GetAttrByRow(self, row, col, attr):
@@ -74,28 +74,28 @@ class TestModel(dv.DataViewIndexListModel):
else: else:
return cmp(self.data[row1][col], self.data[row2][col]) return cmp(self.data[row1][col], self.data[row2][col])
def DeleteRows(self, rows): def DeleteRows(self, rows):
# make a copy since we'll be sorting(mutating) the list # make a copy since we'll be sorting(mutating) the list
rows = list(rows) rows = list(rows)
# use reverse order so the indexes don't change as we remove items # use reverse order so the indexes don't change as we remove items
rows.sort(reverse=True) rows.sort(reverse=True)
for row in rows: for row in rows:
# remove it from our data structure # remove it from our data structure
del self.data[row] del self.data[row]
# notify the view(s) using this model that it has been removed # notify the view(s) using this model that it has been removed
self.RowDeleted(row) self.RowDeleted(row)
def AddRow(self, value): def AddRow(self, value):
# update data structure # update data structure
self.data.append(value) self.data.append(value)
# notify views # notify views
self.RowAppended() self.RowAppended()
class TestPanel(wx.Panel): class TestPanel(wx.Panel):
def __init__(self, parent, log, model=None, data=None): def __init__(self, parent, log, model=None, data=None):
self.log = log self.log = log
@@ -109,12 +109,12 @@ class TestPanel(wx.Panel):
| dv.DV_VERT_RULES | dv.DV_VERT_RULES
| dv.DV_MULTIPLE | dv.DV_MULTIPLE
) )
# Create an instance of our simple model... # Create an instance of our simple model...
if model is None: if model is None:
self.model = TestModel(data, log) self.model = TestModel(data, log)
else: else:
self.model = model self.model = model
# ...and associate it with the dataview control. Models can # ...and associate it with the dataview control. Models can
# be shared between multiple DataViewCtrls, so this does not # be shared between multiple DataViewCtrls, so this does not
@@ -158,9 +158,9 @@ class TestPanel(wx.Panel):
c0.Reorderable = False c0.Reorderable = False
# set the Sizer property (same as SetSizer) # set the Sizer property (same as SetSizer)
self.Sizer = wx.BoxSizer(wx.VERTICAL) self.Sizer = wx.BoxSizer(wx.VERTICAL)
self.Sizer.Add(self.dvc, 1, wx.EXPAND) self.Sizer.Add(self.dvc, 1, wx.EXPAND)
# Add some buttons to help out with the tests # Add some buttons to help out with the tests
b1 = wx.Button(self, label="New View", name="newView") b1 = wx.Button(self, label="New View", name="newView")
self.Bind(wx.EVT_BUTTON, self.OnNewView, b1) self.Bind(wx.EVT_BUTTON, self.OnNewView, b1)
@@ -196,7 +196,7 @@ class TestPanel(wx.Panel):
rows = [self.model.GetRow(item) for item in items] rows = [self.model.GetRow(item) for item in items]
self.model.DeleteRows(rows) self.model.DeleteRows(rows)
def OnAddRow(self, evt): def OnAddRow(self, evt):
# Add some bogus data to a new row in the model's data # Add some bogus data to a new row in the model's data
id = len(self.model.data) + 1 id = len(self.model.data) + 1
@@ -205,7 +205,7 @@ class TestPanel(wx.Panel):
'new title %d' % id, 'new title %d' % id,
'genre %d' % id] 'genre %d' % id]
self.model.AddRow(value) self.model.AddRow(value)
def OnEditingDone(self, evt): def OnEditingDone(self, evt):
self.log.write("OnEditingDone\n") self.log.write("OnEditingDone\n")
@@ -213,18 +213,18 @@ class TestPanel(wx.Panel):
def OnValueChanged(self, evt): def OnValueChanged(self, evt):
self.log.write("OnValueChanged\n") self.log.write("OnValueChanged\n")
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def main(): def main():
from data import musicdata from data import musicdata
app = wx.App() app = wx.App()
frm = wx.Frame(None, title="IndexListModel sample", size=(700,500)) frm = wx.Frame(None, title="IndexListModel sample", size=(700,500))
pnl = TestPanel(frm, sys.stdout, data=musicdata) pnl = TestPanel(frm, sys.stdout, data=musicdata)
frm.Show() frm.Show()
app.MainLoop() app.MainLoop()
#---------------------------------------------------------------------- #----------------------------------------------------------------------

View File

@@ -44,16 +44,16 @@ ID_TEST = 500
class DrawFrame(wx.Frame): class DrawFrame(wx.Frame):
def __init__(self,parent, id,title,position,size): def __init__(self,parent, id,title,position,size):
wx.Frame.__init__(self,parent, id,title,position, size) wx.Frame.__init__(self,parent, id,title,position, size)
## Set up the MenuBar ## Set up the MenuBar
MenuBar = wx.MenuBar() MenuBar = wx.MenuBar()
file_menu = wx.Menu() file_menu = wx.Menu()
exit = file_menu.Append(wx.ID_EXIT, "", "Terminate the program") exit = file_menu.Append(wx.ID_EXIT, "", "Terminate the program")
self.Bind(wx.EVT_MENU, self.OnQuit, exit) self.Bind(wx.EVT_MENU, self.OnQuit, exit)
MenuBar.Append(file_menu, "&File") MenuBar.Append(file_menu, "&File")
draw_menu = wx.Menu() draw_menu = wx.Menu()
draw = draw_menu.Append(wx.ID_ANY, draw = draw_menu.Append(wx.ID_ANY,
"&Draw Test", "&Draw Test",
@@ -65,68 +65,68 @@ class DrawFrame(wx.Frame):
clear = draw_menu.Append(wx.ID_ANY, "&Clear","Clear the Canvas") clear = draw_menu.Append(wx.ID_ANY, "&Clear","Clear the Canvas")
self.Bind(wx.EVT_MENU, self.Clear, clear) self.Bind(wx.EVT_MENU, self.Clear, clear)
MenuBar.Append(draw_menu, "&Draw") MenuBar.Append(draw_menu, "&Draw")
view_menu = wx.Menu() view_menu = wx.Menu()
zoom = view_menu.Append(wx.ID_ANY, "Zoom to &Fit","Zoom to fit the window") zoom = view_menu.Append(wx.ID_ANY, "Zoom to &Fit","Zoom to fit the window")
self.Bind(wx.EVT_MENU, self.ZoomToFit, zoom) self.Bind(wx.EVT_MENU, self.ZoomToFit, zoom)
MenuBar.Append(view_menu, "&View") MenuBar.Append(view_menu, "&View")
help_menu = wx.Menu() help_menu = wx.Menu()
about = help_menu.Append(wx.ID_ABOUT, "", about = help_menu.Append(wx.ID_ABOUT, "",
"More information About this program") "More information About this program")
self.Bind(wx.EVT_MENU, self.OnAbout, about) self.Bind(wx.EVT_MENU, self.OnAbout, about)
MenuBar.Append(help_menu, "&Help") MenuBar.Append(help_menu, "&Help")
self.SetMenuBar(MenuBar) self.SetMenuBar(MenuBar)
self.CreateStatusBar() self.CreateStatusBar()
self.SetStatusText("") self.SetStatusText("")
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
# Other event handlers: # Other event handlers:
self.Bind(wx.EVT_RIGHT_DOWN, self.RightButtonEvent) self.Bind(wx.EVT_RIGHT_DOWN, self.RightButtonEvent)
# Add the Canvas # Add the Canvas
self.Canvas = NavCanvas.NavCanvas(self,-1,(500,500), self.Canvas = NavCanvas.NavCanvas(self,-1,(500,500),
Debug = False, Debug = False,
BackgroundColor = "WHITE").Canvas BackgroundColor = "WHITE").Canvas
self.Canvas.NumBetweenBlits = 1000 self.Canvas.NumBetweenBlits = 1000
self.Show(True) self.Show(True)
self.DrawTest(None) self.DrawTest(None)
return None return None
def RightButtonEvent(self,event): def RightButtonEvent(self,event):
print("Right Button has been clicked in DrawFrame") print("Right Button has been clicked in DrawFrame")
print("coords are: %i, %i"%(event.GetX(),event.GetY())) print("coords are: %i, %i"%(event.GetX(),event.GetY()))
event.Skip() event.Skip()
def OnAbout(self, event): def OnAbout(self, event):
dlg = wx.MessageDialog(self, "This is a small program to demonstrate\n" dlg = wx.MessageDialog(self, "This is a small program to demonstrate\n"
"the use of the FloatCanvas\n", "the use of the FloatCanvas\n",
"About Me", wx.OK | wx.ICON_INFORMATION) "About Me", wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal() dlg.ShowModal()
dlg.Destroy() dlg.Destroy()
def ZoomToFit(self,event): def ZoomToFit(self,event):
self.Canvas.ZoomToBB() self.Canvas.ZoomToBB()
def Clear(self,event = None): def Clear(self,event = None):
self.Canvas.ClearAll() self.Canvas.ClearAll()
self.Canvas.Draw() self.Canvas.Draw()
def OnQuit(self,event): def OnQuit(self,event):
self.Close(True) self.Close(True)
def OnCloseWindow(self, event): def OnCloseWindow(self, event):
self.Destroy() self.Destroy()
def DrawTest(self,event = None): def DrawTest(self,event = None):
import random import random
import numpy.random as RandomArray import numpy.random as RandomArray
Range = (-10,10) Range = (-10,10)
colors = ["AQUAMARINE", "BLACK", "BLUE", "BLUE VIOLET", "BROWN", colors = ["AQUAMARINE", "BLACK", "BLUE", "BLUE VIOLET", "BROWN",
@@ -143,7 +143,7 @@ class DrawFrame(wx.Frame):
"ORCHID", "PALE GREEN", "PINK", "PLUM", "PURPLE", "RED", "ORCHID", "PALE GREEN", "PINK", "PLUM", "PURPLE", "RED",
"SALMON", "SEA GREEN", "SIENNA", "SKY BLUE", "SLATE BLUE", "SALMON", "SEA GREEN", "SIENNA", "SKY BLUE", "SLATE BLUE",
"SPRING GREEN", "STEEL BLUE", "TAN", "THISTLE", "TURQUOISE", "SPRING GREEN", "STEEL BLUE", "TAN", "THISTLE", "TURQUOISE",
"VIOLET", "VIOLET RED", "WHEAT", "WHITE", "YELLOW", "YELLOW GREEN"] "VIOLET", "VIOLET RED", "WHEAT", "WHITE", "YELLOW", "YELLOW GREEN"]
Canvas = self.Canvas Canvas = self.Canvas
# Some Polygons in the background: # Some Polygons in the background:
@@ -161,17 +161,17 @@ class DrawFrame(wx.Frame):
FillColor = colors[cf], FillColor = colors[cf],
FillStyle = 'Solid', FillStyle = 'Solid',
InForeground = False) InForeground = False)
## Pointset ## Pointset
print("Adding Points to Foreground" ) print("Adding Points to Foreground" )
for i in range(1): for i in range(1):
points = RandomArray.uniform(-100,100,(1000,2)) points = RandomArray.uniform(-100,100,(1000,2))
D = 2 D = 2
self.LEs = self.Canvas.AddPointSet(points, Color = "Black", Diameter = D, InForeground = True) self.LEs = self.Canvas.AddPointSet(points, Color = "Black", Diameter = D, InForeground = True)
self.Canvas.AddRectangle((-200,-200), (400,400)) self.Canvas.AddRectangle((-200,-200), (400,400))
Canvas.ZoomToBB() Canvas.ZoomToBB()
def RunMovie(self,event = None): def RunMovie(self,event = None):
import numpy.random as RandomArray import numpy.random as RandomArray
start = clock() start = clock()
@@ -184,80 +184,80 @@ class DrawFrame(wx.Frame):
self.Canvas.Draw() self.Canvas.Draw()
wx.GetApp().Yield(True) wx.GetApp().Yield(True)
print("running the movie took %f seconds"%(clock() - start)) print("running the movie took %f seconds"%(clock() - start))
class DemoApp(wx.App): class DemoApp(wx.App):
""" """
How the demo works: How the demo works:
Under the Draw menu, there are three options: Under the Draw menu, there are three options:
*Draw Test: will put up a picture of a bunch of randomly generated *Draw Test: will put up a picture of a bunch of randomly generated
objects, of each kind supported. objects, of each kind supported.
*Draw Map: will draw a map of the world. Be patient, it is a big map, *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 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 on my 450Mhz PIII). Redraws take about 2 sec. This demonstrates how the
performance is not very good for large drawings. performance is not very good for large drawings.
*Clear: Clears the Canvas. *Clear: Clears the Canvas.
Once you have a picture drawn, you can zoom in and out and move about 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 the picture. There is a tool bar with three tools that can be
selected. selected.
The magnifying glass with the plus is the zoom in tool. Once 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 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 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. 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, 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 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, 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 as it has a LOT of lines to be drawn. The image is double buffered, so
you don't see the drawing in progress) you don't see the drawing in progress)
The hand is the move tool. Once selected, if you click and drag on the 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 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 release the mouse. Nothing is changed while you are dragging. The
drawing is too slow for that. drawing is too slow for that.
I'd like the cursor to change as you change tools, but the stock I'd like the cursor to change as you change tools, but the stock
wx.Cursors didn't include anything I liked, so I stuck with the wx.Cursors didn't include anything I liked, so I stuck with the
pointer. Pleae let me know if you have any nice cursor images for me to pointer. Pleae let me know if you have any nice cursor images for me to
use. use.
Any bugs, comments, feedback, questions, and especially code are welcome: Any bugs, comments, feedback, questions, and especially code are welcome:
-Chris Barker -Chris Barker
ChrisHBarker@home.net ChrisHBarker@home.net
http://members.home.net/barkerlohmann http://members.home.net/barkerlohmann
""" """
def OnInit(self): def OnInit(self):
frame = DrawFrame(None, -1, "Simple Drawing Window",wx.DefaultPosition, (700,700) ) frame = DrawFrame(None, -1, "Simple Drawing Window",wx.DefaultPosition, (700,700) )
self.SetTopWindow(frame) self.SetTopWindow(frame)
return True return True
def Read_MapGen(filename,stats = False): def Read_MapGen(filename,stats = False):
""" """
This function reads a MapGen Format file, and This function reads a MapGen Format file, and
returns a list of NumPy arrays with the line segments in them. 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. 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 The demo should have come with a file, "world.dat" that is the
shorelines of the whole worls, in MapGen format. shorelines of the whole worls, in MapGen format.
""" """
from numpy import array from numpy import array
file = open(filename,'rt') file = open(filename,'rt')
data = file.readlines() data = file.readlines()
data = [s.strip() for s in data] data = [s.strip() for s in data]
Shorelines = [] Shorelines = []
segment = [] segment = []
@@ -268,7 +268,7 @@ def Read_MapGen(filename,stats = False):
else: else:
segment.append(map(float,string.split(line))) segment.append(map(float,string.split(line)))
if segment: Shorelines.append(array(segment)) if segment: Shorelines.append(array(segment))
if stats: if stats:
NumSegments = len(Shorelines) NumSegments = len(Shorelines)
NumPoints = False NumPoints = False
@@ -277,20 +277,20 @@ def Read_MapGen(filename,stats = False):
AvgPoints = NumPoints / NumSegments AvgPoints = NumPoints / NumSegments
print("Number of Segments: ", NumSegments) print("Number of Segments: ", NumSegments)
print("Average Number of Points per segment: ",AvgPoints) print("Average Number of Points per segment: ",AvgPoints)
return Shorelines return Shorelines
if __name__ == "__main__": if __name__ == "__main__":
app = DemoApp(0) app = DemoApp(0)
app.MainLoop() app.MainLoop()

View File

@@ -29,8 +29,8 @@ def BB_HitTest(self, event, HitEvent):
xy = self.PixelToWorld( xy_p ) #Convert to the correct coords xy = self.PixelToWorld( xy_p ) #Convert to the correct coords
for key2 in self.HitDict[HitEvent].keys(): for key2 in self.HitDict[HitEvent].keys():
#Get Mouse Event Position #Get Mouse Event Position
bb = self.HitDict[HitEvent][key2].BoundingBox bb = self.HitDict[HitEvent][key2].BoundingBox
if bb.PointInside(xy): if bb.PointInside(xy):
Object = self.HitDict[HitEvent][key2] Object = self.HitDict[HitEvent][key2]
objects.append(Object) objects.append(Object)
try: try:
@@ -44,7 +44,7 @@ def BB_HitTest(self, event, HitEvent):
Object = self.HitDict[HitEvent][key2] Object = self.HitDict[HitEvent][key2]
if len(objects) > 0: #If no objects then do nothing if len(objects) > 0: #If no objects then do nothing
#Get the highest index object #Get the highest index object
highest_object = objects[object_index_list.index(max(object_index_list))] highest_object = objects[object_index_list.index(max(object_index_list))]
highest_object.HitCoords = xy highest_object.HitCoords = xy
highest_object.HitCoordsPixel = xy_p highest_object.HitCoordsPixel = xy_p
highest_object.CallBackFuncs[HitEvent](highest_object) highest_object.CallBackFuncs[HitEvent](highest_object)
@@ -74,10 +74,10 @@ class DrawFrame(wx.Frame):
Debug = 0, Debug = 0,
BackgroundColor = "DARK SLATE BLUE", BackgroundColor = "DARK SLATE BLUE",
).Canvas ).Canvas
self.Canvas = Canvas self.Canvas = Canvas
self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove) self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove)
Point = (45,40) Point = (45,40)
Text = Canvas.AddScaledText("A String", Text = Canvas.AddScaledText("A String",
@@ -118,10 +118,10 @@ class DrawFrame(wx.Frame):
app = wx.App(False) app = wx.App(False)
F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) ) F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) )
app.MainLoop() app.MainLoop()

View File

@@ -40,7 +40,7 @@ class BNAData:
self.Types = None self.Types = None
if Filename is not None: if Filename is not None:
self.Load(Filename) self.Load(Filename)
def __getitem__(self,index): def __getitem__(self,index):
return (self.PointsData[index], self.Names[index]) return (self.PointsData[index], self.Names[index])
@@ -121,7 +121,7 @@ class DrawFrame(wx.Frame):
self.SetMenuBar(MenuBar) self.SetMenuBar(MenuBar)
self.CreateStatusBar() self.CreateStatusBar()
# Add the Canvas # Add the Canvas
self.Canvas = NavCanvas.NavCanvas(self,-1,(500,500), self.Canvas = NavCanvas.NavCanvas(self,-1,(500,500),
Debug = 0, Debug = 0,
@@ -130,8 +130,8 @@ class DrawFrame(wx.Frame):
wx.EVT_CLOSE(self, self.OnCloseWindow) wx.EVT_CLOSE(self, self.OnCloseWindow)
FloatCanvas.EVT_MOTION(self.Canvas, self.OnMove ) FloatCanvas.EVT_MOTION(self.Canvas, self.OnMove )
FloatCanvas.EVT_LEFT_UP(self.Canvas, self.OnLeftUp ) FloatCanvas.EVT_LEFT_UP(self.Canvas, self.OnLeftUp )
FloatCanvas.EVT_LEFT_DOWN(self.Canvas, self.OnLeftDown) FloatCanvas.EVT_LEFT_DOWN(self.Canvas, self.OnLeftDown)
try: try:
@@ -153,7 +153,7 @@ class DrawFrame(wx.Frame):
if self.SelectedPoly: if self.SelectedPoly:
self.DeSelectPoly() self.DeSelectPoly()
self.Canvas.Draw() self.Canvas.Draw()
def OnAbout(self, event): def OnAbout(self, event):
dlg = wx.MessageDialog(self, "This is a small program to demonstrate\n" dlg = wx.MessageDialog(self, "This is a small program to demonstrate\n"
"the use of the FloatCanvas\n", "the use of the FloatCanvas\n",
@@ -244,7 +244,7 @@ class DrawFrame(wx.Frame):
Canvas.RemoveObject(self.SelectedPoly) Canvas.RemoveObject(self.SelectedPoly)
Canvas.RemoveObject(self.SelectedPoints) Canvas.RemoveObject(self.SelectedPoints)
self.ResetSelections() self.ResetSelections()
def SelectPoly(self, Object): def SelectPoly(self, Object):
Canvas = self.Canvas Canvas = self.Canvas
if Object is self.SelectedPolyOrig: if Object is self.SelectedPolyOrig:
@@ -306,7 +306,7 @@ class BNAEditor(wx.App):
""" """
Once you have a picture drawn, you can zoom in and out and move about 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 the picture. There is a tool bar with three tools that can be
selected. selected.
""" """
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
@@ -329,10 +329,10 @@ class BNAEditor(wx.App):
app = BNAEditor(False)# put in True if you want output to go to it's own window. app = BNAEditor(False)# put in True if you want output to go to it's own window.
app.MainLoop() app.MainLoop()

View File

@@ -20,12 +20,12 @@ MaxValue = 2000
def YScaleFun(center): def YScaleFun(center):
""" """
Function that returns a scaling vector to scale y data to same range as x data Function that returns a scaling vector to scale y data to same range as x data
This is used by FloatCanvas as a "projection function", so that you can have This is used by FloatCanvas as a "projection function", so that you can have
a different scale for X and Y. With the default projection, X and Y are the same scale. a different scale for X and Y. With the default projection, X and Y are the same scale.
""" """
# center gets ignored in this case # center gets ignored in this case
return N.array((1, float(NumChannels)/MaxValue), N.float) return N.array((1, float(NumChannels)/MaxValue), N.float)
@@ -34,7 +34,7 @@ def ScaleWorldToPixel(self, Lengths):
This is a new version of a function that will get passed to the This is a new version of a function that will get passed to the
drawing functions of the objects, to Change a length from world to drawing functions of the objects, to Change a length from world to
pixel coordinates. pixel coordinates.
This version uses the "ceil" function, so that fractional pixel get This version uses the "ceil" function, so that fractional pixel get
rounded up, rather than down. rounded up, rather than down.
@@ -63,14 +63,14 @@ class DrawFrame(wx.Frame):
BackgroundColor = "DARK SLATE BLUE", BackgroundColor = "DARK SLATE BLUE",
ProjectionFun = YScaleFun, ProjectionFun = YScaleFun,
) )
self.Canvas = Canvas = NC.Canvas self.Canvas = Canvas = NC.Canvas
#self.Canvas.ScaleWorldToPixel = ScaleWorldToPixel #self.Canvas.ScaleWorldToPixel = ScaleWorldToPixel
self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove) self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove)
self.Values = random.randint(0, MaxValue, (NumChannels,)) self.Values = random.randint(0, MaxValue, (NumChannels,))
self.Bars = [] self.Bars = []
self.BarWidth = 0.75 self.BarWidth = 0.75
# add an X axis # add an X axis
@@ -88,7 +88,7 @@ class DrawFrame(wx.Frame):
FillStyle = "Solid", FillStyle = "Solid",
) )
self.Bars.append(bar) self.Bars.append(bar)
# Add a couple a button the Toolbar # Add a couple a button the Toolbar
tb = NC.ToolBar tb = NC.ToolBar
@@ -106,7 +106,7 @@ class DrawFrame(wx.Frame):
self.Show() self.Show()
Canvas.ZoomToBB() Canvas.ZoomToBB()
Canvas.Draw(True) Canvas.Draw(True)
def OnMove(self, event): def OnMove(self, event):
""" """
@@ -118,7 +118,7 @@ class DrawFrame(wx.Frame):
channel = "%i,"%(channel+1) channel = "%i,"%(channel+1)
else: else:
channel = "" channel = ""
if value >=0: if value >=0:
value = "%3g"%value value = "%3g"%value
else: else:
@@ -128,16 +128,16 @@ class DrawFrame(wx.Frame):
def ResetData(self, event): def ResetData(self, event):
self.Values = random.randint(0, MaxValue, (NumChannels,)) self.Values = random.randint(0, MaxValue, (NumChannels,))
for i, bar in enumerate(self.Bars): for i, bar in enumerate(self.Bars):
bar.SetShape(bar.XY, (self.BarWidth, self.Values[i])) bar.SetShape(bar.XY, (self.BarWidth, self.Values[i]))
self.Canvas.Draw(Force=True) self.Canvas.Draw(Force=True)
app = wx.App(False) app = wx.App(False)
F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) ) F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) )
app.MainLoop() app.MainLoop()

View File

@@ -32,7 +32,7 @@ FC = FloatCanvas
class MovingObjectMixin: # Borrowed from MovingElements.py class MovingObjectMixin: # Borrowed from MovingElements.py
""" """
Methods required for a Moving object Methods required for a Moving object
""" """
def GetOutlinePoints(self): def GetOutlinePoints(self):
@@ -57,22 +57,22 @@ class Ball(MovingObjectMixin, FloatCanvas.Circle):
class DrawFrame(wx.Frame): class DrawFrame(wx.Frame):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs) wx.Frame.__init__(self, *args, **kwargs)
## Set up the MenuBar ## Set up the MenuBar
MenuBar = wx.MenuBar() MenuBar = wx.MenuBar()
file_menu = wx.Menu() file_menu = wx.Menu()
item = file_menu.Append(wx.ID_EXIT, "","Terminate the program") item = file_menu.Append(wx.ID_EXIT, "","Terminate the program")
self.Bind(wx.EVT_MENU, self.OnQuit, item) self.Bind(wx.EVT_MENU, self.OnQuit, item)
MenuBar.Append(file_menu, "&File") MenuBar.Append(file_menu, "&File")
self.SetMenuBar(MenuBar) self.SetMenuBar(MenuBar)
self.CreateStatusBar() self.CreateStatusBar()
self.SetStatusText("") self.SetStatusText("")
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
# Add the buttons # Add the buttons
@@ -81,7 +81,7 @@ class DrawFrame(wx.Frame):
StartButton = wx.Button(self, label="Start") StartButton = wx.Button(self, label="Start")
StartButton.Bind(wx.EVT_BUTTON, self.OnStart) StartButton.Bind(wx.EVT_BUTTON, self.OnStart)
StopButton = wx.Button(self, label="Stop") StopButton = wx.Button(self, label="Stop")
StopButton.Bind(wx.EVT_BUTTON, self.OnStop) StopButton.Bind(wx.EVT_BUTTON, self.OnStop)
@@ -93,7 +93,7 @@ class DrawFrame(wx.Frame):
NC = NavCanvas.NavCanvas(self, -1, (500,500), NC = NavCanvas.NavCanvas(self, -1, (500,500),
Debug = False, Debug = False,
BackgroundColor = "BLUE") BackgroundColor = "BLUE")
self.Canvas = NC.Canvas self.Canvas = NC.Canvas
self.Initialize(None) self.Initialize(None)
@@ -107,30 +107,30 @@ class DrawFrame(wx.Frame):
self.Bind(wx.EVT_TIMER, self.MoveBall, self.timer) self.Bind(wx.EVT_TIMER, self.MoveBall, self.timer)
self.Show(True) self.Show(True)
def OnQuit(self,event): def OnQuit(self,event):
self.timer.Stop() self.timer.Stop()
self.Close(True) self.Close(True)
def OnCloseWindow(self, event): def OnCloseWindow(self, event):
self.Destroy() self.Destroy()
def Initialize(self, event=None): def Initialize(self, event=None):
Canvas = self.Canvas Canvas = self.Canvas
#Add the floor #Add the floor
Canvas.AddLine(( (0, 0), (100, 0) ), LineWidth=4, LineColor="Black") Canvas.AddLine(( (0, 0), (100, 0) ), LineWidth=4, LineColor="Black")
# add the wall: # add the wall:
Canvas.AddRectangle( (0,0), (10,50), FillColor='green') Canvas.AddRectangle( (0,0), (10,50), FillColor='green')
# add the ball: # add the ball:
self.Ball = Ball( (5, 52), (2, 0), InForeground=True ) self.Ball = Ball( (5, 52), (2, 0), InForeground=True )
Canvas.AddObject( self.Ball ) Canvas.AddObject( self.Ball )
# to capture the mouse to move the ball # to capture the mouse to move the ball
self.Ball.Bind(FC.EVT_FC_LEFT_DOWN, self.BallHit) self.Ball.Bind(FC.EVT_FC_LEFT_DOWN, self.BallHit)
Canvas.Bind(FC.EVT_MOTION, self.OnMove ) Canvas.Bind(FC.EVT_MOTION, self.OnMove )
Canvas.Bind(FC.EVT_LEFT_UP, self.OnLeftUp ) Canvas.Bind(FC.EVT_LEFT_UP, self.OnLeftUp )
wx.CallAfter(Canvas.ZoomToBB) wx.CallAfter(Canvas.ZoomToBB)
def BallHit(self, object): def BallHit(self, object):
@@ -150,12 +150,12 @@ class DrawFrame(wx.Frame):
def OnLeftUp(self, event): def OnLeftUp(self, event):
self.Ball.Moving = False self.Ball.Moving = False
def OnReset(self, event=None): def OnReset(self, event=None):
self.Ball.SetPoint( (5, 52) ) self.Ball.SetPoint( (5, 52) )
self.Ball.Velocity = np.array((1.5, 0.0)) self.Ball.Velocity = np.array((1.5, 0.0))
self.Canvas.Draw(True) self.Canvas.Draw(True)
def OnStart(self, event=None): def OnStart(self, event=None):
self.timer.Start(20) self.timer.Start(20)
@@ -171,7 +171,7 @@ class DrawFrame(wx.Frame):
A = np.pi*(ball.Radius/100)**2 # radius in cm A = np.pi*(ball.Radius/100)**2 # radius in cm
Cd = 0.47 Cd = 0.47
rho = 1.3 rho = 1.3
if not ball.Moving: # don't do this if the user is moving it if not ball.Moving: # don't do this if the user is moving it
vel = ball.Velocity vel = ball.Velocity
pos = ball.XY pos = ball.XY
@@ -179,9 +179,9 @@ class DrawFrame(wx.Frame):
# apply drag # apply drag
vel -= np.sign(vel) * ((0.5 * Cd * rho * A * vel**2) / m * dt) vel -= np.sign(vel) * ((0.5 * Cd * rho * A * vel**2) / m * dt)
# apply gravity # apply gravity
vel[1] -= g * dt vel[1] -= g * dt
# move the ball # move the ball
pos += dt * vel pos += dt * vel
# check if it's on the wall # check if it's on the wall
if pos[1] <= 52. and pos[0] <= 10.: if pos[1] <= 52. and pos[0] <= 10.:
#reverse velocity #reverse velocity
@@ -193,10 +193,10 @@ class DrawFrame(wx.Frame):
vel[1] *= -1.0 vel[1] *= -1.0
pos[1] = ball.Radius pos[1] = ball.Radius
self.Ball.SetPoint( pos ) self.Ball.SetPoint( pos )
self.Canvas.Draw(True) self.Canvas.Draw(True)
wx.GetApp().Yield(onlyIfNeeded=True) wx.GetApp().Yield(onlyIfNeeded=True)
class DemoApp(wx.App): class DemoApp(wx.App):
def OnInit(self): def OnInit(self):
frame = DrawFrame(None, -1, "Simple Drawing Window",wx.DefaultPosition, (700,700) ) frame = DrawFrame(None, -1, "Simple Drawing Window",wx.DefaultPosition, (700,700) )
@@ -204,10 +204,10 @@ class DemoApp(wx.App):
self.SetTopWindow(frame) self.SetTopWindow(frame)
return True return True
if __name__ == "__main__": if __name__ == "__main__":
app = DemoApp(0) app = DemoApp(0)
app.MainLoop() app.MainLoop()

View File

@@ -36,10 +36,10 @@ class DrawFrame(wx.Frame):
# Debug = 0, # Debug = 0,
# BackgroundColor = "White", # BackgroundColor = "White",
# ) # )
self.Canvas = Canvas self.Canvas = Canvas
self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove ) self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove )
self.Canvas.Bind(FloatCanvas.EVT_LEFT_DOWN, self.OnLeft) self.Canvas.Bind(FloatCanvas.EVT_LEFT_DOWN, self.OnLeft)
@@ -49,7 +49,7 @@ class DrawFrame(wx.Frame):
self.SpaceWidth = 1 self.SpaceWidth = 1
self.Labels = ["SW Tasks", "Set RX Rf"] + ["A Row Label"]*16 self.Labels = ["SW Tasks", "Set RX Rf"] + ["A Row Label"]*16
self.NumRows = len(self.Labels) self.NumRows = len(self.Labels)
self.BuildChartBackground() self.BuildChartBackground()
self.AddLabels() self.AddLabels()
self.Show() self.Show()
@@ -69,20 +69,20 @@ class DrawFrame(wx.Frame):
LineColor = None, LineColor = None,
FillColor = "LightGrey", FillColor = "LightGrey",
FillStyle = "Solid",) FillStyle = "Solid",)
# put a dashed line in every 1 unit: # put a dashed line in every 1 unit:
for i in range(16): for i in range(16):
Canvas.AddLine(((i*self.SpaceWidth,bottom),(i*self.SpaceWidth,top)), Canvas.AddLine(((i*self.SpaceWidth,bottom),(i*self.SpaceWidth,top)),
LineColor = "Black", LineColor = "Black",
LineStyle = "Dot", LineStyle = "Dot",
# or "Dot", "ShortDash", "LongDash","ShortDash", "DotDash" # or "Dot", "ShortDash", "LongDash","ShortDash", "DotDash"
LineWidth = 1,) LineWidth = 1,)
def AddLabels(self): def AddLabels(self):
Canvas = self.Canvas Canvas = self.Canvas
for i, label in enumerate(self.Labels): for i, label in enumerate(self.Labels):
Canvas.AddScaledText(label, Canvas.AddScaledText(label,
( -self.TextWidth, -(i+0.2)*self.LineHeight ), ( -self.TextWidth, -(i+0.2)*self.LineHeight ),
Size = 0.6 * self.LineHeight, Size = 0.6 * self.LineHeight,
Color = "Black", Color = "Black",
BackgroundColor = None, BackgroundColor = None,
@@ -111,10 +111,10 @@ class DrawFrame(wx.Frame):
app = wx.App(False) app = wx.App(False)
F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) ) F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) )
app.MainLoop() app.MainLoop()

View File

@@ -24,9 +24,9 @@ from wx.lib.floatcanvas import NavCanvas, FloatCanvas
#from floatcanvas import FloatCanvas as FC #from floatcanvas import FloatCanvas as FC
colors = [ (255, 0 , 0 ), colors = [ (255, 0 , 0 ),
(0 , 255, 0 ), (0 , 255, 0 ),
(0 , 0, 255), (0 , 0, 255),
(255, 255, 0 ), (255, 255, 0 ),
(255, 0, 255), (255, 0, 255),
(0 , 255, 255), (0 , 255, 255),
@@ -49,11 +49,11 @@ class DrawFrame(wx.Frame):
Debug = 0, Debug = 0,
BackgroundColor = "Black", BackgroundColor = "Black",
) )
self.Canvas = Canvas self.Canvas = Canvas
self.Canvas.Bind(wx.EVT_SIZE, self.OnSize) self.Canvas.Bind(wx.EVT_SIZE, self.OnSize)
# build the squares: # build the squares:
w = 10 w = 10
dx = 14 dx = 14
@@ -104,10 +104,10 @@ class DrawFrame(wx.Frame):
app = wx.App(False) app = wx.App(False)
F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) ) F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) )
app.MainLoop() app.MainLoop()

View File

@@ -42,11 +42,11 @@ class DrawFrame(wx.Frame):
Debug = 0, Debug = 0,
BackgroundColor = "White", BackgroundColor = "White",
).Canvas ).Canvas
self.Show(True) self.Show(True)
self.MakePic() self.MakePic()
return None return None
def MakePic(self): def MakePic(self):
@@ -69,4 +69,4 @@ class DrawFrame(wx.Frame):
app = wx.App() app = wx.App()
DrawFrame(None, -1, "FloatCanvas Demo App", wx.DefaultPosition, (700,700) ) DrawFrame(None, -1, "FloatCanvas Demo App", wx.DefaultPosition, (700,700) )
app.MainLoop() app.MainLoop()

View File

@@ -32,7 +32,7 @@ class DrawFrame(wx.Frame):
def __init__(self,parent, id,title,position,size): def __init__(self,parent, id,title,position,size):
wx.Frame.__init__(self,parent, id,title,position, size) wx.Frame.__init__(self,parent, id,title,position, size)
self.CreateStatusBar() self.CreateStatusBar()
# Add the Canvas # Add the Canvas
NC = NavCanvas.NavCanvas(self, NC = NavCanvas.NavCanvas(self,
size= (500,500), size= (500,500),
@@ -40,10 +40,10 @@ class DrawFrame(wx.Frame):
Debug = 0, Debug = 0,
BackgroundColor = "DARK SLATE BLUE", BackgroundColor = "DARK SLATE BLUE",
) )
self.Canvas = NC.Canvas self.Canvas = NC.Canvas
self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove) self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove)
# Add some buttons to the Toolbar # Add some buttons to the Toolbar
tb = NC.ToolBar tb = NC.ToolBar
@@ -65,7 +65,7 @@ class DrawFrame(wx.Frame):
self.RBBoxMode = GUI.RubberBandBox(self.NewRect) self.RBBoxMode = GUI.RubberBandBox(self.NewRect)
self.Canvas.SetMode(self.RBBoxMode) self.Canvas.SetMode(self.RBBoxMode)
self.Canvas.ZoomToBB() self.Canvas.ZoomToBB()
self.Show(True) self.Show(True)
@@ -102,10 +102,10 @@ class DrawFrame(wx.Frame):
app = wx.App() app = wx.App()
DrawFrame(None, -1, "FloatCanvas Rectangle Drawer", wx.DefaultPosition, (700,700) ) DrawFrame(None, -1, "FloatCanvas Rectangle Drawer", wx.DefaultPosition, (700,700) )
app.MainLoop() app.MainLoop()

View File

@@ -35,8 +35,8 @@ class DrawFrame(wx.Frame):
Debug = 0, Debug = 0,
BackgroundColor = "DARK SLATE BLUE", BackgroundColor = "DARK SLATE BLUE",
).Canvas ).Canvas
Point = (45,40) Point = (45,40)
Box = Canvas.AddCircle(Point, Box = Canvas.AddCircle(Point,
Diameter = 10, Diameter = 10,
@@ -52,7 +52,7 @@ class DrawFrame(wx.Frame):
Canvas.GridUnder = Grid Canvas.GridUnder = Grid
#Canvas.GridOver = Grid #Canvas.GridOver = Grid
Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove ) Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove )
self.Show() self.Show()
Canvas.ZoomToBB() Canvas.ZoomToBB()
@@ -69,10 +69,10 @@ class DrawFrame(wx.Frame):
app = wx.App(False) # true to get its own output window. app = wx.App(False) # true to get its own output window.
F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) ) F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) )
app.MainLoop() app.MainLoop()

View File

@@ -37,7 +37,7 @@ class DrawFrame(wx.Frame):
Canvas = NC.Canvas Canvas = NC.Canvas
self.Canvas = Canvas self.Canvas = Canvas
self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove) self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove)
Point = (45,40) Point = (45,40)
@@ -52,7 +52,7 @@ class DrawFrame(wx.Frame):
self.GroupA.AddObjects((C2,T)) self.GroupA.AddObjects((C2,T))
Canvas.AddObject(self.GroupA) Canvas.AddObject(self.GroupA)
## create another Groups of objects ## create another Groups of objects
R = FloatCanvas.Rectangle((15, 15),(10, 18), FillColor="orange") R = FloatCanvas.Rectangle((15, 15),(10, 18), FillColor="orange")
@@ -63,7 +63,7 @@ class DrawFrame(wx.Frame):
self.GroupB = FloatCanvas.Group((R,E,C,C2,T)) self.GroupB = FloatCanvas.Group((R,E,C,C2,T))
Canvas.AddObject(self.GroupB) Canvas.AddObject(self.GroupB)
self.Groups = {"A":self.GroupA, "B":self.GroupB} self.Groups = {"A":self.GroupA, "B":self.GroupB}
# Add a couple of tools to the Canvas Toolbar # Add a couple of tools to the Canvas Toolbar
@@ -106,10 +106,10 @@ class DrawFrame(wx.Frame):
app = wx.App(False) app = wx.App(False)
F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) ) F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) )
app.MainLoop() app.MainLoop()

View File

@@ -37,7 +37,7 @@ class DrawFrame(wx.Frame):
Canvas = NC.Canvas Canvas = NC.Canvas
self.Canvas = Canvas self.Canvas = Canvas
self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove ) self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove )
Point = (45,40) Point = (45,40)
@@ -52,7 +52,7 @@ class DrawFrame(wx.Frame):
self.GroupA.AddObjects((C2,T)) self.GroupA.AddObjects((C2,T))
Canvas.AddObject(self.GroupA) Canvas.AddObject(self.GroupA)
## create another Groups of objects ## create another Groups of objects
R = FloatCanvas.Rectangle((15, 15),(10, 18), FillColor="orange") R = FloatCanvas.Rectangle((15, 15),(10, 18), FillColor="orange")
@@ -63,7 +63,7 @@ class DrawFrame(wx.Frame):
self.GroupB = FloatCanvas.Group((R,E,C,C2,T)) self.GroupB = FloatCanvas.Group((R,E,C,C2,T))
Canvas.AddObject(self.GroupB) Canvas.AddObject(self.GroupB)
self.Groups = {"A":self.GroupA, "B":self.GroupB} self.Groups = {"A":self.GroupA, "B":self.GroupB}
# Add a couple of tools to the Canvas Toolbar # Add a couple of tools to the Canvas Toolbar
@@ -96,10 +96,10 @@ class DrawFrame(wx.Frame):
app = wx.App(False) app = wx.App(False)
F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) ) F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) )
app.MainLoop() app.MainLoop()

View File

@@ -50,7 +50,7 @@ class DrawFrame(wx.Frame):
def MakeHexagons(self): def MakeHexagons(self):
print("Building %i Hexagons"%NumHexagons) print("Building %i Hexagons"%NumHexagons)
# get a list of colors for random colors # get a list of colors for random colors
wx.lib.colourdb.updateColourDB() wx.lib.colourdb.updateColourDB()
self.colors = wx.lib.colourdb.getColourList() self.colors = wx.lib.colourdb.getColourList()
print("Max colors:", len(self.colors)) print("Max colors:", len(self.colors))
@@ -63,7 +63,7 @@ class DrawFrame(wx.Frame):
(-D , 0), (-D , 0),
(-D/2, h), (-D/2, h),
(D/2 , h), (D/2 , h),
)) ))
Centers = uniform(-100, 100, (NumHexagons, 2)) Centers = uniform(-100, 100, (NumHexagons, 2))
for center in Centers: for center in Centers:
# scale the hexagon # scale the hexagon
@@ -87,10 +87,10 @@ class DrawFrame(wx.Frame):
app = wx.App(False) app = wx.App(False)
DrawFrame(None, -1, "FloatCanvas Demo App", wx.DefaultPosition, (700,700) ) DrawFrame(None, -1, "FloatCanvas Demo App", wx.DefaultPosition, (700,700) )
app.MainLoop() app.MainLoop()

View File

@@ -23,7 +23,7 @@ class DrawFrame(wx.Frame):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs) wx.Frame.__init__(self, *args, **kwargs)
self.CreateStatusBar() self.CreateStatusBar()
# Add the Canvas # Add the Canvas
NC = NavCanvas.NavCanvas(self,-1, NC = NavCanvas.NavCanvas(self,-1,
@@ -33,10 +33,10 @@ class DrawFrame(wx.Frame):
BackgroundColor = "White", BackgroundColor = "White",
) )
self.Canvas = NC.Canvas self.Canvas = NC.Canvas
self.LoadMap(TestFileName) self.LoadMap(TestFileName)
self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove ) self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove )
self.Show() self.Show()
self.Canvas.ZoomToBB() self.Canvas.ZoomToBB()
@@ -73,5 +73,5 @@ class DrawFrame(wx.Frame):
app = wx.App(False) app = wx.App(False)
F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) ) F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) )
app.MainLoop() app.MainLoop()

View File

@@ -30,10 +30,10 @@ class DrawFrame(wx.Frame):
Debug = 0, Debug = 0,
BackgroundColor = "DARK SLATE BLUE", BackgroundColor = "DARK SLATE BLUE",
).Canvas ).Canvas
self.Canvas = Canvas self.Canvas = Canvas
self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove ) self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove )
Point = (45,40) Point = (45,40)
Text = Canvas.AddScaledText("A String", Text = Canvas.AddScaledText("A String",
@@ -68,10 +68,10 @@ class DrawFrame(wx.Frame):
app = wx.App(False) app = wx.App(False)
F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) ) F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) )
app.MainLoop() app.MainLoop()

View File

@@ -69,7 +69,7 @@ class DrawFrame(wx.Frame):
BackgroundColor = "DARK SLATE BLUE", BackgroundColor = "DARK SLATE BLUE",
).Canvas ).Canvas
self.Show(True) self.Show(True)
@@ -286,25 +286,25 @@ class DrawFrame(wx.Frame):
elif Dir == "down": Y -= 10 elif Dir == "down": Y -= 10
Object.SetPoint((X,Y)) Object.SetPoint((X,Y))
self.Canvas.Draw(True) self.Canvas.Draw(True)
def UnBindAllMouseEvents(self): def UnBindAllMouseEvents(self):
## Here is how you catch FloatCanvas mouse events ## Here is how you catch FloatCanvas mouse events
self.Canvas.Bind(FloatCanvas.EVT_LEFT_DOWN, self.dummyHandler) self.Canvas.Bind(FloatCanvas.EVT_LEFT_DOWN, self.dummyHandler)
self.Canvas.Bind(FloatCanvas.EVT_LEFT_UP, self.dummyHandler) self.Canvas.Bind(FloatCanvas.EVT_LEFT_UP, self.dummyHandler)
self.Canvas.Bind(FloatCanvas.EVT_LEFT_DCLICK, self.dummyHandler) self.Canvas.Bind(FloatCanvas.EVT_LEFT_DCLICK, self.dummyHandler)
self.Canvas.Bind(FloatCanvas.EVT_MIDDLE_DOWN, self.dummyHandler) self.Canvas.Bind(FloatCanvas.EVT_MIDDLE_DOWN, self.dummyHandler)
self.Canvas.Bind(FloatCanvas.EVT_MIDDLE_UP, self.dummyHandler) self.Canvas.Bind(FloatCanvas.EVT_MIDDLE_UP, self.dummyHandler)
self.Canvas.Bind(FloatCanvas.EVT_MIDDLE_DCLICK, self.dummyHandler) self.Canvas.Bind(FloatCanvas.EVT_MIDDLE_DCLICK, self.dummyHandler)
self.Canvas.Bind(FloatCanvas.EVT_RIGHT_DOWN, self.dummyHandler) self.Canvas.Bind(FloatCanvas.EVT_RIGHT_DOWN, self.dummyHandler)
self.Canvas.Bind(FloatCanvas.EVT_RIGHT_UP, self.dummyHandler) self.Canvas.Bind(FloatCanvas.EVT_RIGHT_UP, self.dummyHandler)
self.Canvas.Bind(FloatCanvas.EVT_RIGHT_DCLICK, self.dummyHandler) self.Canvas.Bind(FloatCanvas.EVT_RIGHT_DCLICK, self.dummyHandler)
self.Canvas.Bind(FloatCanvas.EVT_MOUSEWHEEL, self.dummyHandler) self.Canvas.Bind(FloatCanvas.EVT_MOUSEWHEEL, self.dummyHandler)
self.EventsAreBound = False self.EventsAreBound = False
def dummyHandler(self, evt): def dummyHandler(self, evt):
evt.Skip() evt.Skip()
@@ -318,7 +318,7 @@ class DemoApp(wx.App):
objects, of each kind supported. objects, of each kind supported.
*Draw Map: will draw a map of the world. Be patient, it is a big map, *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 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 on my 450Mhz PIII). Redraws take about 2 sec. This demonstrates how the
performance is not very good for large drawings. performance is not very good for large drawings.
@@ -326,7 +326,7 @@ class DemoApp(wx.App):
Once you have a picture drawn, you can zoom in and out and move about 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 the picture. There is a tool bar with three tools that can be
selected. selected.
The magnifying glass with the plus is the zoom in tool. Once 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 if you click the image, it will zoom in, centered on where you
@@ -369,10 +369,10 @@ class DemoApp(wx.App):
app = DemoApp(False) app = DemoApp(False)
app.MainLoop() app.MainLoop()

View File

@@ -19,25 +19,25 @@ except ImportError:
from wx.lib.floatcanvas import NavCanvas, FloatCanvas, GUIMode from wx.lib.floatcanvas import NavCanvas, FloatCanvas, GUIMode
class TestFrame(wx.Frame): class TestFrame(wx.Frame):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs) wx.Frame.__init__(self, *args, **kwargs)
self.canvas =FloatCanvas.FloatCanvas(self, BackgroundColor = "DARK SLATE BLUE") self.canvas =FloatCanvas.FloatCanvas(self, BackgroundColor = "DARK SLATE BLUE")
# Layout # Layout
MainSizer = wx.BoxSizer(wx.VERTICAL) MainSizer = wx.BoxSizer(wx.VERTICAL)
MainSizer.Add(self.canvas, 4, wx.EXPAND) MainSizer.Add(self.canvas, 4, wx.EXPAND)
self.SetSizer(MainSizer) self.SetSizer(MainSizer)
self.canvas.Bind(FloatCanvas.EVT_LEFT_DOWN, self.OnLeftDown) self.canvas.Bind(FloatCanvas.EVT_LEFT_DOWN, self.OnLeftDown)
self.canvas.AddRectangle((10,10), (100, 20), FillColor="red") self.canvas.AddRectangle((10,10), (100, 20), FillColor="red")
self.canvas.SetMode(GUIMode.GUIMouse(self.canvas)) self.canvas.SetMode(GUIMode.GUIMouse(self.canvas))
wx.CallAfter(self.canvas.ZoomToBB) wx.CallAfter(self.canvas.ZoomToBB)
def OnLeftDown(self, event): def OnLeftDown(self, event):
print('Left Button clicked at: %s' % event.Coords) print('Left Button clicked at: %s' % event.Coords)

View File

@@ -33,7 +33,7 @@ import numpy as N
class MovingObjectMixin: class MovingObjectMixin:
""" """
Methods required for a Moving object Methods required for a Moving object
""" """
def GetOutlinePoints(self): def GetOutlinePoints(self):
@@ -46,20 +46,20 @@ class MovingObjectMixin:
) )
return OutlinePoints return OutlinePoints
class ConnectorObjectMixin: class ConnectorObjectMixin:
""" """
Mixin class for DrawObjects that can be connected with lines Mixin class for DrawObjects that can be connected with lines
NOte that this versionony works for Objects that have an "XY" attribute: NOte that this versionony works for Objects that have an "XY" attribute:
that is, one that is derived from XHObjectMixin. that is, one that is derived from XHObjectMixin.
""" """
def GetConnectPoint(self): def GetConnectPoint(self):
return self.XY return self.XY
class MovingBitmap(FC.ScaledBitmap, MovingObjectMixin, ConnectorObjectMixin): class MovingBitmap(FC.ScaledBitmap, MovingObjectMixin, ConnectorObjectMixin):
""" """
ScaledBitmap Object that can be moved ScaledBitmap Object that can be moved
@@ -67,7 +67,7 @@ class MovingBitmap(FC.ScaledBitmap, MovingObjectMixin, ConnectorObjectMixin):
## All we need to do is is inherit from: ## All we need to do is is inherit from:
## ScaledBitmap, MovingObjectMixin and ConnectorObjectMixin ## ScaledBitmap, MovingObjectMixin and ConnectorObjectMixin
pass pass
class MovingCircle(FC.Circle, MovingObjectMixin, ConnectorObjectMixin): class MovingCircle(FC.Circle, MovingObjectMixin, ConnectorObjectMixin):
""" """
ScaledBitmap Object that can be moved ScaledBitmap Object that can be moved
@@ -75,7 +75,7 @@ class MovingCircle(FC.Circle, MovingObjectMixin, ConnectorObjectMixin):
## All we need to do is is inherit from: ## All we need to do is is inherit from:
## ScaledBitmap, MovingObjectMixin and ConnectorObjectMixin ## ScaledBitmap, MovingObjectMixin and ConnectorObjectMixin
pass pass
class MovingArc(FC.Arc, MovingObjectMixin, ConnectorObjectMixin): class MovingArc(FC.Arc, MovingObjectMixin, ConnectorObjectMixin):
""" """
ScaledBitmap Object that can be moved ScaledBitmap Object that can be moved
@@ -83,7 +83,7 @@ class MovingArc(FC.Arc, MovingObjectMixin, ConnectorObjectMixin):
## All we need to do is is inherit from: ## All we need to do is is inherit from:
## ScaledBitmap, MovingObjectMixin and ConnectorObjectMixin ## ScaledBitmap, MovingObjectMixin and ConnectorObjectMixin
pass pass
class ConnectorLine(FC.LineOnlyMixin, FC.DrawObject,): class ConnectorLine(FC.LineOnlyMixin, FC.DrawObject,):
""" """
@@ -100,8 +100,8 @@ class ConnectorLine(FC.LineOnlyMixin, FC.DrawObject,):
InForeground = False): InForeground = False):
FC.DrawObject.__init__(self, InForeground) FC.DrawObject.__init__(self, InForeground)
self.Object1 = Object1 self.Object1 = Object1
self.Object2 = Object2 self.Object2 = Object2
self.LineColor = LineColor self.LineColor = LineColor
self.LineStyle = LineStyle self.LineStyle = LineStyle
self.LineWidth = LineWidth self.LineWidth = LineWidth
@@ -127,8 +127,8 @@ class ConnectorLine(FC.LineOnlyMixin, FC.DrawObject,):
if HTdc and self.HitAble: if HTdc and self.HitAble:
HTdc.SetPen(self.HitPen) HTdc.SetPen(self.HitPen)
HTdc.DrawLines(Points) HTdc.DrawLines(Points)
class TriangleShape1(FC.Polygon, MovingObjectMixin): class TriangleShape1(FC.Polygon, MovingObjectMixin):
def __init__(self, XY, L): def __init__(self, XY, L):
@@ -153,9 +153,9 @@ class TriangleShape1(FC.Polygon, MovingObjectMixin):
## Override the default OutlinePoints ## Override the default OutlinePoints
def GetOutlinePoints(self): def GetOutlinePoints(self):
return self.Points return self.Points
def CompPoints(self, XY, L): def CompPoints(self, XY, L):
c = L/ N.sqrt(3) c = L/ N.sqrt(3)
Points = N.array(((0, c), Points = N.array(((0, c),
( L/2.0, -c/2.0), ( L/2.0, -c/2.0),
@@ -176,24 +176,24 @@ class DrawFrame(wx.Frame):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs) wx.Frame.__init__(self, *args, **kwargs)
self.CreateStatusBar() self.CreateStatusBar()
# Add the Canvas # Add the Canvas
Canvas = NavCanvas.NavCanvas(self,-1,(500,500), Canvas = NavCanvas.NavCanvas(self,-1,(500,500),
ProjectionFun = None, ProjectionFun = None,
Debug = 0, Debug = 0,
BackgroundColor = "DARK SLATE BLUE", BackgroundColor = "DARK SLATE BLUE",
).Canvas ).Canvas
self.Canvas = Canvas self.Canvas = Canvas
Canvas.Bind(FC.EVT_MOTION, self.OnMove ) Canvas.Bind(FC.EVT_MOTION, self.OnMove )
Canvas.Bind(FC.EVT_LEFT_UP, self.OnLeftUp ) Canvas.Bind(FC.EVT_LEFT_UP, self.OnLeftUp )
Points = N.array(((0,0), Points = N.array(((0,0),
(1,0), (1,0),
(0.5, 1)), (0.5, 1)),
N.float) N.float)
data = (( (0,0), 1), data = (( (0,0), 1),
( (3,3), 2), ( (3,3), 2),
( (-2,3), 2.5 ), ( (-2,3), 2.5 ),
@@ -218,16 +218,16 @@ class DrawFrame(wx.Frame):
) )
Line = ConnectorLine(Bitmaps[0], Bitmaps[1], LineWidth=3, LineColor="Red") Line = ConnectorLine(Bitmaps[0], Bitmaps[1], LineWidth=3, LineColor="Red")
Canvas.AddObject(Line) Canvas.AddObject(Line)
## then add them to the Canvas, so they are on top of the line ## then add them to the Canvas, so they are on top of the line
for bmp in Bitmaps: for bmp in Bitmaps:
Canvas.AddObject(bmp) Canvas.AddObject(bmp)
bmp.Bind(FC.EVT_FC_LEFT_DOWN, self.ObjectHit) bmp.Bind(FC.EVT_FC_LEFT_DOWN, self.ObjectHit)
A = MovingArc((-5, 0),(-2, 2),(-5, 2), LineColor="Red", LineWidth=2) A = MovingArc((-5, 0),(-2, 2),(-5, 2), LineColor="Red", LineWidth=2)
self.Canvas.AddObject(A) self.Canvas.AddObject(A)
A.Bind(FC.EVT_FC_LEFT_DOWN, self.ObjectHit) A.Bind(FC.EVT_FC_LEFT_DOWN, self.ObjectHit)
self.Show(True) self.Show(True)
@@ -272,7 +272,7 @@ class DrawFrame(wx.Frame):
if self.MoveObject is not None: if self.MoveObject is not None:
dxy = event.GetPosition() - self.StartPoint dxy = event.GetPosition() - self.StartPoint
dxy = self.Canvas.ScalePixelToWorld(dxy) dxy = self.Canvas.ScalePixelToWorld(dxy)
self.MovingObject.Move(dxy) self.MovingObject.Move(dxy)
self.MoveTri = None self.MoveTri = None
self.Canvas.Draw(True) self.Canvas.Draw(True)

View File

@@ -83,7 +83,7 @@ class DrawFrame(wx.Frame):
self.timer = None self.timer = None
self.DrawAxis() self.DrawAxis()
return None return None

View File

@@ -57,9 +57,9 @@ class TriangleShape1(FC.Polygon, ShapeMixin):
FillColor = "Red", FillColor = "Red",
FillStyle = "Solid") FillStyle = "Solid")
ShapeMixin.__init__(self) ShapeMixin.__init__(self)
def CompPoints(self, XY, L): def CompPoints(self, XY, L):
c = L/ N.sqrt(3) c = L/ N.sqrt(3)
Points = N.array(((0, c), Points = N.array(((0, c),
( L/2.0, -c/2.0), ( L/2.0, -c/2.0),
@@ -80,18 +80,18 @@ class DrawFrame(wx.Frame):
def __init__(self,parent, id,title,position,size): def __init__(self,parent, id,title,position,size):
wx.Frame.__init__(self,parent, id,title,position, size) wx.Frame.__init__(self,parent, id,title,position, size)
self.CreateStatusBar() self.CreateStatusBar()
# Add the Canvas # Add the Canvas
Canvas = NavCanvas.NavCanvas(self,-1,(500,500), Canvas = NavCanvas.NavCanvas(self,-1,(500,500),
ProjectionFun = None, ProjectionFun = None,
Debug = 0, Debug = 0,
BackgroundColor = "DARK SLATE BLUE", BackgroundColor = "DARK SLATE BLUE",
).Canvas ).Canvas
self.Canvas = Canvas self.Canvas = Canvas
Canvas.Bind(FC.EVT_MOTION, self.OnMove ) Canvas.Bind(FC.EVT_MOTION, self.OnMove )
Canvas.Bind(FC.EVT_LEFT_UP, self.OnLeftUp ) Canvas.Bind(FC.EVT_LEFT_UP, self.OnLeftUp )
Canvas.AddRectangle((-5,-5), Canvas.AddRectangle((-5,-5),
(10,10), (10,10),
@@ -105,7 +105,7 @@ class DrawFrame(wx.Frame):
(1,0), (1,0),
(0.5, 1)), (0.5, 1)),
N.float_) N.float_)
data = (( (0,0), 1), data = (( (0,0), 1),
( (3,3), 2), ( (3,3), 2),
( (-2,3), 2.5 ), ( (-2,3), 2.5 ),
@@ -174,10 +174,10 @@ if __name__ == "__main__":
x = DrawFrame(None, -1, "FloatCanvas TextBox Test App", wx.DefaultPosition, (700,700) ) x = DrawFrame(None, -1, "FloatCanvas TextBox Test App", wx.DefaultPosition, (700,700) )
x.Show() x.Show()
app.MainLoop() app.MainLoop()

View File

@@ -33,10 +33,10 @@ class DrawFrame(wx.Frame):
size = (500,500), size = (500,500),
BackgroundColor = "DARK SLATE BLUE", BackgroundColor = "DARK SLATE BLUE",
) )
self.Canvas = Canvas self.Canvas = Canvas
self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove) self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove)
Point = (45,40) Point = (45,40)
Box = Canvas.AddScaledTextBox("A Two Line\nString", Box = Canvas.AddScaledTextBox("A Two Line\nString",
@@ -78,10 +78,10 @@ class DrawFrame(wx.Frame):
app = wx.App(False) app = wx.App(False)
F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) ) F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) )
app.MainLoop() app.MainLoop()

View File

@@ -5,10 +5,10 @@ A simple demo to show how to "Overlays": i.e. drawing something
on top of eveything else on the Canvas, relative to window coords, on top of eveything else on the Canvas, relative to window coords,
rather than screen coords. rather than screen coords.
This method uses the "GridOver" object in the FloatCanvas This method uses the "GridOver" object in the FloatCanvas
- it was orginally dsigend for girds, graticule,s etc. that - it was orginally dsigend for girds, graticule,s etc. that
are always drawn regardless of zoom, pan, etc, but it works are always drawn regardless of zoom, pan, etc, but it works
for overlays too. for overlays too.
""" """
@@ -28,7 +28,7 @@ class TextOverlay(FloatCanvas.Text):
An example of an Overlay object: An example of an Overlay object:
all it needs is a new _Draw method. all it needs is a new _Draw method.
NOTE: you may want to get fancier with this, NOTE: you may want to get fancier with this,
deriving from ScaledTextBox deriving from ScaledTextBox
@@ -94,8 +94,8 @@ class DrawFrame(wx.Frame):
Debug = 0, Debug = 0,
BackgroundColor = "DARK SLATE BLUE", BackgroundColor = "DARK SLATE BLUE",
).Canvas ).Canvas
Point = (45,40) Point = (45,40)
Box = Canvas.AddCircle(Point, Box = Canvas.AddCircle(Point,
Diameter = 10, Diameter = 10,
@@ -110,7 +110,7 @@ class DrawFrame(wx.Frame):
BackgroundColor = 'Pink', BackgroundColor = 'Pink',
) )
Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove) Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove)
self.Show() self.Show()
Canvas.ZoomToBB() Canvas.ZoomToBB()
@@ -127,10 +127,10 @@ class DrawFrame(wx.Frame):
app = wx.App(False) # true to get its own output window. app = wx.App(False) # true to get its own output window.
F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) ) F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) )
app.MainLoop() app.MainLoop()

View File

@@ -34,29 +34,29 @@ class DrawFrame(wx.Frame):
Debug = 0, Debug = 0,
BackgroundColor = "DARK SLATE BLUE", BackgroundColor = "DARK SLATE BLUE",
).Canvas ).Canvas
self.Canvas = Canvas self.Canvas = Canvas
Values = (10,10,10) Values = (10,10,10)
Colors = ('Red', 'Blue', 'Green') Colors = ('Red', 'Blue', 'Green')
Pie1 = PieChart(N.array((0, 0)), 10, Values, Colors, Scaled=False) Pie1 = PieChart(N.array((0, 0)), 10, Values, Colors, Scaled=False)
Canvas.AddObject(Pie1) Canvas.AddObject(Pie1)
Values = (10, 5, 5) Values = (10, 5, 5)
Pie2 = PieChart(N.array((40, 0)), 10, Values, Colors) Pie2 = PieChart(N.array((40, 0)), 10, Values, Colors)
Canvas.AddObject(Pie2) Canvas.AddObject(Pie2)
# test default colors # test default colors
Values = (10, 15, 12, 24, 6, 10, 13, 11, 9, 13, 15, 12) Values = (10, 15, 12, 24, 6, 10, 13, 11, 9, 13, 15, 12)
Pie3 = PieChart(N.array((20, 20)), 10, Values, LineColor="Black") Pie3 = PieChart(N.array((20, 20)), 10, Values, LineColor="Black")
Canvas.AddObject(Pie3) Canvas.AddObject(Pie3)
# missng slice! # missng slice!
Values = (10, 15, 12, 24) Values = (10, 15, 12, 24)
Colors = ('Red', 'Blue', 'Green', None) Colors = ('Red', 'Blue', 'Green', None)
Pie4 = PieChart(N.array((0, -15)), 10, Values, Colors, LineColor="Black") Pie4 = PieChart(N.array((0, -15)), 10, Values, Colors, LineColor="Black")
Canvas.AddObject(Pie4) Canvas.AddObject(Pie4)
# Test the styles # Test the styles
Values = (10, 12, 14) Values = (10, 12, 14)
@@ -68,7 +68,7 @@ class DrawFrame(wx.Frame):
Pie1.Bind(FloatCanvas.EVT_FC_LEFT_DOWN, self.Pie1Hit) Pie1.Bind(FloatCanvas.EVT_FC_LEFT_DOWN, self.Pie1Hit)
Pie2.Bind(FloatCanvas.EVT_FC_LEFT_DOWN, self.Pie2Hit) Pie2.Bind(FloatCanvas.EVT_FC_LEFT_DOWN, self.Pie2Hit)
self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove ) self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove )
self.Show() self.Show()
Canvas.ZoomToBB() Canvas.ZoomToBB()

View File

@@ -20,27 +20,27 @@ FC = FloatCanvas
class PixelBitmap: class PixelBitmap:
""" """
An unscaled bitmap that can be put on top of the canvas using: An unscaled bitmap that can be put on top of the canvas using:
Canvas.GridOver = MyPixelBitmap Canvas.GridOver = MyPixelBitmap
It will always be drawn on top of everything else, and be positioned It will always be drawn on top of everything else, and be positioned
according to pixel coordinates on teh screen, regardless of zoom and according to pixel coordinates on teh screen, regardless of zoom and
pan position. pan position.
""" """
def __init__(self, Bitmap, XY, Position = 'tl'): def __init__(self, Bitmap, XY, Position = 'tl'):
""" """
PixelBitmap (Bitmap, XY, Position='tl') PixelBitmap (Bitmap, XY, Position='tl')
Bitmap is a wx.Bitmap or wx.Image Bitmap is a wx.Bitmap or wx.Image
XY is the (x,y) location to place the bitmap, in pixel coordinates XY is the (x,y) location to place the bitmap, in pixel coordinates
Position indicates from where in the window the position is relative to: Position indicates from where in the window the position is relative to:
'tl' indicated the position from the top left the the window (the detault) 'tl' indicated the position from the top left the the window (the detault)
'br' the bottom right 'br' the bottom right
'cr the center right, etc. 'cr the center right, etc.
""" """
if type(Bitmap) == wx.Bitmap: if type(Bitmap) == wx.Bitmap:
self.Bitmap = Bitmap self.Bitmap = Bitmap
@@ -51,7 +51,7 @@ class PixelBitmap:
self.XY = np.asarray(XY, dtype=np.int).reshape((2,)) self.XY = np.asarray(XY, dtype=np.int).reshape((2,))
self.Position = Position self.Position = Position
(self.Width, self.Height) = self.Bitmap.GetWidth(), self.Bitmap.GetHeight() (self.Width, self.Height) = self.Bitmap.GetWidth(), self.Bitmap.GetHeight()
self.ShiftFun = FC.TextObjectMixin.ShiftFunDict[Position] self.ShiftFun = FC.TextObjectMixin.ShiftFunDict[Position]
@@ -62,7 +62,7 @@ class PixelBitmap:
XY = (XY[0], h - XY[1] - self.Height) XY = (XY[0], h - XY[1] - self.Height)
elif self.Position[0] == 'c': elif self.Position[0] == 'c':
XY = (XY[0], XY[1] + (h - self.Height)/2) XY = (XY[0], XY[1] + (h - self.Height)/2)
if self.Position[1] == 'r': if self.Position[1] == 'r':
XY = (w - XY[0] - self.Width, XY[1]) XY = (w - XY[0] - self.Width, XY[1])
elif self.Position[1] == 'c': elif self.Position[1] == 'c':
@@ -77,7 +77,7 @@ class GridGroup:
def _Draw(self, *args): def _Draw(self, *args):
for grid in self.Grids: for grid in self.Grids:
grid._Draw(*args) grid._Draw(*args)
class DrawFrame(wx.Frame): class DrawFrame(wx.Frame):
""" """
@@ -97,8 +97,8 @@ class DrawFrame(wx.Frame):
Debug = 0, Debug = 0,
BackgroundColor = "DARK SLATE BLUE", BackgroundColor = "DARK SLATE BLUE",
).Canvas ).Canvas
Point = (45,40) Point = (45,40)
Box = Canvas.AddCircle(Point, Box = Canvas.AddCircle(Point,
Diameter = 10, Diameter = 10,
@@ -118,7 +118,7 @@ class DrawFrame(wx.Frame):
]) ])
Canvas.GridOver = grids Canvas.GridOver = grids
FloatCanvas.EVT_MOTION(Canvas, self.OnMove ) FloatCanvas.EVT_MOTION(Canvas, self.OnMove )
self.Show() self.Show()
Canvas.ZoomToBB() Canvas.ZoomToBB()
@@ -135,10 +135,10 @@ class DrawFrame(wx.Frame):
app = wx.App(False) # true to get its own output window. app = wx.App(False) # true to get its own output window.
F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) ) F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) )
app.MainLoop() app.MainLoop()

View File

@@ -30,16 +30,16 @@ class DrawFrame(wx.Frame):
Debug = 0, Debug = 0,
BackgroundColor = "DARK SLATE BLUE", BackgroundColor = "DARK SLATE BLUE",
).Canvas ).Canvas
self.Canvas = Canvas self.Canvas = Canvas
self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove) self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove)
Pts = ((45,40), (20, 15), (10, 40), (30,30)) Pts = ((45,40), (20, 15), (10, 40), (30,30))
Points = Canvas.AddPointSet(Pts, Diameter=3, Color="Red") Points = Canvas.AddPointSet(Pts, Diameter=3, Color="Red")
Points.HitLineWidth = 10 Points.HitLineWidth = 10
Points.Bind(FloatCanvas.EVT_FC_ENTER_OBJECT, self.OnOverPoints) Points.Bind(FloatCanvas.EVT_FC_ENTER_OBJECT, self.OnOverPoints)
Points.Bind(FloatCanvas.EVT_FC_LEAVE_OBJECT, self.OnLeavePoints) Points.Bind(FloatCanvas.EVT_FC_LEAVE_OBJECT, self.OnLeavePoints)
Points.Bind(FloatCanvas.EVT_FC_LEFT_DOWN, self.OnLeftDown) Points.Bind(FloatCanvas.EVT_FC_LEFT_DOWN, self.OnLeftDown)
@@ -66,10 +66,10 @@ class DrawFrame(wx.Frame):
app = wx.App(False) app = wx.App(False)
F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) ) F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) )
app.MainLoop() app.MainLoop()

View File

@@ -50,7 +50,7 @@ class DrawFrame(wx.Frame):
self.SetMenuBar(MenuBar) self.SetMenuBar(MenuBar)
self.CreateStatusBar() self.CreateStatusBar()
# Add the Canvas # Add the Canvas
self.Canvas = NavCanvas.NavCanvas(self,-1,(500,500), self.Canvas = NavCanvas.NavCanvas(self,-1,(500,500),
Debug = 0, Debug = 0,
@@ -59,9 +59,9 @@ class DrawFrame(wx.Frame):
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove) self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove)
self.Canvas.Bind(FloatCanvas.EVT_LEFT_UP, self.OnLeftUp) self.Canvas.Bind(FloatCanvas.EVT_LEFT_UP, self.OnLeftUp)
self.Canvas.Bind(FloatCanvas.EVT_LEFT_DOWN, self.OnLeftClick) self.Canvas.Bind(FloatCanvas.EVT_LEFT_DOWN, self.OnLeftClick)
self.ResetSelections() self.ResetSelections()
@@ -226,12 +226,12 @@ class PolyEditor(wx.App):
PolyEditor(0).MainLoop()# put in True if you want output to go to it's own window. PolyEditor(0).MainLoop()# put in True if you want output to go to it's own window.

View File

@@ -33,16 +33,16 @@ import numpy as N
class MovingObjectMixin: class MovingObjectMixin:
""" """
Methods required for a Moving object Methods required for a Moving object
""" """
def GetOutlinePoints(self): def GetOutlinePoints(self):
""" """
Returns a set of points with which to draw the outline when moving the Returns a set of points with which to draw the outline when moving the
object. object.
Points are a NX2 array of (x,y) points in World coordinates. Points are a NX2 array of (x,y) points in World coordinates.
""" """
BB = self.BoundingBox BB = self.BoundingBox
OutlinePoints = N.array( ( (BB[0,0], BB[0,1]), OutlinePoints = N.array( ( (BB[0,0], BB[0,1]),
@@ -57,15 +57,15 @@ class MovingObjectMixin:
class ConnectorObjectMixin: class ConnectorObjectMixin:
""" """
Mixin class for DrawObjects that can be connected with lines Mixin class for DrawObjects that can be connected with lines
Note that this version only works for Objects that have an "XY" attribute: Note that this version only works for Objects that have an "XY" attribute:
that is, one that is derived from XHObjectMixin. that is, one that is derived from XHObjectMixin.
""" """
def GetConnectPoint(self): def GetConnectPoint(self):
return self.XY return self.XY
class MovingBitmap(FC.ScaledBitmap, MovingObjectMixin, ConnectorObjectMixin): class MovingBitmap(FC.ScaledBitmap, MovingObjectMixin, ConnectorObjectMixin):
""" """
ScaledBitmap Object that can be moved ScaledBitmap Object that can be moved
@@ -73,7 +73,7 @@ class MovingBitmap(FC.ScaledBitmap, MovingObjectMixin, ConnectorObjectMixin):
## All we need to do is is inherit from: ## All we need to do is is inherit from:
## ScaledBitmap, MovingObjectMixin and ConnectorObjectMixin ## ScaledBitmap, MovingObjectMixin and ConnectorObjectMixin
pass pass
class MovingCircle(FC.Circle, MovingObjectMixin, ConnectorObjectMixin): class MovingCircle(FC.Circle, MovingObjectMixin, ConnectorObjectMixin):
""" """
ScaledBitmap Object that can be moved ScaledBitmap Object that can be moved
@@ -84,10 +84,10 @@ class MovingCircle(FC.Circle, MovingObjectMixin, ConnectorObjectMixin):
class MovingGroup(FC.Group, MovingObjectMixin, ConnectorObjectMixin): class MovingGroup(FC.Group, MovingObjectMixin, ConnectorObjectMixin):
def GetConnectPoint(self): def GetConnectPoint(self):
return self.BoundingBox.Center return self.BoundingBox.Center
class NodeObject(FC.Group, MovingObjectMixin, ConnectorObjectMixin): class NodeObject(FC.Group, MovingObjectMixin, ConnectorObjectMixin):
""" """
A version of the moving group for nodes -- an ellipse with text on it. A version of the moving group for nodes -- an ellipse with text on it.
@@ -117,7 +117,7 @@ class NodeObject(FC.Group, MovingObjectMixin, ConnectorObjectMixin):
def GetConnectPoint(self): def GetConnectPoint(self):
return self.BoundingBox.Center return self.BoundingBox.Center
class MovingText(FC.ScaledText, MovingObjectMixin, ConnectorObjectMixin): class MovingText(FC.ScaledText, MovingObjectMixin, ConnectorObjectMixin):
""" """
@@ -134,7 +134,7 @@ class MovingTextBox(FC.ScaledTextBox, MovingObjectMixin, ConnectorObjectMixin):
## All we need to do is is inherit from: ## All we need to do is is inherit from:
## ScaledBitmap, MovingObjectMixin and ConnectorObjectMixin ## ScaledBitmap, MovingObjectMixin and ConnectorObjectMixin
pass pass
class ConnectorLine(FC.LineOnlyMixin, FC.DrawObject,): class ConnectorLine(FC.LineOnlyMixin, FC.DrawObject,):
""" """
@@ -152,8 +152,8 @@ class ConnectorLine(FC.LineOnlyMixin, FC.DrawObject,):
InForeground = False): InForeground = False):
FC.DrawObject.__init__(self, InForeground) FC.DrawObject.__init__(self, InForeground)
self.Object1 = Object1 self.Object1 = Object1
self.Object2 = Object2 self.Object2 = Object2
self.LineColor = LineColor self.LineColor = LineColor
self.LineStyle = LineStyle self.LineStyle = LineStyle
self.LineWidth = LineWidth self.LineWidth = LineWidth
@@ -179,8 +179,8 @@ class ConnectorLine(FC.LineOnlyMixin, FC.DrawObject,):
if HTdc and self.HitAble: if HTdc and self.HitAble:
HTdc.SetPen(self.HitPen) HTdc.SetPen(self.HitPen)
HTdc.DrawLines(Points) HTdc.DrawLines(Points)
class TriangleShape1(FC.Polygon, MovingObjectMixin): class TriangleShape1(FC.Polygon, MovingObjectMixin):
def __init__(self, XY, L): def __init__(self, XY, L):
@@ -205,9 +205,9 @@ class TriangleShape1(FC.Polygon, MovingObjectMixin):
## Override the default OutlinePoints ## Override the default OutlinePoints
def GetOutlinePoints(self): def GetOutlinePoints(self):
return self.Points return self.Points
def CompPoints(self, XY, L): def CompPoints(self, XY, L):
c = L/ N.sqrt(3) c = L/ N.sqrt(3)
Points = N.array(((0, c), Points = N.array(((0, c),
( L/2.0, -c/2.0), ( L/2.0, -c/2.0),
@@ -232,7 +232,7 @@ class TreeNode:
def __str__(self): def __str__(self):
return "TreeNode: %s"%self.Name return "TreeNode: %s"%self.Name
__repr__ = __str__ __repr__ = __str__
## Build Tree: ## Build Tree:
leaves = [TreeNode(name) for name in ["Assistant VP 1","Assistant VP 2","Assistant VP 3"] ] leaves = [TreeNode(name) for name in ["Assistant VP 1","Assistant VP 2","Assistant VP 3"] ]
@@ -246,12 +246,12 @@ elements = TreeNode("Root", [CEO, Father])
def LayoutTree(root, x, y, level): def LayoutTree(root, x, y, level):
NumNodes = len(root.Children) NumNodes = len(root.Children)
root.Point = (x,y) root.Point = (x,y)
x += root.dx x += root.dx
y += (root.dy * level * (NumNodes-1) / 2.0) y += (root.dy * level * (NumNodes-1) / 2.0)
for node in root.Children: for node in root.Children:
LayoutTree(node, x, y, level-1) LayoutTree(node, x, y, level-1)
y -= root.dy * level y -= root.dy * level
def TraverseTree(root, func): def TraverseTree(root, func):
func(root) func(root)
for child in (root.Children): for child in (root.Children):
@@ -267,25 +267,25 @@ class DrawFrame(wx.Frame):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs) wx.Frame.__init__(self, *args, **kwargs)
self.CreateStatusBar() self.CreateStatusBar()
# Add the Canvas # Add the Canvas
Canvas = NavCanvas.NavCanvas(self,-1,(500,500), Canvas = NavCanvas.NavCanvas(self,-1,(500,500),
ProjectionFun = None, ProjectionFun = None,
Debug = 0, Debug = 0,
BackgroundColor = "White", BackgroundColor = "White",
).Canvas ).Canvas
self.Canvas = Canvas self.Canvas = Canvas
Canvas.Bind(FC.EVT_MOTION, self.OnMove ) Canvas.Bind(FC.EVT_MOTION, self.OnMove )
Canvas.Bind(FC.EVT_LEFT_UP, self.OnLeftUp ) Canvas.Bind(FC.EVT_LEFT_UP, self.OnLeftUp )
self.elements = elements self.elements = elements
LayoutTree(self.elements, 0, 0, 3) LayoutTree(self.elements, 0, 0, 3)
self.AddTree(self.elements) self.AddTree(self.elements)
self.Show(True) self.Show(True)
self.Canvas.ZoomToBB() self.Canvas.ZoomToBB()
@@ -319,7 +319,7 @@ class DrawFrame(wx.Frame):
node.DrawObject = object node.DrawObject = object
Nodes.append(object) Nodes.append(object)
def AddConnectors(node): def AddConnectors(node):
for child in node.Children: for child in node.Children:
Connector = ConnectorLine(node.DrawObject, child.DrawObject, LineWidth=3, LineColor="Red") Connector = ConnectorLine(node.DrawObject, child.DrawObject, LineWidth=3, LineColor="Red")
Connectors.append(Connector) Connectors.append(Connector)
## create the Objects ## create the Objects
@@ -327,14 +327,14 @@ class DrawFrame(wx.Frame):
## create the Connectors ## create the Connectors
TraverseTree(root, AddConnectors) TraverseTree(root, AddConnectors)
## Add the conenctos to the Canvas first, so they are undernieth the nodes ## Add the conenctos to the Canvas first, so they are undernieth the nodes
self.Canvas.AddObjects(Connectors) self.Canvas.AddObjects(Connectors)
## now add the nodes ## now add the nodes
self.Canvas.AddObjects(Nodes) self.Canvas.AddObjects(Nodes)
# Now bind the Nodes -- DrawObjects must be Added to a Canvas before they can be bound. # Now bind the Nodes -- DrawObjects must be Added to a Canvas before they can be bound.
for node in Nodes: for node in Nodes:
#pass #pass
node.Bind(FC.EVT_FC_LEFT_DOWN, self.ObjectHit) node.Bind(FC.EVT_FC_LEFT_DOWN, self.ObjectHit)
def ObjectHit(self, object): def ObjectHit(self, object):
@@ -371,7 +371,7 @@ class DrawFrame(wx.Frame):
if self.MoveObject is not None: if self.MoveObject is not None:
dxy = event.GetPosition() - self.StartPoint dxy = event.GetPosition() - self.StartPoint
dxy = self.Canvas.ScalePixelToWorld(dxy) dxy = self.Canvas.ScalePixelToWorld(dxy)
self.MovingObject.Move(dxy) self.MovingObject.Move(dxy)
self.Canvas.Draw(True) self.Canvas.Draw(True)
app = wx.App(0) app = wx.App(0)

View File

@@ -51,9 +51,9 @@ class DrawFrame(wx.Frame):
Debug = 0, Debug = 0,
BackgroundColor = "DARK SLATE BLUE", BackgroundColor = "DARK SLATE BLUE",
).Canvas ).Canvas
self.Canvas = Canvas self.Canvas = Canvas
Point = N.array((50e-6, 0)) Point = N.array((50e-6, 0))
Size = N.array(( (2000e-6 - 5e-6), 50000)) Size = N.array(( (2000e-6 - 5e-6), 50000))
Box = Canvas.AddRectangle(Point, Box = Canvas.AddRectangle(Point,
@@ -64,14 +64,14 @@ class DrawFrame(wx.Frame):
Canvas.AddText("%s"%(Point,), Point, Position="cr") Canvas.AddText("%s"%(Point,), Point, Position="cr")
Canvas.AddPoint(Point, Diameter=3, Color = "red") Canvas.AddPoint(Point, Diameter=3, Color = "red")
Point = Point + Size Point = Point + Size
Canvas.AddText("%s"%(Point,), Point, Position="cl") Canvas.AddText("%s"%(Point,), Point, Position="cl")
Canvas.AddPoint(Point, Diameter=3, Color = "red") Canvas.AddPoint(Point, Diameter=3, Color = "red")
self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove)
self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove)
self.Show() self.Show()
Canvas.ZoomToBB() Canvas.ZoomToBB()
@@ -85,10 +85,10 @@ class DrawFrame(wx.Frame):
app = wx.App(False) app = wx.App(False)
F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) ) F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) )
app.MainLoop() app.MainLoop()

View File

@@ -8,7 +8,7 @@ but uses memory more efficiently for large images and high zoom levels.)
""" """
## Set a path to an Image file here: ## Set a path to an Image file here:
ImageFile = "white_tank.jpg" ImageFile = "white_tank.jpg"
import wx import wx
@@ -41,9 +41,9 @@ class DrawFrame(wx.Frame):
Canvas.MaxScale=20 # sets the maximum zoom level Canvas.MaxScale=20 # sets the maximum zoom level
self.Canvas = Canvas self.Canvas = Canvas
self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove ) self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove )
# create the image: # create the image:
image = wx.Image(ImageFile) image = wx.Image(ImageFile)
self.width, self.height = image.GetSize() self.width, self.height = image.GetSize()
@@ -53,10 +53,10 @@ class DrawFrame(wx.Frame):
Position = 'tl', Position = 'tl',
) )
Canvas.AddObject(img) Canvas.AddObject(img)
self.Show() self.Show()
Canvas.ZoomToBB() Canvas.ZoomToBB()
def OnMove(self, event): def OnMove(self, event):
""" """
Updates the status bar with the world coordinates Updates the status bar with the world coordinates
@@ -68,10 +68,10 @@ class DrawFrame(wx.Frame):
app = wx.App(False) app = wx.App(False)
F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) ) F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) )
app.MainLoop() app.MainLoop()

View File

@@ -48,7 +48,7 @@ class MyFrame(wx.Frame):
Position = 'br', Position = 'br',
Alignment = "left", Alignment = "left",
InForeground = False) InForeground = False)
wx.CallAfter(Canvas.ZoomToBB) wx.CallAfter(Canvas.ZoomToBB)
# set up the Splitter # set up the Splitter
@@ -56,7 +56,7 @@ class MyFrame(wx.Frame):
splitter.SplitVertically(panel1, panel2, sash_Position) splitter.SplitVertically(panel1, panel2, sash_Position)
min_Pan_size = 40 min_Pan_size = 40
splitter.SetMinimumPaneSize(min_Pan_size) splitter.SetMinimumPaneSize(min_Pan_size)
self.Fit() self.Fit()

View File

@@ -25,9 +25,9 @@ class DrawFrame(wx.Frame):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs) wx.Frame.__init__(self, *args, **kwargs)
self.CreateStatusBar() self.CreateStatusBar()
panel = NavPanel(self) panel = NavPanel(self)
self.Show() self.Show()
class NavPanel(NavCanvas.NavCanvas): class NavPanel(NavCanvas.NavCanvas):
@@ -40,10 +40,10 @@ class NavPanel(NavCanvas.NavCanvas):
ProjectionFun = None, ProjectionFun = None,
BackgroundColor = "DARK SLATE BLUE", BackgroundColor = "DARK SLATE BLUE",
) )
self.parent_frame = parent self.parent_frame = parent
self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove) self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove)
# create the image: # create the image:
self.Canvas.AddPolygon( ( (2,3), self.Canvas.AddPolygon( ( (2,3),
(5,6), (5,6),
@@ -51,9 +51,9 @@ class NavPanel(NavCanvas.NavCanvas):
FillColor = "red", FillColor = "red",
) )
wx.CallAfter(self.Canvas.ZoomToBB) # so it will get called after everything is created and sized wx.CallAfter(self.Canvas.ZoomToBB) # so it will get called after everything is created and sized
def OnMove(self, event): def OnMove(self, event):
""" """
Updates the status bar with the world coordinates Updates the status bar with the world coordinates

View File

@@ -23,7 +23,7 @@ from wx.lib.floatcanvas import NavCanvas
class Spline(FC.Line): class Spline(FC.Line):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
FC.Line.__init__(self, *args, **kwargs) FC.Line.__init__(self, *args, **kwargs)
def _Draw(self, dc , WorldToPixel, ScaleWorldToPixel, HTdc=None): def _Draw(self, dc , WorldToPixel, ScaleWorldToPixel, HTdc=None):
Points = WorldToPixel(self.Points) Points = WorldToPixel(self.Points)
dc.SetPen(self.Pen) dc.SetPen(self.Pen)
@@ -56,21 +56,21 @@ class DrawFrame(wx.Frame):
MenuBar.Append(help_menu, "&Help") MenuBar.Append(help_menu, "&Help")
self.SetMenuBar(MenuBar) self.SetMenuBar(MenuBar)
self.CreateStatusBar() self.CreateStatusBar()
# Add the Canvas # Add the Canvas
self.Canvas = NavCanvas.NavCanvas(self, self.Canvas = NavCanvas.NavCanvas(self,
BackgroundColor = "White", BackgroundColor = "White",
).Canvas ).Canvas
self.Canvas.Bind(FC.EVT_MOTION, self.OnMove) self.Canvas.Bind(FC.EVT_MOTION, self.OnMove)
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
self.DrawTest() self.DrawTest()
self.Show() self.Show()
self.Canvas.ZoomToBB() self.Canvas.ZoomToBB()
def OnAbout(self, event): def OnAbout(self, event):
print("OnAbout called") print("OnAbout called")
@@ -94,7 +94,7 @@ class DrawFrame(wx.Frame):
def DrawTest(self,event=None): def DrawTest(self,event=None):
wx.GetApp().Yield() wx.GetApp().Yield()
Canvas = self.Canvas Canvas = self.Canvas
Points = [(0, 0), Points = [(0, 0),
@@ -135,7 +135,7 @@ class DrawFrame(wx.Frame):
MyLine = FC.Spline(Points, MyLine = FC.Spline(Points,
LineWidth = 3, LineWidth = 3,
LineColor = "Blue") LineColor = "Blue")
Canvas.AddObject(MyLine) Canvas.AddObject(MyLine)
Canvas.AddPointSet(Points, Canvas.AddPointSet(Points,
Color = "Red", Color = "Red",
@@ -148,7 +148,7 @@ class DrawFrame(wx.Frame):
(70, 185), (70, 185),
(160,60), (160,60),
] ]
Canvas.AddSpline(Points, Canvas.AddSpline(Points,
LineWidth = 5, LineWidth = 5,
LineColor = "Purple") LineColor = "Purple")
@@ -163,7 +163,7 @@ class DemoApp(wx.App):
self.SetTopWindow(frame) self.SetTopWindow(frame)
return True return True
app = DemoApp(False)# put in True if you want output to go to it's own window. app = DemoApp(False)# put in True if you want output to go to it's own window.
app.MainLoop() app.MainLoop()

View File

@@ -16,7 +16,7 @@ from wx.lib.floatcanvas import NavCanvas, FloatCanvas
#from floatcanvas import NavCanvas, FloatCanvas #from floatcanvas import NavCanvas, FloatCanvas
import numpy as N import numpy as N
class DrawFrame(wx.Frame): class DrawFrame(wx.Frame):
""" """
@@ -28,16 +28,16 @@ class DrawFrame(wx.Frame):
wx.Frame.__init__(self,parent, id,title,position, size) wx.Frame.__init__(self,parent, id,title,position, size)
# Add the Canvas # Add the Canvas
self.CreateStatusBar() self.CreateStatusBar()
Canvas = NavCanvas.NavCanvas(self,-1,(500,500), Canvas = NavCanvas.NavCanvas(self,-1,(500,500),
ProjectionFun = None, ProjectionFun = None,
Debug = 0, Debug = 0,
BackgroundColor = "DARK SLATE BLUE", BackgroundColor = "DARK SLATE BLUE",
).Canvas ).Canvas
self.Canvas = Canvas self.Canvas = Canvas
self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove ) self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove )
Point = (45,40) Point = (45,40)
Box = Canvas.AddScaledTextBox("A Two Line\nString", Box = Canvas.AddScaledTextBox("A Two Line\nString",
Point, Point,
@@ -265,7 +265,7 @@ class DrawFrame(wx.Frame):
LineSpacing = 0.8, LineSpacing = 0.8,
Alignment = 'center', Alignment = 'center',
) )
self.Show(True) self.Show(True)
self.Canvas.ZoomToBB() self.Canvas.ZoomToBB()
@@ -287,10 +287,10 @@ class DrawFrame(wx.Frame):
app = wx.App() app = wx.App()
DrawFrame(None, -1, "FloatCanvas Demo App", wx.DefaultPosition, (700,700) ) DrawFrame(None, -1, "FloatCanvas Demo App", wx.DefaultPosition, (700,700) )
app.MainLoop() app.MainLoop()

View File

@@ -37,7 +37,7 @@ This is another paragraph. I am trying to make it long enough to wrap a reasonab
##LongString = ( ##LongString = (
##""" This is a not so long string ##""" This is a not so long string
##Another line""") ##Another line""")
class DrawFrame(wx.Frame): class DrawFrame(wx.Frame):
""" """
@@ -48,23 +48,23 @@ class DrawFrame(wx.Frame):
def __init__(self,parent, id,title,position,size): def __init__(self,parent, id,title,position,size):
wx.Frame.__init__(self,parent, id,title,position, size) wx.Frame.__init__(self,parent, id,title,position, size)
self.CreateStatusBar() self.CreateStatusBar()
# Add the Canvas # Add the Canvas
Canvas = NavCanvas.NavCanvas(self,-1,(500,500), Canvas = NavCanvas.NavCanvas(self,-1,(500,500),
ProjectionFun = None, ProjectionFun = None,
Debug = 0, Debug = 0,
BackgroundColor = "DARK SLATE BLUE", BackgroundColor = "DARK SLATE BLUE",
).Canvas ).Canvas
self.Canvas = Canvas self.Canvas = Canvas
self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove ) self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove )
self.Canvas.Bind(FloatCanvas.EVT_LEFT_UP, self.OnLeftUp ) self.Canvas.Bind(FloatCanvas.EVT_LEFT_UP, self.OnLeftUp )
self.Canvas.Bind(FloatCanvas.EVT_LEFT_DOWN, self.OnLeftDown) self.Canvas.Bind(FloatCanvas.EVT_LEFT_DOWN, self.OnLeftDown)
Point = N.array((0,0), N.float) Point = N.array((0,0), N.float)
Canvas.AddCircle(Point, Canvas.AddCircle(Point,
@@ -76,7 +76,7 @@ class DrawFrame(wx.Frame):
) )
Width = 300 Width = 300
self.Box = Canvas.AddScaledTextBox(LongString, self.Box = Canvas.AddScaledTextBox(LongString,
Point, Point,
@@ -93,19 +93,19 @@ class DrawFrame(wx.Frame):
Weight = wx.NORMAL, Weight = wx.NORMAL,
Underlined = False, Underlined = False,
Position = 'tl', Position = 'tl',
LineSpacing = 0.8, LineSpacing = 0.8,
Alignment = "left", Alignment = "left",
#Alignment = "center", #Alignment = "center",
#Alignment = "right", #Alignment = "right",
InForeground = False) InForeground = False)
self.Handle1 = Canvas.AddBitmap(Resources.getMoveCursorBitmap(), Point, Position='cc') self.Handle1 = Canvas.AddBitmap(Resources.getMoveCursorBitmap(), Point, Position='cc')
self.Handle2a = Canvas.AddBitmap(Resources.getMoveRLCursorBitmap(), Point, Position='cc') self.Handle2a = Canvas.AddBitmap(Resources.getMoveRLCursorBitmap(), Point, Position='cc')
self.Handle2b = Canvas.AddBitmap(Resources.getMoveRLCursorBitmap(), Point, Position='cc') self.Handle2b = Canvas.AddBitmap(Resources.getMoveRLCursorBitmap(), Point, Position='cc')
self.SetHandles() self.SetHandles()
self.Handle1.Bind(FloatCanvas.EVT_FC_LEFT_DOWN, self.Handle1Hit) self.Handle1.Bind(FloatCanvas.EVT_FC_LEFT_DOWN, self.Handle1Hit)
self.Handle2a.Bind(FloatCanvas.EVT_FC_LEFT_DOWN, self.Handle2Hit) self.Handle2a.Bind(FloatCanvas.EVT_FC_LEFT_DOWN, self.Handle2Hit)
self.Handle2b.Bind(FloatCanvas.EVT_FC_LEFT_DOWN, self.Handle2Hit) self.Handle2b.Bind(FloatCanvas.EVT_FC_LEFT_DOWN, self.Handle2Hit)
@@ -177,7 +177,7 @@ class DrawFrame(wx.Frame):
def OnLeftDown(self, event): def OnLeftDown(self, event):
pass pass
def OnLeftUp(self, event): def OnLeftUp(self, event):
if self.Resizing: if self.Resizing:
self.Resizing = False self.Resizing = False
@@ -196,7 +196,7 @@ class DrawFrame(wx.Frame):
self.ResizeRect = None self.ResizeRect = None
# self.Box.SetPoint(Point1) # self.Box.SetPoint(Point1)
self.SetHandles() self.SetHandles()
self.Canvas.Draw(True) self.Canvas.Draw(True)
def SetHandles(self): def SetHandles(self):
@@ -208,15 +208,15 @@ class DrawFrame(wx.Frame):
y -= h/3 y -= h/3
self.Handle2b.SetPoint((x,y)) self.Handle2b.SetPoint((x,y))
self.Handle1.SetPoint(self.Box.XY) self.Handle1.SetPoint(self.Box.XY)
app = wx.App() app = wx.App()
DrawFrame(None, -1, "FloatCanvas TextBox Test App", wx.DefaultPosition, (700,700) ) DrawFrame(None, -1, "FloatCanvas TextBox Test App", wx.DefaultPosition, (700,700) )
app.MainLoop() app.MainLoop()

View File

@@ -1,4 +1,4 @@
"Another Name","Another Type", 19 "Another Name","Another Type", 19
-81.531753540039,31.134635925293 -81.531753540039,31.134635925293
-81.531150817871,31.134529113769 -81.531150817871,31.134529113769
-81.530662536621,31.134353637695 -81.530662536621,31.134353637695
@@ -18,7 +18,7 @@
-81.532928466797,31.135110855102 -81.532928466797,31.135110855102
-81.532447814941,31.134794235229 -81.532447814941,31.134794235229
-81.532341003418,31.134586334229 -81.532341003418,31.134586334229
"A third 'name'","6", 7 "A third 'name'","6", 7
-81.522369384766,31.122062683106 -81.522369384766,31.122062683106
-81.522109985352,31.121908187866 -81.522109985352,31.121908187866
-81.522010803223,31.121685028076 -81.522010803223,31.121685028076
@@ -26,7 +26,7 @@
-81.522483825684,31.121797561646 -81.522483825684,31.121797561646
-81.522514343262,31.122062683106 -81.522514343262,31.122062683106
-81.522369384766,31.122062683106 -81.522369384766,31.122062683106
"8223","1", 9 "8223","1", 9
-81.523277282715,31.122261047363 -81.523277282715,31.122261047363
-81.522987365723,31.121982574463 -81.522987365723,31.121982574463
-81.523200988770,31.121547698975 -81.523200988770,31.121547698975

View File

@@ -33,16 +33,16 @@ import numpy as N
class MovingObjectMixin: class MovingObjectMixin:
""" """
Methods required for a Moving object Methods required for a Moving object
""" """
def GetOutlinePoints(self): def GetOutlinePoints(self):
""" """
Returns a set of points with which to draw the outline when moving the Returns a set of points with which to draw the outline when moving the
object. object.
Points are a NX2 array of (x,y) points in World coordinates. Points are a NX2 array of (x,y) points in World coordinates.
""" """
BB = self.BoundingBox BB = self.BoundingBox
OutlinePoints = N.array( ( (BB[0,0], BB[0,1]), OutlinePoints = N.array( ( (BB[0,0], BB[0,1]),
@@ -57,15 +57,15 @@ class MovingObjectMixin:
class ConnectorObjectMixin: class ConnectorObjectMixin:
""" """
Mixin class for DrawObjects that can be connected with lines Mixin class for DrawObjects that can be connected with lines
Note that this version only works for Objects that have an "XY" attribute: Note that this version only works for Objects that have an "XY" attribute:
that is, one that is derived from XHObjectMixin. that is, one that is derived from XHObjectMixin.
""" """
def GetConnectPoint(self): def GetConnectPoint(self):
return self.XY return self.XY
class MovingBitmap(FC.ScaledBitmap, MovingObjectMixin, ConnectorObjectMixin): class MovingBitmap(FC.ScaledBitmap, MovingObjectMixin, ConnectorObjectMixin):
""" """
ScaledBitmap Object that can be moved ScaledBitmap Object that can be moved
@@ -73,7 +73,7 @@ class MovingBitmap(FC.ScaledBitmap, MovingObjectMixin, ConnectorObjectMixin):
## All we need to do is is inherit from: ## All we need to do is is inherit from:
## ScaledBitmap, MovingObjectMixin and ConnectorObjectMixin ## ScaledBitmap, MovingObjectMixin and ConnectorObjectMixin
pass pass
class MovingCircle(FC.Circle, MovingObjectMixin, ConnectorObjectMixin): class MovingCircle(FC.Circle, MovingObjectMixin, ConnectorObjectMixin):
""" """
ScaledBitmap Object that can be moved ScaledBitmap Object that can be moved
@@ -84,10 +84,10 @@ class MovingCircle(FC.Circle, MovingObjectMixin, ConnectorObjectMixin):
class MovingGroup(FC.Group, MovingObjectMixin, ConnectorObjectMixin): class MovingGroup(FC.Group, MovingObjectMixin, ConnectorObjectMixin):
def GetConnectPoint(self): def GetConnectPoint(self):
return self.BoundingBox.Center return self.BoundingBox.Center
class NodeObject(FC.Group, MovingObjectMixin, ConnectorObjectMixin): class NodeObject(FC.Group, MovingObjectMixin, ConnectorObjectMixin):
""" """
A version of the moving group for nodes -- an ellipse with text on it. A version of the moving group for nodes -- an ellipse with text on it.
@@ -117,7 +117,7 @@ class NodeObject(FC.Group, MovingObjectMixin, ConnectorObjectMixin):
def GetConnectPoint(self): def GetConnectPoint(self):
return self.BoundingBox.Center return self.BoundingBox.Center
class MovingText(FC.ScaledText, MovingObjectMixin, ConnectorObjectMixin): class MovingText(FC.ScaledText, MovingObjectMixin, ConnectorObjectMixin):
""" """
@@ -126,7 +126,7 @@ class MovingText(FC.ScaledText, MovingObjectMixin, ConnectorObjectMixin):
## All we need to do is is inherit from: ## All we need to do is is inherit from:
## ScaledBitmap, MovingObjectMixin and ConnectorObjectMixin ## ScaledBitmap, MovingObjectMixin and ConnectorObjectMixin
pass pass
class ConnectorLine(FC.LineOnlyMixin, FC.DrawObject,): class ConnectorLine(FC.LineOnlyMixin, FC.DrawObject,):
""" """
@@ -144,8 +144,8 @@ class ConnectorLine(FC.LineOnlyMixin, FC.DrawObject,):
InForeground = False): InForeground = False):
FC.DrawObject.__init__(self, InForeground) FC.DrawObject.__init__(self, InForeground)
self.Object1 = Object1 self.Object1 = Object1
self.Object2 = Object2 self.Object2 = Object2
self.LineColor = LineColor self.LineColor = LineColor
self.LineStyle = LineStyle self.LineStyle = LineStyle
self.LineWidth = LineWidth self.LineWidth = LineWidth
@@ -171,8 +171,8 @@ class ConnectorLine(FC.LineOnlyMixin, FC.DrawObject,):
if HTdc and self.HitAble: if HTdc and self.HitAble:
HTdc.SetPen(self.HitPen) HTdc.SetPen(self.HitPen)
HTdc.DrawLines(Points) HTdc.DrawLines(Points)
class TriangleShape1(FC.Polygon, MovingObjectMixin): class TriangleShape1(FC.Polygon, MovingObjectMixin):
def __init__(self, XY, L): def __init__(self, XY, L):
@@ -197,9 +197,9 @@ class TriangleShape1(FC.Polygon, MovingObjectMixin):
## Override the default OutlinePoints ## Override the default OutlinePoints
def GetOutlinePoints(self): def GetOutlinePoints(self):
return self.Points return self.Points
def CompPoints(self, XY, L): def CompPoints(self, XY, L):
c = L/ N.sqrt(3) c = L/ N.sqrt(3)
Points = N.array(((0, c), Points = N.array(((0, c),
( L/2.0, -c/2.0), ( L/2.0, -c/2.0),
@@ -224,7 +224,7 @@ class TreeNode:
def __str__(self): def __str__(self):
return "TreeNode: %s"%self.Name return "TreeNode: %s"%self.Name
__repr__ = __str__ __repr__ = __str__
## Build Tree: ## Build Tree:
leaves = [TreeNode(name) for name in ["Assistant VP 1","Assistant VP 2","Assistant VP 3"] ] leaves = [TreeNode(name) for name in ["Assistant VP 1","Assistant VP 2","Assistant VP 3"] ]
@@ -238,12 +238,12 @@ elements = TreeNode("Root", [CEO, Father])
def LayoutTree(root, x, y, level): def LayoutTree(root, x, y, level):
NumNodes = len(root.Children) NumNodes = len(root.Children)
root.Point = (x,y) root.Point = (x,y)
x += root.dx x += root.dx
y += (root.dy * level * (NumNodes-1) / 2.0) y += (root.dy * level * (NumNodes-1) / 2.0)
for node in root.Children: for node in root.Children:
LayoutTree(node, x, y, level-1) LayoutTree(node, x, y, level-1)
y -= root.dy * level y -= root.dy * level
def TraverseTree(root, func): def TraverseTree(root, func):
func(root) func(root)
for child in (root.Children): for child in (root.Children):
@@ -259,25 +259,25 @@ class DrawFrame(wx.Frame):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs) wx.Frame.__init__(self, *args, **kwargs)
self.CreateStatusBar() self.CreateStatusBar()
# Add the Canvas # Add the Canvas
Canvas = NavCanvas.NavCanvas(self,-1,(500,500), Canvas = NavCanvas.NavCanvas(self,-1,(500,500),
ProjectionFun = None, ProjectionFun = None,
Debug = 0, Debug = 0,
BackgroundColor = "White", BackgroundColor = "White",
).Canvas ).Canvas
self.Canvas = Canvas self.Canvas = Canvas
Canvas.Bind(FC.EVT_MOTION, self.OnMove ) Canvas.Bind(FC.EVT_MOTION, self.OnMove )
Canvas.Bind(FC.EVT_LEFT_UP, self.OnLeftUp ) Canvas.Bind(FC.EVT_LEFT_UP, self.OnLeftUp )
self.elements = elements self.elements = elements
LayoutTree(self.elements, 0, 0, 3) LayoutTree(self.elements, 0, 0, 3)
self.AddTree(self.elements) self.AddTree(self.elements)
self.Show(True) self.Show(True)
self.Canvas.ZoomToBB() self.Canvas.ZoomToBB()
@@ -310,7 +310,7 @@ class DrawFrame(wx.Frame):
node.DrawObject = object node.DrawObject = object
Nodes.append(object) Nodes.append(object)
def AddConnectors(node): def AddConnectors(node):
for child in node.Children: for child in node.Children:
Connector = ConnectorLine(node.DrawObject, child.DrawObject, LineWidth=3, LineColor="Red") Connector = ConnectorLine(node.DrawObject, child.DrawObject, LineWidth=3, LineColor="Red")
Connectors.append(Connector) Connectors.append(Connector)
## create the Objects ## create the Objects
@@ -318,14 +318,14 @@ class DrawFrame(wx.Frame):
## create the Connectors ## create the Connectors
TraverseTree(root, AddConnectors) TraverseTree(root, AddConnectors)
## Add the conenctos to the Canvas first, so they are undernieth the nodes ## Add the conenctos to the Canvas first, so they are undernieth the nodes
self.Canvas.AddObjects(Connectors) self.Canvas.AddObjects(Connectors)
## now add the nodes ## now add the nodes
self.Canvas.AddObjects(Nodes) self.Canvas.AddObjects(Nodes)
# Now bind the Nodes -- DrawObjects must be Added to a Canvas before they can be bound. # Now bind the Nodes -- DrawObjects must be Added to a Canvas before they can be bound.
for node in Nodes: for node in Nodes:
#pass #pass
node.Bind(FC.EVT_FC_LEFT_DOWN, self.ObjectHit) node.Bind(FC.EVT_FC_LEFT_DOWN, self.ObjectHit)
def ObjectHit(self, object): def ObjectHit(self, object):
@@ -362,7 +362,7 @@ class DrawFrame(wx.Frame):
if self.MoveObject is not None: if self.MoveObject is not None:
dxy = event.GetPosition() - self.StartPoint dxy = event.GetPosition() - self.StartPoint
dxy = self.Canvas.ScalePixelToWorld(dxy) dxy = self.Canvas.ScalePixelToWorld(dxy)
self.MovingObject.Move(dxy) self.MovingObject.Move(dxy)
self.MoveTri = None self.MoveTri = None
self.Canvas.Draw(True) self.Canvas.Draw(True)

View File

@@ -21,11 +21,11 @@ from wx.lib.floatcanvas import NavCanvas, FloatCanvas
class DrawFrame(wx.Frame): class DrawFrame(wx.Frame):
def __init__(self,parent, id,title,position,size): def __init__(self,parent, id,title,position,size):
wx.Frame.__init__(self,parent, id,title,position, size) wx.Frame.__init__(self,parent, id,title,position, size)
## Set up the MenuBar ## Set up the MenuBar
MenuBar = wx.MenuBar() MenuBar = wx.MenuBar()
file_menu = wx.Menu() file_menu = wx.Menu()
item = file_menu.Append(wx.ID_ANY, "E&xit","Terminate the program") item = file_menu.Append(wx.ID_ANY, "E&xit","Terminate the program")
self.Bind(wx.EVT_MENU, self.OnQuit, item) self.Bind(wx.EVT_MENU, self.OnQuit, item)
@@ -35,22 +35,22 @@ class DrawFrame(wx.Frame):
item = draw_menu.Append(wx.ID_ANY, "&Plot","Re-do Plot") item = draw_menu.Append(wx.ID_ANY, "&Plot","Re-do Plot")
self.Bind(wx.EVT_MENU, self.Plot, item) self.Bind(wx.EVT_MENU, self.Plot, item)
MenuBar.Append(draw_menu, "&Plot") MenuBar.Append(draw_menu, "&Plot")
help_menu = wx.Menu() help_menu = wx.Menu()
item = help_menu.Append(wx.ID_ANY, "&About", item = help_menu.Append(wx.ID_ANY, "&About",
"More information About this program") "More information About this program")
self.Bind(wx.EVT_MENU, self.OnAbout, item) self.Bind(wx.EVT_MENU, self.OnAbout, item)
MenuBar.Append(help_menu, "&Help") MenuBar.Append(help_menu, "&Help")
self.SetMenuBar(MenuBar) self.SetMenuBar(MenuBar)
self.CreateStatusBar() self.CreateStatusBar()
self.SetStatusText("") self.SetStatusText("")
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
# Add the Canvas # Add the Canvas
self.Canvas = NavCanvas.NavCanvas(self ,wx.ID_ANY ,(500,300), self.Canvas = NavCanvas.NavCanvas(self ,wx.ID_ANY ,(500,300),
ProjectionFun = None, ProjectionFun = None,
@@ -60,13 +60,13 @@ class DrawFrame(wx.Frame):
self.Canvas.NumBetweenBlits = 1000 self.Canvas.NumBetweenBlits = 1000
self.Show(True) self.Show(True)
self.Plot() self.Plot()
return None return None
def OnAbout(self, event): def OnAbout(self, event):
dlg = wx.MessageDialog(self, "This is a small program to demonstrate\n" dlg = wx.MessageDialog(self, "This is a small program to demonstrate\n"
"the use of the FloatCanvas\n" "the use of the FloatCanvas\n"
@@ -74,20 +74,20 @@ class DrawFrame(wx.Frame):
"About Me", wx.OK | wx.ICON_INFORMATION) "About Me", wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal() dlg.ShowModal()
dlg.Destroy() dlg.Destroy()
def ZoomToFit(self,event): def ZoomToFit(self,event):
self.Canvas.ZoomToBB() self.Canvas.ZoomToBB()
def OnQuit(self,event): def OnQuit(self,event):
self.Close(True) self.Close(True)
def OnCloseWindow(self, event): def OnCloseWindow(self, event):
self.Destroy() self.Destroy()
def DrawAxis(self): def DrawAxis(self):
Canvas = self.Canvas Canvas = self.Canvas
# Draw the Axis # Draw the Axis
# Note: the AddRectangle Parameters all have sensible # Note: the AddRectangle Parameters all have sensible
@@ -145,59 +145,59 @@ class DrawFrame(wx.Frame):
self.Canvas.Draw() self.Canvas.Draw()
self.Canvas.SaveAsImage("junk.png") self.Canvas.SaveAsImage("junk.png")
class DemoApp(wx.App): class DemoApp(wx.App):
""" """
How the demo works: How the demo works:
Either under the Draw menu, or on the toolbar, you can push Run and Stop Either under the Draw menu, or on the toolbar, you can push Run and Stop
"Run" start an oscilloscope like display of a moving sine curve "Run" start an oscilloscope like display of a moving sine curve
"Stop" stops it. "Stop" stops it.
While the plot os running (or not) you can zoom in and out and move While the plot os running (or not) you can zoom in and out and move
about the picture. There is a tool bar with three tools that can be about the picture. There is a tool bar with three tools that can be
selected. selected.
The magnifying glass with the plus is the zoom in tool. Once 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 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 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. 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, 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 if you click the image, it will zoom out, centered on where you
clicked. clicked.
The hand is the move tool. Once selected, if you click and drag on 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 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 where you release the mouse. Nothing is changed while you are
dragging, but you can see the outline of the former picture. dragging, but you can see the outline of the former picture.
I'd like the cursor to change as you change tools, but the stock I'd like the cursor to change as you change tools, but the stock
wx.Cursors didn't include anything I liked, so I stuck with the wx.Cursors 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 pointer. Please let me know if you have any nice cursor images for me to
use. use.
Any bugs, comments, feedback, questions, and especially code are welcome: Any bugs, comments, feedback, questions, and especially code are welcome:
-Chris Barker -Chris Barker
Chris.Barker@noaa.gov Chris.Barker@noaa.gov
""" """
def OnInit(self): def OnInit(self):
frame = DrawFrame(None, wx.ID_ANY, "Plotting Test",wx.DefaultPosition,wx.Size(700,400)) frame = DrawFrame(None, wx.ID_ANY, "Plotting Test",wx.DefaultPosition,wx.Size(700,400))
self.SetTopWindow(frame) self.SetTopWindow(frame)
return True return True
if __name__ == "__main__": if __name__ == "__main__":
app = DemoApp(0) app = DemoApp(0)
app.MainLoop() app.MainLoop()

View File

@@ -47,9 +47,9 @@ class DrawFrame(wx.Frame):
Debug = 0, Debug = 0,
BackgroundColor = "DARK SLATE BLUE", BackgroundColor = "DARK SLATE BLUE",
).Canvas ).Canvas
self.Canvas = Canvas self.Canvas = Canvas
Point = (0,0) Point = (0,0)
Box = Canvas.AddRectangle(Point, Box = Canvas.AddRectangle(Point,
(80,100), (80,100),
@@ -59,14 +59,14 @@ class DrawFrame(wx.Frame):
Canvas.AddText("%s"%(Point,), Point, Position="cr") Canvas.AddText("%s"%(Point,), Point, Position="cr")
Canvas.AddPoint(Point, Diameter=3, Color = "red") Canvas.AddPoint(Point, Diameter=3, Color = "red")
Point = (0,100) Point = (0,100)
Canvas.AddText("%s"%(Point,), Point, Position="cr") Canvas.AddText("%s"%(Point,), Point, Position="cr")
Canvas.AddPoint(Point, Diameter=3, Color = "red") Canvas.AddPoint(Point, Diameter=3, Color = "red")
self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove )
self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove )
self.Show() self.Show()
Canvas.ZoomToBB() Canvas.ZoomToBB()
@@ -80,10 +80,10 @@ class DrawFrame(wx.Frame):
app = wx.App(False) app = wx.App(False)
F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) ) F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) )
app.MainLoop() app.MainLoop()

View File

@@ -21,13 +21,13 @@ class MyCanvasBase(glcanvas.GLCanvas):
glcanvas.GLCanvas.__init__(self, parent, -1) glcanvas.GLCanvas.__init__(self, parent, -1)
self.init = False self.init = False
self.context = glcanvas.GLContext(self) self.context = glcanvas.GLContext(self)
self.lastx = self.x = 30 self.lastx = self.x = 30
self.lasty = self.y = 30 self.lasty = self.y = 30
self.size = None self.size = None
self.SetBackgroundStyle(wx.BG_STYLE_PAINT) self.SetBackgroundStyle(wx.BG_STYLE_PAINT)
self.Bind(wx.EVT_SIZE, self.OnSize) self.Bind(wx.EVT_SIZE, self.OnSize)
self.Bind(wx.EVT_PAINT, self.OnPaint) self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown) self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown)
@@ -44,7 +44,7 @@ class MyCanvasBase(glcanvas.GLCanvas):
def DoSetViewport(self): def DoSetViewport(self):
size = self.size = self.GetClientSize() size = self.size = self.GetClientSize()
self.SetCurrent(self.context) self.SetCurrent(self.context)
glViewport(0, 0, size.width, size.height) glViewport(0, 0, size.width, size.height)
def OnPaint(self, event): def OnPaint(self, event):

View File

@@ -12,7 +12,7 @@ class SimpleGrid(wx.grid.Grid):
self.SetCellValue(6, 3, "You can veto editing this cell") self.SetCellValue(6, 3, "You can veto editing this cell")
# test all the events # test all the events
self.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.OnCellLeftClick) self.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.OnCellLeftClick)
self.Bind(wx.grid.EVT_GRID_CELL_RIGHT_CLICK, self.OnCellRightClick) self.Bind(wx.grid.EVT_GRID_CELL_RIGHT_CLICK, self.OnCellRightClick)
@@ -81,7 +81,7 @@ class SimpleGrid(wx.grid.Grid):
def OnGridColSort(self, evt): def OnGridColSort(self, evt):
self.log.write("OnGridColSort: %s %s" % (evt.GetCol(), self.GetSortingColumn())) self.log.write("OnGridColSort: %s %s" % (evt.GetCol(), self.GetSortingColumn()))
self.SetSortingColumn(evt.GetCol()) self.SetSortingColumn(evt.GetCol())
def OnRowSize(self, evt): def OnRowSize(self, evt):
self.log.write("OnRowSize: row %d, %s\n" % self.log.write("OnRowSize: row %d, %s\n" %
(evt.GetRowOrCol(), evt.GetPosition())) (evt.GetRowOrCol(), evt.GetPosition()))

View File

@@ -5,7 +5,7 @@ class TestGrid(wx.grid.Grid):
def __init__(self, *args, **kw): def __init__(self, *args, **kw):
wx.grid.Grid.__init__(self, *args, **kw) wx.grid.Grid.__init__(self, *args, **kw)
self.CreateGrid(25, 25) self.CreateGrid(25, 25)
# Show some simple cell formatting # Show some simple cell formatting
self.SetColSize(3, 200) self.SetColSize(3, 200)
self.SetRowSize(4, 45) self.SetRowSize(4, 45)
@@ -33,7 +33,7 @@ class TestGrid(wx.grid.Grid):
# you can set cell attributes for the whole row (or column) # you can set cell attributes for the whole row (or column)
self.SetRowAttr(5, attr) self.SetRowAttr(5, attr)
self.SetColLabelValue(0, "Custom") self.SetColLabelValue(0, "Custom")
self.SetColLabelValue(1, "column") self.SetColLabelValue(1, "column")
self.SetColLabelValue(2, "labels") self.SetColLabelValue(2, "labels")
@@ -55,15 +55,15 @@ class TestGrid(wx.grid.Grid):
self.SetCellRenderer(15,0, renderer) self.SetCellRenderer(15,0, renderer)
self.SetCellValue(15,0, "The text in this cell will be rendered with word-wrapping") self.SetCellValue(15,0, "The text in this cell will be rendered with word-wrapping")
self.SetRowSize(15, 40) self.SetRowSize(15, 40)
class TestFrame(wx.Frame): class TestFrame(wx.Frame):
def __init__(self, *args, **kw): def __init__(self, *args, **kw):
wx.Frame.__init__(self, *args, **kw) wx.Frame.__init__(self, *args, **kw)
self.grid = TestGrid(self) self.grid = TestGrid(self)
app = wx.App() app = wx.App()
frm = TestFrame(None, title="Simple Test Grid", size=(700,500)) frm = TestFrame(None, title="Simple Test Grid", size=(700,500))
frm.Show() frm.Show()

View File

@@ -11,7 +11,7 @@ class TestPanel(wx.Panel):
self.current = "http://wxPython.org" self.current = "http://wxPython.org"
self.frame = self.GetTopLevelParent() self.frame = self.GetTopLevelParent()
self.titleBase = self.frame.GetTitle() self.titleBase = self.frame.GetTitle()
sizer = wx.BoxSizer(wx.VERTICAL) sizer = wx.BoxSizer(wx.VERTICAL)
btnSizer = wx.BoxSizer(wx.HORIZONTAL) btnSizer = wx.BoxSizer(wx.HORIZONTAL)
self.wv = webview.WebView.New(self) self.wv = webview.WebView.New(self)
@@ -19,7 +19,7 @@ class TestPanel(wx.Panel):
self.Bind(webview.EVT_WEBVIEW_NAVIGATED, self.OnWebViewNavigated, self.wv) self.Bind(webview.EVT_WEBVIEW_NAVIGATED, self.OnWebViewNavigated, self.wv)
self.Bind(webview.EVT_WEBVIEW_LOADED, self.OnWebViewLoaded, self.wv) self.Bind(webview.EVT_WEBVIEW_LOADED, self.OnWebViewLoaded, self.wv)
self.Bind(webview.EVT_WEBVIEW_TITLE_CHANGED, self.OnWebViewTitleChanged, self.wv) self.Bind(webview.EVT_WEBVIEW_TITLE_CHANGED, self.OnWebViewTitleChanged, self.wv)
btn = wx.Button(self, -1, "Open", style=wx.BU_EXACTFIT) btn = wx.Button(self, -1, "Open", style=wx.BU_EXACTFIT)
self.Bind(wx.EVT_BUTTON, self.OnOpenButton, btn) self.Bind(wx.EVT_BUTTON, self.OnOpenButton, btn)
btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2) btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)
@@ -50,13 +50,13 @@ class TestPanel(wx.Panel):
self.location.AppendItems(['http://wxPython.org', self.location.AppendItems(['http://wxPython.org',
'http://wxwidgets.org', 'http://wxwidgets.org',
'http://google.com']) 'http://google.com'])
#for url in ['http://wxPython.org', #for url in ['http://wxPython.org',
# 'http://wxwidgets.org', # 'http://wxwidgets.org',
# 'http://google.com']: # 'http://google.com']:
# item = webview.WebViewHistoryItem(url, url) # item = webview.WebViewHistoryItem(url, url)
# self.wv.LoadHistoryItem(item) # self.wv.LoadHistoryItem(item)
self.Bind(wx.EVT_COMBOBOX, self.OnLocationSelect, self.location) self.Bind(wx.EVT_COMBOBOX, self.OnLocationSelect, self.location)
self.location.Bind(wx.EVT_TEXT_ENTER, self.OnLocationEnter) self.location.Bind(wx.EVT_TEXT_ENTER, self.OnLocationEnter)
btnSizer.Add(self.location, 1, wx.EXPAND|wx.ALL, 2) btnSizer.Add(self.location, 1, wx.EXPAND|wx.ALL, 2)
@@ -65,7 +65,7 @@ class TestPanel(wx.Panel):
sizer.Add(btnSizer, 0, wx.EXPAND) sizer.Add(btnSizer, 0, wx.EXPAND)
sizer.Add(self.wv, 1, wx.EXPAND) sizer.Add(self.wv, 1, wx.EXPAND)
self.SetSizer(sizer) self.SetSizer(sizer)
self.wv.LoadURL(self.current) self.wv.LoadURL(self.current)
@@ -82,7 +82,7 @@ class TestPanel(wx.Panel):
def OnWebViewNavigated(self, evt): def OnWebViewNavigated(self, evt):
self.frame.SetStatusText("Loading %s..." % evt.GetURL()) self.frame.SetStatusText("Loading %s..." % evt.GetURL())
def OnWebViewLoaded(self, evt): def OnWebViewLoaded(self, evt):
# The full document has loaded # The full document has loaded
@@ -90,11 +90,11 @@ class TestPanel(wx.Panel):
self.location.SetValue(self.current) self.location.SetValue(self.current)
self.frame.SetStatusText("Loaded") self.frame.SetStatusText("Loaded")
def OnWebViewTitleChanged(self, evt): def OnWebViewTitleChanged(self, evt):
# Set the frame's title to include the document's title # Set the frame's title to include the document's title
self.frame.SetTitle("%s -- %s" % (self.titleBase, evt.GetString())) self.frame.SetTitle("%s -- %s" % (self.titleBase, evt.GetString()))
# Control bar events # Control bar events
def OnLocationSelect(self, evt): def OnLocationSelect(self, evt):
@@ -132,7 +132,7 @@ class TestPanel(wx.Panel):
def OnCheckCanGoBack(self, event): def OnCheckCanGoBack(self, event):
event.Enable(self.wv.CanGoBack()) event.Enable(self.wv.CanGoBack())
def OnCheckCanGoForward(self, event): def OnCheckCanGoForward(self, event):
event.Enable(self.wv.CanGoForward()) event.Enable(self.wv.CanGoForward())
@@ -141,8 +141,8 @@ class TestPanel(wx.Panel):
def OnRefreshPageButton(self, evt): def OnRefreshPageButton(self, evt):
self.wv.Reload() self.wv.Reload()
#---------------------------------------------------------------------- #----------------------------------------------------------------------
@@ -153,7 +153,7 @@ def main():
pnl = TestPanel(frm) pnl = TestPanel(frm)
frm.Show() frm.Show()
app.MainLoop() app.MainLoop()
#---------------------------------------------------------------------- #----------------------------------------------------------------------

View File

@@ -6,7 +6,7 @@ in Python.
""" """
import time import time
import wx import wx
##import os; raw_input('PID: %d\nPress enter...' % os.getpid()) ##import os; raw_input('PID: %d\nPress enter...' % os.getpid())
@@ -27,7 +27,7 @@ class MyFrame(wx.Frame):
panel = wx.Panel(self) panel = wx.Panel(self)
sizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5) sizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
self.sizeCtrl = wx.TextCtrl(panel, -1, "", style=wx.TE_READONLY) self.sizeCtrl = wx.TextCtrl(panel, -1, "", style=wx.TE_READONLY)
sizer.Add(wx.StaticText(panel, -1, "Size:")) sizer.Add(wx.StaticText(panel, -1, "Size:"))
sizer.Add(self.sizeCtrl) sizer.Add(self.sizeCtrl)
@@ -43,7 +43,7 @@ class MyFrame(wx.Frame):
border = wx.BoxSizer() border = wx.BoxSizer()
border.Add(sizer, 0, wx.ALL, 20) border.Add(sizer, 0, wx.ALL, 20)
panel.SetSizer(border) panel.SetSizer(border)
def OnCloseWindow(self, event): def OnCloseWindow(self, event):
self.Destroy() self.Destroy()
@@ -71,22 +71,22 @@ class MyEventLoop(wx.GUIEventLoop):
self.exitCode = 0 self.exitCode = 0
self.shouldExit = False self.shouldExit = False
def DoMyStuff(self): def DoMyStuff(self):
# Do whatever you want to have done for each iteration of the event # Do whatever you want to have done for each iteration of the event
# loop. In this example we'll just sleep a bit to simulate something # loop. In this example we'll just sleep a bit to simulate something
# real happening. # real happening.
time.sleep(0.10) time.sleep(0.10)
def Run(self): def Run(self):
# Set this loop as the active one. It will automatically reset to the # Set this loop as the active one. It will automatically reset to the
# original evtloop when the context manager exits. # original evtloop when the context manager exits.
with wx.EventLoopActivator(self): with wx.EventLoopActivator(self):
while True: while True:
self.DoMyStuff() self.DoMyStuff()
# Generate and process idles events for as long as there # Generate and process idles events for as long as there
# isn't anything else to do # isn't anything else to do
while not self.shouldExit and not self.Pending() and self.ProcessIdle(): while not self.shouldExit and not self.Pending() and self.ProcessIdle():
@@ -94,7 +94,7 @@ class MyEventLoop(wx.GUIEventLoop):
if self.shouldExit: if self.shouldExit:
break break
# dispatch all the pending events and call Dispatch() to wait # dispatch all the pending events and call Dispatch() to wait
# for the next message # for the next message
if not self.ProcessEvents(): if not self.ProcessEvents():
@@ -103,8 +103,8 @@ class MyEventLoop(wx.GUIEventLoop):
# Currently on wxOSX Pending always returns true, so the # Currently on wxOSX Pending always returns true, so the
# ProcessIdle above is not ever called. Call it here instead. # ProcessIdle above is not ever called. Call it here instead.
if 'wxOSX' in wx.PlatformInfo: if 'wxOSX' in wx.PlatformInfo:
self.ProcessIdle() self.ProcessIdle()
# Proces remaining queued messages, if any # Proces remaining queued messages, if any
while True: while True:
checkAgain = False checkAgain = False
@@ -116,29 +116,29 @@ class MyEventLoop(wx.GUIEventLoop):
checkAgain = True checkAgain = True
if not checkAgain: if not checkAgain:
break break
return self.exitCode return self.exitCode
def Exit(self, rc=0): def Exit(self, rc=0):
self.exitCode = rc self.exitCode = rc
self.shouldExit = True self.shouldExit = True
self.OnExit() self.OnExit()
self.WakeUp() self.WakeUp()
def ProcessEvents(self): def ProcessEvents(self):
if wx.GetApp(): if wx.GetApp():
wx.GetApp().ProcessPendingEvents() wx.GetApp().ProcessPendingEvents()
if self.shouldExit: if self.shouldExit:
return False return False
return self.Dispatch() return self.Dispatch()
class MyApp(wx.App): class MyApp(wx.App):

View File

@@ -18,13 +18,13 @@ class TestPanel(wx.Panel):
self.overlay = wx.Overlay() self.overlay = wx.Overlay()
wx.TextCtrl(self, pos=(140,20)) wx.TextCtrl(self, pos=(140,20))
def OnPaint(self, evt): def OnPaint(self, evt):
# Just some simple stuff to paint in the window for an example # Just some simple stuff to paint in the window for an example
dc = wx.PaintDC(self) dc = wx.PaintDC(self)
dc.SetBackground(wx.Brush("sky blue")) dc.SetBackground(wx.Brush("sky blue"))
dc.Clear() dc.Clear()
dc.DrawLabel("Drag the mouse across this window to see \n" dc.DrawLabel("Drag the mouse across this window to see \n"
"a rubber-band effect using wx.Overlay", "a rubber-band effect using wx.Overlay",
(140, 50, -1, -1)) (140, 50, -1, -1))
@@ -34,7 +34,7 @@ class TestPanel(wx.Panel):
dc.SetPen(wx.Pen("red", 2)) dc.SetPen(wx.Pen("red", 2))
dc.SetBrush(wx.CYAN_BRUSH) dc.SetBrush(wx.CYAN_BRUSH)
dc.DrawPolygon(coords) dc.DrawPolygon(coords)
def OnLeftDown(self, evt): def OnLeftDown(self, evt):
# Capture the mouse and save the starting position for the # Capture the mouse and save the starting position for the
@@ -46,7 +46,7 @@ class TestPanel(wx.Panel):
def OnMouseMove(self, evt): def OnMouseMove(self, evt):
if evt.Dragging() and evt.LeftIsDown(): if evt.Dragging() and evt.LeftIsDown():
rect = wx.Rect(topLeft=self.startPos, bottomRight=evt.GetPosition()) rect = wx.Rect(topLeft=self.startPos, bottomRight=evt.GetPosition())
# Draw the rubber-band rectangle using an overlay so it # Draw the rubber-band rectangle using an overlay so it
# will manage keeping the rectangle and the former window # will manage keeping the rectangle and the former window
# contents separate. # contents separate.
@@ -59,7 +59,7 @@ class TestPanel(wx.Panel):
# wx.GCDC so don't try it. # wx.GCDC so don't try it.
if 'wxMac' not in wx.PlatformInfo: if 'wxMac' not in wx.PlatformInfo:
dc = wx.GCDC(dc) dc = wx.GCDC(dc)
dc.SetPen(wx.Pen("black", 2)) dc.SetPen(wx.Pen("black", 2))
dc.SetBrush(wx.Brush(wx.Colour(0xC0, 0xC0, 0xC0, 0x80))) dc.SetBrush(wx.Brush(wx.Colour(0xC0, 0xC0, 0xC0, 0x80)))
dc.DrawRectangle(rect) dc.DrawRectangle(rect)
@@ -78,7 +78,7 @@ class TestPanel(wx.Panel):
del odc del odc
self.overlay.Reset() self.overlay.Reset()
app = wx.App(redirect=False) app = wx.App(redirect=False)
frm = wx.Frame(None, title="wx.Overlay Test", size=(450,450)) frm = wx.Frame(None, title="wx.Overlay Test", size=(450,450))

View File

@@ -54,16 +54,16 @@ class TextDocPrintout(wx.Printout):
dw, dh = dc.GetSize() dw, dh = dc.GetSize()
self.x1 = topLeft.x * self.logUnitsMM self.x1 = topLeft.x * self.logUnitsMM
self.y1 = topLeft.y * self.logUnitsMM self.y1 = topLeft.y * self.logUnitsMM
self.x2 = dc.DeviceToLogicalXRel(dw) - bottomRight.x * self.logUnitsMM self.x2 = dc.DeviceToLogicalXRel(dw) - bottomRight.x * self.logUnitsMM
self.y2 = dc.DeviceToLogicalYRel(dh) - bottomRight.y * self.logUnitsMM self.y2 = dc.DeviceToLogicalYRel(dh) - bottomRight.y * self.logUnitsMM
# use a 1mm buffer around the inside of the box, and a few # use a 1mm buffer around the inside of the box, and a few
# pixels between each line # pixels between each line
self.pageHeight = self.y2 - self.y1 - 2*self.logUnitsMM self.pageHeight = self.y2 - self.y1 - 2*self.logUnitsMM
font = wx.Font(FONTSIZE, wx.FONTFAMILY_TELETYPE, font = wx.Font(FONTSIZE, wx.FONTFAMILY_TELETYPE,
wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)
dc.SetFont(font) dc.SetFont(font)
self.lineHeight = dc.GetCharHeight() self.lineHeight = dc.GetCharHeight()
self.linesPerPage = int(self.pageHeight/self.lineHeight) self.linesPerPage = int(self.pageHeight/self.lineHeight)
@@ -112,7 +112,7 @@ class PrintFrameworkSample(wx.Frame):
# A text widget to display the doc and let it be edited # A text widget to display the doc and let it be edited
self.tc = wx.TextCtrl(self, -1, "", self.tc = wx.TextCtrl(self, -1, "",
style=wx.TE_MULTILINE|wx.TE_DONTWRAP) style=wx.TE_MULTILINE|wx.TE_DONTWRAP)
self.tc.SetFont(wx.Font(FONTSIZE, wx.FONTFAMILY_TELETYPE, self.tc.SetFont(wx.Font(FONTSIZE, wx.FONTFAMILY_TELETYPE,
wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL))
filename = os.path.join(os.path.dirname(__file__), "sample-text.txt") filename = os.path.join(os.path.dirname(__file__), "sample-text.txt")
self.tc.SetValue(open(filename).read()) self.tc.SetValue(open(filename).read())
@@ -135,10 +135,10 @@ class PrintFrameworkSample(wx.Frame):
## menu.AppendSeparator() ## menu.AppendSeparator()
item = menu.Append(wx.ID_ABOUT, "About", "About this application") item = menu.Append(wx.ID_ABOUT, "About", "About this application")
self.Bind(wx.EVT_MENU, self.OnAbout, item) self.Bind(wx.EVT_MENU, self.OnAbout, item)
item = menu.Append(wx.ID_EXIT, "E&xit\tCtrl-Q", "Close this application") item = menu.Append(wx.ID_EXIT, "E&xit\tCtrl-Q", "Close this application")
self.Bind(wx.EVT_MENU, self.OnExit, item) self.Bind(wx.EVT_MENU, self.OnExit, item)
menubar = wx.MenuBar() menubar = wx.MenuBar()
menubar.Append(menu, "&File") menubar.Append(menu, "&File")
self.SetMenuBar(menubar) self.SetMenuBar(menubar)
@@ -187,7 +187,7 @@ class PrintFrameworkSample(wx.Frame):
def OnPrintPreview(self, evt): def OnPrintPreview(self, evt):
data = wx.PrintDialogData(self.pdata) data = wx.PrintDialogData(self.pdata)
text = self.tc.GetValue() text = self.tc.GetValue()
printout1 = TextDocPrintout(text, "title", self.margins) printout1 = TextDocPrintout(text, "title", self.margins)
printout2 = TextDocPrintout(text, "title", self.margins) printout2 = TextDocPrintout(text, "title", self.margins)
preview = wx.PrintPreview(printout1, printout2, data) preview = wx.PrintPreview(printout1, printout2, data)
@@ -205,7 +205,7 @@ class PrintFrameworkSample(wx.Frame):
def OnPrint(self, evt): def OnPrint(self, evt):
data = wx.PrintDialogData(self.pdata) data = wx.PrintDialogData(self.pdata)
printer = wx.Printer(data) printer = wx.Printer(data)
text = self.tc.GetValue() text = self.tc.GetValue()
printout = TextDocPrintout(text, "title", self.margins) printout = TextDocPrintout(text, "title", self.margins)
useSetupDialog = True useSetupDialog = True
if not printer.Print(self, printout, useSetupDialog) \ if not printer.Print(self, printout, useSetupDialog) \
@@ -241,8 +241,8 @@ class PrintFrameworkSample(wx.Frame):
print_("GetPrinterName:", self.pdata.GetPrinterName()) print_("GetPrinterName:", self.pdata.GetPrinterName())
dlg.Destroy() dlg.Destroy()
app = wx.App() app = wx.App()
frm = PrintFrameworkSample() frm = PrintFrameworkSample()
frm.Show() frm.Show()

View File

@@ -50,7 +50,7 @@ class TestPanel(wx.Panel):
tm = t.timeit(num) tm = t.timeit(num)
log.write("%d passes creating %dx%d images in %f seconds\n" log.write("%d passes creating %dx%d images in %f seconds\n"
"\t%f seconds per pass " % (num, DIM,DIM, tm, tm/num)) "\t%f seconds per pass " % (num, DIM,DIM, tm, tm/num))
if not USE_NUMPY: if not USE_NUMPY:
log.write("using raw access\n") log.write("using raw access\n")
self.redBmp = self.MakeBitmap(178, 34, 34) self.redBmp = self.MakeBitmap(178, 34, 34)
@@ -122,7 +122,7 @@ class TestPanel(wx.Panel):
pixels.Set(red, green, blue, wx.ALPHA_OPAQUE) pixels.Set(red, green, blue, wx.ALPHA_OPAQUE)
pixels.MoveTo(pixelData, DIM-1, y) pixels.MoveTo(pixelData, DIM-1, y)
pixels.Set(red, green, blue, wx.ALPHA_OPAQUE) pixels.Set(red, green, blue, wx.ALPHA_OPAQUE)
return bmp return bmp
@@ -149,9 +149,9 @@ class TestPanel(wx.Panel):
# finally, use the array to create a bitmap # finally, use the array to create a bitmap
bmp = wx.Bitmap.FromBufferRGBA(DIM, DIM, arr) bmp = wx.Bitmap.FromBufferRGBA(DIM, DIM, arr)
return bmp return bmp
#---------------------------------------------------------------------- #----------------------------------------------------------------------
if __name__ == '__main__': if __name__ == '__main__':
@@ -160,4 +160,4 @@ if __name__ == '__main__':
pnl = TestPanel(frm, sys.stdout) pnl = TestPanel(frm, sys.stdout)
frm.Show() frm.Show()
app.MainLoop() app.MainLoop()

View File

@@ -49,7 +49,7 @@ class rose:
# The following data is accessible by callers, but there are set # The following data is accessible by callers, but there are set
# methods for most everything and various method calls to client methods # methods for most everything and various method calls to client methods
# to display current values. # to display current values.
style = 100 # Angular distance along curve between points style = 100 # Angular distance along curve between points
sincr = -1 # Amount to increment style by in auto mode sincr = -1 # Amount to increment style by in auto mode
petals = 2 # Lobes on the rose (even values have 2X lobes) petals = 2 # Lobes on the rose (even values have 2X lobes)
@@ -66,7 +66,7 @@ class rose:
# Other variables that the application shouldn't access. # Other variables that the application shouldn't access.
verbose = 0 # No good way to set this at the moment. verbose = 0 # No good way to set this at the moment.
nextpt = 0 # Next position to draw on next clock tick nextpt = 0 # Next position to draw on next clock tick
# Internal states: # Internal states:
INT_IDLE, INT_DRAW, INT_SEARCH, INT_WAIT, INT_RESIZE = range(5) INT_IDLE, INT_DRAW, INT_SEARCH, INT_WAIT, INT_RESIZE = range(5)
int_state = INT_IDLE int_state = INT_IDLE
@@ -74,7 +74,7 @@ class rose:
# Command states # Command states
CMD_STOP, CMD_GO = range(2) CMD_STOP, CMD_GO = range(2)
cmd_state = CMD_STOP cmd_state = CMD_STOP
# Return full rose line (a tuple of (x, y) tuples). Not used by interactive # Return full rose line (a tuple of (x, y) tuples). Not used by interactive
# clients but still useful for command line and batch clients. # clients but still useful for command line and batch clients.
# This is the "purest" code and doesn't require the App* methods defined # This is the "purest" code and doesn't require the App* methods defined
@@ -91,7 +91,7 @@ class rose:
return line return line
# Generate vectors for the next chunk of rose. # Generate vectors for the next chunk of rose.
# This is not meant to be called from an external module, as it is closely # This is not meant to be called from an external module, as it is closely
# coupled to parameters set up within the class and limits set up by # coupled to parameters set up within the class and limits set up by
# restart(). Restart() initializes all data this needs to start drawing a # restart(). Restart() initializes all data this needs to start drawing a
@@ -122,7 +122,7 @@ class rose:
def make_tables(self, vectors): def make_tables(self, vectors):
self.sin_table = [sin(2.0 * pi * i / vectors) for i in range(vectors)] self.sin_table = [sin(2.0 * pi * i / vectors) for i in range(vectors)]
self.cos_table = [cos(2.0 * pi * i / vectors) for i in range(vectors)] self.cos_table = [cos(2.0 * pi * i / vectors) for i in range(vectors)]
# Rescale (x,y) data to match our window. Note the negative scaling in the # Rescale (x,y) data to match our window. Note the negative scaling in the
# Y direction, this compensates for Y moving down the screen, but up on # Y direction, this compensates for Y moving down the screen, but up on
# graph paper. # graph paper.
@@ -186,7 +186,7 @@ class rose:
self.center = (xsize / 2, ysize / 2) self.center = (xsize / 2, ysize / 2)
self.scale = min(xsize, ysize) / 2.1 self.scale = min(xsize, ysize) / 2.1
self.repaint(delay) self.repaint(delay)
# Called from App or above. From App, called with small delay because # Called from App or above. From App, called with small delay because
# some window managers will produce a flood of expose events or call us # some window managers will produce a flood of expose events or call us
# before initialization is done. # before initialization is done.
@@ -196,7 +196,7 @@ class rose:
self.int_state = self.INT_RESIZE self.int_state = self.INT_RESIZE
self.AppCancelTimer() self.AppCancelTimer()
self.AppAfter(delay, self.clock) self.AppAfter(delay, self.clock)
# Method that returns the next style and petal values for automatic # Method that returns the next style and petal values for automatic
# mode and remembers them internally. Keep things scaled in the # mode and remembers them internally. Keep things scaled in the
# range [0:nvec) because there's little reason to exceed that. # range [0:nvec) because there's little reason to exceed that.
@@ -253,7 +253,7 @@ class rose:
self.pincr = -self.pincr self.pincr = -self.pincr
else: else:
self.AppSetIncrs(self.sincr, self.pincr) self.AppSetIncrs(self.sincr, self.pincr)
# Forward/Skip button. CMD_STOP & CMD_GO both just call resume. # Forward/Skip button. CMD_STOP & CMD_GO both just call resume.
def cmd_step(self): def cmd_step(self):
self.resume() # Draw next pattern self.resume() # Draw next pattern
@@ -292,7 +292,7 @@ class rose:
self.AppSetParam(self.style, self.petals, self.nvec) self.AppSetParam(self.style, self.petals, self.nvec)
self.AppSetIncrs(self.sincr, self.pincr) self.AppSetIncrs(self.sincr, self.pincr)
delay = self.restart() # Calls us to start drawing delay = self.restart() # Calls us to start drawing
if delay == 0: if delay == 0:
if self.verbose: if self.verbose:
print_('clock: going idle from state', self.int_state) print_('clock: going idle from state', self.int_state)
@@ -310,7 +310,7 @@ class rose:
# We restrict the style and petals parameters to the range [0: nvec) # We restrict the style and petals parameters to the range [0: nvec)
# since numbers outside of that range aren't interesting. We don't # since numbers outside of that range aren't interesting. We don't
# immediately update the value in the application, we probably should. # immediately update the value in the application, we probably should.
# NW control window - key parameters # NW control window - key parameters
def SetStyle(self, value): def SetStyle(self, value):
self.style = value % self.nvec self.style = value % self.nvec

View File

@@ -96,7 +96,7 @@ class SpinPanel(wx.Panel):
sizer.Add((1,1), 1) sizer.Add((1,1), 1)
sizer.Add(self.sc) sizer.Add(self.sc)
self.SetSizer(sizer) self.SetSizer(sizer)
global spin_panels global spin_panels
spin_panels[name] = self spin_panels[name] = self
@@ -128,7 +128,7 @@ class RosePanel(wx.Panel):
# set default colors # set default colors
self.SetBackgroundColour((51, 51, 51)) # gray20 self.SetBackgroundColour((51, 51, 51)) # gray20
self.SetForegroundColour((164, 211, 238)) # lightskyblue2 self.SetForegroundColour((164, 211, 238)) # lightskyblue2
# connect the size and paint events to handlers # connect the size and paint events to handlers
self.Bind(wx.EVT_SIZE, self.OnSize) self.Bind(wx.EVT_SIZE, self.OnSize)
self.Bind(wx.EVT_PAINT, self.OnPaint) self.Bind(wx.EVT_PAINT, self.OnPaint)
@@ -139,7 +139,7 @@ class RosePanel(wx.Panel):
size = self.GetClientSize() size = self.GetClientSize()
self.buffer = wx.Bitmap(max(1, size.width), self.buffer = wx.Bitmap(max(1, size.width),
max(1, size.height)) max(1, size.height))
def Clear(self): def Clear(self):
dc = self.useBuffer and wx.MemoryDC(self.buffer) or wx.ClientDC(self) dc = self.useBuffer and wx.MemoryDC(self.buffer) or wx.ClientDC(self)
dc.SetBackground(wx.Brush(self.GetBackgroundColour())) dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
@@ -163,7 +163,7 @@ class RosePanel(wx.Panel):
def TriggerRedraw(self): def TriggerRedraw(self):
self.GetParent().TriggerRedraw() self.GetParent().TriggerRedraw()
def OnSize(self, evt): def OnSize(self, evt):
self.resizeNeeded = True self.resizeNeeded = True
@@ -203,9 +203,9 @@ class OptionsPanel(wx.Panel):
sizer.Add((4,4)) sizer.Add((4,4))
sizer.Add(lbl, 0, wx.ALIGN_CENTER_VERTICAL) sizer.Add(lbl, 0, wx.ALIGN_CENTER_VERTICAL)
return sizer, btn return sizer, btn
s, self.fg = makeCButton('Foreground') s, self.fg = makeCButton('Foreground')
sizer.Add(s) sizer.Add(s)
s, self.bg = makeCButton('Background') s, self.bg = makeCButton('Background')
sizer.Add(s) sizer.Add(s)
self.SetSizer(sizer) self.SetSizer(sizer)
@@ -233,7 +233,7 @@ class OptionsPanel(wx.Panel):
def OnUseBuffer(self, evt): def OnUseBuffer(self, evt):
self.rose.useBuffer = evt.IsChecked() self.rose.useBuffer = evt.IsChecked()
self.rose.TriggerRedraw() self.rose.TriggerRedraw()
def OnSetFG(self, evt): def OnSetFG(self, evt):
self.rose.SetForegroundColour(evt.GetValue()) self.rose.SetForegroundColour(evt.GetValue())
self.rose.TriggerRedraw() self.rose.TriggerRedraw()
@@ -277,12 +277,12 @@ class MyFrame(wx.Frame, clroses.rose):
sizer.Add(st, 0, wx.EXPAND) sizer.Add(st, 0, wx.EXPAND)
panel.SetSizer(sizer) panel.SetSizer(sizer)
return panel return panel
wx.Frame.__init__(self, None, title="Roses in wxPython") wx.Frame.__init__(self, None, title="Roses in wxPython")
self.rose_panel = RosePanel(self) self.rose_panel = RosePanel(self)
self.side_panel = wx.Panel(self) self.side_panel = wx.Panel(self)
# The cmd panel is four buttons whose names and foreground colors # The cmd panel is four buttons whose names and foreground colors
# change. Plop them in a StaticBox like the SpinPanels. Use # change. Plop them in a StaticBox like the SpinPanels. Use
# a 2x2 grid, but StaticBoxSizer can't handle that. Therefore, # a 2x2 grid, but StaticBoxSizer can't handle that. Therefore,
@@ -330,14 +330,14 @@ class MyFrame(wx.Frame, clroses.rose):
('Skip first', 0, 0, 3600), ('Skip first', 0, 0, 3600),
('Draw only' , 1, 3600, 3600)), ('Draw only' , 1, 3600, 3600)),
(('Takes', 'Takes 0000 vectors'), )) (('Takes', 'Takes 0000 vectors'), ))
self.tim_panel = makeSP('Timing', self.tim_panel = makeSP('Timing',
(('Vec/tick' , 1, 20, 3600), (('Vec/tick' , 1, 20, 3600),
('msec/tick', 1, 50, 1000), ('msec/tick', 1, 50, 1000),
('Delay' , 1, 2000, 9999))) ('Delay' , 1, 2000, 9999)))
self.opt_panel = OptionsPanel(self.side_panel, self.rose_panel) self.opt_panel = OptionsPanel(self.side_panel, self.rose_panel)
# put them all on in a sizer attached to the side_panel # put them all on in a sizer attached to the side_panel
panelSizer = wx.BoxSizer(wx.VERTICAL) panelSizer = wx.BoxSizer(wx.VERTICAL)
panelSizer.Add(self.cmd_panel, 0, wx.EXPAND|wx.TOP|wx.LEFT|wx.RIGHT, 5) panelSizer.Add(self.cmd_panel, 0, wx.EXPAND|wx.TOP|wx.LEFT|wx.RIGHT, 5)
@@ -412,12 +412,12 @@ class MyFrame(wx.Frame, clroses.rose):
# implement the missing parts of the functionality needed to do # implement the missing parts of the functionality needed to do
# the actual work of getting the diagram to the screen and etc. # the actual work of getting the diagram to the screen and etc.
# Those are implemented here as the App* methods. # Those are implemented here as the App* methods.
def AppClear(self): def AppClear(self):
if verbose: if verbose:
print_('AppClear: clear screen') print_('AppClear: clear screen')
self.rose_panel.Clear() self.rose_panel.Clear()
def AppCreateLine(self, line): def AppCreateLine(self, line):
# print('AppCreateLine, len', len(line), 'next', self.nextpt) # print('AppCreateLine, len', len(line), 'next', self.nextpt)
self.rose_panel.DrawLines(line) self.rose_panel.DrawLines(line)
@@ -439,7 +439,7 @@ class MyFrame(wx.Frame, clroses.rose):
spin_panels['Maximum'].SetValue(maxvec) spin_panels['Maximum'].SetValue(maxvec)
spin_panels['Skip first'].SetValue(skipvec) spin_panels['Skip first'].SetValue(skipvec)
spin_panels['Draw only'].SetValue(drawvec) spin_panels['Draw only'].SetValue(drawvec)
def AppSetTakesVec(self, takes): def AppSetTakesVec(self, takes):
spin_panels['Takes'].SetLabel('Takes %d vectors' % takes) spin_panels['Takes'].SetLabel('Takes %d vectors' % takes)
@@ -463,7 +463,7 @@ class MyFrame(wx.Frame, clroses.rose):
# AppAfter and OnTimer alternate, but don't verify that AppCancelTimer() # AppAfter and OnTimer alternate, but don't verify that AppCancelTimer()
# is canceling anything as callers of that may be uncertain about what's # is canceling anything as callers of that may be uncertain about what's
# happening. # happening.
# Method to provide a single callback after some amount of time. # Method to provide a single callback after some amount of time.
def AppAfter(self, msec, callback): def AppAfter(self, msec, callback):
if self.timer_callback: if self.timer_callback:
@@ -491,7 +491,7 @@ class MyFrame(wx.Frame, clroses.rose):
resize_delay = 300 resize_delay = 300
def TriggerResize(self, size): def TriggerResize(self, size):
self.resize(size, self.resize_delay) self.resize(size, self.resize_delay)
self.resize_delay = 100 self.resize_delay = 100

View File

@@ -3,18 +3,18 @@ import wx
class MyDialog(wx.Dialog): class MyDialog(wx.Dialog):
def __init__(self, *args, **kw): def __init__(self, *args, **kw):
wx.Dialog.__init__(self, *args, **kw) wx.Dialog.__init__(self, *args, **kw)
# Widgets # Widgets
txt = wx.StaticText(self, label="Hello. I am a Dialog! Hear me roar!") txt = wx.StaticText(self, label="Hello. I am a Dialog! Hear me roar!")
ok = wx.Button(self, wx.ID_OK) ok = wx.Button(self, wx.ID_OK)
ok.SetDefault() ok.SetDefault()
cancel = wx.Button(self, wx.ID_CANCEL) cancel = wx.Button(self, wx.ID_CANCEL)
# Layout # Layout
self.Sizer = wx.BoxSizer(wx.VERTICAL) # using the Sizer property self.Sizer = wx.BoxSizer(wx.VERTICAL) # using the Sizer property
self.Sizer.Add(txt, 0, wx.ALL, 10) self.Sizer.Add(txt, 0, wx.ALL, 10)
self.Sizer.Add(wx.StaticLine(self), 0, wx.EXPAND) self.Sizer.Add(wx.StaticLine(self), 0, wx.EXPAND)
# make a new sizer to hold the buttons # make a new sizer to hold the buttons
row = wx.BoxSizer(wx.HORIZONTAL) row = wx.BoxSizer(wx.HORIZONTAL)
row.Add((1,1), 1) # a spacer that gets a portion of the free space row.Add((1,1), 1) # a spacer that gets a portion of the free space
@@ -22,16 +22,16 @@ class MyDialog(wx.Dialog):
row.Add((1,1), 1) row.Add((1,1), 1)
row.Add(cancel) row.Add(cancel)
row.Add((1,1), 1) row.Add((1,1), 1)
# add that sizer to the main sizer # add that sizer to the main sizer
self.Sizer.Add(row, 0, wx.EXPAND|wx.ALL, 10) self.Sizer.Add(row, 0, wx.EXPAND|wx.ALL, 10)
# size the dialog to fit the content managed by the sizer # size the dialog to fit the content managed by the sizer
self.Fit() self.Fit()
app = wx.App() app = wx.App()
dlg = MyDialog(None, title="Hello Dialog") dlg = MyDialog(None, title="Hello Dialog")
val = dlg.ShowModal() val = dlg.ShowModal()
dlg.Destroy() dlg.Destroy()
app.MainLoop() app.MainLoop()

View File

@@ -11,25 +11,25 @@ class MyFrame(wx.Frame):
wx.Frame.__init__(self, *args, **kw) wx.Frame.__init__(self, *args, **kw)
self.Bind(wx.EVT_SIZE, self.onSize) self.Bind(wx.EVT_SIZE, self.onSize)
wx.CallAfter(self.after, 1, 2, 3) wx.CallAfter(self.after, 1, 2, 3)
def after(self, a, b, c): def after(self, a, b, c):
print_('Called via wx.CallAfter:', a, b, c) print_('Called via wx.CallAfter:', a, b, c)
def onSize(self, evt): def onSize(self, evt):
print_(repr(evt.Size)) print_(repr(evt.Size))
evt.Skip() evt.Skip()
class MyApp(wx.App): class MyApp(wx.App):
def OnInit(self): def OnInit(self):
print_('OnInit') print_('OnInit')
frm = MyFrame(None, title="Hello with Events", size=(480,360)) frm = MyFrame(None, title="Hello with Events", size=(480,360))
frm.Show() frm.Show()
return True return True
def OnExit(self): def OnExit(self):
print_('OnExit') print_('OnExit')
return 0 return 0
app = MyApp() app = MyApp()
app.MainLoop() app.MainLoop()

View File

@@ -18,14 +18,14 @@ class ThreadedTask(threading.Thread):
self.counter = 0 self.counter = 0
self.sleepTime = random.random()/2 self.sleepTime = random.random()/2
self.timeToDie = False self.timeToDie = False
def run(self): def run(self):
while not self.timeToDie: while not self.timeToDie:
time.sleep(self.sleepTime) time.sleep(self.sleepTime)
self.counter += 1 self.counter += 1
print('thread: %5s count: %d' % (self.name, self.counter)) print('thread: %5s count: %d' % (self.name, self.counter))
class MainFrame(wx.Frame): class MainFrame(wx.Frame):
def __init__(self): def __init__(self):
@@ -36,8 +36,8 @@ class MainFrame(wx.Frame):
self.pnl.Bind(wx.EVT_CONTEXT_MENU, self.onShowMenu) self.pnl.Bind(wx.EVT_CONTEXT_MENU, self.onShowMenu)
btn = wx.Button(self.pnl, label='timed test', pos=(10, 60)) btn = wx.Button(self.pnl, label='timed test', pos=(10, 60))
self.Bind(wx.EVT_BUTTON, self.onOtherButton, btn) self.Bind(wx.EVT_BUTTON, self.onOtherButton, btn)
def onButton(self, evt): def onButton(self, evt):
dlg = wx.Dialog(self, title='close this dialog', size=(300,150)) dlg = wx.Dialog(self, title='close this dialog', size=(300,150))
dlg.ShowModal() dlg.ShowModal()
@@ -58,8 +58,8 @@ class MainFrame(wx.Frame):
s.IncBy(4,6) s.IncBy(4,6)
wx.MessageBox('%d reps performed in %f seconds' % (reps, time.time() - start), wx.MessageBox('%d reps performed in %f seconds' % (reps, time.time() - start),
'Results') 'Results')
def onShowMenu(self, evt): def onShowMenu(self, evt):
menu = wx.Menu() menu = wx.Menu()
menu.Append(-1, 'one') menu.Append(-1, 'one')
@@ -67,13 +67,13 @@ class MainFrame(wx.Frame):
menu.Append(-1, 'three') menu.Append(-1, 'three')
self.pnl.PopupMenu(menu) self.pnl.PopupMenu(menu)
menu.Destroy() menu.Destroy()
threads = [ ThreadedTask(name='one'), ThreadedTask(name='two'), ThreadedTask(name='three') ] threads = [ ThreadedTask(name='one'), ThreadedTask(name='two'), ThreadedTask(name='three') ]
for t in threads: for t in threads:
t.start() t.start()
app = wx.App() app = wx.App()
frm = MainFrame() frm = MainFrame()
frm.Show() frm.Show()
@@ -81,5 +81,4 @@ app.MainLoop()
for t in threads: for t in threads:
t.timeToDie = True t.timeToDie = True

View File

@@ -9,8 +9,8 @@ pnl.BackgroundColour = 'sky blue'
st = wx.StaticText(pnl, -1, 'Hello World!', (15,10)) st = wx.StaticText(pnl, -1, 'Hello World!', (15,10))
st.SetFont(wx.FFont(14, wx.FONTFAMILY_SWISS, wx.FONTFLAG_BOLD)) st.SetFont(wx.FFont(14, wx.FONTFAMILY_SWISS, wx.FONTFLAG_BOLD))
st = wx.StaticText(pnl, pos=(15,40), st = wx.StaticText(pnl, pos=(15,40),
label='This is wxPython %s\nrunning on Python %s %s' % label='This is wxPython %s\nrunning on Python %s %s' %
(wx.version(), sys.version.split(' ')[0], platform.architecture()[0])) (wx.version(), sys.version.split(' ')[0], platform.architecture()[0]))
st.SetFont(wx.FFont(10, wx.FONTFAMILY_SWISS, wx.FONTFLAG_BOLD)) st.SetFont(wx.FFont(10, wx.FONTFAMILY_SWISS, wx.FONTFLAG_BOLD))
@@ -20,4 +20,4 @@ sb = wx.StaticBitmap(pnl, label=bmp, pos=(15,85))
frm.Show() frm.Show()
app.MainLoop() app.MainLoop()

View File

@@ -25,7 +25,7 @@ class MyFrame(wx.Frame):
# Create the menubar # Create the menubar
menuBar = wx.MenuBar() menuBar = wx.MenuBar()
# and a menu # and a menu
menu = wx.Menu() menu = wx.Menu()
# add an item to the menu, using \tKeyName automatically # add an item to the menu, using \tKeyName automatically
@@ -41,7 +41,7 @@ class MyFrame(wx.Frame):
self.SetMenuBar(menuBar) self.SetMenuBar(menuBar)
self.CreateStatusBar() self.CreateStatusBar()
# Now create the Panel to put the other controls on. # Now create the Panel to put the other controls on.
panel = wx.Panel(self) panel = wx.Panel(self)
@@ -73,7 +73,7 @@ class MyFrame(wx.Frame):
self.SetSizer(sizer) self.SetSizer(sizer)
self.Fit() self.Fit()
self.CenterOnScreen(wx.BOTH) self.CenterOnScreen(wx.BOTH)
def OnTimeToClose(self, evt): def OnTimeToClose(self, evt):
"""Event handler for the button click.""" """Event handler for the button click."""
@@ -97,7 +97,7 @@ class MyApp(AppBaseClass):
frame.Show(True) frame.Show(True)
return True return True
app = MyApp(redirect=True) app = MyApp(redirect=True)
app.MainLoop() app.MainLoop()

View File

@@ -15,16 +15,16 @@ class Frame(wx.Frame):
hwin = HtmlWindow(self, -1, size=(600,400)) hwin = HtmlWindow(self, -1, size=(600,400))
name = os.path.join(os.path.dirname(sys.argv[0]), 'widgetTest.html') name = os.path.join(os.path.dirname(sys.argv[0]), 'widgetTest.html')
hwin.LoadPage(name) hwin.LoadPage(name)
hwin.Bind(wx.EVT_BUTTON, self.OnButton, id=wx.ID_OK) hwin.Bind(wx.EVT_BUTTON, self.OnButton, id=wx.ID_OK)
def OnClose(self, event): def OnClose(self, event):
self.Destroy() self.Destroy()
def OnButton(self, event): def OnButton(self, event):
print('It works!') print('It works!')
app = wx.App() app = wx.App()
top = Frame("wxpTest") top = Frame("wxpTest")