Demo updates for new wx namespace, from Jeff Grimmett

git-svn-id: https://svn.wxwidgets.org/svn/wx/wxWidgets/trunk@24723 c3d73ce0-8a6f-49c7-b76d-6d57e0e08775
This commit is contained in:
Robin Dunn
2003-12-09 01:23:28 +00:00
parent a61d40115f
commit 8fa876ca9e
147 changed files with 7313 additions and 5154 deletions

View File

@@ -13,58 +13,65 @@ have Acrobat Reader 4.0 installed it won't work.
</body></html> </body></html>
""" """
from wxPython.wx import * # 11/24/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for 2.5
#
if wxPlatform == '__WXMSW__': import sys
from wxPython.lib.activexwrapper import MakeActiveXClass import wx
if wx.Platform == '__WXMSW__':
import wx.lib.activexwrapper as ax
import win32com.client.gencache import win32com.client.gencache
try: try:
acrobat = win32com.client.gencache.EnsureModule('{CA8A9783-280D-11CF-A24D-444553540000}', 0x0, 1, 3) acrobat = win32com.client.gencache.EnsureModule(
'{CA8A9783-280D-11CF-A24D-444553540000}', 0x0, 1, 3
)
except: except:
raise ImportError("Can't load PDF.OCX, install Acrobat 4.0") raise ImportError("Can't load PDF.OCX, install Acrobat 4.0")
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.pdf = None self.pdf = None
sizer = wxBoxSizer(wxVERTICAL) sizer = wx.BoxSizer(wx.VERTICAL)
btnSizer = wxBoxSizer(wxHORIZONTAL) btnSizer = wx.BoxSizer(wx.HORIZONTAL)
# this function creates a new class that can be used as # this function creates a new class that can be used as
# a wxWindow, but contains the given ActiveX control. # a wx.Window, but contains the given ActiveX control.
ActiveXWrapper = MakeActiveXClass(acrobat.Pdf) ActiveXWrapper = ax.MakeActiveXClass(acrobat.Pdf)
# create an instance of the new class # create an instance of the new class
self.pdf = ActiveXWrapper( self, -1, style=wxSUNKEN_BORDER) self.pdf = ActiveXWrapper( self, -1, style=wx.SUNKEN_BORDER)
sizer.Add(self.pdf, 1, wxEXPAND) sizer.Add(self.pdf, proportion=1, flag=wx.EXPAND)
btn = wxButton(self, wxNewId(), "Open PDF File") btn = wx.Button(self, wx.NewId(), "Open PDF File")
EVT_BUTTON(self, btn.GetId(), self.OnOpenButton) self.Bind(wx.EVT_BUTTON, self.OnOpenButton)
btnSizer.Add(btn, 1, wxEXPAND|wxALL, 5) btnSizer.Add(btn, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
btn = wxButton(self, wxNewId(), "<-- Previous Page") btn = wx.Button(self, wx.NewId(), "<-- Previous Page")
EVT_BUTTON(self, btn.GetId(), self.OnPrevPageButton) self.Bind(wx.EVT_BUTTON, self.OnPrevPageButton, id=btn.GetId())
btnSizer.Add(btn, 1, wxEXPAND|wxALL, 5) btnSizer.Add(btn, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
btn = wxButton(self, wxNewId(), "Next Page -->") btn = wx.Button(self, wx.NewId(), "Next Page -->")
EVT_BUTTON(self, btn.GetId(), self.OnNextPageButton) self.Bind(wx.EVT_BUTTON, self.OnNextPageButton, id=btn.GetId())
btnSizer.Add(btn, 1, wxEXPAND|wxALL, 5) btnSizer.Add(btn, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
btnSizer.Add(50, -1, 2, wxEXPAND) btnSizer.Add((50,-1), proportion=2, flag=wx.EXPAND)
sizer.Add(btnSizer, 0, wxEXPAND) sizer.Add(btnSizer, proportion=0, flag=wx.EXPAND)
self.SetSizer(sizer) self.SetSizer(sizer)
self.SetAutoLayout(True) self.SetAutoLayout(True)
EVT_WINDOW_DESTROY(self, self.OnDestroy) self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
def OnDestroy(self, evt): def OnDestroy(self, evt):
@@ -75,11 +82,12 @@ class TestPanel(wxPanel):
def OnOpenButton(self, event): def OnOpenButton(self, event):
dlg = wxFileDialog(self, wildcard="*.pdf") dlg = wx.FileDialog(self, wildcard="*.pdf")
if dlg.ShowModal() == wxID_OK:
wxBeginBusyCursor() if dlg.ShowModal() == wx.ID_OK:
wx.BeginBusyCursor()
self.pdf.LoadFile(dlg.GetPath()) self.pdf.LoadFile(dlg.GetPath())
wxEndBusyCursor() wx.EndBusyCursor()
dlg.Destroy() dlg.Destroy()
@@ -96,12 +104,12 @@ class TestPanel(wxPanel):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def runTest(frame, nb, log): def runTest(frame, nb, log):
if wxPlatform == '__WXMSW__': if wx.Platform == '__WXMSW__':
win = TestPanel(nb, log) win = TestPanel(nb, log)
return win return win
else: else:
dlg = wxMessageDialog(frame, 'This demo only works on MSW.', dlg = wx.MessageDialog(frame, 'This demo only works on MSW.',
'Sorry', wxOK | wxICON_INFORMATION) 'Sorry', wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal() dlg.ShowModal()
dlg.Destroy() dlg.Destroy()
@@ -112,17 +120,19 @@ overview = __doc__
if __name__ == '__main__': if __name__ == '__main__':
class TestFrame(wxFrame): class TestFrame(wx.Frame):
def __init__(self): def __init__(self):
wxFrame.__init__(self, None, -1, "ActiveX test -- Acrobat", size=(640, 480), wx.Frame.__init__(
style=wxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE) self, None, -1, "ActiveX test -- Acrobat", size=(640, 480),
style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE
)
self.tp = TestPanel(self, sys.stdout) self.tp = TestPanel(self, sys.stdout)
app = wxPySimpleApp() app = wx.PySimpleApp()
frame = TestFrame() frame = TestFrame()
frame.Show(True) frame.Show(True)
app.MainLoop() app.MainLoop()

View File

@@ -18,93 +18,104 @@ shown.)
</body></html> </body></html>
""" """
from wxPython.wx import * # 11/24/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for V2.5
#
if wxPlatform == '__WXMSW__': import sys
from wxPython.lib.activexwrapper import MakeActiveXClass import wx
if wx.Platform == '__WXMSW__':
import wx.lib.activexwrapper as ax
import win32com.client.gencache import win32com.client.gencache
try: try:
browserModule = win32com.client.gencache.EnsureModule("{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}", 0, 1, 1) browserModule = win32com.client.gencache.EnsureModule(
"{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}", 0, 1, 1
)
except: except:
raise ImportError("IE4 or greater does not appear to be installed.") raise ImportError("IE4 or greater does not appear to be installed.")
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wxWindow): class TestPanel(wx.Window):
def __init__(self, parent, log, frame=None): def __init__(self, parent, log, frame=None):
wxWindow.__init__(self, parent, -1, wx.Window.__init__(
style=wxCLIP_CHILDREN|wxNO_FULL_REPAINT_ON_RESIZE) self, parent, -1,
style=wx.CLIP_CHILDREN|wx.NO_FULL_REPAINT_ON_RESIZE
)
self.ie = None self.ie = None
self.log = log self.log = log
self.current = "http://wxPython.org/" self.current = "http://wxPython.org/"
self.frame = frame self.frame = frame
if frame: if frame:
self.titleBase = frame.GetTitle() self.titleBase = frame.GetTitle()
sizer = wx.BoxSizer(wx.VERTICAL)
sizer = wxBoxSizer(wxVERTICAL) btnSizer = wx.BoxSizer(wx.HORIZONTAL)
btnSizer = wxBoxSizer(wxHORIZONTAL)
# Make a new class that derives from the WebBrowser class in the # Make a new class that derives from the WebBrowser class in the
# COM module imported above. This class also derives from wxWindow and # COM module imported above. This class also derives from wxWindow and
# implements the machinery needed to integrate the two worlds. # implements the machinery needed to integrate the two worlds.
theClass = MakeActiveXClass(browserModule.WebBrowser, theClass = ax.MakeActiveXClass(
eventObj = self) browserModule.WebBrowser, eventObj = self
)
# Create an instance of that class # Create an instance of that class
self.ie = theClass(self, -1) ##, style=wxSUNKEN_BORDER) self.ie = theClass(self, -1) ##, style=wxSUNKEN_BORDER)
btn = wxButton(self, wxNewId(), "Open", style=wxBU_EXACTFIT) btn = wx.Button(self, wx.NewId(), "Open", style=wx.BU_EXACTFIT)
EVT_BUTTON(self, btn.GetId(), self.OnOpenButton) self.Bind(wx.EVT_BUTTON, self.OnOpenButton, id=btn.GetId())
btnSizer.Add(btn, 0, wxEXPAND|wxALL, 2) btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)
btn = wxButton(self, wxNewId(), "Home", style=wxBU_EXACTFIT) btn = wx.Button(self, wx.NewId(), "Home", style=wx.BU_EXACTFIT)
EVT_BUTTON(self, btn.GetId(), self.OnHomeButton) self.Bind(wx.EVT_BUTTON, self.OnHomeButton, id=btn.GetId())
btnSizer.Add(btn, 0, wxEXPAND|wxALL, 2) btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)
btn = wxButton(self, wxNewId(), "<--", style=wxBU_EXACTFIT) btn = wx.Button(self, wx.NewId(), "<--", style=wx.BU_EXACTFIT)
EVT_BUTTON(self, btn.GetId(), self.OnPrevPageButton) self.Bind(wx.EVT_BUTTON, self.OnPrevPageButton, id=btn.GetId())
btnSizer.Add(btn, 0, wxEXPAND|wxALL, 2) btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)
btn = wxButton(self, wxNewId(), "-->", style=wxBU_EXACTFIT) btn = wx.Button(self, wx.NewId(), "-->", style=wx.BU_EXACTFIT)
EVT_BUTTON(self, btn.GetId(), self.OnNextPageButton) self.Bind(wx.EVT_BUTTON, self.OnNextPageButton, id=btn.GetId())
btnSizer.Add(btn, 0, wxEXPAND|wxALL, 2) btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)
btn = wxButton(self, wxNewId(), "Stop", style=wxBU_EXACTFIT) btn = wx.Button(self, wx.NewId(), "Stop", style=wx.BU_EXACTFIT)
EVT_BUTTON(self, btn.GetId(), self.OnStopButton) self.Bind(wx.EVT_BUTTON, self.OnStopButton, id=btn.GetId())
btnSizer.Add(btn, 0, wxEXPAND|wxALL, 2) btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)
btn = wxButton(self, wxNewId(), "Search", style=wxBU_EXACTFIT) btn = wx.Button(self, wx.NewId(), "Search", style=wx.BU_EXACTFIT)
EVT_BUTTON(self, btn.GetId(), self.OnSearchPageButton) self.Bind(wx.EVT_BUTTON, self.OnSearchPageButton, id=btn.GetId())
btnSizer.Add(btn, 0, wxEXPAND|wxALL, 2) btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)
btn = wxButton(self, wxNewId(), "Refresh", style=wxBU_EXACTFIT) btn = wx.Button(self, wx.NewId(), "Refresh", style=wx.BU_EXACTFIT)
EVT_BUTTON(self, btn.GetId(), self.OnRefreshPageButton) self.Bind(wx.EVT_BUTTON, self.OnRefreshPageButton, id=btn.GetId())
btnSizer.Add(btn, 0, wxEXPAND|wxALL, 2) btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)
txt = wxStaticText(self, -1, "Location:") txt = wx.StaticText(self, -1, "Location:")
btnSizer.Add(txt, 0, wxCENTER|wxALL, 2) btnSizer.Add(txt, 0, wx.CENTER|wx.ALL, 2)
self.location = wxComboBox(self, wxNewId(), "", style=wxCB_DROPDOWN) self.location = wx.ComboBox(self, wx.NewId(), "", style=wx.CB_DROPDOWN)
EVT_COMBOBOX(self, self.location.GetId(), self.OnLocationSelect) self.Bind(wx.EVT_COMBOBOX, self.OnLocationSelect, id=self.location.GetId())
EVT_KEY_UP(self.location, self.OnLocationKey) self.Bind(wx.EVT_KEY_UP, self.OnLocationKey, self.location)
EVT_CHAR(self.location, self.IgnoreReturn) self.Bind(wx.EVT_CHAR, self.IgnoreReturn, self.location)
btnSizer.Add(self.location, 1, wxEXPAND|wxALL, 2) btnSizer.Add(self.location, 1, wx.EXPAND|wx.ALL, 2)
sizer.Add(btnSizer, 0, wxEXPAND) sizer.Add(btnSizer, 0, wx.EXPAND)
sizer.Add(self.ie, 1, wxEXPAND) sizer.Add(self.ie, 1, wx.EXPAND)
self.ie.Navigate(self.current) self.ie.Navigate(self.current)
self.location.Append(self.current) self.location.Append(self.current)
self.SetSizer(sizer) self.SetSizer(sizer)
self.SetAutoLayout(True) self.SetAutoLayout(True)
EVT_SIZE(self, self.OnSize) self.Bind(wx.EVT_SIZE, self.OnSize)
self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
EVT_WINDOW_DESTROY(self, self.OnDestroy)
def ShutdownDemo(self): def ShutdownDemo(self):
@@ -130,7 +141,7 @@ class TestPanel(wxWindow):
self.ie.Navigate(url) self.ie.Navigate(url)
def OnLocationKey(self, evt): def OnLocationKey(self, evt):
if evt.KeyCode() == WXK_RETURN: if evt.KeyCode() == wx.WXK_RETURN:
URL = self.location.GetValue() URL = self.location.GetValue()
self.location.Append(URL) self.location.Append(URL)
self.ie.Navigate(URL) self.ie.Navigate(URL)
@@ -139,17 +150,20 @@ class TestPanel(wxWindow):
def IgnoreReturn(self, evt): def IgnoreReturn(self, evt):
print 'IgnoreReturn' print 'IgnoreReturn'
if evt.KeyCode() != WXK_RETURN: if evt.KeyCode() != wx.WXK_RETURN:
evt.Skip() evt.Skip()
def OnOpenButton(self, event): def OnOpenButton(self, event):
dlg = wxTextEntryDialog(self, "Open Location", dlg = wx.TextEntryDialog(self, "Open Location",
"Enter a full URL or local path", "Enter a full URL or local path",
self.current, wxOK|wxCANCEL) self.current, wx.OK|wx.CANCEL)
dlg.CentreOnParent() dlg.CentreOnParent()
if dlg.ShowModal() == wxID_OK:
if dlg.ShowModal() == wx.ID_OK:
self.current = dlg.GetValue() self.current = dlg.GetValue()
self.ie.Navigate(self.current) self.ie.Navigate(self.current)
dlg.Destroy() dlg.Destroy()
def OnHomeButton(self, event): def OnHomeButton(self, event):
@@ -171,7 +185,6 @@ class TestPanel(wxWindow):
self.ie.Refresh2(3) self.ie.Refresh2(3)
# The following event handlers are called by the web browser COM # The following event handlers are called by the web browser COM
# control since we passed self to MakeActiveXClass. It will look # control since we passed self to MakeActiveXClass. It will look
# here for matching attributes and call them if they exist. See the # here for matching attributes and call them if they exist. See the
@@ -199,12 +212,12 @@ class TestPanel(wxWindow):
# for the demo framework... # for the demo framework...
def runTest(frame, nb, log): def runTest(frame, nb, log):
if wxPlatform == '__WXMSW__': if wx.Platform == '__WXMSW__':
win = TestPanel(nb, log, frame) win = TestPanel(nb, log, frame)
return win return win
else: else:
dlg = wxMessageDialog(frame, 'This demo only works on MSW.', dlg = wx.MessageDialog(frame, 'This demo only works on MSW.',
'Sorry', wxOK | wxICON_INFORMATION) 'Sorry', wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal() dlg.ShowModal()
dlg.Destroy() dlg.Destroy()
@@ -215,23 +228,24 @@ overview = __doc__
if __name__ == '__main__': if __name__ == '__main__':
class TestFrame(wxFrame): class TestFrame(wx.Frame):
def __init__(self): def __init__(self):
wxFrame.__init__(self, None, -1, "ActiveX test -- Internet Explorer", wx.Frame.__init__(
self, None, -1, "ActiveX test -- Internet Explorer",
size=(640, 480), size=(640, 480),
style=wxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE) style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE
)
self.CreateStatusBar() self.CreateStatusBar()
self.tp = TestPanel(self, sys.stdout, self) self.tp = TestPanel(self, sys.stdout, self)
EVT_CLOSE(self, self.OnCloseWindow) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
def OnCloseWindow(self, evt): def OnCloseWindow(self, evt):
self.tp.Destroy() self.tp.Destroy()
self.Destroy() self.Destroy()
app = wxPySimpleApp() app = wx.PySimpleApp()
frame = TestFrame() frame = TestFrame()
frame.Show(True) frame.Show(True)
app.MainLoop() app.MainLoop()

View File

@@ -1,52 +1,59 @@
# 11/4/03 - grimmtooth@softhome.net (Jeff Grimmett)
#
# o wx Namespace
#
import wx
import wx.lib.analogclock as aclock
from wxPython.wx import *
from wxPython.lib.analogclock import AnalogClockWindow
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
self.log = log self.log = log
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
c1 = AnalogClockWindow(self) # A red background with blue hands and white markings
c1 = aclock.AnalogClockWindow(self)
c1.SetBackgroundColour("RED") c1.SetBackgroundColour("RED")
c1.SetHandsColour("BLUE") c1.SetHandsColour("BLUE")
c1.SetTickMarkColours("WHITE") c1.SetTickMarkColours("WHITE")
c2 = AnalogClockWindow(self) # A white background with red hands and blue markings
c2 = aclock.AnalogClockWindow(self)
c2.SetBackgroundColour("WHITE") c2.SetBackgroundColour("WHITE")
c2.SetHandsColour("RED") c2.SetHandsColour("RED")
c2.SetTickMarkColours("BLUE") c2.SetTickMarkColours("BLUE")
c3 = AnalogClockWindow(self) # A blue background with white hands and red markings
c3 = aclock.AnalogClockWindow(self)
c3.SetBackgroundColour("BLUE") c3.SetBackgroundColour("BLUE")
c3.SetHandsColour("WHITE") c3.SetHandsColour("WHITE")
c3.SetTickMarkColours("RED") c3.SetTickMarkColours("RED")
c4 = AnalogClockWindow(self, style=wxRAISED_BORDER) # Raised border, circular tick marks.
c4.SetTickMarkStyle(AnalogClockWindow.TICKS_CIRCLE) c4 = aclock.AnalogClockWindow(self, style=wx.RAISED_BORDER)
c4.SetTickMarkStyle(aclock.AnalogClockWindow.TICKS_CIRCLE)
c5 = AnalogClockWindow(self) # No tick marks
c5.SetTickMarkStyle(AnalogClockWindow.TICKS_NONE) c5 = aclock.AnalogClockWindow(self)
c5.SetTickMarkStyle(aclock.AnalogClockWindow.TICKS_NONE)
c6 = AnalogClockWindow(self, style=wxSUNKEN_BORDER) # Sunken into window
c6 = aclock.AnalogClockWindow(self, style=wx.SUNKEN_BORDER)
# layout the clocks in a grid sizer
# layout the clocks in a grid gs = wx.GridSizer(2, 3, 4, 4)
gs = wxGridSizer(2, 3, 4, 4) gs.Add(c1, 0, wx.EXPAND)
gs.Add(c1, 0, wxEXPAND) gs.Add(c2, 0, wx.EXPAND)
gs.Add(c2, 0, wxEXPAND) gs.Add(c3, 0, wx.EXPAND)
gs.Add(c3, 0, wxEXPAND) gs.Add(c4, 0, wx.EXPAND)
gs.Add(c4, 0, wxEXPAND) gs.Add(c5, 0, wx.EXPAND)
gs.Add(c5, 0, wxEXPAND) gs.Add(c6, 0, wx.EXPAND)
gs.Add(c6, 0, wxEXPAND)
# put it in another sizer for a border # put it in another sizer for a border
sizer = wxBoxSizer(wxVERTICAL) sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(gs, 1, wxEXPAND|wxALL, 10) sizer.Add(gs, 1, wx.EXPAND|wx.ALL, 10)
self.SetSizer(sizer) self.SetSizer(sizer)
@@ -70,8 +77,6 @@ members of the wxPython-users group.
</body></html> </body></html>
""" """
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run

View File

@@ -1,12 +1,19 @@
# 11/4/03 - grimmtooth@softhome.net (Jeff Grimmett)
#
# o Updated for wx namespace
#
# Note: this module is not a demo per se, but is used by many of
# the demo modules for various purposes.
from wxPython.wx import * import wx
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class ColoredPanel(wxWindow): class ColoredPanel(wx.Window):
def __init__(self, parent, color): def __init__(self, parent, color):
wxWindow.__init__(self, parent, -1, style = wxSIMPLE_BORDER) #wxRAISED_BORDER) wx.Window.__init__(self, parent, -1, style = wx.SIMPLE_BORDER)
self.SetBackgroundColour(color) self.SetBackgroundColour(color)
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------

View File

@@ -1,39 +1,73 @@
# 11/4/03 - grimmtooth@softhome.net (Jeff Grimmett)
#
# o Updated to use wx namespace
#
# 11/24/03 - grimmtooth@softhome.net (Jeff Grimmett)
#
# o Had to move the call to wx.updateColourDB()
# o Updated several places to change discrete pos and size parameters
# into two-tuples.
#
from wxPython.wx import * import wx
from wxPython.lib import colourdb import wx.lib.colourdb as cdb
import images import images
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestWindow(wxScrolledWindow): class TestWindow(wx.ScrolledWindow):
def __init__(self, parent): def __init__(self, parent):
wxScrolledWindow.__init__(self, parent, -1) wx.ScrolledWindow.__init__(self, parent, -1)
self.clrList = colourdb.getColourList() # Populate our color list
self.clrList = cdb.getColourList()
# Just for style points, we'll use this as a background image.
#self.clrList.sort() #self.clrList.sort()
self.bg_bmp = images.getGridBGBitmap() self.bg_bmp = images.getGridBGBitmap()
EVT_PAINT(self, self.OnPaint) # Event handlers
EVT_ERASE_BACKGROUND(self, self.OnEraseBackground) self.Bind(wx.EVT_PAINT, self.OnPaint)
#self.SetBackgroundColour("WHITE") self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
self.font = wxFont(10, wxSWISS, wxNORMAL, wxNORMAL) # This could also be done by getting the window's default font;
dc = wxClientDC(self) # either way, we need to have a font loaded for later on.
#self.SetBackgroundColour("WHITE")
self.font = wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL)
# Create drawing area and set its font
dc = wx.ClientDC(self)
dc.SetFont(self.font) dc.SetFont(self.font)
w,h,d,e = dc.GetFullTextExtent("Wy") # a wide character and one that descends # Using GetFullTextExtent(), we calculate a basic 'building block'
# that will be used to draw a depiction of the color list. We're
# using 'Wy' as the model becuase 'W' is a wide character and 'y'
# has a descender. This constitutes a 'worst case' scenario, which means
# that no matter what we draw later, text-wise, we'll have room for it
w,h,d,e = dc.GetFullTextExtent("Wy")
# Height plus descender
self.textHeight = h + d self.textHeight = h + d
# Pad a little bit
self.lineHeight = self.textHeight + 5 self.lineHeight = self.textHeight + 5
# ... and this is the basic width.
self.cellWidth = w self.cellWidth = w
# jmg 11/8/03: why 24?
numCells = 24 numCells = 24
self.SetScrollbars(self.cellWidth, self.lineHeight, numCells, len(self.clrList) + 2)
# 'prep' our scroll bars.
self.SetScrollbars(
self.cellWidth, self.lineHeight, numCells, len(self.clrList) + 2
)
# tile the background bitmap loaded in __init__()
def TileBackground(self, dc): def TileBackground(self, dc):
# tile the background bitmap
sz = self.GetClientSize() sz = self.GetClientSize()
w = self.bg_bmp.GetWidth() w = self.bg_bmp.GetWidth()
h = self.bg_bmp.GetHeight() h = self.bg_bmp.GetHeight()
@@ -44,25 +78,29 @@ class TestWindow(wxScrolledWindow):
dx, dy = (spx * vsx) % w, (spy * vsy) % h dx, dy = (spx * vsx) % w, (spy * vsy) % h
x = -dx x = -dx
while x < sz.width: while x < sz.width:
y = -dy y = -dy
while y < sz.height: while y < sz.height:
dc.DrawBitmap(self.bg_bmp, (x, y)) dc.DrawBitmap(self.bg_bmp, (x, y))
y = y + h y = y + h
x = x + w x = x + w
# Redraw the background over a 'damaged' area.
def OnEraseBackground(self, evt): def OnEraseBackground(self, evt):
dc = evt.GetDC() dc = evt.GetDC()
if not dc: if not dc:
dc = wxClientDC(self) dc = wx.ClientDC(self)
rect = self.GetUpdateRegion().GetBox() rect = self.GetUpdateRegion().GetBox()
dc.SetClippingRect(rect) dc.SetClippingRect(rect)
self.TileBackground(dc) self.TileBackground(dc)
def OnPaint(self, evt): def OnPaint(self, evt):
dc = wxPaintDC(self) dc = wx.PaintDC(self)
self.PrepareDC(dc) self.PrepareDC(dc)
self.Draw(dc, self.GetUpdateRegion(), self.GetViewStart()) self.Draw(dc, self.GetUpdateRegion(), self.GetViewStart())
@@ -70,13 +108,15 @@ class TestWindow(wxScrolledWindow):
def Draw(self, dc, rgn=None, vs=None): def Draw(self, dc, rgn=None, vs=None):
dc.BeginDrawing() dc.BeginDrawing()
dc.SetTextForeground("BLACK") dc.SetTextForeground("BLACK")
dc.SetPen(wxPen("BLACK", 1, wxSOLID)) dc.SetPen(wx.Pen("BLACK", 1, wx.SOLID))
dc.SetFont(self.font) dc.SetFont(self.font)
colours = self.clrList colours = self.clrList
numColours = len(colours) numColours = len(colours)
if rgn: if rgn:
# determine the subset that has been exposed and needs drawn # determine the subset of the color list that has been exposed
# and needs drawn. This is based on all the precalculation we
# did in __init__()
rect = rgn.GetBox() rect = rgn.GetBox()
pixStart = vs[1]*self.lineHeight + rect.y pixStart = vs[1]*self.lineHeight + rect.y
pixStop = pixStart + rect.height pixStop = pixStart + rect.height
@@ -89,9 +129,11 @@ class TestWindow(wxScrolledWindow):
for line in range(max(0,start), min(stop,numColours)): for line in range(max(0,start), min(stop,numColours)):
clr = colours[line] clr = colours[line]
y = (line+1) * self.lineHeight + 2 y = (line+1) * self.lineHeight + 2
# Updated for 2.5 - now takes tuple for pos
dc.DrawText(clr, (self.cellWidth, y)) dc.DrawText(clr, (self.cellWidth, y))
brush = wxBrush(clr, wxSOLID) brush = wx.Brush(clr, wx.SOLID)
dc.SetBrush(brush) dc.SetBrush(brush)
dc.DrawRectangle((12 * self.cellWidth, y), dc.DrawRectangle((12 * self.cellWidth, y),
(6 * self.cellWidth, self.textHeight)) (6 * self.cellWidth, self.textHeight))
@@ -100,12 +142,13 @@ class TestWindow(wxScrolledWindow):
# On wxGTK there needs to be a panel under wxScrolledWindows if they are # On wxGTK there needs to be a panel under wxScrolledWindows if they are
# going to be in a wxNotebook... # going to be in a wxNotebook. And, in the demo, we are.
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent): def __init__(self, parent):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.win = TestWindow(self) self.win = TestWindow(self)
EVT_SIZE(self, self.OnSize) self.Bind(wx.EVT_SIZE, self.OnSize)
def OnSize(self, evt): def OnSize(self, evt):
self.win.SetSize(evt.GetSize()) self.win.SetSize(evt.GetSize())
@@ -117,15 +160,46 @@ class TestPanel(wxPanel):
def runTest(frame, nb, log): def runTest(frame, nb, log):
# This loads a whole bunch of new color names and values # This loads a whole bunch of new color names and values
# into wxTheColourDatabase # into TheColourDatabase
colourdb.updateColourDB() #
# Note 11/24/03 - jg - I moved this into runTest() because
# there must be a wx.App existing before this function
# can be called - this is a change from 2.4 -> 2.5.
cdb.updateColourDB()
win = TestPanel(nb) win = TestPanel(nb)
return win return win
#---------------------------------------------------------------------- #----------------------------------------------------------------------
overview = """ overview = """
<html>
<body>
<B><font size=+2>ColourDB</font></b>
<p>wxWindows maintains a database of standard RGB colours for a predefined
set of named colours (such as "BLACK'', "LIGHT GREY''). The application
may add to this set if desired by using Append. There is only one instance
of this class: <b>TheColourDatabase</b>.
<p>The <code>colourdb</code> library is a lightweight API that pre-defines
a multitude of colors for you to use 'out of the box', and this demo serves
to show you these colors (it also serves as a handy reference).
<p>A secondary benefit of this demo is the use of the <b>ScrolledWindow</b> class
and the use of various *DC() classes, including background tiling and the use of
font data to generate a "building block" type of construct for repetitive use.
<p>
<B><font size=+2>Important note</font></b>
<p>
With implementation of V2.5 and later, it is required to have a wx.App already
initialized before <b><code>wx.updateColourDB()</code></b> can be called.
Trying to do otherwise will cause an exception to be raised.
</body>
</html>
""" """

View File

@@ -15,45 +15,61 @@
# - use sizers # - use sizers
# - other minor "improvements" # - other minor "improvements"
#---------------------------------------------------------------------------- #----------------------------------------------------------------------------
# 11/22/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for V2.5
#
# 11/24/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Added Bind() handlers to what events can handle it. However, the
# colourselect library must be converted before its events can be
# bound using the Bind() method.
#
# 12/01/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o colourselect lib converted; demo converted to match.
#
from wxPython.wx import * import wx
from wxPython.lib.colourselect import * import wx.lib.colourselect as csel
#---------------------------------------------------------------------------- #----------------------------------------------------------------------------
class TestColourSelect(wxPanel): class TestColourSelect(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
self.log = log self.log = log
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.SetAutoLayout(True) self.SetAutoLayout(True)
mainSizer = wxBoxSizer(wxVERTICAL) mainSizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(mainSizer) self.SetSizer(mainSizer)
t = wxStaticText(self, -1, t = wx.StaticText(self, -1,
"This example uses a colour selection control based on the wxButton\n" "This example uses a colour selection control based on the wxButton\n"
"and wxColourDialog Classes. Click Button to get Colour Values") "and wxColourDialog Classes. Click Button to get Colour Values")
mainSizer.Add(t, 0, wxALL, 3) mainSizer.Add(t, 0, wx.ALL, 3)
b = wxButton(self, -1, "Show All Colours") b = wx.Button(self, -1, "Show All Colours")
EVT_BUTTON(self, b.GetId(), self.OnShowAll) self.Bind(wx.EVT_BUTTON, self.OnShowAll, id=b.GetId())
mainSizer.Add(b, 0, wxALL, 3) mainSizer.Add(b, 0, wx.ALL, 3)
buttonSizer = wxFlexGridSizer(1, 2) # sizer to contain all the example buttons buttonSizer = wx.FlexGridSizer(1, 2) # sizer to contain all the example buttons
# show a button with all default values # show a button with all default values
self.colourDefaults = ColourSelect(self, -1) self.colourDefaults = csel.ColourSelect(self, -1)
EVT_COLOURSELECT(self.colourDefaults, self.colourDefaults.GetId(), self.OnSelectColour)
self.colourDefaults.Bind(csel.EVT_COLOURSELECT, self.OnSelectColour, self.colourDefaults.GetId())
buttonSizer.AddMany([ buttonSizer.AddMany([
(wxStaticText(self, -1, "Default Colour/Size"), 0, wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL), (wx.StaticText(self, -1, "Default Colour/Size"), 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL),
(self.colourDefaults, 0, wxALL, 3), (self.colourDefaults, 0, wx.ALL, 3),
]) ])
# build several examples of buttons with different colours and sizes # build several examples of buttons with different colours and sizes
buttonData = [ buttonData = [
("Default Size", (255, 255, 0), wxDefaultSize, ""), ("Default Size", (255, 255, 0), wx.DefaultSize, ""),
("Another Size", (255, 0, 255), (60, 20), ""), ("Another Size", (255, 0, 255), (60, 20), ""),
("Another Colour", (0, 255, 0), wxDefaultSize, ""), ("Another Colour", (0, 255, 0), wx.DefaultSize, ""),
("Larger Size", (0, 0, 255), (60, 60), ""), ("Larger Size", (0, 0, 255), (60, 60), ""),
("With a Label", (127, 0, 255), wxDefaultSize, "Colour..."), ("With a Label", (127, 0, 255), wx.DefaultSize, "Colour..."),
("Another Colour/Label", (255, 100, 130), (120, -1), "Choose Colour..."), ("Another Colour/Label", (255, 100, 130), (120, -1), "Choose Colour..."),
] ]
@@ -61,15 +77,17 @@ class TestColourSelect(wxPanel):
# build each button and save a reference to it # build each button and save a reference to it
for name, color, size, label in buttonData: for name, color, size, label in buttonData:
b = ColourSelect(self, -1, label, color, size = size) b = csel.ColourSelect(self, -1, label, color, size = size)
EVT_COLOURSELECT(b, b.GetId(), self.OnSelectColour)
b.Bind(csel.EVT_COLOURSELECT, self.OnSelectColour)
self.buttonRefs.append((name, b)) # store reference to button self.buttonRefs.append((name, b)) # store reference to button
buttonSizer.AddMany([ buttonSizer.AddMany([
(wxStaticText(self, -1, name), 0, wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL), (wx.StaticText(self, -1, name), 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL),
(b, 0, wxALL, 3), (b, 0, wx.ALL, 3),
]) ])
mainSizer.Add(buttonSizer, 0, wxALL, 3) mainSizer.Add(buttonSizer, 0, wx.ALL, 3)
self.Layout() self.Layout()
def OnSelectColour(self, event): def OnSelectColour(self, event):
@@ -104,9 +122,6 @@ overview = """\
""" """
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run

View File

@@ -1,70 +1,97 @@
# 11/4/2003 - grimmtooth@softhome.net (Jeff Grimmett)
#
# o Modified for V2.5
#
# 11/24/2003 - grimmtooth@softhome.net (Jeff Grimmett)
#
# o Removed import of wx.help - now part of wx.core.
#
from wxPython.wx import * import wx
#---------------------------------------------------------------------- #----------------------------------------------------------------------
# We first have to set an application-wide help provider. Normally you # We first have to set an application-wide help provider. Normally you
# would do this in your app's OnInit or in other startup code... # would do this in your app's OnInit or in other startup code...
provider = wxSimpleHelpProvider() provider = wx.SimpleHelpProvider()
wxHelpProvider_Set(provider) wx.HelpProvider_Set(provider)
# This panel is chock full of controls about which we can demonstrate the
class TestPanel(wxPanel): # help system.
class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.log = log self.log = log
self.SetHelpText("This is a wxPanel.") # This help text, set for the panel itself, will be used if context
sizer = wxBoxSizer(wxVERTICAL) # sensitive help cannot be found for any particular control.
self.SetHelpText("This is a wx.Panel.")
cBtn = wxContextHelpButton(self) sizer = wx.BoxSizer(wx.VERTICAL)
cBtn.SetHelpText("wxContextHelpButton")
cBtnText = wxStaticText(self, -1, "This is a wxContextHelpButton. Clicking it puts the\n" # Init the context help button.
"app into context sensitive help mode.") # And even include help text about the help button :-)
cBtn = wx.ContextHelpButton(self)
cBtn.SetHelpText("wx.ContextHelpButton")
cBtnText = wx.StaticText(self, -1,
"This is a wx.ContextHelpButton. Clicking it puts the\n"
"app into context sensitive help mode."
)
# Yes, even static text can have help text associated with it :-)
cBtnText.SetHelpText("Some helpful text...") cBtnText.SetHelpText("Some helpful text...")
s = wxBoxSizer(wxHORIZONTAL) s = wx.BoxSizer(wx.HORIZONTAL)
s.Add(cBtn, 0, wxALL, 5) s.Add(cBtn, 0, wxALL, 5)
s.Add(cBtnText, 0, wxALL, 5) s.Add(cBtnText, 0, wxALL, 5)
sizer.Add((20,20)) sizer.Add((20,20))
sizer.Add(s) sizer.Add(s)
text = wxTextCtrl(self, -1, "Each sub-window can have its own help message", # A text control with help text.
size=(240, 60), style = wxTE_MULTILINE) text = wx.TextCtrl(self, -1, "Each sub-window can have its own help message",
size=(240, 60), style=wx.TE_MULTILINE)
text.SetHelpText("This is my very own help message. This is a really long long long long long long long long long long long long long long long long long long long long message!") text.SetHelpText("This is my very own help message. This is a really long long long long long long long long long long long long long long long long long long long long message!")
sizer.Add((20,20)) sizer.Add((20,20))
sizer.Add(text) sizer.Add(text)
text = wxTextCtrl(self, -1, "You can also intercept the help event if you like. Watch the log window when you click here...", # Same thing, but this time to demonstrate how the help event can be
size=(240, 60), style = wxTE_MULTILINE) # intercepted.
text = wx.TextCtrl(self, -1, "You can also intercept the help event if you like. Watch the log window when you click here...",
size=(240, 60), style = wx.TE_MULTILINE)
text.SetHelpText("Yet another context help message.") text.SetHelpText("Yet another context help message.")
sizer.Add((20,20)) sizer.Add((20,20))
sizer.Add(text) sizer.Add(text)
EVT_HELP(text, text.GetId(), self.OnCtxHelp) self.Bind(wx.EVT_HELP, self.OnCtxHelp, text)
text = wxTextCtrl(self, -1, "This one displays the tip itself...", text = wx.TextCtrl(self, -1, "This one displays the tip itself...",
size=(240, 60), style = wxTE_MULTILINE) size=(240, 60), style = wx.TE_MULTILINE)
sizer.Add((20,20)) sizer.Add((20,20))
sizer.Add(text) sizer.Add(text)
EVT_HELP(text, text.GetId(), self.OnCtxHelp2) self.Bind(wx.EVT_HELP, self.OnCtxHelp2, text)
border = wxBoxSizer(wxVERTICAL) border = wx.BoxSizer(wx.VERTICAL)
border.Add(sizer, 0, wxALL, 25) border.Add(sizer, 0, wx.ALL, 25)
self.SetAutoLayout(True) self.SetAutoLayout(True)
self.SetSizer(border) self.SetSizer(border)
self.Layout() self.Layout()
# On the second text control above, we intercept the help event. This is where
# we process it. Anything could happen here. In this case we're just printing
# some stuff about it, then passing it on, at which point we see the help tip.
def OnCtxHelp(self, evt): def OnCtxHelp(self, evt):
self.log.write("OnCtxHelp: %s" % evt) self.log.write("OnCtxHelp: %s" % evt)
evt.Skip() evt.Skip()
# On the third text control above, we intercept the help event.
# Here, we print a note about it, generate our own tip window, and,
# unlike last time, we don't pass it on to the underlying provider.
def OnCtxHelp2(self, evt): def OnCtxHelp2(self, evt):
self.log.write("OnCtxHelp: %s\n" % evt) self.log.write("OnCtxHelp: %s\n" % evt)
tip = wxTipWindow(self, "This is a wxTipWindow") tip = wx.TipWindow(self, "This is a wx.TipWindow")
#---------------------------------------------------------------------- #----------------------------------------------------------------------
@@ -77,20 +104,14 @@ def runTest(frame, nb, log):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
overview = """ overview = """
This demo shows how to incorporate Context Sensitive This demo shows how to incorporate Context Sensitive
help into your application using the wxSimpleHelpProvider class. help into your application using the wx.SimpleHelpProvider class.
""" """
#---------------------------------------------------------------------- #----------------------------------------------------------------------
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run

View File

@@ -1,42 +1,49 @@
# 11/5/2003 - Modified by grimmtooth@softhome.net (Jeff Grimmett)
from wxPython.wx import * #
# o Updated for wx namespace
#
# 11/24/2003 - Modified by grimmtooth@softhome.net (Jeff Grimmett)
#
# o Issues around line 167. I'm stuck.
#
import cPickle import cPickle
import wx
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class DoodlePad(wxWindow): class DoodlePad(wx.Window):
def __init__(self, parent, log): def __init__(self, parent, log):
wxWindow.__init__(self, parent, -1, style=wxSUNKEN_BORDER) wx.Window.__init__(self, parent, -1, style=wx.SUNKEN_BORDER)
self.log = log self.log = log
self.SetBackgroundColour(wxWHITE) self.SetBackgroundColour(wx.WHITE)
self.lines = [] self.lines = []
self.x = self.y = 0 self.x = self.y = 0
self.SetMode("Draw") self.SetMode("Draw")
EVT_LEFT_DOWN(self, self.OnLeftDown) wx.EVT_LEFT_DOWN(self, self.OnLeftDown)
EVT_LEFT_UP(self, self.OnLeftUp) wx.EVT_LEFT_UP(self, self.OnLeftUp)
EVT_RIGHT_UP(self, self.OnRightUp) wx.EVT_RIGHT_UP(self, self.OnRightUp)
EVT_MOTION(self, self.OnMotion) wx.EVT_MOTION(self, self.OnMotion)
EVT_PAINT(self, self.OnPaint) wx.EVT_PAINT(self, self.OnPaint)
def SetMode(self, mode): def SetMode(self, mode):
self.mode = mode self.mode = mode
if self.mode == "Draw": if self.mode == "Draw":
self.SetCursor(wxStockCursor(wxCURSOR_PENCIL)) self.SetCursor(wx.StockCursor(wx.CURSOR_PENCIL))
else: else:
self.SetCursor(wxSTANDARD_CURSOR) self.SetCursor(wx.STANDARD_CURSOR)
def OnPaint(self, event): def OnPaint(self, event):
dc = wxPaintDC(self) dc = wx.PaintDC(self)
self.DrawSavedLines(dc) self.DrawSavedLines(dc)
def DrawSavedLines(self, dc): def DrawSavedLines(self, dc):
dc.BeginDrawing() dc.BeginDrawing()
dc.SetPen(wxPen(wxBLUE, 3)) dc.SetPen(wx.Pen(wx.BLUE, 3))
for line in self.lines: for line in self.lines:
for coords in line: for coords in line:
dc.DrawLineXY(*coords) dc.DrawLineXY(*coords)
@@ -51,7 +58,7 @@ class DoodlePad(wxWindow):
self.x, self.y = event.GetPositionTuple() self.x, self.y = event.GetPositionTuple()
self.CaptureMouse() self.CaptureMouse()
else: else:
wxBell() wx.Bell()
self.log.write("unknown mode!\n") self.log.write("unknown mode!\n")
@@ -66,10 +73,10 @@ class DoodlePad(wxWindow):
def OnMotion(self, event): def OnMotion(self, event):
if event.Dragging() and not self.mode == "Drag": if event.Dragging() and not self.mode == "Drag":
dc = wxClientDC(self) dc = wx.ClientDC(self)
dc.BeginDrawing() dc.BeginDrawing()
dc.SetPen(wxPen(wxBLUE, 3)) dc.SetPen(wx.Pen(wx.BLUE, 3))
coords = (self.x, self.y) + event.GetPositionTuple() coords = ((self.x, self.y), event.GetPosition())
self.curLine.append(coords) self.curLine.append(coords)
dc.DrawLineXY(*coords) dc.DrawLineXY(*coords)
self.x, self.y = event.GetPositionTuple() self.x, self.y = event.GetPositionTuple()
@@ -82,34 +89,35 @@ class DoodlePad(wxWindow):
# create our own data format and use it in a # create our own data format and use it in a
# custom data object # custom data object
ldata = wxCustomDataObject(wxCustomDataFormat("DoodleLines")) ldata = wx.CustomDataObject(wx.CustomDataFormat("DoodleLines"))
ldata.SetData(linesdata) ldata.SetData(linesdata)
# Also create a Bitmap version of the drawing # Also create a Bitmap version of the drawing
size = self.GetSize() size = self.GetSize()
bmp = wxEmptyBitmap(size.width, size.height) bmp = wx.EmptyBitmap(size.width, size.height)
dc = wxMemoryDC() dc = wx.MemoryDC()
dc.SelectObject(bmp) dc.SelectObject(bmp)
dc.SetBackground(wxWHITE_BRUSH) dc.SetBackground(wx.WHITE_BRUSH)
dc.Clear() dc.Clear()
self.DrawSavedLines(dc) self.DrawSavedLines(dc)
dc.SelectObject(wxNullBitmap) dc.SelectObject(wx.NullBitmap)
# Now make a data object for the bitmap and also a composite # Now make a data object for the bitmap and also a composite
# data object holding both of the others. # data object holding both of the others.
bdata = wxBitmapDataObject(bmp) bdata = wx.BitmapDataObject(bmp)
data = wxDataObjectComposite() data = wx.DataObjectComposite()
data.Add(ldata) data.Add(ldata)
data.Add(bdata) data.Add(bdata)
# And finally, create the drop source and begin the drag # And finally, create the drop source and begin the drag
# and drop opperation # and drop opperation
dropSource = wxDropSource(self) dropSource = wx.DropSource(self)
dropSource.SetData(data) dropSource.SetData(data)
self.log.WriteText("Begining DragDrop\n") self.log.WriteText("Begining DragDrop\n")
result = dropSource.DoDragDrop(wxDrag_AllowMove) result = dropSource.DoDragDrop(wx.Drag_AllowMove)
self.log.WriteText("DragDrop completed: %d\n" % result) self.log.WriteText("DragDrop completed: %d\n" % result)
if result == wxDragMove:
if result == wx.DragMove:
self.lines = [] self.lines = []
self.Refresh() self.Refresh()
@@ -117,15 +125,15 @@ class DoodlePad(wxWindow):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class DoodleDropTarget(wxPyDropTarget): class DoodleDropTarget(wx.PyDropTarget):
def __init__(self, window, log): def __init__(self, window, log):
wxPyDropTarget.__init__(self) wx.PyDropTarget.__init__(self)
self.log = log self.log = log
self.dv = window self.dv = window
# specify the type of data we will accept # specify the type of data we will accept
self.df = wxCustomDataFormat("DoodleLines") self.df = wx.CustomDataFormat("DoodleLines")
self.data = wxCustomDataObject(self.df) self.data = wx.CustomDataObject(self.df)
self.SetDataObject(self.data) self.SetDataObject(self.data)
@@ -163,25 +171,26 @@ class DoodleDropTarget(wxPyDropTarget):
if self.GetData(): if self.GetData():
# convert it back to a list of lines and give it to the viewer # convert it back to a list of lines and give it to the viewer
linesdata = self.data.GetData() linesdata = self.data.GetData()
lines = cPickle.loads(linesdata) lines = wx.InputStream(cPickle.loads(linesdata))
self.dv.SetLines(lines) self.dv.SetLines(lines)
return d # what is returned signals the source what to do
# what is returned signals the source what to do
# with the original data (move, copy, etc.) In this # with the original data (move, copy, etc.) In this
# case we just return the suggested value given to us. # case we just return the suggested value given to us.
return d
class DoodleViewer(wx.Window):
class DoodleViewer(wxWindow):
def __init__(self, parent, log): def __init__(self, parent, log):
wxWindow.__init__(self, parent, -1, style=wxSUNKEN_BORDER) wx.Window.__init__(self, parent, -1, style=wx.SUNKEN_BORDER)
self.log = log self.log = log
self.SetBackgroundColour(wxWHITE) self.SetBackgroundColour(wx.WHITE)
self.lines = [] self.lines = []
self.x = self.y = 0 self.x = self.y = 0
dt = DoodleDropTarget(self, log) dt = DoodleDropTarget(self, log)
self.SetDropTarget(dt) self.SetDropTarget(dt)
EVT_PAINT(self, self.OnPaint) wx.EVT_PAINT(self, self.OnPaint)
def SetLines(self, lines): def SetLines(self, lines):
@@ -189,12 +198,13 @@ class DoodleViewer(wxWindow):
self.Refresh() self.Refresh()
def OnPaint(self, event): def OnPaint(self, event):
dc = wxPaintDC(self) dc = wx.PaintDC(self)
self.DrawSavedLines(dc) self.DrawSavedLines(dc)
def DrawSavedLines(self, dc): def DrawSavedLines(self, dc):
dc.BeginDrawing() dc.BeginDrawing()
dc.SetPen(wxPen(wxRED, 3)) dc.SetPen(wx.Pen(wx.RED, 3))
for line in self.lines: for line in self.lines:
for coords in line: for coords in line:
dc.DrawLineXY(*coords) dc.DrawLineXY(*coords)
@@ -202,14 +212,14 @@ class DoodleViewer(wxWindow):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class CustomDnDPanel(wxPanel): class CustomDnDPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.SetFont(wxFont(10, wxSWISS, wxNORMAL, wxBOLD, False)) self.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD, False))
# Make the controls # Make the controls
text1 = wxStaticText(self, -1, text1 = wx.StaticText(self, -1,
"Draw a little picture in this window\n" "Draw a little picture in this window\n"
"then switch the mode below and drag the\n" "then switch the mode below and drag the\n"
"picture to the lower window or to another\n" "picture to the lower window or to another\n"
@@ -217,12 +227,12 @@ class CustomDnDPanel(wxPanel):
"target.\n" "target.\n"
) )
rb1 = wxRadioButton(self, -1, "Draw", style=wxRB_GROUP) rb1 = wx.RadioButton(self, -1, "Draw", style=wx.RB_GROUP)
rb1.SetValue(True) rb1.SetValue(True)
rb2 = wxRadioButton(self, -1, "Drag") rb2 = wx.RadioButton(self, -1, "Drag")
rb2.SetValue(False) rb2.SetValue(False)
text2 = wxStaticText(self, -1, text2 = wx.StaticText(self, -1,
"The lower window is accepting a\n" "The lower window is accepting a\n"
"custom data type that is a pickled\n" "custom data type that is a pickled\n"
"Python list of lines data.") "Python list of lines data.")
@@ -231,9 +241,9 @@ class CustomDnDPanel(wxPanel):
view = DoodleViewer(self, log) view = DoodleViewer(self, log)
# put them in sizers # put them in sizers
sizer = wxBoxSizer(wxHORIZONTAL) sizer = wx.BoxSizer(wx.HORIZONTAL)
box = wxBoxSizer(wxVERTICAL) box = wx.BoxSizer(wx.VERTICAL)
rbox = wxBoxSizer(wxHORIZONTAL) rbox = wx.BoxSizer(wx.HORIZONTAL)
rbox.Add(rb1) rbox.Add(rb1)
rbox.Add(rb2) rbox.Add(rb2)
@@ -244,18 +254,18 @@ class CustomDnDPanel(wxPanel):
sizer.Add(box) sizer.Add(box)
dndsizer = wxBoxSizer(wxVERTICAL) dndsizer = wx.BoxSizer(wx.VERTICAL)
dndsizer.Add(self.pad, 1, wxEXPAND|wxALL, 5) dndsizer.Add(self.pad, 1, wx.EXPAND|wx.ALL, 5)
dndsizer.Add(view, 1, wxEXPAND|wxALL, 5) dndsizer.Add(view, 1, wx.EXPAND|wx.ALL, 5)
sizer.Add(dndsizer, 1, wxEXPAND) sizer.Add(dndsizer, 1, wx.EXPAND)
self.SetAutoLayout(True) self.SetAutoLayout(True)
self.SetSizer(sizer) self.SetSizer(sizer)
# Events # Events
EVT_RADIOBUTTON(self, rb1.GetId(), self.OnRadioButton) wx.EVT_RADIOBUTTON(self, rb1.GetId(), self.OnRadioButton)
EVT_RADIOBUTTON(self, rb2.GetId(), self.OnRadioButton) wx.EVT_RADIOBUTTON(self, rb2.GetId(), self.OnRadioButton)
def OnRadioButton(self, evt): def OnRadioButton(self, evt):
@@ -266,24 +276,24 @@ class CustomDnDPanel(wxPanel):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.SetAutoLayout(True) self.SetAutoLayout(True)
sizer = wxBoxSizer(wxVERTICAL) sizer = wx.BoxSizer(wx.VERTICAL)
msg = "Custom Drag-And-Drop" msg = "Custom Drag-And-Drop"
text = wxStaticText(self, -1, "", style=wxALIGN_CENTRE) text = wx.StaticText(self, -1, "", style=wx.ALIGN_CENTRE)
text.SetFont(wxFont(24, wxSWISS, wxNORMAL, wxBOLD, False)) text.SetFont(wx.Font(24, wx.SWISS, wx.NORMAL, wx.BOLD, False))
text.SetLabel(msg) text.SetLabel(msg)
w,h = text.GetTextExtent(msg) w,h = text.GetTextExtent(msg)
text.SetSize(wxSize(w,h+1)) text.SetSize(wx.Size(w,h+1))
text.SetForegroundColour(wxBLUE) text.SetForegroundColour(wx.BLUE)
sizer.Add(text, 0, wxEXPAND|wxALL, 5) sizer.Add(text, 0, wx.EXPAND|wx.ALL, 5)
sizer.Add(wxStaticLine(self, -1), 0, wxEXPAND) sizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND)
sizer.Add(CustomDnDPanel(self, log), 1, wxEXPAND) sizer.Add(CustomDnDPanel(self, log), 1, wx.EXPAND)
self.SetSizer(sizer) self.SetSizer(sizer)
@@ -298,29 +308,30 @@ def runTest(frame, nb, log):
if __name__ == '__main__': if __name__ == '__main__':
import sys import sys
class DummyLog: class DummyLog:
def WriteText(self, text): def WriteText(self, text):
sys.stdout.write(text) sys.stdout.write(text)
class TestApp(wxApp): class TestApp(wx.App):
def OnInit(self): def OnInit(self):
wxInitAllImageHandlers() wx.InitAllImageHandlers()
self.MakeFrame() self.MakeFrame()
return True return True
def MakeFrame(self, event=None): def MakeFrame(self, event=None):
frame = wxFrame(None, -1, "Custom Drag and Drop", size=(550,400)) frame = wx.Frame(None, -1, "Custom Drag and Drop", size=(550,400))
menu = wxMenu() menu = wx.Menu()
menu.Append(6543, "Window") menu.Append(6543, "Window")
mb = wxMenuBar() mb = wx.MenuBar()
mb.Append(menu, "New") mb.Append(menu, "New")
frame.SetMenuBar(mb) frame.SetMenuBar(mb)
EVT_MENU(frame, 6543, self.MakeFrame) wx.EVT_MENU(frame, 6543, self.MakeFrame)
panel = TestPanel(frame, DummyLog()) panel = TestPanel(frame, DummyLog())
frame.Show(True) frame.Show(True)
self.SetTopWindow(frame) self.SetTopWindow(frame)
#----------------------------------------------------------------------
app = TestApp(0) app = TestApp(0)
app.MainLoop() app.MainLoop()
@@ -338,10 +349,8 @@ A second data object is also created containing a bitmap of the image
and is made available to any drop target that accepts bitmaps, such as and is made available to any drop target that accepts bitmaps, such as
MS Word. MS Word.
The two data objects are combined in a wxDataObjectComposite and the The two data objects are combined in a wx.DataObjectComposite and the
rest is handled by the framework. rest is handled by the framework.
</body></html> </body></html>
""" """

View File

@@ -10,46 +10,50 @@
# Copyright: (c) 1998 by Total Control Software # Copyright: (c) 1998 by Total Control Software
# Licence: wxWindows license # Licence: wxWindows license
#---------------------------------------------------------------------------- #----------------------------------------------------------------------------
# Updated 11/9/2003 by Jeff Grimmett (grimmtooth@softhome.net)
#
# o Converted for V2.5 compatability
#
import wx
## import all of the wxPython GUI package
from wxPython.wx import *
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
## Create a new frame class, derived from the wxPython Frame. # Create a new frame class, derived from the wxPython Frame.
class MyFrame(wxFrame): class MyFrame(wx.Frame):
def __init__(self, parent, id, title): def __init__(self, parent, id, title):
# First, call the base class' __init__ method to create the frame # First, call the base class' __init__ method to create the frame
wxFrame.__init__(self, parent, id, title, wx.Frame.__init__(self, parent, id, title, (100, 100), (160, 100))
wxPoint(100, 100), wxSize(160, 100))
# Associate some events with methods of this class # Associate some events with methods of this class
EVT_SIZE(self, self.OnSize) self.Bind(wx.EVT_SIZE, self.OnSize)
EVT_MOVE(self, self.OnMove) self.Bind(wx.EVT_MOVE, self.OnMove)
EVT_CLOSE(self, self.OnCloseWindow) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
# Add a panel and some controls to display the size and position # Add a panel and some controls to display the size and position
panel = wxPanel(self, -1) panel = wx.Panel(self, -1)
wxStaticText(panel, -1, "Size:",
wxDLG_PNT(panel, wxPoint(4, 4)), wxDefaultSize)
wxStaticText(panel, -1, "Pos:",
wxDLG_PNT(panel, wxPoint(4, 16)), wxDefaultSize)
self.sizeCtrl = wxTextCtrl(panel, -1, "",
wxDLG_PNT(panel, wxPoint(24, 4)),
wxDLG_SZE(panel, wxSize(36, -1)),
wxTE_READONLY)
self.posCtrl = wxTextCtrl(panel, -1, "", wx.StaticText(panel, -1, "Size:",
wxDLG_PNT(panel, wxPoint(24, 16)), wx.DLG_PNT(panel, (4, 4)), wx.DefaultSize
wxDLG_SZE(panel, wxSize(36, -1)), )
wxTE_READONLY)
#print wxDLG_PNT(panel, wxPoint(24, 4)), wxDLG_SZE(panel, wxSize(36, -1)) wx.StaticText(panel, -1, "Pos:",
#print wxDLG_PNT(panel, wxPoint(24, 16)),wxDLG_SZE(panel, wxSize(36, -1)) wx.DLG_PNT(panel, (4, 16)), wx.DefaultSize
)
self.sizeCtrl = wx.TextCtrl(panel, -1, "",
wx.DLG_PNT(panel, (24, 4)),
wx.DLG_SZE(panel, (36, -1)),
wx.TE_READONLY)
self.posCtrl = wx.TextCtrl(panel, -1, "",
wx.DLG_PNT(panel, (24, 16)),
wx.DLG_SZE(panel, (36, -1)),
wx.TE_READONLY)
#print wx.DLG_PNT(panel, (24, 4)), wx.DLG_SZE(panel, (36, -1))
#print wx.DLG_PNT(panel, (24, 16)),wx.DLG_SZE(panel, (36, -1))
# This method is called automatically when the CLOSE event is # This method is called automatically when the CLOSE event is
# sent to this window # sent to this window
@@ -57,7 +61,6 @@ class MyFrame(wxFrame):
# tell the window to kill itself # tell the window to kill itself
self.Destroy() self.Destroy()
# This method is called by the System when the window is resized, # This method is called by the System when the window is resized,
# because of the association above. # because of the association above.
def OnSize(self, event): def OnSize(self, event):
@@ -81,7 +84,7 @@ class MyFrame(wxFrame):
if __name__ == "__main__": if __name__ == "__main__":
# Every wxWindows application must have a class derived from wxApp # Every wxWindows application must have a class derived from wxApp
class MyApp(wxApp): class MyApp(wx.App):
# wxWindows calls this method to initialize the application # wxWindows calls this method to initialize the application
def OnInit(self): def OnInit(self):

View File

@@ -1,85 +1,116 @@
# 11/5/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
# o Got rid of all the hardcoded window IDs.
# o Fixed a bug in class TestPanel() (empty sizer Add())
#
# 11/25/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Fixed a bug in the BMP file dialog; was using GetFilename()
# instead of GetPath() to get the file to load.
#
from wxPython.wx import * import wx
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class ClipTextPanel(wxPanel): ID_CopyBtn = wx.NewId()
ID_PasteBtn = wx.NewId()
ID_BitmapBtn = wx.NewId()
#----------------------------------------------------------------------
class ClipTextPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.log = log self.log = log
#self.SetFont(wxFont(10, wxSWISS, wxNORMAL, wxBOLD, False)) #self.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD, False))
sizer = wxBoxSizer(wxVERTICAL) sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(wxStaticText(self, -1, sizer.Add(
"Copy/Paste text to/from\n" wx.StaticText(
"this window and other apps"), 0, wxEXPAND|wxALL, 2) self, -1, "Copy/Paste text to/from\n"
"this window and other apps"
),
0, wx.EXPAND|wx.ALL, 2
)
self.text = wxTextCtrl(self, -1, "", style=wxTE_MULTILINE|wxHSCROLL) self.text = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE|wx.HSCROLL)
sizer.Add(self.text, 1, wxEXPAND) sizer.Add(self.text, 1, wx.EXPAND)
hsz = wxBoxSizer(wxHORIZONTAL) hsz = wx.BoxSizer(wx.HORIZONTAL)
hsz.Add(wxButton(self, 6050, " Copy "), 1, wxEXPAND|wxALL, 2) hsz.Add(wx.Button(self, ID_CopyBtn, " Copy "), 1, wx.EXPAND|wx.ALL, 2)
hsz.Add(wxButton(self, 6051, " Paste "), 1, wxEXPAND|wxALL, 2) hsz.Add(wx.Button(self, ID_PasteBtn, " Paste "), 1, wx.EXPAND|wx.ALL, 2)
sizer.Add(hsz, 0, wxEXPAND) sizer.Add(hsz, 0, wx.EXPAND)
sizer.Add(wxButton(self, 6052, " Copy Bitmap "), 0, wxEXPAND|wxALL, 2) sizer.Add(
wx.Button(self, ID_BitmapBtn, " Copy Bitmap "),
0, wx.EXPAND|wx.ALL, 2
)
EVT_BUTTON(self, 6050, self.OnCopy) self.Bind(wx.EVT_BUTTON, self.OnCopy, id=ID_CopyBtn)
EVT_BUTTON(self, 6051, self.OnPaste) self.Bind(wx.EVT_BUTTON, self.OnPaste, id=ID_PasteBtn)
EVT_BUTTON(self, 6052, self.OnCopyBitmap) self.Bind(wx.EVT_BUTTON, self.OnCopyBitmap, id=ID_BitmapBtn)
self.SetAutoLayout(True) self.SetAutoLayout(True)
self.SetSizer(sizer) self.SetSizer(sizer)
def OnCopy(self, evt): def OnCopy(self, evt):
self.do = wxTextDataObject() self.do = wx.TextDataObject()
self.do.SetText(self.text.GetValue()) self.do.SetText(self.text.GetValue())
wxTheClipboard.Open() wx.TheClipboard.Open()
wxTheClipboard.SetData(self.do) wx.TheClipboard.SetData(self.do)
wxTheClipboard.Close() wx.TheClipboard.Close()
def OnPaste(self, evt): def OnPaste(self, evt):
do = wxTextDataObject() do = wx.TextDataObject()
wxTheClipboard.Open() wx.TheClipboard.Open()
success = wxTheClipboard.GetData(do) success = wx.TheClipboard.GetData(do)
wxTheClipboard.Close() wx.TheClipboard.Close()
if success: if success:
self.text.SetValue(do.GetText()) self.text.SetValue(do.GetText())
else: else:
wxMessageBox("There is no data in the clipboard in the required format", wx.MessageBox(
"Error") "There is no data in the clipboard in the required format",
"Error"
)
def OnCopyBitmap(self, evt): def OnCopyBitmap(self, evt):
dlg = wxFileDialog(self, "Choose a bitmap to copy", wildcard="*.bmp") dlg = wx.FileDialog(self, "Choose a bitmap to copy", wildcard="*.bmp")
if dlg.ShowModal() == wxID_OK:
bmp = wxBitmap(dlg.GetFilename(), wxBITMAP_TYPE_BMP) if dlg.ShowModal() == wx.ID_OK:
bmpdo = wxBitmapDataObject(bmp) bmp = wx.Bitmap(dlg.GetPath(), wx.BITMAP_TYPE_BMP)
wxTheClipboard.Open() bmpdo = wx.BitmapDataObject(bmp)
wxTheClipboard.SetData(bmpdo) wx.TheClipboard.Open()
wxTheClipboard.Close() wx.TheClipboard.SetData(bmpdo)
wx.TheClipboard.Close()
wx.MessageBox(
"The bitmap is now in the Clipboard. Switch to a graphics\n"
"editor and try pasting it in..."
)
wxMessageBox("The bitmap is now in the Clipboard. Switch to a graphics\n"
"editor and try pasting it in...")
dlg.Destroy() dlg.Destroy()
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class OtherDropTarget(wxPyDropTarget): class OtherDropTarget(wx.PyDropTarget):
def __init__(self, window, log): def __init__(self, window, log):
wxPyDropTarget.__init__(self) wx.PyDropTarget.__init__(self)
self.log = log self.log = log
self.do = wxFileDataObject() self.do = wx.FileDataObject()
self.SetDataObject(self.do) self.SetDataObject(self.do)
def OnEnter(self, x, y, d): def OnEnter(self, x, y, d):
self.log.WriteText("OnEnter: %d, %d, %d\n" % (x, y, d)) self.log.WriteText("OnEnter: %d, %d, %d\n" % (x, y, d))
return wxDragCopy return wx.DragCopy
#def OnDragOver(self, x, y, d): #def OnDragOver(self, x, y, d):
# self.log.WriteText("OnDragOver: %d, %d, %d\n" % (x, y, d)) # self.log.WriteText("OnDragOver: %d, %d, %d\n" % (x, y, d))
# return wxDragCopy # return wx.DragCopy
def OnLeave(self): def OnLeave(self):
self.log.WriteText("OnLeave\n") self.log.WriteText("OnLeave\n")
@@ -95,11 +126,9 @@ class OtherDropTarget(wxPyDropTarget):
return d return d
class MyFileDropTarget(wx.FileDropTarget):
class MyFileDropTarget(wxFileDropTarget):
def __init__(self, window, log): def __init__(self, window, log):
wxFileDropTarget.__init__(self) wx.FileDropTarget.__init__(self)
self.window = window self.window = window
self.log = log self.log = log
@@ -107,13 +136,14 @@ class MyFileDropTarget(wxFileDropTarget):
self.window.SetInsertionPointEnd() self.window.SetInsertionPointEnd()
self.window.WriteText("\n%d file(s) dropped at %d,%d:\n" % self.window.WriteText("\n%d file(s) dropped at %d,%d:\n" %
(len(filenames), x, y)) (len(filenames), x, y))
for file in filenames: for file in filenames:
self.window.WriteText(file + '\n') self.window.WriteText(file + '\n')
class MyTextDropTarget(wxTextDropTarget): class MyTextDropTarget(wx.TextDropTarget):
def __init__(self, window, log): def __init__(self, window, log):
wxTextDropTarget.__init__(self) wx.TextDropTarget.__init__(self)
self.window = window self.window = window
self.log = log self.log = log
@@ -121,32 +151,43 @@ class MyTextDropTarget(wxTextDropTarget):
self.window.WriteText("(%d, %d)\n%s\n" % (x, y, text)) self.window.WriteText("(%d, %d)\n%s\n" % (x, y, text))
def OnDragOver(self, x, y, d): def OnDragOver(self, x, y, d):
return wxDragCopy return wx.DragCopy
class FileDropPanel(wxPanel): class FileDropPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
#self.SetFont(wxFont(10, wxSWISS, wxNORMAL, wxBOLD, False)) #self.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD, False))
sizer = wxBoxSizer(wxVERTICAL) sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(wxStaticText(self, -1, " \nDrag some files here:"), sizer.Add(
0, wxEXPAND|wxALL, 2) wx.StaticText(self, -1, " \nDrag some files here:"),
0, wx.EXPAND|wx.ALL, 2
)
self.text = wx.TextCtrl(
self, -1, "",
style = wx.TE_MULTILINE|wx.HSCROLL|wx.TE_READONLY
)
self.text = wxTextCtrl(self, -1, "",
style = wxTE_MULTILINE|wxHSCROLL|wxTE_READONLY)
dt = MyFileDropTarget(self, log) dt = MyFileDropTarget(self, log)
self.text.SetDropTarget(dt) self.text.SetDropTarget(dt)
sizer.Add(self.text, 1, wxEXPAND) sizer.Add(self.text, 1, wx.EXPAND)
sizer.Add(
wx.StaticText(self, -1, " \nDrag some text here:"),
0, wx.EXPAND|wx.ALL, 2
)
self.text2 = wx.TextCtrl(
self, -1, "",
style = wx.TE_MULTILINE|wx.HSCROLL|wx.TE_READONLY
)
sizer.Add(wxStaticText(self, -1, " \nDrag some text here:"),
0, wxEXPAND|wxALL, 2)
self.text2 = wxTextCtrl(self, -1, "",
style = wxTE_MULTILINE|wxHSCROLL|wxTE_READONLY)
dt = MyTextDropTarget(self.text2, log) dt = MyTextDropTarget(self.text2, log)
self.text2.SetDropTarget(dt) self.text2.SetDropTarget(dt)
sizer.Add(self.text2, 1, wxEXPAND) sizer.Add(self.text2, 1, wx.EXPAND)
self.SetAutoLayout(True) self.SetAutoLayout(True)
self.SetSizer(sizer) self.SetSizer(sizer)
@@ -162,28 +203,29 @@ class FileDropPanel(wxPanel):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.SetAutoLayout(True) self.SetAutoLayout(True)
outsideSizer = wxBoxSizer(wxVERTICAL) outsideSizer = wx.BoxSizer(wx.VERTICAL)
msg = "Clipboard / Drag-And-Drop" msg = "Clipboard / Drag-And-Drop"
text = wxStaticText(self, -1, "", style=wxALIGN_CENTRE) text = wx.StaticText(self, -1, "", style=wx.ALIGN_CENTRE)
text.SetFont(wxFont(24, wxSWISS, wxNORMAL, wxBOLD, False)) text.SetFont(wx.Font(24, wx.SWISS, wx.NORMAL, wx.BOLD, False))
text.SetLabel(msg) text.SetLabel(msg)
w,h = text.GetTextExtent(msg) w,h = text.GetTextExtent(msg)
text.SetSize(wxSize(w,h+1)) text.SetSize(wx.Size(w,h+1))
text.SetForegroundColour(wxBLUE) text.SetForegroundColour(wx.BLUE)
outsideSizer.Add(text, 0, wxEXPAND|wxALL, 5) outsideSizer.Add(text, 0, wx.EXPAND|wx.ALL, 5)
outsideSizer.Add(wxStaticLine(self, -1), 0, wxEXPAND) outsideSizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND)
inSizer = wxBoxSizer(wxHORIZONTAL) inSizer = wx.BoxSizer(wx.HORIZONTAL)
inSizer.Add(ClipTextPanel(self, log), 1, wxEXPAND) inSizer.Add(ClipTextPanel(self, log), 1, wx.EXPAND)
inSizer.Add(FileDropPanel(self, log), 1, wxEXPAND) inSizer.Add(FileDropPanel(self, log), 1, wx.EXPAND)
outsideSizer.Add(inSizer, 1, wxEXPAND) outsideSizer.Add(inSizer, 1, wx.EXPAND)
self.SetSizer(outsideSizer) self.SetSizer(outsideSizer)
@@ -196,17 +238,9 @@ def runTest(frame, nb, log):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
overview = """\
<html>
<body>
overview = """<html><body>\
This demo shows some examples of data transfer through clipboard or This demo shows some examples of data transfer through clipboard or
drag and drop. In wxWindows, these two ways to transfer data (either drag and drop. In wxWindows, these two ways to transfer data (either
between different applications or inside one and the same) are very between different applications or inside one and the same) are very
@@ -230,12 +264,11 @@ and target, the data provider and the data receiver. These which may
be in the same application and even the same window when, for example, be in the same application and even the same window when, for example,
you drag some text from one position to another in a word you drag some text from one position to another in a word
processor. Let us describe what each of them should do. processor. Let us describe what each of them should do.
</body></html> </body>
</html>
""" """
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run

View File

@@ -1,6 +1,18 @@
# 11/5/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
# o Replaced all calls to deprecated whrandom module with up to date random calls.
# See Python docs regarding whrandom for details.
#
# 11/25/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o New binding
#
from wxPython.wx import * import random
import whrandom, time import time
import wx
#---------------------------------------------------------------------- #----------------------------------------------------------------------
@@ -28,84 +40,106 @@ colours = [
def makeRandomPoints(num, w, h): def makeRandomPoints(num, w, h):
pnts = [] pnts = []
for i in range(num): for i in range(num):
x = whrandom.randint(0, w) x = random.randint(0, w)
y = whrandom.randint(0, h) y = random.randint(0, h)
pnts.append( (x,y) ) pnts.append( (x,y) )
return pnts return pnts
def makeRandomLines(num, w, h): def makeRandomLines(num, w, h):
pnts = [] pnts = []
for i in range(num): for i in range(num):
x1 = whrandom.randint(0, w) x1 = random.randint(0, w)
y1 = whrandom.randint(0, h) y1 = random.randint(0, h)
x2 = whrandom.randint(0, w) x2 = random.randint(0, w)
y2 = whrandom.randint(0, h) y2 = random.randint(0, h)
pnts.append( (x1,y1, x2,y2) ) pnts.append( (x1,y1, x2,y2) )
return pnts return pnts
def makeRandomRectangles(num, W, H): def makeRandomRectangles(num, W, H):
rects = [] rects = []
for i in range(num): for i in range(num):
w = whrandom.randint(10, W/2) w = random.randint(10, W/2)
h = whrandom.randint(10, H/2) h = random.randint(10, H/2)
x = whrandom.randint(0, W - w) x = random.randint(0, W - w)
y = whrandom.randint(0, H - h) y = random.randint(0, H - h)
rects.append( (x, y, w, h) ) rects.append( (x, y, w, h) )
return rects return rects
def makeRandomText(num): def makeRandomText(num):
Np = 8 # number of characters in text Np = 8 # number of characters in text
text = [] text = []
for i in range(num): for i in range(num):
word = [] word = []
for i in range(Np): for i in range(Np):
c = chr( whrandom.randint(48, 122) ) c = chr( random.randint(48, 122) )
word.append( c ) word.append( c )
text.append( "".join(word) ) text.append( "".join(word) )
return text return text
def makeRandomPolygons(num, W, H): def makeRandomPolygons(num, W, H):
Np = 8 # number of points per polygon Np = 8 # number of points per polygon
polys = [] polys = []
for i in range(num): for i in range(num):
poly = [] poly = []
for i in range(Np):
x = whrandom.randint(0, W)
y = whrandom.randint(0, H)
poly.append( (x,y) )
polys.append( poly )
return polys
for i in range(Np):
x = random.randint(0, W)
y = random.randint(0, H)
poly.append( (x,y) )
polys.append( poly )
return polys
def makeRandomPens(num, cache): def makeRandomPens(num, cache):
pens = [] pens = []
for i in range(num): for i in range(num):
c = whrandom.choice(colours) c = random.choice(colours)
t = whrandom.randint(1, 4) t = random.randint(1, 4)
if not cache.has_key( (c, t) ): if not cache.has_key( (c, t) ):
cache[(c, t)] = wxPen(c, t) cache[(c, t)] = wx.Pen(c, t)
pens.append( cache[(c, t)] ) pens.append( cache[(c, t)] )
return pens return pens
def makeRandomBrushes(num, cache): def makeRandomBrushes(num, cache):
brushes = [] brushes = []
for i in range(num): for i in range(num):
c = whrandom.choice(colours) c = random.choice(colours)
if not cache.has_key(c): if not cache.has_key(c):
cache[c] = wxBrush(c) cache[c] = wx.Brush(c)
brushes.append( cache[c] ) brushes.append( cache[c] )
return brushes return brushes
def makeRandomColors(num): def makeRandomColors(num):
colors = [] colors = []
for i in range(num): for i in range(num):
c = whrandom.choice(colours) c = whrandom.choice(colours)
colors.append(wxNamedColour(c)) colors.append(wxNamedColour(c))
@@ -141,11 +175,13 @@ def Init(w, h, n):
# make some lists of random shapes # make some lists of random shapes
points = makeRandomPoints(n, w, h) points = makeRandomPoints(n, w, h)
try: try:
import Numeric import Numeric
Apoints = Numeric.array(points) Apoints = Numeric.array(points)
except: except:
pass pass
lines = makeRandomLines(n, w, h) lines = makeRandomLines(n, w, h)
rectangles = makeRandomRectangles(n, w, h) rectangles = makeRandomRectangles(n, w, h)
polygons = makeRandomPolygons(n, w, h) polygons = makeRandomPolygons(n, w, h)
@@ -163,10 +199,10 @@ def Init(w, h, n):
def TestPoints(dc,log): def TestPoints(dc,log):
dc.BeginDrawing() dc.BeginDrawing()
start = time.time() start = time.time()
dc.SetPen(wxPen("BLACK", 4)) dc.SetPen(wx.Pen("BLACK", 4))
dc.DrawPointList(points) dc.DrawPointList(points)
dc.DrawPointList(points, wxPen("RED", 2)) dc.DrawPointList(points, wx.Pen("RED", 2))
dc.DrawPointList(points, pens) dc.DrawPointList(points, pens)
dc.EndDrawing() dc.EndDrawing()
@@ -179,10 +215,12 @@ def TestArrayPoints(dc,log):
dc.BeginDrawing() dc.BeginDrawing()
start = time.time() start = time.time()
dc.SetPen(wxPen("BLACK", 1)) dc.SetPen(wx.Pen("BLACK", 1))
for i in range(1): for i in range(1):
dc.DrawPointList(Apoints) dc.DrawPointList(Apoints)
#dc.DrawPointList(Apoints, wxPen("RED", 2))
#dc.DrawPointList(Apoints, wx.Pen("RED", 2))
#dc.DrawPointList(Apoints, pens) #dc.DrawPointList(Apoints, pens)
dc.EndDrawing() dc.EndDrawing()
log.write("DrawTime: %s seconds with DrawPointList an Numpy Array\n" % (time.time() - start)) log.write("DrawTime: %s seconds with DrawPointList an Numpy Array\n" % (time.time() - start))
@@ -195,9 +233,9 @@ def TestLines(dc,log):
dc.BeginDrawing() dc.BeginDrawing()
start = time.time() start = time.time()
dc.SetPen(wxPen("BLACK", 2)) dc.SetPen(wx.Pen("BLACK", 2))
dc.DrawLineList(lines) dc.DrawLineList(lines)
dc.DrawLineList(lines, wxPen("RED", 2)) dc.DrawLineList(lines, wx.Pen("RED", 2))
dc.DrawLineList(lines, pens) dc.DrawLineList(lines, pens)
dc.EndDrawing() dc.EndDrawing()
@@ -208,8 +246,8 @@ def TestRectangles(dc,log):
dc.BeginDrawing() dc.BeginDrawing()
start = time.time() start = time.time()
dc.SetPen( wxPen("BLACK",1) ) dc.SetPen( wx.Pen("BLACK",1) )
dc.SetBrush( wxBrush("RED") ) dc.SetBrush( wx.Brush("RED") )
dc.DrawRectangleList(rectangles) dc.DrawRectangleList(rectangles)
dc.DrawRectangleList(rectangles,pens) dc.DrawRectangleList(rectangles,pens)
@@ -228,8 +266,8 @@ def TestEllipses(dc,log):
dc.BeginDrawing() dc.BeginDrawing()
start = time.time() start = time.time()
dc.SetPen( wxPen("BLACK",1) ) dc.SetPen( wx.Pen("BLACK",1) )
dc.SetBrush( wxBrush("RED") ) dc.SetBrush( wx.Brush("RED") )
dc.DrawEllipseList(rectangles) dc.DrawEllipseList(rectangles)
dc.DrawEllipseList(rectangles,pens) dc.DrawEllipseList(rectangles,pens)
@@ -249,7 +287,7 @@ def TestRectanglesArray(dc,log):
dc.BeginDrawing() dc.BeginDrawing()
start = time.time() start = time.time()
dc.SetPen(wxPen("BLACK", 1)) dc.SetPen(wx.Pen("BLACK", 1))
dc.DrawRectangleList(rectangles) dc.DrawRectangleList(rectangles)
dc.DrawRectangleList(rectangles,pens) dc.DrawRectangleList(rectangles,pens)
dc.DrawRectangleList(rectangles,pens[0],brushes) dc.DrawRectangleList(rectangles,pens[0],brushes)
@@ -274,10 +312,12 @@ def TestRectanglesLoop(dc,log):
log.write("DrawTime: %s seconds with DrawRectanglesList\n" % (time.time() - start)) log.write("DrawTime: %s seconds with DrawRectanglesList\n" % (time.time() - start))
start = time.time() start = time.time()
for i in range(len(rectangles)): for i in range(len(rectangles)):
dc.SetPen( pens[i] ) dc.SetPen( pens[i] )
dc.SetBrush( brushes[i] ) dc.SetBrush( brushes[i] )
dc.DrawRectangle(rectangles[i][0],rectangles[i][1],rectangles[i][2],rectangles[i][3]) dc.DrawRectangle(rectangles[i][0],rectangles[i][1],rectangles[i][2],rectangles[i][3])
dc.EndDrawing() dc.EndDrawing()
log.write("DrawTime: %s seconds with Python loop\n" % (time.time() - start)) log.write("DrawTime: %s seconds with Python loop\n" % (time.time() - start))
@@ -286,7 +326,7 @@ def TestPolygons(dc,log):
dc.BeginDrawing() dc.BeginDrawing()
start = time.time() start = time.time()
dc.SetPen(wxPen("BLACK", 1)) dc.SetPen(wx.Pen("BLACK", 1))
dc.DrawPolygonList(polygons) dc.DrawPolygonList(polygons)
dc.DrawPolygonList(polygons,pens) dc.DrawPolygonList(polygons,pens)
dc.DrawPolygonList(polygons,pens[0],brushes) dc.DrawPolygonList(polygons,pens[0],brushes)
@@ -303,7 +343,7 @@ def TestText(dc,log):
start = time.time() start = time.time()
# NOTE: you need to set BackgroundMode for the background colors to be used. # NOTE: you need to set BackgroundMode for the background colors to be used.
dc.SetBackgroundMode(wxSOLID) dc.SetBackgroundMode(wx.SOLID)
foreground = colors1 foreground = colors1
background = colors2 background = colors2
dc.DrawTextList(text, points, foreground, background) dc.DrawTextList(text, points, foreground, background)
@@ -314,14 +354,17 @@ def TestText(dc,log):
class TestNB(wxNotebook): class TestNB(wx.Notebook):
def __init__(self, parent, id, log): def __init__(self, parent, id, log):
style = wxNB_BOTTOM style = wx.NB_BOTTOM
if wxPlatform == "__WXMAC__":
if wx.Platform == "__WXMAC__":
style = 0 style = 0
wxNotebook.__init__(self, parent, id, style=style)
wx.Notebook.__init__(self, parent, id, style=style)
self.log = log self.log = log
# Initialize our various samples and add them to the notebook.
win = DrawPanel(self, TestEllipses, log) win = DrawPanel(self, TestEllipses, log)
self.AddPage(win, 'Ellipses') self.AddPage(win, 'Ellipses')
@@ -340,19 +383,21 @@ class TestNB(wxNotebook):
win = DrawPanel(self, TestRectangles, log) win = DrawPanel(self, TestRectangles, log)
self.AddPage(win, 'Rectangles') self.AddPage(win, 'Rectangles')
# Class used for all the various sample pages; the mechanics are the same
class DrawPanel(wxPanel): # for each one with regards to the notebook. The only difference is
# the function we use to draw on it.
class DrawPanel(wx.Panel):
def __init__(self, parent, drawFun, log): def __init__(self, parent, drawFun, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.SetBackgroundColour(wxWHITE) self.SetBackgroundColour(wx.WHITE)
self.log = log self.log = log
self.drawFun = drawFun self.drawFun = drawFun
EVT_PAINT(self, self.OnPaint) self.Bind(wx.EVT_PAINT, self.OnPaint)
def OnPaint(self, evt): def OnPaint(self, evt):
dc = wxPaintDC(self) dc = wx.PaintDC(self)
dc.Clear() dc.Clear()
self.drawFun(dc,self.log) self.drawFun(dc,self.log)
@@ -373,7 +418,7 @@ def runTest(frame, nb, log):
overview = """\ overview = """\
Some methods have been added to wxDC to help with optimization of Some methods have been added to wx.DC to help with optimization of
drawing routines. Currently they are: drawing routines. Currently they are:
<pre> <pre>

View File

@@ -2,10 +2,25 @@
# usual wxWindows license stuff here. # usual wxWindows license stuff here.
# by Chris Fama, with thanks to Robin Dunn, and others on the wxPython-users # by Chris Fama, with thanks to Robin Dunn, and others on the wxPython-users
# mailing list. # mailing list.
#
# 11/22/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
# 11/25/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Looks like we have issues until the library is updated.
# - Had to rename back to wx* naming conventions
# - Getting unusual failures in the library itself when that is done.
#
import sys
import wx
import wx.lib.ErrorDialogs as edlg
from wxPython.wx import *
from wxPython.lib.ErrorDialogs import *
_debug = 0 _debug = 0
ID_TEXT = 10000 ID_TEXT = 10000
ID_BUTTON_wxPyNonFatalError = 10001 ID_BUTTON_wxPyNonFatalError = 10001
ID_BUTTON_wxPyFatalError = 10002 ID_BUTTON_wxPyFatalError = 10002
@@ -15,44 +30,54 @@ ID_BUTTON_wxPyFatalErrorDialogWithTraceback = 10005
ID_BUTTON_wxPyNonFatalErrorDialogWithTraceback = 10006 ID_BUTTON_wxPyNonFatalErrorDialogWithTraceback = 10006
def ErrorDialogsDemoPanelFunc( parent, call_fit = True, set_sizer = True ): def ErrorDialogsDemoPanelFunc( parent, call_fit = True, set_sizer = True ):
item0 = wxBoxSizer( wxVERTICAL ) item0 = wx.BoxSizer( wx.VERTICAL )
item1 = wxStaticText( parent, ID_TEXT, "Please select one of the buttons below for an example using explicit errors...", wxDefaultPosition, wxDefaultSize, 0 ) item1 = wx.StaticText(
item0.AddWindow( item1, 0, wxALIGN_CENTRE|wxALL, 5 ) parent, ID_TEXT,
"Please select one of the buttons below for an example using explicit errors..."
)
item2 = wxFlexGridSizer( 0, 2, 0, 0 ) item0.AddWindow( item1, 0, wx.ALIGN_CENTRE|wx.ALL, 5 )
item3 = wxButton( parent, ID_BUTTON_wxPyNonFatalError, "wxPyNonFatalError", wxDefaultPosition, wxDefaultSize, 0 ) item2 = wx.FlexGridSizer( 0, 2, 0, 0 )
item2.AddWindow( item3, 0, wxALIGN_CENTRE|wxALL, 5 )
item4 = wxButton( parent, ID_BUTTON_wxPyFatalError, "wxPyFatalError", wxDefaultPosition, wxDefaultSize, 0 ) item3 = wx.Button( parent, ID_BUTTON_wxPyNonFatalError, "wxPyNonFatalError")
item2.AddWindow( item4, 0, wxALIGN_CENTRE|wxALL, 5 ) item2.AddWindow( item3, 0, wx.ALIGN_CENTRE|wx.ALL, 5 )
item0.AddSizer( item2, 0, wxALIGN_CENTRE|wxALL, 5 ) item4 = wx.Button( parent, ID_BUTTON_wxPyFatalError, "wxPyFatalError")
item2.AddWindow( item4, 0, wx.ALIGN_CENTRE|wx.ALL, 5 )
item5 = wxStaticText( parent, ID_TEXT, "Please select one of the buttons below for interpreter errors...", wxDefaultPosition, wxDefaultSize, 0 ) item0.AddSizer( item2, 0, wx.ALIGN_CENTRE|wx.ALL, 5 )
item0.AddWindow( item5, 0, wxALIGN_CENTRE|wxALL, 5 )
item6 = wxFlexGridSizer( 0, 2, 0, 0 ) item5 = wx.StaticText( parent, ID_TEXT, "Please select one of the buttons below for interpreter errors...")
item0.AddWindow( item5, 0, wx.ALIGN_CENTRE|wx.ALL, 5 )
item7 = wxButton( parent, ID_BUTTON_wxPyFatalErrorDialog, "wxPyFatalErrorDialog", wxDefaultPosition, wxDefaultSize, 0 ) item6 = wx.FlexGridSizer( 0, 2, 0, 0 )
item6.AddWindow( item7, 0, wxALIGN_CENTRE|wxALL, 5 )
item8 = wxButton( parent, ID_BUTTON_wxPyNonFatalErrorDialog, "wxPyNonFatalErrorDialog", wxDefaultPosition, wxDefaultSize, 0 ) item7 = wx.Button( parent, ID_BUTTON_wxPyFatalErrorDialog, "wxPyFatalErrorDialog")
item6.AddWindow( item8, 0, wxALIGN_CENTRE|wxALL, 5 ) item6.AddWindow( item7, 0, wx.ALIGN_CENTRE|wx.ALL, 5 )
item9 = wxButton( parent, ID_BUTTON_wxPyFatalErrorDialogWithTraceback, "wxPyFatalErrorDialogWithTraceback", wxDefaultPosition, wxDefaultSize, 0 ) item8 = wx.Button( parent, ID_BUTTON_wxPyNonFatalErrorDialog, "wxPyNonFatalErrorDialog")
item6.AddWindow( item9, 0, wxALIGN_CENTRE|wxALL, 5 ) item6.AddWindow( item8, 0, wx.ALIGN_CENTRE|wx.ALL, 5 )
item10 = wxButton( parent, ID_BUTTON_wxPyNonFatalErrorDialogWithTraceback, "wxPyNonFatalErrorDialogWithTraceback", wxDefaultPosition, wxDefaultSize, 0 ) item9 = wx.Button(
parent, ID_BUTTON_wxPyFatalErrorDialogWithTraceback,
"wxPyFatalErrorDialogWithTraceback"
)
item6.AddWindow( item9, 0, wx.ALIGN_CENTRE|wx.ALL, 5 )
item10 = wx.Button(
parent, ID_BUTTON_wxPyNonFatalErrorDialogWithTraceback,
"wxPyNonFatalErrorDialogWithTraceback"
)
item10.SetDefault() item10.SetDefault()
item6.AddWindow( item10, 0, wxALIGN_CENTRE|wxALL, 5 ) item6.AddWindow( item10, 0, wx.ALIGN_CENTRE|wx.ALL, 5 )
item0.AddSizer( item6, 0, wxALIGN_CENTRE|wxALL, 5 ) item0.AddSizer( item6, 0, wx.ALIGN_CENTRE|wx.ALL, 5 )
item11 = wxFlexGridSizer( 0, 2, 0, 0 ) item11 = wx.FlexGridSizer( 0, 2, 0, 0 )
item0.AddSizer( item11, 0, wxALIGN_CENTRE|wxALL, 5 ) item0.AddSizer( item11, 0, wx.ALIGN_CENTRE|wx.ALL, 5 )
if set_sizer == True: if set_sizer == True:
parent.SetAutoLayout( True ) parent.SetAutoLayout( True )
@@ -70,42 +95,35 @@ def ErrorDialogsDemoPanelFunc( parent, call_fit = True, set_sizer = True ):
# End of generated file # End of generated file
class MyPanel(wxPanel): class MyPanel(wx.Panel):
def __init__(self,parent=None): def __init__(self,parent=None):
wxPanel.__init__(self,parent,-1) wx.Panel.__init__(self,parent,-1)
args = (None, -1) args = (None, -1)
kwargs = { kwargs = {
'programname': "sumthing", 'programname': "sumthing",
'mailto': "me@sumwear", 'mailto': "me@sumwear",
'whendismissed': "from wxPython.wx import * ; wxBell()"} 'whendismissed': "from wxPython.wx import * ; wxBell()"
}
self.dialogs = map(apply, self.dialogs = map(apply,
[wxPyNonFatalErrorDialogWithTraceback, [edlg.wxPyNonFatalErrorDialogWithTraceback,
wxPyNonFatalErrorDialog,#WithTraceback edlg.wxPyNonFatalErrorDialog,#WithTraceback
wxPyFatalErrorDialogWithTraceback, edlg.wxPyFatalErrorDialogWithTraceback,
wxPyFatalErrorDialog],#WithTraceback edlg.wxPyFatalErrorDialog #WithTraceback
],
(args,) * 4, (args,) * 4,
(kwargs,) * 4) (kwargs,) * 4
)
ErrorDialogsDemoPanelFunc(self) ErrorDialogsDemoPanelFunc(self)
EVT_BUTTON(self, self.Bind(wx.EVT_BUTTON, self.DoDialog, id=ID_BUTTON_wxPyFatalErrorDialog)
ID_BUTTON_wxPyFatalErrorDialog, self.Bind(wx.EVT_BUTTON, self.DoDialog, id=ID_BUTTON_wxPyNonFatalError)
self.DoDialog) self.Bind(wx.EVT_BUTTON, self.DoDialog, id=ID_BUTTON_wxPyFatalError)
EVT_BUTTON(self, self.Bind(wx.EVT_BUTTON, self.DoDialog, id=ID_BUTTON_wxPyFatalErrorDialogWithTraceback)
ID_BUTTON_wxPyNonFatalError, self.Bind(wx.EVT_BUTTON, self.DoDialog, id=ID_BUTTON_wxPyNonFatalErrorDialog)
self.DoDialog) self.Bind(wx.EVT_BUTTON, self.DoDialog, id=ID_BUTTON_wxPyNonFatalErrorDialogWithTraceback)
EVT_BUTTON(self,
ID_BUTTON_wxPyFatalError,
self.DoDialog)
EVT_BUTTON(self,
ID_BUTTON_wxPyFatalErrorDialogWithTraceback,
self.DoDialog)
EVT_BUTTON(self,
ID_BUTTON_wxPyNonFatalErrorDialog,
self.DoDialog)
EVT_BUTTON(self,
ID_BUTTON_wxPyNonFatalErrorDialogWithTraceback,
self.DoDialog)
IndexFromID = { IndexFromID = {
ID_BUTTON_wxPyFatalErrorDialog: 3, ID_BUTTON_wxPyFatalErrorDialog: 3,
@@ -116,11 +134,12 @@ class MyPanel(wxPanel):
def DoDialog(self,event): def DoDialog(self,event):
id = event.GetId() id = event.GetId()
if id in [ID_BUTTON_wxPyFatalError,ID_BUTTON_wxPyNonFatalError]: if id in [ID_BUTTON_wxPyFatalError,ID_BUTTON_wxPyNonFatalError]:
if id == ID_BUTTON_wxPyFatalError: if id == ID_BUTTON_wxPyFatalError:
print "%s.DoDialog(): testing explicit wxPyFatalError..."\ print "%s.DoDialog(): testing explicit wxPyFatalError..."\
% self % self
wxPyFatalError(self,"Test Non-fatal error.<p>" edlg.wxPyFatalError(self,"Test Non-fatal error.<p>"
"Nearly arbitrary HTML (i.e., that which is" "Nearly arbitrary HTML (i.e., that which is"
" understood by <B><I>wxHtmlWindow</i></b>)." " understood by <B><I>wxHtmlWindow</i></b>)."
"<p><table border=\"2\"><tr><td>This</td><td>is</td></tr>" "<p><table border=\"2\"><tr><td>This</td><td>is</td></tr>"
@@ -128,7 +147,7 @@ class MyPanel(wxPanel):
else: else:
print "%s.DoDialog(): testing explicit wxPyNonFatalError..."\ print "%s.DoDialog(): testing explicit wxPyNonFatalError..."\
% self % self
wxPyNonFatalError(self,"Test Non-fatal error.<p>" edlg.wxPyNonFatalError(self,"Test Non-fatal error.<p>"
"Nearly arbitrary HTML (i.e., that which is" "Nearly arbitrary HTML (i.e., that which is"
" understood by <B><I>wxHtmlWindow</i></b>)." " understood by <B><I>wxHtmlWindow</i></b>)."
"<p><table border=\"2\"><tr><td>This</td><td>is</td></tr>" "<p><table border=\"2\"><tr><td>This</td><td>is</td></tr>"
@@ -144,19 +163,19 @@ class MyPanel(wxPanel):
class MyFrame(wxFrame): class MyFrame(wx.Frame):
def __init__(self,parent=None): def __init__(self,parent=None):
wxFrame.__init__(self,parent,-1, wx.Frame.__init__(self,parent,-1,
"Please make a selection...", "Please make a selection...",
) )
self.panel = MyPanel(self) self.panel = MyPanel(self)
EVT_CLOSE (self,self.OnCloseWindow) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
def OnCloseWindow(self,event): def OnCloseWindow(self,event):
self.panel.Close() self.panel.Close()
self.Destroy() self.Destroy()
class MyApp(wxApp): class MyApp(wx.App):
def OnInit(self): def OnInit(self):
frame = MyFrame() frame = MyFrame()
frame.Show(True) frame.Show(True)
@@ -167,13 +186,12 @@ def runTest(pframe, nb, log):
panel = MyPanel(nb) panel = MyPanel(nb)
return panel return panel
from wxPython.lib import ErrorDialogs edlg._debug = 1
ErrorDialogs._debug = 1
if __name__ == "__main__": if __name__ == "__main__":
sys.stderr = wxPyNonWindowingErrorHandler() sys.stderr = edlg.wxPyNonWindowingErrorHandler()
app = MyApp(0) app = MyApp(0)
app.MainLoop() app.MainLoop()
sys.exit() sys.exit()
else: else:
overview = ErrorDialogs.__doc__ overview = edlg.__doc__

View File

@@ -8,48 +8,58 @@
# Copyright: (c) 2002 by Robb Shecter (robb@acm.org) # Copyright: (c) 2002 by Robb Shecter (robb@acm.org)
# Licence: wxWindows license # Licence: wxWindows license
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
#
# 11/22/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
# 11/25/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o What happened to wx.Color()?
#
from wxPython.wx import *
from wxPython.lib.evtmgr import eventManager import wx
import wx.lib.evtmgr as em
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.log = log self.log = log
fsize = self.GetFont().GetPointSize() fsize = self.GetFont().GetPointSize()
f1 = wxFont(fsize+0, wxSWISS, wxNORMAL, wxNORMAL) f1 = wx.Font(fsize+0, wx.SWISS, wx.NORMAL, wx.NORMAL)
f2 = wxFont(fsize+2, wxSWISS, wxNORMAL, wxBOLD) f2 = wx.Font(fsize+2, wx.SWISS, wx.NORMAL, wx.BOLD)
f3 = wxFont(fsize+6, wxSWISS, wxNORMAL, wxBOLD) f3 = wx.Font(fsize+6, wx.SWISS, wx.NORMAL, wx.BOLD)
title1 = wxStaticText(self, -1, 'EventManager') title1 = wx.StaticText(self, -1, 'EventManager')
title1.SetFont(f3) title1.SetFont(f3)
txt = """\ txt = """\
This demo shows (1) basic uses and features of the EventManager, as well This demo shows (1) basic uses and features of the EventManager, as well
as (2) how it helps with a real-world task: creating independent, object- as (2) how it helps with a real-world task: creating independent, object-
oriented components.""" oriented components."""
message0 = wxStaticText(self, -1, txt) message0 = wx.StaticText(self, -1, txt)
message0.SetFont(f1) message0.SetFont(f1)
title2 = wxStaticText(self, -1, 'Event Listeners') title2 = wx.StaticText(self, -1, 'Event Listeners')
title2.SetFont(f2) title2.SetFont(f2)
txt = """\ txt = """\
These objects listen to motion events from the target window, using the ability These objects listen to motion events from the target window, using the ability
to register one event with multiple listeners. They also register for mouse events to register one event with multiple listeners. They also register for mouse events
on themselves to implement toggle-button functionality.""" on themselves to implement toggle-button functionality."""
message1 = wxStaticText(self, -1, txt) message1 = wx.StaticText(self, -1, txt)
message1.SetFont(f1) message1.SetFont(f1)
title3 = wxStaticText(self, -1, 'Target Window') title3 = wx.StaticText(self, -1, 'Target Window')
title3.SetFont(f2) title3.SetFont(f2)
txt = """\ txt = """\
A passive window that's used as an event generator. Move the mouse over it to A passive window that's used as an event generator. Move the mouse over it to
send events to the listeners above.""" send events to the listeners above."""
message2 = wxStaticText(self, -1, txt) message2 = wx.StaticText(self, -1, txt)
message2.SetFont(f1) message2.SetFont(f1)
targetPanel = Tile(self, log, bgColor=wxColour(80,10,10), active=0) targetPanel = Tile(self, log, bgColor=wxColour(80,10,10), active=0)
@@ -68,36 +78,36 @@ class TestPanel(wxPanel):
buttonPanel.SetSizer(sizer) buttonPanel.SetSizer(sizer)
sizer.Fit(buttonPanel) sizer.Fit(buttonPanel)
sizer = wxBoxSizer(wxVERTICAL) sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(title1, 0, wxALIGN_CENTER | wxTOP | wxBOTTOM, 6) sizer.Add(title1, 0, wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, 6)
sizer.Add(message0, 0, wxALIGN_CENTER | wxALL, 6) sizer.Add(message0, 0, wx.ALIGN_CENTER | wx.ALL, 6)
sizer.Add(title2, 0, wxALIGN_CENTER | wxLEFT | wxTOP | wxRIGHT, 16) sizer.Add(title2, 0, wx.ALIGN_CENTER | wx.LEFT | wx.TOP | wx.RIGHT, 16)
sizer.Add(message1, 0, wxALIGN_CENTER | wxALL, 6) sizer.Add(message1, 0, wx.ALIGN_CENTER | wx.ALL, 6)
sizer.Add(buttonPanel, 0, wxEXPAND | wxLEFT | wxBOTTOM | wxRIGHT, 16) sizer.Add(buttonPanel, 0, wx.EXPAND | wx.LEFT | wx.BOTTOM | wx.RIGHT, 16)
sizer.Add(title3, 0, wxALIGN_CENTER | wxLEFT | wxRIGHT, 16) sizer.Add(title3, 0, wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT, 16)
sizer.Add(message2, 0, wxALIGN_CENTER | wxALL, 6) sizer.Add(message2, 0, wx.ALIGN_CENTER | wx.ALL, 6)
sizer.Add(targetPanel, 2, wxEXPAND | wxLEFT | wxBOTTOM | wxRIGHT, 16) sizer.Add(targetPanel, 2, wx.EXPAND | wx.LEFT | wx.BOTTOM | wx.RIGHT, 16)
self.SetAutoLayout(1) self.SetAutoLayout(1)
self.SetSizer(sizer) self.SetSizer(sizer)
class Tile(wxPanel): class Tile(wx.Panel):
""" """
This outer class is responsible for changing This outer class is responsible for changing
its border color in response to certain mouse its border color in response to certain mouse
events over its contained 'InnerTile'. events over its contained 'InnerTile'.
""" """
normal = wxColour(150,150,150) normal = wx.Colour(150,150,150)
active = wxColour(250,245,245) active = wx.Colour(250,245,245)
hover = wxColour(210,220,210) hover = wx.Colour(210,220,210)
def __init__(self, parent, log, factor=1, thingToWatch=None, bgColor=None, active=1, size=(38,38), borderWidth=3): def __init__(self, parent, log, factor=1, thingToWatch=None, bgColor=None, active=1, size=(38,38), borderWidth=3):
wxPanel.__init__(self, parent, -1, size=size, style=wxCLIP_CHILDREN) wx.Panel.__init__(self, parent, -1, size=size, style=wx.CLIP_CHILDREN)
self.tile = InnerTile(self, log, factor, thingToWatch, bgColor) self.tile = InnerTile(self, log, factor, thingToWatch, bgColor)
self.log = log self.log = log
sizer = wxBoxSizer(wxHORIZONTAL) sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(self.tile, 1, wxEXPAND | wxALL, borderWidth) sizer.Add(self.tile, 1, wx.EXPAND | wx.ALL, borderWidth)
self.SetAutoLayout(1) self.SetAutoLayout(1)
self.SetSizer(sizer) self.SetSizer(sizer)
self.Layout() self.Layout()
@@ -105,10 +115,10 @@ class Tile(wxPanel):
if active: if active:
# Register myself for mouse events over self.tile in order to # Register myself for mouse events over self.tile in order to
# create typical button/hyperlink visual effects. # create typical button/hyperlink visual effects.
eventManager.Register(self.setHover, EVT_ENTER_WINDOW, self.tile) em.eventManager.Register(self.setHover, wx.EVT_ENTER_WINDOW, self.tile)
eventManager.Register(self.setNormal, EVT_LEAVE_WINDOW, self.tile) em.eventManager.Register(self.setNormal, wx.EVT_LEAVE_WINDOW, self.tile)
eventManager.Register(self.setActive, EVT_LEFT_DOWN, self.tile) em.eventManager.Register(self.setActive, wx.EVT_LEFT_DOWN, self.tile)
eventManager.Register(self.setHover, EVT_LEFT_UP, self.tile) em.eventManager.Register(self.setHover, wx.EVT_LEFT_UP, self.tile)
def setHover(self, event): def setHover(self, event):
@@ -128,10 +138,10 @@ class Tile(wxPanel):
class InnerTile(wxPanel): class InnerTile(wxPanel):
IDLE_COLOR = wxColour( 80, 10, 10) IDLE_COLOR = wx.Colour( 80, 10, 10)
START_COLOR = wxColour(200, 70, 50) START_COLOR = wx.Colour(200, 70, 50)
FINAL_COLOR = wxColour( 20, 80,240) FINAL_COLOR = wx.Colour( 20, 80,240)
OFF_COLOR = wxColour(185,190,185) OFF_COLOR = wx.Colour(185,190,185)
# Some pre-computation. # Some pre-computation.
DELTAS = map(lambda a,b: b-a, START_COLOR.Get(), FINAL_COLOR.Get()) DELTAS = map(lambda a,b: b-a, START_COLOR.Get(), FINAL_COLOR.Get())
START_COLOR_TUPLE = START_COLOR.Get() START_COLOR_TUPLE = START_COLOR.Get()
@@ -141,7 +151,7 @@ class InnerTile(wxPanel):
events over the 'thingToWatch'. events over the 'thingToWatch'.
""" """
def __init__(self, parent, log, factor, thingToWatch=None, bgColor=None): def __init__(self, parent, log, factor, thingToWatch=None, bgColor=None):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.log=log self.log=log
if bgColor: if bgColor:
self.SetBackgroundColour(bgColor) self.SetBackgroundColour(bgColor)
@@ -151,16 +161,16 @@ class InnerTile(wxPanel):
self.state = 0 self.state = 0
self.toggleOnOff() self.toggleOnOff()
# Watch for the mouse click to enable/disable myself. # Watch for the mouse click to enable/disable myself.
eventManager.Register(self.toggleOnOff, EVT_LEFT_UP, self) em.eventManager.Register(self.toggleOnOff, wx.EVT_LEFT_UP, self)
def toggleOnOff(self, event=None): def toggleOnOff(self, event=None):
# Implement being on or off by registering and # Implement being on or off by registering and
# de-registering self.makeColor() from the event manager. # de-registering self.makeColor() from the event manager.
if self.state: if self.state:
eventManager.DeregisterListener(self.makeColor) em.eventManager.DeregisterListener(self.makeColor)
else: else:
eventManager.Register(self.makeColor, EVT_MOTION, self.thingToWatch) em.eventManager.Register(self.makeColor, wx.EVT_MOTION, self.thingToWatch)
self.state = 1 - self.state self.state = 1 - self.state
self.resetColor() self.resetColor()
@@ -188,7 +198,7 @@ class InnerTile(wxPanel):
r = InnerTile.START_COLOR_TUPLE[0] + (InnerTile.DELTAS[0] * percent) r = InnerTile.START_COLOR_TUPLE[0] + (InnerTile.DELTAS[0] * percent)
g = InnerTile.START_COLOR_TUPLE[1] + (InnerTile.DELTAS[1] * percent) g = InnerTile.START_COLOR_TUPLE[1] + (InnerTile.DELTAS[1] * percent)
b = InnerTile.START_COLOR_TUPLE[2] + (InnerTile.DELTAS[2] * percent) b = InnerTile.START_COLOR_TUPLE[2] + (InnerTile.DELTAS[2] * percent)
self.setColor(wxColour(int(r), int(g), int(b))) self.setColor(wx.Colour(int(r), int(g), int(b)))

View File

@@ -1,6 +1,21 @@
# 11/5/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated to wx namespace
#
# 11/25/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Issues previously noted have evaporated.
# o Hoo boy, the doc string in the lib needs fixed :-)
#
# 12/02/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Making the library's doc string acceptable for the overview rendered
# it unusable in the library's own test code, so I copied it over
# and massaged the XML into useful HTML.
#
from wxPython.wx import * import wx
from wxPython.lib import fancytext import wx.lib.fancytext as fancytext
#---------------------------------------------------------------------- #----------------------------------------------------------------------
@@ -11,14 +26,13 @@ test_str = ('<font style="italic" family="swiss" color="red" weight="bold" >'
test_str2 = '<font family="swiss" color="dark green" size="40">big green text</font>' test_str2 = '<font family="swiss" color="dark green" size="40">big green text</font>'
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent): def __init__(self, parent):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
EVT_PAINT(self, self.OnPaint) self.Bind(wx.EVT_PAINT, self.OnPaint)
def OnPaint(self, evt): def OnPaint(self, evt):
dc = wxPaintDC(self) dc = wx.PaintDC(self)
w, h = fancytext.GetExtent(test_str, dc) w, h = fancytext.GetExtent(test_str, dc)
fancytext.RenderToDC(test_str, dc, 20, 20) fancytext.RenderToDC(test_str, dc, 20, 20)
@@ -36,8 +50,43 @@ def runTest(frame, nb, log):
overview = fancytext.__doc__.replace("<", "&lt;") overview = \
"""
<html>
<body>
<h1>FancyText -- <i>methods for rendering XML specified text</i></h1>
<p>This module exports four main methods::
<pre>
def GetExtent(str, dc=None, enclose=True)
def GetFullExtent(str, dc=None, enclose=True)
def RenderToBitmap(str, background=None, enclose=True)
def RenderToDC(str, dc, x, y, enclose=True)
</pre>
In all cases, 'str' is an XML string. Note that start and end tags
are only required if *enclose* is set to False. In this case the
text should be wrapped in FancyText tags.
<p>In addition, the module exports one class::
<pre>
class StaticFancyText(self, window, id, text, background, ...)
</pre>
This class works similar to StaticText except it interprets its text
as FancyText.
<p>The text can support<sup>superscripts</sup> and <sub>subscripts</sub>, text
in different <font size="+3">sizes</font>, <font color="blue">colors</font>,
<i>styles</i>, <b>weights</b> and
<font family="script">families</font>. It also supports a limited set of symbols,
currently <times/>, <infinity/>, <angle/> as well as greek letters in both
upper case (<Alpha/><Beta/>...<Omega/>) and lower case (<alpha/><beta/>...<omega/>).
</font></font>
The End
</body>
</html>
"""

View File

@@ -1,27 +1,44 @@
# 11/7/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
# o Uncommented fbbhCallback in TestPanel.fbbh init. Appears to work fine.
# Wonder why it was commented.
# o Unrelated: TestPanel.dbb appears to cause a program error in the demo. If
# it is commented out, everything works fine. Investigating.
# o Bernhard has responded to query, does not plan on updating demo.
#
# 11/25/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o All issues, including the program error, have gone away in V2.5.
#
""" Demonstrate filebrowsebutton module of the wxPython.lib Library. """ Demonstrate filebrowsebutton module of the wxPython.lib Library.
14.1.2001 Bernhard Reiter <bernhard@intevation.de> 14.1.2001 Bernhard Reiter <bernhard@intevation.de>
Added demo for DirBrowseButton and improved overview text. Added demo for DirBrowseButton and improved overview text.
""" """
from wxPython.wx import *
from wxPython.lib.filebrowsebutton import FileBrowseButton, FileBrowseButtonWithHistory,DirBrowseButton
import wx
import wx.lib.filebrowsebutton as filebrowse
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, ID, log): def __init__(self, parent, ID, log):
wxPanel.__init__(self, parent, ID) wx.Panel.__init__(self, parent, ID)
self.log = log self.log = log
self.fbb = FileBrowseButton(self, -1, wxPoint(20,20), wxSize(450, -1),
changeCallback = self.fbbCallback)
self.fbbh = FileBrowseButtonWithHistory(self, -1, wxPoint(20, 50),
wxSize(450, -1),
#changeCallback = self.fbbhCallback
)
self.dbb = DirBrowseButton(self, -1, wxPoint(20,80), wxSize(450,-1),
changeCallback = self.dbbCallback)
self.fbb = filebrowse.FileBrowseButton(
self, -1, (20, 20), (450, -1), changeCallback = self.fbbCallback
)
self.fbbh = filebrowse.FileBrowseButtonWithHistory(
self, -1, (20, 50), (450, -1), changeCallback = self.fbbhCallback
)
self.dbb = filebrowse.DirBrowseButton(
self, -1, (20, 80), (450, -1), changeCallback = self.dbbCallback
)
self.fbbh.SetHistory(['You', 'can', 'put', 'some', 'file', 'names', 'here']) self.fbbh.SetHistory(['You', 'can', 'put', 'some', 'file', 'names', 'here'])
@@ -30,7 +47,6 @@ class TestPanel(wxPanel):
self.log.write('FileBrowseButton: %s\n' % evt.GetString()) self.log.write('FileBrowseButton: %s\n' % evt.GetString())
def fbbhCallback(self, evt): def fbbhCallback(self, evt):
if hasattr(self, 'fbbh'): if hasattr(self, 'fbbh'):
value = evt.GetString() value = evt.GetString()
@@ -39,11 +55,11 @@ class TestPanel(wxPanel):
history.append(value) history.append(value)
self.fbbh.SetHistory(history) self.fbbh.SetHistory(history)
def dbbCallback(self, evt): def dbbCallback(self, evt):
self.log.write('DirBrowseButton: %s\n' % evt.GetString()) self.log.write('DirBrowseButton: %s\n' % evt.GetString())
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def runTest(frame, nb, log): def runTest(frame, nb, log):
@@ -51,7 +67,6 @@ def runTest(frame, nb, log):
return win return win
#---------------------------------------------------------------------- #----------------------------------------------------------------------
overview = """<html><body> overview = """<html><body>
@@ -71,11 +86,10 @@ overview = """<html><body>
</pre></small> </pre></small>
</body><</html> </body><</html>
""" % ( FileBrowseButton.__doc__, """ % ( filebrowse.FileBrowseButton.__doc__,
FileBrowseButtonWithHistory.__doc__ , filebrowse.FileBrowseButtonWithHistory.__doc__ ,
str(DirBrowseButton.__doc__) ) filebrowse.DirBrowseButton.__doc__
)
if __name__ == '__main__': if __name__ == '__main__':

View File

@@ -1,8 +1,11 @@
# 11/25/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for V2.5
#
from wxPython.wx import * import wx
# Stuff to integrate FloatCanvas into wxPython Demo
## Stuff to integrate FloatCanvas into wxPython Demo
try: try:
import Numeric import Numeric
haveNumeric = True haveNumeric = True
@@ -17,8 +20,10 @@ You can get it at:
http://sourceforge.net/projects/numpy http://sourceforge.net/projects/numpy
""" """
def runTest(frame, nb, log): def runTest(frame, nb, log):
dlg = wxMessageDialog(frame, errorText, dlg = wx.MessageDialog(
'Sorry', wxOK | wxICON_INFORMATION) frame, errorText, 'Sorry', wx.OK | wx.ICON_INFORMATION
)
dlg.ShowModal() dlg.ShowModal()
dlg.Destroy() dlg.Destroy()
@@ -28,21 +33,22 @@ else:
from wxPython.lib import floatcanvas from wxPython.lib import floatcanvas
import wxPython.lib.colourdb import wxPython.lib.colourdb
ID_ABOUT_MENU = wxNewId() ID_ABOUT_MENU = wx.NewId()
ID_EXIT_MENU = wxNewId() ID_EXIT_MENU = wx.NewId()
ID_ZOOM_TO_FIT_MENU = wxNewId() ID_ZOOM_TO_FIT_MENU = wx.NewId()
ID_DRAWTEST_MENU = wxNewId() ID_DRAWTEST_MENU = wx.NewId()
ID_LINETEST_MENU = wxNewId() ID_LINETEST_MENU = wx.NewId()
ID_DRAWMAP_MENU = wxNewId() ID_DRAWMAP_MENU = wx.NewId()
ID_DRAWMAP2_MENU = wxNewId() ID_DRAWMAP2_MENU = wx.NewId()
ID_CLEAR_MENU = wxNewId() ID_CLEAR_MENU = wx.NewId()
colors = [] colors = []
LineStyles = floatcanvas.draw_object.LineStyleList.keys() LineStyles = floatcanvas.draw_object.LineStyleList.keys()
class DrawFrame(wxFrame): class DrawFrame(wx.Frame):
""" """
@@ -51,38 +57,37 @@ else:
""" """
def __init__(self, parent, id, title, position, size): def __init__(self, parent, id, title, position, size):
wxFrame.__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 = wxMenuBar() MenuBar = wx.MenuBar()
file_menu = wxMenu() file_menu = wx.Menu()
file_menu.Append(ID_EXIT_MENU, "&Close","Close this frame") file_menu.Append(ID_EXIT_MENU, "&Close","Close this frame")
EVT_MENU(self, ID_EXIT_MENU, self.OnQuit) self.Bind(wx.EVT_MENU, self.OnQuit, id=ID_EXIT_MENU)
MenuBar.Append(file_menu, "&File") MenuBar.Append(file_menu, "&File")
draw_menu = wxMenu() draw_menu = wx.Menu()
draw_menu.Append(ID_DRAWTEST_MENU, "&Draw Test","Run a test of drawing random components") draw_menu.Append(ID_DRAWTEST_MENU, "&Draw Test","Run a test of drawing random components")
EVT_MENU(self, ID_DRAWTEST_MENU,self.DrawTest) self.Bind(wx.EVT_MENU, self.DrawTest, id=ID_DRAWTEST_MENU)
draw_menu.Append(ID_LINETEST_MENU, "&Line Test","Run a test of drawing random lines") draw_menu.Append(ID_LINETEST_MENU, "&Line Test","Run a test of drawing random lines")
EVT_MENU(self, ID_LINETEST_MENU,self.LineTest) self.Bind(wx.EVT_MENU, self.LineTest, id=ID_LINETEST_MENU)
draw_menu.Append(ID_DRAWMAP_MENU, "Draw &Map","Run a test of drawing a map") draw_menu.Append(ID_DRAWMAP_MENU, "Draw &Map","Run a test of drawing a map")
EVT_MENU(self, ID_DRAWMAP_MENU,self.DrawMap) self.Bind(wx.EVT_MENU, self.DrawMap, id=ID_DRAWMAP_MENU)
draw_menu.Append(ID_CLEAR_MENU, "&Clear","Clear the Canvas") draw_menu.Append(ID_CLEAR_MENU, "&Clear","Clear the Canvas")
EVT_MENU(self, ID_CLEAR_MENU,self.Clear) self.Bind(wx.EVT_MENU, self.Clear, id=ID_CLEAR_MENU)
MenuBar.Append(draw_menu, "&Draw") MenuBar.Append(draw_menu, "&Draw")
view_menu = wx.Menu()
view_menu = wxMenu()
view_menu.Append(ID_ZOOM_TO_FIT_MENU, "Zoom to &Fit","Zoom to fit the window") view_menu.Append(ID_ZOOM_TO_FIT_MENU, "Zoom to &Fit","Zoom to fit the window")
EVT_MENU(self, ID_ZOOM_TO_FIT_MENU,self.ZoomToFit) self.Bind(wx.EVT_MENU, self.ZoomToFit, id=ID_ZOOM_TO_FIT_MENU)
MenuBar.Append(view_menu, "&View") MenuBar.Append(view_menu, "&View")
help_menu = wxMenu() help_menu = wx.Menu()
help_menu.Append(ID_ABOUT_MENU, "&About", help_menu.Append(ID_ABOUT_MENU, "&About",
"More information About this program") "More information About this program")
EVT_MENU(self, ID_ABOUT_MENU, self.OnAbout) self.Bind(wx.EVT_MENU, self.OnAbout, id=ID_ABOUT_MENU)
MenuBar.Append(help_menu, "&Help") MenuBar.Append(help_menu, "&Help")
self.SetMenuBar(MenuBar) self.SetMenuBar(MenuBar)
@@ -90,10 +95,10 @@ else:
self.CreateStatusBar() self.CreateStatusBar()
self.SetStatusText("") self.SetStatusText("")
EVT_CLOSE(self, self.OnCloseWindow) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
# Other event handlers: # Other event handlers:
EVT_RIGHT_DOWN(self, self.RightButtonEvent) self.Bind(wx.EVT_RIGHT_DOWN, self.RightButtonEvent)
# Add the Canvas # Add the Canvas
self.Canvas = floatcanvas.FloatCanvas(self,-1,(500,500), self.Canvas = floatcanvas.FloatCanvas(self,-1,(500,500),
@@ -115,20 +120,24 @@ else:
event.Skip() event.Skip()
def OnAbout(self, event): def OnAbout(self, event):
dlg = wxMessageDialog(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", wxOK | wxICON_INFORMATION) "About Me", wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal() dlg.ShowModal()
dlg.Destroy() dlg.Destroy()
def SetMode(self,event): def SetMode(self,event):
for id in [ID_ZOOM_IN_BUTTON,ID_ZOOM_OUT_BUTTON,ID_MOVE_MODE_BUTTON]: for id in [ID_ZOOM_IN_BUTTON,ID_ZOOM_OUT_BUTTON,ID_MOVE_MODE_BUTTON]:
self.ToolBar.ToggleTool(id,0) self.ToolBar.ToggleTool(id,0)
self.ToolBar.ToggleTool(event.GetId(),1) self.ToolBar.ToggleTool(event.GetId(),1)
if event.GetId() == ID_ZOOM_IN_BUTTON: if event.GetId() == ID_ZOOM_IN_BUTTON:
self.Canvas.SetGUIMode("ZoomIn") self.Canvas.SetGUIMode("ZoomIn")
elif event.GetId() == ID_ZOOM_OUT_BUTTON: elif event.GetId() == ID_ZOOM_OUT_BUTTON:
self.Canvas.SetGUIMode("ZoomOut") self.Canvas.SetGUIMode("ZoomOut")
elif event.GetId() == ID_MOVE_MODE_BUTTON: elif event.GetId() == ID_MOVE_MODE_BUTTON:
self.Canvas.SetGUIMode("Move") self.Canvas.SetGUIMode("Move")
@@ -147,15 +156,17 @@ else:
self.Destroy() self.Destroy()
def DrawTest(self,event): def DrawTest(self,event):
wxGetApp().Yield() wx.GetApp().Yield()
import random import random
import RandomArray import RandomArray
Range = (-10,10) Range = (-10,10)
Canvas = self.Canvas Canvas = self.Canvas
object_list = self.object_list object_list = self.object_list
## Random tests of everything: # Random tests of everything:
# Rectangles # Rectangles
for i in range(5): for i in range(5):
@@ -240,7 +251,7 @@ else:
self.Canvas.ZoomToBB() self.Canvas.ZoomToBB()
def DrawMap(self,event = None): def DrawMap(self,event = None):
wxGetApp().Yield() wx.GetApp().Yield()
import os, time import os, time
## Test of Actual Map Data ## Test of Actual Map Data
self.Clear() self.Clear()
@@ -285,7 +296,7 @@ else:
## print "It took %f seconds to draw %i lines"%(time.clock() - start,len(linepoints) ) ## print "It took %f seconds to draw %i lines"%(time.clock() - start,len(linepoints) )
def LineTest(self,event = None): def LineTest(self,event = None):
wxGetApp().Yield() wx.GetApp().Yield()
import os, time import os, time
import random import random
Range = (-10,10) Range = (-10,10)
@@ -310,7 +321,7 @@ else:
self.Canvas.ZoomToBB() self.Canvas.ZoomToBB()
print "It took %f seconds to draw %i lines"%(time.clock() - start,len(linepoints) ) print "It took %f seconds to draw %i lines"%(time.clock() - start,len(linepoints) )
class DemoApp(wxApp): class DemoApp(wx.App):
""" """
How the demo works: How the demo works:
@@ -450,6 +461,11 @@ if __name__ == "__main__":
print errorText print errorText
else: else:
app = DemoApp(0) app = DemoApp(0)
import wx.lib.colourdb
wx.lib.colourdb.updateColourDB()
colors = wx.lib.colourdb.getColourList()
app.MainLoop() app.MainLoop()

View File

@@ -1,39 +1,45 @@
# 11/25/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for V2.5
#
from wxPython.wx import * import wx
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
e = wxFontEnumerator() e = wx.FontEnumerator()
e.EnumerateFacenames() e.EnumerateFacenames()
list = e.GetFacenames() list = e.GetFacenames()
list.sort() list.sort()
s1 = wxStaticText(self, -1, "Face names:") s1 = wx.StaticText(self, -1, "Face names:")
self.lb1 = wxListBox(self, -1, wxDefaultPosition, (200, 250),
list, wxLB_SINGLE)
EVT_LISTBOX(self, self.lb1.GetId(), self.OnSelect)
self.txt = wxStaticText(self, -1, "Sample text...", (285, 50)) self.lb1 = wx.ListBox(self, -1, wx.DefaultPosition, (200, 250),
list, wx.LB_SINGLE)
row = wxBoxSizer(wxHORIZONTAL) self.Bind(wx.EVT_LISTBOX, self.OnSelect, id=self.lb1.GetId())
row.Add(s1, 0, wxALL, 5)
row.Add(self.lb1, 0, wxALL, 5)
row.Add(self.txt, 0, wxALL|wxADJUST_MINSIZE, 5)
sizer = wxBoxSizer(wxVERTICAL) self.txt = wx.StaticText(self, -1, "Sample text...", (285, 50))
sizer.Add(row, 0, wxALL, 30)
row = wx.BoxSizer(wx.HORIZONTAL)
row.Add(s1, 0, wx.ALL, 5)
row.Add(self.lb1, 0, wx.ALL, 5)
row.Add(self.txt, 0, wx.ALL|wx.ADJUST_MINSIZE, 5)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(row, 0, wx.ALL, 30)
self.SetSizer(sizer) self.SetSizer(sizer)
self.Layout() self.Layout()
self.lb1.SetSelection(0) self.lb1.SetSelection(0)
self.OnSelect(None) self.OnSelect(None)
wxFutureCall(300, self.SetTextSize) wx.FutureCall(300, self.SetTextSize)
def SetTextSize(self): def SetTextSize(self):
@@ -44,7 +50,7 @@ class TestPanel(wxPanel):
#print "OnSelect: " #print "OnSelect: "
face = self.lb1.GetStringSelection() face = self.lb1.GetStringSelection()
#print '\t '+face #print '\t '+face
font = wxFont(28, wxDEFAULT, wxNORMAL, wxNORMAL, False, face) font = wx.Font(28, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False, face)
#print "\t got font" #print "\t got font"
self.txt.SetLabel(face) self.txt.SetLabel(face)
#print "\t set label" #print "\t set label"
@@ -55,9 +61,9 @@ class TestPanel(wxPanel):
## st = font.GetNativeFontInfo().ToString() ## st = font.GetNativeFontInfo().ToString()
## ni2 = wxNativeFontInfo() ## ni2 = wx.NativeFontInfo()
## ni2.FromString(st) ## ni2.FromString(st)
## font2 = wxFontFromNativeInfo(ni2) ## font2 = wx.FontFromNativeInfo(ni2)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
@@ -69,11 +75,6 @@ def runTest(frame, nb, log):
overview = """<html><body> overview = """<html><body>
wxFontEnumerator enumerates either all available fonts on the system or only wxFontEnumerator enumerates either all available fonts on the system or only
the ones with given attributes - either only fixed-width (suited for use in the ones with given attributes - either only fixed-width (suited for use in

View File

@@ -1,104 +1,123 @@
# 11/6/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import * import wx
from wxPython.lib.buttons import * import wx.lib.buttons as buttons
import images import images
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wx.Panel):
class TestPanel(wxPanel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.log = log self.log = log
sizer = wxFlexGridSizer(1, 3, 20, 20) sizer = wx.FlexGridSizer(1, 3, 20, 20)
b = wxButton(self, -1, "A real button")
# A regular button, selected as the default button
b = wx.Button(self, -1, "A real button")
b.SetDefault() b.SetDefault()
EVT_BUTTON(self, b.GetId(), self.OnButton) self.Bind(wx.EVT_BUTTON, self.OnButton, id=b.GetId())
sizer.Add(b) sizer.Add(b)
b = wxButton(self, -1, "non-default") # Same thing, but NOT set as the default button
EVT_BUTTON(self, b.GetId(), self.OnButton) b = wx.Button(self, -1, "non-default")
self.Bind(wx.EVT_BUTTON, self.OnButton, id=b.GetId())
sizer.Add(b) sizer.Add(b)
sizer.Add((10,10)) sizer.Add((10,10))
b = wxGenButton(self, -1, 'Hello') # Plain old text button based off GenButton()
EVT_BUTTON(self, b.GetId(), self.OnButton) b = buttons.GenButton(self, -1, 'Hello')
self.Bind(wx.EVT_BUTTON, self.OnButton, id=b.GetId())
sizer.Add(b) sizer.Add(b)
b = wxGenButton(self, -1, 'disabled') # Plain old text button, disabled.
EVT_BUTTON(self, b.GetId(), self.OnButton) b = buttons.GenButton(self, -1, 'disabled')
self.Bind(wx.EVT_BUTTON, self.OnButton, id=b.GetId())
b.Enable(False) b.Enable(False)
sizer.Add(b) sizer.Add(b)
b = wxGenButton(self, -1, 'bigger') # This time, we let the botton be as big as it can be.
EVT_BUTTON(self, b.GetId(), self.OnBiggerButton) # Also, this one is fancier, with custom colors and bezel size.
b.SetFont(wxFont(20, wxSWISS, wxNORMAL, wxBOLD, False)) b = buttons.GenButton(self, -1, 'bigger')
self.Bind(wx.EVT_BUTTON, self.OnBiggerButton, id=b.GetId())
b.SetFont(wx.Font(20, wx.SWISS, wx.NORMAL, wx.BOLD, False))
b.SetBezelWidth(5) b.SetBezelWidth(5)
###b.SetBestSize() ###b.SetBestSize()
b.SetBackgroundColour("Navy") b.SetBackgroundColour("Navy")
b.SetForegroundColour(wxWHITE) b.SetForegroundColour(wx.WHITE)
b.SetToolTipString("This is a BIG button...") b.SetToolTipString("This is a BIG button...")
sizer.Add(b, flag=wxADJUST_MINSIZE) # let the sizer set best size # let the sizer set best size
sizer.Add(b, flag=wx.ADJUST_MINSIZE)
# An image button
bmp = images.getTest2Bitmap() bmp = images.getTest2Bitmap()
b = wxGenBitmapButton(self, -1, bmp) b = buttons.GenBitmapButton(self, -1, bmp)
EVT_BUTTON(self, b.GetId(), self.OnButton) self.Bind(wx.EVT_BUTTON, self.OnButton, id=b.GetId())
sizer.Add(b) sizer.Add(b)
# An image button, disabled.
bmp = images.getTest2Bitmap() bmp = images.getTest2Bitmap()
b = wxGenBitmapButton(self, -1, bmp) b = buttons.GenBitmapButton(self, -1, bmp)
EVT_BUTTON(self, b.GetId(), self.OnButton) self.Bind(wx.EVT_BUTTON, self.OnButton, id=b.GetId())
sizer.Add(b) sizer.Add(b)
b.Enable(False) b.Enable(False)
b = wxGenBitmapButton(self, -1, None) # An image button, using a mask to get rid of the
EVT_BUTTON(self, b.GetId(), self.OnButton) # undesireable part of the image
b = buttons.GenBitmapButton(self, -1, None)
self.Bind(wx.EVT_BUTTON, self.OnButton, id=b.GetId())
bmp = images.getBulb1Bitmap() bmp = images.getBulb1Bitmap()
mask = wxMaskColour(bmp, wxBLUE) mask = wx.MaskColour(bmp, wx.BLUE)
bmp.SetMask(mask) bmp.SetMask(mask)
b.SetBitmapLabel(bmp) b.SetBitmapLabel(bmp)
bmp = images.getBulb2Bitmap() bmp = images.getBulb2Bitmap()
mask = wxMaskColour(bmp, wxBLUE) mask = wx.MaskColour(bmp, wx.BLUE)
bmp.SetMask(mask) bmp.SetMask(mask)
b.SetBitmapSelected(bmp) b.SetBitmapSelected(bmp)
b.SetBestSize() b.SetBestSize()
sizer.Add(b) sizer.Add(b)
b = wxGenToggleButton(self, -1, "Toggle Button") # A toggle button
EVT_BUTTON(self, b.GetId(), self.OnToggleButton) b = buttons.GenToggleButton(self, -1, "Toggle Button")
self.Bind(wx.EVT_BUTTON, self.OnToggleButton, id=b.GetId())
sizer.Add(b) sizer.Add(b)
b = wxGenBitmapToggleButton(self, -1, None) # An image toggle button
EVT_BUTTON(self, b.GetId(), self.OnToggleButton) b = buttons.GenBitmapToggleButton(self, -1, None)
self.Bind(wx.EVT_BUTTON, self.OnToggleButton, id=b.GetId())
bmp = images.getBulb1Bitmap() bmp = images.getBulb1Bitmap()
mask = wxMaskColour(bmp, wxBLUE) mask = wx.MaskColour(bmp, wx.BLUE)
bmp.SetMask(mask) bmp.SetMask(mask)
b.SetBitmapLabel(bmp) b.SetBitmapLabel(bmp)
bmp = images.getBulb2Bitmap() bmp = images.getBulb2Bitmap()
mask = wxMaskColour(bmp, wxBLUE) mask = wx.MaskColour(bmp, wx.BLUE)
bmp.SetMask(mask) bmp.SetMask(mask)
b.SetBitmapSelected(bmp) b.SetBitmapSelected(bmp)
b.SetToggle(True) b.SetToggle(True)
b.SetBestSize() b.SetBestSize()
sizer.Add(b) sizer.Add(b)
b = wxGenBitmapTextButton(self, -1, None, "Bitmapped Text", size = (200, 45)) # A bitmap button with text.
EVT_BUTTON(self, b.GetId(), self.OnButton) b = buttons.GenBitmapTextButton(self, -1, None, "Bitmapped Text", size = (200, 45))
self.Bind(wx.EVT_BUTTON, self.OnButton, id=b.GetId())
bmp = images.getBulb1Bitmap() bmp = images.getBulb1Bitmap()
mask = wxMaskColour(bmp, wxBLUE) mask = wx.MaskColour(bmp, wx.BLUE)
bmp.SetMask(mask) bmp.SetMask(mask)
b.SetBitmapLabel(bmp) b.SetBitmapLabel(bmp)
bmp = images.getBulb2Bitmap() bmp = images.getBulb2Bitmap()
mask = wxMaskColour(bmp, wxBLUE) mask = wx.MaskColour(bmp, wx.BLUE)
bmp.SetMask(mask) bmp.SetMask(mask)
b.SetBitmapSelected(bmp) b.SetBitmapSelected(bmp)
b.SetUseFocusIndicator(False) b.SetUseFocusIndicator(False)
b.SetBestSize() b.SetBestSize()
sizer.Add(b) sizer.Add(b)
border = wxBoxSizer(wxVERTICAL) border = wx.BoxSizer(wx.VERTICAL)
border.Add(sizer, 0, wxALL, 25) border.Add(sizer, 0, wx.ALL, 25)
self.SetSizer(border) self.SetSizer(border)
@@ -131,10 +150,7 @@ def runTest(frame, nb, log):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
import wxPython.lib.buttons overview = buttons.__doc__
overview = wxPython.lib.buttons.__doc__
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os

View File

@@ -1,10 +1,15 @@
# 11/6/2003 - Jeff Grimmett (grimmtooth@softhome.net)
from wxPython.wx import * #
from wxPython.grid import * # Modified for wx namespace
#
import string import string
import wx
import wx.grid as gridlib
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class MyCellEditor(wxPyGridCellEditor): class MyCellEditor(gridlib.PyGridCellEditor):
""" """
This is a sample GridCellEditor that shows you how to make your own custom This is a sample GridCellEditor that shows you how to make your own custom
grid editors. All the methods that can be overridden are show here. The grid editors. All the methods that can be overridden are show here. The
@@ -23,18 +28,19 @@ class MyCellEditor(wxPyGridCellEditor):
def __init__(self, log): def __init__(self, log):
self.log = log self.log = log
self.log.write("MyCellEditor ctor\n") self.log.write("MyCellEditor ctor\n")
wxPyGridCellEditor.__init__(self) gridlib.PyGridCellEditor.__init__(self)
def Create(self, parent, id, evtHandler): def Create(self, parent, id, evtHandler):
""" """
Called to create the control, which must derive from wxControl. Called to create the control, which must derive from wx.Control.
*Must Override* *Must Override*
""" """
self.log.write("MyCellEditor: Create\n") self.log.write("MyCellEditor: Create\n")
self._tc = wxTextCtrl(parent, id, "") self._tc = wx.TextCtrl(parent, id, "")
self._tc.SetInsertionPoint(0) self._tc.SetInsertionPoint(0)
self.SetControl(self._tc) self.SetControl(self._tc)
if evtHandler: if evtHandler:
self._tc.PushEventHandler(evtHandler) self._tc.PushEventHandler(evtHandler)
@@ -47,7 +53,7 @@ class MyCellEditor(wxPyGridCellEditor):
""" """
self.log.write("MyCellEditor: SetSize %s\n" % rect) self.log.write("MyCellEditor: SetSize %s\n" % rect)
self._tc.SetDimensions(rect.x, rect.y, rect.width+2, rect.height+2, self._tc.SetDimensions(rect.x, rect.y, rect.width+2, rect.height+2,
wxSIZE_ALLOW_MINUS_ONE) wx.SIZE_ALLOW_MINUS_ONE)
def Show(self, show, attr): def Show(self, show, attr):
@@ -95,6 +101,7 @@ class MyCellEditor(wxPyGridCellEditor):
changed = False changed = False
val = self._tc.GetValue() val = self._tc.GetValue()
if val != self.startValue: if val != self.startValue:
changed = True changed = True
grid.GetTable().SetValue(row, col, val) # update the table grid.GetTable().SetValue(row, col, val) # update the table
@@ -126,7 +133,7 @@ class MyCellEditor(wxPyGridCellEditor):
##return self.base_IsAcceptedKey(evt) ##return self.base_IsAcceptedKey(evt)
return (not (evt.ControlDown() or evt.AltDown()) and return (not (evt.ControlDown() or evt.AltDown()) and
evt.GetKeyCode() != WXK_SHIFT) evt.GetKeyCode() != wx.WXK_SHIFT)
def StartingKey(self, evt): def StartingKey(self, evt):
@@ -137,9 +144,12 @@ class MyCellEditor(wxPyGridCellEditor):
self.log.write("MyCellEditor: StartingKey %d\n" % evt.GetKeyCode()) self.log.write("MyCellEditor: StartingKey %d\n" % evt.GetKeyCode())
key = evt.GetKeyCode() key = evt.GetKeyCode()
ch = None ch = None
if key in [WXK_NUMPAD0, WXK_NUMPAD1, WXK_NUMPAD2, WXK_NUMPAD3, WXK_NUMPAD4, if key in [ wx.WXK_NUMPAD0, wx.WXK_NUMPAD1, wx.WXK_NUMPAD2, wx.WXK_NUMPAD3,
WXK_NUMPAD5, WXK_NUMPAD6, WXK_NUMPAD7, WXK_NUMPAD8, WXK_NUMPAD9]: wx.WXK_NUMPAD4, wx.WXK_NUMPAD5, wx.WXK_NUMPAD6, wx.WXK_NUMPAD7,
ch = ch = chr(ord('0') + key - WXK_NUMPAD0) wx.WXK_NUMPAD8, wx.WXK_NUMPAD9
]:
ch = ch = chr(ord('0') + key - wx.WXK_NUMPAD0)
elif key < 256 and key >= 0 and chr(key) in string.printable: elif key < 256 and key >= 0 and chr(key) in string.printable:
ch = chr(key) ch = chr(key)
@@ -180,9 +190,9 @@ class MyCellEditor(wxPyGridCellEditor):
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class GridEditorTest(wxGrid): class GridEditorTest(gridlib.Grid):
def __init__(self, parent, log): def __init__(self, parent, log):
wxGrid.__init__(self, parent, -1) gridlib.Grid.__init__(self, parent, -1)
self.log = log self.log = log
self.CreateGrid(10, 3) self.CreateGrid(10, 3)
@@ -195,16 +205,17 @@ class GridEditorTest(wxGrid):
#self.SetDefaultEditor(MyCellEditor(self.log)) #self.SetDefaultEditor(MyCellEditor(self.log))
# Or we could just do it like this: # Or we could just do it like this:
#self.RegisterDataType(wxGRID_VALUE_STRING, #self.RegisterDataType(wx.GRID_VALUE_STRING,
# wxGridCellStringRenderer(), # wx.GridCellStringRenderer(),
# MyCellEditor(self.log)) # MyCellEditor(self.log))
# )
# but for this example, we'll just set the custom editor on one cell # but for this example, we'll just set the custom editor on one cell
self.SetCellEditor(1, 0, MyCellEditor(self.log)) self.SetCellEditor(1, 0, MyCellEditor(self.log))
self.SetCellValue(1, 0, "Try to edit this box") self.SetCellValue(1, 0, "Try to edit this box")
# and on a column # and on a column
attr = wxGridCellAttr() attr = gridlib.GridCellAttr()
attr.SetEditor(MyCellEditor(self.log)) attr.SetEditor(MyCellEditor(self.log))
self.SetColAttr(2, attr) self.SetColAttr(2, attr)
self.SetCellValue(1, 2, "or any in this column") self.SetCellValue(1, 2, "or any in this column")
@@ -216,9 +227,9 @@ class GridEditorTest(wxGrid):
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class TestFrame(wxFrame): class TestFrame(wx.Frame):
def __init__(self, parent, log): def __init__(self, parent, log):
wxFrame.__init__(self, parent, -1, "Custom Grid Cell Editor Test", wx.Frame.__init__(self, parent, -1, "Custom Grid Cell Editor Test",
size=(640,480)) size=(640,480))
grid = GridEditorTest(self, log) grid = GridEditorTest(self, log)
@@ -226,7 +237,7 @@ class TestFrame(wxFrame):
if __name__ == '__main__': if __name__ == '__main__':
import sys import sys
app = wxPySimpleApp() app = wx.PySimpleApp()
frame = TestFrame(None, sys.stdout) frame = TestFrame(None, sys.stdout)
frame.Show(True) frame.Show(True)
app.MainLoop() app.MainLoop()

View File

@@ -1,28 +1,32 @@
from wxPython.wx import * # 11/6/2003 - Jeff Grimmett (grimmtooth@softhome.net)
from wxPython.grid import * #
# o Updated for wx namespace
# o Also corrected minor bug where 'true' was being used instead of 'True'.
# Doesn't fail for * import (I guess that is still defined in wx), but does
# in the manner we're importing wx now.
import wx
import wx.grid as gridlib
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class CustomDataTable(wxPyGridTableBase): class CustomDataTable(gridlib.PyGridTableBase):
"""
"""
def __init__(self, log): def __init__(self, log):
wxPyGridTableBase.__init__(self) gridlib.PyGridTableBase.__init__(self)
self.log = log self.log = log
self.colLabels = ['ID', 'Description', 'Severity', 'Priority', 'Platform', self.colLabels = ['ID', 'Description', 'Severity', 'Priority', 'Platform',
'Opened?', 'Fixed?', 'Tested?', 'TestFloat'] 'Opened?', 'Fixed?', 'Tested?', 'TestFloat']
self.dataTypes = [wxGRID_VALUE_NUMBER, self.dataTypes = [gridlib.GRID_VALUE_NUMBER,
wxGRID_VALUE_STRING, gridlib.GRID_VALUE_STRING,
wxGRID_VALUE_CHOICE + ':only in a million years!,wish list,minor,normal,major,critical', gridlib.GRID_VALUE_CHOICE + ':only in a million years!,wish list,minor,normal,major,critical',
wxGRID_VALUE_NUMBER + ':1,5', gridlib.GRID_VALUE_NUMBER + ':1,5',
wxGRID_VALUE_CHOICE + ':all,MSW,GTK,other', gridlib.GRID_VALUE_CHOICE + ':all,MSW,GTK,other',
wxGRID_VALUE_BOOL, gridlib.GRID_VALUE_BOOL,
wxGRID_VALUE_BOOL, gridlib.GRID_VALUE_BOOL,
wxGRID_VALUE_BOOL, gridlib.GRID_VALUE_BOOL,
wxGRID_VALUE_FLOAT + ':6,2', gridlib.GRID_VALUE_FLOAT + ':6,2',
] ]
self.data = [ self.data = [
@@ -67,9 +71,10 @@ class CustomDataTable(wxPyGridTableBase):
self.SetValue(row, col, value) self.SetValue(row, col, value)
# tell the grid we've added a row # tell the grid we've added a row
msg = wxGridTableMessage(self, # The table msg = gridlib.GridTableMessage(self, # The table
wxGRIDTABLE_NOTIFY_ROWS_APPENDED, # what we did to it gridlib.GRIDTABLE_NOTIFY_ROWS_APPENDED, # what we did to it
1) # how many 1 # how many
)
self.GetView().ProcessTableMessage(msg) self.GetView().ProcessTableMessage(msg)
@@ -108,9 +113,9 @@ class CustomDataTable(wxPyGridTableBase):
class CustTableGrid(wxGrid): class CustTableGrid(gridlib.Grid):
def __init__(self, parent, log): def __init__(self, parent, log):
wxGrid.__init__(self, parent, -1) gridlib.Grid.__init__(self, parent, -1)
table = CustomDataTable(log) table = CustomDataTable(log)
@@ -123,8 +128,7 @@ class CustTableGrid(wxGrid):
self.SetMargins(0,0) self.SetMargins(0,0)
self.AutoSizeColumns(False) self.AutoSizeColumns(False)
EVT_GRID_CELL_LEFT_DCLICK(self, self.OnLeftDClick) gridlib.EVT_GRID_CELL_LEFT_DCLICK(self, self.OnLeftDClick)
# I do this because I don't like the default behaviour of not starting the # I do this because I don't like the default behaviour of not starting the
@@ -136,17 +140,21 @@ class CustTableGrid(wxGrid):
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class TestFrame(wxFrame): class TestFrame(wx.Frame):
def __init__(self, parent, log): def __init__(self, parent, log):
wxFrame.__init__(self, parent, -1, "Custom Table, data driven Grid Demo", size=(640,480))
p = wxPanel(self, -1, style=0) wx.Frame.__init__(
self, parent, -1, "Custom Table, data driven Grid Demo", size=(640,480)
)
p = wx.Panel(self, -1, style=0)
grid = CustTableGrid(p, log) grid = CustTableGrid(p, log)
b = wxButton(p, -1, "Another Control...") b = wx.Button(p, -1, "Another Control...")
b.SetDefault() b.SetDefault()
EVT_BUTTON(self, b.GetId(), self.OnButton) self.Bind(wx.EVT_BUTTON, self.OnButton, b)
EVT_SET_FOCUS(b, self.OnButtonFocus) b.Bind(wx.EVT_SET_FOCUS, self.OnButtonFocus)
bs = wxBoxSizer(wxVERTICAL) bs = wx.BoxSizer(wx.VERTICAL)
bs.Add(grid, 1, wxGROW|wxALL, 5) bs.Add(grid, 1, wx.GROW|wx.ALL, 5)
bs.Add(b) bs.Add(b)
p.SetSizer(bs) p.SetSizer(bs)
@@ -161,7 +169,7 @@ class TestFrame(wxFrame):
if __name__ == '__main__': if __name__ == '__main__':
import sys import sys
app = wxPySimpleApp() app = wx.PySimpleApp()
frame = TestFrame(None, sys.stdout) frame = TestFrame(None, sys.stdout)
frame.Show(True) frame.Show(True)
app.MainLoop() app.MainLoop()

View File

@@ -1,19 +1,24 @@
# 11/6/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
""" """
Example showing how to make a grid a drop target for files. Example showing how to make a grid a drop target for files.
""" """
from wxPython.wx import * import wx
from wxPython.grid import * import wx.grid as gridlib
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
# Set VIRTUAL to 1 to use a virtual grid # Set VIRTUAL to 1 to use a virtual grid
VIRTUAL = 1 VIRTUAL = 1
#---------------------------------------------------------------------------
class GridFileDropTarget(wxFileDropTarget): class GridFileDropTarget(wx.FileDropTarget):
def __init__(self, grid): def __init__(self, grid):
wxFileDropTarget.__init__(self) wx.FileDropTarget.__init__(self)
self.grid = grid self.grid = grid
def OnDropFiles(self, x, y, filenames): def OnDropFiles(self, x, y, filenames):
@@ -37,9 +42,9 @@ class GridFileDropTarget(wxFileDropTarget):
class FooTable(wxPyGridTableBase): class FooTable(gridlib.PyGridTableBase):
def __init__(self): def __init__(self):
wxPyGridTableBase.__init__(self) gridlib.PyGridTableBase.__init__(self)
self.dropTargets = {(0,0):"Drag", self.dropTargets = {(0,0):"Drag",
(1,0):"A", (1,0):"A",
(2,0):"File", (2,0):"File",
@@ -54,12 +59,12 @@ class FooTable(wxPyGridTableBase):
return self.dropTargets.get((row, col), "") return self.dropTargets.get((row, col), "")
class SimpleGrid(gridlib.Grid):
class SimpleGrid(wxGrid):
def __init__(self, parent, log): def __init__(self, parent, log):
wxGrid.__init__(self, parent, -1) gridlib.Grid.__init__(self, parent, -1)
self.log = log self.log = log
self.moveTo = None self.moveTo = None
if VIRTUAL: if VIRTUAL:
self.table = FooTable() self.table = FooTable()
self.SetTable(self.table) self.SetTable(self.table)
@@ -76,13 +81,12 @@ class SimpleGrid(wxGrid):
if VIRTUAL: if VIRTUAL:
self.table.dropTargets[row, col] = value self.table.dropTargets[row, col] = value
else: else:
wxGrid.SetCellValue(self, row, col, value) gridlib.Grid.SetCellValue(self, row, col, value)
class TestFrame(wx.Frame):
class TestFrame(wxFrame):
def __init__(self, parent, log): def __init__(self, parent, log):
wxFrame.__init__(self, parent, -1, "DragAndDrop Grid", size=(640,480)) wx.Frame.__init__(self, parent, -1, "DragAndDrop Grid", size=(640,480))
grid = SimpleGrid(self, log) grid = SimpleGrid(self, log)
@@ -91,7 +95,7 @@ class TestFrame(wxFrame):
if __name__ == '__main__': if __name__ == '__main__':
import sys import sys
app = wxPySimpleApp() app = wx.PySimpleApp()
frame = TestFrame(None, sys.stdout) frame = TestFrame(None, sys.stdout)
frame.Show(True) frame.Show(True)
app.MainLoop() app.MainLoop()

View File

@@ -1,16 +1,23 @@
from wxPython.wx import * # 11/6/2003 - Jeff Grimmett (grimmtooth@softhome.net)
from wxPython.grid import * #
from wxPython.lib.gridmovers import wxGridColMover, EVT_GRID_COL_MOVE # o Modified for V2.5
from wxPython.lib.gridmovers import wxGridRowMover, EVT_GRID_ROW_MOVE #
# 11/25/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o wx renamer didn't appear to 'catch' all the classes in
# wx.lib.gridmovers
# o Event binder not working properly with wx.lib.gridmovers
#
import wx
import wx.grid as gridlib
import wx.lib.gridmovers as gridmovers
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class CustomDataTable(wxPyGridTableBase): class CustomDataTable(gridlib.PyGridTableBase):
"""
"""
def __init__(self, log): def __init__(self, log):
wxPyGridTableBase.__init__(self) gridlib.PyGridTableBase.__init__(self)
self.log = log self.log = log
self.identifiers = ['id','ds','sv','pr','pl','op','fx','ts'] self.identifiers = ['id','ds','sv','pr','pl','op','fx','ts']
@@ -93,10 +100,12 @@ class CustomDataTable(wxPyGridTableBase):
# Move the column # Move the column
def MoveColumn(self,frm,to): def MoveColumn(self,frm,to):
grid = self.GetView() grid = self.GetView()
if grid: if grid:
# Move the identifiers # Move the identifiers
old = self.identifiers[frm] old = self.identifiers[frm]
del self.identifiers[frm] del self.identifiers[frm]
if to > frm: if to > frm:
self.identifiers.insert(to-1,old) self.identifiers.insert(to-1,old)
else: else:
@@ -104,23 +113,30 @@ class CustomDataTable(wxPyGridTableBase):
# Notify the grid # Notify the grid
grid.BeginBatch() grid.BeginBatch()
msg = wxGridTableMessage(self,wxGRIDTABLE_NOTIFY_COLS_DELETED, msg = gridlib.GridTableMessage(
frm,1) self, gridlib.GRIDTABLE_NOTIFY_COLS_DELETED, frm, 1
)
grid.ProcessTableMessage(msg) grid.ProcessTableMessage(msg)
msg = wxGridTableMessage(self,wxGRIDTABLE_NOTIFY_COLS_INSERTED,
to,1) msg = gridlib.GridTableMessage(
self, gridlib.GRIDTABLE_NOTIFY_COLS_INSERTED, to, 1
)
grid.ProcessTableMessage(msg) grid.ProcessTableMessage(msg)
grid.EndBatch() grid.EndBatch()
# Move the row # Move the row
def MoveRow(self,frm,to): def MoveRow(self,frm,to):
grid = self.GetView() grid = self.GetView()
if grid: if grid:
# Move the rowLabels and data rows # Move the rowLabels and data rows
oldLabel = self.rowLabels[frm] oldLabel = self.rowLabels[frm]
oldData = self.data[frm] oldData = self.data[frm]
del self.rowLabels[frm] del self.rowLabels[frm]
del self.data[frm] del self.data[frm]
if to > frm: if to > frm:
self.rowLabels.insert(to-1,oldLabel) self.rowLabels.insert(to-1,oldLabel)
self.data.insert(to-1,oldData) self.data.insert(to-1,oldData)
@@ -130,11 +146,17 @@ class CustomDataTable(wxPyGridTableBase):
# Notify the grid # Notify the grid
grid.BeginBatch() grid.BeginBatch()
msg = wxGridTableMessage(self,wxGRIDTABLE_NOTIFY_ROWS_DELETED,
frm,1) msg = gridlib.GridTableMessage(
self, gridlib.GRIDTABLE_NOTIFY_ROWS_DELETED, frm, 1
)
grid.ProcessTableMessage(msg) grid.ProcessTableMessage(msg)
msg = wxGridTableMessage(self,wxGRIDTABLE_NOTIFY_ROWS_INSERTED,
to,1) msg = gridlib.GridTableMessage(
self, gridlib.GRIDTABLE_NOTIFY_ROWS_INSERTED, to, 1
)
grid.ProcessTableMessage(msg) grid.ProcessTableMessage(msg)
grid.EndBatch() grid.EndBatch()
@@ -142,9 +164,9 @@ class CustomDataTable(wxPyGridTableBase):
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class DragableGrid(wxGrid): class DragableGrid(gridlib.Grid):
def __init__(self, parent, log): def __init__(self, parent, log):
wxGrid.__init__(self, parent, -1) gridlib.Grid.__init__(self, parent, -1)
table = CustomDataTable(log) table = CustomDataTable(log)
@@ -154,12 +176,16 @@ class DragableGrid(wxGrid):
self.SetTable(table, True) self.SetTable(table, True)
# Enable Column moving # Enable Column moving
wxGridColMover(self) #>> TODO - renamer didn't get this one
EVT_GRID_COL_MOVE(self,self.GetId(),self.OnColMove) gridmovers.wxGridColMover(self)
#>> TODO - Bind() not working here
gridmovers.EVT_GRID_COL_MOVE(self,self.GetId(),self.OnColMove)
# Enable Row moving # Enable Row moving
wxGridRowMover(self) #>> TODO - renamer didn't get this one
EVT_GRID_ROW_MOVE(self,self.GetId(),self.OnRowMove) gridmovers.wxGridRowMover(self)
#>> TODO - Bind() not working here
gridmovers.EVT_GRID_ROW_MOVE(self,self.GetId(),self.OnRowMove)
# Event method called when a column move needs to take place # Event method called when a column move needs to take place
def OnColMove(self,evt): def OnColMove(self,evt):
@@ -175,9 +201,9 @@ class DragableGrid(wxGrid):
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class TestFrame(wxFrame): class TestFrame(wx.Frame):
def __init__(self, parent, log): def __init__(self, parent, log):
wxFrame.__init__(self, parent, -1, "Custom Table, data driven Grid Demo", size=(640,480)) wx.Frame.__init__(self, parent, -1, "Custom Table, data driven Grid Demo", size=(640,480))
grid = DragableGrid(self, log) grid = DragableGrid(self, log)
@@ -185,7 +211,7 @@ class TestFrame(wxFrame):
if __name__ == '__main__': if __name__ == '__main__':
import sys import sys
app = wxPySimpleApp() app = wx.PySimpleApp()
frame = TestFrame(None, sys.stdout) frame = TestFrame(None, sys.stdout)
frame.Show(True) frame.Show(True)
app.MainLoop() app.MainLoop()

View File

@@ -1,11 +1,16 @@
from wxPython.wx import * # 11/6/2003 - Jeff Grimmett (grimmtooth@softhome.net)
from wxPython.grid import * #
# o Updated for wx namespace
#
import wx
import wx.grid as gridlib
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class NewEnterHandlingGrid(wxGrid): class NewEnterHandlingGrid(gridlib.Grid):
def __init__(self, parent, log): def __init__(self, parent, log):
wxGrid.__init__(self, parent, -1) gridlib.Grid.__init__(self, parent, -1)
self.log = log self.log = log
self.CreateGrid(20, 6) self.CreateGrid(20, 6)
@@ -15,11 +20,11 @@ class NewEnterHandlingGrid(wxGrid):
self.SetColSize(0, 150) self.SetColSize(0, 150)
self.SetColSize(5, 150) self.SetColSize(5, 150)
EVT_KEY_DOWN(self, self.OnKeyDown) self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
def OnKeyDown(self, evt): def OnKeyDown(self, evt):
if evt.KeyCode() != WXK_RETURN: if evt.KeyCode() != wx.WXK_RETURN:
evt.Skip() evt.Skip()
return return
@@ -29,8 +34,10 @@ class NewEnterHandlingGrid(wxGrid):
self.DisableCellEditControl() self.DisableCellEditControl()
success = self.MoveCursorRight(evt.ShiftDown()) success = self.MoveCursorRight(evt.ShiftDown())
if not success: if not success:
newRow = self.GetGridCursorRow() + 1 newRow = self.GetGridCursorRow() + 1
if newRow < self.GetTable().GetNumberRows(): if newRow < self.GetTable().GetNumberRows():
self.SetGridCursor(newRow, 0) self.SetGridCursor(newRow, 0)
self.MakeCellVisible(newRow, 0) self.MakeCellVisible(newRow, 0)
@@ -42,9 +49,9 @@ class NewEnterHandlingGrid(wxGrid):
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class TestFrame(wxFrame): class TestFrame(wx.Frame):
def __init__(self, parent, log): def __init__(self, parent, log):
wxFrame.__init__(self, parent, -1, "Simple Grid Demo", size=(640,480)) wx.Frame.__init__(self, parent, -1, "Simple Grid Demo", size=(640,480))
grid = NewEnterHandlingGrid(self, log) grid = NewEnterHandlingGrid(self, log)
@@ -53,7 +60,7 @@ class TestFrame(wxFrame):
if __name__ == '__main__': if __name__ == '__main__':
import sys import sys
app = wxPySimpleApp() app = wx.PySimpleApp()
frame = TestFrame(None, sys.stdout) frame = TestFrame(None, sys.stdout)
frame.Show(True) frame.Show(True)
app.MainLoop() app.MainLoop()

View File

@@ -1,9 +1,14 @@
from wxPython.wx import * # 11/6/2003 - Jeff Grimmett (grimmtooth@softhome.net)
from wxPython.grid import * #
# o Updated for wx namespace
#
import wx
import wx.grid as gridlib
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class HugeTable(wxPyGridTableBase): class HugeTable(gridlib.PyGridTableBase):
""" """
This is all it takes to make a custom data table to plug into a This is all it takes to make a custom data table to plug into a
@@ -13,7 +18,7 @@ class HugeTable(wxPyGridTableBase):
""" """
def __init__(self, log): def __init__(self, log):
wxPyGridTableBase.__init__(self) gridlib.PyGridTableBase.__init__(self)
self.log = log self.log = log
self.odd=wxGridCellAttr() self.odd=wxGridCellAttr()
@@ -46,9 +51,9 @@ class HugeTable(wxPyGridTableBase):
class HugeTableGrid(wxGrid): class HugeTableGrid(gridlib.Grid):
def __init__(self, parent, log): def __init__(self, parent, log):
wxGrid.__init__(self, parent, -1) gridlib.Grid.__init__(self, parent, -1)
table = HugeTable(log) table = HugeTable(log)
@@ -57,21 +62,18 @@ class HugeTableGrid(wxGrid):
# a reference to it and call it's Destroy method later. # a reference to it and call it's Destroy method later.
self.SetTable(table, True) self.SetTable(table, True)
EVT_GRID_CELL_RIGHT_CLICK(self, self.OnRightDown) #added self.Bind(gridlib.EVT_GRID_CELL_RIGHT_CLICK, self.OnRightDown)
def OnRightDown(self, event): #added def OnRightDown(self, event):
print "hello" print "hello"
print self.GetSelectedRows() #added print self.GetSelectedRows()
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class TestFrame(wxFrame): class TestFrame(wx.Frame):
def __init__(self, parent, log): def __init__(self, parent, log):
wxFrame.__init__(self, parent, -1, "Huge (virtual) Table Demo", size=(640,480)) wx.Frame.__init__(self, parent, -1, "Huge (virtual) Table Demo", size=(640,480))
grid = HugeTableGrid(self, log) grid = HugeTableGrid(self, log)
grid.SetReadOnly(5,5, True) grid.SetReadOnly(5,5, True)
@@ -80,7 +82,7 @@ class TestFrame(wxFrame):
if __name__ == '__main__': if __name__ == '__main__':
import sys import sys
app = wxPySimpleApp() app = wx.PySimpleApp()
frame = TestFrame(None, sys.stdout) frame = TestFrame(None, sys.stdout)
frame.Show(True) frame.Show(True)
app.MainLoop() app.MainLoop()

View File

@@ -1,17 +1,29 @@
from wxPython.wx import * # 11/6/2003 - Jeff Grimmett (grimmtooth@softhome.net)
from wxPython.grid import * #
from wxPython.lib.mixins.grid import wxGridAutoEditMixin # o Updated for V2.5
# o The mixin features were all commented out. Is it broke? Should it even
# be in the source? Or is it left as an exercise to the reader?
#
# 11/25/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Robin confirms, this is tutorial code. But be warned! It has not been
# converted OR tested!
#
import wx
import wx.grid as gridlib
#import wx.lib.mixins.grid as mixins
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class SimpleGrid(wxGrid): ##, wxGridAutoEditMixin): class SimpleGrid(gridlib.Grid): ##, mixins.GridAutoEditMixin):
def __init__(self, parent, log): def __init__(self, parent, log):
wxGrid.__init__(self, parent, -1) gridlib.Grid.__init__(self, parent, -1)
##wxGridAutoEditMixin.__init__(self) ##mixins.GridAutoEditMixin.__init__(self)
self.log = log self.log = log
self.moveTo = None self.moveTo = None
EVT_IDLE(self, self.OnIdle) self.Bind(wx.EVT_IDLE, self.OnIdle)
self.CreateGrid(25, 25) #, wxGrid.wxGridSelectRows) self.CreateGrid(25, 25) #, wxGrid.wxGridSelectRows)
##self.EnableEditing(False) ##self.EnableEditing(False)
@@ -23,16 +35,16 @@ class SimpleGrid(wxGrid): ##, wxGridAutoEditMixin):
self.SetCellValue(1, 1, "Another cell") self.SetCellValue(1, 1, "Another cell")
self.SetCellValue(2, 2, "Yet another cell") self.SetCellValue(2, 2, "Yet another cell")
self.SetCellValue(3, 3, "This cell is read-only") self.SetCellValue(3, 3, "This cell is read-only")
self.SetCellFont(0, 0, wxFont(12, wxROMAN, wxITALIC, wxNORMAL)) self.SetCellFont(0, 0, wx.Font(12, wx.ROMAN, wx.ITALIC, wx.NORMAL))
self.SetCellTextColour(1, 1, wxRED) self.SetCellTextColour(1, 1, wx.RED)
self.SetCellBackgroundColour(2, 2, wxCYAN) self.SetCellBackgroundColour(2, 2, wx.CYAN)
self.SetReadOnly(3, 3, True) self.SetReadOnly(3, 3, True)
self.SetCellEditor(5, 0, wxGridCellNumberEditor(1,1000)) self.SetCellEditor(5, 0, gridlib.GridCellNumberEditor(1,1000))
self.SetCellValue(5, 0, "123") self.SetCellValue(5, 0, "123")
self.SetCellEditor(6, 0, wxGridCellFloatEditor()) self.SetCellEditor(6, 0, gridlib.GridCellFloatEditor())
self.SetCellValue(6, 0, "123.34") self.SetCellValue(6, 0, "123.34")
self.SetCellEditor(7, 0, wxGridCellNumberEditor()) self.SetCellEditor(7, 0, gridlib.GridCellNumberEditor())
self.SetCellValue(6, 3, "You can veto editing this cell") self.SetCellValue(6, 3, "You can veto editing this cell")
@@ -41,10 +53,10 @@ class SimpleGrid(wxGrid): ##, wxGridAutoEditMixin):
# attribute objects let you keep a set of formatting values # attribute objects let you keep a set of formatting values
# in one spot, and reuse them if needed # in one spot, and reuse them if needed
attr = wxGridCellAttr() attr = gridlib.GridCellAttr()
attr.SetTextColour(wxBLACK) attr.SetTextColour(wx.BLACK)
attr.SetBackgroundColour(wxRED) attr.SetBackgroundColour(wx.RED)
attr.SetFont(wxFont(10, wxSWISS, wxNORMAL, wxBOLD)) attr.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD))
# 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)
@@ -53,7 +65,7 @@ class SimpleGrid(wxGrid): ##, wxGridAutoEditMixin):
self.SetColLabelValue(1, "column") self.SetColLabelValue(1, "column")
self.SetColLabelValue(2, "labels") self.SetColLabelValue(2, "labels")
self.SetColLabelAlignment(wxALIGN_LEFT, wxALIGN_BOTTOM) self.SetColLabelAlignment(wx.ALIGN_LEFT, wx.ALIGN_BOTTOM)
#self.SetDefaultCellOverflow(False) #self.SetDefaultCellOverflow(False)
#r = wxGridCellAutoWrapStringRenderer() #r = wxGridCellAutoWrapStringRenderer()
@@ -62,38 +74,37 @@ class SimpleGrid(wxGrid): ##, wxGridAutoEditMixin):
# overflow cells # overflow cells
self.SetCellValue( 9, 1, "This default cell will overflow into neighboring cells, but not if you turn overflow off."); self.SetCellValue( 9, 1, "This default cell will overflow into neighboring cells, but not if you turn overflow off.");
self.SetCellSize(11, 1, 3, 3); self.SetCellSize(11, 1, 3, 3);
self.SetCellAlignment(11, 1, wxALIGN_CENTRE, wxALIGN_CENTRE); self.SetCellAlignment(11, 1, wx.ALIGN_CENTRE, wx.ALIGN_CENTRE);
self.SetCellValue(11, 1, "This cell is set to span 3 rows and 3 columns"); self.SetCellValue(11, 1, "This cell is set to span 3 rows and 3 columns");
editor = wxGridCellTextEditor() editor = gridlib.GridCellTextEditor()
editor.SetParameters('10') editor.SetParameters('10')
self.SetCellEditor(0, 4, editor) self.SetCellEditor(0, 4, editor)
self.SetCellValue(0, 4, "Limited text") self.SetCellValue(0, 4, "Limited text")
# test all the events # test all the events
EVT_GRID_CELL_LEFT_CLICK(self, self.OnCellLeftClick) self.Bind(gridlib.EVT_GRID_CELL_LEFT_CLICK, self.OnCellLeftClick)
EVT_GRID_CELL_RIGHT_CLICK(self, self.OnCellRightClick) self.Bind(gridlib.EVT_GRID_CELL_RIGHT_CLICK, self.OnCellRightClick)
EVT_GRID_CELL_LEFT_DCLICK(self, self.OnCellLeftDClick) self.Bind(gridlib.EVT_GRID_CELL_LEFT_DCLICK, self.OnCellLeftDClick)
EVT_GRID_CELL_RIGHT_DCLICK(self, self.OnCellRightDClick) self.Bind(gridlib.EVT_GRID_CELL_RIGHT_DCLICK, self.OnCellRightDClick)
EVT_GRID_LABEL_LEFT_CLICK(self, self.OnLabelLeftClick) self.Bind(gridlib.EVT_GRID_LABEL_LEFT_CLICK, self.OnLabelLeftClick)
EVT_GRID_LABEL_RIGHT_CLICK(self, self.OnLabelRightClick) self.Bind(gridlib.EVT_GRID_LABEL_RIGHT_CLICK, self.OnLabelRightClick)
EVT_GRID_LABEL_LEFT_DCLICK(self, self.OnLabelLeftDClick) self.Bind(gridlib.EVT_GRID_LABEL_LEFT_DCLICK, self.OnLabelLeftDClick)
EVT_GRID_LABEL_RIGHT_DCLICK(self, self.OnLabelRightDClick) self.Bind(gridlib.EVT_GRID_LABEL_RIGHT_DCLICK, self.OnLabelRightDClick)
EVT_GRID_ROW_SIZE(self, self.OnRowSize) self.Bind(gridlib.EVT_GRID_ROW_SIZE, self.OnRowSize)
EVT_GRID_COL_SIZE(self, self.OnColSize) self.Bind(gridlib.EVT_GRID_COL_SIZE, self.OnColSize)
EVT_GRID_RANGE_SELECT(self, self.OnRangeSelect) self.Bind(gridlib.EVT_GRID_RANGE_SELECT, self.OnRangeSelect)
EVT_GRID_CELL_CHANGE(self, self.OnCellChange) self.Bind(gridlib.EVT_GRID_CELL_CHANGE, self.OnCellChange)
EVT_GRID_SELECT_CELL(self, self.OnSelectCell) self.Bind(gridlib.EVT_GRID_SELECT_CELL, self.OnSelectCell)
EVT_GRID_EDITOR_SHOWN(self, self.OnEditorShown)
EVT_GRID_EDITOR_HIDDEN(self, self.OnEditorHidden)
EVT_GRID_EDITOR_CREATED(self, self.OnEditorCreated)
self.Bind(gridlib.EVT_GRID_EDITOR_SHOWN, self.OnEditorShown)
self.Bind(gridlib.EVT_GRID_EDITOR_HIDDEN, self.OnEditorHidden)
self.Bind(gridlib.EVT_GRID_EDITOR_CREATED, self.OnEditorCreated)
def OnCellLeftClick(self, evt): def OnCellLeftClick(self, evt):
@@ -136,7 +147,6 @@ class SimpleGrid(wxGrid): ##, wxGridAutoEditMixin):
(evt.GetRow(), evt.GetCol(), evt.GetPosition())) (evt.GetRow(), evt.GetCol(), evt.GetPosition()))
evt.Skip() evt.Skip()
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()))
@@ -163,6 +173,7 @@ class SimpleGrid(wxGrid): ##, wxGridAutoEditMixin):
# won't have any effect. Instead, set coordinates to move to in # won't have any effect. Instead, set coordinates to move to in
# idle time. # idle time.
value = self.GetCellValue(evt.GetRow(), evt.GetCol()) value = self.GetCellValue(evt.GetRow(), evt.GetCol())
if value == 'no good': if value == 'no good':
self.moveTo = evt.GetRow(), evt.GetCol() self.moveTo = evt.GetRow(), evt.GetCol()
@@ -171,6 +182,7 @@ class SimpleGrid(wxGrid): ##, wxGridAutoEditMixin):
if self.moveTo != None: if self.moveTo != None:
self.SetGridCursor(self.moveTo[0], self.moveTo[1]) self.SetGridCursor(self.moveTo[0], self.moveTo[1])
self.moveTo = None self.moveTo = None
evt.Skip() evt.Skip()
@@ -181,19 +193,23 @@ class SimpleGrid(wxGrid): ##, wxGridAutoEditMixin):
# Another way to stay in a cell that has a bad value... # Another way to stay in a cell that has a bad value...
row = self.GetGridCursorRow() row = self.GetGridCursorRow()
col = self.GetGridCursorCol() col = self.GetGridCursorCol()
if self.IsCellEditControlEnabled(): if self.IsCellEditControlEnabled():
self.HideCellEditControl() self.HideCellEditControl()
self.DisableCellEditControl() self.DisableCellEditControl()
value = self.GetCellValue(row, col) value = self.GetCellValue(row, col)
if value == 'no good 2': if value == 'no good 2':
return # cancels the cell selection return # cancels the cell selection
evt.Skip() evt.Skip()
def OnEditorShown(self, evt): def OnEditorShown(self, evt):
if evt.GetRow() == 6 and evt.GetCol() == 3 and \ if evt.GetRow() == 6 and evt.GetCol() == 3 and \
wxMessageBox("Are you sure you wish to edit this cell?", wx.MessageBox("Are you sure you wish to edit this cell?",
"Checking", wxYES_NO) == wxNO: "Checking", wx.YES_NO) == wx.NO:
evt.Veto() evt.Veto()
return return
@@ -204,8 +220,8 @@ class SimpleGrid(wxGrid): ##, wxGridAutoEditMixin):
def OnEditorHidden(self, evt): def OnEditorHidden(self, evt):
if evt.GetRow() == 6 and evt.GetCol() == 3 and \ if evt.GetRow() == 6 and evt.GetCol() == 3 and \
wxMessageBox("Are you sure you wish to finish editing this cell?", wx.MessageBox("Are you sure you wish to finish editing this cell?",
"Checking", wxYES_NO) == wxNO: "Checking", wx.YES_NO) == wx.NO:
evt.Veto() evt.Veto()
return return
@@ -222,9 +238,9 @@ class SimpleGrid(wxGrid): ##, wxGridAutoEditMixin):
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class TestFrame(wxFrame): class TestFrame(wx.Frame):
def __init__(self, parent, log): def __init__(self, parent, log):
wxFrame.__init__(self, parent, -1, "Simple Grid Demo", size=(640,480)) wx.Frame.__init__(self, parent, -1, "Simple Grid Demo", size=(640,480))
grid = SimpleGrid(self, log) grid = SimpleGrid(self, log)
@@ -233,7 +249,7 @@ class TestFrame(wxFrame):
if __name__ == '__main__': if __name__ == '__main__':
import sys import sys
app = wxPySimpleApp() app = wx.PySimpleApp()
frame = TestFrame(None, sys.stdout) frame = TestFrame(None, sys.stdout)
frame.Show(True) frame.Show(True)
app.MainLoop() app.MainLoop()

View File

@@ -1,13 +1,19 @@
from wxPython.wx import * # 11/25/2003 - Jeff Grimmett (grimmtooth@softhome.net)
from wxPython.grid import * #
# o Updated for V2.5
# o There is one wx.Size() I haven't figured out how to get rid of yet.
#
import random import random
import wx
import wx.grid as gridlib
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class MyCustomRenderer(wxPyGridCellRenderer): class MyCustomRenderer(gridlib.PyGridCellRenderer):
def __init__(self): def __init__(self):
wxPyGridCellRenderer.__init__(self) gridlib.PyGridCellRenderer.__init__(self)
def Draw(self, grid, attr, dc, rect, row, col, isSelected): def Draw(self, grid, attr, dc, rect, row, col, isSelected):
dc.SetBackgroundMode(wxSOLID) dc.SetBackgroundMode(wxSOLID)
@@ -15,13 +21,14 @@ class MyCustomRenderer(wxPyGridCellRenderer):
dc.SetPen(wxTRANSPARENT_PEN) dc.SetPen(wxTRANSPARENT_PEN)
dc.DrawRectangleRect(rect) dc.DrawRectangleRect(rect)
dc.SetBackgroundMode(wxTRANSPARENT) dc.SetBackgroundMode(wx.TRANSPARENT)
dc.SetFont(attr.GetFont()) dc.SetFont(attr.GetFont())
text = grid.GetCellValue(row, col) text = grid.GetCellValue(row, col)
colors = ["RED", "WHITE", "SKY BLUE"] colors = ["RED", "WHITE", "SKY BLUE"]
x = rect.x + 1 x = rect.x + 1
y = rect.y + 1 y = rect.y + 1
for ch in text: for ch in text:
dc.SetTextForeground(random.choice(colors)) dc.SetTextForeground(random.choice(colors))
dc.DrawText(ch, (x, y)) dc.DrawText(ch, (x, y))
@@ -35,7 +42,7 @@ class MyCustomRenderer(wxPyGridCellRenderer):
text = grid.GetCellValue(row, col) text = grid.GetCellValue(row, col)
dc.SetFont(attr.GetFont()) dc.SetFont(attr.GetFont())
w, h = dc.GetTextExtent(text) w, h = dc.GetTextExtent(text)
return wxSize(w, h) return wx.Size(w, h)
def Clone(self): def Clone(self):
@@ -45,34 +52,33 @@ class MyCustomRenderer(wxPyGridCellRenderer):
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
rendererDemoData = [ rendererDemoData = [
('wxGridCellStringRenderer\n(the default)', 'this is a text value', wxGridCellStringRenderer, ()), ('GridCellStringRenderer\n(the default)', 'this is a text value', gridlib.GridCellStringRenderer, ()),
('wxGridCellNumberRenderer', '12345', wxGridCellNumberRenderer, ()), ('GridCellNumberRenderer', '12345', gridlib.GridCellNumberRenderer, ()),
('wxGridCellFloatRenderer', '1234.5678', wxGridCellFloatRenderer, (6,2)), ('GridCellFloatRenderer', '1234.5678', gridlib.GridCellFloatRenderer, (6,2)),
('wxGridCellBoolRenderer', '1', wxGridCellBoolRenderer, ()), ('GridCellBoolRenderer', '1', gridlib.GridCellBoolRenderer, ()),
('MyCustomRenderer', 'This is my renderer', MyCustomRenderer, ()), ('MyCustomRenderer', 'This is my renderer', MyCustomRenderer, ()),
] ]
editorDemoData = [ editorDemoData = [
('wxGridCellTextEditor\n(the default)', 'Here is some more text', wxGridCellTextEditor, ()), ('GridCellTextEditor\n(the default)', 'Here is some more text', gridlib.GridCellTextEditor, ()),
('wxGridCellNumberEditor\nwith min,max', '101', wxGridCellNumberEditor, (5, 10005)), ('GridCellNumberEditor\nwith min,max', '101', gridlib.GridCellNumberEditor, (5, 10005)),
('wxGridCellNumberEditor\nwithout bounds', '101', wxGridCellNumberEditor, ()), ('GridCellNumberEditor\nwithout bounds', '101', gridlib.GridCellNumberEditor, ()),
('wxGridCellFloatEditor', '1234.5678', wxGridCellFloatEditor, ()), ('GridCellFloatEditor', '1234.5678', gridlib.GridCellFloatEditor, ()),
('wxGridCellBoolEditor', '1', wxGridCellBoolEditor, ()), ('GridCellBoolEditor', '1', gridlib.GridCellBoolEditor, ()),
('wxGridCellChoiceEditor', 'one', wxGridCellChoiceEditor, (['one', 'two', 'three', 'four', ('GridCellChoiceEditor', 'one', gridlib.GridCellChoiceEditor, (['one', 'two', 'three', 'four',
'kick', 'Microsoft', 'out the', 'kick', 'Microsoft', 'out the',
'door'], False)), 'door'], False)),
] ]
comboDemoData = [ comboDemoData = [
('wxGridCellNumberRenderer\nwxGridCellNumberEditor', '20792', wxGridCellNumberRenderer, wxGridCellNumberEditor), ('GridCellNumberRenderer\nGridCellNumberEditor', '20792', gridlib.GridCellNumberRenderer, gridlib.GridCellNumberEditor),
('wxGridCellBoolRenderer\nwxGridCellBoolEditor', '1', wxGridCellBoolRenderer, wxGridCellBoolEditor), ('GridCellBoolRenderer\nGridCellBoolEditor', '1', gridlib.GridCellBoolRenderer, gridlib.GridCellBoolEditor),
] ]
class EditorsAndRenderersGrid(wxGrid): class EditorsAndRenderersGrid(gridlib.Grid):
def __init__(self, parent, log): def __init__(self, parent, log):
wxGrid.__init__(self, parent, -1) gridlib.Grid.__init__(self, parent, -1)
self.log = log self.log = log
self.CreateGrid(25, 8) self.CreateGrid(25, 8)
@@ -106,6 +112,7 @@ Renderers used together.
''') ''')
row = 2 row = 2
for label, value, renderClass, args in rendererDemoData: for label, value, renderClass, args in rendererDemoData:
renderer = renderClass(*args) renderer = renderClass(*args)
self.SetCellValue(row, renCol, label) self.SetCellValue(row, renCol, label)
@@ -115,6 +122,7 @@ Renderers used together.
row = 2 row = 2
for label, value, editorClass, args in editorDemoData: for label, value, editorClass, args in editorDemoData:
editor = editorClass(*args) editor = editorClass(*args)
self.SetCellValue(row, edCol, label) self.SetCellValue(row, edCol, label)
@@ -124,6 +132,7 @@ Renderers used together.
row = 18 row = 18
for label, value, renClass, edClass in comboDemoData: for label, value, renClass, edClass in comboDemoData:
self.SetCellValue(row, renCol, label) self.SetCellValue(row, renCol, label)
self.SetCellValue(row, renCol+1, value) self.SetCellValue(row, renCol+1, value)
@@ -133,14 +142,13 @@ Renderers used together.
self.SetCellRenderer(row, renCol+1, renderer) self.SetCellRenderer(row, renCol+1, renderer)
row = row + 2 row = row + 2
font = self.GetFont() font = self.GetFont()
font.SetWeight(wxBOLD) font.SetWeight(wx.BOLD)
attr = wxGridCellAttr() attr = gridlib.GridCellAttr()
attr.SetFont(font) attr.SetFont(font)
attr.SetBackgroundColour(wxLIGHT_GREY) attr.SetBackgroundColour(wx.LIGHT_GREY)
attr.SetReadOnly(True) attr.SetReadOnly(True)
attr.SetAlignment(wxRIGHT, -1) attr.SetAlignment(wx.RIGHT, -1)
self.SetColAttr(renCol, attr) self.SetColAttr(renCol, attr)
attr.IncRef() attr.IncRef()
self.SetColAttr(edCol, attr) self.SetColAttr(edCol, attr)
@@ -149,7 +157,7 @@ Renderers used together.
self.AutoSizeColumns(True) self.AutoSizeColumns(True)
self.AutoSizeRows(True) self.AutoSizeRows(True)
EVT_GRID_CELL_LEFT_DCLICK(self, self.OnLeftDClick) self.Bind(gridlib.EVT_GRID_CELL_LEFT_DCLICK, self.OnLeftDClick)
# I do this because I don't like the default behaviour of not starting the # I do this because I don't like the default behaviour of not starting the
@@ -161,9 +169,9 @@ Renderers used together.
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class TestFrame(wxFrame): class TestFrame(wx.Frame):
def __init__(self, parent, log): def __init__(self, parent, log):
wxFrame.__init__(self, parent, -1, "Editors and Renderers Demo", size=(640,480)) wx.Frame.__init__(self, parent, -1, "Editors and Renderers Demo", size=(640,480))
grid = EditorsAndRenderersGrid(self, log) grid = EditorsAndRenderersGrid(self, log)
@@ -172,7 +180,7 @@ class TestFrame(wxFrame):
if __name__ == '__main__': if __name__ == '__main__':
import sys import sys
app = wxPySimpleApp() app = wx.PySimpleApp()
frame = TestFrame(None, sys.stdout) frame = TestFrame(None, sys.stdout)
frame.Show(True) frame.Show(True)
app.MainLoop() app.MainLoop()

View File

@@ -8,40 +8,49 @@
# Date: Feb 26, 2001 # Date: Feb 26, 2001
# Licence: wxWindows license # Licence: wxWindows license
#---------------------------------------------------------------------------- #----------------------------------------------------------------------------
#
# 11/23/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
# 11/25/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Library has to be updated, it is using obsolete names
# (wxPyDefaultSize, etc)
#
from wxPython.wx import *
from wxPython.lib.imagebrowser import *
import os import os
import wx
import wx.lib.imagebrowser as ib
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
def runTest(frame, nb, log): def runTest(frame, nb, log):
dir = os.getcwd() # get working directory # get current working directory
initial_dir = os.path.join(dir, 'bitmaps') # set the initial directory for the demo bitmaps dir = os.getcwd()
win = ImageDialog(frame, initial_dir) # open the image browser dialog
# set the initial directory for the demo bitmaps
initial_dir = os.path.join(dir, 'bitmaps')
# open the image browser dialog
win = ib.ImageDialog(frame, initial_dir)
win.Centre() win.Centre()
if win.ShowModal() == wxID_OK:
log.WriteText("You Selected File: " + win.GetFile()) # show the selected file if win.ShowModal() == wx.ID_OK:
# show the selected file
log.WriteText("You Selected File: " + win.GetFile())
else: else:
log.WriteText("You pressed Cancel\n") log.WriteText("You pressed Cancel\n")
win.Destroy()
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
overview = """\ overview = """\
""" """
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run

View File

@@ -1,67 +1,179 @@
# 11/6/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
# o In the lambda function at the top, removed the leading 'wx' from the
# ID names to remove confusion with 'official' wx members.
#
from wxPython.wx import * import wx
from wxPython.lib.anchors import LayoutAnchors import wx.lib.anchors as anchors
#---------------------------------------------------------------------- #----------------------------------------------------------------------
# Nifty little trick here; apply wx.NewId() to generate a series of
# IDs used later on in the app.
[wxID_ANCHORSDEMOFRAMEANCHOREDPANEL, wxID_ANCHORSDEMOFRAMEHELPSTATICTEXT, [ ID_ANCHORSDEMOFRAMEANCHOREDPANEL,
wxID_ANCHORSDEMOFRAMEMAINPANEL, wxID_ANCHORSDEMOFRAMEBACKGROUNDPANEL, ID_ANCHORSDEMOFRAMEHELPSTATICTEXT,
wxID_ANCHORSDEMOFRAMERIGHTCHECKBOX, wxID_ANCHORSDEMOFRAMEOKBUTTON, ID_ANCHORSDEMOFRAMEMAINPANEL,
wxID_ANCHORSDEMOFRAMETOPCHECKBOX, wxID_ANCHORSDEMOFRAMEBOTTOMCHECKBOX, ID_ANCHORSDEMOFRAMEBACKGROUNDPANEL,
wxID_ANCHORSDEMOFRAME, wxID_ANCHORSDEMOFRAMELEFTCHECKBOX, ID_ANCHORSDEMOFRAMERIGHTCHECKBOX,
] = map(lambda _init_ctrls: wxNewId(), range(10)) ID_ANCHORSDEMOFRAMEOKBUTTON,
ID_ANCHORSDEMOFRAMETOPCHECKBOX,
ID_ANCHORSDEMOFRAMEBOTTOMCHECKBOX,
ID_ANCHORSDEMOFRAME,
ID_ANCHORSDEMOFRAMELEFTCHECKBOX,
] = map(lambda _init_ctrls: wx.NewId(), range(10))
class AnchorsDemoFrame(wxFrame): # A small note here: while only certain parts of this frame are actually demonstrating
# the capabilities of the LayoutAnchors feature, all the controls are within the same
# frame; therefore, all controls and windows within the frame must use LayoutAnchors.
# You can't mix LayoutAnchors and sizers.
class AnchorsDemoFrame(wx.Frame):
def _init_utils(self): def _init_utils(self):
pass pass
def _init_ctrls(self, prnt): def _init_ctrls(self, prnt):
wxFrame.__init__(self, size = wxSize(328, 187), id = wxID_ANCHORSDEMOFRAME, title = 'LayoutAnchors Demonstration', parent = prnt, name = 'AnchorsDemoFrame', style = wxDEFAULT_FRAME_STYLE | wxCLIP_CHILDREN, pos = wxPoint(261, 123)) wx.Frame.__init__(
self, size=(328, 187), id=ID_ANCHORSDEMOFRAME,
title='LayoutAnchors Demonstration', parent=prnt,
name='AnchorsDemoFrame',
style = wx.DEFAULT_FRAME_STYLE | wx.CLIP_CHILDREN, pos=(261, 123)
)
self._init_utils() self._init_utils()
self.mainPanel = wxPanel(size = wxSize(320, 160), parent = self, id = wxID_ANCHORSDEMOFRAMEMAINPANEL, name = 'panel1', style = wxTAB_TRAVERSAL | wxCLIP_CHILDREN, pos = wxPoint(0, 0)) self.mainPanel = wx.Panel(
size=(320, 160), parent=self,
id=ID_ANCHORSDEMOFRAMEMAINPANEL, name='panel1',
style=wx.TAB_TRAVERSAL | wx.CLIP_CHILDREN,
pos=(0, 0)
)
self.mainPanel.SetAutoLayout(True) self.mainPanel.SetAutoLayout(True)
self.okButton = wxButton(label = 'OK', id = wxID_ANCHORSDEMOFRAMEOKBUTTON, parent = self.mainPanel, name = 'okButton', size = wxSize(72, 24), style = 0, pos = wxPoint(240, 128)) self.okButton = wx.Button(
self.okButton.SetConstraints(LayoutAnchors(self.okButton, False, False, True, True)) label='OK', id=ID_ANCHORSDEMOFRAMEOKBUTTON,
EVT_BUTTON(self.okButton, wxID_ANCHORSDEMOFRAMEOKBUTTON, self.OnOkButtonButton) parent=self.mainPanel, name='okButton',
size=(72, 24), style=0, pos=(240, 128)
)
self.backgroundPanel = wxPanel(size = wxSize(304, 80), parent = self.mainPanel, id = wxID_ANCHORSDEMOFRAMEBACKGROUNDPANEL, name = 'backgroundPanel', style = wxSIMPLE_BORDER | wxCLIP_CHILDREN, pos = wxPoint(8, 40)) self.okButton.SetConstraints(
self.backgroundPanel.SetBackgroundColour(wxColour(255, 255, 255)) anchors.LayoutAnchors(self.okButton, False, False, True, True)
self.backgroundPanel.SetConstraints(LayoutAnchors(self.backgroundPanel, True, True, True, True)) )
self.anchoredPanel = wxPanel(size = wxSize(88, 48), id = wxID_ANCHORSDEMOFRAMEANCHOREDPANEL, parent = self.backgroundPanel, name = 'anchoredPanel', style = wxSIMPLE_BORDER, pos = wxPoint(104, 16)) self.Bind(
self.anchoredPanel.SetBackgroundColour(wxColour(0, 0, 222)) wx.EVT_BUTTON, self.OnOkButtonButton, id=ID_ANCHORSDEMOFRAMEOKBUTTON
self.anchoredPanel.SetConstraints(LayoutAnchors(self.anchoredPanel, False, False, False, False)) )
self.leftCheckBox = wxCheckBox(label = 'Left', id = wxID_ANCHORSDEMOFRAMELEFTCHECKBOX, parent = self.mainPanel, name = 'leftCheckBox', size = wxSize(40, 16), style = 0, pos = wxPoint(8, 8)) self.backgroundPanel = wx.Panel(
self.leftCheckBox.SetConstraints(LayoutAnchors(self.leftCheckBox, False, True, False, False)) size=(304, 80), parent=self.mainPanel,
EVT_CHECKBOX(self.leftCheckBox, wxID_ANCHORSDEMOFRAMELEFTCHECKBOX, self.OnCheckboxCheckbox) id=ID_ANCHORSDEMOFRAMEBACKGROUNDPANEL,
name='backgroundPanel',
style=wx.SIMPLE_BORDER | wx.CLIP_CHILDREN,
pos = (8, 40)
)
self.topCheckBox = wxCheckBox(label = 'Top', id = wxID_ANCHORSDEMOFRAMETOPCHECKBOX, parent = self.mainPanel, name = 'topCheckBox', size = wxSize(40, 16), style = 0, pos = wxPoint(88, 8)) self.backgroundPanel.SetBackgroundColour(wx.Colour(255, 255, 255))
self.topCheckBox.SetConstraints(LayoutAnchors(self.topCheckBox, False, True, False, False)) self.backgroundPanel.SetConstraints(
EVT_CHECKBOX(self.topCheckBox, wxID_ANCHORSDEMOFRAMETOPCHECKBOX, self.OnCheckboxCheckbox) anchors.LayoutAnchors(self.backgroundPanel, True, True, True, True)
)
self.rightCheckBox = wxCheckBox(label = 'Right', id = wxID_ANCHORSDEMOFRAMERIGHTCHECKBOX, parent = self.mainPanel, name = 'rightCheckBox', size = wxSize(48, 16), style = 0, pos = wxPoint(168, 8)) self.anchoredPanel = wx.Panel(
self.rightCheckBox.SetConstraints(LayoutAnchors(self.rightCheckBox, False, True, False, False)) size=(88, 48), id=ID_ANCHORSDEMOFRAMEANCHOREDPANEL,
EVT_CHECKBOX(self.rightCheckBox, wxID_ANCHORSDEMOFRAMERIGHTCHECKBOX, self.OnCheckboxCheckbox) parent=self.backgroundPanel, name='anchoredPanel',
style=wx.SIMPLE_BORDER, pos=(104, 16)
)
self.bottomCheckBox = wxCheckBox(label = 'Bottom', id = wxID_ANCHORSDEMOFRAMEBOTTOMCHECKBOX, parent = self.mainPanel, name = 'bottomCheckBox', size = wxSize(56, 16), style = 0, pos = wxPoint(248, 8)) self.anchoredPanel.SetBackgroundColour(wx.Colour(0, 0, 222))
self.bottomCheckBox.SetConstraints(LayoutAnchors(self.bottomCheckBox, False, True, False, False)) self.anchoredPanel.SetConstraints(
EVT_CHECKBOX(self.bottomCheckBox, wxID_ANCHORSDEMOFRAMEBOTTOMCHECKBOX, self.OnCheckboxCheckbox) anchors.LayoutAnchors(self.anchoredPanel, False, False, False, False)
)
self.helpStaticText = wxStaticText(label = 'Select anchor options above, then resize window to see the effect', id = wxID_ANCHORSDEMOFRAMEHELPSTATICTEXT, parent = self.mainPanel, name = 'helpStaticText', size = wxSize(224, 24), style = wxST_NO_AUTORESIZE, pos = wxPoint(8, 128)) self.leftCheckBox = wx.CheckBox(
self.helpStaticText.SetConstraints(LayoutAnchors(self.helpStaticText, True, False, True, True)) label='Left', id=ID_ANCHORSDEMOFRAMELEFTCHECKBOX,
parent=self.mainPanel, name='leftCheckBox',
size=(40, 16), style=0, pos=(8, 8)
)
self.leftCheckBox.SetConstraints(
anchors.LayoutAnchors(self.leftCheckBox, False, True, False, False)
)
self.Bind(
wx.EVT_CHECKBOX, self.OnCheckboxCheckbox, source=self.leftCheckBox,
id=ID_ANCHORSDEMOFRAMELEFTCHECKBOX
)
self.topCheckBox = wx.CheckBox(
label='Top', id=ID_ANCHORSDEMOFRAMETOPCHECKBOX,
parent=self.mainPanel, name='topCheckBox',
size=(40, 16), style=0, pos=(88, 8)
)
self.topCheckBox.SetConstraints(
anchors.LayoutAnchors(self.topCheckBox, False, True, False, False)
)
self.Bind(
wx.EVT_CHECKBOX, self.OnCheckboxCheckbox, source=self.topCheckBox,
id=ID_ANCHORSDEMOFRAMETOPCHECKBOX
)
self.rightCheckBox = wx.CheckBox(
label='Right', id=ID_ANCHORSDEMOFRAMERIGHTCHECKBOX,
parent=self.mainPanel, name='rightCheckBox',
size=(48, 16), style=0, pos=(168, 8)
)
self.rightCheckBox.SetConstraints(
anchors.LayoutAnchors(self.rightCheckBox, False, True, False, False)
)
self.Bind(
wx.EVT_CHECKBOX, self.OnCheckboxCheckbox, source=self.rightCheckBox,
id=ID_ANCHORSDEMOFRAMERIGHTCHECKBOX
)
self.bottomCheckBox = wx.CheckBox(
label='Bottom', id=ID_ANCHORSDEMOFRAMEBOTTOMCHECKBOX,
parent=self.mainPanel, name='bottomCheckBox',
size=(56, 16), style=0, pos=(248, 8)
)
self.bottomCheckBox.SetConstraints(
anchors.LayoutAnchors(self.bottomCheckBox, False, True, False, False)
)
self.Bind(
wx.EVT_CHECKBOX, self.OnCheckboxCheckbox, source=self.bottomCheckBox,
id=ID_ANCHORSDEMOFRAMEBOTTOMCHECKBOX
)
self.helpStaticText = wx.StaticText(
label='Select anchor options above, then resize window to see the effect',
id=ID_ANCHORSDEMOFRAMEHELPSTATICTEXT,
parent=self.mainPanel, name='helpStaticText',
size=(224, 24), style=wx.ST_NO_AUTORESIZE,
pos=(8, 128)
)
self.helpStaticText.SetConstraints(
anchors.LayoutAnchors(self.helpStaticText, True, False, True, True)
)
def __init__(self, parent): def __init__(self, parent):
self._init_ctrls(parent) self._init_ctrls(parent)
# Based on the values of the above checkboxes, we will adjust the layout constraints
# on the sample window whenever one of the checkboxes changes state.
def OnCheckboxCheckbox(self, event): def OnCheckboxCheckbox(self, event):
self.anchoredPanel.SetConstraints( self.anchoredPanel.SetConstraints(
LayoutAnchors(self.anchoredPanel, anchors.LayoutAnchors(self.anchoredPanel,
self.leftCheckBox.GetValue(), self.topCheckBox.GetValue(), self.leftCheckBox.GetValue(), self.topCheckBox.GetValue(),
self.rightCheckBox.GetValue(), self.bottomCheckBox.GetValue()) ) self.rightCheckBox.GetValue(), self.bottomCheckBox.GetValue()
)
)
def OnOkButtonButton(self, event): def OnOkButtonButton(self, event):
self.Close() self.Close()
@@ -79,8 +191,6 @@ def runTest(frame, nb, log):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
overview = """<html><body> overview = """<html><body>
<h2>LayoutAnchors</h2> <h2>LayoutAnchors</h2>
A class that implements Delphi's Anchors with wxLayoutConstraints. A class that implements Delphi's Anchors with wxLayoutConstraints.
@@ -132,10 +242,6 @@ overview = """<html><body>
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run

View File

@@ -1,45 +1,62 @@
# 11/12/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
# o Controls now use dynamic IDs instead of hardcoded IDs.
#
from wxPython.wx import * import wx
from wxPython.lib.layoutf import Layoutf import wx.lib.layoutf as layoutf
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class TestLayoutf(wxPanel): ID_Button = wx.NewId()
#---------------------------------------------------------------------------
class TestLayoutf(wx.Panel):
def __init__(self, parent): def __init__(self, parent):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.SetAutoLayout(True) self.SetAutoLayout(True)
EVT_BUTTON(self, 100, self.OnButton) self.Bind(EVT_BUTTON, self.OnButton, id=ID_Button)
self.panelA = wxWindow(self, -1, style=wxSIMPLE_BORDER) self.panelA = wx.Window(self, -1, style=wx.SIMPLE_BORDER)
self.panelA.SetBackgroundColour(wxBLUE) self.panelA.SetBackgroundColour(wx.BLUE)
self.panelA.SetConstraints(Layoutf('t=t10#1;l=l10#1;b=b10#1;r%r50#1',(self,))) self.panelA.SetConstraints(
layoutf.Layoutf('t=t10#1;l=l10#1;b=b10#1;r%r50#1',(self,))
)
self.panelB = wxWindow(self, -1, style=wxSIMPLE_BORDER) self.panelB = wx.Window(self, -1, style=wx.SIMPLE_BORDER)
self.panelB.SetBackgroundColour(wxRED) self.panelB.SetBackgroundColour(wx.RED)
self.panelB.SetConstraints(Layoutf('t=t10#1;r=r10#1;b%b30#1;l>10#2', (self,self.panelA))) self.panelB.SetConstraints(
layoutf.Layoutf('t=t10#1;r=r10#1;b%b30#1;l>10#2', (self,self.panelA))
)
self.panelC = wxWindow(self, -1, style=wxSIMPLE_BORDER) self.panelC = wx.Window(self, -1, style=wx.SIMPLE_BORDER)
self.panelC.SetBackgroundColour(wxWHITE) self.panelC.SetBackgroundColour(wx.WHITE)
self.panelC.SetConstraints(Layoutf('t_10#3;r=r10#1;b=b10#1;l>10#2', (self,self.panelA,self.panelB))) self.panelC.SetConstraints(
layoutf.Layoutf('t_10#3;r=r10#1;b=b10#1;l>10#2', (self,self.panelA,self.panelB))
)
b = wxButton(self.panelA, 100, ' Panel A ') b = wx.Button(self.panelA, ID_Button, ' Panel A ')
b.SetConstraints(Layoutf('X=X#1;Y=Y#1;h*;w%w50#1', (self.panelA,))) b.SetConstraints(layoutf.Layoutf('X=X#1;Y=Y#1;h*;w%w50#1', (self.panelA,)))
b = wxButton(self.panelB, 100, ' Panel B ') b = wx.Button(self.panelB, ID_Button, ' Panel B ')
b.SetConstraints(Layoutf('t=t2#1;r=r4#1;h*;w*', (self.panelB,))) b.SetConstraints(layoutf.Layoutf('t=t2#1;r=r4#1;h*;w*', (self.panelB,)))
self.panelD = wxWindow(self.panelC, -1, style=wxSIMPLE_BORDER) self.panelD = wx.Window(self.panelC, -1, style=wx.SIMPLE_BORDER)
self.panelD.SetBackgroundColour(wxGREEN) self.panelD.SetBackgroundColour(wx.GREEN)
self.panelD.SetConstraints(Layoutf('b%h50#1;r%w50#1;h=h#2;w=w#2', (self.panelC, b))) self.panelD.SetConstraints(
layoutf.Layoutf('b%h50#1;r%w50#1;h=h#2;w=w#2', (self.panelC, b))
)
b = wxButton(self.panelC, 100, ' Panel C ') b = wx.Button(self.panelC, ID_Button, ' Panel C ')
b.SetConstraints(Layoutf('t_#1;l>#1;h*;w*', (self.panelD,))) b.SetConstraints(layoutf.Layoutf('t_#1;l>#1;h*;w*', (self.panelD,)))
wxStaticText(self.panelD, -1, "Panel D", wxPoint(4, 4)).SetBackgroundColour(wxGREEN) wx.StaticText(self.panelD, -1, "Panel D", (4, 4)).SetBackgroundColour(wx.GREEN)
def OnButton(self, event): def OnButton(self, event):
wxBell() wx.Bell()
@@ -51,18 +68,7 @@ def runTest(frame, nb, log):
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
overview = layoutf.Layoutf.__doc__
overview = Layoutf.__doc__
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os

View File

@@ -1,35 +1,49 @@
#!/usr/bin/env python #!/usr/bin/env python
from wxPython.wx import * # 11/12/2003 - Jeff Grimmett (grimmtooth@softhome.net)
from wxScrolledWindow import MyCanvas #
# o Updated for wx namespace
# o Replaced hardcoded menu IDs with dynamic IDs
#
import wx
# Importing wxScrolledWindow demo to make use of the MyCanvas
# class defined within.
import wxScrolledWindow
import images import images
SHOW_BACKGROUND = 1 SHOW_BACKGROUND = 1
#----------------------------------------------------------------------
ID_New = wx.NewId()
ID_Exit = wx.NewId()
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class MyParentFrame(wxMDIParentFrame): class MyParentFrame(wx.MDIParentFrame):
def __init__(self): def __init__(self):
wxMDIParentFrame.__init__(self, None, -1, "MDI Parent", size=(600,400)) wx.MDIParentFrame.__init__(self, None, -1, "MDI Parent", size=(600,400))
self.winCount = 0 self.winCount = 0
menu = wxMenu() menu = wx.Menu()
menu.Append(5000, "&New Window") menu.Append(ID_New, "&New Window")
menu.AppendSeparator() menu.AppendSeparator()
menu.Append(5001, "E&xit") menu.Append(ID_Exit, "E&xit")
menubar = wxMenuBar() menubar = wx.MenuBar()
menubar.Append(menu, "&File") menubar.Append(menu, "&File")
self.SetMenuBar(menubar) self.SetMenuBar(menubar)
self.CreateStatusBar() self.CreateStatusBar()
EVT_MENU(self, 5000, self.OnNewWindow) self.Bind(wx.EVT_MENU, self.OnNewWindow, id=ID_New)
EVT_MENU(self, 5001, self.OnExit) self.Bind(wx.EVT_MENU, self.OnExit, id=ID_Exit)
if SHOW_BACKGROUND: if SHOW_BACKGROUND:
self.bg_bmp = images.getGridBGBitmap() self.bg_bmp = images.getGridBGBitmap()
EVT_ERASE_BACKGROUND(self.GetClientWindow(), self.OnEraseBackground) self.GetClientWindow().Bind(
wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground
)
def OnExit(self, evt): def OnExit(self, evt):
@@ -38,42 +52,46 @@ class MyParentFrame(wxMDIParentFrame):
def OnNewWindow(self, evt): def OnNewWindow(self, evt):
self.winCount = self.winCount + 1 self.winCount = self.winCount + 1
win = wxMDIChildFrame(self, -1, "Child Window: %d" % self.winCount) win = wx.MDIChildFrame(self, -1, "Child Window: %d" % self.winCount)
canvas = MyCanvas(win) canvas = wxScrolledWindow.MyCanvas(win)
win.Show(True) win.Show(True)
def OnEraseBackground(self, evt): def OnEraseBackground(self, evt):
dc = evt.GetDC() dc = evt.GetDC()
if not dc: if not dc:
dc = wxClientDC(self.GetClientWindow()) dc = wx.ClientDC(self.GetClientWindow())
# tile the background bitmap # tile the background bitmap
sz = self.GetClientSize() sz = self.GetClientSize()
w = self.bg_bmp.GetWidth() w = self.bg_bmp.GetWidth()
h = self.bg_bmp.GetHeight() h = self.bg_bmp.GetHeight()
x = 0 x = 0
while x < sz.width: while x < sz.width:
y = 0 y = 0
while y < sz.height: while y < sz.height:
dc.DrawBitmap(self.bg_bmp, (x, y)) dc.DrawBitmap(self.bg_bmp, (x, y))
y = y + h y = y + h
x = x + w x = x + w
#---------------------------------------------------------------------- #----------------------------------------------------------------------
if __name__ == '__main__': if __name__ == '__main__':
class MyApp(wxApp): class MyApp(wx.App):
def OnInit(self): def OnInit(self):
wxInitAllImageHandlers() wx.InitAllImageHandlers()
frame = MyParentFrame() frame = MyParentFrame()
frame.Show(True) frame.Show(True)
self.SetTopWindow(frame) self.SetTopWindow(frame)
return True return True
app = MyApp(0) app = MyApp(False)
app.MainLoop() app.MainLoop()

View File

@@ -1,115 +1,131 @@
#!/usr/bin/env python #!/usr/bin/env python
from wxPython.wx import * # 11/6/2003 - Jeff Grimmett (grimmtooth@softhome.net)
from wxScrolledWindow import MyCanvas #
# o Updated for wx namespace
#
import wx
import wxScrolledWindow
#----------------------------------------------------------------------
# There are better ways to do IDs, but this demo requires that the window
# IDs be in a specific range. There are better ways to do that, too, but
# this will do for purposes of this demo.
ID_Menu_New = 5004
ID_Menu_Exit = 5005
ID_WINDOW_TOP = 5000
ID_WINDOW_LEFT1 = 5001
ID_WINDOW_LEFT2 = 5002
ID_WINDOW_BOTTOM = 5003
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class MyParentFrame(wxMDIParentFrame): class MyParentFrame(wx.MDIParentFrame):
ID_WINDOW_TOP = 5100
ID_WINDOW_LEFT1 = 5101
ID_WINDOW_LEFT2 = 5102
ID_WINDOW_BOTTOM = 5103
def __init__(self): def __init__(self):
wxMDIParentFrame.__init__(self, None, -1, "MDI Parent", size=(600,400), wx.MDIParentFrame.__init__(
style = wxDEFAULT_FRAME_STYLE | wxHSCROLL | wxVSCROLL) self, None, -1, "MDI Parent", size=(600,400),
style = wx.DEFAULT_FRAME_STYLE | wx.HSCROLL | wx.VSCROLL
)
self.winCount = 0 self.winCount = 0
menu = wxMenu() menu = wx.Menu()
menu.Append(5000, "&New Window") menu.Append(ID_Menu_New, "&New Window")
menu.AppendSeparator() menu.AppendSeparator()
menu.Append(5001, "E&xit") menu.Append(ID_Menu_Exit, "E&xit")
menubar = wxMenuBar() menubar = wx.MenuBar()
menubar.Append(menu, "&File") menubar.Append(menu, "&File")
self.SetMenuBar(menubar) self.SetMenuBar(menubar)
#self.CreateStatusBar() #self.CreateStatusBar()
EVT_MENU(self, 5000, self.OnNewWindow) self.Bind(wx.EVT_MENU, self.OnNewWindow, id=ID_Menu_New)
EVT_MENU(self, 5001, self.OnExit) self.Bind(wx.EVT_MENU, self.OnExit, id=ID_Menu_Exit)
self.Bind(
wx.EVT_SASH_DRAGGED_RANGE, self.OnSashDrag, id=ID_WINDOW_TOP,
id2=ID_WINDOW_BOTTOM
)
EVT_SASH_DRAGGED_RANGE(self, self.Bind(wx.EVT_SIZE, self.OnSize)
self.ID_WINDOW_TOP, self.ID_WINDOW_BOTTOM,
self.OnSashDrag)
EVT_SIZE(self, self.OnSize)
# Create some layout windows # Create some layout windows
# A window like a toolbar # A window like a toolbar
win = wxSashLayoutWindow(self, self.ID_WINDOW_TOP, style = wxNO_BORDER|wxSW_3D) win = wx.SashLayoutWindow(self, ID_WINDOW_TOP, style=wx.NO_BORDER|wx.SW_3D)
win.SetDefaultSize((1000, 30)) win.SetDefaultSize((1000, 30))
win.SetOrientation(wxLAYOUT_HORIZONTAL) win.SetOrientation(wx.LAYOUT_HORIZONTAL)
win.SetAlignment(wxLAYOUT_TOP) win.SetAlignment(wx.LAYOUT_TOP)
win.SetBackgroundColour(wxColour(255, 0, 0)) win.SetBackgroundColour(wx.Colour(255, 0, 0))
win.SetSashVisible(wxSASH_BOTTOM, True) win.SetSashVisible(wx.SASH_BOTTOM, True)
self.topWindow = win self.topWindow = win
# A window like a statusbar # A window like a statusbar
win = wxSashLayoutWindow(self, self.ID_WINDOW_BOTTOM, style = wxNO_BORDER|wxSW_3D) win = wx.SashLayoutWindow(self, ID_WINDOW_BOTTOM, style=wx.NO_BORDER|wx.SW_3D)
win.SetDefaultSize((1000, 30)) win.SetDefaultSize((1000, 30))
win.SetOrientation(wxLAYOUT_HORIZONTAL) win.SetOrientation(wx.LAYOUT_HORIZONTAL)
win.SetAlignment(wxLAYOUT_BOTTOM) win.SetAlignment(wx.LAYOUT_BOTTOM)
win.SetBackgroundColour(wxColour(0, 0, 255)) win.SetBackgroundColour(wx.Colour(0, 0, 255))
win.SetSashVisible(wxSASH_TOP, True) win.SetSashVisible(wx.SASH_TOP, True)
self.bottomWindow = win self.bottomWindow = win
# A window to the left of the client window # A window to the left of the client window
win = wxSashLayoutWindow(self, self.ID_WINDOW_LEFT1, style = wxNO_BORDER|wxSW_3D) win = wx.SashLayoutWindow(self, ID_WINDOW_LEFT1, style=wx.NO_BORDER|wx.SW_3D)
win.SetDefaultSize((120, 1000)) win.SetDefaultSize((120, 1000))
win.SetOrientation(wxLAYOUT_VERTICAL) win.SetOrientation(wx.LAYOUT_VERTICAL)
win.SetAlignment(wxLAYOUT_LEFT) win.SetAlignment(wx.LAYOUT_LEFT)
win.SetBackgroundColour(wxColour(0, 255, 0)) win.SetBackgroundColour(wx.Colour(0, 255, 0))
win.SetSashVisible(wxSASH_RIGHT, True) win.SetSashVisible(wx.SASH_RIGHT, True)
win.SetExtraBorderSize(10) win.SetExtraBorderSize(10)
textWindow = wxTextCtrl(win, -1, "", wxDefaultPosition, wxDefaultSize, textWindow = wx.TextCtrl(win, -1, "", style=wx.TE_MULTILINE|wx.SUNKEN_BORDER)
wxTE_MULTILINE|wxSUNKEN_BORDER)
textWindow.SetValue("A sub window") textWindow.SetValue("A sub window")
self.leftWindow1 = win self.leftWindow1 = win
# Another window to the left of the client window # Another window to the left of the client window
win = wxSashLayoutWindow(self, self.ID_WINDOW_LEFT2, style = wxNO_BORDER|wxSW_3D) win = wx.SashLayoutWindow(self, ID_WINDOW_LEFT2, style=wx.NO_BORDER|wx.SW_3D)
win.SetDefaultSize((120, 1000)) win.SetDefaultSize((120, 1000))
win.SetOrientation(wxLAYOUT_VERTICAL) win.SetOrientation(wx.LAYOUT_VERTICAL)
win.SetAlignment(wxLAYOUT_LEFT) win.SetAlignment(wx.LAYOUT_LEFT)
win.SetBackgroundColour(wxColour(0, 255, 255)) win.SetBackgroundColour(wx.Colour(0, 255, 255))
win.SetSashVisible(wxSASH_RIGHT, True) win.SetSashVisible(wx.SASH_RIGHT, True)
self.leftWindow2 = win self.leftWindow2 = win
def OnSashDrag(self, event): def OnSashDrag(self, event):
if event.GetDragStatus() == wxSASH_STATUS_OUT_OF_RANGE: if event.GetDragStatus() == wx.SASH_STATUS_OUT_OF_RANGE:
return return
eID = event.GetId() eID = event.GetId()
if eID == self.ID_WINDOW_TOP:
self.topWindow.SetDefaultSize(wxSize(1000, event.GetDragRect().height))
elif eID == self.ID_WINDOW_LEFT1: if eID == ID_WINDOW_TOP:
self.leftWindow1.SetDefaultSize(wxSize(event.GetDragRect().width, 1000)) self.topWindow.SetDefaultSize((1000, event.GetDragRect().height))
elif eID == ID_WINDOW_LEFT1:
self.leftWindow1.SetDefaultSize((event.GetDragRect().width, 1000))
elif eID == self.ID_WINDOW_LEFT2: elif eID == ID_WINDOW_LEFT2:
self.leftWindow2.SetDefaultSize(wxSize(event.GetDragRect().width, 1000)) self.leftWindow2.SetDefaultSize((event.GetDragRect().width, 1000))
elif eID == self.ID_WINDOW_BOTTOM: elif eID == ID_WINDOW_BOTTOM:
self.bottomWindow.SetDefaultSize(wxSize(1000, event.GetDragRect().height)) self.bottomWindow.SetDefaultSize((1000, event.GetDragRect().height))
wxLayoutAlgorithm().LayoutMDIFrame(self) wx.LayoutAlgorithm().LayoutMDIFrame(self)
self.GetClientWindow().Refresh() self.GetClientWindow().Refresh()
def OnSize(self, event): def OnSize(self, event):
wxLayoutAlgorithm().LayoutMDIFrame(self) wx.LayoutAlgorithm().LayoutMDIFrame(self)
def OnExit(self, evt): def OnExit(self, evt):
@@ -118,24 +134,23 @@ class MyParentFrame(wxMDIParentFrame):
def OnNewWindow(self, evt): def OnNewWindow(self, evt):
self.winCount = self.winCount + 1 self.winCount = self.winCount + 1
win = wxMDIChildFrame(self, -1, "Child Window: %d" % self.winCount) win = wx.MDIChildFrame(self, -1, "Child Window: %d" % self.winCount)
canvas = MyCanvas(win) canvas = wxScrolledWindow.MyCanvas(win)
win.Show(True) win.Show(True)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
if __name__ == '__main__': if __name__ == '__main__':
class MyApp(wxApp): class MyApp(wx.App):
def OnInit(self): def OnInit(self):
wxInitAllImageHandlers() wx.InitAllImageHandlers()
frame = MyParentFrame() frame = MyParentFrame()
frame.Show(True) frame.Show(True)
self.SetTopWindow(frame) self.SetTopWindow(frame)
return True return True
app = MyApp(False)
app = MyApp(0)
app.MainLoop() app.MainLoop()

View File

@@ -1,10 +1,21 @@
from wxPython.wx import * # 11/23/2003 - Jeff Grimmett (grimmtooth@softhome.net)
from wxPython.lib.maskededit import Field, wxMaskedTextCtrl, wxMaskedComboBox, wxIpAddrCtrl, states, state_names, months #
from wxPython.lib.maskededit import __doc__ as maskededit_doc # o Updated for wx namespace
from wxPython.lib.maskededit import autoformats #
from wxPython.lib.maskedctrl import wxMaskedCtrl, controlTypes, MASKEDCOMBO # 11/26/2003 - Jeff Grimmett (grimmtooth@softhome.net)
from wxPython.lib.scrolledpanel import wxScrolledPanel #
import string, sys, traceback # o the three libraries below all have not been hit by the
# wx renamer.
#
import string
import sys
import traceback
import wx
import wx.lib.maskededit as med
import wx.lib.maskedctrl as mctl
import wx.lib.scrolledpanel as scroll
class demoMixin: class demoMixin:
@@ -12,17 +23,17 @@ class demoMixin:
Centralized routines common to demo pages, to remove repetition. Centralized routines common to demo pages, to remove repetition.
""" """
def labelGeneralTable(self, sizer): def labelGeneralTable(self, sizer):
description = wxStaticText( self, -1, "Description", ) description = wx.StaticText( self, -1, "Description", )
mask = wxStaticText( self, -1, "Mask Value" ) mask = wx.StaticText( self, -1, "Mask Value" )
formatcode = wxStaticText( self, -1, "Format" ) formatcode = wx.StaticText( self, -1, "Format" )
regex = wxStaticText( self, -1, "Regexp Validator(opt.)" ) regex = wx.StaticText( self, -1, "Regexp Validator(opt.)" )
ctrl = wxStaticText( self, -1, "wxMaskedTextCtrl" ) ctrl = wx.StaticText( self, -1, "wxMaskedTextCtrl" )
description.SetFont( wxFont(9, wxSWISS, wxNORMAL, wxBOLD)) description.SetFont( wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD))
mask.SetFont( wxFont(9, wxSWISS, wxNORMAL, wxBOLD)) mask.SetFont( wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD))
formatcode.SetFont( wxFont(9, wxSWISS, wxNORMAL, wxBOLD) ) formatcode.SetFont( wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD) )
regex.SetFont( wxFont(9, wxSWISS, wxNORMAL, wxBOLD)) regex.SetFont( wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD))
ctrl.SetFont( wxFont(9, wxSWISS, wxNORMAL, wxBOLD)) ctrl.SetFont( wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD))
sizer.Add(description) sizer.Add(description)
sizer.Add(mask) sizer.Add(mask)
@@ -33,13 +44,13 @@ class demoMixin:
def layoutGeneralTable(self, controls, sizer): def layoutGeneralTable(self, controls, sizer):
for control in controls: for control in controls:
sizer.Add( wxStaticText( self, -1, control[0]) ) sizer.Add( wx.StaticText( self, -1, control[0]) )
sizer.Add( wxStaticText( self, -1, control[1]) ) sizer.Add( wx.StaticText( self, -1, control[1]) )
sizer.Add( wxStaticText( self, -1, control[3]) ) sizer.Add( wx.StaticText( self, -1, control[3]) )
sizer.Add( wxStaticText( self, -1, control[4]) ) sizer.Add( wx.StaticText( self, -1, control[4]) )
if control in controls: if control in controls:
newControl = wxMaskedTextCtrl( self, -1, "", newControl = med.wxMaskedTextCtrl( self, -1, "",
mask = control[1], mask = control[1],
excludeChars = control[2], excludeChars = control[2],
formatcodes = control[3], formatcodes = control[3],
@@ -56,25 +67,28 @@ class demoMixin:
def changeControlParams(self, event, parameter, checked_value, notchecked_value): def changeControlParams(self, event, parameter, checked_value, notchecked_value):
if event.Checked(): value = checked_value if event.IsChecked(): value = checked_value
else: value = notchecked_value else: value = notchecked_value
kwargs = {parameter: value} kwargs = {parameter: value}
for control in self.editList: for control in self.editList:
control.SetCtrlParameters(**kwargs) control.SetCtrlParameters(**kwargs)
control.Refresh() control.Refresh()
self.Refresh() self.Refresh()
#---------------------------------------------------------------------------- #----------------------------------------------------------------------------
class demoPage1(wxScrolledPanel, demoMixin): class demoPage1(scroll.wxScrolledPanel, demoMixin):
def __init__(self, parent, log): def __init__(self, parent, log):
wxScrolledPanel.__init__(self, parent, -1) scroll.wxScrolledPanel.__init__(self, parent, -1)
self.sizer = wxBoxSizer( wxVERTICAL ) self.sizer = wx.BoxSizer( wx.VERTICAL )
self.editList = [] self.editList = []
label = wxStaticText( self, -1, """\ label = wx.StaticText( self, -1, """\
Here are some basic wxMaskedTextCtrls to give you an idea of what you can do Here are some basic MaskedTextCtrls to give you an idea of what you can do
with this control. Note that all controls have been auto-sized by including 'F' in with this control. Note that all controls have been auto-sized by including 'F' in
the format codes. the format codes.
@@ -83,25 +97,25 @@ Note that the State and Last Name fields are list-limited (valid last names are:
Smith, Jones, Williams). Signs on numbers can be toggled with the minus key. Smith, Jones, Williams). Signs on numbers can be toggled with the minus key.
""") """)
label.SetForegroundColour( "Blue" ) label.SetForegroundColour( "Blue" )
header = wxBoxSizer( wxHORIZONTAL ) header = wx.BoxSizer( wx.HORIZONTAL )
header.Add( label, 0, flag=wxALIGN_LEFT|wxALL, border = 5 ) header.Add( label, 0, flag=wx.ALIGN_LEFT|wx.ALL, border = 5 )
highlight = wxCheckBox( self, -1, "Highlight Empty" ) highlight = wx.CheckBox( self, -1, "Highlight Empty" )
disallow = wxCheckBox( self, -1, "Disallow Empty" ) disallow = wx.CheckBox( self, -1, "Disallow Empty" )
showFill = wxCheckBox( self, -1, "change fillChar" ) showFill = wx.CheckBox( self, -1, "change fillChar" )
vbox = wxBoxSizer( wxVERTICAL ) vbox = wx.BoxSizer( wx.VERTICAL )
vbox.Add( highlight, 0, wxALIGN_LEFT|wxALL, 5 ) vbox.Add( highlight, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
vbox.Add( disallow, 0, wxALIGN_LEFT|wxALL, 5 ) vbox.Add( disallow, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
vbox.Add( showFill, 0, wxALIGN_LEFT|wxALL, 5 ) vbox.Add( showFill, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
header.AddSpacer(15, 0) header.Add((15, 0))
header.Add(vbox, 0, flag=wxALIGN_LEFT|wxALL, border=5 ) header.Add(vbox, 0, flag=wx.ALIGN_LEFT|wx.ALL, border=5 )
EVT_CHECKBOX( self, highlight.GetId(), self.onHighlightEmpty ) self.Bind(wx.EVT_CHECKBOX, self.onHighlightEmpty, id=highlight.GetId())
EVT_CHECKBOX( self, disallow.GetId(), self.onDisallowEmpty ) self.Bind(wx.EVT_CHECKBOX, self.onDisallowEmpty, id=disallow.GetId())
EVT_CHECKBOX( self, showFill.GetId(), self.onShowFill ) self.Bind(wx.EVT_CHECKBOX, self.onShowFill, id=showFill.GetId())
grid = wxFlexGridSizer( 0, 5, vgap=10, hgap=10 ) grid = wx.FlexGridSizer( 0, 5, vgap=10, hgap=10 )
self.labelGeneralTable(grid) self.labelGeneralTable(grid)
# The following list is of the controls for the demo. Feel free to play around with # The following list is of the controls for the demo. Feel free to play around with
@@ -119,8 +133,8 @@ Smith, Jones, Williams). Signs on numbers can be toggled with the minus key.
] ]
self.layoutGeneralTable(controls, grid) self.layoutGeneralTable(controls, grid)
self.sizer.Add( header, 0, flag=wxALIGN_LEFT|wxALL, border=5 ) self.sizer.Add( header, 0, flag=wx.ALIGN_LEFT|wx.ALL, border=5 )
self.sizer.Add( grid, 0, flag= wxALIGN_LEFT|wxLEFT, border=5 ) self.sizer.Add( grid, 0, flag= wx.ALIGN_LEFT|wx.LEFT, border=5 )
self.SetSizer(self.sizer) self.SetSizer(self.sizer)
self.SetupScrolling() self.SetupScrolling()
self.SetAutoLayout(1) self.SetAutoLayout(1)
@@ -139,13 +153,13 @@ Smith, Jones, Williams). Signs on numbers can be toggled with the minus key.
self.changeControlParams( event, "fillChar", '?', ' ' ) self.changeControlParams( event, "fillChar", '?', ' ' )
class demoPage2(wxScrolledPanel, demoMixin): class demoPage2(scroll.wxScrolledPanel, demoMixin):
def __init__( self, parent, log ): def __init__( self, parent, log ):
self.log = log self.log = log
wxScrolledPanel.__init__( self, parent, -1 ) scroll.wxScrolledPanel.__init__( self, parent, -1 )
self.sizer = wxBoxSizer( wxVERTICAL ) self.sizer = wx.BoxSizer( wx.VERTICAL )
label = wxStaticText( self, -1, """\ label = wx.StaticText( self, -1, """\
All these controls have been created by passing a single parameter, the autoformat code, All these controls have been created by passing a single parameter, the autoformat code,
and use the factory class wxMaskedCtrl with its default controlType. and use the factory class wxMaskedCtrl with its default controlType.
The maskededit module contains an internal dictionary of types and formats (autoformats). The maskededit module contains an internal dictionary of types and formats (autoformats).
@@ -154,72 +168,72 @@ Many of these already do complicated validation; To see some examples, try
""") """)
label.SetForegroundColour( "Blue" ) label.SetForegroundColour( "Blue" )
self.sizer.Add( label, 0, wxALIGN_LEFT|wxALL, 5 ) self.sizer.Add( label, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
description = wxStaticText( self, -1, "Description") description = wx.StaticText( self, -1, "Description")
autofmt = wxStaticText( self, -1, "AutoFormat Code") autofmt = wx.StaticText( self, -1, "AutoFormat Code")
ctrl = wxStaticText( self, -1, "wxMaskedCtrl") ctrl = wx.StaticText( self, -1, "MaskedCtrl")
description.SetFont( wxFont( 9, wxSWISS, wxNORMAL, wxBOLD ) ) description.SetFont( wx.Font( 9, wx.SWISS, wx.NORMAL, wx.BOLD ) )
autofmt.SetFont( wxFont( 9, wxSWISS, wxNORMAL, wxBOLD ) ) autofmt.SetFont( wx.Font( 9, wx.SWISS, wx.NORMAL, wx.BOLD ) )
ctrl.SetFont( wxFont( 9, wxSWISS, wxNORMAL, wxBOLD ) ) ctrl.SetFont( wx.Font( 9, wx.SWISS, wx.NORMAL, wx.BOLD ) )
grid = wxFlexGridSizer( 0, 3, vgap=10, hgap=5 ) grid = wx.FlexGridSizer( 0, 3, vgap=10, hgap=5 )
grid.Add( description, 0, wxALIGN_LEFT ) grid.Add( description, 0, wx.ALIGN_LEFT )
grid.Add( autofmt, 0, wxALIGN_LEFT ) grid.Add( autofmt, 0, wx.ALIGN_LEFT )
grid.Add( ctrl, 0, wxALIGN_LEFT ) grid.Add( ctrl, 0, wx.ALIGN_LEFT )
for autoformat, desc in autoformats: for autoformat, desc in med.autoformats:
grid.Add( wxStaticText( self, -1, desc), 0, wxALIGN_LEFT ) grid.Add( wx.StaticText( self, -1, desc), 0, wx.ALIGN_LEFT )
grid.Add( wxStaticText( self, -1, autoformat), 0, wxALIGN_LEFT ) grid.Add( wx.StaticText( self, -1, autoformat), 0, wx.ALIGN_LEFT )
grid.Add( wxMaskedCtrl( self, -1, "", grid.Add( mctl.wxMaskedCtrl( self, -1, "",
autoformat = autoformat, autoformat = autoformat,
demo = True, demo = True,
name = autoformat), name = autoformat),
0, wxALIGN_LEFT ) 0, wx.ALIGN_LEFT )
self.sizer.Add( grid, 0, wxALIGN_LEFT|wxALL, border=5 ) self.sizer.Add( grid, 0, wx.ALIGN_LEFT|wx.ALL, border=5 )
self.SetSizer( self.sizer ) self.SetSizer( self.sizer )
self.SetAutoLayout( 1 ) self.SetAutoLayout( 1 )
self.SetupScrolling() self.SetupScrolling()
class demoPage3(wxScrolledPanel, demoMixin): class demoPage3(scroll.wxScrolledPanel, demoMixin):
def __init__(self, parent, log): def __init__(self, parent, log):
self.log = log self.log = log
wxScrolledPanel.__init__(self, parent, -1) scroll.wxScrolledPanel.__init__(self, parent, -1)
self.sizer = wxBoxSizer( wxVERTICAL ) self.sizer = wx.BoxSizer( wx.VERTICAL )
self.editList = [] self.editList = []
label = wxStaticText( self, -1, """\ label = wx.StaticText( self, -1, """\
Here wxMaskedTextCtrls that have default values. The states Here wxMaskedTextCtrls that have default values. The states
control has a list of valid values, and the unsigned integer control has a list of valid values, and the unsigned integer
has a legal range specified. has a legal range specified.
""") """)
label.SetForegroundColour( "Blue" ) label.SetForegroundColour( "Blue" )
requireValid = wxCheckBox( self, -1, "Require Valid Value" ) requireValid = wx.CheckBox( self, -1, "Require Valid Value" )
EVT_CHECKBOX( self, requireValid.GetId(), self.onRequireValid ) self.Bind(wx.EVT_CHECKBOX, self.onRequireValid, id=requireValid.GetId())
header = wxBoxSizer( wxHORIZONTAL ) header = wx.BoxSizer( wx.HORIZONTAL )
header.Add( label, 0, flag=wxALIGN_LEFT|wxALL, border = 5) header.Add( label, 0, flag=wx.ALIGN_LEFT|wx.ALL, border = 5)
header.AddSpacer(75, 0) header.Add((75, 0))
header.Add( requireValid, 0, flag=wxALIGN_LEFT|wxALL, border=10 ) header.Add( requireValid, 0, flag=wx.ALIGN_LEFT|wx.ALL, border=10 )
grid = wxFlexGridSizer( 0, 5, vgap=10, hgap=10 ) grid = wx.FlexGridSizer( 0, 5, vgap=10, hgap=10 )
self.labelGeneralTable( grid ) self.labelGeneralTable( grid )
controls = [ controls = [
#description mask excl format regexp range,list,initial #description mask excl format regexp range,list,initial
("U.S. State (2 char)", "AA", "", 'F!_', "[A-Z]{2}", '',states, states[0]), ("U.S. State (2 char)", "AA", "", 'F!_', "[A-Z]{2}", '',med.states, med.states[0]),
("Integer (signed)", "#{6}", "", 'F-_', "", '','', ' 0 '), ("Integer (signed)", "#{6}", "", 'F-_', "", '','', ' 0 '),
("Integer (unsigned)\n(1-399)","######", "", 'F_', "", (1,399),'', '1 '), ("Integer (unsigned)\n(1-399)","######", "", 'F_', "", (1,399),'', '1 '),
("Float (signed)", "#{6}.#{9}", "", 'F-_R', "", '','', '000000.000000000'), ("Float (signed)", "#{6}.#{9}", "", 'F-_R', "", '','', '000000.000000000'),
("Date (MDY) + Time", "##/##/#### ##:##:## AM", 'BCDEFGHIJKLMNOQRSTUVWXYZ','DF!',"", '','', wxDateTime_Now().Format("%m/%d/%Y %I:%M:%S %p")), ("Date (MDY) + Time", "##/##/#### ##:##:## AM", 'BCDEFGHIJKLMNOQRSTUVWXYZ','DF!',"", '','', wx.DateTime_Now().Format("%m/%d/%Y %I:%M:%S %p")),
] ]
self.layoutGeneralTable( controls, grid ) self.layoutGeneralTable( controls, grid )
self.sizer.Add( header, 0, flag=wxALIGN_LEFT|wxALL, border=5 ) self.sizer.Add( header, 0, flag=wx.ALIGN_LEFT|wx.ALL, border=5 )
self.sizer.Add( grid, 0, flag=wxALIGN_LEFT|wxALL, border=5 ) self.sizer.Add( grid, 0, flag=wx.ALIGN_LEFT|wx.ALL, border=5 )
self.SetSizer( self.sizer ) self.SetSizer( self.sizer )
self.SetAutoLayout( 1 ) self.SetAutoLayout( 1 )
@@ -230,13 +244,13 @@ has a legal range specified.
self.changeControlParams( event, "validRequired", True, False ) self.changeControlParams( event, "validRequired", True, False )
class demoPage4(wxScrolledPanel, demoMixin): class demoPage4(scroll.wxScrolledPanel, demoMixin):
def __init__( self, parent, log ): def __init__( self, parent, log ):
self.log = log self.log = log
wxScrolledPanel.__init__( self, parent, -1 ) scroll.wxScrolledPanel.__init__( self, parent, -1 )
self.sizer = wxBoxSizer( wxVERTICAL ) self.sizer = wx.BoxSizer( wx.VERTICAL )
label = wxStaticText( self, -1, """\ label = wx.StaticText( self, -1, """\
These controls have field-specific choice lists and allow autocompletion. These controls have field-specific choice lists and allow autocompletion.
Down arrow or Page Down in an uncompleted field with an auto-completable field will attempt Down arrow or Page Down in an uncompleted field with an auto-completable field will attempt
@@ -246,111 +260,111 @@ Page Up and Shift-Up arrow will similarly cycle backwards through the list.
""") """)
label.SetForegroundColour( "Blue" ) label.SetForegroundColour( "Blue" )
self.sizer.Add( label, 0, wxALIGN_LEFT|wxALL, 5 ) self.sizer.Add( label, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
description = wxStaticText( self, -1, "Description" ) description = wx.StaticText( self, -1, "Description" )
autofmt = wxStaticText( self, -1, "AutoFormat Code" ) autofmt = wx.StaticText( self, -1, "AutoFormat Code" )
fields = wxStaticText( self, -1, "Field Objects" ) fields = wx.StaticText( self, -1, "Field Objects" )
ctrl = wxStaticText( self, -1, "wxMaskedTextCtrl" ) ctrl = wx.StaticText( self, -1, "wxMaskedTextCtrl" )
description.SetFont( wxFont( 9, wxSWISS, wxNORMAL, wxBOLD ) ) description.SetFont( wx.Font( 9, wx.SWISS, wx.NORMAL, wx.BOLD ) )
autofmt.SetFont( wxFont( 9, wxSWISS, wxNORMAL, wxBOLD ) ) autofmt.SetFont( wx.Font( 9, wx.SWISS, wx.NORMAL, wx.BOLD ) )
fields.SetFont( wxFont( 9, wxSWISS, wxNORMAL, wxBOLD ) ) fields.SetFont( wx.Font( 9, wx.SWISS, wx.NORMAL, wx.BOLD ) )
ctrl.SetFont( wxFont( 9, wxSWISS, wxNORMAL, wxBOLD ) ) ctrl.SetFont( wx.Font( 9, wx.SWISS, wx.NORMAL, wx.BOLD ) )
grid = wxFlexGridSizer( 0, 4, vgap=10, hgap=10 ) grid = wx.FlexGridSizer( 0, 4, vgap=10, hgap=10 )
grid.Add( description, 0, wxALIGN_LEFT ) grid.Add( description, 0, wx.ALIGN_LEFT )
grid.Add( autofmt, 0, wxALIGN_LEFT ) grid.Add( autofmt, 0, wx.ALIGN_LEFT )
grid.Add( fields, 0, wxALIGN_LEFT ) grid.Add( fields, 0, wx.ALIGN_LEFT )
grid.Add( ctrl, 0, wxALIGN_LEFT ) grid.Add( ctrl, 0, wx.ALIGN_LEFT )
autoformat = "USPHONEFULLEXT" autoformat = "USPHONEFULLEXT"
fieldsDict = {0: Field(choices=["617","781","508","978","413"], choiceRequired=True)} fieldsDict = {0: med.Field(choices=["617","781","508","978","413"], choiceRequired=True)}
fieldsLabel = """\ fieldsLabel = """\
{0: Field(choices=[ {0: Field(choices=[
"617","781", "617","781",
"508","978","413"], "508","978","413"],
choiceRequired=True)}""" choiceRequired=True)}"""
grid.Add( wxStaticText( self, -1, "Restricted Area Code"), 0, wxALIGN_LEFT ) grid.Add( wx.StaticText( self, -1, "Restricted Area Code"), 0, wx.ALIGN_LEFT )
grid.Add( wxStaticText( self, -1, autoformat), 0, wxALIGN_LEFT ) grid.Add( wx.StaticText( self, -1, autoformat), 0, wx.ALIGN_LEFT )
grid.Add( wxStaticText( self, -1, fieldsLabel), 0, wxALIGN_LEFT ) grid.Add( wx.StaticText( self, -1, fieldsLabel), 0, wx.ALIGN_LEFT )
grid.Add( wxMaskedTextCtrl( self, -1, "", grid.Add( med.wxMaskedTextCtrl( self, -1, "",
autoformat = autoformat, autoformat = autoformat,
fields = fieldsDict, fields = fieldsDict,
demo = True, demo = True,
name = autoformat), name = autoformat),
0, wxALIGN_LEFT ) 0, wx.ALIGN_LEFT )
autoformat = "EXPDATEMMYY" autoformat = "EXPDATEMMYY"
fieldsDict = {1: Field(choices=["03", "04", "05"], choiceRequired=True)} fieldsDict = {1: med.Field(choices=["03", "04", "05"], choiceRequired=True)}
fieldsLabel = """\ fieldsLabel = """\
{1: Field(choices=[ {1: Field(choices=[
"03", "04", "05"], "03", "04", "05"],
choiceRequired=True)}""" choiceRequired=True)}"""
exp = wxMaskedTextCtrl( self, -1, "", exp = med.wxMaskedTextCtrl( self, -1, "",
autoformat = autoformat, autoformat = autoformat,
fields = fieldsDict, fields = fieldsDict,
demo = True, demo = True,
name = autoformat) name = autoformat)
grid.Add( wxStaticText( self, -1, "Restricted Expiration"), 0, wxALIGN_LEFT ) grid.Add( wx.StaticText( self, -1, "Restricted Expiration"), 0, wx.ALIGN_LEFT )
grid.Add( wxStaticText( self, -1, autoformat), 0, wxALIGN_LEFT ) grid.Add( wx.StaticText( self, -1, autoformat), 0, wx.ALIGN_LEFT )
grid.Add( wxStaticText( self, -1, fieldsLabel), 0, wxALIGN_LEFT ) grid.Add( wx.StaticText( self, -1, fieldsLabel), 0, wx.ALIGN_LEFT )
grid.Add( exp, 0, wxALIGN_LEFT ) grid.Add( exp, 0, wx.ALIGN_LEFT )
fieldsDict = {0: Field(choices=["02134","02155"], choiceRequired=True), fieldsDict = {0: med.Field(choices=["02134","02155"], choiceRequired=True),
1: Field(choices=["1234", "5678"], choiceRequired=False)} 1: med.Field(choices=["1234", "5678"], choiceRequired=False)}
fieldsLabel = """\ fieldsLabel = """\
{0: Field(choices=["02134","02155"], {0: Field(choices=["02134","02155"],
choiceRequired=True), choiceRequired=True),
1: Field(choices=["1234", "5678"], 1: Field(choices=["1234", "5678"],
choiceRequired=False)}""" choiceRequired=False)}"""
autoformat = "USZIPPLUS4" autoformat = "USZIPPLUS4"
zip = wxMaskedTextCtrl( self, -1, "", zip = med.wxMaskedTextCtrl( self, -1, "",
autoformat = autoformat, autoformat = autoformat,
fields = fieldsDict, fields = fieldsDict,
demo = True, demo = True,
name = autoformat) name = autoformat)
grid.Add( wxStaticText( self, -1, "Restricted Zip + 4"), 0, wxALIGN_LEFT ) grid.Add( wx.StaticText( self, -1, "Restricted Zip + 4"), 0, wx.ALIGN_LEFT )
grid.Add( wxStaticText( self, -1, autoformat), 0, wxALIGN_LEFT ) grid.Add( wx.StaticText( self, -1, autoformat), 0, wx.ALIGN_LEFT )
grid.Add( wxStaticText( self, -1, fieldsLabel), 0, wxALIGN_LEFT ) grid.Add( wx.StaticText( self, -1, fieldsLabel), 0, wx.ALIGN_LEFT )
grid.Add( zip, 0, wxALIGN_LEFT ) grid.Add( zip, 0, wx.ALIGN_LEFT )
self.sizer.Add( grid, 0, wxALIGN_LEFT|wxALL, border=5 ) self.sizer.Add( grid, 0, wx.ALIGN_LEFT|wx.ALL, border=5 )
self.SetSizer( self.sizer ) self.SetSizer( self.sizer )
self.SetAutoLayout(1) self.SetAutoLayout(1)
self.SetupScrolling() self.SetupScrolling()
class demoPage5(wxScrolledPanel, demoMixin): class demoPage5(scroll.wxScrolledPanel, demoMixin):
def __init__( self, parent, log ): def __init__( self, parent, log ):
self.log = log self.log = log
wxScrolledPanel.__init__( self, parent, -1 ) scroll.wxScrolledPanel.__init__( self, parent, -1 )
self.sizer = wxBoxSizer( wxVERTICAL ) self.sizer = wx.BoxSizer( wx.VERTICAL )
labelMaskedCombos = wxStaticText( self, -1, """\ labelMaskedCombos = wx.StaticText( self, -1, """\
These are some examples of wxMaskedComboBox:""") These are some examples of wxMaskedComboBox:""")
labelMaskedCombos.SetForegroundColour( "Blue" ) labelMaskedCombos.SetForegroundColour( "Blue" )
label_statecode = wxStaticText( self, -1, """\ label_statecode = wx.StaticText( self, -1, """\
A state selector; only A state selector; only
"legal" values can be "legal" values can be
entered:""") entered:""")
statecode = wxMaskedComboBox( self, -1, states[0], statecode = med.wxMaskedComboBox( self, -1, med.states[0],
choices = states, choices = med.states,
autoformat="USSTATE") autoformat="USSTATE")
label_statename = wxStaticText( self, -1, """\ label_statename = wx.StaticText( self, -1, """\
A state name selector, A state name selector,
with auto-select:""") with auto-select:""")
# Create this one using factory function: # Create this one using factory function:
statename = wxMaskedCtrl( self, -1, state_names[0], statename = mctl.wxMaskedCtrl( self, -1, med.state_names[0],
controlType = controlTypes.MASKEDCOMBO, controlType = mctl.controlTypes.MASKEDCOMBO,
choices = state_names, choices = med.state_names,
autoformat="USSTATENAME", autoformat="USSTATENAME",
autoSelect=True) autoSelect=True)
statename.SetCtrlParameters(formatcodes = 'F!V_') statename.SetCtrlParameters(formatcodes = 'F!V_')
@@ -358,8 +372,8 @@ with auto-select:""")
numerators = [ str(i) for i in range(1, 4) ] numerators = [ str(i) for i in range(1, 4) ]
denominators = [ string.ljust(str(i), 2) for i in [2,3,4,5,8,16,32,64] ] denominators = [ string.ljust(str(i), 2) for i in [2,3,4,5,8,16,32,64] ]
fieldsDict = {0: Field(choices=numerators, choiceRequired=False), fieldsDict = {0: med.Field(choices=numerators, choiceRequired=False),
1: Field(choices=denominators, choiceRequired=True)} 1: med.Field(choices=denominators, choiceRequired=True)}
choices = [] choices = []
for n in numerators: for n in numerators:
for d in denominators: for d in denominators:
@@ -367,13 +381,13 @@ with auto-select:""")
choices.append( '%s/%s' % (n,d) ) choices.append( '%s/%s' % (n,d) )
label_fraction = wxStaticText( self, -1, """\ label_fraction = wx.StaticText( self, -1, """\
A masked ComboBox for fraction selection. A masked ComboBox for fraction selection.
Choices for each side of the fraction can Choices for each side of the fraction can
be selected with PageUp/Down:""") be selected with PageUp/Down:""")
fraction = wxMaskedCtrl( self, -1, "", fraction = mctl.wxMaskedCtrl( self, -1, "",
controlType = MASKEDCOMBO, controlType = mctl.MASKEDCOMBO,
choices = choices, choices = choices,
choiceRequired = True, choiceRequired = True,
mask = "#/##", mask = "#/##",
@@ -382,23 +396,23 @@ be selected with PageUp/Down:""")
fields = fieldsDict ) fields = fieldsDict )
label_code = wxStaticText( self, -1, """\ label_code = wx.StaticText( self, -1, """\
A masked ComboBox to validate A masked ComboBox to validate
text from a list of numeric codes:""") text from a list of numeric codes:""")
choices = ["91", "136", "305", "4579"] choices = ["91", "136", "305", "4579"]
code = wxMaskedComboBox( self, -1, choices[0], code = med.wxMaskedComboBox( self, -1, choices[0],
choices = choices, choices = choices,
choiceRequired = True, choiceRequired = True,
formatcodes = "F_r", formatcodes = "F_r",
mask = "####") mask = "####")
label_selector = wxStaticText( self, -1, """\ label_selector = wx.StaticText( self, -1, """\
Programmatically set Programmatically set
choice sets:""") choice sets:""")
self.list_selector = wxComboBox(self, -1, '', choices = ['list1', 'list2', 'list3']) self.list_selector = wx.ComboBox(self, -1, '', choices = ['list1', 'list2', 'list3'])
self.dynamicbox = wxMaskedCtrl( self, -1, ' ', self.dynamicbox = mctl.wxMaskedCtrl( self, -1, ' ',
controlType = controlTypes.MASKEDCOMBO, controlType = mctl.controlTypes.MASKEDCOMBO,
mask = 'XXXX', mask = 'XXXX',
formatcodes = 'F_', formatcodes = 'F_',
# these are to give dropdown some initial height, # these are to give dropdown some initial height,
@@ -409,24 +423,24 @@ choice sets:""")
self.dynamicbox.Clear() # get rid of initial choices used to size the dropdown self.dynamicbox.Clear() # get rid of initial choices used to size the dropdown
labelIpAddrs = wxStaticText( self, -1, """\ labelIpAddrs = wx.StaticText( self, -1, """\
Here are some examples of wxIpAddrCtrl, a control derived from wxMaskedTextCtrl:""") Here are some examples of wxIpAddrCtrl, a control derived from wxMaskedTextCtrl:""")
labelIpAddrs.SetForegroundColour( "Blue" ) labelIpAddrs.SetForegroundColour( "Blue" )
label_ipaddr1 = wxStaticText( self, -1, "An empty control:") label_ipaddr1 = wx.StaticText( self, -1, "An empty control:")
ipaddr1 = wxIpAddrCtrl( self, -1, style = wxTE_PROCESS_TAB ) ipaddr1 = med.wxIpAddrCtrl( self, -1, style = wx.TE_PROCESS_TAB )
label_ipaddr2 = wxStaticText( self, -1, "A restricted mask:") label_ipaddr2 = wx.StaticText( self, -1, "A restricted mask:")
ipaddr2 = wxIpAddrCtrl( self, -1, mask=" 10. 1.109.###" ) ipaddr2 = med.wxIpAddrCtrl( self, -1, mask=" 10. 1.109.###" )
label_ipaddr3 = wxStaticText( self, -1, """\ label_ipaddr3 = wx.StaticText( self, -1, """\
A control with restricted legal values: A control with restricted legal values:
10. (1|2) . (129..255) . (0..255)""") 10. (1|2) . (129..255) . (0..255)""")
ipaddr3 = wxMaskedCtrl( self, -1, ipaddr3 = mctl.wxMaskedCtrl( self, -1,
controlType = controlTypes.IPADDR, controlType = mctl.controlTypes.IPADDR,
mask=" 10. #.###.###") mask=" 10. #.###.###")
ipaddr3.SetFieldParameters(0, validRegex="1|2",validRequired=False ) # requires entry to match or not allowed ipaddr3.SetFieldParameters(0, validRegex="1|2",validRequired=False ) # requires entry to match or not allowed
@@ -435,104 +449,103 @@ A control with restricted legal values:
labelNumerics = wxStaticText( self, -1, """\ labelNumerics = wx.StaticText( self, -1, """\
Here are some useful configurations of a wxMaskedTextCtrl for integer and floating point input that still treat Here are some useful configurations of a wxMaskedTextCtrl for integer and floating point input that still treat
the control as a text control. (For a true numeric control, check out the wxMaskedNumCtrl class!)""") the control as a text control. (For a true numeric control, check out the wxMaskedNumCtrl class!)""")
labelNumerics.SetForegroundColour( "Blue" ) labelNumerics.SetForegroundColour( "Blue" )
label_intctrl1 = wxStaticText( self, -1, """\ label_intctrl1 = wx.StaticText( self, -1, """\
An integer entry control with An integer entry control with
shifting insert enabled:""") shifting insert enabled:""")
self.intctrl1 = wxMaskedTextCtrl(self, -1, name='intctrl', mask="#{9}", formatcodes = '_-,F>') self.intctrl1 = med.wxMaskedTextCtrl(self, -1, name='intctrl', mask="#{9}", formatcodes = '_-,F>')
label_intctrl2 = wxStaticText( self, -1, """\ label_intctrl2 = wx.StaticText( self, -1, """\
Right-insert integer entry:""") Right-insert integer entry:""")
self.intctrl2 = wxMaskedTextCtrl(self, -1, name='intctrl', mask="#{9}", formatcodes = '_-,Fr') self.intctrl2 = med.wxMaskedTextCtrl(self, -1, name='intctrl', mask="#{9}", formatcodes = '_-,Fr')
label_floatctrl = wxStaticText( self, -1, """\ label_floatctrl = wx.StaticText( self, -1, """\
A floating point entry control A floating point entry control
with right-insert for ordinal:""") with right-insert for ordinal:""")
self.floatctrl = wxMaskedTextCtrl(self, -1, name='floatctrl', mask="#{9}.#{2}", formatcodes="F,_-R", useParensForNegatives=False) self.floatctrl = med.wxMaskedTextCtrl(self, -1, name='floatctrl', mask="#{9}.#{2}", formatcodes="F,_-R", useParensForNegatives=False)
self.floatctrl.SetFieldParameters(0, formatcodes='r<', validRequired=True) # right-insert, require explicit cursor movement to change fields self.floatctrl.SetFieldParameters(0, formatcodes='r<', validRequired=True) # right-insert, require explicit cursor movement to change fields
self.floatctrl.SetFieldParameters(1, defaultValue='00') # don't allow blank fraction self.floatctrl.SetFieldParameters(1, defaultValue='00') # don't allow blank fraction
label_numselect = wxStaticText( self, -1, """\ label_numselect = wx.StaticText( self, -1, """\
<= Programmatically set the value <= Programmatically set the value
of the float entry ctrl:""") of the float entry ctrl:""")
numselect = wxComboBox(self, -1, choices = [ '', '111', '222.22', '-3', '54321.666666666', '-1353.978', numselect = wx.ComboBox(self, -1, choices = [ '', '111', '222.22', '-3', '54321.666666666', '-1353.978',
'1234567', '-1234567', '123456789', '-123456789.1', '1234567', '-1234567', '123456789', '-123456789.1',
'1234567890.', '-1234567890.1' ]) '1234567890.', '-1234567890.1' ])
parens_check = wxCheckBox(self, -1, "Use () to indicate negatives in above controls") parens_check = wx.CheckBox(self, -1, "Use () to indicate negatives in above controls")
gridCombos = wxFlexGridSizer( 0, 4, vgap=10, hgap = 10 ) gridCombos = wx.FlexGridSizer( 0, 4, vgap=10, hgap = 10 )
gridCombos.Add( label_statecode, 0, wxALIGN_LEFT ) gridCombos.Add( label_statecode, 0, wx.ALIGN_LEFT )
gridCombos.Add( statecode, 0, wxALIGN_LEFT ) gridCombos.Add( statecode, 0, wx.ALIGN_LEFT )
gridCombos.Add( label_fraction, 0, wxALIGN_LEFT ) gridCombos.Add( label_fraction, 0, wx.ALIGN_LEFT )
gridCombos.Add( fraction, 0, wxALIGN_LEFT ) gridCombos.Add( fraction, 0, wx.ALIGN_LEFT )
gridCombos.Add( label_statename, 0, wxALIGN_LEFT ) gridCombos.Add( label_statename, 0, wx.ALIGN_LEFT )
gridCombos.Add( statename, 0, wxALIGN_LEFT ) gridCombos.Add( statename, 0, wx.ALIGN_LEFT )
gridCombos.Add( label_code, 0, wxALIGN_LEFT ) gridCombos.Add( label_code, 0, wx.ALIGN_LEFT )
gridCombos.Add( code, 0, wxALIGN_LEFT ) gridCombos.Add( code, 0, wx.ALIGN_LEFT )
gridCombos.Add( label_selector, 0, wxALIGN_LEFT) gridCombos.Add( label_selector, 0, wx.ALIGN_LEFT)
hbox = wxBoxSizer( wxHORIZONTAL ) hbox = wx.BoxSizer( wx.HORIZONTAL )
hbox.Add( self.list_selector, 0, wxALIGN_LEFT ) hbox.Add( self.list_selector, 0, wx.ALIGN_LEFT )
hbox.Add(wxStaticText(self, -1, ' => '), 0, wxALIGN_LEFT) hbox.Add(wx.StaticText(self, -1, ' => '), 0, wx.ALIGN_LEFT)
hbox.Add( self.dynamicbox, 0, wxALIGN_LEFT ) hbox.Add( self.dynamicbox, 0, wx.ALIGN_LEFT )
gridCombos.Add( hbox, 0, wxALIGN_LEFT ) gridCombos.Add( hbox, 0, wx.ALIGN_LEFT )
gridIpAddrs = wxFlexGridSizer( 0, 4, vgap=10, hgap = 15 ) gridIpAddrs = wx.FlexGridSizer( 0, 4, vgap=10, hgap = 15 )
gridIpAddrs.Add( label_ipaddr1, 0, wxALIGN_LEFT ) gridIpAddrs.Add( label_ipaddr1, 0, wx.ALIGN_LEFT )
gridIpAddrs.Add( ipaddr1, 0, wxALIGN_LEFT ) gridIpAddrs.Add( ipaddr1, 0, wx.ALIGN_LEFT )
gridIpAddrs.Add( label_ipaddr2, 0, wxALIGN_LEFT ) gridIpAddrs.Add( label_ipaddr2, 0, wx.ALIGN_LEFT )
gridIpAddrs.Add( ipaddr2, 0, wxALIGN_LEFT ) gridIpAddrs.Add( ipaddr2, 0, wx.ALIGN_LEFT )
gridIpAddrs.Add( label_ipaddr3, 0, wxALIGN_LEFT ) gridIpAddrs.Add( label_ipaddr3, 0, wx.ALIGN_LEFT )
gridIpAddrs.Add( ipaddr3, 0, wxALIGN_LEFT ) gridIpAddrs.Add( ipaddr3, 0, wx.ALIGN_LEFT )
gridNumerics = wxFlexGridSizer( 0, 4, vgap=10, hgap = 10 ) gridNumerics = wx.FlexGridSizer( 0, 4, vgap=10, hgap = 10 )
gridNumerics.Add( label_intctrl1, 0, wxALIGN_LEFT ) gridNumerics.Add( label_intctrl1, 0, wx.ALIGN_LEFT )
gridNumerics.Add( self.intctrl1, 0, wxALIGN_LEFT ) gridNumerics.Add( self.intctrl1, 0, wx.ALIGN_LEFT )
gridNumerics.Add( label_intctrl2, 0, wxALIGN_RIGHT ) gridNumerics.Add( label_intctrl2, 0, wx.ALIGN_RIGHT )
gridNumerics.Add( self.intctrl2, 0, wxALIGN_LEFT ) gridNumerics.Add( self.intctrl2, 0, wx.ALIGN_LEFT )
gridNumerics.Add( label_floatctrl, 0, wxALIGN_LEFT ) gridNumerics.Add( label_floatctrl, 0, wx.ALIGN_LEFT )
gridNumerics.Add( self.floatctrl, 0, wxALIGN_LEFT ) gridNumerics.Add( self.floatctrl, 0, wx.ALIGN_LEFT )
gridNumerics.Add( label_numselect, 0, wxALIGN_RIGHT ) gridNumerics.Add( label_numselect, 0, wx.ALIGN_RIGHT )
gridNumerics.Add( numselect, 0, wxALIGN_LEFT ) gridNumerics.Add( numselect, 0, wx.ALIGN_LEFT )
self.sizer.Add( labelMaskedCombos, 0, wxALIGN_LEFT|wxALL, 5 ) self.sizer.Add( labelMaskedCombos, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
self.sizer.Add( gridCombos, 0, wxALIGN_LEFT|wxALL, border=5 ) self.sizer.Add( gridCombos, 0, wx.ALIGN_LEFT|wx.ALL, border=5 )
self.sizer.Add( wxStaticLine(self, -1), 0, wxEXPAND|wxTOP|wxBOTTOM, border=8 ) self.sizer.Add( wx.StaticLine(self, -1), 0, wx.EXPAND|wx.TOP|wx.BOTTOM, border=8 )
self.sizer.Add( labelIpAddrs, 0, wxALIGN_LEFT|wxALL, 5 ) self.sizer.Add( labelIpAddrs, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
self.sizer.Add( gridIpAddrs, 0, wxALIGN_LEFT|wxALL, border=5 ) self.sizer.Add( gridIpAddrs, 0, wx.ALIGN_LEFT|wx.ALL, border=5 )
self.sizer.Add( wxStaticLine(self, -1), 0, wxEXPAND|wxTOP|wxBOTTOM, border=8 ) self.sizer.Add( wx.StaticLine(self, -1), 0, wx.EXPAND|wx.TOP|wx.BOTTOM, border=8 )
self.sizer.Add( labelNumerics, 0, wxALIGN_LEFT|wxALL, 5 ) self.sizer.Add( labelNumerics, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
self.sizer.Add( gridNumerics, 0, wxALIGN_LEFT|wxALL, border=5 ) self.sizer.Add( gridNumerics, 0, wx.ALIGN_LEFT|wx.ALL, border=5 )
self.sizer.Add( parens_check, 0, wxALIGN_LEFT|wxALL, 5 ) self.sizer.Add( parens_check, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
self.SetSizer( self.sizer ) self.SetSizer( self.sizer )
self.SetAutoLayout(1) self.SetAutoLayout(1)
self.SetupScrolling() self.SetupScrolling()
EVT_COMBOBOX( self, fraction.GetId(), self.OnComboSelection ) self.Bind(wx.EVT_COMBOBOX, self.OnComboSelection, id=fraction.GetId())
EVT_COMBOBOX( self, code.GetId(), self.OnComboSelection ) self.Bind(wx.EVT_COMBOBOX, self.OnComboSelection, id=code.GetId())
EVT_COMBOBOX( self, statecode.GetId(), self.OnComboSelection ) self.Bind(wx.EVT_COMBOBOX, self.OnComboSelection, id=statecode.GetId())
EVT_COMBOBOX( self, statename.GetId(), self.OnComboSelection ) self.Bind(wx.EVT_COMBOBOX, self.OnComboSelection, id=statename.GetId())
EVT_TEXT( self, fraction.GetId(), self.OnTextChange ) self.Bind(wx.EVT_TEXT, self.OnTextChange, id=code.GetId())
EVT_TEXT( self, code.GetId(), self.OnTextChange ) self.Bind(wx.EVT_TEXT, self.OnTextChange, id=statecode.GetId())
EVT_TEXT( self, statecode.GetId(), self.OnTextChange ) self.Bind(wx.EVT_TEXT, self.OnTextChange, id=statename.GetId())
EVT_TEXT( self, statename.GetId(), self.OnTextChange ) self.Bind(wx.EVT_COMBOBOX, self.OnListSelection, id=self.list_selector.GetId())
EVT_COMBOBOX( self, self.list_selector.GetId(), self.OnListSelection )
EVT_TEXT( self, self.intctrl1.GetId(), self.OnTextChange ) self.Bind(wx.EVT_TEXT, self.OnTextChange, id=self.intctrl1.GetId())
EVT_TEXT( self, self.intctrl2.GetId(), self.OnTextChange ) self.Bind(wx.EVT_TEXT, self.OnTextChange, id=self.intctrl2.GetId())
EVT_TEXT( self, self.floatctrl.GetId(), self.OnTextChange ) self.Bind(wx.EVT_TEXT, self.OnTextChange, id=self.floatctrl.GetId())
EVT_COMBOBOX( self, numselect.GetId(), self.OnNumberSelect ) self.Bind(wx.EVT_COMBOBOX, self.OnNumberSelect, id=numselect.GetId())
EVT_CHECKBOX( self, parens_check.GetId(), self.OnParensCheck ) self.Bind(wx.EVT_CHECKBOX, self.OnParensCheck, id=parens_check.GetId())
EVT_TEXT( self, ipaddr1.GetId(), self.OnIpAddrChange ) self.Bind(wx.EVT_TEXT, self.OnIpAddrChange, id=ipaddr1.GetId())
EVT_TEXT( self, ipaddr2.GetId(), self.OnIpAddrChange ) self.Bind(wx.EVT_TEXT, self.OnIpAddrChange, id=ipaddr2.GetId())
EVT_TEXT( self, ipaddr3.GetId(), self.OnIpAddrChange ) self.Bind(wx.EVT_TEXT, self.OnIpAddrChange, id=ipaddr3.GetId())
@@ -595,9 +608,9 @@ with right-insert for ordinal:""")
self.dynamicbox.SetValue(choices[0]) self.dynamicbox.SetValue(choices[0])
# --------------------------------------------------------------------- # ---------------------------------------------------------------------
class TestMaskedTextCtrls(wxNotebook): class TestMaskedTextCtrls(wx.Notebook):
def __init__(self, parent, id, log): def __init__(self, parent, id, log):
wxNotebook.__init__(self, parent, id) wx.Notebook.__init__(self, parent, id)
self.log = log self.log = log
win = demoPage1(self, log) win = demoPage1(self, log)
@@ -623,19 +636,16 @@ def runTest(frame, nb, log):
return testWin return testWin
def RunStandalone(): def RunStandalone():
app = wxPySimpleApp() app = wx.PySimpleApp()
frame = wxFrame(None, -1, "Test wxMaskedTextCtrl", size=(640, 480)) frame = wx.Frame(None, -1, "Test MaskedTextCtrl", size=(640, 480))
win = TestMaskedTextCtrls(frame, -1, sys.stdout) win = TestMaskedTextCtrls(frame, -1, sys.stdout)
frame.Show(True) frame.Show(True)
app.MainLoop() app.MainLoop()
#---------------------------------------------------------------------------- #----------------------------------------------------------------------------
if __name__ == "__main__":
RunStandalone()
overview = """<html> overview = """<html>
<PRE><FONT SIZE=-1> <PRE><FONT SIZE=-1>
""" + maskededit_doc + """ """ + med.__doc__ + """
</FONT></PRE> </FONT></PRE>
""" """

View File

@@ -1,50 +1,56 @@
# 11/13/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import * import wx
from wxPython.html import * import wx.html as wxhtml
#---------------------------------------------------------------------- #----------------------------------------------------------------------
BTN1 = wxNewId() BTN1 = wx.NewId()
BTN2 = wxNewId() BTN2 = wx.NewId()
class TestPanel(wx.Panel):
class TestPanel(wxPanel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.log = log self.log = log
sizer = wxBoxSizer(wxVERTICAL) sizer = wx.BoxSizer(wx.VERTICAL)
html = wxHtmlWindow(self, -1) html = wxhtml.HtmlWindow(self, -1)
html.SetPage(overview) html.SetPage(overview)
sizer.Add(html, 1, wxEXPAND|wxALL, 5) sizer.Add(html, 1, wx.EXPAND|wx.ALL, 5)
btns = wxBoxSizer(wxHORIZONTAL) btns = wx.BoxSizer(wx.HORIZONTAL)
btns.Add(50, -1, 1, wxEXPAND) btns.Add((50, -1), 1, wx.EXPAND)
btn1 = wxButton(self, BTN1, "Find My Alter-ego") # don't save a ref to this one btn1 = wx.Button(self, BTN1, "Find My Alter-ego") # don't save a ref to this one
btns.Add(btn1) btns.Add(btn1)
btns.Add(50, -1, 1, wxEXPAND) btns.Add((50, -1), 1, wx.EXPAND)
self.btn2 = wxButton(self, BTN2, "Find Myself") self.btn2 = wx.Button(self, BTN2, "Find Myself")
btns.Add(self.btn2) btns.Add(self.btn2)
btns.Add(50, -1, 1, wxEXPAND) btns.Add((50, -1), 1, wx.EXPAND)
sizer.Add(btns, 0, wxEXPAND|wxALL, 15) sizer.Add(btns, 0, wx.EXPAND|wx.ALL, 15)
self.SetSizer(sizer) self.SetSizer(sizer)
self.SetAutoLayout(True) self.SetAutoLayout(True)
self.sizer = sizer # save it for testing later self.sizer = sizer # save it for testing later
EVT_BUTTON(self, BTN1, self.OnFindButton1) self.Bind(wx.EVT_BUTTON, self.OnFindButton1, id=BTN1)
EVT_BUTTON(self, BTN2, self.OnFindButton2) self.Bind(wx.EVT_BUTTON, self.OnFindButton2, id=BTN2)
def OnFindButton1(self, evt): def OnFindButton1(self, evt):
win = self.FindWindowById(BTN1) win = self.FindWindowById(BTN1)
if win is None: if win is None:
self.log.write("***** OOPS! None returned...\n") self.log.write("***** OOPS! None returned...\n")
return return
className = win.__class__.__name__ className = win.__class__.__name__
if className in ["wxButton", "wxButtonPtr"]:
if className in ["Button", "ButtonPtr"]:
self.log.write("The types are the same! <grin>\n") self.log.write("The types are the same! <grin>\n")
else: else:
self.log.write("Got %s, expected wxButton or wxButtonPtr\n" % className) self.log.write("Got %s, expected wxButton or wxButtonPtr\n" % className)
@@ -53,27 +59,33 @@ class TestPanel(wxPanel):
def OnFindButton2(self, evt): def OnFindButton2(self, evt):
win = self.FindWindowById(BTN2) win = self.FindWindowById(BTN2)
if win is None: if win is None:
self.log.write("***** OOPS! None returned...\n") self.log.write("***** OOPS! None returned...\n")
return return
if win is self.btn2: if win is self.btn2:
self.log.write("The objects are the same! <grin>\n") self.log.write("The objects are the same! <grin>\n")
else: else:
self.log.write("The objects are NOT the same! <frown>\n") self.log.write("The objects are NOT the same! <frown>\n")
win = evt.GetEventObject() win = evt.GetEventObject()
if win is None: if win is None:
self.log.write("***** OOPS! None returned...\n") self.log.write("***** OOPS! None returned...\n")
return return
if win is self.btn2: if win is self.btn2:
self.log.write("The objects are the same! <grin>\n") self.log.write("The objects are the same! <grin>\n")
else: else:
self.log.write("The objects are NOT the same! <frown>\n") self.log.write("The objects are NOT the same! <frown>\n")
sizer = self.GetSizer() sizer = self.GetSizer()
if sizer is None: if sizer is None:
self.log.write("***** OOPS! None returned...\n") self.log.write("***** OOPS! None returned...\n")
return return
if sizer is self.sizer: if sizer is self.sizer:
self.log.write("The objects are the same! <grin>\n") self.log.write("The objects are the same! <grin>\n")
else: else:
@@ -132,7 +144,7 @@ and be able to then turn wxPyTypeCast in to a no-op.
</ol> </ol>
<p>The first button below shows the first of these phases (<i>working</i>) <p>The first button below shows the first of these phases (<i>working</i>)
and the second will show #2 (<i>working as of 2.3.2</i>) and the second will show #2 (<i>working as of Python 2.3.2</i>)
</body></html> </body></html>
""" """

View File

@@ -1,48 +1,58 @@
# 11/13/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
# o Got rid of static buton IDs
# o Took at a stab at a lucid overview string.
#
from wxPython.wx import * import wx
from wxScrolledWindow import MyCanvas import wxScrolledWindow
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class MyPrintout(wxPrintout): ID_Setup = wx.NewId()
ID_Preview = wx.NewId()
ID_Print = wx.NewId()
class MyPrintout(wx.Printout):
def __init__(self, canvas, log): def __init__(self, canvas, log):
wxPrintout.__init__(self) wx.Printout.__init__(self)
self.canvas = canvas self.canvas = canvas
self.log = log self.log = log
def OnBeginDocument(self, start, end): def OnBeginDocument(self, start, end):
self.log.WriteText("wxPrintout.OnBeginDocument\n") self.log.WriteText("wx.Printout.OnBeginDocument\n")
return self.base_OnBeginDocument(start, end) return self.base_OnBeginDocument(start, end)
def OnEndDocument(self): def OnEndDocument(self):
self.log.WriteText("wxPrintout.OnEndDocument\n") self.log.WriteText("wx.Printout.OnEndDocument\n")
self.base_OnEndDocument() self.base_OnEndDocument()
def OnBeginPrinting(self): def OnBeginPrinting(self):
self.log.WriteText("wxPrintout.OnBeginPrinting\n") self.log.WriteText("wx.Printout.OnBeginPrinting\n")
self.base_OnBeginPrinting() self.base_OnBeginPrinting()
def OnEndPrinting(self): def OnEndPrinting(self):
self.log.WriteText("wxPrintout.OnEndPrinting\n") self.log.WriteText("wx.Printout.OnEndPrinting\n")
self.base_OnEndPrinting() self.base_OnEndPrinting()
def OnPreparePrinting(self): def OnPreparePrinting(self):
self.log.WriteText("wxPrintout.OnPreparePrinting\n") self.log.WriteText("wx.Printout.OnPreparePrinting\n")
self.base_OnPreparePrinting() self.base_OnPreparePrinting()
def HasPage(self, page): def HasPage(self, page):
self.log.WriteText("wxPrintout.HasPage: %d\n" % page) self.log.WriteText("wx.Printout.HasPage: %d\n" % page)
if page <= 2: if page <= 2:
return True return True
else: else:
return False return False
def GetPageInfo(self): def GetPageInfo(self):
self.log.WriteText("wxPrintout.GetPageInfo\n") self.log.WriteText("wx.Printout.GetPageInfo\n")
return (1, 2, 1, 2) return (1, 2, 1, 2)
def OnPrintPage(self, page): def OnPrintPage(self, page):
self.log.WriteText("wxPrintout.OnPrintPage: %d\n" % page) self.log.WriteText("wx.Printout.OnPrintPage: %d\n" % page)
dc = self.GetDC() dc = self.GetDC()
#------------------------------------------- #-------------------------------------------
@@ -88,41 +98,40 @@ class MyPrintout(wxPrintout):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPrintPanel(wxPanel): class TestPrintPanel(wx.Panel):
def __init__(self, parent, frame, log): def __init__(self, parent, frame, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.log = log self.log = log
self.frame = frame self.frame = frame
self.printData = wx.PrintData()
self.printData.SetPaperId(wx.PAPER_LETTER)
self.printData = wxPrintData() self.box = wx.BoxSizer(wx.VERTICAL)
self.printData.SetPaperId(wxPAPER_LETTER) self.canvas = wxScrolledWindow.MyCanvas(self)
self.box.Add(self.canvas, 1, wx.GROW)
self.box = wxBoxSizer(wxVERTICAL) subbox = wx.BoxSizer(wx.HORIZONTAL)
self.canvas = MyCanvas(self) btn = wx.Button(self, ID_Setup, "Print Setup")
self.box.Add(self.canvas, 1, wxGROW) self.Bind(wx.EVT_BUTTON, self.OnPrintSetup, id=ID_Setup)
subbox.Add(btn, 1, wx.GROW | wx.ALL, 2)
subbox = wxBoxSizer(wxHORIZONTAL) btn = wx.Button(self, ID_Preview, "Print Preview")
btn = wxButton(self, 1201, "Print Setup") self.Bind(wx.EVT_BUTTON, self.OnPrintPreview, id=ID_Preview)
EVT_BUTTON(self, 1201, self.OnPrintSetup) subbox.Add(btn, 1, wx.GROW | wx.ALL, 2)
subbox.Add(btn, 1, wxGROW | wxALL, 2)
btn = wxButton(self, 1202, "Print Preview") btn = wx.Button(self, ID_Print, "Print")
EVT_BUTTON(self, 1202, self.OnPrintPreview) self.Bind(wx.EVT_BUTTON, self.OnDoPrint, id=ID_Print)
subbox.Add(btn, 1, wxGROW | wxALL, 2) subbox.Add(btn, 1, wx.GROW | wx.ALL, 2)
btn = wxButton(self, 1203, "Print") self.box.Add(subbox, 0, wx.GROW)
EVT_BUTTON(self, 1203, self.OnDoPrint)
subbox.Add(btn, 1, wxGROW | wxALL, 2)
self.box.Add(subbox, 0, wxGROW)
self.SetAutoLayout(True) self.SetAutoLayout(True)
self.SetSizer(self.box) self.SetSizer(self.box)
def OnPrintSetup(self, event): def OnPrintSetup(self, event):
printerDialog = wxPrintDialog(self) printerDialog = wx.PrintDialog(self)
printerDialog.GetPrintDialogData().SetPrintData(self.printData) printerDialog.GetPrintDialogData().SetPrintData(self.printData)
printerDialog.GetPrintDialogData().SetSetupDialog(True) printerDialog.GetPrintDialogData().SetSetupDialog(True)
printerDialog.ShowModal(); printerDialog.ShowModal();
@@ -134,12 +143,13 @@ class TestPrintPanel(wxPanel):
self.log.WriteText("OnPrintPreview\n") self.log.WriteText("OnPrintPreview\n")
printout = MyPrintout(self.canvas, self.log) printout = MyPrintout(self.canvas, self.log)
printout2 = MyPrintout(self.canvas, self.log) printout2 = MyPrintout(self.canvas, self.log)
self.preview = wxPrintPreview(printout, printout2, self.printData) self.preview = wx.PrintPreview(printout, printout2, self.printData)
if not self.preview.Ok(): if not self.preview.Ok():
self.log.WriteText("Houston, we have a problem...\n") self.log.WriteText("Houston, we have a problem...\n")
return return
frame = wxPreviewFrame(self.preview, self.frame, "This is a print preview") frame = wx.PreviewFrame(self.preview, self.frame, "This is a print preview")
frame.Initialize() frame.Initialize()
frame.SetPosition(self.frame.GetPosition()) frame.SetPosition(self.frame.GetPosition())
@@ -149,12 +159,13 @@ class TestPrintPanel(wxPanel):
def OnDoPrint(self, event): def OnDoPrint(self, event):
pdd = wxPrintDialogData() pdd = wx.PrintDialogData()
pdd.SetPrintData(self.printData) pdd.SetPrintData(self.printData)
printer = wxPrinter(pdd) printer = wx.Printer(pdd)
printout = MyPrintout(self.canvas, self.log) printout = MyPrintout(self.canvas, self.log)
if not printer.Print(self.frame, printout): if not printer.Print(self.frame, printout):
wxMessageBox("There was a problem printing.\nPerhaps your current printer is not set correctly?", "Printing", wxOK) wx.MessageBox("There was a problem printing.\nPerhaps your current printer is not set correctly?", "Printing", wx.OK)
else: else:
self.printData = printer.GetPrintDialogData().GetPrintData() self.printData = printer.GetPrintDialogData().GetPrintData()
printout.Destroy() printout.Destroy()
@@ -174,12 +185,48 @@ def runTest(frame, nb, log):
overview = """\ overview = """\
<html>
<body>
<h1>PrintFramework</h1>
This is an overview of the classes and methods used to print documents.
It also demonstrates how to do print previews and invoke the printer
setup dialog.
<p>Classes demonstrated here:<P>
<ul>
<li><b>wx.Printout()</b> - This class encapsulates the functionality of printing out
an application document. A new class must be derived and members overridden
to respond to calls such as OnPrintPage and HasPage. Instances of this class
are passed to wx.Printer.Print() or a wx.PrintPreview object to initiate
printing or previewing.<P><p>
<li><b>wx.PrintData()</b> - This class holds a variety of information related to
printers and printer device contexts. This class is used to create a
wx.PrinterDC and a wx.PostScriptDC. It is also used as a data member of
wx.PrintDialogData and wx.PageSetupDialogData, as part of the mechanism for
transferring data between the print dialogs and the application.<p><p>
<li><b>wx.PrintDialog()</b> - This class represents the print and print setup
common dialogs. You may obtain a wx.PrinterDC device context from a
successfully dismissed print dialog.<p><p>
<li><b>wx.PrintPreview()</b> - Objects of this class manage the print preview
process. The object is passed a wx.Printout object, and the wx.PrintPreview
object itself is passed to a wx.PreviewFrame object. Previewing is started by
initializing and showing the preview frame. Unlike wxPrinter.Print, flow of
control returns to the application immediately after the frame is shown.<p><p>
</ul>
<p>Other classes are also demonstrated, but this is the gist of the printer interface
framework in wxPython.
</body>
</html>
""" """
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run

View File

@@ -1,6 +1,9 @@
# 11/13/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wx import py import wx.py as py
#---------------------------------------------------------------------- #----------------------------------------------------------------------

View File

@@ -1,7 +1,9 @@
# 11/13/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
import wx.py as py
from wx import py
#---------------------------------------------------------------------- #----------------------------------------------------------------------

View File

@@ -1,24 +1,43 @@
# 11/13/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import *
import sys import sys
import wx
#---------------------------------------------------------------------- #----------------------------------------------------------------------
myEVT_BUTTON_CLICKPOS = wxNewEventType() # This shows the new 'official' way to do custom events as derived
# from the wxPython 2.5 migration guide.
def EVT_BUTTON_CLICKPOS(win, id, func): #######################################################\
win.Connect(id, -1, myEVT_BUTTON_CLICKPOS, func) # *** Old and busted *** |
# |
# myEVT_BUTTON_CLICKPOS = wx.NewEventType() |
# |
# def EVT_BUTTON_CLICKPOS(win, id, func): |
# win.Connect(id, -1, myEVT_BUTTON_CLICKPOS, func) |
#######################################################/
#############################\
# *** The new Hottness *** |
#############################/
myEVT_BUTTON_CLICKPOS = wx.NewEventType()
EVT_BUTTON_CLICKPOS = wx.PyEventBinder(myEVT_BUTTON_CLICKPOS, 1)
#----------------------------------------------------------------------
class MyEvent(wx.PyCommandEvent):
class MyEvent(wxPyCommandEvent):
def __init__(self, evtType, id): def __init__(self, evtType, id):
wxPyCommandEvent.__init__(self, evtType, id) wx.PyCommandEvent.__init__(self, evtType, id)
self.myVal = None self.myVal = None
#def __del__(self): #def __del__(self):
# print '__del__' # print '__del__'
# wxPyCommandEvent.__del__(self) # wx.PyCommandEvent.__del__(self)
def SetMyVal(self, val): def SetMyVal(self, val):
self.myVal = val self.myVal = val
@@ -27,11 +46,10 @@ class MyEvent(wxPyCommandEvent):
return self.myVal return self.myVal
class MyButton(wx.Button):
class MyButton(wxButton):
def __init__(self, parent, id, txt, pos): def __init__(self, parent, id, txt, pos):
wxButton.__init__(self, parent, id, txt, pos) wx.Button.__init__(self, parent, id, txt, pos)
EVT_LEFT_DOWN(self, self.OnLeftDown) self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
def OnLeftDown(self, event): def OnLeftDown(self, event):
pt = event.GetPosition() pt = event.GetPosition()
@@ -44,17 +62,21 @@ class MyButton(wxButton):
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.log = log self.log = log
b = MyButton(self, -1, " Click me ", wxPoint(30,30)) b = MyButton(self, -1, " Click me ", (30,30))
EVT_BUTTON(self, b.GetId(), self.OnClick) self.Bind(wx.EVT_BUTTON, self.OnClick, id=b.GetId())
EVT_BUTTON_CLICKPOS(self, b.GetId(), self.OnMyEvent)
wxStaticText(self, -1, "Please see the Overview and Demo Code for details...", # This is our custom event binder created above.
wxPoint(30, 80)) self.Bind(EVT_BUTTON_CLICKPOS, self.OnMyEvent, id=b.GetId())
wx.StaticText(
self, -1, "Please see the Overview and Demo Code for details...",
(30, 80)
)
def OnClick(self, event): def OnClick(self, event):
@@ -74,17 +96,15 @@ def runTest(frame, nb, log):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
overview = """\ overview = """\
This demo is a contrived example of defining an event class in wxPython and sending it up the containment hierarchy for processing. This demo is a contrived example of defining an event class in wxPython and
sending it up the containment hierarchy for processing.
V2.5 note: this demo also shows the new style of creating event binders that
is required if you used the *.Bind() method of setting up event handlers.
""" """
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run

View File

@@ -1,15 +1,24 @@
# 11/13/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
# o Gotta fix the overview.
#
# 11/26/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Overview fixed.
#
from wxPython.wx import * import wx
from wxPython.lib.rcsizer import RowColSizer import wx.lib.rcsizer as rcs
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent): def __init__(self, parent):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
sizer = rcs.RowColSizer()
sizer = RowColSizer()
text = "This sizer lays out it's items by row and column "\ text = "This sizer lays out it's items by row and column "\
"that are specified explicitly when the item is \n"\ "that are specified explicitly when the item is \n"\
"added to the sizer. Grid cells with nothing in "\ "added to the sizer. Grid cells with nothing in "\
@@ -17,31 +26,51 @@ class TestPanel(wxPanel):
"handled as well. Growable rows and columns are "\ "handled as well. Growable rows and columns are "\
"specified just like the wxFlexGridSizer." "specified just like the wxFlexGridSizer."
sizer.Add(wxStaticText(self, -1, text), row=1, col=1, colspan=5) sizer.Add(wx.StaticText(self, -1, text), row=1, col=1, colspan=5)
sizer.Add(wxTextCtrl(self, -1, "(3,1)"), flag=wxEXPAND, row=3, col=1) sizer.Add(wx.TextCtrl(self, -1, "(3,1)"), flag=wx.EXPAND, row=3, col=1)
sizer.Add(wxTextCtrl(self, -1, "(3,2)"), row=3, col=2) sizer.Add(wx.TextCtrl(self, -1, "(3,2)"), row=3, col=2)
sizer.Add(wxTextCtrl(self, -1, "(3,3)"), row=3, col=3) sizer.Add(wx.TextCtrl(self, -1, "(3,3)"), row=3, col=3)
sizer.Add(wxTextCtrl(self, -1, "(3,4)"), row=3, col=4) sizer.Add(wx.TextCtrl(self, -1, "(3,4)"), row=3, col=4)
sizer.Add(wxTextCtrl(self, -1, "(4,2) span:(2,2)"), flag=wxEXPAND, sizer.Add(
row=4, col=2, rowspan=2, colspan=2) wx.TextCtrl(self, -1, "(4,2) span:(2,2)"),
sizer.Add(wxTextCtrl(self, -1, "(6,4)"), row=6, col=4) flag=wx.EXPAND, row=4, col=2, rowspan=2, colspan=2
sizer.Add(wxTextCtrl(self, -1, "(7,2)"), row=7, col=2) )
sizer.Add(wxTextCtrl(self, -1, "(8,3)"), row=8, col=3)
sizer.Add(wxTextCtrl(self, -1, "(10,1) colspan: 4"), flag=wxEXPAND, pos=(10,1), colspan=4)
sizer.Add(wxTextCtrl(self, -1, "(3,5) rowspan: 8, growable col", style=wxTE_MULTILINE),
flag=wxEXPAND, pos=(3,5), size=(8,1))
box = wxBoxSizer(wxVERTICAL) sizer.Add(wx.TextCtrl(self, -1, "(6,4)"), row=6, col=4)
box.Add(wxButton(self, -1, "A vertical box"), flag=wxEXPAND) sizer.Add(wx.TextCtrl(self, -1, "(7,2)"), row=7, col=2)
box.Add(wxButton(self, -1, "sizer put in the"), flag=wxEXPAND) sizer.Add(wx.TextCtrl(self, -1, "(8,3)"), row=8, col=3)
box.Add(wxButton(self, -1, "RowColSizer at (12,1)"), flag=wxEXPAND) sizer.Add(
wx.TextCtrl(self, -1, "(10,1) colspan: 4"),
flag=wx.EXPAND, pos=(10,1), colspan=4
)
sizer.Add(
wx.TextCtrl(self, -1, "(3,5) rowspan: 8, growable col", style=wx.TE_MULTILINE),
flag=wx.EXPAND, pos=(3,5), size=(8,1)
)
box = wx.BoxSizer(wx.VERTICAL)
box.Add(wx.Button(self, -1, "A vertical box"), flag=wx.EXPAND)
box.Add(wx.Button(self, -1, "sizer put in the"), flag=wx.EXPAND)
box.Add(wx.Button(self, -1, "RowColSizer at (12,1)"), flag=wx.EXPAND)
sizer.Add(box, pos=(12,1)) sizer.Add(box, pos=(12,1))
sizer.Add(wxTextCtrl(self, -1, "(12,2) align bottom"), flag=wxALIGN_BOTTOM, pos=(12,2)) sizer.Add(
sizer.Add(wxTextCtrl(self, -1, "(12,3) align center"), flag=wxALIGN_CENTER_VERTICAL, pos=(12,3)) wx.TextCtrl(self, -1, "(12,2) align bottom"),
sizer.Add(wxTextCtrl(self, -1, "(12,4)"),pos=(12,4)) flag=wx.ALIGN_BOTTOM, pos=(12,2)
sizer.Add(wxTextCtrl(self, -1, "(12,5) full border"), flag=wxEXPAND|wxALL, border=15, pos=(12,5)) )
sizer.Add(
wx.TextCtrl(self, -1, "(12,3) align center"),
flag=wx.ALIGN_CENTER_VERTICAL, pos=(12,3)
)
sizer.Add(wx.TextCtrl(self, -1, "(12,4)"),pos=(12,4))
sizer.Add(
wx.TextCtrl(self, -1, "(12,5) full border"),
flag=wx.EXPAND|wx.ALL, border=15, pos=(12,5)
)
sizer.AddGrowableCol(5) sizer.AddGrowableCol(5)
sizer.AddGrowableRow(9) sizer.AddGrowableRow(9)
@@ -63,10 +92,7 @@ def runTest(frame, nb, log):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
import wxPython.lib.rcsizer overview = rcs.__doc__
overview = wxPython.lib.rcsizer.__doc__
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os

View File

@@ -1,68 +1,72 @@
# 11/13/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import * import wx
import images import images
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestFrame(wxFrame): class TestFrame(wx.Frame):
def __init__(self, parent, log): def __init__(self, parent, log):
self.log = log self.log = log
wxFrame.__init__(self, parent, -1, "Shaped Window", wx.Frame.__init__(self, parent, -1, "Shaped Window",
style = style =
wxFRAME_SHAPED wx.FRAME_SHAPED
| wxSIMPLE_BORDER | wx.SIMPLE_BORDER
| wxFRAME_NO_TASKBAR | wx.FRAME_NO_TASKBAR
| wxSTAY_ON_TOP | wx.STAY_ON_TOP
) )
self.hasShape = False self.hasShape = False
self.delta = wxPoint(0,0) self.delta = (0,0)
EVT_LEFT_DCLICK(self, self.OnDoubleClick) self.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)
EVT_LEFT_DOWN(self, self.OnLeftDown) self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
EVT_LEFT_UP(self, self.OnLeftUp) self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
EVT_MOTION(self, self.OnMouseMove) self.Bind(wx.EVT_MOTION, self.OnMouseMove)
EVT_RIGHT_UP(self, self.OnExit) self.Bind(wx.EVT_RIGHT_UP, self.OnExit)
EVT_PAINT(self, self.OnPaint) self.Bind(wx.EVT_PAINT, self.OnPaint)
self.bmp = images.getTuxBitmap() self.bmp = images.getTuxBitmap()
w, h = self.bmp.GetWidth(), self.bmp.GetHeight() w, h = self.bmp.GetWidth(), self.bmp.GetHeight()
self.SetClientSize( (w, h) ) self.SetClientSize( (w, h) )
if wxPlatform != "__WXMAC__": if wx.Platform != "__WXMAC__":
# wxMac clips the tooltip to the window shape, YUCK!!! # wxMac clips the tooltip to the window shape, YUCK!!!
self.SetToolTipString("Right-click to close the window\n" self.SetToolTipString("Right-click to close the window\n"
"Double-click the image to set/unset the window shape") "Double-click the image to set/unset the window shape")
if wxPlatform == "__WXGTK__": if wx.Platform == "__WXGTK__":
# wxGTK requires that the window be created before you can # wxGTK requires that the window be created before you can
# set its shape, so delay the call to SetWindowShape until # set its shape, so delay the call to SetWindowShape until
# this event. # this event.
EVT_WINDOW_CREATE(self, self.SetWindowShape) self.Bind(wx.EVT_WINDOW_CREATE, self.SetWindowShape)
else: else:
# On wxMSW and wxMac the window has already been created, so go for it. # On wxMSW and wxMac the window has already been created, so go for it.
self.SetWindowShape() self.SetWindowShape()
dc = wxClientDC(self) dc = wx.ClientDC(self)
dc.DrawBitmap(self.bmp, (0,0), True) dc.DrawBitmap(self.bmp, (0,0), True)
def SetWindowShape(self, *evt): def SetWindowShape(self, *evt):
# Use the bitmap's mask to determine the region # Use the bitmap's mask to determine the region
r = wxRegionFromBitmap(self.bmp) r = wx.RegionFromBitmap(self.bmp)
self.hasShape = self.SetShape(r) self.hasShape = self.SetShape(r)
def OnDoubleClick(self, evt): def OnDoubleClick(self, evt):
if self.hasShape: if self.hasShape:
self.SetShape(wxRegion()) self.SetShape(wx.Region())
self.hasShape = False self.hasShape = False
else: else:
self.SetWindowShape() self.SetWindowShape()
def OnPaint(self, evt): def OnPaint(self, evt):
dc = wxPaintDC(self) dc = wx.PaintDC(self)
dc.DrawBitmap(self.bmp, (0,0), True) dc.DrawBitmap(self.bmp, (0,0), True)
def OnExit(self, evt): def OnExit(self, evt):
@@ -71,11 +75,11 @@ class TestFrame(wxFrame):
def OnLeftDown(self, evt): def OnLeftDown(self, evt):
self.CaptureMouse() self.CaptureMouse()
pos = self.ClientToScreen(evt.GetPosition()) x, y = self.ClientToScreen(evt.GetPosition())
origin = self.GetPosition() originx, originy = self.GetPosition()
dx = pos.x - origin.x dx = x - originx
dy = pos.y - origin.y dy = y - originy
self.delta = wxPoint(dx, dy) self.delta = ((dx, dy))
def OnLeftUp(self, evt): def OnLeftUp(self, evt):
@@ -85,8 +89,8 @@ class TestFrame(wxFrame):
def OnMouseMove(self, evt): def OnMouseMove(self, evt):
if evt.Dragging() and evt.LeftIsDown(): if evt.Dragging() and evt.LeftIsDown():
pos = self.ClientToScreen(evt.GetPosition()) x, y = self.ClientToScreen(evt.GetPosition())
fp = (pos.x - self.delta.x, pos.y - self.delta.y) fp = (x - self.delta[0], y - self.delta[1])
self.Move(fp) self.Move(fp)

View File

@@ -1,77 +1,90 @@
# 11/13/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
# o Issues exist that will probably need to be addressed in the 2.5 build.
#
# 11/26/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Had to do a bit of rework for the demo; there was no panel attached
# to the demo window, so all buttons were showing as dark gray on
# dark gray. I have no idea why this didn't break before. Robin,
# please examine my changes to ensure you approve. It's rather
# hackish looking.
#
#---------------------------------------------------------------------- #----------------------------------------------------------------------
# sizer test code # sizer test code
#---------------------------------------------------------------------- #----------------------------------------------------------------------
from wxPython.wx import * import wx
from wxPython.lib.grids import wxGridSizer, wxFlexGridSizer
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def makeSimpleBox1(win): def makeSimpleBox1(win):
box = wxBoxSizer(wxHORIZONTAL) box = wx.BoxSizer(wx.HORIZONTAL)
box.Add(wxButton(win, 1010, "one"), 0, wxEXPAND) box.Add(wx.Button(win, -1, "one"), 0, wx.EXPAND)
box.Add(wxButton(win, 1010, "two"), 0, wxEXPAND) box.Add(wx.Button(win, -1, "two"), 0, wx.EXPAND)
box.Add(wxButton(win, 1010, "three"), 0, wxEXPAND) box.Add(wx.Button(win, -1, "three"), 0, wx.EXPAND)
box.Add(wxButton(win, 1010, "four"), 0, wxEXPAND) box.Add(wx.Button(win, -1, "four"), 0, wx.EXPAND)
return box return box
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def makeSimpleBox2(win): def makeSimpleBox2(win):
box = wxBoxSizer(wxVERTICAL) box = wx.BoxSizer(wx.VERTICAL)
box.Add(wxButton(win, 1010, "one"), 0, wxEXPAND) box.Add(wx.Button(win, -1, "one"), 0, wx.EXPAND)
box.Add(wxButton(win, 1010, "two"), 0, wxEXPAND) box.Add(wx.Button(win, -1, "two"), 0, wx.EXPAND)
box.Add(wxButton(win, 1010, "three"), 0, wxEXPAND) box.Add(wx.Button(win, -1, "three"), 0, wx.EXPAND)
box.Add(wxButton(win, 1010, "four"), 0, wxEXPAND) box.Add(wx.Button(win, -1, "four"), 0, wx.EXPAND)
return box return box
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def makeSimpleBox3(win): def makeSimpleBox3(win):
box = wxBoxSizer(wxHORIZONTAL) box = wx.BoxSizer(wx.HORIZONTAL)
box.Add(wxButton(win, 1010, "one"), 0, wxEXPAND) box.Add(wx.Button(win, -1, "one"), 0, wx.EXPAND)
box.Add(wxButton(win, 1010, "two"), 0, wxEXPAND) box.Add(wx.Button(win, -1, "two"), 0, wx.EXPAND)
box.Add(wxButton(win, 1010, "three"), 0, wxEXPAND) box.Add(wx.Button(win, -1, "three"), 0, wx.EXPAND)
box.Add(wxButton(win, 1010, "four"), 0, wxEXPAND) box.Add(wx.Button(win, -1, "four"), 0, wx.EXPAND)
box.Add(wxButton(win, 1010, "five"), 1, wxEXPAND) box.Add(wx.Button(win, -1, "five"), 1, wx.EXPAND)
return box return box
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def makeSimpleBox4(win): def makeSimpleBox4(win):
box = wxBoxSizer(wxHORIZONTAL) box = wx.BoxSizer(wx.HORIZONTAL)
box.Add(wxButton(win, 1010, "one"), 0, wxEXPAND) box.Add(wx.Button(win, -1, "one"), 0, wx.EXPAND)
box.Add(wxButton(win, 1010, "two"), 0, wxEXPAND) box.Add(wx.Button(win, -1, "two"), 0, wx.EXPAND)
box.Add(wxButton(win, 1010, "three"), 1, wxEXPAND) box.Add(wx.Button(win, -1, "three"), 1, wx.EXPAND)
box.Add(wxButton(win, 1010, "four"), 1, wxEXPAND) box.Add(wx.Button(win, -1, "four"), 1, wx.EXPAND)
box.Add(wxButton(win, 1010, "five"), 1, wxEXPAND) box.Add(wx.Button(win, -1, "five"), 1, wx.EXPAND)
return box return box
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def makeSimpleBox5(win): def makeSimpleBox5(win):
box = wxBoxSizer(wxHORIZONTAL) box = wx.BoxSizer(wx.HORIZONTAL)
box.Add(wxButton(win, 1010, "one"), 0, wxEXPAND) box.Add(wx.Button(win, -1, "one"), 0, wx.EXPAND)
box.Add(wxButton(win, 1010, "two"), 0, wxEXPAND) box.Add(wx.Button(win, -1, "two"), 0, wx.EXPAND)
box.Add(wxButton(win, 1010, "three"), 3, wxEXPAND) box.Add(wx.Button(win, -1, "three"), 3, wx.EXPAND)
box.Add(wxButton(win, 1010, "four"), 1, wxEXPAND) box.Add(wx.Button(win, -1, "four"), 1, wx.EXPAND)
box.Add(wxButton(win, 1010, "five"), 1, wxEXPAND) box.Add(wx.Button(win, -1, "five"), 1, wx.EXPAND)
return box return box
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def makeSimpleBox6(win): def makeSimpleBox6(win):
box = wxBoxSizer(wxHORIZONTAL) box = wx.BoxSizer(wx.HORIZONTAL)
box.Add(wxButton(win, 1010, "one"), 1, wxALIGN_TOP) box.Add(wx.Button(win, -1, "one"), 1, wx.ALIGN_TOP)
box.Add(wxButton(win, 1010, "two"), 1, wxEXPAND) box.Add(wx.Button(win, -1, "two"), 1, wx.EXPAND)
box.Add(wxButton(win, 1010, "three"), 1, wxALIGN_CENTER) box.Add(wx.Button(win, -1, "three"), 1, wx.ALIGN_CENTER)
box.Add(wxButton(win, 1010, "four"), 1, wxEXPAND) box.Add(wx.Button(win, -1, "four"), 1, wx.EXPAND)
box.Add(wxButton(win, 1010, "five"), 1, wxALIGN_BOTTOM) box.Add(wx.Button(win, -1, "five"), 1, wx.ALIGN_BOTTOM)
return box return box
@@ -105,30 +118,30 @@ def makeSimpleBox8(win):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def makeSimpleBorder1(win): def makeSimpleBorder1(win):
bdr = wxBoxSizer(wxHORIZONTAL) bdr = wx.BoxSizer(wx.HORIZONTAL)
btn = wxButton(win, 1010, "border") btn = wx.Button(win, -1, "border")
btn.SetSize(wxSize(80, 80)) btn.SetSize((80, 80))
bdr.Add(btn, 1, wxEXPAND|wxALL, 15) bdr.Add(btn, 1, wx.EXPAND|wx.ALL, 15)
return bdr return bdr
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def makeSimpleBorder2(win): def makeSimpleBorder2(win):
bdr = wxBoxSizer(wxHORIZONTAL) bdr = wx.BoxSizer(wx.HORIZONTAL)
btn = wxButton(win, 1010, "border") btn = wx.Button(win, -1, "border")
btn.SetSize(wxSize(80, 80)) btn.SetSize((80, 80))
bdr.Add(btn, 1, wxEXPAND | wxEAST | wxWEST, 15) bdr.Add(btn, 1, wx.EXPAND | wx.EAST | wx.WEST, 15)
return bdr return bdr
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def makeSimpleBorder3(win): def makeSimpleBorder3(win):
bdr = wxBoxSizer(wxHORIZONTAL) bdr = wx.BoxSizer(wx.HORIZONTAL)
btn = wxButton(win, 1010, "border") btn = wx.Button(win, -1, "border")
btn.SetSize(wxSize(80, 80)) btn.SetSize((80, 80))
bdr.Add(btn, 1, wxEXPAND | wxNORTH | wxWEST, 15) bdr.Add(btn, 1, wx.EXPAND | wx.NORTH | wx.WEST, 15)
return bdr return bdr
@@ -136,28 +149,28 @@ def makeSimpleBorder3(win):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def makeBoxInBox(win): def makeBoxInBox(win):
box = wxBoxSizer(wxVERTICAL) box = wx.BoxSizer(wx.VERTICAL)
box.Add(wxButton(win, 1010, "one"), 0, wxEXPAND) box.Add(wx.Button(win, -1, "one"), 0, wx.EXPAND)
box2 = wxBoxSizer(wxHORIZONTAL) box2 = wx.BoxSizer(wx.HORIZONTAL)
box2.Add(wxButton(win, 1010, "two"), 0, wxEXPAND) box2.Add(wx.Button(win, -1, "two"), 0, wx.EXPAND)
btn3 = wxButton(win, 1010, "three") btn3 = wx.Button(win, -1, "three")
box2.Add(btn3, 0, wxEXPAND) box2.Add(btn3, 0, wx.EXPAND)
box2.Add(wxButton(win, 1010, "four"), 0, wxEXPAND) box2.Add(wx.Button(win, -1, "four"), 0, wx.EXPAND)
box2.Add(wxButton(win, 1010, "five"), 0, wxEXPAND) box2.Add(wx.Button(win, -1, "five"), 0, wx.EXPAND)
box3 = wxBoxSizer(wxVERTICAL) box3 = wx.BoxSizer(wx.VERTICAL)
box3.AddMany([ (wxButton(win, 1010, "six"), 0, wxEXPAND), box3.AddMany([ (wx.Button(win, -1, "six"), 0, wx.EXPAND),
(wxButton(win, 1010, "seven"), 2, wxEXPAND), (wx.Button(win, -1, "seven"), 2, wx.EXPAND),
(wxButton(win, 1010, "eight"), 1, wxEXPAND), (wx.Button(win, -1, "eight"), 1, wx.EXPAND),
(wxButton(win, 1010, "nine"), 1, wxEXPAND), (wx.Button(win, -1, "nine"), 1, wx.EXPAND),
]) ])
box2.Add(box3, 1, wxEXPAND) box2.Add(box3, 1, wx.EXPAND)
box.Add(box2, 1, wxEXPAND) box.Add(box2, 1, wx.EXPAND)
box.Add(wxButton(win, 1010, "ten"), 0, wxEXPAND) box.Add(wx.Button(win, -1, "ten"), 0, wx.EXPAND)
##box.Hide(btn3) ##box.Hide(btn3)
@@ -166,43 +179,43 @@ def makeBoxInBox(win):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def makeBoxInBorder(win): def makeBoxInBorder(win):
bdr = wxBoxSizer(wxHORIZONTAL) bdr = wx.BoxSizer(wx.HORIZONTAL)
box = makeSimpleBox3(win) box = makeSimpleBox3(win)
bdr.Add(box, 1, wxEXPAND | wxALL, 15) bdr.Add(box, 1, wx.EXPAND | wx.ALL, 15)
return bdr return bdr
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def makeBorderInBox(win): def makeBorderInBox(win):
insideBox = wxBoxSizer(wxHORIZONTAL) insideBox = wx.BoxSizer(wx.HORIZONTAL)
box2 = wxBoxSizer(wxHORIZONTAL) box2 = wx.BoxSizer(wx.HORIZONTAL)
box2.AddMany([ (wxButton(win, 1010, "one"), 0, wxEXPAND), box2.AddMany([ (wx.Button(win, -1, "one"), 0, wx.EXPAND),
(wxButton(win, 1010, "two"), 0, wxEXPAND), (wx.Button(win, -1, "two"), 0, wx.EXPAND),
(wxButton(win, 1010, "three"), 0, wxEXPAND), (wx.Button(win, -1, "three"), 0, wx.EXPAND),
(wxButton(win, 1010, "four"), 0, wxEXPAND), (wx.Button(win, -1, "four"), 0, wx.EXPAND),
(wxButton(win, 1010, "five"), 0, wxEXPAND), (wx.Button(win, -1, "five"), 0, wx.EXPAND),
]) ])
insideBox.Add(box2, 0, wxEXPAND) insideBox.Add(box2, 0, wx.EXPAND)
bdr = wxBoxSizer(wxHORIZONTAL) bdr = wx.BoxSizer(wx.HORIZONTAL)
bdr.Add(wxButton(win, 1010, "border"), 1, wxEXPAND | wxALL) bdr.Add(wx.Button(win, -1, "border"), 1, wx.EXPAND | wx.ALL)
insideBox.Add(bdr, 1, wxEXPAND | wxALL, 20) insideBox.Add(bdr, 1, wx.EXPAND | wx.ALL, 20)
box3 = wxBoxSizer(wxVERTICAL) box3 = wx.BoxSizer(wx.VERTICAL)
box3.AddMany([ (wxButton(win, 1010, "six"), 0, wxEXPAND), box3.AddMany([ (wx.Button(win, -1, "six"), 0, wx.EXPAND),
(wxButton(win, 1010, "seven"), 2, wxEXPAND), (wx.Button(win, -1, "seven"), 2, wx.EXPAND),
(wxButton(win, 1010, "eight"), 1, wxEXPAND), (wx.Button(win, -1, "eight"), 1, wx.EXPAND),
(wxButton(win, 1010, "nine"), 1, wxEXPAND), (wx.Button(win, -1, "nine"), 1, wx.EXPAND),
]) ])
insideBox.Add(box3, 1, wxEXPAND) insideBox.Add(box3, 1, wx.EXPAND)
outsideBox = wxBoxSizer(wxVERTICAL) outsideBox = wx.BoxSizer(wx.VERTICAL)
outsideBox.Add(wxButton(win, 1010, "top"), 0, wxEXPAND) outsideBox.Add(wx.Button(win, -1, "top"), 0, wx.EXPAND)
outsideBox.Add(insideBox, 1, wxEXPAND) outsideBox.Add(insideBox, 1, wx.EXPAND)
outsideBox.Add(wxButton(win, 1010, "bottom"), 0, wxEXPAND) outsideBox.Add(wx.Button(win, -1, "bottom"), 0, wx.EXPAND)
return outsideBox return outsideBox
@@ -210,18 +223,18 @@ def makeBorderInBox(win):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def makeGrid1(win): def makeGrid1(win):
gs = wxGridSizer(3, 3, 2, 2) # rows, cols, hgap, vgap gs = wx.GridSizer(3, 3, 2, 2) # rows, cols, hgap, vgap
gs.AddMany([ (wxButton(win, 1010, 'one'), 0, wxEXPAND), gs.AddMany([ (wx.Button(win, -1, 'one'), 0, wx.EXPAND),
(wxButton(win, 1010, 'two'), 0, wxEXPAND), (wx.Button(win, -1, 'two'), 0, wx.EXPAND),
(wxButton(win, 1010, 'three'), 0, wxEXPAND), (wx.Button(win, -1, 'three'), 0, wx.EXPAND),
(wxButton(win, 1010, 'four'), 0, wxEXPAND), (wx.Button(win, -1, 'four'), 0, wx.EXPAND),
(wxButton(win, 1010, 'five'), 0, wxEXPAND), (wx.Button(win, -1, 'five'), 0, wx.EXPAND),
#(75, 50), #(75, 50),
(wxButton(win, 1010, 'six'), 0, wxEXPAND), (wx.Button(win, -1, 'six'), 0, wx.EXPAND),
(wxButton(win, 1010, 'seven'), 0, wxEXPAND), (wx.Button(win, -1, 'seven'), 0, wx.EXPAND),
(wxButton(win, 1010, 'eight'), 0, wxEXPAND), (wx.Button(win, -1, 'eight'), 0, wx.EXPAND),
(wxButton(win, 1010, 'nine'), 0, wxEXPAND), (wx.Button(win, -1, 'nine'), 0, wx.EXPAND),
]) ])
return gs return gs
@@ -229,27 +242,27 @@ def makeGrid1(win):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def makeGrid2(win): def makeGrid2(win):
gs = wxGridSizer(3, 3) # rows, cols, hgap, vgap gs = wx.GridSizer(3, 3) # rows, cols, hgap, vgap
box = wxBoxSizer(wxVERTICAL) box = wx.BoxSizer(wx.VERTICAL)
box.Add(wxButton(win, 1010, 'A'), 0, wxEXPAND) box.Add(wx.Button(win, -1, 'A'), 0, wx.EXPAND)
box.Add(wxButton(win, 1010, 'B'), 1, wxEXPAND) box.Add(wx.Button(win, -1, 'B'), 1, wx.EXPAND)
gs2 = wxGridSizer(2,2, 4, 4) gs2 = wx.GridSizer(2,2, 4, 4)
gs2.AddMany([ (wxButton(win, 1010, 'C'), 0, wxEXPAND), gs2.AddMany([ (wx.Button(win, -1, 'C'), 0, wx.EXPAND),
(wxButton(win, 1010, 'E'), 0, wxEXPAND), (wx.Button(win, -1, 'E'), 0, wx.EXPAND),
(wxButton(win, 1010, 'F'), 0, wxEXPAND), (wx.Button(win, -1, 'F'), 0, wx.EXPAND),
(wxButton(win, 1010, 'G'), 0, wxEXPAND)]) (wx.Button(win, -1, 'G'), 0, wx.EXPAND)])
gs.AddMany([ (wxButton(win, 1010, 'one'), 0, wxALIGN_RIGHT | wxALIGN_BOTTOM), gs.AddMany([ (wx.Button(win, -1, 'one'), 0, wx.ALIGN_RIGHT | wx.ALIGN_BOTTOM),
(wxButton(win, 1010, 'two'), 0, wxEXPAND), (wx.Button(win, -1, 'two'), 0, wx.EXPAND),
(wxButton(win, 1010, 'three'), 0, wxALIGN_LEFT | wxALIGN_BOTTOM), (wx.Button(win, -1, 'three'), 0, wx.ALIGN_LEFT | wx.ALIGN_BOTTOM),
(wxButton(win, 1010, 'four'), 0, wxEXPAND), (wx.Button(win, -1, 'four'), 0, wx.EXPAND),
(wxButton(win, 1010, 'five'), 0, wxALIGN_CENTER), (wx.Button(win, -1, 'five'), 0, wx.ALIGN_CENTER),
(wxButton(win, 1010, 'six'), 0, wxEXPAND), (wx.Button(win, -1, 'six'), 0, wx.EXPAND),
(box, 0, wxEXPAND | wxALL, 10), (box, 0, wx.EXPAND | wx.ALL, 10),
(wxButton(win, 1010, 'eight'), 0, wxEXPAND), (wx.Button(win, -1, 'eight'), 0, wx.EXPAND),
(gs2, 0, wxEXPAND | wxALL, 4), (gs2, 0, wx.EXPAND | wx.ALL, 4),
]) ])
return gs return gs
@@ -257,18 +270,18 @@ def makeGrid2(win):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def makeGrid3(win): def makeGrid3(win):
gs = wxFlexGridSizer(3, 3, 2, 2) # rows, cols, hgap, vgap gs = wx.FlexGridSizer(3, 3, 2, 2) # rows, cols, hgap, vgap
gs.AddMany([ (wxButton(win, 1010, 'one'), 0, wxEXPAND), gs.AddMany([ (wx.Button(win, -1, 'one'), 0, wx.EXPAND),
(wxButton(win, 1010, 'two'), 0, wxEXPAND), (wx.Button(win, -1, 'two'), 0, wx.EXPAND),
(wxButton(win, 1010, 'three'), 0, wxEXPAND), (wx.Button(win, -1, 'three'), 0, wx.EXPAND),
(wxButton(win, 1010, 'four'), 0, wxEXPAND), (wx.Button(win, -1, 'four'), 0, wx.EXPAND),
#(wxButton(win, 1010, 'five'), 0, wxEXPAND), #(wxButton(win, 1010, 'five'), 0, wxEXPAND),
(175, 50), ((175, 50)),
(wxButton(win, 1010, 'six'), 0, wxEXPAND), (wx.Button(win, -1, 'six'), 0, wx.EXPAND),
(wxButton(win, 1010, 'seven'), 0, wxEXPAND), (wx.Button(win, -1, 'seven'), 0, wx.EXPAND),
(wxButton(win, 1010, 'eight'), 0, wxEXPAND), (wx.Button(win, -1, 'eight'), 0, wx.EXPAND),
(wxButton(win, 1010, 'nine'), 0, wxEXPAND), (wx.Button(win, -1, 'nine'), 0, wx.EXPAND),
]) ])
gs.AddGrowableRow(0) gs.AddGrowableRow(0)
@@ -279,28 +292,28 @@ def makeGrid3(win):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def makeGrid4(win): def makeGrid4(win):
bpos = wxDefaultPosition bpos = wx.DefaultPosition
bsize = wxSize(100, 50) bsize = wx.Size(100, 50)
gs = wxGridSizer(3, 3, 2, 2) # rows, cols, hgap, vgap gs = wx.GridSizer(3, 3, 2, 2) # rows, cols, hgap, vgap
gs.AddMany([ (wxButton(win, 1010, 'one', bpos, bsize), gs.AddMany([ (wx.Button(win, -1, 'one', bpos, bsize),
0, wxALIGN_TOP | wxALIGN_LEFT ), 0, wx.ALIGN_TOP | wx.ALIGN_LEFT ),
(wxButton(win, 1010, 'two', bpos, bsize), (wx.Button(win, -1, 'two', bpos, bsize),
0, wxALIGN_TOP | wxALIGN_CENTER_HORIZONTAL ), 0, wx.ALIGN_TOP | wx.ALIGN_CENTER_HORIZONTAL ),
(wxButton(win, 1010, 'three', bpos, bsize), (wx.Button(win, -1, 'three', bpos, bsize),
0, wxALIGN_TOP | wxALIGN_RIGHT ), 0, wx.ALIGN_TOP | wx.ALIGN_RIGHT ),
(wxButton(win, 1010, 'four', bpos, bsize), (wx.Button(win, -1, 'four', bpos, bsize),
0, wxALIGN_CENTER_VERTICAL | wxALIGN_LEFT ), 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT ),
(wxButton(win, 1010, 'five', bpos, bsize), (wx.Button(win, -1, 'five', bpos, bsize),
0, wxALIGN_CENTER ), 0, wx.ALIGN_CENTER ),
(wxButton(win, 1010, 'six', bpos, bsize), (wx.Button(win, -1, 'six', bpos, bsize),
0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT ), 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT ),
(wxButton(win, 1010, 'seven', bpos, bsize), (wx.Button(win, -1, 'seven', bpos, bsize),
0, wxALIGN_BOTTOM | wxALIGN_LEFT ), 0, wx.ALIGN_BOTTOM | wx.ALIGN_LEFT ),
(wxButton(win, 1010, 'eight', bpos, bsize), (wx.Button(win, -1, 'eight', bpos, bsize),
0, wxALIGN_BOTTOM | wxALIGN_CENTER_HORIZONTAL ), 0, wx.ALIGN_BOTTOM | wx.ALIGN_CENTER_HORIZONTAL ),
(wxButton(win, 1010, 'nine', bpos, bsize), (wx.Button(win, -1, 'nine', bpos, bsize),
0, wxALIGN_BOTTOM | wxALIGN_RIGHT ), 0, wx.ALIGN_BOTTOM | wx.ALIGN_RIGHT ),
]) ])
return gs return gs
@@ -308,28 +321,28 @@ def makeGrid4(win):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def makeShapes(win): def makeShapes(win):
bpos = wxDefaultPosition bpos = wx.DefaultPosition
bsize = wxSize(100, 50) bsize = wx.Size(100, 50)
gs = wxGridSizer(3, 3, 2, 2) # rows, cols, hgap, vgap gs = wx.GridSizer(3, 3, 2, 2) # rows, cols, hgap, vgap
gs.AddMany([ (wxButton(win, 1010, 'one', bpos, bsize), gs.AddMany([ (wx.Button(win, -1, 'one', bpos, bsize),
0, wxSHAPED | wxALIGN_TOP | wxALIGN_LEFT ), 0, wx.SHAPED | wx.ALIGN_TOP | wx.ALIGN_LEFT ),
(wxButton(win, 1010, 'two', bpos, bsize), (wx.Button(win, -1, 'two', bpos, bsize),
0, wxSHAPED | wxALIGN_TOP | wxALIGN_CENTER_HORIZONTAL ), 0, wx.SHAPED | wx.ALIGN_TOP | wx.ALIGN_CENTER_HORIZONTAL ),
(wxButton(win, 1010, 'three', bpos, bsize), (wx.Button(win, -1, 'three', bpos, bsize),
0, wxSHAPED | wxALIGN_TOP | wxALIGN_RIGHT ), 0, wx.SHAPED | wx.ALIGN_TOP | wx.ALIGN_RIGHT ),
(wxButton(win, 1010, 'four', bpos, bsize), (wx.Button(win, -1, 'four', bpos, bsize),
0, wxSHAPED | wxALIGN_CENTER_VERTICAL | wxALIGN_LEFT ), 0, wx.SHAPED | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT ),
(wxButton(win, 1010, 'five', bpos, bsize), (wx.Button(win, -1, 'five', bpos, bsize),
0, wxSHAPED | wxALIGN_CENTER ), 0, wx.SHAPED | wx.ALIGN_CENTER ),
(wxButton(win, 1010, 'six', bpos, bsize), (wx.Button(win, -1, 'six', bpos, bsize),
0, wxSHAPED | wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT ), 0, wx.SHAPED | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT ),
(wxButton(win, 1010, 'seven', bpos, bsize), (wx.Button(win, -1, 'seven', bpos, bsize),
0, wxSHAPED | wxALIGN_BOTTOM | wxALIGN_LEFT ), 0, wx.SHAPED | wx.ALIGN_BOTTOM | wx.ALIGN_LEFT ),
(wxButton(win, 1010, 'eight', bpos, bsize), (wx.Button(win, -1, 'eight', bpos, bsize),
0, wxSHAPED | wxALIGN_BOTTOM | wxALIGN_CENTER_HORIZONTAL ), 0, wx.SHAPED | wx.ALIGN_BOTTOM | wx.ALIGN_CENTER_HORIZONTAL ),
(wxButton(win, 1010, 'nine', bpos, bsize), (wx.Button(win, -1, 'nine', bpos, bsize),
0, wxSHAPED | wxALIGN_BOTTOM | wxALIGN_RIGHT ), 0, wx.SHAPED | wx.ALIGN_BOTTOM | wx.ALIGN_RIGHT ),
]) ])
return gs return gs
@@ -337,12 +350,12 @@ def makeShapes(win):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def makeSimpleBoxShaped(win): def makeSimpleBoxShaped(win):
box = wxBoxSizer(wxHORIZONTAL) box = wx.BoxSizer(wx.HORIZONTAL)
box.Add(wxButton(win, 1010, "one"), 0, wxEXPAND) box.Add(wx.Button(win, -1, "one"), 0, wx.EXPAND)
box.Add(wxButton(win, 1010, "two"), 0, wxEXPAND) box.Add(wx.Button(win, -1, "two"), 0, wx.EXPAND)
box.Add(wxButton(win, 1010, "three"), 0, wxEXPAND) box.Add(wx.Button(win, -1, "three"), 0, wx.EXPAND)
box.Add(wxButton(win, 1010, "four"), 0, wxEXPAND) box.Add(wx.Button(win, -1, "four"), 0, wx.EXPAND)
box.Add(wxButton(win, 1010, "five"), 1, wxSHAPED) box.Add(wx.Button(win, -1, "five"), 1, wx.SHAPED)
return box return box
@@ -393,14 +406,14 @@ theTests = [
), ),
# ("Percent Sizer", makeSimpleBox6, # ("Percent Sizer", makeSimpleBox6,
# "You can use the wxBoxSizer like a Percent Sizer. Just make sure that all " # "You can use the wx.BoxSizer like a Percent Sizer. Just make sure that all "
# "the weighting factors add up to 100!" # "the weighting factors add up to 100!"
# ), # ),
("", None, ""), ("", None, ""),
("Simple border sizer", makeSimpleBorder1, ("Simple border sizer", makeSimpleBorder1,
"The wxBoxSizer can leave empty space around its contents. This one " "The wx.BoxSizer can leave empty space around its contents. This one "
"gives a border all the way around." "gives a border all the way around."
), ),
@@ -471,19 +484,22 @@ theTests = [
] ]
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestFrame(wxFrame): class TestFrame(wx.Frame):
def __init__(self, parent, title, sizerFunc): def __init__(self, parent, title, sizerFunc):
wxFrame.__init__(self, parent, -1, title) wx.Frame.__init__(self, parent, -1, title)
EVT_BUTTON(self, 1010, self.OnButton) self.Bind(wx.EVT_BUTTON, self.OnButton)
self.sizer = sizerFunc(self) p = wx.Panel(self, -1)
self.sizer = sizerFunc(p)
self.CreateStatusBar() self.CreateStatusBar()
self.SetStatusText("Resize this frame to see how the sizers respond...") self.SetStatusText("Resize this frame to see how the sizers respond...")
self.sizer.Fit(self) self.sizer.Fit(p)
self.SetAutoLayout(True) p.SetAutoLayout(True)
self.SetSizer(self.sizer) p.SetSizer(self.sizer)
EVT_CLOSE(self, self.OnCloseWindow) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
self.Fit()
def OnCloseWindow(self, event): def OnCloseWindow(self, event):
self.MakeModal(False) self.MakeModal(False)
@@ -496,30 +512,29 @@ class TestFrame(wxFrame):
class TestSelectionPanel(wxPanel): class TestSelectionPanel(wx.Panel):
def __init__(self, parent, frame): def __init__(self, parent, frame):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.frame = frame self.frame = frame
self.list = wxListBox(self, 401, self.list = wx.ListBox(self, -1,
wxDLG_PNT(self, 10, 10), wxDLG_SZE(self, 100, 100), wx.DLG_PNT(self, 10, 10), wx.DLG_SZE(self, 100, 100),
[]) [])
EVT_LISTBOX(self, 401, self.OnSelect) self.Bind(wx.EVT_LISTBOX, self.OnSelect, id=self.list.GetId())
EVT_LISTBOX_DCLICK(self, 401, self.OnDClick) self.Bind(wx.EVT_LISTBOX_DCLICK, self.OnDClick, id=self.list.GetId())
self.btn = wxButton(self, 402, "Try it!", wxDLG_PNT(self, 120, 10)).SetDefault() self.btn = wx.Button(self, -1, "Try it!", wx.DLG_PNT(self, 120, 10)).SetDefault()
EVT_BUTTON(self, 402, self.OnDClick) self.Bind(wx.EVT_BUTTON, self.OnDClick)
self.text = wxTextCtrl(self, -1, "", self.text = wx.TextCtrl(self, -1, "",
wxDLG_PNT(self, 10, 115), wx.DLG_PNT(self, 10, 115),
wxDLG_SZE(self, 200, 50), wx.DLG_SZE(self, 200, 50),
wxTE_MULTILINE | wxTE_READONLY) wx.TE_MULTILINE | wx.TE_READONLY)
for item in theTests: for item in theTests:
self.list.Append(item[0]) self.list.Append(item[0])
def OnSelect(self, event): def OnSelect(self, event):
pos = self.list.GetSelection() pos = self.list.GetSelection()
self.text.SetValue(theTests[pos][2]) self.text.SetValue(theTests[pos][2])
@@ -532,7 +547,7 @@ class TestSelectionPanel(wxPanel):
if func: if func:
win = TestFrame(self, title, func) win = TestFrame(self, title, func)
win.CentreOnParent(wxBOTH) win.CentreOnParent(wx.BOTH)
win.Show(True) win.Show(True)
win.MakeModal(True) win.MakeModal(True)
@@ -549,24 +564,22 @@ overview = ""
#---------------------------------------------------------------------- #----------------------------------------------------------------------
if __name__ == '__main__': if __name__ == '__main__':
class MainFrame(wxFrame): class MainFrame(wx.Frame):
def __init__(self): def __init__(self):
wxFrame.__init__(self, None, -1, "Testing...") wx.Frame.__init__(self, None, -1, "Testing...")
self.CreateStatusBar() self.CreateStatusBar()
mainmenu = wxMenuBar() mainmenu = wx.MenuBar()
menu = wxMenu() menu = wx.Menu()
menu.Append(200, 'E&xit', 'Get the heck outta here!') menu.Append(200, 'E&xit', 'Get the heck outta here!')
mainmenu.Append(menu, "&File") mainmenu.Append(menu, "&File")
self.SetMenuBar(mainmenu) self.SetMenuBar(mainmenu)
EVT_MENU(self, 200, self.OnExit) self.Bind(wx.EVT_MENU, self.OnExit, id=200)
self.panel = TestSelectionPanel(self, self) self.panel = TestSelectionPanel(self, self)
self.SetSize(wxSize(400, 380)) self.SetSize((400, 380))
EVT_CLOSE(self, self.OnCloseWindow) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
def OnCloseWindow(self, event): def OnCloseWindow(self, event):
self.Destroy() self.Destroy()
@@ -575,14 +588,14 @@ if __name__ == '__main__':
self.Close(True) self.Close(True)
class TestApp(wxApp): class TestApp(wx.App):
def OnInit(self): def OnInit(self):
frame = MainFrame() frame = MainFrame()
frame.Show(True) frame.Show(True)
self.SetTopWindow(frame) self.SetTopWindow(frame)
return True return True
app = TestApp(0) app = TestApp(False)
app.MainLoop() app.MainLoop()

View File

@@ -1,26 +1,42 @@
from wxPython.wx import * # 11/13/2003 - Jeff Grimmett (grimmtooth@softhome.net)
from wxPython.gizmos import * #
# o Updated for wx namespace
#
# 11/26/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Bigtime errors on startup. Blows up with a program error.
# Error:
#
# 21:04:11: Debug: ..\..\src\msw\treectrl.cpp(1508): assert "IsVisible(item)"
# failed: The item you call GetNextVisible() for must be visible itself!
#
# I suspect this error is in the lib itself.
#
import wx
import wx.gizmos as gizmos
import images import images
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestTree(wxRemotelyScrolledTreeCtrl): class TestTree(gizmos.RemotelyScrolledTreeCtrl):
def __init__(self, parent, ID, pos=wxDefaultPosition, size=wxDefaultSize, def __init__(self, parent, style=wx.TR_HAS_BUTTONS):
style=wxTR_HAS_BUTTONS): gizmos.RemotelyScrolledTreeCtrl.__init__(self, parent, -1, style=style)
wxRemotelyScrolledTreeCtrl.__init__(self, parent, ID, pos, size, style)
# make an image list # make an image list
im1 = im2 = -1 im1 = im2 = -1
self.il = wxImageList(16, 16) self.il = wx.ImageList(16, 16)
im1 = self.il.Add(images.getFolder1Bitmap()) im1 = self.il.Add(images.getFolder1Bitmap())
im2 = self.il.Add(images.getFile1Bitmap()) im2 = self.il.Add(images.getFile1Bitmap())
self.SetImageList(self.il) self.SetImageList(self.il)
# Add some items # Add some items
root = self.AddRoot("Root") root = self.AddRoot("Root")
for i in range(30): for i in range(30):
item = self.AppendItem(root, "Item %d" % i, im1) item = self.AppendItem(root, "Item %d" % i, im1)
for j in range(10): for j in range(10):
child = self.AppendItem(item, "Child %d" % j, im2) child = self.AppendItem(item, "Child %d" % j, im2)
@@ -28,11 +44,11 @@ class TestTree(wxRemotelyScrolledTreeCtrl):
class TestValueWindow(wxTreeCompanionWindow): class TestValueWindow(gizmos.TreeCompanionWindow):
def __init__(self, parent, ID, pos=wxDefaultPosition, size=wxDefaultSize, style=0): def __init__(self, parent, style=0):
wxTreeCompanionWindow.__init__(self, parent, ID, pos, size, style) gizmos.TreeCompanionWindow.__init__(self, parent, -1, style=style)
self.SetBackgroundColour("WHITE") self.SetBackgroundColour("WHITE")
EVT_ERASE_BACKGROUND(self, self.OEB) self.Bind(wx.EVT_ERASE_BACKGROUND, self.OEB)
def OEB(self, evt): def OEB(self, evt):
pass pass
@@ -40,41 +56,54 @@ class TestValueWindow(wxTreeCompanionWindow):
# This method is called to draw each item in the value window # This method is called to draw each item in the value window
def DrawItem(self, dc, itemId, rect): def DrawItem(self, dc, itemId, rect):
tree = self.GetTreeCtrl() tree = self.GetTreeCtrl()
if tree: if tree:
text = "This is " text = "This is "
parent = tree.GetItemParent(itemId) parent = tree.GetItemParent(itemId)
if parent.IsOk(): if parent.IsOk():
ptext = tree.GetItemText(parent) ptext = tree.GetItemText(parent)
text = text + ptext + " --> " text = text + ptext + " --> "
text = text + tree.GetItemText(itemId) text = text + tree.GetItemText(itemId)
pen = wxPen(wxSystemSettings_GetSystemColour(wxSYS_COLOUR_3DLIGHT), 1, wxSOLID) pen = wx.Pen(
wx.SystemSettings_GetSystemColour(wx.SYS_COLOUR_3DLIGHT),
1, wx.SOLID
)
dc.SetPen(pen) dc.SetPen(pen)
dc.SetBrush(wxBrush(self.GetBackgroundColour(), wxSOLID)) dc.SetBrush(wx.Brush(self.GetBackgroundColour(), wx.SOLID))
dc.DrawRectangle(rect.x, rect.y, rect.width+1, rect.height+1) dc.DrawRectangle((rect.x, rect.y), (rect.width+1, rect.height+1))
dc.SetTextForeground("BLACK") dc.SetTextForeground("BLACK")
dc.SetBackgroundMode(wxTRANSPARENT) dc.SetBackgroundMode(wx.TRANSPARENT)
tw, th = dc.GetTextExtent(text) tw, th = dc.GetTextExtent(text)
x = 5 x = 5
y = rect.y + max(0, (rect.height - th) / 2) y = rect.y + max(0, (rect.height - th) / 2)
dc.DrawText(text, x, y) dc.DrawText(text, (x, y))
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.log = log self.log = log
scroller = wxSplitterScrolledWindow(self, -1, #(50,50), (350, 250), scroller = gizmos.SplitterScrolledWindow(
style=wxNO_BORDER | wxCLIP_CHILDREN | wxVSCROLL) self, -1, style=wx.NO_BORDER | wx.CLIP_CHILDREN | wx.VSCROLL
splitter = wxThinSplitterWindow(scroller, -1, style=wxSP_3DBORDER | wxCLIP_CHILDREN) )
splitter = gizmos.ThinSplitterWindow(
scroller, -1, style=wx.SP_3DBORDER | wx.CLIP_CHILDREN
)
splitter.SetSashSize(2) splitter.SetSashSize(2)
tree = TestTree(splitter, -1, style = wxTR_HAS_BUTTONS | tree = TestTree(splitter, -1, style = wx.TR_HAS_BUTTONS |
wxTR_NO_LINES | wx.TR_NO_LINES |
wxTR_ROW_LINES | wx.TR_ROW_LINES |
#wxTR_HIDE_ROOT | #wx.TR_HIDE_ROOT |
wxNO_BORDER ) wx.NO_BORDER )
valueWindow = TestValueWindow(splitter, -1, style=wxNO_BORDER)
valueWindow = TestValueWindow(splitter, style=wx.NO_BORDER)
splitter.SplitVertically(tree, valueWindow, 150) splitter.SplitVertically(tree, valueWindow, 150)
scroller.SetTargetWindow(tree) scroller.SetTargetWindow(tree)
@@ -83,8 +112,8 @@ class TestPanel(wxPanel):
valueWindow.SetTreeCtrl(tree) valueWindow.SetTreeCtrl(tree)
tree.SetCompanionWindow(valueWindow) tree.SetCompanionWindow(valueWindow)
sizer = wxBoxSizer(wxVERTICAL) sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(scroller, 1, wxEXPAND|wxALL, 25) sizer.Add(scroller, 1, wx.EXPAND|wx.ALL, 25)
self.SetAutoLayout(True) self.SetAutoLayout(True)
self.SetSizer(sizer) self.SetSizer(sizer)
@@ -92,8 +121,8 @@ class TestPanel(wxPanel):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def runTest(frame, nb, log): def runTest(frame, nb, log):
if wxPlatform == "__WXMAC__": if wx.Platform == "__WXMAC__":
wxMessageBox("This demo currently fails on the Mac. The problem is being looked into...", "Sorry") wx.MessageBox("This demo currently fails on the Mac. The problem is being looked into...", "Sorry")
return return
win = TestPanel(nb, log) win = TestPanel(nb, log)
@@ -103,14 +132,11 @@ def runTest(frame, nb, log):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
overview = """\ overview = """\
This demo shows a collection of classes that were designed to operate This demo shows a collection of classes that were designed to operate
together and provide a tree control with additional columns for each together and provide a tree control with additional columns for each
item. The classes are wxRemotelyScrolledTreeCtrl, wxTreeCompanionWindow, item. The classes are wx.RemotelyScrolledTreeCtrl, wx.TreeCompanionWindow,
wxThinSplitterWindow, and wxSplitterScrolledWindow, some of which may wx.ThinSplitterWindow, and wx.SplitterScrolledWindow, some of which may
also be useful by themselves. also be useful by themselves.
""" """

View File

@@ -1,9 +1,20 @@
# 11/13/2003 - Jeff Grimmett (grimmtooth@softhome.net)
from wxPython.wx import * #
from wxPython.lib.printout import PrintTable # o Updated for wx namespace
# o Color preview example generates deprecation warnings.
#
# 11/26/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Note: wx.NamedColour must remain because printout.py requiress it.
# o printout.py is generating a snootful of errors all related to the
# requirement for tuples on the base DC calls now
#
import os import os
import wx
import wx.lib.printout as printout
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
buttonDefs = { buttonDefs = {
@@ -15,21 +26,22 @@ buttonDefs = {
} }
class TablePanel(wxPanel): class TablePanel(wx.Panel):
def __init__(self, parent, log, frame): def __init__(self, parent, log, frame):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.log = log self.log = log
self.frame = frame self.frame = frame
box = wxBoxSizer(wxVERTICAL) box = wx.BoxSizer(wx.VERTICAL)
box.Add(20, 30) box.Add((20, 30))
keys = buttonDefs.keys() keys = buttonDefs.keys()
keys.sort() keys.sort()
for k in keys: for k in keys:
text = buttonDefs[k][1] text = buttonDefs[k][1]
btn = wxButton(self, k, text) btn = wx.Button(self, k, text)
box.Add(btn, 0, wxALIGN_CENTER|wxALL, 15) box.Add(btn, 0, wx.ALIGN_CENTER|wx.ALL, 15)
EVT_BUTTON(self, k, self.OnButton) self.Bind(wx.EVT_BUTTON, self.OnButton, btn)
self.SetAutoLayout(True) self.SetAutoLayout(True)
self.SetSizer(box) self.SetSizer(box)
@@ -60,7 +72,7 @@ class TablePanel(wxPanel):
def PreviewWide(self): def PreviewWide(self):
self.ReadData() self.ReadData()
prt = PrintTable(self.frame) prt = printout.PrintTable(self.frame)
prt.data = self.data prt.data = self.data
prt.left_margin = 0.5 prt.left_margin = 0.5
prt.set_column = [1.0, 1.0, 1.0, 1.5, 1.0, 3.0] prt.set_column = [1.0, 1.0, 1.0, 1.5, 1.0, 3.0]
@@ -68,14 +80,14 @@ class TablePanel(wxPanel):
prt.SetLandscape() prt.SetLandscape()
prt.SetColumnLineSize(2, 3) prt.SetColumnLineSize(2, 3)
prt.SetColumnLineColour(3, wxNamedColour('RED')) prt.SetColumnLineColour(3, wx.NamedColour('RED'))
prt.SetRowLineSize(1, 3) prt.SetRowLineSize(1, 3)
prt.SetRowLineColour(5, wxNamedColour('RED')) prt.SetRowLineColour(5, wx.NamedColour('RED'))
prt.SetHeader("wxWindows Applications") prt.SetHeader("wx.Windows Applications")
prt.SetFooter() prt.SetFooter()
prt.SetFooter("Date: ", type = "Date", align=wxALIGN_RIGHT, indent = -2, colour = wxNamedColour('RED')) prt.SetFooter("Date: ", type = "Date", align=wx.ALIGN_RIGHT, indent = -2, colour = wx.NamedColour('RED'))
prt.Preview() prt.Preview()
def PreviewNarrow(self): def PreviewNarrow(self):
@@ -87,26 +99,26 @@ class TablePanel(wxPanel):
val = self.header val = self.header
new_header = [val[0], val[1], val[2], val[4], val[5]] new_header = [val[0], val[1], val[2], val[4], val[5]]
prt = PrintTable(self.frame) prt = printout.PrintTable(self.frame)
prt.data = new_data prt.data = new_data
prt.set_column = [ 1, 1, 1, 1, 2] prt.set_column = [ 1, 1, 1, 1, 2]
prt.label = new_header prt.label = new_header
prt.SetColAlignment(1, wxALIGN_CENTRE) prt.SetColAlignment(1, wx.ALIGN_CENTRE)
prt.SetColBackgroundColour(0, wxNamedColour('RED')) prt.SetColBackgroundColour(0, wx.NamedColour('RED'))
prt.SetColTextColour(0, wxNamedColour('WHITE')) prt.SetColTextColour(0, wx.NamedColour('WHITE'))
prt.SetCellColour(4, 0, wxNamedColour('LIGHT BLUE')) prt.SetCellColour(4, 0, wx.NamedColour('LIGHT BLUE'))
prt.SetCellColour(4, 1, wxNamedColour('LIGHT BLUE')) prt.SetCellColour(4, 1, wx.NamedColour('LIGHT BLUE'))
prt.SetCellColour(17, 1, wxNamedColour('LIGHT BLUE')) prt.SetCellColour(17, 1, wx.NamedColour('LIGHT BLUE'))
prt.SetColBackgroundColour(2, wxNamedColour('LIGHT BLUE')) prt.SetColBackgroundColour(2, wx.NamedColour('LIGHT BLUE'))
prt.SetCellText(4, 2, wxNamedColour('RED')) prt.SetCellText(4, 2, wx.NamedColour('RED'))
prt.SetColTextColour(3, wxNamedColour('RED')) prt.SetColTextColour(3, wx.NamedColour('RED'))
prt.label_font_colour = wxNamedColour('WHITE') prt.label_font_colour = wx.NamedColour('WHITE')
prt.SetHeader("wxWindows Applications", colour = wxNamedColour('RED')) prt.SetHeader("wxWindows Applications", colour = wx.NamedColour('RED'))
prt.SetHeader("Printed: ", type = "Date & Time", align=wxALIGN_RIGHT, indent = -2, colour = wxNamedColour('BLUE')) prt.SetHeader("Printed: ", type = "Date & Time", align=wx.ALIGN_RIGHT, indent = -2, colour = wx.NamedColour('BLUE'))
prt.SetFooter("Page No", colour = wxNamedColour('RED'), type ="Num") prt.SetFooter("Page No", colour = wx.NamedColour('RED'), type ="Num")
prt.Preview() prt.Preview()
def OnPreviewMatrix(self): def OnPreviewMatrix(self):
@@ -121,7 +133,7 @@ class TablePanel(wxPanel):
for val in range(total_col): for val in range(total_col):
columns.append(hsize) columns.append(hsize)
prt = PrintTable(self.frame) prt = printout.PrintTable(self.frame)
for row in range(total_row): for row in range(total_row):
value = [] value = []
@@ -130,7 +142,7 @@ class TablePanel(wxPanel):
data.append(value) data.append(value)
for col in range(total_col): for col in range(total_col):
prt.SetColAlignment(col, wxALIGN_CENTRE) prt.SetColAlignment(col, wx.ALIGN_CENTRE)
prt.SetLandscape() prt.SetLandscape()
prt.text_font_size = 8 prt.text_font_size = 8
@@ -142,7 +154,7 @@ class TablePanel(wxPanel):
prt.Preview() prt.Preview()
def PreviewLine(self): def PreviewLine(self):
prt = PrintTable(self.frame) prt = printout.PrintTable(self.frame)
prt.label = ["Header 1", "Header 2", "Header 3"] prt.label = ["Header 1", "Header 2", "Header 3"]
prt.set_column = [] prt.set_column = []
prt.data = [["Row 1", "1", "2"], ["Row 2", "3", "4\nNew Line to see if it also can wrap around the cell region properly\nAnother new line"]] prt.data = [["Row 1", "1", "2"], ["Row 2", "3", "4\nNew Line to see if it also can wrap around the cell region properly\nAnother new line"]]
@@ -151,7 +163,7 @@ class TablePanel(wxPanel):
def PrintWide(self): def PrintWide(self):
self.ReadData() self.ReadData()
prt = PrintTable(self.frame) prt = printout.PrintTable(self.frame)
prt.data = self.data prt.data = self.data
prt.left_margin = 0.5 prt.left_margin = 0.5
@@ -173,12 +185,6 @@ def runTest(frame, nb, log):
import os
import wxPython.lib.printout
overview = """\ overview = """\
<html><body> <html><body>
<h2>Table Printing</h2> <h2>Table Printing</h2>
@@ -203,7 +209,7 @@ the program knows it before trying to parse through the available pages. This w
when the framework allows for it. when the framework allows for it.
""" % os.path.join(os.path.dirname(wxPython.lib.printout.__file__), "printout.py") """ % os.path.join(os.path.dirname(printout.__file__), "printout.py")

View File

@@ -1,15 +1,26 @@
# 11/13/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
# o Replaced deprecated whrandom with random module.
#
# 11/13/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Currently uses lib.newevent; should probably be updated to use
# new-style event binder. OTOH, this is the only place we get
# to see that library used that I know of.
#
from wxPython.wx import * import random
from wxPython.lib import newevent
import thread
import time import time
from whrandom import random import thread
import wx
import wx.lib.newevent
#---------------------------------------------------------------------- #----------------------------------------------------------------------
# This creates a new Event class and a EVT binder function # This creates a new Event class and a EVT binder function
UpdateBarEvent, EVT_UPDATE_BARGRAPH = newevent.NewEvent() (UpdateBarEvent, EVT_UPDATE_BARGRAPH) = wx.lib.newevent.NewEvent()
#---------------------------------------------------------------------- #----------------------------------------------------------------------
@@ -33,14 +44,14 @@ class CalcBarThread:
def Run(self): def Run(self):
while self.keepGoing: while self.keepGoing:
evt = UpdateBarEvent(barNum = self.barNum, value = int(self.val)) evt = UpdateBarEvent(barNum = self.barNum, value = int(self.val))
wxPostEvent(self.win, evt) wx.PostEvent(self.win.GetEventHandler(), evt)
#del evt #del evt
sleeptime = (random() * 2) + 0.5 sleeptime = (random.random() * 2) + 0.5
time.sleep(sleeptime/4) time.sleep(sleeptime/4)
sleeptime = sleeptime * 5 sleeptime = sleeptime * 5
if int(random() * 2): if int(random.random() * 2):
self.val = self.val + sleeptime self.val = self.val + sleeptime
else: else:
self.val = self.val - sleeptime self.val = self.val - sleeptime
@@ -53,22 +64,22 @@ class CalcBarThread:
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class GraphWindow(wxWindow): class GraphWindow(wx.Window):
def __init__(self, parent, labels): def __init__(self, parent, labels):
wxWindow.__init__(self, parent, -1) wx.Window.__init__(self, parent, -1)
self.values = [] self.values = []
for label in labels: for label in labels:
self.values.append((label, 0)) self.values.append((label, 0))
font = wxFont(12, wxSWISS, wxNORMAL, wxBOLD) font = wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD)
self.SetFont(font) self.SetFont(font)
self.colors = [ wxRED, wxGREEN, wxBLUE, wxCYAN, self.colors = [ wx.RED, wx.GREEN, wx.BLUE, wx.CYAN,
"Yellow", "Navy" ] "Yellow", "Navy" ]
EVT_ERASE_BACKGROUND(self, self.OnEraseBackground) self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
EVT_PAINT(self, self.OnPaint) self.Bind(wx.EVT_PAINT, self.OnPaint)
def SetValue(self, index, value): def SetValue(self, index, value):
@@ -78,7 +89,7 @@ class GraphWindow(wxWindow):
def SetFont(self, font): def SetFont(self, font):
wxWindow.SetFont(self, font) wx.Window.SetFont(self, font)
wmax = hmax = 0 wmax = hmax = 0
for label, val in self.values: for label, val in self.values:
w,h = self.GetTextExtent(label) w,h = self.GetTextExtent(label)
@@ -94,8 +105,8 @@ class GraphWindow(wxWindow):
def Draw(self, dc, size): def Draw(self, dc, size):
dc.SetFont(self.GetFont()) dc.SetFont(self.GetFont())
dc.SetTextForeground(wxBLUE) dc.SetTextForeground(wx.BLUE)
dc.SetBackground(wxBrush(self.GetBackgroundColour())) dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
dc.Clear() dc.Clear()
dc.SetPen(wxPen(wxBLACK, 3, wxSOLID)) dc.SetPen(wxPen(wxBLACK, 3, wxSOLID))
dc.DrawLine((self.linePos, 0), (self.linePos, size.height-10)) dc.DrawLine((self.linePos, 0), (self.linePos, size.height-10))
@@ -112,23 +123,25 @@ class GraphWindow(wxWindow):
dc.DrawRectangle((self.linePos+3, ypos), (val, bh)) dc.DrawRectangle((self.linePos+3, ypos), (val, bh))
ypos = ypos + 2*bh ypos = ypos + 2*bh
if ypos > size.height-10: if ypos > size[1]-10:
break break
def OnPaint(self, evt): def OnPaint(self, evt):
size = self.GetSize() width, height = self.GetSize()
bmp = wxEmptyBitmap(size.width, size.height) bmp = wx.EmptyBitmap(width, height)
dc = wxMemoryDC()
dc.SelectObject(bmp)
self.Draw(dc, size)
wdc = wxPaintDC(self) dc = wx.MemoryDC()
dc.SelectObject(bmp)
self.Draw(dc, (width, height))
wdc = wx.PaintDC(self)
wdc.BeginDrawing() wdc.BeginDrawing()
wdc.Blit((0,0), size, dc, (0,0)) wdc.Blit((0,0), size, dc, (0,0))
wdc.EndDrawing() wdc.EndDrawing()
dc.SelectObject(wxNullBitmap) dc.SelectObject(wx.NullBitmap)
def OnEraseBackground(self, evt): def OnEraseBackground(self, evt):
@@ -139,34 +152,35 @@ class GraphWindow(wxWindow):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestFrame(wxFrame): class TestFrame(wx.Frame):
def __init__(self, parent, log): def __init__(self, parent, log):
wxFrame.__init__(self, parent, -1, "Thread Test", size=(450,300)) wx.Frame.__init__(self, parent, -1, "Thread Test", size=(450,300))
self.log = log self.log = log
#self.CenterOnParent() #self.CenterOnParent()
panel = wxPanel(self, -1) panel = wx.Panel(self, -1)
panel.SetFont(wxFont(10, wxSWISS, wxNORMAL, wxBOLD)) panel.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD))
wxStaticText(panel, -1, wx.StaticText(panel, -1,
"This demo shows multiple threads interacting with this\n" "This demo shows multiple threads interacting with this\n"
"window by sending events to it, one thread for each bar.", "window by sending events to it, one thread for each bar.",
wxPoint(5,5)) (5,5))
panel.Fit() panel.Fit()
self.graph = GraphWindow(self, ['Zero', 'One', 'Two', 'Three', 'Four', self.graph = GraphWindow(self, ['Zero', 'One', 'Two', 'Three', 'Four',
'Five', 'Six', 'Seven']) 'Five', 'Six', 'Seven'])
self.graph.SetSize((450, self.graph.GetBestHeight())) self.graph.SetSize((450, self.graph.GetBestHeight()))
sizer = wxBoxSizer(wxVERTICAL) sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(panel, 0, wxEXPAND) sizer.Add(panel, 0, wx.EXPAND)
sizer.Add(self.graph, 1, wxEXPAND) sizer.Add(self.graph, 1, wx.EXPAND)
self.SetSizer(sizer) self.SetSizer(sizer)
self.SetAutoLayout(True) self.SetAutoLayout(True)
sizer.Fit(self) sizer.Fit(self)
EVT_UPDATE_BARGRAPH(self, self.OnUpdate) self.Bind(EVT_UPDATE_BARGRAPH, self.OnUpdate)
self.threads = [] self.threads = []
self.threads.append(CalcBarThread(self, 0, 50)) self.threads.append(CalcBarThread(self, 0, 50))
self.threads.append(CalcBarThread(self, 1, 75)) self.threads.append(CalcBarThread(self, 1, 75))
@@ -180,7 +194,7 @@ class TestFrame(wxFrame):
for t in self.threads: for t in self.threads:
t.Start() t.Start()
EVT_CLOSE(self, self.OnCloseWindow) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
def OnUpdate(self, evt): def OnUpdate(self, evt):
@@ -189,16 +203,22 @@ class TestFrame(wxFrame):
def OnCloseWindow(self, evt): def OnCloseWindow(self, evt):
busy = wxBusyInfo("One moment please, waiting for threads to die...") busy = wx.BusyInfo("One moment please, waiting for threads to die...")
wxYield() wx.Yield()
for t in self.threads: for t in self.threads:
t.Stop() t.Stop()
running = 1 running = 1
while running: while running:
running = 0 running = 0
for t in self.threads: for t in self.threads:
running = running + t.IsRunning() running = running + t.IsRunning()
time.sleep(0.1) time.sleep(0.1)
self.Destroy() self.Destroy()
@@ -228,7 +248,7 @@ application and makes it difficult to use additional threads at all.
Since wxPython already makes extensive use of event handlers, it is a Since wxPython already makes extensive use of event handlers, it is a
logical extension to allow events to be sent to GUI objects from logical extension to allow events to be sent to GUI objects from
alternate threads. A function called wxPostEvent allows you to do alternate threads. A function called wx.PostEvent allows you to do
this. It accepts an event and an event handler (window) and instead this. It accepts an event and an event handler (window) and instead
of sending the event immediately in the current context like of sending the event immediately in the current context like
ProcessEvent does, it processes it later from the context of the GUI ProcessEvent does, it processes it later from the context of the GUI

View File

@@ -1,17 +1,24 @@
# #
# Throbber.py - Cliff Wells <clifford.wells@attbi.com> # Throbber.py - Cliff Wells <clifford.wells@attbi.com>
# #
# 11/23/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
import wx
import wx.lib.rcsizer as rcs
import wx.lib.throbber as throb
from wxPython.wx import *
from wxPython.lib.rcsizer import RowColSizer
from wxPython.lib.throbber import Throbber, __doc__ as docString
import throbImages # this was created using a modified version of img2py import throbImages # this was created using a modified version of img2py
from wx.lib.throbber import __doc__ as docString
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.log = log self.log = log
# create the throbbers # create the throbbers
@@ -34,83 +41,96 @@ class TestPanel(wxPanel):
for i in throbImages.index for i in throbImages.index
if i not in ['eclouds', 'logo']] if i not in ['eclouds', 'logo']]
self.throbbers['plain']['throbber'] = Throbber(self, -1, self.throbbers['plain']['throbber'] = \
images, size=(36, 36), throb.Throbber(self, -1, images, size=(36, 36),frameDelay = 0.1)
frameDelay = 0.1)
self.throbbers['reverse']['throbber'] = Throbber(self, -1, images, #size=(36, 36),
frameDelay = 0.07)
self.throbbers['reverse']['throbber'].Reverse()
self.throbbers['autoreverse']['throbber'] = Throbber(self, -1,
images, #size=(36, 36),
frameDelay = 0.1,
reverse = True)
self.throbbers['autoreverse']['throbber'].sequence.append(0)
self.throbbers['label']['throbber'] = Throbber(self, -1,
images, #size=(36, 36),
frameDelay = 0.1,
label = 'Label')
self.throbbers['label']['throbber'].SetFont(wxFont(pointSize = 10,
family = wxDEFAULT,
style = wxNORMAL,
weight = wxBOLD))
self.throbbers['overlay']['throbber'] = Throbber(self, -1,
images, #size=(36, 36),
frameDelay = 0.1,
overlay = throbImages.catalog['logo'].getBitmap())
self.throbbers['overlay+text']['throbber'] = Throbber(self, -1,
images, #size=(36, 36),
frameDelay = 0.1,
overlay = throbImages.catalog['logo'].getBitmap(),
label = "Python!")
self.throbbers['overlay+text']['throbber'].SetFont(wxFont(pointSize = 8,
family = wxDEFAULT,
style = wxNORMAL,
weight = wxBOLD))
self.throbbers['reverse']['throbber'] = \
throb.Throbber(self, -1, images, frameDelay = 0.07)
self.throbbers['reverse']['throbber'].Reverse()
self.throbbers['autoreverse']['throbber'] = \
throb.Throbber(self, -1, images, frameDelay = 0.1, reverse = True)
self.throbbers['autoreverse']['throbber'].sequence.append(0)
self.throbbers['label']['throbber'] = \
throb.Throbber(self, -1, images, frameDelay = 0.1, label = 'Label')
self.throbbers['label']['throbber'].SetFont(wx.Font(
pointSize = 10, family = wx.DEFAULT, style = wx.NORMAL, weight = wx.BOLD
))
self.throbbers['overlay']['throbber'] = \
throb.Throbber(
self, -1, images, frameDelay = 0.1,
overlay = throbImages.catalog['logo'].getBitmap()
)
self.throbbers['overlay+text']['throbber'] = \
throb.Throbber(
self, -1, images, frameDelay = 0.1,
overlay = throbImages.catalog['logo'].getBitmap(), label = "Python!"
)
self.throbbers['overlay+text']['throbber'].SetFont(wx.Font(
pointSize = 8, family = wx.DEFAULT, style = wx.NORMAL, weight = wx.BOLD
))
# this throbber is created using a single, composite image # this throbber is created using a single, composite image
self.otherThrobber = Throbber(self, -1, self.otherThrobber = throb.Throbber(
throbImages.catalog['eclouds'].getBitmap(), #size=(48, 48), self, -1, throbImages.catalog['eclouds'].getBitmap(), frameDelay = 0.15,
frameDelay = 0.15, frames = 12, frameWidth = 48, label = "Stop"
frames = 12, )
frameWidth = 48,
label = "Stop")
EVT_LEFT_DOWN(self.otherThrobber, self.OnClickThrobber) self.otherThrobber.Bind(wx.EVT_LEFT_DOWN, self.OnClickThrobber)
box = wxBoxSizer(wxVERTICAL) box = wx.BoxSizer(wx.VERTICAL)
sizer = RowColSizer() sizer = rcs.RowColSizer()
box.Add(sizer, 1, wxEXPAND|wxALL, 5) box.Add(sizer, 1, wx.EXPAND|wx.ALL, 5)
sizer.AddGrowableCol(1) sizer.AddGrowableCol(1)
sizer.Add(self.otherThrobber, row = 0, col = 2, rowspan = 4, flag = wxALIGN_CENTER_VERTICAL) sizer.Add(
self.otherThrobber, row = 0, col = 2, rowspan = 4,
flag = wx.ALIGN_CENTER_VERTICAL
)
row = 2 row = 2
# use a list so we can keep our order # use a list so we can keep our order
for t in ['plain', 'reverse', 'autoreverse', 'label', 'overlay', 'overlay+text']: for t in ['plain', 'reverse', 'autoreverse', 'label', 'overlay', 'overlay+text']:
sizer.Add(self.throbbers[t]['throbber'], row = row, col = 0, flag = wxALIGN_CENTER|wxALL, border=2) sizer.Add(
sizer.Add(wxStaticText(self, -1, self.throbbers[t]['text']), row = row, col = 1, self.throbbers[t]['throbber'], row = row, col = 0,
flag = wxALIGN_CENTER_VERTICAL | wxALIGN_LEFT) flag = wx.ALIGN_CENTER|wx.ALL, border=2
)
sizer.Add(
wx.StaticText(self, -1, self.throbbers[t]['text']),
row = row, col = 1, flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT
)
row += 1 row += 1
# start and stop buttons # start and stop buttons
startButton = wxButton(self, -1, "Start") startButton = wx.Button(self, -1, "Start")
EVT_BUTTON(self, startButton.GetId(), self.OnStartAnimation) self.Bind(wx.EVT_BUTTON, self.OnStartAnimation, id=startButton.GetId())
stopButton = wxButton(self, -1, "Stop")
EVT_BUTTON(self, stopButton.GetId(), self.OnStopAnimation)
buttonBox = wxBoxSizer(wxHORIZONTAL) stopButton = wx.Button(self, -1, "Stop")
self.Bind(wx.EVT_BUTTON, self.OnStopAnimation, id=stopButton.GetId())
buttonBox = wx.BoxSizer(wx.HORIZONTAL)
buttonBox.AddMany([ buttonBox.AddMany([
(startButton, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5), (startButton, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, 5),
(stopButton, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5), (stopButton, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, 5),
]) ])
sizer.Add(buttonBox, sizer.Add(buttonBox,
row = len(self.throbbers) + 3, row = len(self.throbbers) + 3,
col = 0, col = 0,
colspan = 3, colspan = 3,
flag = wxALIGN_CENTER) flag = wx.ALIGN_CENTER
)
self.SetSizer(box) self.SetSizer(box)
self.SetAutoLayout(True) self.SetAutoLayout(True)
@@ -120,10 +140,11 @@ class TestPanel(wxPanel):
for t in self.throbbers.keys(): for t in self.throbbers.keys():
self.throbbers[t]['throbber'].Start() self.throbbers[t]['throbber'].Start()
self.otherThrobber.Start() self.otherThrobber.Start()
self.otherThrobber.Reverse() self.otherThrobber.Reverse()
EVT_WINDOW_DESTROY(self, self.OnDestroy) self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
def OnDestroy(self, event): def OnDestroy(self, event):
self.log.write("got destroy event") self.log.write("got destroy event")
@@ -154,8 +175,8 @@ class TestPanel(wxPanel):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def runTest(frame, nb, log): def runTest(frame, nb, log):
if wxPlatform == "__WXMAC__": if wx.Platform == "__WXMAC__":
wxMessageBox("This demo currently fails on the Mac.", wx.MessageBox("This demo currently fails on the Mac.",
"Sorry") "Sorry")
return return
else: else:

View File

@@ -1,22 +1,26 @@
# 11/15/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import * import wx
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class MyURLDropTarget(wxPyDropTarget): class MyURLDropTarget(wx.PyDropTarget):
def __init__(self, window): def __init__(self, window):
wxPyDropTarget.__init__(self) wx.PyDropTarget.__init__(self)
self.window = window self.window = window
self.data = wxURLDataObject(); self.data = wx.URLDataObject();
self.SetDataObject(self.data) self.SetDataObject(self.data)
def OnDragOver(self, x, y, d): def OnDragOver(self, x, y, d):
return wxDragLink return wx.DragLink
def OnData(self, x, y, d): def OnData(self, x, y, d):
if not self.GetData(): if not self.GetData():
return wxDragNone return wx.DragNone
url = self.data.GetURL() url = self.data.GetURL()
self.window.AppendText(url + "\n") self.window.AppendText(url + "\n")
@@ -26,16 +30,16 @@ class MyURLDropTarget(wxPyDropTarget):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.SetAutoLayout(True) self.SetAutoLayout(True)
outsideSizer = wxBoxSizer(wxVERTICAL) outsideSizer = wx.BoxSizer(wx.VERTICAL)
msg = "Drag-And-Drop of URLs" msg = "Drag-And-Drop of URLs"
text = wxStaticText(self, -1, "", style=wxALIGN_CENTRE) text = wx.StaticText(self, -1, "", style=wx.ALIGN_CENTRE)
text.SetFont(wxFont(24, wxSWISS, wxNORMAL, wxBOLD, False)) text.SetFont(wx.Font(24, wx.SWISS, wx.NORMAL, wx.BOLD, False))
text.SetLabel(msg) text.SetLabel(msg)
w,h = text.GetTextExtent(msg) w,h = text.GetTextExtent(msg)
text.SetSize(wxSize(w,h+1)) text.SetSize(wxSize(w,h+1))
@@ -44,55 +48,53 @@ class TestPanel(wxPanel):
outsideSizer.Add(wxStaticLine(self, -1), 0, wxEXPAND) outsideSizer.Add(wxStaticLine(self, -1), 0, wxEXPAND)
outsideSizer.Add((20,20)) outsideSizer.Add((20,20))
self.SetFont(wxFont(10, wxSWISS, wxNORMAL, wxBOLD, False)) self.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD, False))
inSizer = wxFlexGridSizer(2, 2, 5, 5) inSizer = wx.FlexGridSizer(2, 2, 5, 5)
inSizer.AddGrowableCol(0) inSizer.AddGrowableCol(0)
inSizer.Add((20,20)) inSizer.Add((20,20))
inSizer.Add((20,20)) inSizer.Add((20,20))
inSizer.Add(wxStaticText(self, -1, inSizer.Add(wxStaticText(self, -1,
"Drag URLs from your browser to\nthis window:", "Drag URLs from your browser to\nthis window:",
style = wxALIGN_RIGHT), style = wx.ALIGN_RIGHT),
0, wxALIGN_RIGHT ) 0, wx.ALIGN_RIGHT )
self.dropText = wxTextCtrl(self, -1, "", size=(380, 180), self.dropText = wx.TextCtrl(self, -1, "", size=(380, 180),
style=wxTE_MULTILINE|wxTE_READONLY) style=wx.TE_MULTILINE|wx.TE_READONLY)
inSizer.Add(self.dropText, 0, wxEXPAND) inSizer.Add(self.dropText, 0, wx.EXPAND)
inSizer.Add(wxStaticText(self, -1, inSizer.Add(wx.StaticText(self, -1,
"Drag this URL to your browser:", "Drag this URL to your browser:",
style = wxALIGN_RIGHT), style = wx.ALIGN_RIGHT),
0, wxALIGN_RIGHT ) 0, wx.ALIGN_RIGHT )
self.dragText = wxTextCtrl(self, -1, "http://wxPython.org/") self.dragText = wx.TextCtrl(self, -1, "http://wxPython.org/")
inSizer.Add(self.dragText, 0, wxEXPAND) inSizer.Add(self.dragText, 0, wx.EXPAND)
EVT_MOTION(self.dragText, self.OnStartDrag) self.dragText.Bind(wx.EVT_MOTION, self.OnStartDrag)
## inSizer.Add(wxStaticText(self, -1, ## inSizer.Add(wx.StaticText(self, -1,
## "Drag this TEXT to your browser:", ## "Drag this TEXT to your browser:",
## style = wxALIGN_RIGHT), ## style = wx.ALIGN_RIGHT),
## 0, wxALIGN_RIGHT ) ## 0, wx.ALIGN_RIGHT )
## self.dragText2 = wxTextCtrl(self, -1, "http://wxPython.org/") ## self.dragText2 = wx.TextCtrl(self, -1, "http://wxPython.org/")
## inSizer.Add(self.dragText2, 0, wxEXPAND) ## inSizer.Add(self.dragText2, 0, wx.EXPAND)
## EVT_MOTION(self.dragText2, self.OnStartDrag2) ## self.dragText2.Bind(EVT_MOTION, self.OnStartDrag2)
outsideSizer.Add(inSizer, 1, wxEXPAND) outsideSizer.Add(inSizer, 1, wx.EXPAND)
self.SetSizer(outsideSizer) self.SetSizer(outsideSizer)
self.dropText.SetDropTarget(MyURLDropTarget(self.dropText)) self.dropText.SetDropTarget(MyURLDropTarget(self.dropText))
def OnStartDrag(self, evt): def OnStartDrag(self, evt):
if evt.Dragging(): if evt.Dragging():
url = self.dragText.GetValue() url = self.dragText.GetValue()
data = wxURLDataObject() data = wx.URLDataObject()
data.SetURL(url) data.SetURL(url)
dropSource = wxDropSource(self.dragText) dropSource = wx.DropSource(self.dragText)
dropSource.SetData(data) dropSource.SetData(data)
result = dropSource.DoDragDrop() result = dropSource.DoDragDrop()
@@ -100,10 +102,10 @@ class TestPanel(wxPanel):
def OnStartDrag2(self, evt): def OnStartDrag2(self, evt):
if evt.Dragging(): if evt.Dragging():
url = self.dragText2.GetValue() url = self.dragText2.GetValue()
data = wxTextDataObject() data = wx.TextDataObject()
data.SetText(url) data.SetText(url)
dropSource = wxDropSource(self.dragText2) dropSource = wx.DropSource(self.dragText2)
dropSource.SetData(data) dropSource.SetData(data)
result = dropSource.DoDragDrop() result = dropSource.DoDragDrop()

View File

@@ -1,6 +1,9 @@
# 11/13/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
import wx
from wxPython.wx import *
#---------------------------------------------------------------------- #----------------------------------------------------------------------
@@ -41,22 +44,22 @@ rus_utf8 = ('\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd - \xd0\xbb\xd1\x83\xd1\x87
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
self.log = log self.log = log
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
box = wxBoxSizer(wxVERTICAL) box = wx.BoxSizer(wx.VERTICAL)
if not wxUSE_UNICODE: if not wx.USE_UNICODE:
self.AddLine(box) self.AddLine(box)
self.AddText(box, "Sorry, this wxPython was not built with Unicode support.", self.AddText(box, "Sorry, this wxPython was not built with Unicode support.",
font = wxFont(12, wxSWISS, wxNORMAL, wxBOLD)) font = wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD))
self.AddLine(box) self.AddLine(box)
else: else:
f = self.GetFont() f = self.GetFont()
font = wxFont(14, f.GetFamily(), f.GetStyle(), wxBOLD, False, font = wx.Font(14, f.GetFamily(), f.GetStyle(), wx.BOLD, False,
f.GetFaceName(), f.GetEncoding()) f.GetFaceName(), f.GetEncoding())
self.AddLine(box) self.AddLine(box)
@@ -77,32 +80,32 @@ class TestPanel(wxPanel):
self.AddLine(box) self.AddLine(box)
border = wxBoxSizer(wxVERTICAL) border = wx.BoxSizer(wx.VERTICAL)
border.Add(box, 1, wxEXPAND|wxALL, 10) border.Add(box, 1, wx.EXPAND|wx.ALL, 10)
self.SetAutoLayout(True) self.SetAutoLayout(True)
self.SetSizer(border) self.SetSizer(border)
def AddLine(self, sizer): def AddLine(self, sizer):
sizer.Add(wxStaticLine(self, -1), 0, wxEXPAND) sizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND)
def AddText(self, sizer, text1, text2='', lang='', font=None): def AddText(self, sizer, text1, text2='', lang='', font=None):
# create some controls # create some controls
lang = wxStaticText(self, -1, lang) lang = wx.StaticText(self, -1, lang)
text1 = wxStaticText(self, -1, text1) text1 = wx.StaticText(self, -1, text1)
text2 = wxStaticText(self, -1, text2, style=wxALIGN_RIGHT) text2 = wx.StaticText(self, -1, text2, style=wx.ALIGN_RIGHT)
if font is not None: if font is not None:
text1.SetFont(font) text1.SetFont(font)
# put them in a sizer # put them in a sizer
row = wxBoxSizer(wxHORIZONTAL) row = wx.BoxSizer(wx.HORIZONTAL)
row.Add(lang) row.Add(lang)
row.Add(15,10) row.Add((15,10))
row.Add(text1, 1, wxEXPAND) row.Add(text1, 1, wx.EXPAND)
row.Add(text2) row.Add(text2)
# put the row in the main sizer # put the row in the main sizer
sizer.Add(row, 0, wxEXPAND|wxALL, 5) sizer.Add(row, 0, wx.EXPAND|wx.ALL, 5)
#---------------------------------------------------------------------- #----------------------------------------------------------------------

View File

@@ -1,9 +1,13 @@
# 11/22/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
import sys import sys
import wx
py2 = sys.version[0] == '2' py2 = sys.version[0] == '2'
from wxPython.wx import *
try: try:
if py2: if py2:
from xml.parsers import expat from xml.parsers import expat
@@ -19,30 +23,34 @@ except ImportError:
if not haveXML: if not haveXML:
def runTest(frame, nb, log): def runTest(frame, nb, log):
dlg = wxMessageDialog(frame, 'This demo requires the XML package. ' dlg = wx.MessageDialog(
frame, 'This demo requires the XML package. '
'See http://www.python.org/sigs/xml-sig/', 'See http://www.python.org/sigs/xml-sig/',
'Sorry', wxOK | wxICON_INFORMATION) 'Sorry', wx.OK | wx.ICON_INFORMATION
)
dlg.ShowModal() dlg.ShowModal()
dlg.Destroy() dlg.Destroy()
else: else:
class XMLTree(wxTreeCtrl): class XMLTree(wx.TreeCtrl):
def __init__(self, parent, ID): def __init__(self, parent, ID):
wxTreeCtrl.__init__(self, parent, ID) wx.TreeCtrl.__init__(self, parent, ID)
self.nodeStack = [self.AddRoot("Root")] self.nodeStack = [self.AddRoot("Root")]
# Trees need an image list to do DnD... # Trees need an image list to do DnD...
self.il = wxImageList(16,16) self.il = wx.ImageList(16,16)
self.SetImageList(self.il) self.SetImageList(self.il)
# event handlers for DnD # event handlers for DnD
EVT_TREE_BEGIN_DRAG(self, ID, self.OnBeginDrag) self.Bind(wx.EVT_TREE_BEGIN_DRAG, self.OnBeginDrag)
EVT_TREE_END_DRAG(self, ID, self.OnEndDrag) self.Bind(wx.EVT_TREE_END_DRAG, self.OnEndDrag)
def OnBeginDrag(self, event): def OnBeginDrag(self, event):
item = event.GetItem() item = event.GetItem()
if item != self.GetRootItem(): if item != self.GetRootItem():
self.draggingItem = item self.draggingItem = item
event.Allow() # if DnD of this item is okay Allow it. event.Allow() # if DnD of this item is okay Allow it.
@@ -69,6 +77,7 @@ else:
def StartElement(self, name, attrs ): def StartElement(self, name, attrs ):
if py2: if py2:
name = name.encode() name = name.encode()
id = self.AppendItem(self.nodeStack[-1], name) id = self.AppendItem(self.nodeStack[-1], name)
self.nodeStack.append(id) self.nodeStack.append(id)
@@ -79,6 +88,7 @@ else:
if data.strip(): if data.strip():
if py2: if py2:
data = data.encode() data = data.encode()
self.AppendItem(self.nodeStack[-1], data) self.AppendItem(self.nodeStack[-1], data)
@@ -104,16 +114,10 @@ else:
overview = """\ overview = """\
""" """
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run

View File

@@ -1,5 +1,11 @@
#!/usr/bin/env python #!/usr/bin/env python
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
# 11/9/2003 - Jeff Grimmett (grimmtooth@softhome.net
#
# o Updated for V2.5
# o Mainloop is freezing up app.
#
""" """
This demo attempts to override the C++ MainLoop and implement it This demo attempts to override the C++ MainLoop and implement it
in Python. This is not part of the demo framework. in Python. This is not part of the demo framework.
@@ -8,10 +14,8 @@ in Python. This is not part of the demo framework.
THIS FEATURE IS STILL EXPERIMENTAL... THIS FEATURE IS STILL EXPERIMENTAL...
""" """
import wx # This module uses the new wx namespace
import time import time
import wx
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
@@ -19,37 +23,37 @@ class MyFrame(wx.Frame):
def __init__(self, parent, id, title): def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, wx.Frame.__init__(self, parent, id, title,
wx.Point(100, 100), wx.Size(160, 150)) (100, 100), (160, 150))
wx.EVT_SIZE(self, self.OnSize) self.Bind(wx.EVT_SIZE, self.OnSize)
wx.EVT_MOVE(self, self.OnMove) self.Bind(wx.EVT_MOVE, self.OnMove)
wx.EVT_CLOSE(self, self.OnCloseWindow) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
wx.EVT_IDLE(self, self.OnIdle) self.Bind(wx.EVT_IDLE, self.OnIdle)
self.count = 0 self.count = 0
panel = wx.Panel(self, -1) panel = wx.Panel(self, -1)
wx.StaticText(panel, -1, "Size:", wx.StaticText(panel, -1, "Size:",
wx.DLG_PNT(panel, wx.Point(4, 4)), wx.DefaultSize) wx.DLG_PNT(panel, (4, 4)), wx.DefaultSize)
wx.StaticText(panel, -1, "Pos:", wx.StaticText(panel, -1, "Pos:",
wx.DLG_PNT(panel, wx.Point(4, 16)), wx.DefaultSize) wx.DLG_PNT(panel, (4, 16)), wx.DefaultSize)
wx.StaticText(panel, -1, "Idle:", wx.StaticText(panel, -1, "Idle:",
wx.DLG_PNT(panel, wx.Point(4, 28)), wx.DefaultSize) wx.DLG_PNT(panel, (4, 28)), wx.DefaultSize)
self.sizeCtrl = wx.TextCtrl(panel, -1, "", self.sizeCtrl = wx.TextCtrl(panel, -1, "",
wx.DLG_PNT(panel, wx.Point(24, 4)), wx.DLG_PNT(panel, (24, 4)),
wx.DLG_SZE(panel, wx.Size(36, -1)), wx.DLG_SZE(panel, (36, -1)),
wx.TE_READONLY) wx.TE_READONLY)
self.posCtrl = wx.TextCtrl(panel, -1, "", self.posCtrl = wx.TextCtrl(panel, -1, "",
wx.DLG_PNT(panel, wx.Point(24, 16)), wx.DLG_PNT(panel, (24, 16)),
wx.DLG_SZE(panel, wx.Size(36, -1)), wx.DLG_SZE(panel, (36, -1)),
wx.TE_READONLY) wx.TE_READONLY)
self.idleCtrl = wx.TextCtrl(panel, -1, "", self.idleCtrl = wx.TextCtrl(panel, -1, "",
wx.DLG_PNT(panel, wx.Point(24, 28)), wx.DLG_PNT(panel, (24, 28)),
wx.DLG_SZE(panel, wx.Size(36, -1)), wx.DLG_SZE(panel, (36, -1)),
wx.TE_READONLY) wx.TE_READONLY)
@@ -112,7 +116,7 @@ class MyApp(wx.App):
return True return True
app = MyApp(0) app = MyApp(False)
app.MainLoop() app.MainLoop()

View File

@@ -1,5 +1,9 @@
#!/usr/bin/env python #!/usr/bin/env python
#---------------------------------------------------------------------- #----------------------------------------------------------------------
# 11/5/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Modified for wx namespace
#
""" """
This is a way to save the startup time when running img2py on lots of This is a way to save the startup time when running img2py on lots of
@@ -7,7 +11,8 @@ files...
""" """
import sys import sys
from wxPython.tools import img2py
from wx.tools import img2py
command_lines = [ command_lines = [

View File

@@ -1,48 +1,87 @@
# 11/12/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
# o wx module doesn't like the doc string.
#
# 11/25/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Library didn't get hit by the wx renamer.
# o Docstring issues resolved.
#
from wxPython.wx import * import sys
from wxPython.lib.infoframe import *
import wx
import wx.lib.infoframe as infoframe
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class MyFrame(wxFrame): class MyFrame(wx.Frame):
def __init__(self, output): def __init__(self, output):
wxFrame.__init__(self,None,-1,"Close me...",size=(300,100)) wx.Frame.__init__(self, None, -1, "Close me...", size=(300,100))
menubar = wxMenuBar()
menu = wxMenu()
mID = wxNewId()
menu.Append(mID,"&Enable output","Display output frame")
EVT_MENU(self,mID,output.EnableOutput)
mID = wxNewId()
menu.Append(mID,"&Disable output","Close output frame")
EVT_MENU(self,mID,output.DisableOutput)
menubar.Append(menu,"&Output")
self.SetMenuBar(menubar)
output.SetParent(self)
output.SetOtherMenuBar(menubar,menuname="Output")
EVT_CLOSE(self,self.OnClose)
EVT_TIMER(self, -1, self.OnTimer)
self.timer = wxTimer(self, -1) menubar = wx.MenuBar()
# Output menu
menu = wx.Menu()
# Enable output menu item
mID = wx.NewId()
menu.Append(mID, "&Enable output", "Display output frame")
self.Bind(wx.EVT_MENU, output.EnableOutput, id=mID)
# Disable output menu item
mID = wx.NewId()
menu.Append(mID, "&Disable output", "Close output frame")
self.Bind(wx.EVT_MENU, output.DisableOutput, id=mID)
# Attach the menu to our menu bar
menubar.Append(menu, "&Output")
# Attach menu bar to frame
self.SetMenuBar(menubar)
# Point to ourselves as the output object's parent.
output.SetParent(self)
# Associate menu bar with output object
output.SetOtherMenuBar(menubar, menuname="Output")
self.Bind(wx.EVT_CLOSE, self.OnClose)
# We're going to set up a timer; set up an event handler for it.
self.Bind(wx.EVT_TIMER, self.OnTimer)
# Set up a timer for demo purposes
self.timer = wx.Timer(self, -1)
self.timer.Start(1000) self.timer.Start(1000)
# Get a copy of stdout and set it aside. We'll use it later.
self.save_stdout = sys.stdout self.save_stdout = sys.stdout
# Now point to the output object for stdout
sys.stdout = self.output = output sys.stdout = self.output = output
# ... and use it.
print "Hello!" print "Hello!"
def OnClose(self,event): def OnClose(self,event):
# We stored a pointer to the original stdout above in .__init__(), and
# here we restore it before closing the window.
sys.stdout = self.save_stdout sys.stdout = self.save_stdout
# Clean up
self.output.close() self.output.close()
self.timer.Stop() self.timer.Stop()
self.timer = None self.timer = None
self.Destroy() self.Destroy()
# Event handler for timer events.
def OnTimer(self, evt): def OnTimer(self, evt):
print "This was printed with \"print\"" print "This was printed with \"print\""
#---------------------------------------------------------------------- #----------------------------------------------------------------------
from wxPython.lib import infoframe
overview = infoframe.__doc__ overview = infoframe.__doc__
def runTest(frame, nb, log): def runTest(frame, nb, log):
@@ -50,7 +89,7 @@ def runTest(frame, nb, log):
This method is used by the wxPython Demo Framework for integrating This method is used by the wxPython Demo Framework for integrating
this demo with the rest. this demo with the rest.
""" """
win = MyFrame(wxPyInformationalMessagesFrame()) win = MyFrame(infoframe.wxPyInformationalMessagesFrame())
frame.otherWin = win frame.otherWin = win
win.Show(1) win.Show(1)
@@ -78,18 +117,42 @@ if __name__ == "__main__":
## sys.stdout.close() ## sys.stdout.close()
## self.Destroy() ## self.Destroy()
class MyApp(wxApp): # Override the default output window and point it to the
outputWindowClass = wxPyInformationalMessagesFrame # custom class.
#>>Todo: wx renamer didn't get this
outputWindowClass = infoframe.wxPyInformationalMessagesFrame
def OnInit(self): def OnInit(self):
# At this point, we should probably check to see if self.stdioWin
# is actually pointed to something. By default, wx.App() sets this
# attribute to None. This causes problems when setting up the menus
# in MyFrame() above. On the other hand, since there's little that
# can be done at this point, you might be better served putting
# an error handler directly into MyFrame().
#
# That's in practice. In the case of this demo, the whole point
# of the exercise is to demonstrate the window, so we're being
# just a little lazy for clarity's sake. But do be careful in
# a 'real world' implementation :-)
frame = MyFrame(self.stdioWin) frame = MyFrame(self.stdioWin)
frame.Show(True) frame.Show(True)
self.SetTopWindow(frame) self.SetTopWindow(frame)
if isinstance(sys.stdout,wxPyInformationalMessagesFrame):
# Associate the frame with stdout.
#>>Todo: wx renamer didn't get this
if isinstance(sys.stdout, infoframe.wxPyInformationalMessagesFrame):
sys.stdout.SetParent(frame) sys.stdout.SetParent(frame)
#self.redirectStdio(None)# this is done automatically
# by the MyApp(1) call below
print "Starting.\n", print "Starting.\n",
return True return True
app = MyApp(1) # *extremely important*
#
# In this demo, if the redirect flag is set to False, the infoframe will not
# be created or used. All output will go to the default stdout, which in this
# case will cause the app to throw an exception. In a real app, you should
# probably plan ahead and add a check before forging ahead. See suggestion above.
app = MyApp(True)
app.MainLoop() app.MainLoop()

View File

@@ -1,60 +0,0 @@
#----------------------------------------------------------------------
# A very simple wxPython example. Just a wxFrame, wxPanel,
# wxStaticText, wxButton, and a wxBoxSizer, but it shows the basic
# structure of any wxPython application.
#----------------------------------------------------------------------
from wxPython.wx import *
print "wxVERSION_STRING = ", wxVERSION_STRING
class MyFrame(wxFrame):
"""
This is MyFrame. It just shows a few controls on a wxPanel,
and has a simple menu.
"""
def __init__(self, parent, title):
wxFrame.__init__(self, parent, -1, title, size=(350, 200))
menuBar = wxMenuBar()
menu = wxMenu()
menu.Append(101, "E&xit\tAlt-X", "Exit demo")
EVT_MENU(self, 101, self.OnButton)
menuBar.Append(menu, "&File")
self.SetMenuBar(menuBar)
panel = wxPanel(self, -1)
text = wxStaticText(panel, -1, "Hello World!")
text.SetFont(wxFont(14, wxSWISS, wxNORMAL, wxBOLD))
text.SetSize(text.GetBestSize())
btn = wxButton(panel, -1, "Close")
btn.SetDefault()
btn2 = wxButton(panel, -1, "Just for fun...")
sizer = wxBoxSizer(wxVERTICAL)
sizer.Add(text, 0, wxALL, 10)
sizer.Add(btn, 0, wxALL, 10)
sizer.Add(btn2, 0, wxALL, 10)
panel.SetSizer(sizer)
panel.SetAutoLayout(True)
panel.Layout()
EVT_BUTTON(self, btn.GetId(), self.OnButton)
EVT_BUTTON(self, btn2.GetId(), self.OnFunButton)
def OnButton(self, evt):
"""Event handler for the button click."""
print "OnButton"
self.Close()
def OnFunButton(self, evt):
"""Event handler for the button click."""
print "Having fun yet?"
app = wxPySimpleApp()
frame = MyFrame(None, "Simple wxPython App")
frame.Show(True)
app.MainLoop()

View File

@@ -1,3 +1,8 @@
# 11/13/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
""" """
Hello, and welcome to this test of the wxTreeItemData Hello, and welcome to this test of the wxTreeItemData
class. class.
@@ -23,8 +28,10 @@ sample not because it's used, but because it's so
beautifully documented... beautifully documented...
""" """
from wxPython import wx import string # Used for demo purposes, nothing more. :-)
import sys, string # Don't use it, but it's fun expanding :-) import sys
import wx
#---------------------------------------------------------------------- #----------------------------------------------------------------------
@@ -47,8 +54,10 @@ def _sourcefinder(func):
for i in range(func.co_firstlineno): for i in range(func.co_firstlineno):
line = f.readline() line = f.readline()
ind = _getindent(line) ind = _getindent(line)
msg = "" msg = ""
while line: while line:
msg = msg + line msg = msg + line
line = f.readline() line = f.readline()
@@ -56,13 +65,14 @@ def _sourcefinder(func):
# confused by multiline docstrings. Using == works most of # confused by multiline docstrings. Using == works most of
# the time... but not always! # the time... but not always!
if _getindent(line) == ind: break if _getindent(line) == ind: break
return msg return msg
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class pyTree(wx.wxTreeCtrl): class pyTree(wx.TreeCtrl):
""" """
This wxTreeCtrl derivative displays a tree view of a Python namespace. This wx.TreeCtrl derivative displays a tree view of a Python namespace.
Anything from which the dir() command returns a non-empty list is a branch Anything from which the dir() command returns a non-empty list is a branch
in this tree. in this tree.
""" """
@@ -75,13 +85,16 @@ class pyTree(wx.wxTreeCtrl):
SEL_CHANGED handler attempts to display interesting SEL_CHANGED handler attempts to display interesting
information about the selected object. information about the selected object.
""" """
wx.wxTreeCtrl.__init__(self, parent, id) wx.TreeCtrl.__init__(self, parent, id)
self.root = self.AddRoot(str(root), -1, -1, wx.wxTreeItemData(root)) self.root = self.AddRoot(str(root), -1, -1, wx.TreeItemData(root))
if dir(root): if dir(root):
self.SetItemHasChildren(self.root, wx.True) self.SetItemHasChildren(self.root, True)
wx.EVT_TREE_ITEM_EXPANDING(self, self.GetId(), self.OnItemExpanding)
wx.EVT_TREE_ITEM_COLLAPSED(self, self.GetId(), self.OnItemCollapsed) self.Bind(wx.EVT_TREE_ITEM_EXPANDING, self.OnItemExpanding, id=self.GetId())
wx.EVT_TREE_SEL_CHANGED(self, self.GetId(), self.OnSelChanged) self.Bind(wx.EVT_TREE_ITEM_COLLAPSED, self.OnItemCollapsed, id=self.GetId())
self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged, id=self.GetId())
self.output = None self.output = None
self.Expand(self.root) self.Expand(self.root)
@@ -112,16 +125,20 @@ class pyTree(wx.wxTreeCtrl):
will again figure out what the offspring is. will again figure out what the offspring is.
""" """
item = event.GetItem() item = event.GetItem()
if self.IsExpanded(item): # This event can happen twice in the self.Expand call if self.IsExpanded(item): # This event can happen twice in the self.Expand call
return return
obj = self.GetPyData( item ) obj = self.GetPyData( item )
lst = dir(obj) lst = dir(obj)
for key in lst: for key in lst:
new_obj = getattr(obj,key) new_obj = getattr(obj,key)
new_item = self.AppendItem( item, key, -1, -1, new_item = self.AppendItem( item, key, -1, -1,
wx.wxTreeItemData(new_obj) ) wx.TreeItemData(new_obj) )
if dir(new_obj): if dir(new_obj):
self.SetItemHasChildren(new_item, wx.True) self.SetItemHasChildren(new_item, True)
def OnItemCollapsed(self, event): def OnItemCollapsed(self, event):
""" """
@@ -140,16 +157,22 @@ class pyTree(wx.wxTreeCtrl):
""" """
if not self.output: if not self.output:
return return
obj = self.GetPyData( event.GetItem() ) obj = self.GetPyData( event.GetItem() )
msg = str(obj) msg = str(obj)
if hasattr(obj, '__doc__'): if hasattr(obj, '__doc__'):
msg = msg+"\n\nDocumentation string:\n\n%s" % ( getattr(obj, '__doc__'),) msg = msg+"\n\nDocumentation string:\n\n%s" % ( getattr(obj, '__doc__'),)
# Is it a function? # Is it a function?
func = None func = None
if hasattr(obj, "func_code"): # normal function if hasattr(obj, "func_code"): # normal function
func = getattr(obj, "func_code") func = getattr(obj, "func_code")
elif hasattr(obj, "im_func"): # unbound class method elif hasattr(obj, "im_func"): # unbound class method
func = getattr(getattr(obj, "im_func"), "func_code") func = getattr(getattr(obj, "im_func"), "func_code")
if func: # if we found one, let's try to print the source if func: # if we found one, let's try to print the source
msg = msg+"\n\nFunction source:\n\n" + _sourcefinder(func) msg = msg+"\n\nFunction source:\n\n" + _sourcefinder(func)
@@ -164,17 +187,15 @@ def runTest(frame, nb, log):
This method is used by the wxPython Demo Framework for integrating This method is used by the wxPython Demo Framework for integrating
this demo with the rest. this demo with the rest.
""" """
#thisModule = __import__(__name__, globals())
thisModule = sys.modules[__name__] thisModule = sys.modules[__name__]
win = wx.wxFrame(frame, -1, "PyTreeItemData Test") win = wx.Frame(frame, -1, "PyTreeItemData Test")
split = wx.wxSplitterWindow(win, -1) split = wx.SplitterWindow(win, -1)
tree = pyTree(split, -1, thisModule) tree = pyTree(split, -1, thisModule)
text = wx.wxTextCtrl(split, -1, "", wx.wxDefaultPosition, text = wx.TextCtrl(split, -1, "", style=wx.TE_MULTILINE)
wx.wxDefaultSize, wx.wxTE_MULTILINE)
split.SplitVertically(tree, text, 200) split.SplitVertically(tree, text, 200)
tree.SetOutput(text.SetValue) tree.SetOutput(text.SetValue)
tree.SelectItem(tree.root) tree.SelectItem(tree.root)
win.SetSize(wx.wxSize(800,500)) win.SetSize((800,500))
frame.otherWin = win frame.otherWin = win
win.Show(1) win.Show(1)
@@ -183,33 +204,31 @@ def runTest(frame, nb, log):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
if __name__ == '__main__': if __name__ == '__main__':
class MyFrame(wx.wxFrame): class MyFrame(wx.Frame):
"""Very standard Frame class. Nothing special here!""" """Very standard Frame class. Nothing special here!"""
def __init__(self): def __init__(self):
"""Make a splitter window; left a tree, right a textctrl. Wow.""" """Make a splitter window; left a tree, right a textctrl. Wow."""
import __main__ import __main__
wx.wxFrame.__init__(self, None, -1, "PyTreeItemData Test", wx.Frame.__init__(self, None, -1, "PyTreeItemData Test", size=(800,500))
wx.wxDefaultPosition, wx.wxSize(800,500)) split = wx.SplitterWindow(self, -1)
split = wx.wxSplitterWindow(self, -1)
tree = pyTree(split, -1, __main__) tree = pyTree(split, -1, __main__)
text = wx.wxTextCtrl(split, -1, "", wx.wxDefaultPosition, text = wx.TextCtrl(split, -1, "", style=wx.TE_MULTILINE)
wx.wxDefaultSize, wx.wxTE_MULTILINE)
split.SplitVertically(tree, text, 200) split.SplitVertically(tree, text, 200)
tree.SetOutput(text.SetValue) tree.SetOutput(text.SetValue)
tree.SelectItem(tree.root) tree.SelectItem(tree.root)
class MyApp(wx.wxApp): class MyApp(wx.App):
"""This class is even less interesting than MyFrame.""" """This class is even less interesting than MyFrame."""
def OnInit(self): def OnInit(self):
"""OnInit. Boring, boring, boring!""" """OnInit. Boring, boring, boring!"""
frame = MyFrame() frame = MyFrame()
frame.Show(wx.True) frame.Show(True)
self.SetTopWindow(frame) self.SetTopWindow(frame)
return wx.True return True
app = MyApp(0) app = MyApp(False)
app.MainLoop() app.MainLoop()

View File

@@ -1,63 +0,0 @@
#----------------------------------------------------------------------
# A very simple wxPython example. Just a wxFrame, wxPanel,
# wxStaticText, wxButton, and a wxBoxSizer, but it shows the basic
# structure of any wxPython application.
#----------------------------------------------------------------------
import wx # This module uses the new wx namespace
print "wx.VERSION_STRING = ", wx.VERSION_STRING
#import os; print os.getpid(); raw_input("press a key...")
class MyFrame(wx.Frame):
"""
This is MyFrame. It just shows a few controls on a wxPanel,
and has a simple menu.
"""
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, -1, title, size=(350, 200))
menuBar = wx.MenuBar()
menu = wx.Menu()
menu.Append(101, "E&xit\tAlt-X", "Exit demo")
wx.EVT_MENU(self, 101, self.OnButton)
menuBar.Append(menu, "&File")
self.SetMenuBar(menuBar)
panel = wx.Panel(self, -1)
text = wx.StaticText(panel, -1, "Hello World!")
text.SetFont(wx.Font(14, wx.SWISS, wx.NORMAL, wx.BOLD))
text.SetSize(text.GetBestSize())
btn = wx.Button(panel, -1, "Close")
btn.SetDefault()
btn2 = wx.Button(panel, -1, "Just for fun...")
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(text, 0, wx.ALL, 10)
sizer.Add(btn, 0, wx.ALL, 10)
sizer.Add(btn2, 0, wx.ALL, 10)
panel.SetSizer(sizer)
panel.SetAutoLayout(True)
panel.Layout()
wx.EVT_BUTTON(self, btn.GetId(), self.OnButton)
wx.EVT_BUTTON(self, btn2.GetId(), self.OnFunButton)
def OnButton(self, evt):
"""Event handler for the button click."""
print "OnButton"
self.Close()
def OnFunButton(self, evt):
"""Event handler for the button click."""
print "Having fun yet?"
app = wx.PySimpleApp()
frame = MyFrame(None, "Simple wxPython App")
frame.Show(True)
app.MainLoop()

View File

@@ -1,4 +1,10 @@
#!/usr/bin/env python #!/usr/bin/env python
#
# 11/15/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
""" """
Run wxPython in a second thread. Run wxPython in a second thread.
@@ -56,7 +62,8 @@ class viewer_thread:
def start(self): def start(self):
""" start the GUI thread """ start the GUI thread
""" """
import thread,time import time
import thread
thread.start_new_thread(self.run, ()) thread.start_new_thread(self.run, ())
def run(self): def run(self):
@@ -68,9 +75,10 @@ class viewer_thread:
the import would occur in the main thread and the import would occur in the main thread and
wxPython wouldn't run correctly in the second thread. wxPython wouldn't run correctly in the second thread.
""" """
from viewer_basics import * import viewer_basics
try: try:
self.app = SecondThreadApp(0) self.app = viewer_basics.SecondThreadApp(0)
self.app.MainLoop() self.app.MainLoop()
except TypeError: except TypeError:
self.app = None self.app = None
@@ -81,6 +89,7 @@ class viewer_thread:
other thread and tell it to create a cone window. other thread and tell it to create a cone window.
""" """
import viewer_basics import viewer_basics
if self.app: if self.app:
evt = viewer_basics.AddCone() evt = viewer_basics.AddCone()
viewer_basics.wxPostEvent(self.app.catcher, evt) viewer_basics.wxPostEvent(self.app.catcher, evt)

View File

@@ -1,14 +1,20 @@
from wxPython.wx import * # 11/15/2003 - Jeff Grimmett (grimmtooth@softhome.net)
from wxPython.lib import vtk #
# o Updated for wx namespace
# o No idea what this does.
#
import wx
import wx.lib.vtk as vtk
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class VtkFrame(wxFrame): class VtkFrame(wx.Frame):
""" """
Simple example VTK window that contains a cone. Simple example VTK window that contains a cone.
""" """
def __init__(self, parent, id, title): def __init__(self, parent, id, title):
wxFrame.__init__(self, parent,id,title, size=(450, 300)) wx.Frame.__init__(self, parent, id, title, size=(450, 300))
win = vtk.wxVTKRenderWindow(self, -1) win = vtk.VTKRenderWindow(self, -1)
renWin = win.GetRenderWindow() renWin = win.GetRenderWindow()
@@ -22,19 +28,17 @@ class VtkFrame(wxFrame):
ren.AddActor(coneActor) ren.AddActor(coneActor)
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
wxEVT_ADD_CONE = 25015 # Using new event binder
wx_EVT_ADD_CONE = wx.NewEventType()
EVT_ADD_CONE = wx.PyEventBinder(wx_EVT_ADD_CONE, 1)
def EVT_ADD_CONE(win, func): class AddCone(wx.PyEvent):
win.Connect(-1, -1, wxEVT_ADD_CONE, func)
class AddCone(wxPyEvent):
def __init__(self): def __init__(self):
wxPyEvent.__init__(self) wx.PyEvent.__init__(self)
self.SetEventType(wxEVT_ADD_CONE) self.SetEventType(wx_EVT_ADD_CONE)
class HiddenCatcher(wxFrame): class HiddenCatcher(wx.Frame):
""" """
The "catcher" frame in the second thread. The "catcher" frame in the second thread.
It is invisible. It's only job is to receive It is invisible. It's only job is to receive
@@ -42,8 +46,8 @@ class HiddenCatcher(wxFrame):
the appropriate windows. the appropriate windows.
""" """
def __init__(self): def __init__(self):
wxFrame.__init__(self, None, -1, '') wx.Frame.__init__(self, None, -1, '')
EVT_ADD_CONE(self, self.AddCone) self.Bind(EVT_ADD_CONE, self.AddCone)
def AddCone(self,evt): def AddCone(self,evt):
add_cone() add_cone()
@@ -51,7 +55,7 @@ class HiddenCatcher(wxFrame):
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class SecondThreadApp(wxApp): class SecondThreadApp(wx.App):
""" """
wxApp that lives in the second thread. wxApp that lives in the second thread.
""" """

View File

@@ -1,36 +1,42 @@
# 11/15/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
# This file is used for the wx.HtmlWindow demo.
#
import sys import sys
from wxPython.wx import * import wx
from wxPython.html import * import wx.html as html
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wx.Panel):
class TestPanel(wxPanel): def __init__(self, parent, id=-1, size=wx.DefaultSize, bgcolor=None):
def __init__(self, parent, id=-1, size=wxDefaultSize, bgcolor=None): wx.Panel.__init__(self, parent, id, size=size)
wxPanel.__init__(self, parent, id, size=size)
if bgcolor: if bgcolor:
self.SetBackgroundColour(bgcolor) self.SetBackgroundColour(bgcolor)
wxStaticText(self, -1, 'Name:', wxPoint(10, 10)) wx.StaticText(self, -1, 'Name:', (10, 10))
wxStaticText(self, -1, 'Email:', wxPoint(10, 40)) wx.StaticText(self, -1, 'Email:', (10, 40))
self.name = wxTextCtrl(self, -1, '', wxPoint(50, 10), wxSize(100, -1)) self.name = wx.TextCtrl(self, -1, '', (50, 10), (100, -1))
self.email = wxTextCtrl(self, -1, '', wxPoint(50, 40), wxSize(100, -1)) self.email = wx.TextCtrl(self, -1, '', (50, 40), (100, -1))
wxButton(self, 12121, 'Okay', wxPoint(50, 70)) wx.Button(self, -1, 'Okay', (50, 70))
EVT_BUTTON(self, 12121, self.OnButton) self.Bind(wx.EVT_BUTTON, self.OnButton)
def OnButton(self, event): def OnButton(self, event):
name = self.name.GetValue() name = self.name.GetValue()
email = self.email.GetValue() email = self.email.GetValue()
dlg = wxMessageDialog(self, dlg = wx.MessageDialog(
'You entered:\n %s\n %s' % (name, email), self, 'You entered:\n %s\n %s' % (name, email),
'Results', style = wxOK | wxICON_INFORMATION) 'Results', style = wx.OK | wx.ICON_INFORMATION
)
dlg.ShowModal() dlg.ShowModal()
dlg.Destroy() dlg.Destroy()
@@ -38,17 +44,29 @@ class TestPanel(wxPanel):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestHtmlPanel(wxPanel): class TestHtmlPanel(wx.Panel):
def __init__(self, parent, id=-1, size=wxDefaultSize): def __init__(self, parent, id=-1, size=wx.DefaultSize):
import About import About
wxPanel.__init__(self, parent, id, size=size)
self.html = wxHtmlWindow(self, -1, wxPoint(5,5), wxSize(400, 350)) wx.Panel.__init__(self, parent, id, size=size)
self.html = html.HtmlWindow(self, -1, (5,5), (400, 350))
py_version = sys.version.split()[0] py_version = sys.version.split()[0]
self.html.SetPage(About.MyAboutBox.text % (wx.__version__, py_version)) self.html.SetPage(About.MyAboutBox.text % (wx.VERSION_STRING, py_version))
ir = self.html.GetInternalRepresentation() ir = self.html.GetInternalRepresentation()
self.html.SetSize( (ir.GetWidth()+5, ir.GetHeight()+5) ) self.html.SetSize( (ir.GetWidth()+5, ir.GetHeight()+5) )
self.Fit() self.Fit()
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def runTest(frame, nb, log):
win = TestHtmlPanel(frame)
return win
#----------------------------------------------------------------------
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -1,56 +1,60 @@
# 11/15/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import *
import cStringIO import cStringIO
import wx
#---------------------------------------------------------------------- #----------------------------------------------------------------------
ArtClients = [ "wxART_TOOLBAR", ArtClients = [ "wx.ART_TOOLBAR",
"wxART_MENU", "wx.ART_MENU",
"wxART_FRAME_ICON", "wx.ART_FRAME_ICON",
"wxART_CMN_DIALOG", "wx.ART_CMN_DIALOG",
"wxART_HELP_BROWSER", "wx.ART_HELP_BROWSER",
"wxART_MESSAGE_BOX", "wx.ART_MESSAGE_BOX",
"wxART_OTHER", "wx.ART_OTHER",
] ]
ArtIDs = [ "wxART_ADD_BOOKMARK", ArtIDs = [ "wx.ART_ADD_BOOKMARK",
"wxART_DEL_BOOKMARK", "wx.ART_DEL_BOOKMARK",
"wxART_HELP_SIDE_PANEL", "wx.ART_HELP_SIDE_PANEL",
"wxART_HELP_SETTINGS", "wx.ART_HELP_SETTINGS",
"wxART_HELP_BOOK", "wx.ART_HELP_BOOK",
"wxART_HELP_FOLDER", "wx.ART_HELP_FOLDER",
"wxART_HELP_PAGE", "wx.ART_HELP_PAGE",
"wxART_GO_BACK", "wx.ART_GO_BACK",
"wxART_GO_FORWARD", "wx.ART_GO_FORWARD",
"wxART_GO_UP", "wx.ART_GO_UP",
"wxART_GO_DOWN", "wx.ART_GO_DOWN",
"wxART_GO_TO_PARENT", "wx.ART_GO_TO_PARENT",
"wxART_GO_HOME", "wx.ART_GO_HOME",
"wxART_FILE_OPEN", "wx.ART_FILE_OPEN",
"wxART_PRINT", "wx.ART_PRINT",
"wxART_HELP", "wx.ART_HELP",
"wxART_TIP", "wx.ART_TIP",
"wxART_REPORT_VIEW", "wx.ART_REPORT_VIEW",
"wxART_LIST_VIEW", "wx.ART_LIST_VIEW",
"wxART_NEW_DIR", "wx.ART_NEW_DIR",
"wxART_FOLDER", "wx.ART_FOLDER",
"wxART_GO_DIR_UP", "wx.ART_GO_DIR_UP",
"wxART_EXECUTABLE_FILE", "wx.ART_EXECUTABLE_FILE",
"wxART_NORMAL_FILE", "wx.ART_NORMAL_FILE",
"wxART_TICK_MARK", "wx.ART_TICK_MARK",
"wxART_CROSS_MARK", "wx.ART_CROSS_MARK",
"wxART_ERROR", "wx.ART_ERROR",
"wxART_QUESTION", "wx.ART_QUESTION",
"wxART_WARNING", "wx.ART_WARNING",
"wxART_INFORMATION", "wx.ART_INFORMATION",
] ]
#----------------------------------------------------------------------
class MyArtProvider(wx.ArtProvider):
class MyArtProvider(wxArtProvider):
def __init__(self, log): def __init__(self, log):
wxArtProvider.__init__(self) wx.ArtProvider.__init__(self)
self.log = log self.log = log
def CreateBitmap(self, artid, client, size): def CreateBitmap(self, artid, client, size):
@@ -60,32 +64,32 @@ class MyArtProvider(wxArtProvider):
# See end of file for the image data # See end of file for the image data
bmp = wxNullBitmap bmp = wx.NullBitmap
# use this one for all 48x48 images # use this one for all 48x48 images
if size.width == 48: if size.width == 48:
bmp = makeBitmap(smile48_png) bmp = makeBitmap(smile48_png)
# but be more specific for these # but be more specific for these
elif size.width == 16 and artid == wxART_ADD_BOOKMARK: elif size.width == 16 and artid == wx.ART_ADD_BOOKMARK:
bmp = makeBitmap(smile16_png) bmp = makeBitmap(smile16_png)
elif size.width == 32 and artid == wxART_ADD_BOOKMARK: elif size.width == 32 and artid == wx.ART_ADD_BOOKMARK:
bmp = makeBitmap(smile32_png) bmp = makeBitmap(smile32_png)
# and just ignore the size for these # and just ignore the size for these
elif artid == wxART_GO_BACK: elif artid == wx.ART_GO_BACK:
bmp = makeBitmap(left_png) bmp = makeBitmap(left_png)
elif artid == wxART_GO_FORWARD: elif artid == wx.ART_GO_FORWARD:
bmp = makeBitmap(right_png) bmp = makeBitmap(right_png)
elif artid == wxART_GO_UP: elif artid == wx.ART_GO_UP:
bmp = makeBitmap(up_png) bmp = makeBitmap(up_png)
elif artid == wxART_GO_DOWN: elif artid == wx.ART_GO_DOWN:
bmp = makeBitmap(down_png) bmp = makeBitmap(down_png)
elif artid == wxART_GO_TO_PARENT: elif artid == wx.ART_GO_TO_PARENT:
bmp = makeBitmap(back_png) bmp = makeBitmap(back_png)
elif artid == wxART_CROSS_MARK: elif artid == wx.ART_CROSS_MARK:
bmp = makeBitmap(cross_png) bmp = makeBitmap(cross_png)
elif artid == wxART_TICK_MARK: elif artid == wx.ART_TICK_MARK:
bmp = makeBitmap(tick_png) bmp = makeBitmap(tick_png)
if bmp.Ok(): if bmp.Ok():
@@ -94,69 +98,69 @@ class MyArtProvider(wxArtProvider):
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.log = log self.log = log
sizer = wxBoxSizer(wxVERTICAL) sizer = wx.BoxSizer(wx.VERTICAL)
title = wxStaticText(self, -1, "wxArtProvider") title = wx.StaticText(self, -1, "ArtProvider")
title.SetFont(wxFont(18, wxSWISS, wxNORMAL, wxBOLD)) title.SetFont(wx.Font(18, wx.SWISS, wx.NORMAL, wx.BOLD))
sizer.AddWindow(title, 0, wxALIGN_CENTRE|wxALL, 5) sizer.Add(title, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
line = wxStaticLine(self, -1, size=(20,-1), style=wxLI_HORIZONTAL) line = wx.StaticLine(self, -1, size=(20,-1), style=wx.LI_HORIZONTAL)
sizer.AddWindow(line, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 5) sizer.Add(line, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
fgs = wxFlexGridSizer(0, 3, 10, 10) fgs = wx.FlexGridSizer(0, 3, 10, 10)
combo = wxComboBox(self, -1, "", choices = ArtClients, combo = wx.ComboBox(self, -1, "", choices = ArtClients,
style = wxCB_DROPDOWN|wxCB_READONLY) style = wx.CB_DROPDOWN|wx.CB_READONLY)
fgs.AddWindow(combo, 0, wxALIGN_CENTRE|wxALL, 5) fgs.Add(combo, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
EVT_COMBOBOX(self, combo.GetId(), self.OnSelectClient) self.Bind(wx.EVT_COMBOBOX, self.OnSelectClient, combo)
combo.Select(0) combo.Select(0)
combo = wxComboBox(self, -1, "", choices = ArtIDs, combo = wx.ComboBox(self, -1, "", choices = ArtIDs,
style = wxCB_DROPDOWN|wxCB_READONLY) style = wx.CB_DROPDOWN|wx.CB_READONLY)
fgs.AddWindow(combo, 0, wxALIGN_CENTRE|wxALL, 5) fgs.Add(combo, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
EVT_COMBOBOX(self, combo.GetId(), self.OnSelectID) self.Bind(wx.EVT_COMBOBOX, self.OnSelectID, combo)
combo.Select(0) combo.Select(0)
cb = wxCheckBox(self, -1, "Use custom provider") cb = wxCheckBox(self, -1, "Use custom provider")
fgs.AddWindow(cb, 0, wxALIGN_CENTRE|wxALL, 5) fgs.Add(cb, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
EVT_CHECKBOX(self, cb.GetId(), self.OnUseCustom) self.Bind(EVT_CHECKBOX, self.OnUseCustom, cb)
fgs.Add((10, 10), 0, wxALIGN_CENTRE|wxALL, 5) fgs.Add((10, 10), 0, wx.ALIGN_CENTRE|wx.ALL, 5)
fgs.Add((10, 10), 0, wxALIGN_CENTRE|wxALL, 5) fgs.Add((10, 10), 0, wx.ALIGN_CENTRE|wx.ALL, 5)
fgs.Add((10, 10), 0, wxALIGN_CENTRE|wxALL, 5) fgs.Add((10, 10), 0, wx.ALIGN_CENTRE|wx.ALL, 5)
box = wxBoxSizer(wxVERTICAL) box = wx.BoxSizer(wx.VERTICAL)
bmp = wxEmptyBitmap(16,16) bmp = wx.EmptyBitmap(16,16)
self.bmp16 = wxStaticBitmap(self, -1, bmp) self.bmp16 = wx.StaticBitmap(self, -1, bmp)
box.AddWindow(self.bmp16, 0, wxALIGN_CENTRE|wxALL, 5) box.Add(self.bmp16, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
text = wxStaticText(self, -1, "16x16") text = wx.StaticText(self, -1, "16x16")
box.AddWindow(text, 0, wxALIGN_CENTRE|wxALL, 5) box.Add(text, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
fgs.AddSizer(box, 0, wxALIGN_CENTRE|wxALL, 5) fgs.Add(box, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
box = wxBoxSizer(wxVERTICAL) box = wx.BoxSizer(wx.VERTICAL)
bmp = wxEmptyBitmap(32,32) bmp = wx.EmptyBitmap(32,32)
self.bmp32 = wxStaticBitmap(self, -1, bmp) self.bmp32 = wx.StaticBitmap(self, -1, bmp)
box.AddWindow(self.bmp32, 0, wxALIGN_CENTRE|wxALL, 5) box.Add(self.bmp32, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
text = wxStaticText(self, -1, "32x32") text = wx.StaticText(self, -1, "32x32")
box.AddWindow(text, 0, wxALIGN_CENTRE|wxALL, 5) box.Add(text, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
fgs.AddSizer(box, 0, wxALIGN_CENTRE|wxALL, 5) fgs.Add(box, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
box = wxBoxSizer(wxVERTICAL) box = wx.BoxSizer(wx.VERTICAL)
bmp = wxEmptyBitmap(48,48) bmp = wx.EmptyBitmap(48,48)
self.bmp48 = wxStaticBitmap(self, -1, bmp) self.bmp48 = wx.StaticBitmap(self, -1, bmp)
box.AddWindow(self.bmp48, 0, wxALIGN_CENTRE|wxALL, 5) box.Add(self.bmp48, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
text = wxStaticText(self, -1, "48x48") text = wx.StaticText(self, -1, "48x48")
box.AddWindow(text, 0, wxALIGN_CENTRE|wxALL, 5) box.Add(text, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
fgs.AddSizer(box, 0, wxALIGN_CENTRE|wxALL, 5) fgs.AddSizer(box, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
sizer.AddSizer(fgs, 0, wxALL, 5) sizer.Add(fgs, 0, wx.ALL, 5)
self.SetSizer(sizer) self.SetSizer(sizer)
self.client = eval(ArtClients[0]) self.client = eval(ArtClients[0])
@@ -179,29 +183,35 @@ class TestPanel(wxPanel):
def OnUseCustom(self, evt): def OnUseCustom(self, evt):
if evt.IsChecked(): if evt.IsChecked():
self.log.write("Images will now be provided by MyArtProvider\n") self.log.write("Images will now be provided by MyArtProvider\n")
wxArtProvider_PushProvider( MyArtProvider(self.log) ) wx.ArtProvider_PushProvider( MyArtProvider(self.log) )
else: else:
self.log.write("MyArtProvider deactivated\n") self.log.write("MyArtProvider deactivated\n")
wxArtProvider_PopProvider() wx.ArtProvider_PopProvider()
self.getArt() self.getArt()
def getArt(self): def getArt(self):
self.log.write("Getting art for %s:%s\n" % (self.client, self.artid)) self.log.write("Getting art for %s:%s\n" % (self.client, self.artid))
bmp = wxArtProvider_GetBitmap(self.artid, self.client, (16,16)) bmp = wx.ArtProvider_GetBitmap(self.artid, self.client, (16,16))
if not bmp.Ok(): if not bmp.Ok():
bmp = wxEmptyBitmap(16,16) bmp = wxEmptyBitmap(16,16)
self.bmp16.SetBitmap(bmp) self.bmp16.SetBitmap(bmp)
bmp = wxArtProvider_GetBitmap(self.artid, self.client, (32,32)) bmp = wx.ArtProvider_GetBitmap(self.artid, self.client, (32,32))
if not bmp.Ok(): if not bmp.Ok():
bmp = wxEmptyBitmap(32,32) bmp = wxEmptyBitmap(32,32)
self.bmp32.SetBitmap(bmp) self.bmp32.SetBitmap(bmp)
bmp = wxArtProvider_GetBitmap(self.artid, self.client, (48,48)) bmp = wx.ArtProvider_GetBitmap(self.artid, self.client, (48,48))
if not bmp.Ok(): if not bmp.Ok():
bmp = wxEmptyBitmap(48,48) bmp = wxEmptyBitmap(48,48)
self.bmp48.SetBitmap(bmp) self.bmp48.SetBitmap(bmp)
@@ -214,7 +224,6 @@ def runTest(frame, nb, log):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
overview = """<html><body> overview = """<html><body>
<h2><center>wxArtProvider</center></h2> <h2><center>wxArtProvider</center></h2>
@@ -242,7 +251,7 @@ provided by wxArtProvider_GetBitmap or wxArtProvider_GetIcon methods.
def makeBitmap(data): def makeBitmap(data):
stream = cStringIO.StringIO(data) stream = cStringIO.StringIO(data)
return wxBitmapFromImage(wxImageFromStream(stream)) return wx.BitmapFromImage(wx.ImageFromStream(stream))
back_png = \ back_png = \

View File

@@ -1,47 +1,50 @@
# 11/15/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import * import wx
import images import images
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1, wx.Panel.__init__(self, parent, -1,
style=wxNO_FULL_REPAINT_ON_RESIZE) style=wx.NO_FULL_REPAINT_ON_RESIZE)
self.log = log self.log = log
b = wxButton(self, 10, "Default Button", wxPoint(20, 20)) b = wx.Button(self, 10, "Default Button", (20, 20))
EVT_BUTTON(self, 10, self.OnClick) self.Bind(EVT_BUTTON, self.OnClick, b)
b.SetDefault() b.SetDefault()
b.SetSize(b.GetBestSize()) b.SetSize(b.GetBestSize())
b = wxButton(self, 20, "HELLO AGAIN!", wxPoint(20, 80), wxSize(120, 45)) b = wx.Button(self, 20, "HELLO AGAIN!", (20, 80), (120, 45))
EVT_BUTTON(self, 20, self.OnClick) self.Bind(EVT_BUTTON, self.OnClick, b)
b.SetToolTipString("This is a Hello button...") b.SetToolTipString("This is a Hello button...")
if 0: # a test case for catching wxPyAssertionError if 0: # a test case for catching wx.PyAssertionError
#wxGetApp().SetAssertMode(wxPYAPP_ASSERT_SUPPRESS) #wx.GetApp().SetAssertMode(wx.PYAPP_ASSERT_SUPPRESS)
#wxGetApp().SetAssertMode(wxPYAPP_ASSERT_EXCEPTION) #wx.GetApp().SetAssertMode(wx.PYAPP_ASSERT_EXCEPTION)
#wxGetApp().SetAssertMode(wxPYAPP_ASSERT_DIALOG) #wx.GetApp().SetAssertMode(wx.PYAPP_ASSERT_DIALOG)
#wxGetApp().SetAssertMode(wxPYAPP_ASSERT_EXCEPTION | wxPYAPP_ASSERT_DIALOG) #wx.GetApp().SetAssertMode(wx.PYAPP_ASSERT_EXCEPTION | wx.PYAPP_ASSERT_DIALOG)
try: try:
bmp = wxBitmap("nosuchfile.bmp", wxBITMAP_TYPE_BMP) bmp = wx.Bitmap("nosuchfile.bmp", wx.BITMAP_TYPE_BMP)
mask = wxMaskColour(bmp, wxBLUE) mask = wx.MaskColour(bmp, wx.BLUE)
except wxPyAssertionError: except wx.PyAssertionError:
self.log.write("Caught wxPyAssertionError! I will fix the problem.\n") self.log.write("Caught wx.PyAssertionError! I will fix the problem.\n")
bmp = images.getTest2Bitmap() bmp = images.getTest2Bitmap()
mask = wxMaskColour(bmp, wxBLUE) mask = wx.MaskColour(bmp, wx.BLUE)
else: else:
bmp = images.getTest2Bitmap() bmp = images.getTest2Bitmap()
mask = wxMaskColour(bmp, wxBLUE) mask = wx.MaskColour(bmp, wx.BLUE)
bmp.SetMask(mask) bmp.SetMask(mask)
wxBitmapButton(self, 30, bmp, wxPoint(160, 20), wx.BitmapButton(self, 30, bmp, (160, 20),
wxSize(bmp.GetWidth()+10, bmp.GetHeight()+10)) (bmp.GetWidth()+10, bmp.GetHeight()+10))
EVT_BUTTON(self, 30, self.OnClick) self.Bind(wx.EVT_BUTTON, self.OnClick, id=30)
def OnClick(self, event): def OnClick(self, event):
@@ -61,9 +64,9 @@ def runTest(frame, nb, log):
overview = """<html><body> overview = """<html><body>
<h2>wxButton</h2> <h2>Button</h2>
A button is a control that contains a text string or a bitmap and cab be A button is a control that contains a text string or a bitmap and can be
placed on nearly any kind of window. placed on nearly any kind of window.
</body></html> </body></html>

View File

@@ -8,12 +8,37 @@
# Date: Feb 26, 2001 # Date: Feb 26, 2001
# Licence: wxWindows license # Licence: wxWindows license
#---------------------------------------------------------------------------- #----------------------------------------------------------------------------
# 11/15/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
# o Some updating of the library itself will be needed for this demo to work
# correctly.
#
# 11/26/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Problems have changed a little. The print dialog requires
# a wx.Size to work with the calendar library. wx.core doesn't
# approve, though, so we get deprecation warnings.
# o Ugh. AFter updating to the Bind() method, things lock up
# on various control clicks. Will have to debug. Only seems
# to happen on windows with calendar controls, though.
#
# 11/30/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Lockup issue clarification: it appears that the spinner is
# the culprit.
#
# 12/01/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o New Bind() method now fully supported.
#
from wxPython.wx import * import os
from wxPython.lib.calendar import wxCalendar, Month, PrtCalDraw, CalenDlg
import wx
import wx.lib.calendar as calendar
import images import images
import os
# highlighted days in month # highlighted days in month
@@ -35,21 +60,25 @@ test_days ={ 0: [],
# test of full window calendar control functions # test of full window calendar control functions
def GetMonthList(): def GetMonthList():
monthlist = [] monthlist = []
for i in range(13): for i in range(13):
name = Month[i] name = calendar.Month[i]
if name != None: if name != None:
monthlist.append(name) monthlist.append(name)
return monthlist return monthlist
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log, frame): def __init__(self, parent, log, frame):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.log = log self.log = log
self.frame = frame self.frame = frame
self.calend = wxCalendar(self, -1, wxPoint(100, 50), wxSize(200, 180)) self.calend = calendar.wxCalendar(self, -1, (100, 50), (200, 180))
# start_month = 2 # preselect the date for calendar # start_month = 2 # preselect the date for calendar
# start_year = 2001 # start_year = 2001
@@ -61,12 +90,13 @@ class TestPanel(wxPanel):
monthlist = GetMonthList() monthlist = GetMonthList()
mID = wxNewId() mID = wx.NewId()
self.date = wxComboBox(self, mID, "", self.date = wx.ComboBox(self, mID, "",
wxPoint(100, 20), wxSize(90, -1), (100, 20), (90, -1),
monthlist, wxCB_DROPDOWN) monthlist, wx.CB_DROPDOWN)
self.date.SetSelection(start_month-1) self.date.SetSelection(start_month-1)
EVT_COMBOBOX(self, mID, self.EvtComboBox) self.Bind(wx.EVT_COMBOBOX, self.EvtComboBox, id=mID)
# set start month and year # set start month and year
@@ -84,56 +114,57 @@ class TestPanel(wxPanel):
self.ResetDisplay() self.ResetDisplay()
# mouse click event # mouse click event
self.Bind(calendar.EVT_CALENDAR, self.MouseClick, self.calend)
self.Connect(self.calend.GetId(), -1, 2100, self.MouseClick)
# scroll bar for month selection # scroll bar for month selection
mID = wxNewId() mID = wx.NewId()
self.scroll = wxScrollBar(self, mID, wxPoint(100, 240), wxSize(200, 20), wxSB_HORIZONTAL)
self.scroll = wx.ScrollBar(self, mID, (100, 240), (200, 20), wx.SB_HORIZONTAL)
self.scroll.SetScrollbar(start_month-1, 1, 12, 1, True) self.scroll.SetScrollbar(start_month-1, 1, 12, 1, True)
EVT_COMMAND_SCROLL(self, mID, self.Scroll) self.Bind(wx.EVT_COMMAND_SCROLL, self.Scroll, id=mID)
# spin control for year selection # spin control for year selection
self.dtext = wxTextCtrl(self, -1, str(start_year), wxPoint(200, 20), wxSize(60, -1)) self.dtext = wx.TextCtrl(self, -1, str(start_year), (200, 20), (60, -1))
h = self.dtext.GetSize().height h = self.dtext.GetSize().height
mID = wxNewId() mID = wx.NewId()
self.spin = wxSpinButton(self, mID, wxPoint(270, 20), wxSize(h*2, h)) self.spin = wx.SpinButton(self, mID, (270, 20), (h*2, h))
self.spin.SetRange(1980, 2010) self.spin.SetRange(1980, 2010)
self.spin.SetValue(start_year) self.spin.SetValue(start_year)
EVT_SPIN(self, mID, self.OnSpin) self.Bind(wx.EVT_SPIN, self.OnSpin, id=mID)
# button for calendar dialog test # button for calendar dialog test
wxStaticText(self, -1, "Test Calendar Dialog", wxPoint(350, 50), wxSize(150, -1)) wx.StaticText(self, -1, "Test Calendar Dialog", (350, 50), (150, -1))
mID = wxNewId() mID = wx.NewId()
bmp = images.getCalendarBitmap() bmp = images.getCalendarBitmap()
self.but = wxBitmapButton(self, mID, bmp, wxPoint(380, 80))#, wxSize(30, 30)) self.but = wx.BitmapButton(self, mID, bmp, (380, 80))
EVT_BUTTON(self, mID, self.TestDlg) self.Bind(wx.EVT_BUTTON, self.TestDlg, id=mID)
# button for calendar window test # button for calendar window test
wxStaticText(self, -1, "Test Calendar Window", wxPoint(350, 150), wxSize(150, -1)) wx.StaticText(self, -1, "Test Calendar Window", (350, 150), (150, -1))
mID = wxNewId() mID = wx.NewId()
self.but = wxBitmapButton(self, mID, bmp, wxPoint(380, 180))#, wxSize(30, 30)) self.but = wx.BitmapButton(self, mID, bmp, (380, 180))
EVT_BUTTON(self, mID, self.TestFrame) self.Bind(wx.EVT_BUTTON, self.TestFrame, id=mID)
wxStaticText(self, -1, "Test Calendar Print", wxPoint(350, 250), wxSize(150, -1)) wx.StaticText(self, -1, "Test Calendar Print", (350, 250), (150, -1))
mID = wxNewId() mID = wx.NewId()
self.but = wxBitmapButton(self, mID, bmp, wxPoint(380, 280))#, wxSize(30, 30)) self.but = wx.BitmapButton(self, mID, bmp, (380, 280))
EVT_BUTTON(self, mID, self.OnPreview) self.Bind(wx.EVT_BUTTON, self.OnPreview, id=mID)
# calendar dialog # calendar dialog
def TestDlg(self, event): # test the date dialog def TestDlg(self, event): # test the date dialog
dlg = CalenDlg(self) dlg = calendar.CalenDlg(self)
dlg.Centre() dlg.Centre()
if dlg.ShowModal() == wxID_OK:
if dlg.ShowModal() == wx.ID_OK:
result = dlg.result result = dlg.result
day = result[1] day = result[1]
month = result[2] month = result[2]
@@ -183,7 +214,7 @@ class TestPanel(wxPanel):
self.ResetDisplay() self.ResetDisplay()
self.log.WriteText('Month: %s\n' % value) self.log.WriteText('Month: %s\n' % value)
name = Month[monthval] name = calendar.Month[monthval]
self.date.SetValue(name) self.date.SetValue(name)
# log mouse events # log mouse events
@@ -197,6 +228,7 @@ class TestPanel(wxPanel):
def ResetDisplay(self): def ResetDisplay(self):
month = self.calend.GetMonth() month = self.calend.GetMonth()
try: try:
set_days = test_days[month] set_days = test_days[month]
except: except:
@@ -230,16 +262,17 @@ class TestPanel(wxPanel):
# test of full window calendar control functions # test of full window calendar control functions
class CalendFrame(wxFrame): class CalendFrame(wx.Frame):
def __init__(self, parent, id, title, log): def __init__(self, parent, id, title, log):
wxFrame.__init__(self, parent, id, title, size=wxSize(400, 400), wx.Frame.__init__(self, parent, id, title, size=(400, 400),
style=wxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE) style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE)
EVT_CLOSE(self, self.OnCloseWindow)
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
self.log = log self.log = log
self.CreateStatusBar() self.CreateStatusBar()
self.mainmenu = wxMenuBar() self.mainmenu = wx.MenuBar()
menu = wxMenu() menu = wx.Menu()
menu = self.MakeFileMenu() menu = self.MakeFileMenu()
self.mainmenu.Append(menu, '&File') self.mainmenu.Append(menu, '&File')
@@ -247,7 +280,7 @@ class CalendFrame(wxFrame):
self.MakeToolMenu() # toolbar self.MakeToolMenu() # toolbar
self.SetMenuBar(self.mainmenu) self.SetMenuBar(self.mainmenu)
self.calend = wxCalendar(self, -1) self.calend = calendar.wxCalendar(self, -1)
self.calend.SetCurrentDay() self.calend.SetCurrentDay()
self.calend.grid_color = 'BLUE' self.calend.grid_color = 'BLUE'
self.calend.SetBusType() self.calend.SetBusType()
@@ -255,7 +288,7 @@ class CalendFrame(wxFrame):
self.ResetDisplay() self.ResetDisplay()
self.Connect(self.calend.GetId(), -1, 2100, self.MouseClick) self.Bind(calendar.EVT_CALENDAR, self.MouseClick, self.calend)
def MouseClick(self, evt): def MouseClick(self, evt):
text = '%s CLICK %02d/%02d/%d' % (evt.click, evt.day, evt.month, evt.year) # format date text = '%s CLICK %02d/%02d/%d' % (evt.click, evt.day, evt.month, evt.year) # format date
@@ -266,6 +299,7 @@ class CalendFrame(wxFrame):
def ResetDisplay(self): def ResetDisplay(self):
month = self.calend.GetMonth() month = self.calend.GetMonth()
try: try:
set_days = test_days[month] set_days = test_days[month]
except: except:
@@ -297,46 +331,46 @@ class CalendFrame(wxFrame):
self.ResetDisplay() self.ResetDisplay()
def MakeFileMenu(self): def MakeFileMenu(self):
menu = wxMenu() menu = wx.Menu()
mID = wxNewId() mID = wx.NewId()
menu.Append(mID, 'Decrement', 'Next') menu.Append(mID, 'Decrement', 'Next')
EVT_MENU(self, mID, self.OnDecMonth) self.Bind(wx.EVT_MENU, self.OnDecMonth, id=mID)
mID = wxNewId() mID = wx.NewId()
menu.Append(mID, 'Increment', 'Dec') menu.Append(mID, 'Increment', 'Dec')
EVT_MENU(self, mID, self.OnIncMonth) self.Bind(wx.EVT_MENU, self.OnIncMonth, id=mID)
menu.AppendSeparator() menu.AppendSeparator()
mID = wxNewId() mID = wx.NewId()
menu.Append(mID, 'E&xit', 'Exit') menu.Append(mID, 'E&xit', 'Exit')
EVT_MENU(self, mID, self.OnCloseWindow) self.Bind(wx.EVT_MENU, self.OnCloseWindow, id=mID)
return menu return menu
def MakeToolMenu(self): def MakeToolMenu(self):
tb = self.CreateToolBar(wxTB_HORIZONTAL|wxNO_BORDER) tb = self.CreateToolBar(wx.TB_HORIZONTAL|wx.NO_BORDER)
mID = wxNewId() mID = wx.NewId()
SetToolPath(self, tb, mID, images.getDbDecBitmap(), 'Dec Year') SetToolPath(self, tb, mID, images.getDbDecBitmap(), 'Dec Year')
EVT_TOOL(self, mID, self.OnDecYear) self.Bind(wx.EVT_TOOL, self.OnDecYear, id=mID)
mID = wxNewId() mID = wx.NewId()
SetToolPath(self, tb, mID, images.getDecBitmap(), 'Dec Month') SetToolPath(self, tb, mID, images.getDecBitmap(), 'Dec Month')
EVT_TOOL(self, mID, self.OnDecMonth) self.Bind(wx.EVT_TOOL, self.OnDecMonth, id=mID)
mID = wxNewId() mID = wx.NewId()
SetToolPath(self, tb, mID, images.getPtBitmap(), 'Current Month') SetToolPath(self, tb, mID, images.getPtBitmap(), 'Current Month')
EVT_TOOL(self, mID, self.OnCurrent) self.Bind(wx.EVT_TOOL, self.OnCurrent, id=mID)
mID = wxNewId() mID = wx.NewId()
SetToolPath(self, tb, mID, images.getIncBitmap(), 'Inc Month') SetToolPath(self, tb, mID, images.getIncBitmap(), 'Inc Month')
EVT_TOOL(self, mID, self.OnIncMonth) self.Bind(wx.EVT_TOOL, self.OnIncMonth, id=mID)
mID = wxNewId() mID = wx.NewId()
SetToolPath(self, tb, mID, images.getDbIncBitmap(), 'Inc Year') SetToolPath(self, tb, mID, images.getDbIncBitmap(), 'Inc Year')
EVT_TOOL(self, mID, self.OnIncYear) self.Bind(wx.EVT_TOOL, self.OnIncYear, id=mID)
tb.Realize() tb.Realize()
@@ -352,15 +386,15 @@ class PrintCalend:
self.SetParms() self.SetParms()
self.SetCal() self.SetCal()
self.printData = wxPrintData() self.printData = wx.PrintData()
def SetCal(self): def SetCal(self):
self.grid_color = 'BLUE' self.grid_color = 'BLUE'
self.back_color = 'WHITE' self.back_color = 'WHITE'
self.sel_color = 'RED' self.sel_color = 'RED'
self.high_color = 'LIGHT BLUE' self.high_color = 'LIGHT BLUE'
self.font = wxSWISS self.font = wx.SWISS
self.bold = wxNORMAL self.bold = wx.NORMAL
self.sel_key = None # last used by self.sel_key = None # last used by
self.sel_lst = [] # highlighted selected days self.sel_lst = [] # highlighted selected days
@@ -404,14 +438,15 @@ class PrintCalend:
def Preview(self): def Preview(self):
printout = SetPrintout(self) printout = SetPrintout(self)
printout2 = SetPrintout(self) printout2 = SetPrintout(self)
self.preview = wxPrintPreview(printout, printout2, self.printData) self.preview = wx.PrintPreview(printout, printout2, self.printData)
if not self.preview.Ok(): if not self.preview.Ok():
wxMessageBox("There was a problem printing!", "Printing", wxOK) wx.MessageBox("There was a problem printing!", "Printing", wx.OK)
return return
self.preview.SetZoom(60) # initial zoom value self.preview.SetZoom(60) # initial zoom value
frame = wxPreviewFrame(self.preview, self.frame, "Print preview") frame = wx.PreviewFrame(self.preview, self.frame, "Print preview")
frame.Initialize() frame.Initialize()
frame.SetPosition(self.frame.GetPosition()) frame.SetPosition(self.frame.GetPosition())
@@ -419,22 +454,24 @@ class PrintCalend:
frame.Show(True) frame.Show(True)
def Print(self): def Print(self):
pdd = wxPrintDialogData() pdd = wx.PrintDialogData()
pdd.SetPrintData(self.printData) pdd.SetPrintData(self.printData)
printer = wxPrinter(pdd) printer = wx.Printer(pdd)
printout = SetPrintout(self) printout = SetPrintout(self)
frame = wxFrame(None, -1, "Test") frame = wx.Frame(None, -1, "Test")
if not printer.Print(frame, printout): if not printer.Print(frame, printout):
wxMessageBox("There was a problem printing.\nPerhaps your current printer is not set correctly?", "Printing", wxOK) wx.MessageBox("There was a problem printing.\nPerhaps your current printer is not set correctly?", "Printing", wx.OK)
else: else:
self.printData = printer.GetPrintDialogData().GetPrintData() self.printData = printer.GetPrintDialogData().GetPrintData()
printout.Destroy() printout.Destroy()
def DoDrawing(self, DC): def DoDrawing(self, DC):
size = DC.GetSizeTuple() size = DC.GetSize()
DC.BeginDrawing() DC.BeginDrawing()
cal = PrtCalDraw(self) cal = calendar.PrtCalDraw(self)
if self.preview is None: if self.preview is None:
cal.SetPSize(size[0]/self.pagew, size[1]/self.pageh) cal.SetPSize(size[0]/self.pagew, size[1]/self.pageh)
@@ -458,14 +495,16 @@ class PrintCalend:
cal.font = self.font cal.font = self.font
cal.bold = self.bold cal.bold = self.bold
cal_size = wxSize(3.0, 3.0) cal_size = (3.0, 3.0)
cal.SetSize(cal_size) cal.SetSize(cal_size)
year, month = self.year, self.month year, month = self.year, self.month
x = 1.0 x = 1.0
for i in range(2): for i in range(2):
y = 0.5 y = 0.5
for j in range(3): for j in range(3):
cal.SetCal(year, month) # current month cal.SetCal(year, month) # current month
cal.SetPos(x, y) cal.SetPos(x, y)
@@ -481,6 +520,7 @@ class PrintCalend:
year, month = self.IncMonth(year, month) year, month = self.IncMonth(year, month)
y = y + 3.5 y = y + 3.5
x = x + 4.0 # next column x = x + 4.0 # next column
DC.EndDrawing() DC.EndDrawing()
@@ -490,6 +530,7 @@ class PrintCalend:
def IncMonth(self, year, month): # next month def IncMonth(self, year, month): # next month
month = month + 1 month = month + 1
if month > 12: if month > 12:
month = 1 month = 1
year = year + 1 year = year + 1
@@ -520,9 +561,9 @@ class PrintCalend:
def SetToolPath(self, tb, id, bmp, title): def SetToolPath(self, tb, id, bmp, title):
tb.AddSimpleTool(id, bmp, title, title) tb.AddSimpleTool(id, bmp, title, title)
class SetPrintout(wxPrintout): class SetPrintout(wx.Printout):
def __init__(self, canvas): def __init__(self, canvas):
wxPrintout.__init__(self) wx.Printout.__init__(self)
self.canvas = canvas self.canvas = canvas
self.end_pg = 1 self.end_pg = 1
@@ -541,10 +582,12 @@ class SetPrintout(wxPrintout):
def GetPageInfo(self): def GetPageInfo(self):
self.end_pg = self.canvas.GetTotalPages() self.end_pg = self.canvas.GetTotalPages()
str_pg = 1 str_pg = 1
try: try:
end_pg = self.end_pg end_pg = self.end_pg
except: except:
end_pg = 1 end_pg = 1
return (str_pg, end_pg, str_pg, end_pg) return (str_pg, end_pg, str_pg, end_pg)
def OnPreparePrinting(self): def OnPreparePrinting(self):
@@ -554,12 +597,13 @@ class SetPrintout(wxPrintout):
dc = self.GetDC() dc = self.GetDC()
self.preview = self.IsPreview() self.preview = self.IsPreview()
if (self.preview): if (self.preview):
self.pixelsPerInch = self.GetPPIScreen() self.pixelsPerInch = self.GetPPIScreen()
else: else:
self.pixelsPerInch = self.GetPPIPrinter() self.pixelsPerInch = self.GetPPIPrinter()
(w, h) = dc.GetSizeTuple() (w, h) = dc.GetSize()
scaleX = float(w) / 1000 scaleX = float(w) / 1000
scaleY = float(h) / 1000 scaleY = float(h) / 1000
self.printUserScale = min(scaleX, scaleY) self.printUserScale = min(scaleX, scaleY)
@@ -576,7 +620,7 @@ class SetPrintout(wxPrintout):
def OnPrintPage(self, page): def OnPrintPage(self, page):
dc = self.GetDC() dc = self.GetDC()
(w, h) = dc.GetSizeTuple() (w, h) = dc.GetSize()
scaleX = float(w) / 1000 scaleX = float(w) / 1000
scaleY = float(h) / 1000 scaleY = float(h) / 1000
self.printUserScale = min(scaleX, scaleY) self.printUserScale = min(scaleX, scaleY)
@@ -596,9 +640,9 @@ class SetPrintout(wxPrintout):
self.canvas.DoDrawing(dc) self.canvas.DoDrawing(dc)
return True return True
class MyApp(wxApp): class MyApp(wx.App):
def OnInit(self): def OnInit(self):
frame = CalendFrame(None, -1, "Test Calendar") frame = CalendFrame(None, -1, "Test Calendar", log)
frame.Show(True) frame.Show(True)
self.SetTopWindow(frame) self.SetTopWindow(frame)
return True return True
@@ -606,7 +650,7 @@ class MyApp(wxApp):
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
def MessageDlg(self, message, type = 'Message'): def MessageDlg(self, message, type = 'Message'):
dlg = wxMessageDialog(self, message, type, wxOK | wxICON_INFORMATION) dlg = wx.MessageDialog(self, message, type, wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal() dlg.ShowModal()
dlg.Destroy() dlg.Destroy()
@@ -620,11 +664,14 @@ def runTest(frame, nb, log):
overview = """\ overview = """\
This control provides a calendar control class for displaying and selecting dates. In addition, the class is extended and can now be used for printing/previewing. This control provides a calendar control class for displaying and selecting dates.
In addition, the class is extended and can now be used for printing/previewing.
Additional features include weekend highlighting and business type Monday-Sunday format. Additional features include weekend highlighting and business type Monday-Sunday
format.
See example for various methods used to set display month, year, and highlighted dates (different font and background colours). See example for various methods used to set display month, year, and highlighted
dates (different font and background colours).
by Lorne White by Lorne White

View File

@@ -1,29 +1,32 @@
# 11/15/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import * import wx
from wxPython.calendar import * import wx.lib.calendar as calendar
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, ID, log): def __init__(self, parent, ID, log):
wxPanel.__init__(self, parent, ID) wx.Panel.__init__(self, parent, ID)
self.log = log self.log = log
cal = wxCalendarCtrl(self, -1, wxDateTime_Now(), pos = (25,50), cal = calendar.CalendarCtrl(self, -1, wx.DateTime_Now(), pos = (25,50),
style = wxCAL_SHOW_HOLIDAYS style = calendar.CAL_SHOW_HOLIDAYS
| wxCAL_SUNDAY_FIRST | calendar.CAL_SUNDAY_FIRST
| wxCAL_SEQUENTIAL_MONTH_SELECTION | calendar.CAL_SEQUENTIAL_MONTH_SELECTION
) )
EVT_CALENDAR(self, cal.GetId(), self.OnCalSelected) self.Bind(calendar.EVT_CALENDAR, self.OnCalSelected, id=cal.GetId())
b = wxButton(self, -1, "Destroy the Calendar", pos = (250, 50)) b = wx.Button(self, -1, "Destroy the Calendar", pos = (250, 50))
EVT_BUTTON(self, b.GetId(), self.OnButton) self.Bind(wx.EVT_BUTTON, self.OnButton, id= b.GetId())
self.cal = cal self.cal = cal
# Set up control to display a set of holidays: # Set up control to display a set of holidays:
EVT_CALENDAR_MONTH(self, cal.GetId(), self.OnChangeMonth) self.Bind(calendar.EVT_CALENDAR_MONTH, self.OnChangeMonth, id=cal.GetId())
self.holidays = [(1,1), (10,31), (12,25) ] # (these don't move around) self.holidays = [(1,1), (10,31), (12,25) ] # (these don't move around)
self.OnChangeMonth() self.OnChangeMonth()
@@ -36,6 +39,7 @@ class TestPanel(wxPanel):
def OnChangeMonth(self, evt=None): def OnChangeMonth(self, evt=None):
cur_month = self.cal.GetDate().GetMonth() + 1 # convert wxDateTime 0-11 => 1-12 cur_month = self.cal.GetDate().GetMonth() + 1 # convert wxDateTime 0-11 => 1-12
for month, day in self.holidays: for month, day in self.holidays:
if month == cur_month: if month == cur_month:
self.cal.SetHoliday(day) self.cal.SetHoliday(day)

View File

@@ -1,26 +1,28 @@
# 11/15/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import * import wx
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class TestCheckBox(wxPanel): class TestCheckBox(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
self.log = log self.log = log
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
wxStaticText(self, -1, "This example uses the wxCheckBox control.", wx.StaticText(self, -1, "This example uses the wxCheckBox control.", (10, 10))
wxPoint(10, 10))
cID = wxNewId() cID = wx.NewId()
cb1 = wxCheckBox(self, cID, " Apples", wxPoint(65, 40), wxSize(150, 20), wxNO_BORDER) cb1 = wx.CheckBox(self, cID, " Apples", (65, 40), (150, 20), wx.NO_BORDER)
cb2 = wxCheckBox(self, cID+1, " Oranges", wxPoint(65, 60), wxSize(150, 20), wxNO_BORDER) cb2 = wx.CheckBox(self, cID+1, " Oranges", (65, 60), (150, 20), wx.NO_BORDER)
cb2.SetValue(True) cb2.SetValue(True)
cb3 = wxCheckBox(self, cID+2, " Pears", wxPoint(65, 80), wxSize(150, 20), wxNO_BORDER) cb3 = wx.CheckBox(self, cID+2, " Pears", (65, 80), (150, 20), wx.NO_BORDER)
EVT_CHECKBOX(self, cID, self.EvtCheckBox)
EVT_CHECKBOX(self, cID+1, self.EvtCheckBox)
EVT_CHECKBOX(self, cID+2, self.EvtCheckBox)
self.Bind(wx.EVT_CHECKBOX, self.EvtCheckBox, cb1)
self.Bind(wx.EVT_CHECKBOX, self.EvtCheckBox, cb2)
self.Bind(wx.EVT_CHECKBOX, self.EvtCheckBox, cb3)
def EvtCheckBox(self, event): def EvtCheckBox(self, event):
self.log.WriteText('EvtCheckBox: %d\n' % event.IsChecked()) self.log.WriteText('EvtCheckBox: %d\n' % event.IsChecked())
@@ -37,16 +39,6 @@ def runTest(frame, nb, log):
overview = """\ overview = """\
A checkbox is a labelled box which is either on (checkmark is visible) or off (no checkmark). A checkbox is a labelled box which is either on (checkmark is visible) or off (no checkmark).

View File

@@ -1,33 +1,34 @@
# 11/15/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
# o Why is there a popup menu in this demo?
#
from wxPython.wx import * import wx
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.log = log self.log = log
sampleList = ['zero', 'one', 'two', 'three', 'four', 'five', sampleList = ['zero', 'one', 'two', 'three', 'four', 'five',
'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven',
'twelve', 'thirteen', 'fourteen'] 'twelve', 'thirteen', 'fourteen']
wxStaticText(self, -1, "This example uses the wxCheckListBox control.", wx.StaticText(self, -1, "This example uses the wxCheckListBox control.", (45, 15))
(45, 15))
lb = wxCheckListBox(self, 60, (80, 50), (80, 120), lb = wx.CheckListBox(self, 60, (80, 50), (80, 120), sampleList)
sampleList) self.Bind(wx.EVT_LISTBOX, self.EvtListBox, id=60)
EVT_LISTBOX(self, 60, self.EvtListBox) self.Bind(wx.EVT_LISTBOX_DCLICK, self.EvtListBoxDClick, id=60)
EVT_LISTBOX_DCLICK(self, 60, self.EvtListBoxDClick)
lb.SetSelection(0) lb.SetSelection(0)
self.lb = lb self.lb = lb
pos = lb.GetPosition().x + lb.GetSize().width + 25 pos = lb.GetPosition().x + lb.GetSize().width + 25
btn = wxButton(self, -1, "Test SetString", (pos, 50)) btn = wx.Button(self, -1, "Test SetString", (pos, 50))
EVT_BUTTON(self, btn.GetId(), self.OnTestButton) self.Bind(wx.EVT_BUTTON, self.OnTestButton, id=btn.GetId())
self.Bind(wx.EVT_RIGHT_UP, self.OnDoPopup)
EVT_RIGHT_UP(self, self.OnDoPopup)
def EvtListBox(self, event): def EvtListBox(self, event):
self.log.WriteText('EvtListBox: %s\n' % event.GetString()) self.log.WriteText('EvtListBox: %s\n' % event.GetString())
@@ -40,19 +41,23 @@ class TestPanel(wxPanel):
def OnDoPopup(self, evt): def OnDoPopup(self, evt):
menu = wxMenu() menu = wx.Menu()
# Make this first item bold # Make this first item bold
item = wxMenuItem(menu, wxNewId(), "If supported, this is bold") item = wx.MenuItem(menu, wx.NewId(), "If supported, this is bold")
df = wxSystemSettings_GetSystemFont(wxSYS_DEFAULT_GUI_FONT) df = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
nf = wxFont(df.GetPointSize(), df.GetFamily(), df.GetStyle(), wxBOLD,
False, df.GetFaceName()) nf = wx.Font(
df.GetPointSize(), df.GetFamily(), df.GetStyle(),
wx.BOLD, False, df.GetFaceName()
)
item.SetFont(nf) item.SetFont(nf)
menu.AppendItem(item) menu.AppendItem(item)
menu.AppendItem(wxMenuItem(menu, wxNewId(), "Normal Item &1")) menu.AppendItem(wx.MenuItem(menu, wx.NewId(), "Normal Item &1"))
menu.AppendItem(wxMenuItem(menu, wxNewId(), "Normal Item &2")) menu.AppendItem(wx.MenuItem(menu, wx.NewId(), "Normal Item &2"))
menu.AppendItem(wxMenuItem(menu, wxNewId(), "Normal Item &3")) menu.AppendItem(wx.MenuItem(menu, wx.NewId(), "Normal Item &3"))
menu.AppendItem(wxMenuItem(menu, wxNewId(), "Normal Item &4")) menu.AppendItem(wx.MenuItem(menu, wx.NewId(), "Normal Item &4"))
self.PopupMenu(menu, evt.GetPosition()) self.PopupMenu(menu, evt.GetPosition())
menu.Destroy() menu.Destroy()
@@ -68,15 +73,18 @@ def runTest(frame, nb, log):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
overview = """\ overview = """\
A checklistbox is like a Listbox, but allows items to be checked or unchecked rather
than relying on extended selection (e.g. shift-select) to select multiple items in
the list.
This class is currently implemented under Windows and GTK.
This demo shows the basic CheckListBox and how to use the SetString method to change
labels dynamically.
""" """
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run

View File

@@ -1,28 +1,33 @@
# 11/15/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import * import wx
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class TestChoice(wxPanel): class TestChoice(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
self.log = log self.log = log
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
sampleList = ['zero', 'one', 'two', 'three', 'four', 'five', sampleList = ['zero', 'one', 'two', 'three', 'four', 'five',
'six', 'seven', 'eight'] 'six', 'seven', 'eight']
wxStaticText(self, -1, "This example uses the wxChoice control.", wx.StaticText(self, -1, "This example uses the wxChoice control.", (15, 10))
wxPoint(15, 10)) wx.StaticText(self, -1, "Select one:", (15, 50), (75, 20))
self.ch = wx.Choice(self, -1, (80, 50), choices = sampleList)
wxStaticText(self, -1, "Select one:", wxPoint(15, 50), wxSize(75, 20)) self.Bind(wx.EVT_CHOICE, self.EvtChoice, self.ch)
self.ch = wxChoice(self, 40, (80, 50), choices = sampleList)
EVT_CHOICE(self, 40, self.EvtChoice)
def EvtChoice(self, event): def EvtChoice(self, event):
self.log.WriteText('EvtChoice: %s\n' % event.GetString()) self.log.WriteText('EvtChoice: %s\n' % event.GetString())
self.ch.Append("A new item") self.ch.Append("A new item")
if event.GetString() == 'one':
self.log.WriteText('Well done!\n')
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
@@ -32,25 +37,22 @@ def runTest(frame, nb, log):
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
overview = """
A Choice control is used to select one of a list of strings. Unlike a listbox,
only the current selection is visible until the user pulls down the menu of
choices.
This demo illustrates how to set up the Choice control and how to extract the
selected choice once it is selected.
Note that the syntax of the constructor is different than the C++ implementation.
The number of choices and the choice array are consilidated into one python
<code>list</code>.
overview = """\
A choice item is used to select one of a list of strings. Unlike a listbox, only the selection is visible until the user pulls down the menu of choices.
""" """
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run

View File

@@ -1,39 +1,57 @@
# 11/15/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import * import wx
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
def runTest(frame, nb, log): def runTest(frame, nb, log):
dlg = wxColourDialog(frame) dlg = wx.ColourDialog(frame)
# Ensure the full colour dialog is displayed,
# not the abbreviated version.
dlg.GetColourData().SetChooseFull(True) dlg.GetColourData().SetChooseFull(True)
if dlg.ShowModal() == wxID_OK:
if dlg.ShowModal() == wx.ID_OK:
# If the user selected OK, then the dialog's wx.ColourData will
# contain valid information. Fetch the data ...
data = dlg.GetColourData() data = dlg.GetColourData()
# ... then do something with it. The actual colour data will be
# returned as a three-tuple (r, g, b) in this particular case.
log.WriteText('You selected: %s\n' % str(data.GetColour().Get())) log.WriteText('You selected: %s\n' % str(data.GetColour().Get()))
# Once the dialog is destroyed, Mr. wx.ColourData is no longer your
# friend. Don't use it again!
dlg.Destroy() dlg.Destroy()
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
overview = """\ overview = """\
This class represents the colour chooser dialog. This class represents the colour chooser dialog.
Use of this dialog is a multi-stage process.
The actual information about how to display the dialog and the colors in the
dialog's 'registers' are contained in a wx.ColourData instance that is created by
the dialog at init time. Before displaying the dialog, you may alter these settings
to suit your needs. In the example, we set the dialog up to show the extended colour
data selection pane. Otherwise, only the more compact and less extensive colour
dialog is shown. You may also preset the colour as well as other items.
If the user selects something and selects OK, then the wxColourData instance contains
the colour data that the user selected. Before destroying the dialog, retrieve the data.
<b>Do not try to retain the wx.ColourData instance.</b> It will probably not be valid
after the dialog is destroyed.
Along with he wxColourDialog documentation, see also the wx.ColourData documentation
for details.
""" """
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run

View File

@@ -1,60 +1,80 @@
from wxPython.wx import * # 11/15/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
import wx
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class TestComboBox(wxPanel): class TestComboBox(wx.Panel):
def OnSetFocus(self, evt): def OnSetFocus(self, evt):
print "OnSetFocus" print "OnSetFocus"
evt.Skip() evt.Skip()
def OnKillFocus(self, evt): def OnKillFocus(self, evt):
print "OnKillFocus" print "OnKillFocus"
evt.Skip() evt.Skip()
def __init__(self, parent, log): def __init__(self, parent, log):
self.log = log self.log = log
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
sampleList = ['zero', 'one', 'two', 'three', 'four', 'five', sampleList = ['zero', 'one', 'two', 'three', 'four', 'five',
##'this is a long item that needs a scrollbar...', #'this is a long item that needs a scrollbar...',
'six', 'seven', 'eight'] 'six', 'seven', 'eight']
wxStaticText(self, -1, "This example uses the wxComboBox control.", wx.StaticText(self, -1, "This example uses the wxComboBox control.", (8, 10))
wxPoint(8, 10)) wx.StaticText(self, -1, "Select one:", (15, 50), (75, 18))
# This combobox is created with a preset list of values.
cb = wx.ComboBox(
self, 500, "default value", (90, 50),
(95, -1), sampleList, wx.CB_DROPDOWN #|wxTE_PROCESS_ENTER
)
wxStaticText(self, -1, "Select one:", wxPoint(15, 50), wxSize(75, 18))
cb = wxComboBox(self, 500, "default value", wxPoint(90, 50), wxSize(95, -1),
sampleList, wxCB_DROPDOWN)#|wxTE_PROCESS_ENTER)
##import win32api, win32con ##import win32api, win32con
##win32api.SendMessage(cb.GetHandle(), ##win32api.SendMessage(cb.GetHandle(),
## win32con.CB_SETHORIZONTALEXTENT, ## win32con.CB_SETHORIZONTALEXTENT,
## 200, 0) ## 200, 0)
EVT_COMBOBOX(self, 500, self.EvtComboBox) self.Bind(wx.EVT_COMBOBOX, self.EvtComboBox, cb)
EVT_TEXT(self, 500, self.EvtText) self.Bind(wx.EVT_TEXT, self.EvtText, cb)
EVT_TEXT_ENTER(self, 500, self.EvtTextEnter) self.Bind(wx.EVT_TEXT_ENTER, self.EvtTextEnter, cb)
EVT_SET_FOCUS(cb, self.OnSetFocus) cb.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
EVT_KILL_FOCUS(cb, self.OnKillFocus) cb.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
# Once the combobox is set up, we append some more data to it.
cb.Append("foo", "This is some client data for this item") cb.Append("foo", "This is some client data for this item")
cb = wxComboBox(self, 501, "default value", wxPoint(90, 80), wxSize(95, -1), # This combobox is created with no values initially.
[], wxCB_SIMPLE) cb = wx.ComboBox(
self, 501, "default value", (90, 80), (95, -1), [], wx.CB_SIMPLE)
# Here we dynamically add our values to the second combobox.
for item in sampleList: for item in sampleList:
cb.Append(item, item.upper()) cb.Append(item, item.upper())
EVT_COMBOBOX(self, 501, self.EvtComboBox)
EVT_TEXT(self, 501, self.EvtText)
self.Bind(wx.EVT_COMBOBOX, self.EvtComboBox, cb)
self.Bind(wx.EVT_COMBOBOX, self.EvtText, cb)
# The user selects something, we go here.
def EvtComboBox(self, evt): def EvtComboBox(self, evt):
cb = evt.GetEventObject() cb = evt.GetEventObject()
data = cb.GetClientData(cb.GetSelection()) data = cb.GetClientData(cb.GetSelection())
self.log.WriteText('EvtComboBox: %s\nClientData: %s\n' % (evt.GetString(), data)) self.log.WriteText('EvtComboBox: %s\nClientData: %s\n' % (evt.GetString(), data))
if evt.GetString() == 'one':
self.log.WriteText("You follow directions well!\n\n")
# Capture events every time a user hits a key in the text entry field.
def EvtText(self, evt): def EvtText(self, evt):
self.log.WriteText('EvtText: %s\n' % evt.GetString()) self.log.WriteText('EvtText: %s\n' % evt.GetString())
# Capture events when the user types something into the control then
# hits ENTER.
def EvtTextEnter(self, evt): def EvtTextEnter(self, evt):
self.log.WriteText('EvtTextEnter: does this work?') self.log.WriteText('EvtTextEnter: %s' % evt.GetString())
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
@@ -66,17 +86,28 @@ def runTest(frame, nb, log):
overview = """\ overview = """\
A combobox is like a combination of an edit control and a listbox. It can be displayed as static list with editable or read-only text field; or a drop-down list with text field; or a drop-down list without a text field. A ComboBox is like a combination of an edit control and a listbox. It can be
displayed as static list with editable or read-only text field; or a drop-down
list with text field; or a drop-down list without a text field.
This example shows both a preset ComboBox and one that is dynamically created
(that is, it is initially empty but then we 'grow' it out of program-supplied
data). The former is common for read-only controls.
This example also shows the two form factors for the ComboBox. The first is more
common, and resembles a Choice control. The latter, although less common, shows
how all the values in the ComboBox can be visible, yet the functionality is the
same for both.
Finally, this demo shows how event handling can differ. The first ComboBox is set
up to handle EVT_TEXT_ENTER events, in which text is typed in and then ENTER is
hit by the user. This allows the user to enter a line of text which can then be
processed by the program. EVT_TEXT can also be processed, but in that case the
event is generated every time that the user hits a key in the ComboBox entry field.
""" """
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run

View File

@@ -1,120 +1,135 @@
# 11/15/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import * import wx
##from wxPython.help import *
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
# Create and set a help provider. Normally you would do this in # Create and set a help provider. Normally you would do this in
# the app's OnInit as it must be done before any SetHelpText calls. # the app's OnInit as it must be done before any SetHelpText calls.
provider = wxSimpleHelpProvider() provider = wx.SimpleHelpProvider()
wxHelpProvider_Set(provider) wx.HelpProvider_Set(provider)
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class TestDialog(wxDialog): class TestDialog(wx.Dialog):
def __init__(self, parent, ID, title, def __init__(
pos=wxDefaultPosition, size=wxDefaultSize, self, parent, ID, title, size=wx.DefaultSize, pos=wx.DefaultPosition,
style=wxDEFAULT_DIALOG_STYLE): style=wx.DEFAULT_DIALOG_STYLE
):
# Instead of calling wxDialog.__init__ we precreate the dialog # Instead of calling wxDialog.__init__ we precreate the dialog
# object so we can set an extra style that must be set before # so we can set an extra style that must be set before
# creation, and then we create the GUI dialog using the Create # creation, and then we create the GUI dialog using the Create
# method. # method.
pre = wxPreDialog() pre = wx.PreDialog()
pre.SetExtraStyle(wxDIALOG_EX_CONTEXTHELP) pre.SetExtraStyle(wx.DIALOG_EX_CONTEXTHELP)
pre.Create(parent, ID, title, pos, size, style) pre.Create(parent, ID, title, pos, size, style)
# This next step is the most important, it turns this Python # This next step is the most important, it turns this Python
# object into the real wrapper of the dialog (instead of pre) # object into the real wrapper of the dialog (instead of pre)
# as far as the wxPython extension is concerned. # as far as the wxPython extension is concerned.
self.PostCreate(pre) self.this = pre.this
# Now continue with the normal construction of the dialog # Now continue with the normal construction of the dialog
# contents # contents
sizer = wxBoxSizer(wxVERTICAL) sizer = wx.BoxSizer(wx.VERTICAL)
label = wxStaticText(self, -1, "This is a wxDialog") label = wx.StaticText(self, -1, "This is a wxDialog")
label.SetHelpText("This is the help text for the label") label.SetHelpText("This is the help text for the label")
sizer.Add(label, 0, wxALIGN_CENTRE|wxALL, 5) sizer.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
box = wxBoxSizer(wxHORIZONTAL) box = wx.BoxSizer(wx.HORIZONTAL)
label = wxStaticText(self, -1, "Field #1:") label = wx.StaticText(self, -1, "Field #1:")
label.SetHelpText("This is the help text for the label") label.SetHelpText("This is the help text for the label")
box.Add(label, 0, wxALIGN_CENTRE|wxALL, 5) box.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
text = wxTextCtrl(self, -1, "", size=(80,-1)) text = wx.TextCtrl(self, -1, "", size=(80,-1))
text.SetHelpText("Here's some help text for field #1") text.SetHelpText("Here's some help text for field #1")
box.Add(text, 1, wxALIGN_CENTRE|wxALL, 5) box.Add(text, 1, wx.ALIGN_CENTRE|wx.ALL, 5)
sizer.AddSizer(box, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 5) sizer.AddSizer(box, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
box = wxBoxSizer(wxHORIZONTAL) box = wx.BoxSizer(wx.HORIZONTAL)
label = wxStaticText(self, -1, "Field #2:") label = wx.StaticText(self, -1, "Field #2:")
label.SetHelpText("This is the help text for the label") label.SetHelpText("This is the help text for the label")
box.Add(label, 0, wxALIGN_CENTRE|wxALL, 5) box.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
text = wxTextCtrl(self, -1, "", size=(80,-1)) text = wx.TextCtrl(self, -1, "", size=(80,-1))
text.SetHelpText("Here's some help text for field #2") text.SetHelpText("Here's some help text for field #2")
box.Add(text, 1, wxALIGN_CENTRE|wxALL, 5) box.Add(text, 1, wx.ALIGN_CENTRE|wx.ALL, 5)
sizer.AddSizer(box, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 5) sizer.AddSizer(box, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
line = wxStaticLine(self, -1, size=(20,-1), style=wxLI_HORIZONTAL) line = wx.StaticLine(self, -1, size=(20,-1), style=wx.LI_HORIZONTAL)
sizer.Add(line, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxRIGHT|wxTOP, 5) sizer.Add(line, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.RIGHT|wx.TOP, 5)
box = wxBoxSizer(wxHORIZONTAL) box = wx.BoxSizer(wx.HORIZONTAL)
if wxPlatform != "__WXMSW__": if wx.Platform != "__WXMSW__":
btn = wxContextHelpButton(self) btn = wx.ContextHelpButton(self)
box.Add(btn, 0, wxALIGN_CENTRE|wxALL, 5) box.Add(btn, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
btn = wxButton(self, wxID_OK, " OK ") btn = wx.Button(self, wx.ID_OK, " OK ")
btn.SetDefault() btn.SetDefault()
btn.SetHelpText("The OK button completes the dialog") btn.SetHelpText("The OK button completes the dialog")
box.Add(btn, 0, wxALIGN_CENTRE|wxALL, 5) box.Add(btn, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
btn = wxButton(self, wxID_CANCEL, " Cancel ") btn = wx.Button(self, wx.ID_CANCEL, " Cancel ")
btn.SetHelpText("The Cancel button cnacels the dialog. (Duh!)") btn.SetHelpText("The Cancel button cnacels the dialog. (Cool, huh?)")
box.Add(btn, 0, wxALIGN_CENTRE|wxALL, 5) box.Add(btn, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
sizer.Add(box, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5) sizer.Add(box, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
self.SetSizer(sizer) self.SetSizer(sizer)
self.SetAutoLayout(True) self.SetAutoLayout(True)
sizer.Fit(self) sizer.Fit(self)
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
def runTest(frame, nb, log): def runTest(frame, nb, log):
win = TestDialog(frame, -1, "This is a wxDialog", size=wxSize(350, 200), win = TestDialog(frame, -1, "This is a Dialog", size=(350, 200),
#style = wxCAPTION | wxSYSTEM_MENU | wxTHICK_FRAME #style = wxCAPTION | wxSYSTEM_MENU | wxTHICK_FRAME
style = wxDEFAULT_DIALOG_STYLE style = wx.DEFAULT_DIALOG_STYLE
) )
win.CenterOnScreen() win.CenterOnScreen()
val = win.ShowModal() val = win.ShowModal()
if val == wxID_OK:
if val == wx.ID_OK:
log.WriteText("You pressed OK\n") log.WriteText("You pressed OK\n")
else: else:
log.WriteText("You pressed Cancel\n") log.WriteText("You pressed Cancel\n")
win.Destroy() win.Destroy()
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
overview = """\ overview = """\
wxPython offers quite a few general purpose dialogs for useful data input from
the user; they are all based on the wx.Dialog class, which you can also subclass
to create custom dialogs to suit your needs.
The Dialog class, in addition to dialog-like behaviors, also supports the full
wxWindows layout featureset, which means that you can incorporate sizers or
layout constraints as needed to achieve the look and feel desired. It even supports
context-sensitive help, which is illustrated in this example.
The example is very simple; in real world situations, a dialog that had input
fields such as this would no doubt be required to deliver those values back to
the calling function. The Dialog class supports data retrieval in this manner.
<b>However, the data must be retrieved prior to the dialog being destroyed.</b>
The example shown here is <i>modal</i>; non-modal dialogs are possible as well.
See the documentation for the <code>Dialog</code> class for more details.
""" """
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run

View File

@@ -1,23 +1,35 @@
# 11/17/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import * import wx
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
def runTest(frame, nb, log): def runTest(frame, nb, log):
dlg = wxDirDialog(frame, "Choose a directory:",
style=wxDD_DEFAULT_STYLE|wxDD_NEW_DIR_BUTTON) # In this case we include a "New directory" button.
if dlg.ShowModal() == wxID_OK: dlg = wx.DirDialog(frame, "Choose a directory:",
style=wx.DD_DEFAULT_STYLE|wx.DD_NEW_DIR_BUTTON)
# If the user selects OK, then we process the dialog's data.
# This is done by getting the path data from the dialog - BEFORE
# we destroy it.
if dlg.ShowModal() == wx.ID_OK:
log.WriteText('You selected: %s\n' % dlg.GetPath()) log.WriteText('You selected: %s\n' % dlg.GetPath())
# Only destroy a dialog after you're done with it.
dlg.Destroy() dlg.Destroy()
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
overview = """\ overview = """\
This class represents the directory chooser dialog. This class represents the directory chooser dialog. It is used when all you
need from the user is the name of a directory. Data is retrieved via utility
methods; see the <code>DirDialog</code> documentation for specifics.
""" """

View File

@@ -1,6 +1,9 @@
# 11/15/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import * import wx
import images import images
#---------------------------------------------------------------------- #----------------------------------------------------------------------
@@ -8,25 +11,22 @@ import images
class DragShape: class DragShape:
def __init__(self, bmp): def __init__(self, bmp):
self.bmp = bmp self.bmp = bmp
self.pos = wxPoint(0,0) self.pos = (0,0)
self.shown = True self.shown = True
self.text = None self.text = None
self.fullscreen = False self.fullscreen = False
def HitTest(self, pt): def HitTest(self, pt):
rect = self.GetRect() rect = self.GetRect()
return rect.InsideXY(pt.x, pt.y) return rect.InsideXY(pt.x, pt.y)
def GetRect(self): def GetRect(self):
return wxRect(self.pos.x, self.pos.y, return wx.Rect(self.pos[0], self.pos[1],
self.bmp.GetWidth(), self.bmp.GetHeight()) self.bmp.GetWidth(), self.bmp.GetHeight())
def Draw(self, dc, op = wx.COPY):
def Draw(self, dc, op = wxCOPY):
if self.bmp.Ok(): if self.bmp.Ok():
memDC = wxMemoryDC() memDC = wx.MemoryDC()
memDC.SelectObject(self.bmp) memDC.SelectObject(self.bmp)
dc.Blit((self.pos.x, self.pos.y), dc.Blit((self.pos.x, self.pos.y),
@@ -41,100 +41,111 @@ class DragShape:
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class DragCanvas(wxScrolledWindow): class DragCanvas(wx.ScrolledWindow):
def __init__(self, parent, ID): def __init__(self, parent, ID):
wxScrolledWindow.__init__(self, parent, ID) wx.ScrolledWindow.__init__(self, parent, ID)
self.shapes = [] self.shapes = []
self.dragImage = None self.dragImage = None
self.dragShape = None self.dragShape = None
self.hiliteShape = None self.hiliteShape = None
self.SetCursor(wxStockCursor(wxCURSOR_ARROW)) self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
self.bg_bmp = images.getBackgroundBitmap() self.bg_bmp = images.getBackgroundBitmap()
# Make a shape from an image and mask. This one will demo # Make a shape from an image and mask. This one will demo
# dragging outside the window # dragging outside the window
bmp = images.getTestStarBitmap() bmp = images.getTestStarBitmap()
shape = DragShape(bmp) shape = DragShape(bmp)
shape.pos = wxPoint(5, 5) shape.pos = (5, 5)
shape.fullscreen = True shape.fullscreen = True
self.shapes.append(shape) self.shapes.append(shape)
# Make a shape from some text # Make a shape from some text
text = "Some Text" text = "Some Text"
bg_colour = wxColour(57, 115, 57) # matches the bg image bg_colour = wx.Colour(57, 115, 57) # matches the bg image
font = wxFont(15, wxROMAN, wxNORMAL, wxBOLD) font = wx.Font(15, wx.ROMAN, wx.NORMAL, wx.BOLD)
textExtent = self.GetFullTextExtent(text, font) textExtent = self.GetFullTextExtent(text, font)
bmp = wxEmptyBitmap(textExtent[0], textExtent[1])
dc = wxMemoryDC() # create a bitmap the same size as our text
bmp = wx.EmptyBitmap(textExtent[0], textExtent[1])
# 'draw' the text onto the bitmap
dc = wx.MemoryDC()
dc.SelectObject(bmp) dc.SelectObject(bmp)
dc.SetBackground(wxBrush(bg_colour, wxSOLID)) dc.SetBackground(wx.Brush(bg_colour, wx.SOLID))
dc.Clear() dc.Clear()
dc.SetTextForeground(wxRED) dc.SetTextForeground(wx.RED)
dc.SetFont(font) dc.SetFont(font)
dc.DrawText(text, (0, 0)) dc.DrawText(text, (0, 0))
dc.SelectObject(wxNullBitmap) dc.SelectObject(wxNullBitmap)
mask = wxMaskColour(bmp, bg_colour) mask = wxMaskColour(bmp, bg_colour)
bmp.SetMask(mask) bmp.SetMask(mask)
shape = DragShape(bmp) shape = DragShape(bmp)
shape.pos = wxPoint(5, 100) shape.pos = (5, 100)
shape.text = "Some dragging text" shape.text = "Some dragging text"
self.shapes.append(shape) self.shapes.append(shape)
# Make some shapes from some playing card images. # Make some shapes from some playing card images.
x = 200 x = 200
for card in ['_01c_', '_12h_', '_13d_', '_10s_']: for card in ['_01c_', '_12h_', '_13d_', '_10s_']:
bmpFunc = getattr(images, "get%sBitmap" % card) bmpFunc = getattr(images, "get%sBitmap" % card)
bmp = bmpFunc() bmp = bmpFunc()
shape = DragShape(bmp) shape = DragShape(bmp)
shape.pos = wxPoint(x, 5) shape.pos = (x, 5)
self.shapes.append(shape) self.shapes.append(shape)
x = x + 80 x = x + 80
EVT_ERASE_BACKGROUND(self, self.OnEraseBackground) self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
EVT_PAINT(self, self.OnPaint) self.Bind(wx.EVT_PAINT, self.OnPaint)
EVT_LEFT_DOWN(self, self.OnLeftDown) self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
EVT_LEFT_UP(self, self.OnLeftUp) self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
EVT_MOTION(self, self.OnMotion) self.Bind(wx.EVT_MOTION, self.OnMotion)
EVT_LEAVE_WINDOW(self, self.OnLeaveWindow) self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)
# We're not doing anything here, but you might have reason to.
# for example, if you were dragging something, you might elect to
# 'drop it' when the cursor left the window.
def OnLeaveWindow(self, evt): def OnLeaveWindow(self, evt):
pass pass
def TileBackground(self, dc):
# tile the background bitmap # tile the background bitmap
def TileBackground(self, dc):
sz = self.GetClientSize() sz = self.GetClientSize()
w = self.bg_bmp.GetWidth() w = self.bg_bmp.GetWidth()
h = self.bg_bmp.GetHeight() h = self.bg_bmp.GetHeight()
x = 0 x = 0
while x < sz.width: while x < sz.width:
y = 0 y = 0
while y < sz.height: while y < sz.height:
dc.DrawBitmap(self.bg_bmp, (x, y)) dc.DrawBitmap(self.bg_bmp, (x, y))
y = y + h y = y + h
x = x + w x = x + w
# Go through our list of shapes and draw them in whatever place they are.
def DrawShapes(self, dc): def DrawShapes(self, dc):
for shape in self.shapes: for shape in self.shapes:
if shape.shown: if shape.shown:
shape.Draw(dc) shape.Draw(dc)
# This is actually a sophisticated 'hit test', but in this
# case we're also determining which shape, if any, was 'hit'.
def FindShape(self, pt): def FindShape(self, pt):
for shape in self.shapes: for shape in self.shapes:
if shape.HitTest(pt): if shape.HitTest(pt):
return shape return shape
return None return None
# Remove a shape from the display
def EraseShape(self, shape, dc): def EraseShape(self, shape, dc):
r = shape.GetRect() r = shape.GetRect()
dc.SetClippingRect(r) dc.SetClippingRect(r)
@@ -142,55 +153,80 @@ class DragCanvas(wxScrolledWindow):
self.DrawShapes(dc) self.DrawShapes(dc)
dc.DestroyClippingRegion() dc.DestroyClippingRegion()
# Clears the background, then redraws it. If the DC is passed, then
# we only do so in the area so designated. Otherwise, it's the whole thing.
def OnEraseBackground(self, evt): def OnEraseBackground(self, evt):
dc = evt.GetDC() dc = evt.GetDC()
if not dc: if not dc:
dc = wxClientDC(self) dc = wxClientDC(self)
rect = self.GetUpdateRegion().GetBox() rect = self.GetUpdateRegion().GetBox()
dc.SetClippingRect(rect) dc.SetClippingRect(rect)
self.TileBackground(dc) self.TileBackground(dc)
# Fired whenever a paint event occurs
def OnPaint(self, evt): def OnPaint(self, evt):
dc = wxPaintDC(self) dc = wx.PaintDC(self)
self.PrepareDC(dc) self.PrepareDC(dc)
self.DrawShapes(dc) self.DrawShapes(dc)
# Left mouse button is down.
def OnLeftDown(self, evt): def OnLeftDown(self, evt):
# Did the mouse go down on one of our shapes?
shape = self.FindShape(evt.GetPosition()) shape = self.FindShape(evt.GetPosition())
# If a shape was 'hit', then set that as the shape we're going to
# drag around. Get our start position. Dragging has not yet started.
# That will happen once the mouse moves, OR the mouse is released.
if shape: if shape:
# get ready to start dragging, but wait for the user to
# move it a bit first
self.dragShape = shape self.dragShape = shape
self.dragStartPos = evt.GetPosition() self.dragStartPos = evt.GetPosition()
# Left mouse button up.
def OnLeftUp(self, evt): def OnLeftUp(self, evt):
if not self.dragImage or not self.dragShape: if not self.dragImage or not self.dragShape:
self.dragImage = None self.dragImage = None
self.dragShape = None self.dragShape = None
return return
# end the dragging # Hide the image, end dragging, and nuke out the drag image.
self.dragImage.Hide() self.dragImage.Hide()
self.dragImage.EndDrag() self.dragImage.EndDrag()
self.dragImage = None self.dragImage = None
dc = wxClientDC(self) dc = wx.ClientDC(self)
if self.hiliteShape: if self.hiliteShape:
self.hiliteShape.Draw(dc) self.hiliteShape.Draw(dc)
self.hiliteShape = None self.hiliteShape = None
# reposition and draw the shape # reposition and draw the shape
self.dragShape.pos = self.dragShape.pos + evt.GetPosition() - self.dragStartPos
# Note by jmg 11/28/03
# Here's the original:
#
# self.dragShape.pos = self.dragShape.pos + evt.GetPosition() - self.dragStartPos
#
# So if there are any problems associated with this, use that as
# a starting place in your investigation. I've tried to simulate the
# wx.Point __add__ method here -- it won't work for tuples as we
# have now from the various methods
#
# There must be a better way to do this :-)
#
self.dragShape.pos = (
self.dragShape.pos[0] + evt.GetPosition()[0] - self.dragStartPos[0],
self.dragShape.pos[1] + evt.GetPosition()[1] - self.dragStartPos[1]
)
self.dragShape.shown = True self.dragShape.shown = True
self.dragShape.Draw(dc) self.dragShape.Draw(dc)
self.dragShape = None self.dragShape = None
# The mouse is moving
def OnMotion(self, evt): def OnMotion(self, evt):
# Ignore mouse movement if we're not dragging.
if not self.dragShape or not evt.Dragging() or not evt.LeftIsDown(): if not self.dragShape or not evt.Dragging() or not evt.LeftIsDown():
return return
@@ -206,17 +242,17 @@ class DragCanvas(wxScrolledWindow):
return return
# erase the shape since it will be drawn independently now # erase the shape since it will be drawn independently now
dc = wxClientDC(self) dc = wx.ClientDC(self)
self.dragShape.shown = False self.dragShape.shown = False
self.EraseShape(self.dragShape, dc) self.EraseShape(self.dragShape, dc)
if self.dragShape.text: if self.dragShape.text:
self.dragImage = wxDragString(self.dragShape.text, self.dragImage = wx.DragString(self.dragShape.text,
wxStockCursor(wxCURSOR_HAND)) wx.StockCursor(wx.CURSOR_HAND))
else: else:
self.dragImage = wxDragImage(self.dragShape.bmp, self.dragImage = wx.DragImage(self.dragShape.bmp,
wxStockCursor(wxCURSOR_HAND)) wx.StockCursor(wx.CURSOR_HAND))
hotspot = self.dragStartPos - self.dragShape.pos hotspot = self.dragStartPos - self.dragShape.pos
self.dragImage.BeginDrag(hotspot, self, self.dragShape.fullscreen) self.dragImage.BeginDrag(hotspot, self, self.dragShape.fullscreen)
@@ -244,14 +280,14 @@ class DragCanvas(wxScrolledWindow):
self.dragImage.Hide() self.dragImage.Hide()
if unhiliteOld: if unhiliteOld:
dc = wxClientDC(self) dc = wx.ClientDC(self)
self.hiliteShape.Draw(dc) self.hiliteShape.Draw(dc)
self.hiliteShape = None self.hiliteShape = None
if hiliteNew: if hiliteNew:
dc = wxClientDC(self) dc = wx.ClientDC(self)
self.hiliteShape = onShape self.hiliteShape = onShape
self.hiliteShape.Draw(dc, wxINVERT) self.hiliteShape.Draw(dc, wx.INVERT)
# now move it and show it again if needed # now move it and show it again if needed
self.dragImage.Move(evt.GetPosition()) self.dragImage.Move(evt.GetPosition())
@@ -262,10 +298,14 @@ class DragCanvas(wxScrolledWindow):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def runTest(frame, nb, log): def runTest(frame, nb, log):
win = wxPanel(nb, -1)
win = wx.Panel(nb, -1)
canvas = DragCanvas(win, -1) canvas = DragCanvas(win, -1)
def onSize(evt, panel=win, canvas=canvas): canvas.SetSize(panel.GetSize())
EVT_SIZE(win, onSize) def onSize(evt, panel=win, canvas=canvas):
canvas.SetSize(panel.GetSize())
win.Bind(wx.EVT_SIZE, onSize)
return win return win
#---------------------------------------------------------------------- #----------------------------------------------------------------------
@@ -273,6 +313,28 @@ def runTest(frame, nb, log):
overview = """\ overview = """\
DragImage is used when you wish to drag an object on the screen, and a simple
cursor is not enough.
On Windows, the WIN32 API is used to do achieve smooth dragging. On other
platforms, <code>GenericDragImage</code> is used. Applications may also prefer to use
<code>GenericDragImage</code> on Windows, too.
<b>wxPython note</b>: wxPython uses <code>GenericDragImage</code> on all
platforms, but uses the <code>DragImage</code> name.
To use this class, when you wish to start dragging an image, create a
<code>DragImage</code> object and store it somewhere you can access it as the
drag progresses. Call BeginDrag to start, and EndDrag to stop the drag. To move
the image, initially call Show and then Move. If you wish to update the screen
contents during the drag (for example, highlight an item as in the example), first
call Hide, update the screen, call Move, and then call Show.
You can drag within one window, or you can use full-screen dragging either across
the whole screen, or just restricted to one area of the screen to save resources.
If you want the user to drag between two windows, then you will need to use
full-screen dragging.
""" """

View File

@@ -1,23 +1,29 @@
# 11/17/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import * import wx
from wxPython.gizmos import * import wx.gizmos as gizmos
from wxPython.stc import * import wx.stc as stc
#---------------------------------------------------------------------- #----------------------------------------------------------------------
# This is an example of the complex view that manages its own scrollbars # This is an example of the complex view that manages its own scrollbars
# as described in the overview below. # as described in the overview below.
class TestView(wxStyledTextCtrl): class TestView(stc.StyledTextCtrl):
def __init__(self, parent, ID, log): def __init__(self, parent, ID, log):
wxStyledTextCtrl.__init__(self, parent, ID, style=wxNO_BORDER) stc.StyledTextCtrl.__init__(self, parent, ID, style=wx.NO_BORDER)
self.dyn_sash = parent self.dyn_sash = parent
self.log = log self.log = log
self.SetupScrollBars() self.SetupScrollBars()
self.SetMarginWidth(1,0) self.SetMarginWidth(1,0)
self.StyleSetFont(wxSTC_STYLE_DEFAULT,
wxFont(10, wxMODERN, wxNORMAL, wxNORMAL)) self.StyleSetFont(stc.STC_STYLE_DEFAULT,
EVT_DYNAMIC_SASH_SPLIT(self, -1, self.OnSplit) wx.Font(10, wx.MODERN, wx.NORMAL, wx.NORMAL))
EVT_DYNAMIC_SASH_UNIFY(self, -1, self.OnUnify)
self.Bind(gizmos.EVT_DYNAMIC_SASH_SPLIT, self.OnSplit)
self.Bind(gizmos.EVT_DYNAMIC_SASH_UNIFY, self.OnUnify)
#self.SetScrollWidth(500) #self.SetScrollWidth(500)
def SetupScrollBars(self): def SetupScrollBars(self):
@@ -25,10 +31,10 @@ class TestView(wxStyledTextCtrl):
# to this view # to this view
v_bar = self.dyn_sash.GetVScrollBar(self) v_bar = self.dyn_sash.GetVScrollBar(self)
h_bar = self.dyn_sash.GetHScrollBar(self) h_bar = self.dyn_sash.GetHScrollBar(self)
EVT_SCROLL(v_bar, self.OnSBScroll) v_bar.Bind(wx.EVT_SCROLL, self.OnSBScroll)
EVT_SCROLL(h_bar, self.OnSBScroll) h_bar.Bind(wx.EVT_SCROLL, self.OnSBScroll)
EVT_SET_FOCUS(v_bar, self.OnSBFocus) v_bar.Bind(wx.EVT_SET_FOCUS, self.OnSBFocus)
EVT_SET_FOCUS(h_bar, self.OnSBFocus) h_bar.Bind(wx.EVT_SET_FOCUS, self.OnSBFocus)
# And set the wxStyledText to use these scrollbars instead # And set the wxStyledText to use these scrollbars instead
# of its built-in ones. # of its built-in ones.
@@ -67,20 +73,20 @@ continue splitting the new views as much as you like. Try it and see.
In this case the views also share the same document so changes in one In this case the views also share the same document so changes in one
are instantly seen in the others. This is a feature of the are instantly seen in the others. This is a feature of the
wxStyledTextCtrl that is used for the view class in this sample. StyledTextCtrl that is used for the view class in this sample.
""" """
#---------------------------------------------------------------------- #----------------------------------------------------------------------
# This one is simpler, but doesn't do anything with the scrollbars # This one is simpler, but doesn't do anything with the scrollbars
# except the default wxDynamicSashWindow behaviour # except the default wxDynamicSashWindow behaviour
class SimpleView(wxPanel): class SimpleView(wx.Panel):
def __init__(self, parent, ID, log): def __init__(self, parent, ID, log):
wxPanel.__init__(self, parent, ID) wx.Panel.__init__(self, parent, ID)
self.dyn_sash = parent self.dyn_sash = parent
self.log = log self.log = log
self.SetBackgroundColour("LIGHT BLUE") self.SetBackgroundColour("LIGHT BLUE")
EVT_DYNAMIC_SASH_SPLIT(self, -1, self.OnSplit) self.Bind(gizmos.EVT_DYNAMIC_SASH_SPLIT, self.OnSplit)
def OnSplit(self, evt): def OnSplit(self, evt):
v = SimpleView(self.dyn_sash, -1, self.log) v = SimpleView(self.dyn_sash, -1, self.log)
@@ -89,21 +95,21 @@ class SimpleView(wxPanel):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def runTest(frame, nb, log): def runTest(frame, nb, log):
if wxPlatform == "__WXMAC__": if wx.Platform == "__WXMAC__":
wxMessageBox("This demo currently fails on the Mac. The problem is being looked into...", "Sorry") wx.MessageBox("This demo currently fails on the Mac. The problem is being looked into...", "Sorry")
return return
if 1: if 1:
win = wxDynamicSashWindow(nb, -1, style = 0 win = gizmos.DynamicSashWindow(nb, -1, style = wx.CLIP_CHILDREN
| wxCLIP_CHILDREN
#| wxDS_MANAGE_SCROLLBARS #| wxDS_MANAGE_SCROLLBARS
#| wxDS_DRAG_CORNER #| wxDS_DRAG_CORNER
) )
win.SetFont(wxFont(10, wxMODERN, wxNORMAL, wxNORMAL))
win.SetFont(wx.Font(10, wx.MODERN, wx.NORMAL, wx.NORMAL))
view = TestView(win, -1, log) view = TestView(win, -1, log)
view.SetText(sampleText) view.SetText(sampleText)
else: else:
win = wxDynamicSashWindow(nb, -1) win = wx.DynamicSashWindow(nb, -1)
view = SimpleView(win, -1, log) view = SimpleView(win, -1, log)
return win return win
@@ -111,7 +117,7 @@ def runTest(frame, nb, log):
overview = """\ overview = """\
<html><body> <html><body>
<h2>wxDynamicSashWindow</h2> <h2>DynamicSashWindow</h2>
<p> <p>
wxDynamicSashWindow widgets manages the way other widgets are viewed. wxDynamicSashWindow widgets manages the way other widgets are viewed.
When a wxDynamicSashWindow is first shown, it will contain one child When a wxDynamicSashWindow is first shown, it will contain one child

View File

@@ -1,17 +1,23 @@
from wxPython.wx import * # 11/17/2003 - Jeff Grimmett (grimmtooth@softhome.net)
from wxPython.gizmos import * #
# o Updated for wx namespace
# o Added overview text based on source code delving.
#
import wx
import wx.gizmos as gizmos
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.log = log self.log = log
self.elb = wxEditableListBox(self, -1, "List of Stuff", self.elb = gizmos.EditableListBox(
(50,50), (250, 250), self, -1, "List of Stuff", (50,50), (250, 250)
) )
#style=wxEL_ALLOW_NEW | wxEL_ALLOW_EDIT | wxEL_ALLOW_DELETE) #style=wx.EL_ALLOW_NEW | wx.EL_ALLOW_EDIT | wx.EL_ALLOW_DELETE)
self.elb.SetStrings(["This is a nifty ListBox widget", self.elb.SetStrings(["This is a nifty ListBox widget",
"that is editable by the user.", "that is editable by the user.",
@@ -29,21 +35,66 @@ def runTest(frame, nb, log):
win = TestPanel(nb, log) win = TestPanel(nb, log)
return win return win
#---------------------------------------------------------------------- #----------------------------------------------------------------------
overview = """\ overview = """\
This class provides a composite control that lets the <html>
user easily enter and edit a list of strings. <body>
This class provides a composite control that lets the user easily enter and edit
a list of strings.
<p><b>Styles supported:</b><p>
<ul>
<li><b>EL_ALLOW_NEW</b> - Allow user to create new items.
<li><b>EL_ALLOW_EDIT</b> - Allow user to edit text in the control.
<li><b>EL_ALLOW_DELETE</b> - Allow user to delete text from the control.
</ul>
<p><b>Init:</b>
<pre>
EditableListBox(wxWindow *parent, wxWindowID id=-1,
const wxString& label,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = EL_ALLOW_NEW | EL_ALLOW_EDIT | EL_ALLOW_DELETE,
const wxString& name = "editableListBox")
</pre>
<p><b>Methods:</b>
<ul>
<li><b>SetStrings(const wxArrayString& strings)</b> - Set an array of strings
into the control. <b>Note</b>: The wxPython method accepts a Python list instead
of an array of strings.
<li><b>void GetStrings(wxArrayString& strings)</b> - Retrieves an array
of strings from the control. The wxPython version returns a list of strings.
<li><b>GetListCtrl()</b> - Retrieves a reference to the actual list control
portion of the custom control.
<li><b>GetDelButton()</b> - Retrieves a reference to the BitmapButton that is used
as the 'delete' button in the control.
<li><b>GetNewButton()</b> - Retrieves a reference to the BitmapButton that is used
as the 'new' button in the control.
<li><b>GetUpButton()</b> - Retrieves a reference to the BitmapButton that is used
as the 'up' button in the control.
<li><b>GetDownButton()</b> - Retrieves a reference to the BitmapButton that is used
as the 'down' button in the control.
<li><b>GetEditButton()</b> - Retrieves a reference to the BitmapButton that is used
as the 'edit' button in the control.
</ul>
</body>
</html>
""" """
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run

View File

@@ -1,14 +1,22 @@
# 11/17/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
# 11/28/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o editor lib hasn't been hit by the renamer yet.
#
from wxPython.wx import * import wx
from wxPython.lib.editor import wxEditor import wx.lib.editor as editor
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def runTest(frame, nb, log): def runTest(frame, nb, log):
win = wxPanel(nb, -1) win = wx.Panel(nb, -1)
ed = wxEditor(win, -1, style=wxSUNKEN_BORDER) ed = editor.wxEditor(win, -1, style=wx.SUNKEN_BORDER)
box = wxBoxSizer(wxVERTICAL) box = wx.BoxSizer(wx.VERTICAL)
box.Add(ed, 1, wxALL|wxGROW, 1) box.Add(ed, 1, wx.ALL|wx.GROW, 1)
win.SetSizer(box) win.SetSizer(box)
win.SetAutoLayout(True) win.SetAutoLayout(True)
@@ -57,7 +65,6 @@ component. One example of this might be to change the key
Alt key commands. In that case you would (for example) override the Alt key commands. In that case you would (for example) override the
SetAltFuncs() method. SetAltFuncs() method.
""" """

View File

@@ -1,38 +1,64 @@
# 11/17/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import *
import os import os
import wx
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
# This is how you pre-establish a file filter so that the dialog
# only shows the extention(s) you want it to.
wildcard = "Python source (*.py)|*.py|" \ wildcard = "Python source (*.py)|*.py|" \
"Compiled Python (*.pyc)|*.pyc|" \ "Compiled Python (*.pyc)|*.pyc|" \
"All files (*.*)|*.*" "All files (*.*)|*.*"
def runTest(frame, nb, log): def runTest(frame, nb, log):
log.WriteText("CWD: %s\n" % os.getcwd()) log.WriteText("CWD: %s\n" % os.getcwd())
dlg = wxFileDialog(frame, "Choose a file", os.getcwd(), "", wildcard,
wxOPEN # Create the dialog. In this case the current directory is forced as the starting
| wxMULTIPLE # directory for the dialog, and no default file name is forced. This can easilly
#| wxCHANGE_DIR # be changed in your program. This is an 'open' dialog, and allows multitple
# file selection to boot.
#
# Finally, of the directory is changed in the process of getting files, this
# dialog is set up to change the current working directory to the path chosen.
dlg = wx.FileDialog(
frame, message="Choose a file", defaultDir=os.getcwd(),
defaultFile="", wildcard=wildcard, style=wx.OPEN | wx.MULTIPLE | wx.CHANGE_DIR
) )
if dlg.ShowModal() == wxID_OK:
# Show the dialog and retrieve the user response. If it is the OK response,
# process the data.
if dlg.ShowModal() == wx.ID_OK:
# This returns a Python list of files that were selected.
paths = dlg.GetPaths() paths = dlg.GetPaths()
log.WriteText('You selected %d files:' % len(paths)) log.WriteText('You selected %d files:' % len(paths))
for path in paths: for path in paths:
log.WriteText(' %s\n' % path) log.WriteText(' %s\n' % path)
# Compare this with the debug above; did we change working dirs?
log.WriteText("CWD: %s\n" % os.getcwd()) log.WriteText("CWD: %s\n" % os.getcwd())
# Destroy the dialog. Don't do this until you are done with it!
# BAD things can happen otherwise!
dlg.Destroy() dlg.Destroy()
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
overview = """\ overview = """\
This class provides the file chooser dialog. This class provides the file selection dialog. It incorporates OS-native features
depending on the OS in use, and can be used both for open and save operations.
The files displayed can be filtered by setting up a wildcard filter, multiple files
can be selected (open only), and files can be forced in a read-only mode.
There are two ways to get the results back from the dialog. GetFiles() returns only
the file names themselves, in a Python list. GetPaths() returns the full path and
filenames combined as a Python list.
""" """

View File

@@ -1,9 +1,15 @@
# 11/17/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import *
import os import os
import wx
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
# This is how you pre-establish a file filter so that the dialog
# only shows the extention(s) you want it to.
wildcard = "Python source (*.py)|*.py|" \ wildcard = "Python source (*.py)|*.py|" \
"Compiled Python (*.pyc)|*.pyc|" \ "Compiled Python (*.pyc)|*.pyc|" \
"SPAM files (*.spam)|*.spam|" \ "SPAM files (*.spam)|*.spam|" \
@@ -12,28 +18,69 @@ wildcard = "Python source (*.py)|*.py|" \
def runTest(frame, nb, log): def runTest(frame, nb, log):
log.WriteText("CWD: %s\n" % os.getcwd()) log.WriteText("CWD: %s\n" % os.getcwd())
dlg = wxFileDialog(frame, "Save file as...", os.getcwd(), "", wildcard,
wxSAVE # Create the dialog. In this case the current directory is forced as the starting
#| wxCHANGE_DIR # directory for the dialog, and no default file name is forced. This can easilly
# be changed in your program. This is an 'save' dialog.
#
# Unlike the 'open dialog' example found elsewhere, this example does NOT
# force the current working directory to change if the user chooses a different
# directory than the one initially set.
dlg = wx.FileDialog(
frame, message="Save file as ...", defaultDir=os.getcwd(),
defaultFile="", wildcard=wildcard, style=wx.SAVE
) )
# This sets the default filter that the user will initially see. Otherwise,
# the first filter in the list will be used by default.
dlg.SetFilterIndex(2) dlg.SetFilterIndex(2)
if dlg.ShowModal() == wxID_OK:
# Show the dialog and retrieve the user response. If it is the OK response,
# process the data.
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath() path = dlg.GetPath()
log.WriteText('You selected "%s"' % path) log.WriteText('You selected "%s"' % path)
# Normally, at this point you would save your data using the file and path
# data that the user provided to you, but since we didn't actually start
# with any data to work with, that would be difficult.
#
# The code to do so would be similar to this, assuming 'data' contains
# the data you want to save:
#
# fp = file(path, 'w') # Create file anew
# fp.write(data)
# fp.close()
#
# You might want to add some error checking :-)
#
# Note that the current working dir didn't change. This is good since
# that's the way we set it up.
log.WriteText("CWD: %s\n" % os.getcwd()) log.WriteText("CWD: %s\n" % os.getcwd())
# Destroy the dialog. Don't do this until you are done with it!
# BAD things can happen otherwise!
dlg.Destroy() dlg.Destroy()
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
overview = """\ overview = """\
This class provides the file chooser dialog. This class provides the file selection dialog. It incorporates OS-native features
depending on the OS in use, and can be used both for open and save operations.
The files displayed can be filtered by setting up a wildcard filter, multiple files
can be selected (open only), and files can be forced in a read-only mode.
There are two ways to get the results back from the dialog. GetFiles() returns only
the file names themselves, in a Python list. GetPaths() returns the full path and
filenames combined as a Python list.
One important thing to note: if you use the file extention filters, then files saved
with the filter set to something will automatically get that extention appended to them
if it is not already there. For example, suppose the dialog was displaying the 'egg'
extention and you entered a file name of 'fried'. It would be saved as 'fried.egg.'
Yum!
""" """

View File

@@ -1,68 +1,83 @@
# 11/17/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import *
import os import os
import wx
#---------------------------------------------------------------------- #----------------------------------------------------------------------
text = """\ text = """\
Right-click on the panel to get a menu. This menu will be managed by Right-click on the panel above the line to get a menu. This menu will
a wxFileHistory object and so the files you select will automatically be managed by a FileHistory object and so the files you select will
be added to the end of the menu and will be selectable the next time automatically be added to the end of the menu and will be selectable
the menu is viewed. The filename selected, either via the Open menu the next time the menu is viewed. The filename selected, either via the
item, or from the history, will be displayed in the log window below. Open menu item, or from the history, will be displayed in the log
window below.
""" """
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
self.log = log self.log = log
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
box = wxBoxSizer(wxVERTICAL) box = wx.BoxSizer(wx.VERTICAL)
# Make and layout the controls # Make and layout the controls
fs = self.GetFont().GetPointSize() fs = self.GetFont().GetPointSize()
bf = wxFont(fs+4, wxSWISS, wxNORMAL, wxBOLD) bf = wx.Font(fs+4, wx.SWISS, wx.NORMAL, wx.BOLD)
nf = wxFont(fs+2, wxSWISS, wxNORMAL, wxNORMAL) nf = wx.Font(fs+2, wx.SWISS, wx.NORMAL, wx.NORMAL)
t = wxStaticText(self, -1, "wxFileHistory") t = wx.StaticText(self, -1, "FileHistory")
t.SetFont(bf) t.SetFont(bf)
box.Add(t, 0, wxCENTER|wxALL, 5) box.Add(t, 0, wx.CENTER|wx.ALL, 5)
box.Add(wxStaticLine(self, -1), 0, wxEXPAND) box.Add(wx.StaticLine(self, -1), 0, wx.EXPAND)
box.Add((10,20)) box.Add((10,20))
t = wxStaticText(self, -1, text) t = wx.StaticText(self, -1, text)
t.SetFont(nf) t.SetFont(nf)
box.Add(t, 0, wxCENTER|wxALL, 5) box.Add(t, 0, wx.CENTER|wx.ALL, 5)
self.SetSizer(box) self.SetSizer(box)
self.SetAutoLayout(True) self.SetAutoLayout(True)
# Make a menu # Make a menu
self.menu = m = wxMenu() self.menu = m = wx.Menu()
m.Append(wxID_NEW, "&New")
m.Append(wxID_OPEN, "&Open...") # Little know wx Fact #42: there are a number of pre-set IDs
m.Append(wxID_CLOSE, "&Close") # in the wx package, to be used for common controls such as those
m.Append(wxID_SAVE, "&Save") # illustrated below. Neat, huh?
m.Append(wxID_SAVEAS, "Save &as...") m.Append(wx.ID_NEW, "&New")
m.Enable(wxID_NEW, False) m.Append(wx.ID_OPEN, "&Open...")
m.Enable(wxID_CLOSE, False) m.Append(wx.ID_CLOSE, "&Close")
m.Enable(wxID_SAVE, False) m.Append(wx.ID_SAVE, "&Save")
m.Enable(wxID_SAVEAS, False) m.Append(wx.ID_SAVEAS, "Save &as...")
m.Enable(wx.ID_NEW, False)
m.Enable(wx.ID_CLOSE, False)
m.Enable(wx.ID_SAVE, False)
m.Enable(wx.ID_SAVEAS, False)
# and a file history # and a file history
self.filehistory = wxFileHistory() self.filehistory = wx.FileHistory()
self.filehistory.UseMenu(self.menu) self.filehistory.UseMenu(self.menu)
# and finally the event handler bindings # and finally the event handler bindings
EVT_RIGHT_UP(self, self.OnRightClick) self.Bind(wx.EVT_RIGHT_UP, self.OnRightClick)
EVT_MENU(self, wxID_OPEN, self.OnFileOpenDialog)
EVT_MENU_RANGE(self, wxID_FILE1, wxID_FILE9, self.OnFileHistory) self.Bind(wx.EVT_MENU, self.OnFileOpenDialog, id=wx.ID_OPEN)
EVT_WINDOW_DESTROY(self, self.Cleanup)
self.Bind(
wx.EVT_MENU_RANGE, self.OnFileHistory, id=wx.ID_FILE1, id2=wx.ID_FILE9
)
self.Bind(wx.EVT_WINDOW_DESTROY, self.Cleanup)
def Cleanup(self, *args): def Cleanup(self, *args):
# A little extra cleanup is required for the FileHistory control
del self.filehistory del self.filehistory
self.menu.Destroy() self.menu.Destroy()
@@ -72,11 +87,12 @@ class TestPanel(wxPanel):
def OnFileOpenDialog(self, evt): def OnFileOpenDialog(self, evt):
dlg = wxFileDialog(self, dlg = wx.FileDialog(self,
defaultDir = os.getcwd(), defaultDir = os.getcwd(),
wildcard = "All Files|*", wildcard = "All Files|*",
style = wxOPEN | wxCHANGE_DIR) style = wx.OPEN | wx.CHANGE_DIR)
if dlg.ShowModal() == wxID_OK:
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath() path = dlg.GetPath()
self.log.write("You selected %s\n" % path) self.log.write("You selected %s\n" % path)
@@ -88,7 +104,7 @@ class TestPanel(wxPanel):
def OnFileHistory(self, evt): def OnFileHistory(self, evt):
# get the file based on the menu ID # get the file based on the menu ID
fileNum = evt.GetId() - wxID_FILE1 fileNum = evt.GetId() - wx.ID_FILE1
path = self.filehistory.GetHistoryFile(fileNum) path = self.filehistory.GetHistoryFile(fileNum)
self.log.write("You selected %s\n" % path) self.log.write("You selected %s\n" % path)
@@ -108,12 +124,19 @@ def runTest(frame, nb, log):
overview = """<html><body> overview = """<html><body>
<h3>wxFileHistory</h3> <h3>FileHistory</h3>
wxFileHistory encapsulates functionality to record the last few files wxFileHistory encapsulates functionality to record the last few files
visited, and to allow the user to quickly load these files using the visited, and to allow the user to quickly load these files using the
list appended to a menu, such as the File menu. list appended to a menu, such as the File menu.
<p>Note that this inclusion is not automatic; as illustrated in this example,
you must add files (and remove them) as deemed necessary within the framework
of your program.
<p>Note also the additional cleanup required for this class, namely trapping the
enclosing window's Destroy event and deleting the file history control and its
associated menu.
</body></html> </body></html>
""" """

View File

@@ -1,56 +1,79 @@
# 11/17/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
# 11/28/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Changed the event binding slightly.
# o There are issues with the GetReplaceText() method of the
# FindDialogEvent. Must be retested when this is fixed.
#
from wxPython.wx import * import wx
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.log = log self.log = log
b = wxButton(self, -1, "Show Find Dialog", (25, 50)) b = wx.Button(self, -1, "Show Find Dialog", (25, 50))
EVT_BUTTON(self, b.GetId(), self.OnShowFind) self.Bind(wx.EVT_BUTTON, self.OnShowFind, b)
b = wxButton(self, -1, "Show Find && Replace Dialog", (25, 90)) b = wx.Button(self, -1, "Show Find && Replace Dialog", (25, 90))
EVT_BUTTON(self, b.GetId(), self.OnShowFindReplace) self.Bind(wx.EVT_BUTTON, self.OnShowFindReplace, b)
EVT_COMMAND_FIND(self, -1, self.OnFind)
EVT_COMMAND_FIND_NEXT(self, -1, self.OnFind) # jg - 11/28/03 - corrected a long standing issue here where
EVT_COMMAND_FIND_REPLACE(self, -1, self.OnFind) # EVT_COMMAND_FIND_* was being used for these event binders
EVT_COMMAND_FIND_REPLACE_ALL(self, -1, self.OnFind) # instead of the actual event IDs shown below. As a result,
EVT_COMMAND_FIND_CLOSE(self, -1, self.OnFindClose) # onFind() was never showing the appropriate type. I guess
# nobody really paid much attention to that little
# debugging window :-)
#
self.Bind(wx.EVT_FIND, self.OnFind)
self.Bind(wx.EVT_FIND_NEXT, self.OnFind)
self.Bind(wx.EVT_FIND_REPLACE, self.OnFind)
self.Bind(wx.EVT_FIND_REPLACE_ALL, self.OnFind)
self.Bind(wx.EVT_FIND_CLOSE, self.OnFindClose)
def OnShowFind(self, evt): def OnShowFind(self, evt):
data = wxFindReplaceData() data = wx.FindReplaceData()
dlg = wxFindReplaceDialog(self, data, "Find") dlg = wx.FindReplaceDialog(self, data, "Find")
dlg.data = data # save a reference to it... dlg.data = data # save a reference to it...
dlg.Show(True) dlg.Show(True)
def OnShowFindReplace(self, evt): def OnShowFindReplace(self, evt):
data = wxFindReplaceData() data = wx.FindReplaceData()
dlg = wxFindReplaceDialog(self, data, "Find & Replace", wxFR_REPLACEDIALOG) dlg = wx.FindReplaceDialog(self, data, "Find & Replace", wx.FR_REPLACEDIALOG)
dlg.data = data # save a reference to it... dlg.data = data # save a reference to it...
dlg.Show(True) dlg.Show(True)
def OnFind(self, evt): def OnFind(self, evt):
map = { map = {
wxEVT_COMMAND_FIND : "FIND", wx.wxEVT_COMMAND_FIND : "FIND",
wxEVT_COMMAND_FIND_NEXT : "FIND_NEXT", wx.wxEVT_COMMAND_FIND_NEXT : "FIND_NEXT",
wxEVT_COMMAND_FIND_REPLACE : "REPLACE", wx.wxEVT_COMMAND_FIND_REPLACE : "REPLACE",
wxEVT_COMMAND_FIND_REPLACE_ALL : "REPLACE_ALL", wx.wxEVT_COMMAND_FIND_REPLACE_ALL : "REPLACE_ALL",
} }
et = evt.GetEventType() et = evt.GetEventType()
try: #print evt.GetReplaceString()
if et in map:
evtType = map[et] evtType = map[et]
except KeyError: else:
evtType = "**Unknown Event Type**" evtType = "**Unknown Event Type**"
if et == wxEVT_COMMAND_FIND_REPLACE or et == wxEVT_COMMAND_FIND_REPLACE_ALL: #>> Todo: the GetReplaceString() method is broken. Has to be
replaceTxt = "Replace text: " + evt.GetReplaceString() # fixed.
if et == wx.EVT_COMMAND_FIND_REPLACE or et == wx.EVT_COMMAND_FIND_REPLACE_ALL:
replaceTxt = "Replace text: %s" % evt.GetReplaceString()
else: else:
replaceTxt = "" replaceTxt = ""
@@ -59,7 +82,7 @@ class TestPanel(wxPanel):
def OnFindClose(self, evt): def OnFindClose(self, evt):
self.log.write("wxFindReplaceDialog closing...\n") self.log.write("FindReplaceDialog closing...\n")
evt.GetDialog().Destroy() evt.GetDialog().Destroy()
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
@@ -74,7 +97,20 @@ def runTest(frame, nb, log):
overview = """\ overview = """\
A generic find and replace dialog. FindReplaceDialog is a standard modeless dialog which is used to allow the user
to search for some text (and possibly replace it with something else). The actual
searching is supposed to be done in the owner window which is the parent of this
dialog. Note that it means that unlike for the other standard dialogs this one
<u>must have a parent window</u>. Also note that there is no way to use this
dialog in a modal way; <b>it is always, by design and implementation, modeless</b>.
FileReplaceDialog requires the use of <b>FindReplaceData</b>. This holds the
data for the dialog. It is used to initialize the dialog with the default values
and will keep the last values from the dialog when it is closed. It is also
updated each time a FindDialogEvent is generated so instead of using the
FindDialogEvent methods you can also directly query this object. <b>Care must be
taken not to use this object after the dialog is destroyed.</b> The data within
will be invalid after the parent dialog is destroyed.
""" """

View File

@@ -1,53 +1,69 @@
from wxPython.wx import * # 11/18/2003 - Jeff Grimmett (grimmtooth@softhome.net)
from wxPython.lib.floatbar import * #
# o Updated for wx namespace
# o OK, Main.py indicates this is deprecated. But I don't see a
# replacement yet. So conversion is done anyway.
#
# 11/28/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Issues - library has to be converted to work properly
# with new namespace.
#
import wx
import wx.lib.floatbar as float
import images import images
class TestFloatBar(wxFrame): class TestFloatBar(wx.Frame):
def __init__(self, parent, log): def __init__(self, parent, log):
wxFrame.__init__(self, parent, -1, 'Test ToolBar', wx.Frame.__init__(
wxPoint(0,0), wxSize(500, 300)) self, parent, -1, 'Test ToolBar', wx.DefaultPosition, (500, 300)
)
self.log = log self.log = log
win = wxWindow(self, -1) win = wx.Window(self, -1)
win.SetBackgroundColour(wxNamedColour("WHITE")) win.SetBackgroundColour("WHITE")
wxStaticText(win, -1, "Drag the toolbar to float it,\n" wx.StaticText(
"Toggle the last tool to remove\nthe title.", wxPoint(15,15)) win, -1, "Drag the toolbar to float it,\n"
"Toggle the last tool to remove\nthe title.", (15,15)
)
tb = wxFloatBar(self, -1) tb = float.wxFloatBar(self, -1)
self.SetToolBar(tb) self.SetToolBar(tb)
tb.SetFloatable(1) tb.SetFloatable(1)
tb.SetTitle("Floating!") tb.SetTitle("Floating!")
self.CreateStatusBar() self.CreateStatusBar()
tb.AddSimpleTool(10, images.getNewBitmap(), "New", "Long help for 'New'") tb.AddSimpleTool(10, images.getNewBitmap(), "New", "Long help for 'New'")
EVT_TOOL(self, 10, self.OnToolClick) self.Bind(wx.EVT_TOOL, self.OnToolClick, id=10)
EVT_TOOL_RCLICKED(self, 10, self.OnToolRClick) self.Bind(wx.EVT_TOOL_RCLICKED, self.OnToolRClick, id=10)
tb.AddSimpleTool(20, images.getOpenBitmap(), "Open") tb.AddSimpleTool(20, images.getOpenBitmap(), "Open")
EVT_TOOL(self, 20, self.OnToolClick) self.Bind(wx.EVT_TOOL, self.OnToolClick, id=20)
EVT_TOOL_RCLICKED(self, 20, self.OnToolRClick) self.Bind(wx.EVT_TOOL_RCLICKED, self.OnToolRClick, id=20)
tb.AddSeparator() tb.AddSeparator()
tb.AddSimpleTool(30, images.getCopyBitmap(), "Copy") tb.AddSimpleTool(30, images.getCopyBitmap(), "Copy")
EVT_TOOL(self, 30, self.OnToolClick) self.Bind(wx.EVT_TOOL, self.OnToolClick, id=30)
EVT_TOOL_RCLICKED(self, 30, self.OnToolRClick) self.Bind(wx.EVT_TOOL_RCLICKED, self.OnToolRClick, id=30)
tb.AddSimpleTool(40, images.getPasteBitmap(), "Paste") tb.AddSimpleTool(40, images.getPasteBitmap(), "Paste")
EVT_TOOL(self, 40, self.OnToolClick) self.Bind(wx.EVT_TOOL, self.OnToolClick, id=40)
EVT_TOOL_RCLICKED(self, 40, self.OnToolRClick) self.Bind(wx.EVT_TOOL_RCLICKED, self.OnToolRClick, id=40)
tb.AddSeparator() tb.AddSeparator()
tb.AddCheckTool(60, images.getTog1Bitmap(), images.getTog2Bitmap()) tb.AddCheckTool(60, images.getTog1Bitmap(), images.getTog2Bitmap())
EVT_TOOL(self, 60, self.OnToolClick) self.Bind(wx.EVT_TOOL, self.OnToolClick, id=60)
EVT_TOOL_RCLICKED(self, 60, self.OnToolRClick) self.Bind(wx.EVT_TOOL_RCLICKED, self.OnToolRClick, id=60)
tb.Realize() tb.Realize()
self.tb = tb self.tb = tb
EVT_CLOSE(self, self.OnCloseWindow) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
def OnCloseWindow(self, event): def OnCloseWindow(self, event):
@@ -55,8 +71,10 @@ class TestFloatBar(wxFrame):
def OnToolClick(self, event): def OnToolClick(self, event):
self.log.WriteText("tool %s clicked\n" % event.GetId()) self.log.WriteText("tool %s clicked\n" % event.GetId())
if event.GetId() == 60: if event.GetId() == 60:
print event.GetExtraLong(), event.Checked(), event.GetInt(), self.tb.GetToolState(60) print event.GetExtraLong(), event.Checked(), event.GetInt(), self.tb.GetToolState(60)
if event.GetExtraLong(): if event.GetExtraLong():
self.tb.SetTitle("") self.tb.SetTitle("")
else: else:
@@ -83,12 +101,6 @@ close it to make the toolbar return to its original position.
""" """
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run

View File

@@ -1,69 +1,73 @@
# 11/18/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import * import wx
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.log = log self.log = log
btn = wxButton(self, -1, "Select Font") btn = wx.Button(self, -1, "Select Font")
EVT_BUTTON(self, btn.GetId(), self.OnSelectFont) self.Bind(wx.EVT_BUTTON, self.OnSelectFont, btn)
self.sampleText = wxTextCtrl(self, -1, "Sample Text") self.sampleText = wx.TextCtrl(self, -1, "Sample Text")
#from wxPython.lib.stattext import wxGenStaticText #from wxPython.lib.stattext import wxGenStaticText
#self.sampleText = wxGenStaticText(self, -1, "Sample Text") #self.sampleText = wxGenStaticText(self, -1, "Sample Text")
self.curFont = self.sampleText.GetFont() self.curFont = self.sampleText.GetFont()
self.curClr = wxBLACK self.curClr = wx.BLACK
fgs = wxFlexGridSizer(cols=2, vgap=5, hgap=5) fgs = wx.FlexGridSizer(cols=2, vgap=5, hgap=5)
fgs.AddGrowableCol(1) fgs.AddGrowableCol(1)
fgs.AddGrowableRow(0) fgs.AddGrowableRow(0)
fgs.Add(btn) fgs.Add(btn)
fgs.Add(self.sampleText, 0, wxADJUST_MINSIZE|wxGROW) fgs.Add(self.sampleText, 0, wx.ADJUST_MINSIZE|wx.GROW)
fgs.Add((15,15)); fgs.Add((15,15)) # an empty row fgs.Add((15,15)); fgs.Add((15,15)) # an empty row
fgs.Add(wxStaticText(self, -1, "PointSize:")) fgs.Add(wx.StaticText(self, -1, "PointSize:"))
self.ps = wxStaticText(self, -1, "") self.ps = wx.StaticText(self, -1, "")
font = self.ps.GetFont() font = self.ps.GetFont()
font.SetWeight(wxBOLD) font.SetWeight(wx.BOLD)
self.ps.SetFont(font) self.ps.SetFont(font)
fgs.Add(self.ps, 0, wxADJUST_MINSIZE) fgs.Add(self.ps, 0, wx.ADJUST_MINSIZE)
fgs.Add(wxStaticText(self, -1, "Family:")) fgs.Add(wx.StaticText(self, -1, "Family:"))
self.family = wxStaticText(self, -1, "") self.family = wx.StaticText(self, -1, "")
self.family.SetFont(font) self.family.SetFont(font)
fgs.Add(self.family, 0, wxADJUST_MINSIZE) fgs.Add(self.family, 0, wx.ADJUST_MINSIZE)
fgs.Add(wxStaticText(self, -1, "Style:")) fgs.Add(wx.StaticText(self, -1, "Style:"))
self.style = wxStaticText(self, -1, "") self.style = wx.StaticText(self, -1, "")
self.style.SetFont(font) self.style.SetFont(font)
fgs.Add(self.style, 0, wxADJUST_MINSIZE) fgs.Add(self.style, 0, wx.ADJUST_MINSIZE)
fgs.Add(wxStaticText(self, -1, "Weight:")) fgs.Add(wx.StaticText(self, -1, "Weight:"))
self.weight = wxStaticText(self, -1, "") self.weight = wx.StaticText(self, -1, "")
self.weight.SetFont(font) self.weight.SetFont(font)
fgs.Add(self.weight, 0, wxADJUST_MINSIZE) fgs.Add(self.weight, 0, wx.ADJUST_MINSIZE)
fgs.Add(wxStaticText(self, -1, "Face:")) fgs.Add(wx.StaticText(self, -1, "Face:"))
self.face = wxStaticText(self, -1, "") self.face = wx.StaticText(self, -1, "")
self.face.SetFont(font) self.face.SetFont(font)
fgs.Add(self.face, 0, wxADJUST_MINSIZE) fgs.Add(self.face, 0, wx.ADJUST_MINSIZE)
fgs.Add((15,15)); fgs.Add((15,15)) # an empty row fgs.Add((15,15)); fgs.Add((15,15)) # an empty row
fgs.Add(wxStaticText(self, -1, "wxNativeFontInfo:")) fgs.Add(wx.StaticText(self, -1, "wx.NativeFontInfo:"))
self.nfi = wxStaticText(self, -1, "") self.nfi = wx.StaticText(self, -1, "")
self.nfi.SetFont(font) self.nfi.SetFont(font)
fgs.Add(self.nfi, 0, wxADJUST_MINSIZE) fgs.Add(self.nfi, 0, wx.ADJUST_MINSIZE)
# give it some border space # give it some border space
sizer = wxBoxSizer(wxVERTICAL) sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(fgs, 0, wxGROW|wxADJUST_MINSIZE|wxALL, 25) sizer.Add(fgs, 0, wx.GROW|wx.ADJUST_MINSIZE|wx.ALL, 25)
self.SetSizer(sizer) self.SetSizer(sizer)
self.UpdateUI() self.UpdateUI()
@@ -81,47 +85,58 @@ class TestPanel(wxPanel):
def OnSelectFont(self, evt): def OnSelectFont(self, evt):
data = wxFontData() data = wx.FontData()
data.EnableEffects(True) data.EnableEffects(True)
data.SetColour(self.curClr) # set colour data.SetColour(self.curClr) # set colour
data.SetInitialFont(self.curFont) data.SetInitialFont(self.curFont)
dlg = wxFontDialog(self, data) dlg = wx.FontDialog(self, data)
if dlg.ShowModal() == wxID_OK:
if dlg.ShowModal() == wx.ID_OK:
data = dlg.GetFontData() data = dlg.GetFontData()
font = data.GetChosenFont() font = data.GetChosenFont()
colour = data.GetColour() colour = data.GetColour()
self.log.WriteText('You selected: "%s", %d points, color %s\n' % self.log.WriteText('You selected: "%s", %d points, color %s\n' %
(font.GetFaceName(), font.GetPointSize(), (font.GetFaceName(), font.GetPointSize(),
colour.Get())) colour.Get()))
self.curFont = font self.curFont = font
self.curClr = colour self.curClr = colour
self.UpdateUI() self.UpdateUI()
# Don't destroy the dialog until you get everything you need from the
# dialog!
dlg.Destroy() dlg.Destroy()
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
def runTest(frame, nb, log): def runTest(frame, nb, log):
win = TestPanel(nb, log) win = TestPanel(nb, log)
return win return win
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
overview = """\ overview = """\
This class allows you to use the system font chooser dialog. This class allows you to use the system font selection dialog
from within your program. Generally speaking, this allows you
to select a font by its name, font size, and weight, and
on some systems such things as strikethrough and underline.
As with other dialogs used in wxPython, it is important to
use the class' methods to extract the information you need
about the font <b>before</b> you destroy the dialog. Failure
to observe this almost always leads to a program failure of
some sort, often ugly.
This demo serves two purposes; it shows how to use the dialog
to GET font information from the user, but also shows how
to APPLY that information once you get it.
""" """
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run

View File

@@ -1,18 +1,25 @@
# 11/18/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import * import wx
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class MyFrame(wxFrame): class MyFrame(wx.Frame):
def __init__(self, parent, ID, title, pos=wxDefaultPosition, def __init__(
size=wxDefaultSize, style=wxDEFAULT_FRAME_STYLE): self, parent, ID, title, pos=wx.DefaultPosition,
wxFrame.__init__(self, parent, ID, title, pos, size, style) size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE
panel = wxPanel(self, -1) ):
button = wxButton(panel, 1003, "Close Me") wx.Frame.__init__(self, parent, ID, title, pos, size, style)
button.SetPosition(wxPoint(15, 15)) panel = wx.Panel(self, -1)
EVT_BUTTON(self, 1003, self.OnCloseMe)
EVT_CLOSE(self, self.OnCloseWindow) button = wx.Button(panel, 1003, "Close Me")
button.SetPosition((15, 15))
self.Bind(wx.EVT_BUTTON, self.OnCloseMe, button)
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
def OnCloseMe(self, event): def OnCloseMe(self, event):
@@ -25,7 +32,7 @@ class MyFrame(wxFrame):
def runTest(frame, nb, log): def runTest(frame, nb, log):
win = MyFrame(frame, -1, "This is a wxFrame", size=(350, 200), win = MyFrame(frame, -1, "This is a wxFrame", size=(350, 200),
style = wxDEFAULT_FRAME_STYLE)# | wxFRAME_TOOL_WINDOW ) style = wx.DEFAULT_FRAME_STYLE)# | wx.FRAME_TOOL_WINDOW )
frame.otherWin = win frame.otherWin = win
win.Show(True) win.Show(True)
@@ -33,20 +40,30 @@ def runTest(frame, nb, log):
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
overview = """\ overview = """\
A Frame is a window whose size and position can (usually) be changed by
the user. It usually has thick borders and a title bar, and can optionally
contain a menu bar, toolbar and status bar. A frame can contain any window
that is not a Frame or Dialog. It is one of the most fundamental of the
wxWindows components.
A Frame that has a status bar and toolbar created via the
<code>CreateStatusBar</code> / <code>CreateToolBar</code> functions manages
these windows, and adjusts the value returned by <code>GetClientSize</code>
to reflect the remaining size available to application windows.
By itself, a Frame is not too useful, but with the addition of Panels and
other child objects, it encompasses the framework around which most user
interfaces are constructed.
If you plan on using Sizers and auto-layout features, be aware that the Frame
class lacks the ability to handle these features unless it contains a Panel.
The Panel has all the necessary functionality to both control the size of
child components, and also communicate that information in a useful way to
the Frame itself.
""" """
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run

View File

@@ -1,6 +1,15 @@
from wxPython.wx import * # 11/18/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
# o Note: unable to install PyOpenGL on my system as I am running Python 2.3
# and PyOpenGL does not support anything above Python 2.2. Did what I could,
# but odds are good there are problems.
#
import wx
try: try:
from wxPython.glcanvas import * import wx.glcanvas as glcanvas
haveGLCanvas = True haveGLCanvas = True
except ImportError: except ImportError:
haveGLCanvas = False haveGLCanvas = False
@@ -8,8 +17,9 @@ except ImportError:
try: try:
# The Python OpenGL package can be found at # The Python OpenGL package can be found at
# http://PyOpenGL.sourceforge.net/ # http://PyOpenGL.sourceforge.net/
from OpenGL.GL import *
from OpenGL.GLUT import * import OpenGL.GL as gl
import OpenGL.GLUT as glut
haveOpenGL = True haveOpenGL = True
except ImportError: except ImportError:
haveOpenGL = False haveOpenGL = False
@@ -18,49 +28,52 @@ except ImportError:
if not haveGLCanvas: if not haveGLCanvas:
def runTest(frame, nb, log): def runTest(frame, nb, log):
dlg = wxMessageDialog(frame, 'The wxGLCanvas has not been included with this build of wxPython!', dlg = wx.MessageDialog(
'Sorry', wxOK | wxICON_INFORMATION) frame, 'The wxGLCanvas has not been included with this build of wxPython!',
'Sorry', wx.OK | wx.ICON_INFORMATION
)
dlg.ShowModal() dlg.ShowModal()
dlg.Destroy() dlg.Destroy()
elif not haveOpenGL: elif not haveOpenGL:
def runTest(frame, nb, log): def runTest(frame, nb, log):
dlg = wxMessageDialog(frame, dlg = wxMessageDialog(
'The OpenGL package was not found. You can get it at\n' frame, 'The OpenGL package was not found. You can get it at\n'
'http://PyOpenGL.sourceforge.net/', 'http://PyOpenGL.sourceforge.net/', 'Sorry', wx.OK | wx.ICON_INFORMATION
'Sorry', wxOK | wxICON_INFORMATION) )
dlg.ShowModal() dlg.ShowModal()
dlg.Destroy() dlg.Destroy()
else: else:
buttonDefs = { buttonDefs = {
wxNewId() : ('CubeCanvas', 'Cube'), wx.NewId() : ('CubeCanvas', 'Cube'),
wxNewId() : ('ConeCanvas', 'Cone'), wx.NewId() : ('ConeCanvas', 'Cone'),
} }
class ButtonPanel(wxPanel): class ButtonPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.log = log self.log = log
box = wxBoxSizer(wxVERTICAL) box = wx.BoxSizer(wx.VERTICAL)
box.Add(20, 30) box.Add((20, 30))
keys = buttonDefs.keys() keys = buttonDefs.keys()
keys.sort() keys.sort()
for k in keys: for k in keys:
text = buttonDefs[k][1] text = buttonDefs[k][1]
btn = wxButton(self, k, text) btn = wx.Button(self, k, text)
box.Add(btn, 0, wxALIGN_CENTER|wxALL, 15) box.Add(btn, 0, wx.ALIGN_CENTER|wx.ALL, 15)
EVT_BUTTON(self, k, self.OnButton) self.Bind(wx.EVT_BUTTON, self.OnButton, id=k)
#** Enable this to show putting a wxGLCanvas on the wxPanel #** Enable this to show putting a wxGLCanvas on the wxPanel
if 0: if 0:
c = CubeCanvas(self) c = CubeCanvas(self)
c.SetSize((200, 200)) c.SetSize((200, 200))
box.Add(c, 0, wxALIGN_CENTER|wxALL, 15) box.Add(c, 0, wx.ALIGN_CENTER|wx.ALL, 15)
self.SetAutoLayout(True) self.SetAutoLayout(True)
self.SetSizer(box) self.SetSizer(box)
@@ -69,7 +82,7 @@ else:
def OnButton(self, evt): def OnButton(self, evt):
canvasClassName = buttonDefs[evt.GetId()][0] canvasClassName = buttonDefs[evt.GetId()][0]
canvasClass = eval(canvasClassName) canvasClass = eval(canvasClassName)
frame = wxFrame(None, -1, canvasClassName, size=(400,400)) frame = wx.Frame(None, -1, canvasClassName, size=(400,400))
canvas = canvasClass(frame) canvas = canvasClass(frame)
frame.Show(True) frame.Show(True)
@@ -82,35 +95,38 @@ else:
class MyCanvasBase(wxGLCanvas): class MyCanvasBase(glcanvas.GLCanvas):
def __init__(self, parent): def __init__(self, parent):
wxGLCanvas.__init__(self, parent, -1) glcanvas.GLCanvas.__init__(self, parent, -1)
self.init = False self.init = False
# initial mouse position # initial mouse position
self.lastx = self.x = 30 self.lastx = self.x = 30
self.lasty = self.y = 30 self.lasty = self.y = 30
EVT_ERASE_BACKGROUND(self, self.OnEraseBackground) self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
EVT_SIZE(self, self.OnSize) self.Bind(wx.EVT_SIZE, self.OnSize)
EVT_PAINT(self, self.OnPaint) self.Bind(wx.EVT_PAINT, self.OnPaint)
EVT_LEFT_DOWN(self, self.OnMouseDown) # needs fixing... self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown) # needs fixing...
EVT_LEFT_UP(self, self.OnMouseUp) self.Bind(wx.EVT_LEFT_UP, self.OnMouseUp)
EVT_MOTION(self, self.OnMouseMotion) self.Bind(wx.EVT_MOTION, self.OnMouseMotion)
def OnEraseBackground(self, event): def OnEraseBackground(self, event):
pass # Do nothing, to avoid flashing on MSW. pass # Do nothing, to avoid flashing on MSW.
def OnSize(self, event): def OnSize(self, event):
size = self.GetClientSize() size = self.GetClientSize()
if self.GetContext(): if self.GetContext():
self.SetCurrent() self.SetCurrent()
glViewport(0, 0, size.width, size.height) glcanvas.glViewport(0, 0, size.width, size.height)
def OnPaint(self, event): def OnPaint(self, event):
dc = wxPaintDC(self) dc = wx.PaintDC(self)
self.SetCurrent() self.SetCurrent()
if not self.init: if not self.init:
self.InitGL() self.InitGL()
self.init = True self.init = True
self.OnDraw() self.OnDraw()
def OnMouseDown(self, evt): def OnMouseDown(self, evt):
@@ -126,118 +142,113 @@ else:
self.Refresh(False) self.Refresh(False)
class CubeCanvas(MyCanvasBase): class CubeCanvas(MyCanvasBase):
def InitGL(self): def InitGL(self):
# set viewing projection # set viewing projection
glMatrixMode(GL_PROJECTION); glcanvas.glMatrixMode(glcanvas.GL_PROJECTION);
glFrustum(-0.5, 0.5, -0.5, 0.5, 1.0, 3.0); glcanvas.glFrustum(-0.5, 0.5, -0.5, 0.5, 1.0, 3.0);
# position viewer # position viewer
glMatrixMode(GL_MODELVIEW); glcanvas.glMatrixMode(glcanvas.GL_MODELVIEW);
glTranslatef(0.0, 0.0, -2.0); glcanvas.glTranslatef(0.0, 0.0, -2.0);
# position object # position object
glRotatef(self.y, 1.0, 0.0, 0.0); glcanvas.glRotatef(self.y, 1.0, 0.0, 0.0);
glRotatef(self.x, 0.0, 1.0, 0.0); glcanvas.glRotatef(self.x, 0.0, 1.0, 0.0);
glEnable(GL_DEPTH_TEST); glcanvas.glEnable(glcanvas.GL_DEPTH_TEST);
glEnable(GL_LIGHTING); glcanvas.glEnable(glcanvas.GL_LIGHTING);
glEnable(GL_LIGHT0); glcanvas.glEnable(glcanvas.GL_LIGHT0);
def OnDraw(self): def OnDraw(self):
# clear color and depth buffers # clear color and depth buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glcanvas.glClear(glcanvas.GL_COLOR_BUFFER_BIT | glcanvas.GL_DEPTH_BUFFER_BIT)
# draw six faces of a cube # draw six faces of a cube
glBegin(GL_QUADS) glcanvas.glBegin(glcanvas.GL_QUADS)
glNormal3f( 0.0, 0.0, 1.0) glcanvas.glNormal3f( 0.0, 0.0, 1.0)
glVertex3f( 0.5, 0.5, 0.5) glcanvas.glVertex3f( 0.5, 0.5, 0.5)
glVertex3f(-0.5, 0.5, 0.5) glcanvas.glVertex3f(-0.5, 0.5, 0.5)
glVertex3f(-0.5,-0.5, 0.5) glcanvas.glVertex3f(-0.5,-0.5, 0.5)
glVertex3f( 0.5,-0.5, 0.5) glcanvas.glVertex3f( 0.5,-0.5, 0.5)
glNormal3f( 0.0, 0.0,-1.0) glcanvas.glNormal3f( 0.0, 0.0,-1.0)
glVertex3f(-0.5,-0.5,-0.5) glcanvas.glVertex3f(-0.5,-0.5,-0.5)
glVertex3f(-0.5, 0.5,-0.5) glcanvas.glVertex3f(-0.5, 0.5,-0.5)
glVertex3f( 0.5, 0.5,-0.5) glcanvas.glVertex3f( 0.5, 0.5,-0.5)
glVertex3f( 0.5,-0.5,-0.5) glcanvas.glVertex3f( 0.5,-0.5,-0.5)
glNormal3f( 0.0, 1.0, 0.0) glcanvas.glNormal3f( 0.0, 1.0, 0.0)
glVertex3f( 0.5, 0.5, 0.5) glcanvas.glVertex3f( 0.5, 0.5, 0.5)
glVertex3f( 0.5, 0.5,-0.5) glcanvas.glVertex3f( 0.5, 0.5,-0.5)
glVertex3f(-0.5, 0.5,-0.5) glcanvas.glVertex3f(-0.5, 0.5,-0.5)
glVertex3f(-0.5, 0.5, 0.5) glcanvas.glVertex3f(-0.5, 0.5, 0.5)
glNormal3f( 0.0,-1.0, 0.0) glcanvas.glNormal3f( 0.0,-1.0, 0.0)
glVertex3f(-0.5,-0.5,-0.5) glcanvas.glVertex3f(-0.5,-0.5,-0.5)
glVertex3f( 0.5,-0.5,-0.5) glcanvas.glVertex3f( 0.5,-0.5,-0.5)
glVertex3f( 0.5,-0.5, 0.5) glcanvas.glVertex3f( 0.5,-0.5, 0.5)
glVertex3f(-0.5,-0.5, 0.5) glcanvas.glVertex3f(-0.5,-0.5, 0.5)
glNormal3f( 1.0, 0.0, 0.0) glcanvas.glNormal3f( 1.0, 0.0, 0.0)
glVertex3f( 0.5, 0.5, 0.5) glcanvas.glVertex3f( 0.5, 0.5, 0.5)
glVertex3f( 0.5,-0.5, 0.5) glcanvas.glVertex3f( 0.5,-0.5, 0.5)
glVertex3f( 0.5,-0.5,-0.5) glcanvas.glVertex3f( 0.5,-0.5,-0.5)
glVertex3f( 0.5, 0.5,-0.5) glcanvas.glVertex3f( 0.5, 0.5,-0.5)
glNormal3f(-1.0, 0.0, 0.0) glcanvas.glNormal3f(-1.0, 0.0, 0.0)
glVertex3f(-0.5,-0.5,-0.5) glcanvas.glVertex3f(-0.5,-0.5,-0.5)
glVertex3f(-0.5,-0.5, 0.5) glcanvas.glVertex3f(-0.5,-0.5, 0.5)
glVertex3f(-0.5, 0.5, 0.5) glcanvas.glVertex3f(-0.5, 0.5, 0.5)
glVertex3f(-0.5, 0.5,-0.5) glcanvas.glVertex3f(-0.5, 0.5,-0.5)
glEnd() glcanvas.glEnd()
glRotatef((self.lasty - self.y)/100., 1.0, 0.0, 0.0); glcanvas.glRotatef((self.lasty - self.y)/100., 1.0, 0.0, 0.0);
glRotatef((self.lastx - self.x)/100., 0.0, 1.0, 0.0); glcanvas.glRotatef((self.lastx - self.x)/100., 0.0, 1.0, 0.0);
self.SwapBuffers() self.SwapBuffers()
class ConeCanvas(MyCanvasBase): class ConeCanvas(MyCanvasBase):
def InitGL( self ): def InitGL( self ):
glMatrixMode(GL_PROJECTION); glcanvas.glMatrixMode(glcanvas.GL_PROJECTION);
# camera frustrum setup # camera frustrum setup
glFrustum(-0.5, 0.5, -0.5, 0.5, 1.0, 3.0); glcanvas.glFrustum(-0.5, 0.5, -0.5, 0.5, 1.0, 3.0);
glMaterial(GL_FRONT, GL_AMBIENT, [0.2, 0.2, 0.2, 1.0]) glcanvas.glMaterial(glcanvas.GL_FRONT, glcanvas.GL_AMBIENT, [0.2, 0.2, 0.2, 1.0])
glMaterial(GL_FRONT, GL_DIFFUSE, [0.8, 0.8, 0.8, 1.0]) glcanvas.glMaterial(glcanvas.GL_FRONT, glcanvas.GL_DIFFUSE, [0.8, 0.8, 0.8, 1.0])
glMaterial(GL_FRONT, GL_SPECULAR, [1.0, 0.0, 1.0, 1.0]) glcanvas.glMaterial(glcanvas.GL_FRONT, glcanvas.GL_SPECULAR, [1.0, 0.0, 1.0, 1.0])
glMaterial(GL_FRONT, GL_SHININESS, 50.0) glcanvas.glMaterial(glcanvas.GL_FRONT, glcanvas.GL_SHININESS, 50.0)
glLight(GL_LIGHT0, GL_AMBIENT, [0.0, 1.0, 0.0, 1.0]) glcanvas.glLight(glcanvas.GL_LIGHT0, glcanvas.GL_AMBIENT, [0.0, 1.0, 0.0, 1.0])
glLight(GL_LIGHT0, GL_DIFFUSE, [1.0, 1.0, 1.0, 1.0]) glcanvas.glLight(glcanvas.GL_LIGHT0, glcanvas.GL_DIFFUSE, [1.0, 1.0, 1.0, 1.0])
glLight(GL_LIGHT0, GL_SPECULAR, [1.0, 1.0, 1.0, 1.0]) glcanvas.glLight(glcanvas.GL_LIGHT0, glcanvas.GL_SPECULAR, [1.0, 1.0, 1.0, 1.0])
glLight(GL_LIGHT0, GL_POSITION, [1.0, 1.0, 1.0, 0.0]); glcanvas.glLight(glcanvas.GL_LIGHT0, glcanvas.GL_POSITION, [1.0, 1.0, 1.0, 0.0]);
glLightModel(GL_LIGHT_MODEL_AMBIENT, [0.2, 0.2, 0.2, 1.0]) glcanvas.glLightModel(glcanvas.GL_LIGHT_MODEL_AMBIENT, [0.2, 0.2, 0.2, 1.0])
glEnable(GL_LIGHTING) glcanvas.glEnable(glcanvas.GL_LIGHTING)
glEnable(GL_LIGHT0) glcanvas.glEnable(glcanvas.GL_LIGHT0)
glDepthFunc(GL_LESS) glcanvas.glDepthFunc(glcanvas.GL_LESS)
glEnable(GL_DEPTH_TEST) glcanvas.glEnable(glcanvas.GL_DEPTH_TEST)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glcanvas.glClear(glcanvas.GL_COLOR_BUFFER_BIT | glcanvas.GL_DEPTH_BUFFER_BIT)
# position viewer # position viewer
glMatrixMode(GL_MODELVIEW); glcanvas.glMatrixMode(glcanvas.GL_MODELVIEW);
def OnDraw(self): def OnDraw(self):
# clear color and depth buffers # clear color and depth buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glcanvas.glClear(glcanvas.GL_COLOR_BUFFER_BIT | glcanvas.GL_DEPTH_BUFFER_BIT);
# use a fresh transformation matrix # use a fresh transformation matrix
glPushMatrix() glcanvas.glPushMatrix()
# position object # position object
glTranslate(0.0, 0.0, -2.0); glcanvas.glTranslate(0.0, 0.0, -2.0);
glRotate(30.0, 1.0, 0.0, 0.0); glcanvas.glRotate(30.0, 1.0, 0.0, 0.0);
glRotate(30.0, 0.0, 1.0, 0.0); glcanvas.glRotate(30.0, 0.0, 1.0, 0.0);
glTranslate(0, -1, 0) glcanvas.glTranslate(0, -1, 0)
glRotate(250, 1, 0, 0) glcanvas.glRotate(250, 1, 0, 0)
glutSolidCone(0.5, 1, 30, 5) glcanvas.glutSolidCone(0.5, 1, 30, 5)
glPopMatrix() glcanvas.glPopMatrix()
glRotatef((self.lasty - self.y)/100., 0.0, 0.0, 1.0); glcanvas.glRotatef((self.lasty - self.y)/100., 0.0, 0.0, 1.0);
glRotatef(0.0, (self.lastx - self.x)/100., 1.0, 0.0); glcanvas.glRotatef(0.0, (self.lastx - self.x)/100., 1.0, 0.0);
# push into visible buffer # push into visible buffer
self.SwapBuffers() self.SwapBuffers()
@@ -248,24 +259,16 @@ else:
overview = """\ overview = """\
""" """
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def _test(): def _test():
class MyApp(wxApp): class MyApp(wxApp):
def OnInit(self): def OnInit(self):
frame = wxFrame(None, -1, "GL Demos", wxDefaultPosition, wxSize(600,300)) frame = wx.Frame(None, -1, "GL Demos", wx.DefaultPosition, (600,300))
#win = ConeCanvas(frame) #win = ConeCanvas(frame)
MySplitter(frame) MySplitter(frame)
frame.Show(True) frame.Show(True)

View File

@@ -1,33 +1,41 @@
# 11/15/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import * import wx
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.log = log self.log = log
self.count = 0 self.count = 0
wxStaticText(self, -1, "This example shows the wxGauge control.", wx.StaticText(self, -1, "This example shows the wxGauge control.", (45, 15))
wxPoint(45, 15))
self.g1 = wxGauge(self, -1, 50, wxPoint(110, 50), wxSize(250, 25)) self.g1 = wx.Gauge(self, -1, 50, (110, 50), (250, 25))
self.g1.SetBezelFace(3) self.g1.SetBezelFace(3)
self.g1.SetShadowWidth(3) self.g1.SetShadowWidth(3)
self.g2 = wxGauge(self, -1, 50, wxPoint(110, 95), wxSize(250, 25), self.g2 = wx.Gauge(
wxGA_HORIZONTAL|wxGA_SMOOTH) self, -1, 50, (110, 95), (250, 25),
wx.GA_HORIZONTAL|wx.GA_SMOOTH
)
self.g2.SetBezelFace(5) self.g2.SetBezelFace(5)
self.g2.SetShadowWidth(5) self.g2.SetShadowWidth(5)
EVT_IDLE(self, self.IdleHandler) self.Bind(wx.EVT_IDLE, self.IdleHandler)
def IdleHandler(self, event): def IdleHandler(self, event):
self.count = self.count + 1 self.count = self.count + 1
if self.count >= 50: if self.count >= 50:
self.count = 0 self.count = 0
self.g1.SetValue(self.count) self.g1.SetValue(self.count)
self.g2.SetValue(self.count) self.g2.SetValue(self.count)
@@ -42,20 +50,19 @@ def runTest(frame, nb, log):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
overview = """\ overview = """\
A Gauge is a horizontal or vertical bar which shows a quantity in a graphical
fashion. It is often used to indicate progress through lengthy tasks, such as
file copying or data analysis.
When the Gauge is initialized, it's "complete" value is usually set; at any rate,
before using the Gauge, the maximum value of the control must be set. As the task
progresses, the Gauge is updated by the program via the <code>SetValue</code> method.
This control is for use within a GUI; there is a seperate ProgressDialog class
to present the same sort of control as a dialog to the user.
""" """
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run

View File

@@ -1,23 +1,28 @@
from wxPython.wx import * # 11/18/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
import wx
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.log = log self.log = log
txt1 = wxStaticText(self, -1, "style=0") txt1 = wx.StaticText(self, -1, "style=0")
dir1 = wxGenericDirCtrl(self, -1, size=(200,225), style=0) dir1 = wx.GenericDirCtrl(self, -1, size=(200,225), style=0)
txt2 = wxStaticText(self, -1, "wxDIRCTRL_DIR_ONLY") txt2 = wx.StaticText(self, -1, "wx.DIRCTRL_DIR_ONLY")
dir2 = wxGenericDirCtrl(self, -1, size=(200,225), style=wxDIRCTRL_DIR_ONLY) dir2 = wx.GenericDirCtrl(self, -1, size=(200,225), style=wx.DIRCTRL_DIR_ONLY)
txt3 = wxStaticText(self, -1, "wxDIRCTRL_SHOW_FILTERS") txt3 = wx.StaticText(self, -1, "wx.DIRCTRL_SHOW_FILTERS")
dir3 = wxGenericDirCtrl(self, -1, size=(200,225), style=wxDIRCTRL_SHOW_FILTERS, dir3 = wx.GenericDirCtrl(self, -1, size=(200,225), style=wx.DIRCTRL_SHOW_FILTERS,
filter="All files (*.*)|*.*|Python files (*.py)|*.py") filter="All files (*.*)|*.*|Python files (*.py)|*.py")
sz = wxFlexGridSizer(cols=3, hgap=5, vgap=5) sz = wx.FlexGridSizer(cols=3, hgap=5, vgap=5)
sz.Add((35, 35)) # some space above sz.Add((35, 35)) # some space above
sz.Add((35, 35)) sz.Add((35, 35))
sz.Add((35, 35)) sz.Add((35, 35))
@@ -26,9 +31,9 @@ class TestPanel(wxPanel):
sz.Add(txt2) sz.Add(txt2)
sz.Add(txt3) sz.Add(txt3)
sz.Add(dir1, 0, wxEXPAND) sz.Add(dir1, 0, wx.EXPAND)
sz.Add(dir2, 0, wxEXPAND) sz.Add(dir2, 0, wx.EXPAND)
sz.Add(dir3, 0, wxEXPAND) sz.Add(dir3, 0, wx.EXPAND)
sz.Add((35,35)) # some space below sz.Add((35,35)) # some space below
@@ -36,6 +41,7 @@ class TestPanel(wxPanel):
sz.AddGrowableCol(0) sz.AddGrowableCol(0)
sz.AddGrowableCol(1) sz.AddGrowableCol(1)
sz.AddGrowableCol(2) sz.AddGrowableCol(2)
self.SetSizer(sz) self.SetSizer(sz)
self.SetAutoLayout(True) self.SetAutoLayout(True)
@@ -46,16 +52,17 @@ def runTest(frame, nb, log):
win = TestPanel(nb, log) win = TestPanel(nb, log)
return win return win
#---------------------------------------------------------------------- #----------------------------------------------------------------------
overview = """\ overview = """\
This control can be used to place a directory listing (with optional files) This control can be used to place a directory listing (with optional files)
on an arbitrary window. on an arbitrary window. The control contains a TreeCtrl window representing
the directory hierarchy, and optionally, a Choice window containing a list
of filters.
The filters work in the same manner as in FileDialog.
""" """

View File

@@ -1,5 +1,9 @@
# 11/18/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import * import wx
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
@@ -15,20 +19,21 @@ buttonDefs = {
} }
class ButtonPanel(wxPanel): class ButtonPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.log = log self.log = log
box = wxBoxSizer(wxVERTICAL) box = wxBoxSizer(wx.VERTICAL)
box.Add((20, 20)) box.Add((20, 20))
keys = buttonDefs.keys() keys = buttonDefs.keys()
keys.sort() keys.sort()
for k in keys: for k in keys:
text = buttonDefs[k][1] text = buttonDefs[k][1]
btn = wxButton(self, k, text) btn = wx.Button(self, k, text)
box.Add(btn, 0, wxALIGN_CENTER|wxALL, 10) box.Add(btn, 0, wx.ALIGN_CENTER|wx.ALL, 10)
EVT_BUTTON(self, k, self.OnButton) self.Bind(wx.EVT_BUTTON, self.OnButton, btn)
self.SetAutoLayout(True) self.SetAutoLayout(True)
self.SetSizer(box) self.SetSizer(box)
@@ -51,13 +56,6 @@ def runTest(frame, nb, log):
overview = """\ overview = """\
<html><body> <html><body>
<h2>wxGrid</h2> <h2>wxGrid</h2>
@@ -99,8 +97,6 @@ and wrapping around to the next row when needed.
""" """
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run

View File

@@ -20,7 +20,6 @@ class TestFrame(wx.Frame):
gbs.Add( wx.StaticText(p, -1, gbsDescription), gbs.Add( wx.StaticText(p, -1, gbsDescription),
(0,0), (1,7), wx.ALIGN_CENTER | wx.ALL, 5) (0,0), (1,7), wx.ALIGN_CENTER | wx.ALL, 5)
gbs.Add( wx.TextCtrl(p, -1, "pos(1,0)"), (1,0) ) gbs.Add( wx.TextCtrl(p, -1, "pos(1,0)"), (1,0) )
gbs.Add( wx.TextCtrl(p, -1, "pos(1,1)"), (1,1) ) gbs.Add( wx.TextCtrl(p, -1, "pos(1,1)"), (1,1) )
gbs.Add( wx.TextCtrl(p, -1, "pos(2,0)"), (2,0) ) gbs.Add( wx.TextCtrl(p, -1, "pos(2,0)"), (2,0) )

View File

@@ -1,8 +1,14 @@
from wxPython.wx import * # 11/18/2003 - Jeff Grimmett (grimmtooth@softhome.net)
from wxPython.grid import * #
# o Updated for wx namespace
#
import wx
import wx.grid as Grid
import images import images
class MegaTable(wxPyGridTableBase): class MegaTable(Grid.PyGridTableBase):
""" """
A custom wxGrid Table using user supplied data A custom wxGrid Table using user supplied data
""" """
@@ -13,12 +19,12 @@ class MegaTable(wxPyGridTableBase):
colname colname
""" """
# The base class must be initialized *first* # The base class must be initialized *first*
wxPyGridTableBase.__init__(self) Grid.PyGridTableBase.__init__(self)
self.data = data self.data = data
self.colnames = colnames self.colnames = colnames
self.plugins = plugins or {} self.plugins = plugins or {}
# XXX # XXX
# we need to store the row length and collength to # we need to store the row length and column length to
# see if the table has changed size # see if the table has changed size
self._rows = self.GetNumberRows() self._rows = self.GetNumberRows()
self._cols = self.GetNumberCols() self._cols = self.GetNumberCols()
@@ -46,21 +52,24 @@ class MegaTable(wxPyGridTableBase):
def ResetView(self, grid): def ResetView(self, grid):
""" """
(wxGrid) -> Reset the grid view. Call this to (Grid) -> Reset the grid view. Call this to
update the grid if rows and columns have been added or deleted update the grid if rows and columns have been added or deleted
""" """
grid.BeginBatch() grid.BeginBatch()
for current, new, delmsg, addmsg in [ for current, new, delmsg, addmsg in [
(self._rows, self.GetNumberRows(), wxGRIDTABLE_NOTIFY_ROWS_DELETED, wxGRIDTABLE_NOTIFY_ROWS_APPENDED), (self._rows, self.GetNumberRows(), Grid.GRIDTABLE_NOTIFY_ROWS_DELETED, Grid.GRIDTABLE_NOTIFY_ROWS_APPENDED),
(self._cols, self.GetNumberCols(), wxGRIDTABLE_NOTIFY_COLS_DELETED, wxGRIDTABLE_NOTIFY_COLS_APPENDED), (self._cols, self.GetNumberCols(), Grid.GRIDTABLE_NOTIFY_COLS_DELETED, Grid.GRIDTABLE_NOTIFY_COLS_APPENDED),
]: ]:
if new < current: if new < current:
msg = wxGridTableMessage(self,delmsg,new,current-new) msg = Grid.GridTableMessage(self,delmsg,new,current-new)
grid.ProcessTableMessage(msg) grid.ProcessTableMessage(msg)
elif new > current: elif new > current:
msg = wxGridTableMessage(self,addmsg,new-current) msg = Grid.GridTableMessage(self,addmsg,new-current)
grid.ProcessTableMessage(msg) grid.ProcessTableMessage(msg)
self.UpdateValues(grid) self.UpdateValues(grid)
grid.EndBatch() grid.EndBatch()
self._rows = self.GetNumberRows() self._rows = self.GetNumberRows()
@@ -76,7 +85,7 @@ class MegaTable(wxPyGridTableBase):
def UpdateValues(self, grid): def UpdateValues(self, grid):
"""Update all displayed values""" """Update all displayed values"""
# This sends an event to the grid table to update all of the values # This sends an event to the grid table to update all of the values
msg = wxGridTableMessage(self, wxGRIDTABLE_REQUEST_VIEW_GET_VALUES) msg = Grid.GridTableMessage(self, Grid.GRIDTABLE_REQUEST_VIEW_GET_VALUES)
grid.ProcessTableMessage(msg) grid.ProcessTableMessage(msg)
def _updateColAttrs(self, grid): def _updateColAttrs(self, grid):
@@ -88,25 +97,33 @@ class MegaTable(wxPyGridTableBase):
Otherwise default to the default renderer. Otherwise default to the default renderer.
""" """
col = 0 col = 0
for colname in self.colnames: for colname in self.colnames:
attr = wxGridCellAttr() attr = Grid.GridCellAttr()
if colname in self.plugins: if colname in self.plugins:
renderer = self.plugins[colname](self) renderer = self.plugins[colname](self)
if renderer.colSize: if renderer.colSize:
grid.SetColSize(col, renderer.colSize) grid.SetColSize(col, renderer.colSize)
if renderer.rowSize: if renderer.rowSize:
grid.SetDefaultRowSize(renderer.rowSize) grid.SetDefaultRowSize(renderer.rowSize)
attr.SetReadOnly(True) attr.SetReadOnly(True)
attr.SetRenderer(renderer) attr.SetRenderer(renderer)
grid.SetColAttr(col, attr) grid.SetColAttr(col, attr)
col += 1 col += 1
# ------------------------------------------------------ # ------------------------------------------------------
# begin the added code to manipulate the table (non wx related) # begin the added code to manipulate the table (non wx related)
def AppendRow(self, row): def AppendRow(self, row):
#print 'append'
entry = {} entry = {}
for name in self.colnames: for name in self.colnames:
entry[name] = "Appended_%i"%row entry[name] = "Appended_%i"%row
# XXX Hack # XXX Hack
# entry["A"] can only be between 1..4 # entry["A"] can only be between 1..4
entry["A"] = random.choice(range(4)) entry["A"] = random.choice(range(4))
@@ -123,11 +140,13 @@ class MegaTable(wxPyGridTableBase):
deleteCount = 0 deleteCount = 0
cols = cols[:] cols = cols[:]
cols.sort() cols.sort()
for i in cols: for i in cols:
self.colnames.pop(i-deleteCount) self.colnames.pop(i-deleteCount)
# we need to advance the delete count # we need to advance the delete count
# to make sure we delete the right columns # to make sure we delete the right columns
deleteCount += 1 deleteCount += 1
if not len(self.colnames): if not len(self.colnames):
self.data = [] self.data = []
@@ -139,6 +158,7 @@ class MegaTable(wxPyGridTableBase):
deleteCount = 0 deleteCount = 0
rows = rows[:] rows = rows[:]
rows.sort() rows.sort()
for i in rows: for i in rows:
self.data.pop(i-deleteCount) self.data.pop(i-deleteCount)
# we need to advance the delete count # we need to advance the delete count
@@ -151,12 +171,14 @@ class MegaTable(wxPyGridTableBase):
""" """
name = self.colnames[col] name = self.colnames[col]
_data = [] _data = []
for row in self.data: for row in self.data:
rowname, entry = row rowname, entry = row
_data.append((entry.get(name, None), row)) _data.append((entry.get(name, None), row))
_data.sort() _data.sort()
self.data = [] self.data = []
for sortvalue, row in _data: for sortvalue, row in _data:
self.data.append(row) self.data.append(row)
@@ -167,42 +189,45 @@ class MegaTable(wxPyGridTableBase):
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# Sample wxGrid renderers # Sample wxGrid renderers
class MegaImageRenderer(wxPyGridCellRenderer): class MegaImageRenderer(Grid.PyGridCellRenderer):
def __init__(self, table): def __init__(self, table):
""" """
Image Renderer Test. This just places an image in a cell Image Renderer Test. This just places an image in a cell
based on the row index. There are N choices and the based on the row index. There are N choices and the
choice is made by choice[row%N] choice is made by choice[row%N]
""" """
wxPyGridCellRenderer.__init__(self) Grid.PyGridCellRenderer.__init__(self)
self.table = table self.table = table
self._choices = [images.getSmilesBitmap, self._choices = [images.getSmilesBitmap,
images.getMondrianBitmap, images.getMondrianBitmap,
images.get_10s_Bitmap, images.get_10s_Bitmap,
images.get_01c_Bitmap] images.get_01c_Bitmap]
self.colSize = None self.colSize = None
self.rowSize = None self.rowSize = None
def Draw(self, grid, attr, dc, rect, row, col, isSelected): def Draw(self, grid, attr, dc, rect, row, col, isSelected):
choice = self.table.GetRawValue(row, col) choice = self.table.GetRawValue(row, col)
bmp = self._choices[ choice % len(self._choices)]() bmp = self._choices[ choice % len(self._choices)]()
image = wxMemoryDC() image = wx.MemoryDC()
image.SelectObject(bmp) image.SelectObject(bmp)
# clear the background # clear the background
dc.SetBackgroundMode(wxSOLID) dc.SetBackgroundMode(wx.SOLID)
if isSelected: if isSelected:
dc.SetBrush(wxBrush(wxBLUE, wxSOLID)) dc.SetBrush(wx.Brush(wx.BLUE, wx.SOLID))
dc.SetPen(wxPen(wxBLUE, 1, wxSOLID)) dc.SetPen(wx.Pen(wx.BLUE, 1, wx.SOLID))
else: else:
dc.SetBrush(wxBrush(wxWHITE, wxSOLID)) dc.SetBrush(wxBrush(wxWHITE, wxSOLID))
dc.SetPen(wxPen(wxWHITE, 1, wxSOLID)) dc.SetPen(wxPen(wxWHITE, 1, wxSOLID))
dc.DrawRectangleRect(rect) dc.DrawRectangleRect(rect)
#dc.DrawRectangle((rect.x, rect.y), (rect.width, rect.height))
# copy the image but only to the size of the grid cell # copy the image but only to the size of the grid cell
width, height = bmp.GetWidth(), bmp.GetHeight() width, height = bmp.GetWidth(), bmp.GetHeight()
if width > rect.width-2: if width > rect.width-2:
width = rect.width-2 width = rect.width-2
@@ -214,17 +239,15 @@ class MegaImageRenderer(wxPyGridCellRenderer):
(0, 0), wxCOPY, True) (0, 0), wxCOPY, True)
class MegaFontRenderer(wxPyGridCellRenderer): class MegaFontRenderer(Grid.PyGridCellRenderer):
def __init__(self, table, color="blue", font="ARIAL", fontsize=8): def __init__(self, table, color="blue", font="ARIAL", fontsize=8):
"""Render data in the specified color and font and fontsize""" """Render data in the specified color and font and fontsize"""
wxPyGridCellRenderer.__init__(self) Grid.PyGridCellRenderer.__init__(self)
self.table = table self.table = table
self.color = color self.color = color
self.font = wxFont(fontsize, wxDEFAULT, wxNORMAL, wxNORMAL, self.font = wx.Font(fontsize, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, font)
0, font) self.selectedBrush = wx.Brush("blue", wx.SOLID)
self.selectedBrush = wxBrush("blue", self.normalBrush = wx.Brush(wx.WHITE, wx.SOLID)
wxSOLID)
self.normalBrush = wxBrush(wxWHITE, wxSOLID)
self.colSize = None self.colSize = None
self.rowSize = 50 self.rowSize = 50
@@ -236,17 +259,20 @@ class MegaFontRenderer(wxPyGridCellRenderer):
dc.SetClippingRect(rect) dc.SetClippingRect(rect)
# clear the background # clear the background
dc.SetBackgroundMode(wxSOLID) dc.SetBackgroundMode(wx.SOLID)
if isSelected: if isSelected:
dc.SetBrush(wxBrush(wxBLUE, wxSOLID)) dc.SetBrush(wx.Brush(wx.BLUE, wx.SOLID))
dc.SetPen(wxPen(wxBLUE, 1, wxSOLID)) dc.SetPen(wx.Pen(wx.BLUE, 1, wx.SOLID))
else: else:
dc.SetBrush(wxBrush(wxWHITE, wxSOLID)) dc.SetBrush(wxBrush(wxWHITE, wxSOLID))
dc.SetPen(wxPen(wxWHITE, 1, wxSOLID)) dc.SetPen(wxPen(wxWHITE, 1, wxSOLID))
dc.DrawRectangleRect(rect) dc.DrawRectangleRect(rect)
#dc.DrawRectangle((rect.x, rect.y), (rect.width, rect.height))
text = self.table.GetValue(row, col) text = self.table.GetValue(row, col)
dc.SetBackgroundMode(wxSOLID) dc.SetBackgroundMode(wx.SOLID)
# change the text background based on whether the grid is selected # change the text background based on whether the grid is selected
# or not # or not
@@ -267,6 +293,7 @@ class MegaFontRenderer(wxPyGridCellRenderer):
# when the text is larger than the grid cell # when the text is larger than the grid cell
width, height = dc.GetTextExtent(text) width, height = dc.GetTextExtent(text)
if width > rect.width-2: if width > rect.width-2:
width, height = dc.GetTextExtent("...") width, height = dc.GetTextExtent("...")
x = rect.x+1 + rect.width-2 - width x = rect.x+1 + rect.width-2 - width
@@ -280,7 +307,7 @@ class MegaFontRenderer(wxPyGridCellRenderer):
# Sample Grid using a specialized table and renderers that can # Sample Grid using a specialized table and renderers that can
# be plugged in based on column names # be plugged in based on column names
class MegaGrid(wxGrid): class MegaGrid(Grid.Grid):
def __init__(self, parent, data, colnames, plugins=None): def __init__(self, parent, data, colnames, plugins=None):
"""parent, data, colnames, plugins=None """parent, data, colnames, plugins=None
Initialize a grid using the data defined in data and colnames Initialize a grid using the data defined in data and colnames
@@ -289,12 +316,12 @@ class MegaGrid(wxGrid):
""" """
# The base class must be initialized *first* # The base class must be initialized *first*
wxGrid.__init__(self, parent, -1) Grid.Grid.__init__(self, parent, -1)
self._table = MegaTable(data, colnames, plugins) self._table = MegaTable(data, colnames, plugins)
self.SetTable(self._table) self.SetTable(self._table)
self._plugins = plugins self._plugins = plugins
EVT_GRID_LABEL_RIGHT_CLICK(self, self.OnLabelRightClicked) self.Bind(Grid.EVT_GRID_LABEL_RIGHT_CLICK, self.OnLabelRightClicked)
def Reset(self): def Reset(self):
"""reset the view based on the data in the table. Call """reset the view based on the data in the table. Call
@@ -309,12 +336,14 @@ class MegaGrid(wxGrid):
def rowPopup(self, row, evt): def rowPopup(self, row, evt):
"""(row, evt) -> display a popup menu when a row label is right clicked""" """(row, evt) -> display a popup menu when a row label is right clicked"""
appendID = wxNewId() appendID = wx.NewId()
deleteID = wxNewId() deleteID = wx.NewId()
x = self.GetRowSize(row)/2 x = self.GetRowSize(row)/2
if not self.GetSelectedRows(): if not self.GetSelectedRows():
self.SelectRow(row) self.SelectRow(row)
menu = wxMenu()
menu = wx.Menu()
xo, yo = evt.GetPosition() xo, yo = evt.GetPosition()
menu.Append(appendID, "Append Row") menu.Append(appendID, "Append Row")
menu.Append(deleteID, "Delete Row(s)") menu.Append(deleteID, "Delete Row(s)")
@@ -328,18 +357,20 @@ class MegaGrid(wxGrid):
self._table.DeleteRows(rows) self._table.DeleteRows(rows)
self.Reset() self.Reset()
EVT_MENU(self, appendID, append) self.Bind(wx.EVT_MENU, append, id=appendID)
EVT_MENU(self, deleteID, delete) self.Bind(wx.EVT_MENU, delete, id=deleteID)
self.PopupMenu(menu, wxPoint(x, yo)) self.PopupMenu(menu, (x, yo))
menu.Destroy() menu.Destroy()
return
def colPopup(self, col, evt): def colPopup(self, col, evt):
"""(col, evt) -> display a popup menu when a column label is """(col, evt) -> display a popup menu when a column label is
right clicked""" right clicked"""
x = self.GetColSize(col)/2 x = self.GetColSize(col)/2
menu = wxMenu() menu = wx.Menu()
id1 = wxNewId() id1 = wx.NewId()
sortID = wxNewId() sortID = wx.NewId()
xo, yo = evt.GetPosition() xo, yo = evt.GetPosition()
self.SelectCol(col) self.SelectCol(col)
@@ -357,11 +388,14 @@ class MegaGrid(wxGrid):
self._table.SortColumn(col) self._table.SortColumn(col)
self.Reset() self.Reset()
EVT_MENU(self, id1, delete) self.Bind(wx.EVT_MENU, delete, id=id1)
if len(cols) == 1: if len(cols) == 1:
EVT_MENU(self, sortID, sort) self.Bind(wx.EVT_MENU, sort, id=sortID)
self.PopupMenu(menu, wxPoint(xo, 0))
self.PopupMenu(menu, (xo, 0))
menu.Destroy() menu.Destroy()
return
# ----------------------------------------------------------------- # -----------------------------------------------------------------
# Test data # Test data
@@ -374,10 +408,12 @@ import random
colnames = ["Row", "This", "Is", "A", "Test"] colnames = ["Row", "This", "Is", "A", "Test"]
data = [] data = []
for row in range(1000): for row in range(1000):
d = {} d = {}
for name in ["This", "Test", "Is"]: for name in ["This", "Test", "Is"]:
d[name] = random.random() d[name] = random.random()
d["Row"] = len(data) d["Row"] = len(data)
# XXX # XXX
# the "A" column can only be between one and 4 # the "A" column can only be between one and 4
@@ -402,11 +438,11 @@ class MegaFontRendererFactory:
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class TestFrame(wxFrame): class TestFrame(wx.Frame):
def __init__(self, parent, plugins={"This":MegaFontRendererFactory("red", "ARIAL", 8), def __init__(self, parent, plugins={"This":MegaFontRendererFactory("red", "ARIAL", 8),
"A":MegaImageRenderer, "A":MegaImageRenderer,
"Test":MegaFontRendererFactory("orange", "TIMES", 24),}): "Test":MegaFontRendererFactory("orange", "TIMES", 24),}):
wxFrame.__init__(self, parent, -1, wx.Frame.__init__(self, parent, -1,
"Test Frame", size=(640,480)) "Test Frame", size=(640,480))
grid = MegaGrid(self, data, colnames, plugins) grid = MegaGrid(self, data, colnames, plugins)
@@ -428,22 +464,22 @@ This example attempts to show many examples and tricks of
using a virtual grid object. Hopefully the source isn't too jumbled. using a virtual grid object. Hopefully the source isn't too jumbled.
Features: Features:
1) Uses a virtual grid <ol>
2) Columns and rows have popup menus (right click on labels) <li>Uses a virtual grid
3) Columns and rows can be deleted (i.e. table can be <li>Columns and rows have popup menus (right click on labels)
<li>Columns and rows can be deleted (i.e. table can be
resized) resized)
4) Dynamic renderers. Renderers are plugins based on <li>Dynamic renderers. Renderers are plugins based on
column header name. Shows a simple Font Renderer and column header name. Shows a simple Font Renderer and
an Image Renderer. an Image Renderer.
</ol>
Look for XXX in the code to indicate some workarounds for non-obvious Look for 'XXX' in the code to indicate some workarounds for non-obvious
behavior and various hacks. behavior and various hacks.
""" """
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run

View File

@@ -1,9 +1,13 @@
# 11/18/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
import sys, os import os
import sys
from wxPython.wx import * import wx
from wxPython.html import * import wx.html as html
import wxPython.lib.wxpTag
from Main import opj from Main import opj
@@ -13,18 +17,17 @@ from Main import opj
# This shows how to catch the OnLinkClicked non-event. (It's a virtual # This shows how to catch the OnLinkClicked non-event. (It's a virtual
# method in the C++ code...) # method in the C++ code...)
class MyHtmlWindow(wxHtmlWindow): class MyHtmlWindow(html.HtmlWindow):
def __init__(self, parent, id, log): def __init__(self, parent, id, log):
wxHtmlWindow.__init__(self, parent, id, style=wxNO_FULL_REPAINT_ON_RESIZE) html.HtmlWindow.__init__(self, parent, id, style=wx.NO_FULL_REPAINT_ON_RESIZE)
self.log = log self.log = log
EVT_SCROLLWIN( self, self.OnScroll ) self.Bind(wx.EVT_SCROLLWIN, self.OnScroll )
def OnScroll( self, event ): def OnScroll( self, event ):
#print 'event.GetOrientation()',event.GetOrientation() #print 'event.GetOrientation()',event.GetOrientation()
#print 'event.GetPosition()',event.GetPosition() #print 'event.GetPosition()',event.GetPosition()
event.Skip() event.Skip()
def OnLinkClicked(self, linkinfo): def OnLinkClicked(self, linkinfo):
self.log.WriteText('OnLinkClicked: %s\n' % linkinfo.GetHref()) self.log.WriteText('OnLinkClicked: %s\n' % linkinfo.GetHref())
@@ -46,9 +49,9 @@ class MyHtmlWindow(wxHtmlWindow):
# This filter doesn't really do anything but show how to use filters # This filter doesn't really do anything but show how to use filters
class MyHtmlFilter(wxHtmlFilter): class MyHtmlFilter(html.HtmlFilter):
def __init__(self, log): def __init__(self, log):
wxHtmlFilter.__init__(self) html.HtmlFilter.__init__(self)
self.log = log self.log = log
# This method decides if this filter is able to read the file # This method decides if this filter is able to read the file
@@ -62,64 +65,65 @@ class MyHtmlFilter(wxHtmlFilter):
return "" return ""
class TestHtmlPanel(wxPanel): class TestHtmlPanel(wx.Panel):
def __init__(self, parent, frame, log): def __init__(self, parent, frame, log):
wxPanel.__init__(self, parent, -1, style=wxNO_FULL_REPAINT_ON_RESIZE) wx.Panel.__init__(self, parent, -1, style=wx.NO_FULL_REPAINT_ON_RESIZE)
self.log = log self.log = log
self.frame = frame self.frame = frame
self.cwd = os.path.split(sys.argv[0])[0] self.cwd = os.path.split(sys.argv[0])[0]
if not self.cwd: if not self.cwd:
self.cwd = os.getcwd() self.cwd = os.getcwd()
if frame: if frame:
self.titleBase = frame.GetTitle() self.titleBase = frame.GetTitle()
wxHtmlWindow_AddFilter(MyHtmlFilter(log)) html.HtmlWindow_AddFilter(MyHtmlFilter(log))
self.html = MyHtmlWindow(self, -1, log) self.html = MyHtmlWindow(self, -1, log)
self.html.SetRelatedFrame(frame, self.titleBase + " -- %s") self.html.SetRelatedFrame(frame, self.titleBase + " -- %s")
self.html.SetRelatedStatusBar(0) self.html.SetRelatedStatusBar(0)
self.printer = wxHtmlEasyPrinting() self.printer = html.HtmlEasyPrinting()
self.box = wxBoxSizer(wxVERTICAL) self.box = wx.BoxSizer(wx.VERTICAL)
self.box.Add(self.html, 1, wxGROW) self.box.Add(self.html, 1, wx.GROW)
subbox = wxBoxSizer(wxHORIZONTAL) subbox = wx.BoxSizer(wx.HORIZONTAL)
btn = wxButton(self, -1, "Load File") btn = wx.Button(self, -1, "Load File")
EVT_BUTTON(self, btn.GetId(), self.OnLoadFile) self.Bind(wx.EVT_BUTTON, self.OnLoadFile, btn)
subbox.Add(btn, 1, wxGROW | wxALL, 2) subbox.Add(btn, 1, wx.GROW | wx.ALL, 2)
btn = wxButton(self, -1, "Load URL") btn = wx.Button(self, -1, "Load URL")
EVT_BUTTON(self, btn.GetId(), self.OnLoadURL) self.Bind(wx.EVT_BUTTON, self.OnLoadURL, btn)
subbox.Add(btn, 1, wxGROW | wxALL, 2) subbox.Add(btn, 1, wx.GROW | wx.ALL, 2)
btn = wxButton(self, -1, "With Widgets") btn = wx.Button(self, -1, "With Widgets")
EVT_BUTTON(self, btn.GetId(), self.OnWithWidgets) self.Bind(wx.EVT_BUTTON, self.OnWithWidgets, btn)
subbox.Add(btn, 1, wxGROW | wxALL, 2) subbox.Add(btn, 1, wx.GROW | wx.ALL, 2)
btn = wxButton(self, -1, "Back") btn = wx.Button(self, -1, "Back")
EVT_BUTTON(self, btn.GetId(), self.OnBack) self.Bind(wx.EVT_BUTTON, self.OnBack, btn)
subbox.Add(btn, 1, wxGROW | wxALL, 2) subbox.Add(btn, 1, wx.GROW | wx.ALL, 2)
btn = wxButton(self, -1, "Forward") btn = wx.Button(self, -1, "Forward")
EVT_BUTTON(self, btn.GetId(), self.OnForward) self.Bind(wx.EVT_BUTTON, self.OnForward, btn)
subbox.Add(btn, 1, wxGROW | wxALL, 2) subbox.Add(btn, 1, wx.GROW | wx.ALL, 2)
btn = wxButton(self, -1, "Print") btn = wx.Button(self, -1, "Print")
EVT_BUTTON(self, btn.GetId(), self.OnPrint) self.Bind(wx.EVT_BUTTON, self.OnPrint, btn)
subbox.Add(btn, 1, wxGROW | wxALL, 2) subbox.Add(btn, 1, wx.GROW | wx.ALL, 2)
btn = wxButton(self, -1, "View Source") btn = wx.Button(self, -1, "View Source")
EVT_BUTTON(self, btn.GetId(), self.OnViewSource) self.Bind(wx.EVT_BUTTON, self.OnViewSource, btn)
subbox.Add(btn, 1, wxGROW | wxALL, 2) subbox.Add(btn, 1, wx.GROW | wx.ALL, 2)
self.box.Add(subbox, 0, wxGROW) self.box.Add(subbox, 0, wx.GROW)
self.SetSizer(self.box) self.SetSizer(self.box)
self.SetAutoLayout(True) self.SetAutoLayout(True)
# A button with this ID is created on the widget test page. # A button with this ID is created on the widget test page.
EVT_BUTTON(self, wxID_OK, self.OnOk) self.Bind(wx.EVT_BUTTON, self.OnOk, id=wx.ID_OK)
self.OnShowDefault(None) self.OnShowDefault(None)
@@ -136,18 +140,22 @@ class TestHtmlPanel(wxPanel):
def OnLoadFile(self, event): def OnLoadFile(self, event):
dlg = wxFileDialog(self, wildcard = '*.htm*', style=wxOPEN) dlg = wx.FileDialog(self, wildcard = '*.htm*', style=wx.OPEN)
if dlg.ShowModal(): if dlg.ShowModal():
path = dlg.GetPath() path = dlg.GetPath()
self.html.LoadPage(path) self.html.LoadPage(path)
dlg.Destroy() dlg.Destroy()
def OnLoadURL(self, event): def OnLoadURL(self, event):
dlg = wxTextEntryDialog(self, "Enter a URL") dlg = wx.TextEntryDialog(self, "Enter a URL")
if dlg.ShowModal(): if dlg.ShowModal():
url = dlg.GetValue() url = dlg.GetValue()
self.html.LoadPage(url) self.html.LoadPage(url)
dlg.Destroy() dlg.Destroy()
@@ -162,18 +170,20 @@ class TestHtmlPanel(wxPanel):
def OnBack(self, event): def OnBack(self, event):
if not self.html.HistoryBack(): if not self.html.HistoryBack():
wxMessageBox("No more items in history!") wx.MessageBox("No more items in history!")
def OnForward(self, event): def OnForward(self, event):
if not self.html.HistoryForward(): if not self.html.HistoryForward():
wxMessageBox("No more items in history!") wx.MessageBox("No more items in history!")
def OnViewSource(self, event): def OnViewSource(self, event):
from wxPython.lib.dialogs import wxScrolledMessageDialog import wx.lib.dialogs as dlgs
source = self.html.GetParser().GetSource() source = self.html.GetParser().GetSource()
dlg = wxScrolledMessageDialog(self, source, 'HTML Source')
dlg = dlgs.wxScrolledMessageDialog(self, source, 'HTML Source')
dlg.ShowModal() dlg.ShowModal()
dlg.Destroy() dlg.Destroy()
@@ -186,16 +196,13 @@ class TestHtmlPanel(wxPanel):
def runTest(frame, nb, log): def runTest(frame, nb, log):
win = TestHtmlPanel(nb, frame, log) win = TestHtmlPanel(nb, frame, log)
print wxWindow_FindFocus() print wx.Window_FindFocus()
return win return win
#---------------------------------------------------------------------- #----------------------------------------------------------------------
overview = """<html><body> overview = """<html><body>
<h2>wxHtmlWindow</h2> <h2>wxHtmlWindow</h2>
@@ -203,9 +210,8 @@ overview = """<html><body>
simple HTML tags. simple HTML tags.
<p>It is not intended to be a high-end HTML browser. If you're <p>It is not intended to be a high-end HTML browser. If you're
looking for something like that try http://www.mozilla.org - there's a looking for something like that see the IEHtmlWin class, which
chance you'll be able to make their widget wxWindows-compatible. I'm wraps the core MSIE HTML viewer.
sure everyone will enjoy your work in that case...
</body></html> </body></html>
""" """

View File

@@ -1,83 +1,96 @@
# 11/18/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
# 11/28/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o iewin.py is missing
#
from wxPython.wx import * import wx
if wxPlatform == '__WXMSW__': if wx.Platform == '__WXMSW__':
from wxPython.iewin import * import wx.iewin as iewin
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wxWindow): class TestPanel(wx.Window):
def __init__(self, parent, log, frame=None): def __init__(self, parent, log, frame=None):
wxWindow.__init__(self, parent, -1, wx.Window.__init__(
style=wxTAB_TRAVERSAL|wxCLIP_CHILDREN|wxNO_FULL_REPAINT_ON_RESIZE) self, parent, -1,
style=wx.TAB_TRAVERSAL|wx.CLIP_CHILDREN|wx.NO_FULL_REPAINT_ON_RESIZE
)
self.log = log self.log = log
self.current = "http://wxWindows.org/" self.current = "http://wxPython.org/"
self.frame = frame self.frame = frame
if frame: if frame:
self.titleBase = frame.GetTitle() self.titleBase = frame.GetTitle()
sizer = wx.BoxSizer(wx.VERTICAL)
btnSizer = wx.BoxSizer(wx.HORIZONTAL)
sizer = wxBoxSizer(wxVERTICAL) self.ie = iewin.IEHtmlWin(self, -1, style = wx.NO_FULL_REPAINT_ON_RESIZE)
btnSizer = wxBoxSizer(wxHORIZONTAL)
self.ie = wxIEHtmlWin(self, -1, style = wxNO_FULL_REPAINT_ON_RESIZE)
btn = wxButton(self, wxNewId(), "Open", style=wxBU_EXACTFIT) btn = wx.Button(self, wx.NewId(), "Open", style=wx.BU_EXACTFIT)
EVT_BUTTON(self, btn.GetId(), self.OnOpenButton) wx.EVT_BUTTON(self, btn.GetId(), self.OnOpenButton)
btnSizer.Add(btn, 0, wxEXPAND|wxALL, 2) btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)
btn = wxButton(self, wxNewId(), "Home", style=wxBU_EXACTFIT) btn = wx.Button(self, wx.NewId(), "Home", style=wx.BU_EXACTFIT)
EVT_BUTTON(self, btn.GetId(), self.OnHomeButton) wx.EVT_BUTTON(self, btn.GetId(), self.OnHomeButton)
btnSizer.Add(btn, 0, wxEXPAND|wxALL, 2) btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)
btn = wxButton(self, wxNewId(), "<--", style=wxBU_EXACTFIT) btn = wx.Button(self, wx.NewId(), "<--", style=wx.BU_EXACTFIT)
EVT_BUTTON(self, btn.GetId(), self.OnPrevPageButton) wx.EVT_BUTTON(self, btn.GetId(), self.OnPrevPageButton)
btnSizer.Add(btn, 0, wxEXPAND|wxALL, 2) btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)
btn = wxButton(self, wxNewId(), "-->", style=wxBU_EXACTFIT) btn = wx.Button(self, wx.NewId(), "-->", style=wx.BU_EXACTFIT)
EVT_BUTTON(self, btn.GetId(), self.OnNextPageButton) wx.EVT_BUTTON(self, btn.GetId(), self.OnNextPageButton)
btnSizer.Add(btn, 0, wxEXPAND|wxALL, 2) btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)
btn = wxButton(self, wxNewId(), "Stop", style=wxBU_EXACTFIT) btn = wx.Button(self, wx.NewId(), "Stop", style=wx.BU_EXACTFIT)
EVT_BUTTON(self, btn.GetId(), self.OnStopButton) wx.EVT_BUTTON(self, btn.GetId(), self.OnStopButton)
btnSizer.Add(btn, 0, wxEXPAND|wxALL, 2) btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)
btn = wxButton(self, wxNewId(), "Search", style=wxBU_EXACTFIT) btn = wx.Button(self, wx.NewId(), "Search", style=wx.BU_EXACTFIT)
EVT_BUTTON(self, btn.GetId(), self.OnSearchPageButton) wx.EVT_BUTTON(self, btn.GetId(), self.OnSearchPageButton)
btnSizer.Add(btn, 0, wxEXPAND|wxALL, 2) btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)
btn = wxButton(self, wxNewId(), "Refresh", style=wxBU_EXACTFIT) btn = wx.Button(self, wx.NewId(), "Refresh", style=wx.BU_EXACTFIT)
EVT_BUTTON(self, btn.GetId(), self.OnRefreshPageButton) wx.EVT_BUTTON(self, btn.GetId(), self.OnRefreshPageButton)
btnSizer.Add(btn, 0, wxEXPAND|wxALL, 2) btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)
txt = wxStaticText(self, -1, "Location:") txt = wx.StaticText(self, -1, "Location:")
btnSizer.Add(txt, 0, wxCENTER|wxALL, 2) btnSizer.Add(txt, 0, wx.CENTER|wx.ALL, 2)
self.location = wxComboBox(self, wxNewId(), "", style=wxCB_DROPDOWN|wxPROCESS_ENTER) self.location = wx.ComboBox(
EVT_COMBOBOX(self, self.location.GetId(), self.OnLocationSelect) self, wx.NewId(), "", style=wx.CB_DROPDOWN|wx.PROCESS_ENTER
EVT_KEY_UP(self.location, self.OnLocationKey) )
EVT_CHAR(self.location, self.IgnoreReturn)
btnSizer.Add(self.location, 1, wxEXPAND|wxALL, 2)
wx.EVT_COMBOBOX(self, self.location.GetId(), self.OnLocationSelect)
wx.EVT_KEY_UP(self.location, self.OnLocationKey)
wx.EVT_CHAR(self.location, self.IgnoreReturn)
btnSizer.Add(self.location, 1, wx.EXPAND|wx.ALL, 2)
sizer.Add(btnSizer, 0, wxEXPAND) sizer.Add(btnSizer, 0, wx.EXPAND)
sizer.Add(self.ie, 1, wxEXPAND) sizer.Add(self.ie, 1, wx.EXPAND)
self.ie.Navigate(self.current) self.ie.Navigate(self.current)
self.location.Append(self.current) self.location.Append(self.current)
self.SetSizer(sizer) self.SetSizer(sizer)
self.SetAutoLayout(True) self.SetAutoLayout(True)
EVT_SIZE(self, self.OnSize) wx.EVT_SIZE(self, self.OnSize)
# Hook up the event handlers for the IE window # Hook up the event handlers for the IE window
EVT_MSHTML_BEFORENAVIGATE2(self, -1, self.OnBeforeNavigate2) iewin.EVT_MSHTML_BEFORENAVIGATE2(self, -1, self.OnBeforeNavigate2)
EVT_MSHTML_NEWWINDOW2(self, -1, self.OnNewWindow2) iewin.EVT_MSHTML_NEWWINDOW2(self, -1, self.OnNewWindow2)
EVT_MSHTML_DOCUMENTCOMPLETE(self, -1, self.OnDocumentComplete) iewin.EVT_MSHTML_DOCUMENTCOMPLETE(self, -1, self.OnDocumentComplete)
#EVT_MSHTML_PROGRESSCHANGE(self, -1, self.OnProgressChange) #EVT_MSHTML_PROGRESSCHANGE(self, -1, self.OnProgressChange)
EVT_MSHTML_STATUSTEXTCHANGE(self, -1, self.OnStatusTextChange) iewin.EVT_MSHTML_STATUSTEXTCHANGE(self, -1, self.OnStatusTextChange)
EVT_MSHTML_TITLECHANGE(self, -1, self.OnTitleChange) iewin.EVT_MSHTML_TITLECHANGE(self, -1, self.OnTitleChange)
def ShutdownDemo(self): def ShutdownDemo(self):
@@ -96,7 +109,7 @@ class TestPanel(wxWindow):
self.ie.Navigate(url) self.ie.Navigate(url)
def OnLocationKey(self, evt): def OnLocationKey(self, evt):
if evt.KeyCode() == WXK_RETURN: if evt.KeyCode() == wx.WXK_RETURN:
URL = self.location.GetValue() URL = self.location.GetValue()
self.location.Append(URL) self.location.Append(URL)
self.ie.Navigate(URL) self.ie.Navigate(URL)
@@ -105,17 +118,19 @@ class TestPanel(wxWindow):
def IgnoreReturn(self, evt): def IgnoreReturn(self, evt):
if evt.GetKeyCode() != WXK_RETURN: if evt.GetKeyCode() != wx.WXK_RETURN:
evt.Skip() evt.Skip()
def OnOpenButton(self, event): def OnOpenButton(self, event):
dlg = wxTextEntryDialog(self, "Open Location", dlg = wx.TextEntryDialog(self, "Open Location",
"Enter a full URL or local path", "Enter a full URL or local path",
self.current, wxOK|wxCANCEL) self.current, wx.OK|wx.CANCEL)
dlg.CentreOnParent() dlg.CentreOnParent()
if dlg.ShowModal() == wxID_OK:
if dlg.ShowModal() == wx.ID_OK:
self.current = dlg.GetValue() self.current = dlg.GetValue()
self.ie.Navigate(self.current) self.ie.Navigate(self.current)
dlg.Destroy() dlg.Destroy()
def OnHomeButton(self, event): def OnHomeButton(self, event):
@@ -134,8 +149,7 @@ class TestPanel(wxWindow):
self.ie.GoSearch() self.ie.GoSearch()
def OnRefreshPageButton(self, evt): def OnRefreshPageButton(self, evt):
self.ie.Refresh(wxIEHTML_REFRESH_COMPLETELY) self.ie.Refresh(iewin.IEHTML_REFRESH_COMPLETELY)
def logEvt(self, name, event): def logEvt(self, name, event):
@@ -169,12 +183,12 @@ class TestPanel(wxWindow):
# for the demo framework... # for the demo framework...
def runTest(frame, nb, log): def runTest(frame, nb, log):
if wxPlatform == '__WXMSW__': if wx.Platform == '__WXMSW__':
win = TestPanel(nb, log, frame) win = TestPanel(nb, log, frame)
return win return win
else: else:
dlg = wxMessageDialog(frame, 'This demo only works on MSW.', dlg = wx.MessageDialog(frame, 'This demo only works on MSW.',
'Sorry', wxOK | wxICON_INFORMATION) 'Sorry', wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal() dlg.ShowModal()
dlg.Destroy() dlg.Destroy()

View File

@@ -1,31 +1,33 @@
# 11/19/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
import wx
from wxPython.wx import *
from Main import opj from Main import opj
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def runTest(frame, nb, log): def runTest(frame, nb, log):
bmp = wxImage(opj('bitmaps/image.bmp'), wxBITMAP_TYPE_BMP).ConvertToBitmap() bmp = wx.Image(opj('bitmaps/image.bmp'), wx.BITMAP_TYPE_BMP).ConvertToBitmap()
gif = wxImage(opj('bitmaps/image.gif'), wxBITMAP_TYPE_GIF).ConvertToBitmap() gif = wx.Image(opj('bitmaps/image.gif'), wx.BITMAP_TYPE_GIF).ConvertToBitmap()
png = wxImage(opj('bitmaps/image.png'), wxBITMAP_TYPE_PNG).ConvertToBitmap() png = wx.Image(opj('bitmaps/image.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap()
jpg = wxImage(opj('bitmaps/image.jpg'), wxBITMAP_TYPE_JPEG).ConvertToBitmap() jpg = wx.Image(opj('bitmaps/image.jpg'), wx.BITMAP_TYPE_JPEG).ConvertToBitmap()
panel = wx.Panel(nb, -1)
panel = wxPanel(nb, -1)
pos = 10 pos = 10
wxStaticBitmap(panel, -1, bmp, wxPoint(10, pos), wx.StaticBitmap(panel, -1, bmp, (10, pos), (bmp.GetWidth(), bmp.GetHeight()))
wxSize(bmp.GetWidth(), bmp.GetHeight()))
pos = pos + bmp.GetHeight() + 10 pos = pos + bmp.GetHeight() + 10
wxStaticBitmap(panel, -1, gif, wxPoint(10, pos), wx.StaticBitmap(panel, -1, gif, (10, pos), (gif.GetWidth(), gif.GetHeight()))
wxSize(gif.GetWidth(), gif.GetHeight()))
pos = pos + gif.GetHeight() + 10 pos = pos + gif.GetHeight() + 10
wxStaticBitmap(panel, -1, png, wxPoint(10, pos), wx.StaticBitmap(panel, -1, png, (10, pos), (png.GetWidth(), png.GetHeight()))
wxSize(png.GetWidth(), png.GetHeight()))
pos = pos + png.GetHeight() + 10 pos = pos + png.GetHeight() + 10
wxStaticBitmap(panel, -1, jpg, wxPoint(10, pos), wx.StaticBitmap(panel, -1, jpg, (10, pos), (jpg.GetWidth(), jpg.GetHeight()))
wxSize(jpg.GetWidth(), jpg.GetHeight()))
return panel return panel
@@ -33,14 +35,44 @@ def runTest(frame, nb, log):
overview = """\ overview = """\
""" <html>
<body>
This class encapsulates a platform-independent image. An image can be created
from data, or using <code>wxBitmap.ConvertToImage</code>. An image can be loaded from
a file in a variety of formats, and is extensible to new formats via image
format handlers. Functions are available to set and get image bits, so it can
be used for basic image manipulation.
<p>The following image handlers are available. wxBMPHandler is always installed
by default. To use other image formats, install the appropriate handler or use
<code>wx.InitAllImageHandlers()</code>.
<p>
<table>
<tr><td width=25%>wxBMPHandler</td> <td>For loading and saving, always installed.</td></tr>
<tr><td>wxPNGHandler</td> <td>For loading and saving.</td> </tr>
<tr><td>wxJPEGHandler</td> <td>For loading and saving.</td> </tr>
<tr><td>wxGIFHandler</td> <td>Only for loading, due to legal issues.</td> </tr>
<tr><td>wxPCXHandler</td> <td>For loading and saving.</td> </tr>
<tr><td>wxPNMHandler</td> <td>For loading and saving.</td> </tr>
<tr><td>wxTIFFHandler</td> <td>For loading and saving.</td> </tr>
<tr><td>wxIFFHandler</td> <td>For loading only.</td> </tr>
<tr><td>wxXPMHandler</td> <td>For loading and saving.</td> </tr>
<tr><td>wxICOHandler</td> <td>For loading and saving.</td> </tr>
<tr><td>wxCURHandler</td> <td>For loading and saving.</td> </tr>
<tr><td>wxANIHandler</td> <td>For loading only.</td> </tr>
</table>
<p>When saving in PCX format, wxPCXHandler will count the number of different
colours in the image; if there are 256 or less colours, it will save as 8 bit,
else it will save as 24 bit.
<p>Loading PNMs only works for ASCII or raw RGB images. When saving in PNM format,
wxPNMHandler will always save as raw RGB.
</body>
</html>"""
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os

View File

@@ -1,24 +1,31 @@
# 11/19/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
import cStringIO
import wx
from wxPython.wx import *
from Main import opj from Main import opj
from cStringIO import StringIO
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
data = open(opj('bitmaps/image.png'), "rb").read() data = open(opj('bitmaps/image.png'), "rb").read()
stream = StringIO(data) stream = cStringIO.StringIO(data)
bmp = wxBitmapFromImage( wxImageFromStream( stream )) bmp = wx.BitmapFromImage( wx.ImageFromStream( stream ))
wxStaticText(self, -1, wx.StaticText(
"This image was loaded from a Python file-like object:", self, -1, "This image was loaded from a Python file-like object:",
(15, 15)) (15, 15)
wxStaticBitmap(self, -1, bmp, (15, 45))#, (bmp.GetWidth(), bmp.GetHeight())) )
wx.StaticBitmap(self, -1, bmp, (15, 45))#, (bmp.GetWidth(), bmp.GetHeight()))
@@ -37,10 +44,7 @@ directly from any Python file-like object, such as a memory buffer
using StringIO. """ using StringIO. """
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run
run.main(['', os.path.basename(sys.argv[0])]) run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -1,52 +1,62 @@
from wxPython.wx import * # 11/19/2003 - Jeff Grimmett (grimmtooth@softhome.net)
from wxPython.lib.intctrl import * #
# o Updated for wx namespace
#
# 11/29/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o intctrl needs the renamer applied.
# o intctrl needs new event binders.
#
import wx
import wx.lib.intctrl as intctrl
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel( wxPanel ): class TestPanel( wx.Panel ):
def __init__( self, parent, log ): def __init__( self, parent, log ):
wxPanel.__init__( self, parent, -1 ) wx.Panel.__init__( self, parent, -1 )
self.log = log self.log = log
panel = wxPanel( self, -1 ) panel = wx.Panel( self, -1 )
self.set_min = wxCheckBox( panel, -1, "Set minimum value:" ) self.set_min = wx.CheckBox( panel, -1, "Set minimum value:" )
self.min = wxIntCtrl( panel, size=wxSize( 50, -1 ) ) self.min = intctrl.wxIntCtrl( panel, size=( 50, -1 ) )
self.min.Enable( False ) self.min.Enable( False )
self.set_max = wxCheckBox( panel, -1, "Set maximum value:" ) self.set_max = wx.CheckBox( panel, -1, "Set maximum value:" )
self.max = wxIntCtrl( panel, size=wxSize( 50, -1 ) ) self.max = intctrl.wxIntCtrl( panel, size=( 50, -1 ) )
self.max.Enable( False ) self.max.Enable( False )
self.limit_target = wxCheckBox( panel, -1, "Limit control" ) self.limit_target = wx.CheckBox( panel, -1, "Limit control" )
self.allow_none = wxCheckBox( panel, -1, "Allow empty control" ) self.allow_none = wx.CheckBox( panel, -1, "Allow empty control" )
self.allow_long = wxCheckBox( panel, -1, "Allow long integers" ) self.allow_long = wx.CheckBox( panel, -1, "Allow long integers" )
label = wxStaticText( panel, -1, "Resulting integer control:" ) label = wx.StaticText( panel, -1, "Resulting integer control:" )
self.target_ctl = wxIntCtrl( panel ) self.target_ctl = intctrl.wxIntCtrl( panel )
grid = wxFlexGridSizer( 0, 2, 0, 0 ) grid = wx.FlexGridSizer( 0, 2, 0, 0 )
grid.AddWindow( self.set_min, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5 ) grid.Add( self.set_min, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5 )
grid.AddWindow( self.min, 0, wxALIGN_LEFT|wxALL, 5 ) grid.Add( self.min, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
grid.AddWindow( self.set_max, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5 ) grid.Add(self.set_max, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5 )
grid.AddWindow( self.max, 0, wxALIGN_LEFT|wxALL, 5 ) grid.Add( self.max, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
grid.AddWindow( self.limit_target, 0, wxALIGN_LEFT|wxALL, 5 ) grid.Add( self.limit_target, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
grid.AddSpacer( (20, 0), 0, wxALIGN_LEFT|wxALL, 5 ) grid.Add( (20, 0), 0, wx.ALIGN_LEFT|wx.ALL, 5 )
grid.AddWindow( self.allow_none, 0, wxALIGN_LEFT|wxALL, 5 ) grid.Add( self.allow_none, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
grid.AddSpacer( (20, 0), 0, wxALIGN_LEFT|wxALL, 5 ) grid.Add( (20, 0), 0, wx.ALIGN_LEFT|wx.ALL, 5 )
grid.AddWindow( self.allow_long, 0, wxALIGN_LEFT|wxALL, 5 ) grid.Add( self.allow_long, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
grid.AddSpacer( (20, 0), 0, wxALIGN_LEFT|wxALL, 5 ) grid.Add( (20, 0), 0, wx.ALIGN_LEFT|wx.ALL, 5 )
grid.AddSpacer( (20, 0), 0, wxALIGN_LEFT|wxALL, 5 ) grid.Add( (20, 0), 0, wx.ALIGN_LEFT|wx.ALL, 5 )
grid.AddSpacer( (20, 0), 0, wxALIGN_LEFT|wxALL, 5 ) grid.Add( (20, 0), 0, wx.ALIGN_LEFT|wx.ALL, 5 )
grid.AddWindow( label, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5 ) grid.Add( label, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5 )
grid.AddWindow( self.target_ctl, 0, wxALIGN_LEFT|wxALL, 5 ) grid.Add( self.target_ctl, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
outer_box = wxBoxSizer( wxVERTICAL ) outer_box = wx.BoxSizer( wx.VERTICAL )
outer_box.AddSizer( grid, 0, wxALIGN_CENTRE|wxALL, 20 ) outer_box.AddSizer( grid, 0, wx.ALIGN_CENTRE|wx.ALL, 20 )
panel.SetAutoLayout( True ) panel.SetAutoLayout( True )
panel.SetSizer( outer_box ) panel.SetSizer( outer_box )
@@ -54,14 +64,16 @@ class TestPanel( wxPanel ):
panel.Move( (50,50) ) panel.Move( (50,50) )
self.panel = panel self.panel = panel
EVT_CHECKBOX( self, self.set_min.GetId(), self.OnSetMin ) self.Bind(wx.EVT_CHECKBOX, self.OnSetMin, self.set_min)
EVT_CHECKBOX( self, self.set_max.GetId(), self.OnSetMax ) self.Bind(wx.EVT_CHECKBOX, self.OnSetMax, self.set_max)
EVT_CHECKBOX( self, self.limit_target.GetId(), self.SetTargetMinMax ) self.Bind(wx.EVT_CHECKBOX, self.SetTargetMinMax, self.limit_target)
EVT_CHECKBOX( self, self.allow_none.GetId(), self.OnSetAllowNone ) self.Bind(wx.EVT_CHECKBOX, self.OnSetAllowNone, self.allow_none)
EVT_CHECKBOX( self, self.allow_long.GetId(), self.OnSetAllowLong ) self.Bind(wx.EVT_CHECKBOX, self.OnSetAllowLong, self.allow_long)
EVT_INT( self, self.min.GetId(), self.SetTargetMinMax )
EVT_INT( self, self.max.GetId(), self.SetTargetMinMax ) # Once the intctrl library is updated, this should be too.
EVT_INT( self, self.target_ctl.GetId(), self.OnTargetChange ) intctrl.EVT_INT(self, self.min.GetId(), self.SetTargetMinMax)
intctrl.EVT_INT(self, self.max.GetId(), self.SetTargetMinMax)
intctrl.EVT_INT(self, self.target_ctl.GetId(), self.OnTargetChange)
def OnSetMin( self, event ): def OnSetMin( self, event ):
@@ -79,6 +91,7 @@ class TestPanel( wxPanel ):
if self.set_min.GetValue(): if self.set_min.GetValue():
min = self.min.GetValue() min = self.min.GetValue()
if self.set_max.GetValue(): if self.set_max.GetValue():
max = self.max.GetValue() max = self.max.GetValue()
@@ -86,16 +99,18 @@ class TestPanel( wxPanel ):
if min != cur_min and not self.target_ctl.SetMin( min ): if min != cur_min and not self.target_ctl.SetMin( min ):
self.log.write( "min (%d) > current max (%d) -- bound not set\n" % ( min, self.target_ctl.GetMax() ) ) self.log.write( "min (%d) > current max (%d) -- bound not set\n" % ( min, self.target_ctl.GetMax() ) )
self.min.SetForegroundColour( wxRED ) self.min.SetForegroundColour( wx.RED )
else: else:
self.min.SetForegroundColour( wxBLACK ) self.min.SetForegroundColour( wx.BLACK )
self.min.Refresh() self.min.Refresh()
if max != cur_max and not self.target_ctl.SetMax( max ): if max != cur_max and not self.target_ctl.SetMax( max ):
self.log.write( "max (%d) < current min (%d) -- bound not set\n" % ( max, self.target_ctl.GetMin() ) ) self.log.write( "max (%d) < current min (%d) -- bound not set\n" % ( max, self.target_ctl.GetMin() ) )
self.max.SetForegroundColour( wxRED ) self.max.SetForegroundColour( wx.RED )
else: else:
self.max.SetForegroundColour( wxBLACK ) self.max.SetForegroundColour( wx.BLACK )
self.max.Refresh() self.max.Refresh()
if min != cur_min or max != cur_max: if min != cur_min or max != cur_max:

View File

@@ -1,139 +1,148 @@
# 11/19/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
# 11/29/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o lib.mixins.listctrl needs wx renamer applied.
#
from wxPython.wx import * import wx
import wx.lib.mixins.listctrl as listmix
#---------------------------------------------------------------------- #----------------------------------------------------------------------
keyMap = { keyMap = {
WXK_BACK : "WXK_BACK", wx.WXK_BACK : "wx.WXK_BACK",
WXK_TAB : "WXK_TAB", wx.WXK_TAB : "wx.WXK_TAB",
WXK_RETURN : "WXK_RETURN", wx.WXK_RETURN : "wx.WXK_RETURN",
WXK_ESCAPE : "WXK_ESCAPE", wx.WXK_ESCAPE : "wx.WXK_ESCAPE",
WXK_SPACE : "WXK_SPACE", wx.WXK_SPACE : "wx.WXK_SPACE",
WXK_DELETE : "WXK_DELETE", wx.WXK_DELETE : "wx.WXK_DELETE",
WXK_START : "WXK_START", wx.WXK_START : "wx.WXK_START",
WXK_LBUTTON : "WXK_LBUTTON", wx.WXK_LBUTTON : "wx.WXK_LBUTTON",
WXK_RBUTTON : "WXK_RBUTTON", wx.WXK_RBUTTON : "wx.WXK_RBUTTON",
WXK_CANCEL : "WXK_CANCEL", wx.WXK_CANCEL : "wx.WXK_CANCEL",
WXK_MBUTTON : "WXK_MBUTTON", wx.WXK_MBUTTON : "wx.WXK_MBUTTON",
WXK_CLEAR : "WXK_CLEAR", wx.WXK_CLEAR : "wx.WXK_CLEAR",
WXK_SHIFT : "WXK_SHIFT", wx.WXK_SHIFT : "wx.WXK_SHIFT",
WXK_ALT : "WXK_ALT", wx.WXK_ALT : "wx.WXK_ALT",
WXK_CONTROL : "WXK_CONTROL", wx.WXK_CONTROL : "wx.WXK_CONTROL",
WXK_MENU : "WXK_MENU", wx.WXK_MENU : "wx.WXK_MENU",
WXK_PAUSE : "WXK_PAUSE", wx.WXK_PAUSE : "wx.WXK_PAUSE",
WXK_CAPITAL : "WXK_CAPITAL", wx.WXK_CAPITAL : "wx.WXK_CAPITAL",
WXK_PRIOR : "WXK_PRIOR", wx.WXK_PRIOR : "wx.WXK_PRIOR",
WXK_NEXT : "WXK_NEXT", wx.WXK_NEXT : "wx.WXK_NEXT",
WXK_END : "WXK_END", wx.WXK_END : "wx.WXK_END",
WXK_HOME : "WXK_HOME", wx.WXK_HOME : "wx.WXK_HOME",
WXK_LEFT : "WXK_LEFT", wx.WXK_LEFT : "wx.WXK_LEFT",
WXK_UP : "WXK_UP", wx.WXK_UP : "wx.WXK_UP",
WXK_RIGHT : "WXK_RIGHT", wx.WXK_RIGHT : "wx.WXK_RIGHT",
WXK_DOWN : "WXK_DOWN", wx.WXK_DOWN : "wx.WXK_DOWN",
WXK_SELECT : "WXK_SELECT", wx.WXK_SELECT : "wx.WXK_SELECT",
WXK_PRINT : "WXK_PRINT", wx.WXK_PRINT : "wx.WXK_PRINT",
WXK_EXECUTE : "WXK_EXECUTE", wx.WXK_EXECUTE : "wx.WXK_EXECUTE",
WXK_SNAPSHOT : "WXK_SNAPSHOT", wx.WXK_SNAPSHOT : "wx.WXK_SNAPSHOT",
WXK_INSERT : "WXK_INSERT", wx.WXK_INSERT : "wx.WXK_INSERT",
WXK_HELP : "WXK_HELP", wx.WXK_HELP : "wx.WXK_HELP",
WXK_NUMPAD0 : "WXK_NUMPAD0", wx.WXK_NUMPAD0 : "wx.WXK_NUMPAD0",
WXK_NUMPAD1 : "WXK_NUMPAD1", wx.WXK_NUMPAD1 : "wx.WXK_NUMPAD1",
WXK_NUMPAD2 : "WXK_NUMPAD2", wx.WXK_NUMPAD2 : "wx.WXK_NUMPAD2",
WXK_NUMPAD3 : "WXK_NUMPAD3", wx.WXK_NUMPAD3 : "wx.WXK_NUMPAD3",
WXK_NUMPAD4 : "WXK_NUMPAD4", wx.WXK_NUMPAD4 : "wx.WXK_NUMPAD4",
WXK_NUMPAD5 : "WXK_NUMPAD5", wx.WXK_NUMPAD5 : "wx.WXK_NUMPAD5",
WXK_NUMPAD6 : "WXK_NUMPAD6", wx.WXK_NUMPAD6 : "wx.WXK_NUMPAD6",
WXK_NUMPAD7 : "WXK_NUMPAD7", wx.WXK_NUMPAD7 : "wx.WXK_NUMPAD7",
WXK_NUMPAD8 : "WXK_NUMPAD8", wx.WXK_NUMPAD8 : "wx.WXK_NUMPAD8",
WXK_NUMPAD9 : "WXK_NUMPAD9", wx.WXK_NUMPAD9 : "wx.WXK_NUMPAD9",
WXK_MULTIPLY : "WXK_MULTIPLY", wx.WXK_MULTIPLY : "wx.WXK_MULTIPLY",
WXK_ADD : "WXK_ADD", wx.WXK_ADD : "wx.WXK_ADD",
WXK_SEPARATOR : "WXK_SEPARATOR", wx.WXK_SEPARATOR : "wx.WXK_SEPARATOR",
WXK_SUBTRACT : "WXK_SUBTRACT", wx.WXK_SUBTRACT : "wx.WXK_SUBTRACT",
WXK_DECIMAL : "WXK_DECIMAL", wx.WXK_DECIMAL : "wx.WXK_DECIMAL",
WXK_DIVIDE : "WXK_DIVIDE", wx.WXK_DIVIDE : "wx.WXK_DIVIDE",
WXK_F1 : "WXK_F1", wx.WXK_F1 : "wx.WXK_F1",
WXK_F2 : "WXK_F2", wx.WXK_F2 : "wx.WXK_F2",
WXK_F3 : "WXK_F3", wx.WXK_F3 : "wx.WXK_F3",
WXK_F4 : "WXK_F4", wx.WXK_F4 : "wx.WXK_F4",
WXK_F5 : "WXK_F5", wx.WXK_F5 : "wx.WXK_F5",
WXK_F6 : "WXK_F6", wx.WXK_F6 : "wx.WXK_F6",
WXK_F7 : "WXK_F7", wx.WXK_F7 : "wx.WXK_F7",
WXK_F8 : "WXK_F8", wx.WXK_F8 : "wx.WXK_F8",
WXK_F9 : "WXK_F9", wx.WXK_F9 : "wx.WXK_F9",
WXK_F10 : "WXK_F10", wx.WXK_F10 : "wx.WXK_F10",
WXK_F11 : "WXK_F11", wx.WXK_F11 : "wx.WXK_F11",
WXK_F12 : "WXK_F12", wx.WXK_F12 : "wx.WXK_F12",
WXK_F13 : "WXK_F13", wx.WXK_F13 : "wx.WXK_F13",
WXK_F14 : "WXK_F14", wx.WXK_F14 : "wx.WXK_F14",
WXK_F15 : "WXK_F15", wx.WXK_F15 : "wx.WXK_F15",
WXK_F16 : "WXK_F16", wx.WXK_F16 : "wx.WXK_F16",
WXK_F17 : "WXK_F17", wx.WXK_F17 : "wx.WXK_F17",
WXK_F18 : "WXK_F18", wx.WXK_F18 : "wx.WXK_F18",
WXK_F19 : "WXK_F19", wx.WXK_F19 : "wx.WXK_F19",
WXK_F20 : "WXK_F20", wx.WXK_F20 : "wx.WXK_F20",
WXK_F21 : "WXK_F21", wx.WXK_F21 : "wx.WXK_F21",
WXK_F22 : "WXK_F22", wx.WXK_F22 : "wx.WXK_F22",
WXK_F23 : "WXK_F23", wx.WXK_F23 : "wx.WXK_F23",
WXK_F24 : "WXK_F24", wx.WXK_F24 : "wx.WXK_F24",
WXK_NUMLOCK : "WXK_NUMLOCK", wx.WXK_NUMLOCK : "wx.WXK_NUMLOCK",
WXK_SCROLL : "WXK_SCROLL", wx.WXK_SCROLL : "wx.WXK_SCROLL",
WXK_PAGEUP : "WXK_PAGEUP", wx.WXK_PAGEUP : "wx.WXK_PAGEUP",
WXK_PAGEDOWN : "WXK_PAGEDOWN", wx.WXK_PAGEDOWN : "wx.WXK_PAGEDOWN",
WXK_NUMPAD_SPACE : "WXK_NUMPAD_SPACE", wx.WXK_NUMPAD_SPACE : "wx.WXK_NUMPAD_SPACE",
WXK_NUMPAD_TAB : "WXK_NUMPAD_TAB", wx.WXK_NUMPAD_TAB : "wx.WXK_NUMPAD_TAB",
WXK_NUMPAD_ENTER : "WXK_NUMPAD_ENTER", wx.WXK_NUMPAD_ENTER : "wx.WXK_NUMPAD_ENTER",
WXK_NUMPAD_F1 : "WXK_NUMPAD_F1", wx.WXK_NUMPAD_F1 : "wx.WXK_NUMPAD_F1",
WXK_NUMPAD_F2 : "WXK_NUMPAD_F2", wx.WXK_NUMPAD_F2 : "wx.WXK_NUMPAD_F2",
WXK_NUMPAD_F3 : "WXK_NUMPAD_F3", wx.WXK_NUMPAD_F3 : "wx.WXK_NUMPAD_F3",
WXK_NUMPAD_F4 : "WXK_NUMPAD_F4", wx.WXK_NUMPAD_F4 : "wx.WXK_NUMPAD_F4",
WXK_NUMPAD_HOME : "WXK_NUMPAD_HOME", wx.WXK_NUMPAD_HOME : "wx.WXK_NUMPAD_HOME",
WXK_NUMPAD_LEFT : "WXK_NUMPAD_LEFT", wx.WXK_NUMPAD_LEFT : "wx.WXK_NUMPAD_LEFT",
WXK_NUMPAD_UP : "WXK_NUMPAD_UP", wx.WXK_NUMPAD_UP : "wx.WXK_NUMPAD_UP",
WXK_NUMPAD_RIGHT : "WXK_NUMPAD_RIGHT", wx.WXK_NUMPAD_RIGHT : "wx.WXK_NUMPAD_RIGHT",
WXK_NUMPAD_DOWN : "WXK_NUMPAD_DOWN", wx.WXK_NUMPAD_DOWN : "wx.WXK_NUMPAD_DOWN",
WXK_NUMPAD_PRIOR : "WXK_NUMPAD_PRIOR", wx.WXK_NUMPAD_PRIOR : "wx.WXK_NUMPAD_PRIOR",
WXK_NUMPAD_PAGEUP : "WXK_NUMPAD_PAGEUP", wx.WXK_NUMPAD_PAGEUP : "wx.WXK_NUMPAD_PAGEUP",
WXK_NUMPAD_NEXT : "WXK_NUMPAD_NEXT", wx.WXK_NUMPAD_NEXT : "wx.WXK_NUMPAD_NEXT",
WXK_NUMPAD_PAGEDOWN : "WXK_NUMPAD_PAGEDOWN", wx.WXK_NUMPAD_PAGEDOWN : "wx.WXK_NUMPAD_PAGEDOWN",
WXK_NUMPAD_END : "WXK_NUMPAD_END", wx.WXK_NUMPAD_END : "wx.WXK_NUMPAD_END",
WXK_NUMPAD_BEGIN : "WXK_NUMPAD_BEGIN", wx.WXK_NUMPAD_BEGIN : "wx.WXK_NUMPAD_BEGIN",
WXK_NUMPAD_INSERT : "WXK_NUMPAD_INSERT", wx.WXK_NUMPAD_INSERT : "wx.WXK_NUMPAD_INSERT",
WXK_NUMPAD_DELETE : "WXK_NUMPAD_DELETE", wx.WXK_NUMPAD_DELETE : "wx.WXK_NUMPAD_DELETE",
WXK_NUMPAD_EQUAL : "WXK_NUMPAD_EQUAL", wx.WXK_NUMPAD_EQUAL : "wx.WXK_NUMPAD_EQUAL",
WXK_NUMPAD_MULTIPLY : "WXK_NUMPAD_MULTIPLY", wx.WXK_NUMPAD_MULTIPLY : "wx.WXK_NUMPAD_MULTIPLY",
WXK_NUMPAD_ADD : "WXK_NUMPAD_ADD", wx.WXK_NUMPAD_ADD : "wx.WXK_NUMPAD_ADD",
WXK_NUMPAD_SEPARATOR : "WXK_NUMPAD_SEPARATOR", wx.WXK_NUMPAD_SEPARATOR : "wx.WXK_NUMPAD_SEPARATOR",
WXK_NUMPAD_SUBTRACT : "WXK_NUMPAD_SUBTRACT", wx.WXK_NUMPAD_SUBTRACT : "wx.WXK_NUMPAD_SUBTRACT",
WXK_NUMPAD_DECIMAL : "WXK_NUMPAD_DECIMAL", wx.WXK_NUMPAD_DECIMAL : "wx.WXK_NUMPAD_DECIMAL",
WXK_NUMPAD_DIVIDE : "WXK_NUMPAD_DIVIDE", wx.WXK_NUMPAD_DIVIDE : "wx.WXK_NUMPAD_DIVIDE",
} }
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class KeySink(wxWindow): class KeySink(wx.Window):
def __init__(self, parent): def __init__(self, parent):
wxWindow.__init__(self, parent, -1, style = wx.Window.__init__(self, parent, -1, style=wx.WANTS_CHARS
wxWANTS_CHARS #| wx.RAISED_BORDER
#| wxRAISED_BORDER #| wx.SUNKEN_BORDER
#| wxSUNKEN_BORDER
) )
self.SetBackgroundColour(wxBLUE)
self.SetBackgroundColour(wx.BLUE)
self.haveFocus = False self.haveFocus = False
self.callSkip = False self.callSkip = False
self.logKeyDn = True self.logKeyDn = True
self.logKeyUp = True self.logKeyUp = True
self.logChar = True self.logChar = True
EVT_PAINT(self, self.OnPaint) self.Bind(wx.EVT_PAINT, self.OnPaint)
EVT_SET_FOCUS(self, self.OnSetFocus) self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
EVT_KILL_FOCUS(self, self.OnKillFocus) self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
EVT_MOUSE_EVENTS(self, self.OnMouse) self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
EVT_KEY_DOWN(self, self.OnKeyDown) self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
EVT_KEY_UP(self, self.OnKeyUp) self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
EVT_CHAR(self, self.OnChar) self.Bind(wx.EVT_CHAR, self.OnChar)
def SetCallSkip(self, skip): def SetCallSkip(self, skip):
@@ -150,17 +159,17 @@ class KeySink(wxWindow):
def OnPaint(self, evt): def OnPaint(self, evt):
dc = wxPaintDC(self) dc = wx.PaintDC(self)
rect = self.GetClientRect() rect = self.GetClientRect()
dc.SetTextForeground(wxWHITE) dc.SetTextForeground(wx.WHITE)
dc.DrawLabel("Click here and then press some keys", dc.DrawLabel("Click here and then press some keys",
rect, wxALIGN_CENTER | wxALIGN_TOP) rect, wx.ALIGN_CENTER | wx.ALIGN_TOP)
if self.haveFocus: if self.haveFocus:
dc.SetTextForeground(wxGREEN) dc.SetTextForeground(wx.GREEN)
dc.DrawLabel("Have Focus", rect, wxALIGN_RIGHT | wxALIGN_BOTTOM) dc.DrawLabel("Have Focus", rect, wx.ALIGN_RIGHT | wx.ALIGN_BOTTOM)
else: else:
dc.SetTextForeground(wxRED) dc.SetTextForeground(wx.RED)
dc.DrawLabel("Need Focus!", rect, wxALIGN_RIGHT | wxALIGN_BOTTOM) dc.DrawLabel("Need Focus!", rect, wx.ALIGN_RIGHT | wx.ALIGN_BOTTOM)
def OnSetFocus(self, evt): def OnSetFocus(self, evt):
@@ -195,14 +204,12 @@ class KeySink(wxWindow):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
from wxPython.lib.mixins.listctrl import wxListCtrlAutoWidthMixin class KeyLog(wx.ListCtrl, listmix.wxListCtrlAutoWidthMixin):
class KeyLog(wxListCtrl, wxListCtrlAutoWidthMixin):
def __init__(self, parent): def __init__(self, parent):
wxListCtrl.__init__(self, parent, -1, wx.ListCtrl.__init__(self, parent, -1,
style = wxLC_REPORT|wxLC_VRULES|wxLC_HRULES) style = wx.LC_REPORT|wx.LC_VRULES|wx.LC_HRULES)
wxListCtrlAutoWidthMixin.__init__(self) listmix.wxListCtrlAutoWidthMixin.__init__(self)
self.InsertColumn(0, "Event Type") self.InsertColumn(0, "Event Type")
self.InsertColumn(1, "Key Name") self.InsertColumn(1, "Key Name")
@@ -213,7 +220,7 @@ class KeyLog(wxListCtrl, wxListCtrlAutoWidthMixin):
self.InsertColumn(6, "") self.InsertColumn(6, "")
for x in range(6): for x in range(6):
self.SetColumnWidth(x, wxLIST_AUTOSIZE_USEHEADER) self.SetColumnWidth(x, wx.LIST_AUTOSIZE_USEHEADER)
self.SetColumnWidth(1, 125) self.SetColumnWidth(1, 125)
@@ -261,43 +268,43 @@ class KeyLog(wxListCtrl, wxListCtrlAutoWidthMixin):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
self.log = log self.log = log
wxPanel.__init__(self, parent, -1, style=0) wx.Panel.__init__(self, parent, -1, style=0)
self.keysink = KeySink(self) self.keysink = KeySink(self)
self.keysink.SetSize((100, 65)) self.keysink.SetSize((100, 65))
self.keylog = KeyLog(self) self.keylog = KeyLog(self)
btn = wxButton(self, -1, "Clear Log") btn = wx.Button(self, -1, "Clear Log")
EVT_BUTTON(self, btn.GetId(), self.OnClearBtn) self.Bind(wx.EVT_BUTTON, self.OnClearBtn, btn)
cb1 = wxCheckBox(self, -1, "Call evt.Skip for Key Up/Dn events") cb1 = wx.CheckBox(self, -1, "Call evt.Skip for Key Up/Dn events")
EVT_CHECKBOX(self, cb1.GetId(), self.OnSkipCB) self.Bind(wx.EVT_CHECKBOX, self.OnSkipCB, cb1)
cb2 = wxCheckBox(self, -1, "EVT_KEY_UP") cb2 = wx.CheckBox(self, -1, "EVT_KEY_UP")
EVT_CHECKBOX(self, cb2.GetId(), self.OnKeyUpCB) self.Bind(wx.EVT_CHECKBOX, self.OnKeyUpCB, cb2)
cb2.SetValue(True) cb2.SetValue(True)
cb3 = wxCheckBox(self, -1, "EVT_KEY_DOWN") cb3 = wx.CheckBox(self, -1, "EVT_KEY_DOWN")
EVT_CHECKBOX(self, cb3.GetId(), self.OnKeyDnCB) self.Bind(wx.EVT_CHECKBOX, self.OnKeyDnCB, cb3)
cb3.SetValue(True) cb3.SetValue(True)
cb4 = wxCheckBox(self, -1, "EVT_CHAR") cb4 = wx.CheckBox(self, -1, "EVT_CHAR")
EVT_CHECKBOX(self, cb4.GetId(), self.OnCharCB) self.Bind(wx.EVT_CHECKBOX, self.OnCharCB, cb4)
cb4.SetValue(True) cb4.SetValue(True)
buttons = wxBoxSizer(wxHORIZONTAL) buttons = wx.BoxSizer(wx.HORIZONTAL)
buttons.Add(btn, 0, wxALL, 4) buttons.Add(btn, 0, wx.ALL, 4)
buttons.Add(cb1, 0, wxALIGN_CENTER_VERTICAL|wxLEFT|wxRIGHT, 6) buttons.Add(cb1, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 6)
buttons.Add(cb2, 0, wxALIGN_CENTER_VERTICAL|wxLEFT, 6) buttons.Add(cb2, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT, 6)
buttons.Add(cb3, 0, wxALIGN_CENTER_VERTICAL|wxLEFT, 6) buttons.Add(cb3, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT, 6)
buttons.Add(cb4, 0, wxALIGN_CENTER_VERTICAL|wxLEFT, 6) buttons.Add(cb4, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT, 6)
sizer = wxBoxSizer(wxVERTICAL) sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.keysink, 0, wxGROW) sizer.Add(self.keysink, 0, wx.GROW)
sizer.Add(buttons) sizer.Add(buttons)
sizer.Add(self.keylog, 1, wxGROW) sizer.Add(self.keylog, 1, wx.GROW)
self.SetSizer(sizer) self.SetSizer(sizer)
@@ -331,7 +338,7 @@ def runTest(frame, nb, log):
overview = """<html><body> overview = """<html><body>
<h2><center>wxKeyEvents</center></h2> <h2><center>wxKeyEvents</center></h2>
This demo simply lets catches all key events and prints info about them. This demo simply catches all key events and prints info about them.
It is meant to be used as a compatibility test for cross platform work. It is meant to be used as a compatibility test for cross platform work.
</body></html> </body></html>

View File

@@ -1,32 +1,36 @@
# 11/19/2003 - Jeff Grimmett (grimmtooth@softhome.net)
from wxPython.wx import * #
from wxPython.gizmos import * # o Updated for wx namespace
#
import time import time
import wx
import wx.gizmos as gizmos
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.log = log self.log = log
led = wxLEDNumberCtrl(self, -1, (25,25), (280, 50)) led = gizmos.LEDNumberCtrl(self, -1, (25,25), (280, 50))
led.SetValue("01234") led.SetValue("01234")
led = wxLEDNumberCtrl(self, -1, (25,100), (280, 50)) led = gizmos.LEDNumberCtrl(self, -1, (25,100), (280, 50))
led.SetValue("56789") led.SetValue("56789")
led.SetAlignment(wxLED_ALIGN_RIGHT) led.SetAlignment(gizmos.LED_ALIGN_RIGHT)
led.SetDrawFaded(False) led.SetDrawFaded(False)
led = wxLEDNumberCtrl(self, -1, (25,175), (280, 50), led = gizmos.LEDNumberCtrl(self, -1, (25,175), (280, 50),
wxLED_ALIGN_CENTER)# | wxLED_DRAW_FADED) gizmos.LED_ALIGN_CENTER)# | gizmos.LED_DRAW_FADED)
self.clock = led self.clock = led
self.OnTimer(None) self.OnTimer(None)
self.timer = wxTimer(self) self.timer = wx.Timer(self)
self.timer.Start(1000) self.timer.Start(1000)
EVT_TIMER(self, -1, self.OnTimer) self.Bind(wx.EVT_TIMER, self.OnTimer)
def OnTimer(self, evt): def OnTimer(self, evt):
@@ -45,6 +49,62 @@ def runTest(frame, nb, log):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
overview = """\ overview = """\
<html>
<body>
<font size=-1>The following was gleaned as best I could from the wxWindows
source, which was a bit reluctant to reveal its secrets. My appologies if
I missed anything - jmg</font>
<p>
<code><b>wxLEDNumberCtrl</b>( parent, id=-1, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=LED_ALIGN_LEFT | LED_DRAW_FADED)</code>
<p>This is a control that simulates an LED clock display. It only accepts
numeric input.
<p><b>Styles</b>
<p><dl>
<dt><b>LED_ALIGN_LEFT</b>
<dd>Align to the left.
<dt><b>LED_ALIGN_RIGHT</b>
<dd>Align to the right.
<dt><b>LED_ALIGN_CENTER</b>
<dd>Center on display.
<dt><b>LED_DRAW_FADED</b>
<dd>Not implemented.
</dl>
<p><b>Methods</b> (and best guesses at what they do)
<p><dl>
<dt><b>GetAlignment()</b>
<dd>Returns the alignment attribute for the control.
<dt><b>GetDrawFaded()</b>
<dd>Returns the DrawFaded attribute for the control.
<dt><b>GetValue()</b>
<dd>Returns the current value of the control.
<dt><b>SetAlignment(alignment)</b>
<dd>Set the alignment attribute for the control.
<dt><b>SetDrawFaded(value)</b>
<dd>Set the DrawFaded attribute for the control.
<dt><b>SetValue(number)</b>
<dd>Set the value for the control. Only numeric values are accepted.
</dl>
<p>Additionally, several methods of wx.Window are available as well.
</body>
</html>
""" """

View File

@@ -1,95 +1,99 @@
# 11/19/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import * import wx
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class TestLayoutConstraints(wxPanel): class TestLayoutConstraints(wx.Panel):
def __init__(self, parent): def __init__(self, parent):
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
self.SetAutoLayout(True) self.SetAutoLayout(True)
EVT_BUTTON(self, 100, self.OnButton) self.Bind(wx.EVT_BUTTON, self.OnButton, id=100)
self.SetBackgroundColour(wxNamedColour("MEDIUM ORCHID")) self.SetBackgroundColour(wx.NamedColour("MEDIUM ORCHID"))
self.panelA = wxWindow(self, -1, wxDefaultPosition, wxDefaultSize, self.panelA = wx.Window(self, -1, style=wx.SIMPLE_BORDER)
wxSIMPLE_BORDER) self.panelA.SetBackgroundColour(wx.BLUE)
self.panelA.SetBackgroundColour(wxBLUE)
txt = wxStaticText(self.panelA, -1, txt = wx.StaticText(
self.panelA, -1,
"Resize the window and see\n" "Resize the window and see\n"
"what happens... Notice that\n" "what happens... Notice that\n"
"there is no OnSize handler.", "there is no OnSize handler.",
wxPoint(5,5), wxSize(-1, 50)) (5,5), (-1, 50)
txt.SetBackgroundColour(wxBLUE) )
txt.SetForegroundColour(wxWHITE)
lc = wxLayoutConstraints() txt.SetBackgroundColour(wx.BLUE)
lc.top.SameAs(self, wxTop, 10) txt.SetForegroundColour(wx.WHITE)
lc.left.SameAs(self, wxLeft, 10)
lc.bottom.SameAs(self, wxBottom, 10) lc = wx.LayoutConstraints()
lc.right.PercentOf(self, wxRight, 50) lc.top.SameAs(self, wx.Top, 10)
lc.left.SameAs(self, wx.Left, 10)
lc.bottom.SameAs(self, wx.Bottom, 10)
lc.right.PercentOf(self, wx.Right, 50)
self.panelA.SetConstraints(lc) self.panelA.SetConstraints(lc)
self.panelB = wxWindow(self, -1, wxDefaultPosition, wxDefaultSize, self.panelB = wx.Window(self, -1, style=wx.SIMPLE_BORDER)
wxSIMPLE_BORDER) self.panelB.SetBackgroundColour(wx.RED)
self.panelB.SetBackgroundColour(wxRED) lc = wx.LayoutConstraints()
lc = wxLayoutConstraints() lc.top.SameAs(self, wx.Top, 10)
lc.top.SameAs(self, wxTop, 10) lc.right.SameAs(self, wx.Right, 10)
lc.right.SameAs(self, wxRight, 10) lc.bottom.PercentOf(self, wx.Bottom, 30)
lc.bottom.PercentOf(self, wxBottom, 30)
lc.left.RightOf(self.panelA, 10) lc.left.RightOf(self.panelA, 10)
self.panelB.SetConstraints(lc) self.panelB.SetConstraints(lc)
self.panelC = wxWindow(self, -1, wxDefaultPosition, wxDefaultSize, self.panelC = wx.Window(self, -1, style=wx.SIMPLE_BORDER)
wxSIMPLE_BORDER) self.panelC.SetBackgroundColour(wx.WHITE)
self.panelC.SetBackgroundColour(wxWHITE) lc = wx.LayoutConstraints()
lc = wxLayoutConstraints()
lc.top.Below(self.panelB, 10) lc.top.Below(self.panelB, 10)
lc.right.SameAs(self, wxRight, 10) lc.right.SameAs(self, wx.Right, 10)
lc.bottom.SameAs(self, wxBottom, 10) lc.bottom.SameAs(self, wx.Bottom, 10)
lc.left.RightOf(self.panelA, 10) lc.left.RightOf(self.panelA, 10)
self.panelC.SetConstraints(lc) self.panelC.SetConstraints(lc)
b = wxButton(self.panelA, 100, ' Panel A ') b = wx.Button(self.panelA, 100, ' Panel A ')
lc = wxLayoutConstraints() lc = wx.LayoutConstraints()
lc.centreX.SameAs (self.panelA, wxCentreX) lc.centreX.SameAs (self.panelA, wx.CentreX)
lc.centreY.SameAs (self.panelA, wxCentreY) lc.centreY.SameAs (self.panelA, wx.CentreY)
lc.height.AsIs () lc.height.AsIs ()
lc.width.PercentOf (self.panelA, wxWidth, 50) lc.width.PercentOf (self.panelA, wx.Width, 50)
b.SetConstraints(lc); b.SetConstraints(lc);
b = wxButton(self.panelB, 100, ' Panel B ') b = wx.Button(self.panelB, 100, ' Panel B ')
lc = wxLayoutConstraints() lc = wx.LayoutConstraints()
lc.top.SameAs (self.panelB, wxTop, 2) lc.top.SameAs (self.panelB, wx.Top, 2)
lc.right.SameAs (self.panelB, wxRight, 4) lc.right.SameAs (self.panelB, wx.Right, 4)
lc.height.AsIs () lc.height.AsIs ()
lc.width.AsIs () lc.width.AsIs ()
b.SetConstraints(lc); b.SetConstraints(lc);
self.panelD = wxWindow(self.panelC, -1, wxDefaultPosition, wxDefaultSize, self.panelD = wx.Window(self.panelC, -1, style=wx.SIMPLE_BORDER)
wxSIMPLE_BORDER) self.panelD.SetBackgroundColour(wx.GREEN)
self.panelD.SetBackgroundColour(wxGREEN) wx.StaticText(
wxStaticText(self.panelD, -1, "Panel D", wxPoint(4, 4)).SetBackgroundColour(wxGREEN) self.panelD, -1, "Panel D", (4, 4)
).SetBackgroundColour(wx.GREEN)
b = wxButton(self.panelC, 100, ' Panel C ') b = wx.Button(self.panelC, 100, ' Panel C ')
lc = wxLayoutConstraints() lc = wx.LayoutConstraints()
lc.top.Below (self.panelD) lc.top.Below (self.panelD)
lc.left.RightOf (self.panelD) lc.left.RightOf (self.panelD)
lc.height.AsIs () lc.height.AsIs ()
lc.width.AsIs () lc.width.AsIs ()
b.SetConstraints(lc); b.SetConstraints(lc);
lc = wxLayoutConstraints() lc = wx.LayoutConstraints()
lc.bottom.PercentOf (self.panelC, wxHeight, 50) lc.bottom.PercentOf (self.panelC, wx.Height, 50)
lc.right.PercentOf (self.panelC, wxWidth, 50) lc.right.PercentOf (self.panelC, wx.Width, 50)
lc.height.SameAs (b, wxHeight) lc.height.SameAs (b, wx.Height)
lc.width.SameAs (b, wxWidth) lc.width.SameAs (b, wx.Width)
self.panelD.SetConstraints(lc); self.panelD.SetConstraints(lc);
def OnButton(self, event): def OnButton(self, event):
wxBell() wx.Bell()
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
@@ -102,43 +106,33 @@ def runTest(frame, nb, log):
overview = """\
<html><body>
overview = """\<html><body>
Objects of this class can be associated with a window to define its Objects of this class can be associated with a window to define its
layout constraints, with respect to siblings or its parent. layout constraints, with respect to siblings or its parent.
The class consists of the following eight constraints of class <p>The class consists of the following eight constraints of class
wxIndividualLayoutConstraint, some or all of which should be accessed wxIndividualLayoutConstraint, some or all of which should be accessed
directly to set the appropriate constraints. directly to set the appropriate constraints.
left: represents the left hand edge of the window <p><ul>
<li>left: represents the left hand edge of the window
right: represents the right hand edge of the window <li>right: represents the right hand edge of the window
top: represents the top edge of the window <li>top: represents the top edge of the window
bottom: represents the bottom edge of the window <li>bottom: represents the bottom edge of the window
width: represents the width of the window <li>width: represents the width of the window
height: represents the height of the window <li>height: represents the height of the window
centreX: represents the horizontal centre point of the window <li>centreX: represents the horizontal centre point of the window
centreY: represents the vertical centre point of the window <li>centreY: represents the vertical centre point of the window
</ul>
Most constraints are initially set to have the relationship <p>Most constraints are initially set to have the relationship
wxUnconstrained, which means that their values should be calculated by wxUnconstrained, which means that their values should be calculated by
looking at known constraints. The exceptions are width and height, looking at known constraints. The exceptions are width and height,
which are set to wxAsIs to ensure that if the user does not specify a which are set to wxAsIs to ensure that if the user does not specify a

View File

@@ -1,49 +1,64 @@
# 11/20/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import * import wx
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class wxFindPrefixListBox(wxListBox): # This listbox subclass lets you type the starting letters of what you want to
def __init__(self, parent, id, pos=wxDefaultPosition, size=wxDefaultSize, # select, and scrolls the list to the match if it is found.
choices=[], style=0, validator=wxDefaultValidator): class FindPrefixListBox(wx.ListBox):
wxListBox.__init__(self, parent, id, pos, size, choices, style, validator) def __init__(self, parent, id, pos=wx.DefaultPosition, size=wx.DefaultSize,
choices=[], style=0, validator=wx.DefaultValidator):
wx.ListBox.__init__(self, parent, id, pos, size, choices, style, validator)
self.typedText = '' self.typedText = ''
self.log = parent.log self.log = parent.log
EVT_KEY_DOWN(self, self.OnKey) self.Bind(wx.EVT_KEY_DOWN, self.OnKey)
def FindPrefix(self, prefix): def FindPrefix(self, prefix):
self.log.WriteText('Looking for prefix: %s\n' % prefix) self.log.WriteText('Looking for prefix: %s\n' % prefix)
if prefix: if prefix:
prefix = prefix.lower() prefix = prefix.lower()
length = len(prefix) length = len(prefix)
for x in range(self.Number()):
# Changed in 2.5 because ListBox.Number() is no longer supported.
# ListBox.GetCount() is now the appropriate way to go.
for x in range(self.GetCount()):
text = self.GetString(x) text = self.GetString(x)
text = text.lower() text = text.lower()
if text[:length] == prefix: if text[:length] == prefix:
self.log.WriteText('Prefix %s is found.\n' % prefix) self.log.WriteText('Prefix %s is found.\n' % prefix)
return x return x
self.log.WriteText('Prefix %s is not found.\n' % prefix) self.log.WriteText('Prefix %s is not found.\n' % prefix)
return -1 return -1
def OnKey(self, evt): def OnKey(self, evt):
key = evt.GetKeyCode() key = evt.GetKeyCode()
if key >= 32 and key <= 127: if key >= 32 and key <= 127:
self.typedText = self.typedText + chr(key) self.typedText = self.typedText + chr(key)
item = self.FindPrefix(self.typedText) item = self.FindPrefix(self.typedText)
if item != -1: if item != -1:
self.SetSelection(item) self.SetSelection(item)
elif key == WXK_BACK: # backspace removes one character and backs up elif key == wx.WXK_BACK: # backspace removes one character and backs up
self.typedText = self.typedText[:-1] self.typedText = self.typedText[:-1]
if not self.typedText: if not self.typedText:
self.SetSelection(0) self.SetSelection(0)
else: else:
item = self.FindPrefix(self.typedText) item = self.FindPrefix(self.typedText)
if item != -1: if item != -1:
self.SetSelection(item) self.SetSelection(item)
else: else:
self.typedText = '' self.typedText = ''
evt.Skip() evt.Skip()
@@ -54,44 +69,38 @@ class wxFindPrefixListBox(wxListBox):
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
class TestListBox(wxPanel): class TestListBox(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
self.log = log self.log = log
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
sampleList = ['zero', 'one', 'two', 'three', 'four', 'five', sampleList = ['zero', 'one', 'two', 'three', 'four', 'five',
'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven',
'twelve', 'thirteen', 'fourteen'] 'twelve', 'thirteen', 'fourteen']
wxStaticText(self, -1, "This example uses the wxListBox control.", wx.StaticText(self, -1, "This example uses the wxListBox control.", (45, 10))
wxPoint(45, 10)) wx.StaticText(self, -1, "Select one:", (15, 50), (65, 18))
self.lb1 = wx.ListBox(self, 60, (80, 50), (80, 120), sampleList, wx.LB_SINGLE)
wxStaticText(self, -1, "Select one:", wxPoint(15, 50), wxSize(65, 18)) self.Bind(wx.EVT_LISTBOX, self.EvtListBox, self.lb1)
self.lb1 = wxListBox(self, 60, wxPoint(80, 50), wxSize(80, 120), self.Bind(wx.EVT_LISTBOX_DCLICK, self.EvtListBoxDClick, self.lb1)
sampleList, wxLB_SINGLE) self.lb1.Bind(wx.EVT_RIGHT_UP, self.EvtRightButton)
EVT_LISTBOX(self, 60, self.EvtListBox)
EVT_LISTBOX_DCLICK(self, 60, self.EvtListBoxDClick)
EVT_RIGHT_UP(self.lb1, self.EvtRightButton)
self.lb1.SetSelection(3) self.lb1.SetSelection(3)
self.lb1.Append("with data", "This one has data"); self.lb1.Append("with data", "This one has data");
self.lb1.SetClientData(2, "This one has data"); self.lb1.SetClientData(2, "This one has data");
wxStaticText(self, -1, "Select many:", wxPoint(200, 50), wxSize(65, 18)) wx.StaticText(self, -1, "Select many:", (200, 50), (65, 18))
self.lb2 = wxListBox(self, 70, wxPoint(280, 50), wxSize(80, 120), self.lb2 = wx.ListBox(self, 70, (280, 50), (80, 120), sampleList, wx.LB_EXTENDED)
sampleList, wxLB_EXTENDED) self.Bind(wx.EVT_LISTBOX, self.EvtMultiListBox, self.lb2)
EVT_LISTBOX(self, 70, self.EvtMultiListBox) self.lb2.Bind(wx.EVT_RIGHT_UP, self.EvtRightButton)
EVT_RIGHT_UP(self.lb2, self.EvtRightButton)
self.lb2.SetSelection(0) self.lb2.SetSelection(0)
sampleList = sampleList + ['test a', 'test aa', 'test aab', sampleList = sampleList + ['test a', 'test aa', 'test aab',
'test ab', 'test abc', 'test abcc', 'test ab', 'test abc', 'test abcc',
'test abcd' ] 'test abcd' ]
sampleList.sort() sampleList.sort()
wxStaticText(self, -1, "Find Prefix:", wxPoint(15, 250)) wx.StaticText(self, -1, "Find Prefix:", (15, 250))
fp = wxFindPrefixListBox(self, -1, wxPoint(80, 250), wxSize(80, 120), fp = FindPrefixListBox(self, -1, (80, 250), (80, 120), sampleList, wx.LB_SINGLE)
sampleList, wxLB_SINGLE)
fp.SetSelection(0) fp.SetSelection(0)
@@ -101,6 +110,7 @@ class TestListBox(wxPanel):
lb = event.GetEventObject() lb = event.GetEventObject()
data = lb.GetClientData(lb.GetSelection()) data = lb.GetClientData(lb.GetSelection())
if data is not None: if data is not None:
self.log.WriteText('\tdata: %s\n' % data) self.log.WriteText('\tdata: %s\n' % data)
@@ -114,9 +124,11 @@ class TestListBox(wxPanel):
def EvtRightButton(self, event): def EvtRightButton(self, event):
self.log.WriteText('EvtRightButton: %s\n' % event.GetPosition()) self.log.WriteText('EvtRightButton: %s\n' % event.GetPosition())
if event.GetEventObject().GetId() == 70: if event.GetEventObject().GetId() == 70:
selections = list(self.lb2.GetSelections()) selections = list(self.lb2.GetSelections())
selections.reverse() selections.reverse()
for index in selections: for index in selections:
self.lb2.Delete(index) self.lb2.Delete(index)
@@ -132,9 +144,6 @@ def runTest(frame, nb, log):
overview = """<html><body> overview = """<html><body>
A listbox is used to select one or more of a list of A listbox is used to select one or more of a list of
strings. The strings are displayed in a scrolling box, with the strings. The strings are displayed in a scrolling box, with the

View File

@@ -9,9 +9,21 @@
# Copyright: (c) 1998 by Total Control Software # Copyright: (c) 1998 by Total Control Software
# Licence: wxWindows license # Licence: wxWindows license
#---------------------------------------------------------------------------- #----------------------------------------------------------------------------
#
# 11/20/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
# 11/29/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o listctrl mixin needs wx renamer.
# o wx.ListItem.GetText() returns a wxString pointer, not the text.
#
from wxPython.wx import * import wx
from wxPython.lib.mixins.listctrl import wxColumnSorterMixin, wxListCtrlAutoWidthMixin import wx.lib.mixins.listctrl as listmix
import images
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
@@ -72,84 +84,85 @@ musicdata = {
54: ("David Lanz", "Leaves on the Seine", "New Age"), 54: ("David Lanz", "Leaves on the Seine", "New Age"),
} }
import images #---------------------------------------------------------------------------
class TestListCtrl(wx.ListCtrl, listmix.wxListCtrlAutoWidthMixin):
def __init__(self, parent, ID, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=0):
wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
listmix.wxListCtrlAutoWidthMixin.__init__(self)
class TestListCtrl(wxListCtrl, wxListCtrlAutoWidthMixin): class TestListCtrlPanel(wx.Panel, listmix.wxColumnSorterMixin):
def __init__(self, parent, ID, pos=wxDefaultPosition,
size=wxDefaultSize, style=0):
wxListCtrl.__init__(self, parent, ID, pos, size, style)
wxListCtrlAutoWidthMixin.__init__(self)
class TestListCtrlPanel(wxPanel, wxColumnSorterMixin):
def __init__(self, parent, log): def __init__(self, parent, log):
wxPanel.__init__(self, parent, -1, style=wxWANTS_CHARS) wx.Panel.__init__(self, parent, -1, style=wx.WANTS_CHARS)
self.log = log self.log = log
tID = wxNewId() tID = wx.NewId()
self.il = wxImageList(16, 16) self.il = wx.ImageList(16, 16)
self.idx1 = self.il.Add(images.getSmilesBitmap()) self.idx1 = self.il.Add(images.getSmilesBitmap())
self.sm_up = self.il.Add(images.getSmallUpArrowBitmap()) self.sm_up = self.il.Add(images.getSmallUpArrowBitmap())
self.sm_dn = self.il.Add(images.getSmallDnArrowBitmap()) self.sm_dn = self.il.Add(images.getSmallDnArrowBitmap())
self.list = TestListCtrl(self, tID, self.list = TestListCtrl(self, tID,
style=wxLC_REPORT | wxSUNKEN_BORDER style=wx.LC_REPORT
| wxLC_EDIT_LABELS | wx.SUNKEN_BORDER
| wx.LC_EDIT_LABELS
#| wxLC_NO_HEADER #| wxLC_NO_HEADER
#| wxLC_VRULES | wxLC_HRULES #| wxLC_VRULES | wxLC_HRULES
) )
self.list.SetImageList(self.il, wxIMAGE_LIST_SMALL)
self.list.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
self.PopulateList() self.PopulateList()
# Now that the list exists we can init the other base class, # Now that the list exists we can init the other base class,
# see wxPython/lib/mixins/listctrl.py # see wxPython/lib/mixins/listctrl.py
self.itemDataMap = musicdata self.itemDataMap = musicdata
wxColumnSorterMixin.__init__(self, 3) listmix.wxColumnSorterMixin.__init__(self, 3)
#self.SortListItems(0, True) #self.SortListItems(0, True)
EVT_SIZE(self, self.OnSize) self.Bind(wx.EVT_SIZE, self.OnSize)
EVT_LIST_ITEM_SELECTED(self, tID, self.OnItemSelected)
EVT_LIST_ITEM_DESELECTED(self, tID, self.OnItemDeselected)
EVT_LIST_ITEM_ACTIVATED(self, tID, self.OnItemActivated)
EVT_LIST_DELETE_ITEM(self, tID, self.OnItemDelete)
EVT_LIST_COL_CLICK(self, tID, self.OnColClick)
EVT_LIST_COL_RIGHT_CLICK(self, tID, self.OnColRightClick)
EVT_LIST_COL_BEGIN_DRAG(self, tID, self.OnColBeginDrag)
EVT_LIST_COL_DRAGGING(self, tID, self.OnColDragging)
EVT_LIST_COL_END_DRAG(self, tID, self.OnColEndDrag)
EVT_LIST_BEGIN_LABEL_EDIT(self, tID, self.OnBeginEdit)
EVT_LEFT_DCLICK(self.list, self.OnDoubleClick) self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected, self.list)
EVT_RIGHT_DOWN(self.list, self.OnRightDown) self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnItemDeselected, self.list)
self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated, self.list)
self.Bind(wx.EVT_LIST_DELETE_ITEM, self.OnItemDelete, self.list)
self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick, self.list)
self.Bind(wx.EVT_LIST_COL_RIGHT_CLICK, self.OnColRightClick, self.list)
self.Bind(wx.EVT_LIST_COL_BEGIN_DRAG, self.OnColBeginDrag, self.list)
self.Bind(wx.EVT_LIST_COL_DRAGGING, self.OnColDragging, self.list)
self.Bind(wx.EVT_LIST_COL_END_DRAG, self.OnColEndDrag, self.list)
self.Bind(wx.EVT_LIST_BEGIN_LABEL_EDIT, self.OnBeginEdit, self.list)
self.list.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)
self.list.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown)
# for wxMSW # for wxMSW
EVT_COMMAND_RIGHT_CLICK(self.list, tID, self.OnRightClick) self.list.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightClick)
# for wxGTK # for wxGTK
EVT_RIGHT_UP(self.list, self.OnRightClick) self.list.Bind(wx.EVT_RIGHT_UP, self.OnRightClick)
def PopulateList(self): def PopulateList(self):
if 0: if 0:
# for normal, simple columns, you can add them like this: # for normal, simple columns, you can add them like this:
self.list.InsertColumn(0, "Artist") self.list.InsertColumn(0, "Artist")
self.list.InsertColumn(1, "Title", wxLIST_FORMAT_RIGHT) self.list.InsertColumn(1, "Title", wx.LIST_FORMAT_RIGHT)
self.list.InsertColumn(2, "Genre") self.list.InsertColumn(2, "Genre")
else: else:
# but since we want images on the column header we have to do it the hard way: # but since we want images on the column header we have to do it the hard way:
info = wxListItem() info = wx.ListItem()
info.m_mask = wxLIST_MASK_TEXT | wxLIST_MASK_IMAGE | wxLIST_MASK_FORMAT info.m_mask = wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT
info.m_image = -1 info.m_image = -1
info.m_format = 0 info.m_format = 0
info.m_text = "Artist" info.m_text = "Artist"
self.list.InsertColumnInfo(0, info) self.list.InsertColumnInfo(0, info)
info.m_format = wxLIST_FORMAT_RIGHT info.m_format = wx.LIST_FORMAT_RIGHT
info.m_text = "Title" info.m_text = "Title"
self.list.InsertColumnInfo(1, info) self.list.InsertColumnInfo(1, info)
@@ -165,19 +178,19 @@ class TestListCtrlPanel(wxPanel, wxColumnSorterMixin):
self.list.SetStringItem(x, 2, data[2]) self.list.SetStringItem(x, 2, data[2])
self.list.SetItemData(x, key) self.list.SetItemData(x, key)
self.list.SetColumnWidth(0, wxLIST_AUTOSIZE) self.list.SetColumnWidth(0, wx.LIST_AUTOSIZE)
self.list.SetColumnWidth(1, wxLIST_AUTOSIZE) self.list.SetColumnWidth(1, wx.LIST_AUTOSIZE)
self.list.SetColumnWidth(2, 100) self.list.SetColumnWidth(2, 100)
# show how to select an item # show how to select an item
self.list.SetItemState(5, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED) self.list.SetItemState(5, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED)
# show how to change the colour of a couple items # show how to change the colour of a couple items
item = self.list.GetItem(1) item = self.list.GetItem(1)
item.SetTextColour(wxBLUE) item.SetTextColour(wx.BLUE)
self.list.SetItem(item) self.list.SetItem(item)
item = self.list.GetItem(4) item = self.list.GetItem(4)
item.SetTextColour(wxRED) item.SetTextColour(wx.RED)
self.list.SetItem(item) self.list.SetItem(item)
self.currentItem = 0 self.currentItem = 0
@@ -197,8 +210,10 @@ class TestListCtrlPanel(wxPanel, wxColumnSorterMixin):
self.y = event.GetY() self.y = event.GetY()
self.log.WriteText("x, y = %s\n" % str((self.x, self.y))) self.log.WriteText("x, y = %s\n" % str((self.x, self.y)))
item, flags = self.list.HitTest((self.x, self.y)) item, flags = self.list.HitTest((self.x, self.y))
if flags & wxLIST_HITTEST_ONITEM:
if flags & wx.LIST_HITTEST_ONITEM:
self.list.Select(item) self.list.Select(item)
event.Skip() event.Skip()
@@ -215,11 +230,13 @@ class TestListCtrlPanel(wxPanel, wxColumnSorterMixin):
self.list.GetItemText(self.currentItem), self.list.GetItemText(self.currentItem),
self.getColumnText(self.currentItem, 1), self.getColumnText(self.currentItem, 1),
self.getColumnText(self.currentItem, 2))) self.getColumnText(self.currentItem, 2)))
if self.currentItem == 10: if self.currentItem == 10:
self.log.WriteText("OnItemSelected: Veto'd selection\n") self.log.WriteText("OnItemSelected: Veto'd selection\n")
#event.Veto() # doesn't work #event.Veto() # doesn't work
# this does # this does
self.list.SetItemState(10, 0, wxLIST_STATE_SELECTED) self.list.SetItemState(10, 0, wx.LIST_STATE_SELECTED)
event.Skip() event.Skip()
@@ -229,7 +246,7 @@ class TestListCtrlPanel(wxPanel, wxColumnSorterMixin):
# Show how to reselect something we don't want deselected # Show how to reselect something we don't want deselected
if evt.m_itemIndex == 11: if evt.m_itemIndex == 11:
wxCallAfter(self.list.SetItemState, 11, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED) wx.CallAfter(self.list.SetItemState, 11, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED)
def OnItemActivated(self, event): def OnItemActivated(self, event):
@@ -275,21 +292,22 @@ class TestListCtrlPanel(wxPanel, wxColumnSorterMixin):
# only do this part the first time so the events are only bound once # only do this part the first time so the events are only bound once
if not hasattr(self, "popupID1"): if not hasattr(self, "popupID1"):
self.popupID1 = wxNewId() self.popupID1 = wx.NewId()
self.popupID2 = wxNewId() self.popupID2 = wx.NewId()
self.popupID3 = wxNewId() self.popupID3 = wx.NewId()
self.popupID4 = wxNewId() self.popupID4 = wx.NewId()
self.popupID5 = wxNewId() self.popupID5 = wx.NewId()
self.popupID6 = wxNewId() self.popupID6 = wx.NewId()
EVT_MENU(self, self.popupID1, self.OnPopupOne)
EVT_MENU(self, self.popupID2, self.OnPopupTwo) self.Bind(wx.EVT_MENU, self.OnPopupOne, id=self.popupID1)
EVT_MENU(self, self.popupID3, self.OnPopupThree) self.Bind(wx.EVT_MENU, self.OnPopupTwo, id=self.popupID2)
EVT_MENU(self, self.popupID4, self.OnPopupFour) self.Bind(wx.EVT_MENU, self.OnPopupThree, id=self.popupID3)
EVT_MENU(self, self.popupID5, self.OnPopupFive) self.Bind(wx.EVT_MENU, self.OnPopupFour, id=self.popupID4)
EVT_MENU(self, self.popupID6, self.OnPopupSix) self.Bind(wx.EVT_MENU, self.OnPopupFive, id=self.popupID5)
self.Bind(wx.EVT_MENU, self.OnPopupSix, id=self.popupID6)
# make a menu # make a menu
menu = wxMenu() menu = wx.Menu()
# add some items # add some items
menu.Append(self.popupID1, "FindItem tests") menu.Append(self.popupID1, "FindItem tests")
menu.Append(self.popupID2, "Iterate Selected") menu.Append(self.popupID2, "Iterate Selected")
@@ -300,7 +318,7 @@ class TestListCtrlPanel(wxPanel, wxColumnSorterMixin):
# Popup the menu. If an item is selected then its handler # Popup the menu. If an item is selected then its handler
# will be called before PopupMenu returns. # will be called before PopupMenu returns.
self.PopupMenu(menu, wxPoint(self.x, self.y)) self.PopupMenu(menu, (self.x, self.y))
menu.Destroy() menu.Destroy()
@@ -312,15 +330,15 @@ class TestListCtrlPanel(wxPanel, wxColumnSorterMixin):
def OnPopupTwo(self, event): def OnPopupTwo(self, event):
self.log.WriteText("Selected items:\n") self.log.WriteText("Selected items:\n")
index = self.list.GetFirstSelected() index = self.list.GetFirstSelected()
while index != -1: while index != -1:
self.log.WriteText(" %s: %s\n" % (self.list.GetItemText(index), self.getColumnText(index, 1))) self.log.WriteText(" %s: %s\n" % (self.list.GetItemText(index), self.getColumnText(index, 1)))
index = self.list.GetNextSelected(index) index = self.list.GetNextSelected(index)
def OnPopupThree(self, event): def OnPopupThree(self, event):
self.log.WriteText("Popup three\n") self.log.WriteText("Popup three\n")
self.list.ClearAll() self.list.ClearAll()
wxCallAfter(self.PopulateList) wx.CallAfter(self.PopulateList)
def OnPopupFour(self, event): def OnPopupFour(self, event):
self.list.DeleteAllItems() self.list.DeleteAllItems()
@@ -339,9 +357,6 @@ class TestListCtrlPanel(wxPanel, wxColumnSorterMixin):
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
def runTest(frame, nb, log): def runTest(frame, nb, log):
@@ -351,17 +366,138 @@ def runTest(frame, nb, log):
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
overview = """\ overview = """\
A list control presents lists in a number of formats: list view, report view, icon view and small icon view. Elements are numbered from zero. <html>
<body>
A list control presents lists in a number of formats: list view, report view,
icon view and small icon view. In any case, elements are numbered from zero.
For all these modes (but not for virtual list controls), the items are stored
in the control and must be added to it using InsertItem method.
<p>To intercept events from a list control, use the event table macros described in
<code>wxListEvent.</code>
<h3>Mix-ins</h3>
This example demonstrates how to use mixins. The following mixins are available.
<h4>ColumnSorterMixin</h4>
<code><b>ColumnSorterMixin(numColumns)</b></code>
<p>A mixin class that handles sorting of a wxListCtrl in REPORT mode when the column
header is clicked on.
<p>There are a few requirments needed in order for this to work genericly:
<p><ol>
<li>The combined class must have a <code>GetListCtrl</code> method that returns
the ListCtrl to be sorted, and the list control must exist at the time the
<code>ColumnSorterMixin.__init__()</code>method is called because it uses
<code>GetListCtrl</code>.
<li>Items in the list control must have a unique data value set with
<code>list.SetItemData</code>.
<li>The combined class must have an attribute named <code>itemDataMap</code>
that is a dictionary mapping the data values to a sequence of objects
representing the values in each column. These valuesare compared in
the column sorter to determine sort order.
</ol>
<p>Interesting methods to override are <code>GetColumnSorter</code>,
<code>GetSecondarySortValues</code>, and <code>GetSortImages</code>.
<h5>Methods</h5>
<dl>
<dt><code>SetColumnCount(newNumColumns)</code>
<dd>Informs the mixin as to the number of columns in the control. When it is
set, it also sets up an event handler for <code>EVT_LIST_COL_CLICK</code> events.
<dt><code>SortListItems(col=-1, ascending=1)</code>
<dd>Sort the list on demand. Can also be used to set the sort column and order.
<dt><code>GetColumnWidths()</code>
<dd>Returns a list of column widths. Can be used to help restore the current
view later.
<dt><code>GetSortImages()</code>
<dd>Returns a tuple of image list indexes the indexes in the image list for an
image to be put on the column header when sorting in descending order
<dt><code>GetColumnSorter()</code>
<dd>Returns a callable object to be used for comparing column values when sorting.
<dt><code>GetSecondarySortValues(col, key1, key2)</code>
<dd>Returns a tuple of 2 values to use for secondary sort values when the
items in the selected column match equal. The default just returns the
item data values.
</dl>
<h4>ListCtrlAutoWidthMixin</h4>
<code><b>wxListCtrlAutoWidthMixin()</b></code>
<p>A mix-in class that automatically resizes the last column to take up the
remaining width of the ListCtrl.
<p>This causes the ListCtrl to automatically take up the full width of the list,
without either a horizontal scroll bar (unless absolutely necessary) or empty
space to the right of the last column.
<p><b>NOTE:</b> This only works for report-style lists.
<p><b>WARNING:</b> If you override the <code>EVT_SIZE</code> event in your ListCtrl,
make sure you call event.Skip() to ensure that the mixin's _OnResize method is
called.
<p>This mix-in class was written by <a href='mailto:ewestra@wave.co.nz'>Erik Westra </a>
<h5>Methods</h5>
<dl>
<dt><code>resizeLastColumn(minWidth)</code>
<dd>Resize the last column appropriately. If the list's columns are too wide to
fit within the window, we use a horizontal scrollbar. Otherwise, we expand the
right-most column to take up the remaining free space in the list. This method is
called automatically when the ListCtrl is resized; you can also call it yourself
whenever you want the last column to be resized appropriately (eg, when adding,
removing or resizing columns). 'minWidth' is the preferred minimum width for
the last column.
</dl>
<h4>ListCtrlSelectionManagerMix</h4>
<code><b>ListCtrlSelectionManagerMix()</b></code>
<p>Mixin that defines a platform independent selection policy
<p>As selection single and multi-select list return the item index or a
list of item indexes respectively.
<h5>Methods</h5>
<dl>
<dt><code>getPopupMenu()</code>
<dd>Override to implement dynamic menus (create)
<dt><code>setPopupMenu(menu)</code>
<dd>Must be set for default behaviour.
<dt><code>afterPopupMenu()</code>
<dd>Override to implement dynamic menus (destroy).
<dt><code>getSelection()</code>
<dd>Returns the current selection (or selections as a Python list if extended
selection is enabled)
</body>
</html>
""" """
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run

View File

@@ -1,18 +1,29 @@
# 11/20/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
# 11/29/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o wx.ListItem.GetText() returns a wxString pointer, not the text.
#
from wxPython.wx import * import wx
import images import images
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestVirtualList(wxListCtrl): class TestVirtualList(wx.ListCtrl):
def __init__(self, parent, log): def __init__(self, parent, log):
wxListCtrl.__init__(self, parent, -1, wx.ListCtrl.__init__(
style=wxLC_REPORT|wxLC_VIRTUAL|wxLC_HRULES|wxLC_VRULES) self, parent, -1,
style=wx.LC_REPORT|wx.LC_VIRTUAL|wx.LC_HRULES|wx.LC_VRULES
)
self.log = log self.log = log
self.il = wxImageList(16, 16) self.il = wx.ImageList(16, 16)
self.idx1 = self.il.Add(images.getSmilesBitmap()) self.idx1 = self.il.Add(images.getSmilesBitmap())
self.SetImageList(self.il, wxIMAGE_LIST_SMALL) self.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
self.InsertColumn(0, "First") self.InsertColumn(0, "First")
@@ -24,15 +35,15 @@ class TestVirtualList(wxListCtrl):
self.SetItemCount(1000000) self.SetItemCount(1000000)
self.attr1 = wxListItemAttr() self.attr1 = wx.ListItemAttr()
self.attr1.SetBackgroundColour("yellow") self.attr1.SetBackgroundColour("yellow")
self.attr2 = wxListItemAttr() self.attr2 = wx.ListItemAttr()
self.attr2.SetBackgroundColour("light blue") self.attr2.SetBackgroundColour("light blue")
EVT_LIST_ITEM_SELECTED(self, self.GetId(), self.OnItemSelected) self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
EVT_LIST_ITEM_ACTIVATED(self, self.GetId(), self.OnItemActivated) self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated)
EVT_LIST_ITEM_DESELECTED(self, self.GetId(), self.OnItemDeselected) self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnItemDeselected)
def OnItemSelected(self, event): def OnItemSelected(self, event):
@@ -89,10 +100,12 @@ def runTest(frame, nb, log):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
overview = """\ overview = """\
This example demonstrates the ListCtrl's Virtual List features. A Virtual list
can contain any number of cells, but data is not loaded into the control itself.
It is loaded on demand via virtual methods <code>OnGetItemText(), OnGetItemImage()</code>,
and <code>OnGetItemAttr()</code>. This greatly reduces the amount of memory required
without limiting what can be done with the list control itself.
""" """

View File

@@ -1,11 +1,15 @@
# 11/22/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
# 11/29/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Bunches of imports that might need to go away for the final roll-out.
#
from wxPython.wx import * import sys
import ColorPanel import wx
import GridSimple
import wxListCtrl
import wxScrolledWindow
import images
colourList = [ "Aquamarine", "Black", "Blue", "Blue Violet", "Brown", "Cadet Blue", colourList = [ "Aquamarine", "Black", "Blue", "Blue Violet", "Brown", "Cadet Blue",
"Coral", "Cornflower Blue", "Cyan", "Dark Grey", "Dark Green", "Coral", "Cornflower Blue", "Cyan", "Dark Grey", "Dark Green",
@@ -26,10 +30,10 @@ colourList = [ "Aquamarine", "Black", "Blue", "Blue Violet", "Brown", "Cadet Blu
#---------------------------------------------------------------------------- #----------------------------------------------------------------------------
class TestLB(wxListbook): class TestLB(wx.Listbook):
def __init__(self, parent, id, log): def __init__(self, parent, id, log):
wxListbook.__init__(self, parent, id, style= wx.Listbook.__init__(self, parent, id, style=
wxLB_DEFAULT wx.LB_DEFAULT
#wxLB_TOP #wxLB_TOP
#wxLB_BOTTOM #wxLB_BOTTOM
#wxLB_LEFT #wxLB_LEFT
@@ -46,7 +50,6 @@ class TestLB(wxListbook):
il.Add(bmp) il.Add(bmp)
self.AssignImageList(il) self.AssignImageList(il)
# Now make a bunch of panels for the list book # Now make a bunch of panels for the list book
first = True first = True
imID = 0 imID = 0
@@ -71,12 +74,12 @@ class TestLB(wxListbook):
def makeColorPanel(self, color): def makeColorPanel(self, color):
p = wxPanel(self, -1) p = wx.Panel(self, -1)
win = ColorPanel.ColoredPanel(p, color) win = ColorPanel.ColoredPanel(p, color)
p.win = win p.win = win
def OnCPSize(evt, win=win): def OnCPSize(evt, win=win):
win.SetSize(evt.GetSize()) win.SetSize(evt.GetSize())
EVT_SIZE(p, OnCPSize) p.Bind(wx.EVT_SIZE, OnCPSize)
return p return p
@@ -103,8 +106,6 @@ def runTest(frame, nb, log):
#---------------------------------------------------------------------------- #----------------------------------------------------------------------------
overview = """\ overview = """\
<html><body> <html><body>
<h2>wxListbook</h2> <h2>wxListbook</h2>
@@ -122,6 +123,3 @@ if __name__ == '__main__':
run.main(['', os.path.basename(sys.argv[0])]) run.main(['', os.path.basename(sys.argv[0])])

View File

@@ -1,34 +1,39 @@
# 11/12/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import * import wx
import MDIDemo
import MDISashDemo
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, log): def __init__(self, parent, log):
self.log = log self.log = log
wxPanel.__init__(self, parent, -1) wx.Panel.__init__(self, parent, -1)
b1 = wxButton(self, -1, "MDI demo") b1 = wx.Button(self, -1, "MDI demo")
EVT_BUTTON(self, b1.GetId(), self.ShowMDIDemo) self.Bind(wx.EVT_BUTTON, self.ShowMDIDemo, b1)
b2 = wxButton(self, -1, "MDI with SashWindows demo") b2 = wx.Button(self, -1, "MDI with SashWindows demo")
EVT_BUTTON(self, b2.GetId(), self.ShowMDISashDemo) self.Bind(wx.EVT_BUTTON, self.ShowMDIDemo, b2)
box = wxBoxSizer(wxVERTICAL) box = wx.BoxSizer(wx.VERTICAL)
box.Add((20, 30)) box.Add((20, 30))
box.Add(b1, 0, wxALIGN_CENTER|wxALL, 15) box.Add(b1, 0, wx.ALIGN_CENTER|wx.ALL, 15)
box.Add(b2, 0, wxALIGN_CENTER|wxALL, 15) box.Add(b2, 0, wx.ALIGN_CENTER|wx.ALL, 15)
self.SetAutoLayout(True) self.SetAutoLayout(True)
self.SetSizer(box) self.SetSizer(box)
def ShowMDIDemo(self, evt): def ShowMDIDemo(self, evt):
import MDIDemo
frame = MDIDemo.MyParentFrame() frame = MDIDemo.MyParentFrame()
frame.Show() frame.Show()
def ShowMDISashDemo(self, evt): def ShowMDISashDemo(self, evt):
import MDISashDemo
frame = MDISashDemo.MyParentFrame() frame = MDISashDemo.MyParentFrame()
frame.Show() frame.Show()
@@ -48,15 +53,13 @@ overview = """<html><body>
<h2><center>Multiple Document Interface</center></h2> <h2><center>Multiple Document Interface</center></h2>
Although Microsoft has deprecated the MDI model, wxWindows still supports Although Microsoft has deprecated the MDI model, wxWindows still supports
it. Here are a couple samples of how to use it. it. Here are a couple samples of how to use it - one straightforward, the other
showing how the MDI interface can be integrated into a SashWindow interface.
</body></html> </body></html>
""" """
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run

View File

@@ -1,8 +1,17 @@
# 11/20/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
# 11/30/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Library must be updated for this to run.
#
import sys, os import os
from wxPython.wx import * import sys
from wxPython.lib.mvctree import *
import wx
import wx.lib.mvctree as tree
logger = None logger = None
def selchanging(evt): def selchanging(evt):
@@ -23,24 +32,26 @@ def delitem(evt):
logger.write("Delete\n") logger.write("Delete\n")
def runTest(frame, nb, log): def runTest(frame, nb, log):
#f = wxFrame(frame, -1, "wxMVCTree", wxPoint(0,0), wxSize(200,500)) #f = wx.Frame(frame, -1, "wxMVCTree", (0,0), (200,500))
global logger global logger
logger = log logger = log
p = wxMVCTree(nb, -1) p = tree.wxMVCTree(nb, -1)
#f = wxFrame(frame, -1, "wxMVCTree") #f = wx.Frame(frame, -1, "wxMVCTree")
#p = wxMVCTree(f, -1) #p = tree.wxMVCTree(f, -1)
p.SetAssumeChildren(True) p.SetAssumeChildren(True)
p.SetModel(LateFSTreeModel(os.path.normpath(os.getcwd() + os.sep +'..'))) p.SetModel(tree.LateFSTreeModel(os.path.normpath(os.getcwd() + os.sep +'..')))
#Uncomment this to enable live filename editing! #Uncomment this to enable live filename editing!
# p.AddEditor(FileEditor(p)) # p.AddEditor(FileEditor(p))
p.SetMultiSelect(True) p.SetMultiSelect(True)
EVT_MVCTREE_SEL_CHANGING(p, p.GetId(), selchanging) tree.EVT_MVCTREE_SEL_CHANGING(p, p.GetId(), selchanging)
EVT_MVCTREE_SEL_CHANGED(p, p.GetId(), selchanged) tree.EVT_MVCTREE_SEL_CHANGED(p, p.GetId(), selchanged)
EVT_MVCTREE_ITEM_EXPANDED(p, p.GetId(), expanded) tree.EVT_MVCTREE_ITEM_EXPANDED(p, p.GetId(), expanded)
EVT_MVCTREE_ITEM_COLLAPSED(p, p.GetId(), closed) tree.EVT_MVCTREE_ITEM_COLLAPSED(p, p.GetId(), closed)
EVT_MVCTREE_ADD_ITEM(p, p.GetId(), add) tree.EVT_MVCTREE_ADD_ITEM(p, p.GetId(), add)
EVT_MVCTREE_DELETE_ITEM(p, p.GetId(), delitem) tree.EVT_MVCTREE_DELETE_ITEM(p, p.GetId(), delitem)
EVT_MVCTREE_KEY_DOWN(p, p.GetId(), key) tree.EVT_MVCTREE_KEY_DOWN(p, p.GetId(), key)
return p return p
#frame.otherWin = f #frame.otherWin = f
@@ -48,8 +59,6 @@ def runTest(frame, nb, log):
#return None #return None
overview = """\ overview = """\
wxMVCTree is a control which handles hierarchical data. It is wxMVCTree is a control which handles hierarchical data. It is
@@ -71,9 +80,6 @@ demo, to avoid accidentally renaming files!
""" """
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os
import run import run

View File

@@ -1,37 +1,41 @@
# 11/20/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for wx namespace
#
from wxPython.wx import * import wx
#---------------------------------------------------------------------- #----------------------------------------------------------------------
logicList = [ logicList = [
('wxAND', wxAND), ('wx.AND', wx.AND),
('wxAND_INVERT', wxAND_INVERT), ('wx.AND_INVERT', wx.AND_INVERT),
('wxAND_REVERSE', wxAND_REVERSE), ('wx.AND_REVERSE', wx.AND_REVERSE),
('wxCLEAR', wxCLEAR), ('wx.CLEAR', wx.CLEAR),
('wxCOPY', wxCOPY), ('wx.COPY', wx.COPY),
('wxEQUIV', wxEQUIV), ('wx.EQUIV', wx.EQUIV),
('wxINVERT', wxINVERT), ('wx.INVERT', wx.INVERT),
('wxNAND', wxNAND), ('wx.NAND', wx.NAND),
# this one causes an assert on wxGTK, and doesn't seem to # this one causes an assert on wxGTK, and doesn't seem to
# do much on MSW anyway, so I'll just take it out.... # do much on MSW anyway, so I'll just take it out....
#('wxNOR', wxNOR), #('wxNOR', wxNOR),
('wxNO_OP', wxNO_OP), ('wx.NO_OP', wx.NO_OP),
('wxOR', wxOR), ('wx.OR', wx.OR),
('wxOR_INVERT', wxOR_INVERT), ('wx.OR_INVERT', wx.OR_INVERT),
('wxOR_REVERSE', wxOR_REVERSE), ('wx.OR_REVERSE', wx.OR_REVERSE),
('wxSET', wxSET), ('wx.SET', wx.SET),
('wxSRC_INVERT', wxSRC_INVERT), ('wx.SRC_INVERT', wx.SRC_INVERT),
('wxXOR', wxXOR), ('wx.XOR', wx.XOR),
] ]
import images import images
class TestMaskWindow(wxScrolledWindow): class TestMaskWindow(wx.ScrolledWindow):
def __init__(self, parent): def __init__(self, parent):
wxScrolledWindow.__init__(self, parent, -1) wx.ScrolledWindow.__init__(self, parent, -1)
self.SetBackgroundColour(wxColour(0,128,0)) self.SetBackgroundColour(wx.Colour(0,128,0))
# A reference bitmap that we won't mask # A reference bitmap that we won't mask
self.bmp_nomask = images.getTestStar2Bitmap() self.bmp_nomask = images.getTestStar2Bitmap()
@@ -40,8 +44,8 @@ class TestMaskWindow(wxScrolledWindow):
self.bmp_withmask = images.getTestStar2Bitmap() self.bmp_withmask = images.getTestStar2Bitmap()
# this mask comes from a monochrome bitmap # this mask comes from a monochrome bitmap
self.bmp_themask = wxBitmapFromImage(images.getTestMaskImage(), 1) self.bmp_themask = wx.BitmapFromImage(images.getTestMaskImage(), 1)
mask = wxMask(self.bmp_themask) mask = wx.Mask(self.bmp_themask)
# set the mask on our bitmap # set the mask on our bitmap
self.bmp_withmask.SetMask(mask) self.bmp_withmask.SetMask(mask)
@@ -49,21 +53,21 @@ class TestMaskWindow(wxScrolledWindow):
# Now we'll create a mask in a bit of an easier way, by picking a # Now we'll create a mask in a bit of an easier way, by picking a
# colour in the image that is to be the transparent colour. # colour in the image that is to be the transparent colour.
self.bmp_withcolourmask = images.getTestStar2Bitmap() self.bmp_withcolourmask = images.getTestStar2Bitmap()
mask = wxMaskColour(self.bmp_withcolourmask, wxWHITE) mask = wx.MaskColour(self.bmp_withcolourmask, wx.WHITE)
self.bmp_withcolourmask.SetMask(mask) self.bmp_withcolourmask.SetMask(mask)
self.SetScrollbars(20, 20, 700/20, 460/20) self.SetScrollbars(20, 20, 700/20, 460/20)
EVT_PAINT(self, self.OnPaint) self.Bind(wx.EVT_PAINT, self.OnPaint)
def OnPaint (self, e): def OnPaint (self, e):
dc = wxPaintDC(self) dc = wx.PaintDC(self)
self.PrepareDC(dc) self.PrepareDC(dc)
dc.SetTextForeground(wxWHITE) dc.SetTextForeground(wx.WHITE)
# make an interesting background... # make an interesting background...
dc.SetPen(wxMEDIUM_GREY_PEN) dc.SetPen(wx.MEDIUM_GREY_PEN)
for i in range(100): for i in range(100):
dc.DrawLine((0,i*10), (i*10,0)) dc.DrawLine((0,i*10), (i*10,0))
@@ -80,8 +84,9 @@ class TestMaskWindow(wxScrolledWindow):
cx,cy = self.bmp_themask.GetWidth(), self.bmp_themask.GetHeight() cx,cy = self.bmp_themask.GetWidth(), self.bmp_themask.GetHeight()
# draw array of assorted blit operations # draw array of assorted blit operations
mdc = wxMemoryDC() mdc = wx.MemoryDC()
i = 0 i = 0
for text, code in logicList: for text, code in logicList:
x,y = 120+150*(i%4), 20+100*(i/4) x,y = 120+150*(i%4), 20+100*(i/4)
dc.DrawText(text, (x, y-20)) dc.DrawText(text, (x, y-20))
@@ -92,11 +97,11 @@ class TestMaskWindow(wxScrolledWindow):
# On wxGTK there needs to be a panel under wxScrolledWindows if they are # On wxGTK there needs to be a panel under wxScrolledWindows if they are
# going to be in a wxNotebook... # going to be in a wxNotebook...
class TestPanel(wxPanel): class TestPanel(wx.Panel):
def __init__(self, parent, ID): def __init__(self, parent, ID):
wxPanel.__init__(self, parent, ID) wx.Panel.__init__(self, parent, ID)
self.win = TestMaskWindow(self) self.win = TestMaskWindow(self)
EVT_SIZE(self, self.OnSize) self.Bind(wx.EVT_SIZE, self.OnSize)
def OnSize(self, evt): def OnSize(self, evt):
self.win.SetSize(evt.GetSize()) self.win.SetSize(evt.GetSize())
@@ -111,8 +116,14 @@ def runTest(frame, nb, log):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
overview = """\ overview = """\
This class encapsulates a monochrome mask bitmap, where the masked area is black
and the unmasked area is white. When associated with a bitmap and drawn in a device
context, the unmasked area of the bitmap will be drawn, and the masked area will
not be drawn.
This example shows not only how to create a Mask, but the effects of the Device
Context (dc) <code>Blit()</code> method's logic codes.
""" """

View File

@@ -1,143 +1,145 @@
from wxPython.wx import * # 11/20/2003 - Jeff Grimmett (grimmtooth@softhome.net)
from wxPython.lib.maskednumctrl import wxMaskedNumCtrl, EVT_MASKEDNUM #
from wxPython.lib.maskednumctrl import __doc__ as overviewdoc # o Updated for wx namespace
from wxPython.lib.maskededit import wxMaskedTextCtrl #
import string, sys, traceback # 11/29/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o wx.lib.maskednumctrl needs hit up with the renamer and new binders
#
import string
import sys
import traceback
import wx
import wx.lib.maskednumctrl as mnum
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class TestPanel( wxPanel ): class TestPanel( wx.Panel ):
def __init__( self, parent, log ): def __init__( self, parent, log ):
wxPanel.__init__( self, parent, -1 ) wx.Panel.__init__( self, parent, -1 )
self.log = log self.log = log
panel = wxPanel( self, -1 ) panel = wx.Panel( self, -1 )
header = wxStaticText(panel, -1, """\ header = wx.StaticText(panel, -1, """\
This shows the various options for wxMaskedNumCtrl. This shows the various options for wxMaskedNumCtrl.
The controls at the top reconfigure the resulting control at the bottom. The controls at the top reconfigure the resulting control at the bottom.
""") """)
header.SetForegroundColour( "Blue" ) header.SetForegroundColour( "Blue" )
intlabel = wxStaticText( panel, -1, "Integer width:" ) intlabel = wx.StaticText( panel, -1, "Integer width:" )
self.integerwidth = wxMaskedNumCtrl( self.integerwidth = mnum.wxMaskedNumCtrl(
panel, value=10, panel, value=10, integerWidth=2, allowNegative=False
integerWidth=2, )
allowNegative=False)
fraclabel = wxStaticText( panel, -1, "Fraction width:" ) fraclabel = wx.StaticText( panel, -1, "Fraction width:" )
self.fractionwidth = wxMaskedNumCtrl( self.fractionwidth = mnum.wxMaskedNumCtrl(
panel, value=0, panel, value=0, integerWidth=2, allowNegative=False
integerWidth=2, )
allowNegative=False )
groupcharlabel = wxStaticText( panel,-1, "Grouping char:" ) groupcharlabel = wx.StaticText( panel,-1, "Grouping char:" )
self.groupchar = wxMaskedTextCtrl( panel, -1, self.groupchar = mnum.wxMaskedTextCtrl(
value=',', panel, -1, value=',', mask='&', excludeChars = '-()',
mask='&', formatcodes='F', emptyInvalid=True, validRequired=True
excludeChars = '-()', )
formatcodes='F',
emptyInvalid=True,
validRequired=True)
decimalcharlabel = wxStaticText( panel,-1, "Decimal char:" ) decimalcharlabel = wx.StaticText( panel,-1, "Decimal char:" )
self.decimalchar = wxMaskedTextCtrl( panel, -1, self.decimalchar = mnum.wxMaskedTextCtrl(
value='.', panel, -1, value='.', mask='&', excludeChars = '-()',
mask='&', formatcodes='F', emptyInvalid=True, validRequired=True
excludeChars = '-()', )
formatcodes='F',
emptyInvalid=True,
validRequired=True)
self.set_min = wxCheckBox( panel, -1, "Set minimum value:" ) self.set_min = wx.CheckBox( panel, -1, "Set minimum value:" )
# Create this wxMaskedNumCtrl using factory, to show how: # Create this MaskedNumCtrl using factory, to show how:
self.min = wxMaskedNumCtrl( panel, integerWidth=5, fractionWidth=2 ) self.min = mnum.wxMaskedNumCtrl( panel, integerWidth=5, fractionWidth=2 )
self.min.Enable( False ) self.min.Enable( False )
self.set_max = wxCheckBox( panel, -1, "Set maximum value:" ) self.set_max = wx.CheckBox( panel, -1, "Set maximum value:" )
self.max = wxMaskedNumCtrl( panel, integerWidth=5, fractionWidth=2 ) self.max = mnum.wxMaskedNumCtrl( panel, integerWidth=5, fractionWidth=2 )
self.max.Enable( False ) self.max.Enable( False )
self.limit_target = wxCheckBox( panel, -1, "Limit control" ) self.limit_target = wx.CheckBox( panel, -1, "Limit control" )
self.allow_none = wxCheckBox( panel, -1, "Allow empty control" ) self.allow_none = wx.CheckBox( panel, -1, "Allow empty control" )
self.group_digits = wxCheckBox( panel, -1, "Group digits" ) self.group_digits = wx.CheckBox( panel, -1, "Group digits" )
self.group_digits.SetValue( True ) self.group_digits.SetValue( True )
self.allow_negative = wxCheckBox( panel, -1, "Allow negative values" ) self.allow_negative = wx.CheckBox( panel, -1, "Allow negative values" )
self.allow_negative.SetValue( True ) self.allow_negative.SetValue( True )
self.use_parens = wxCheckBox( panel, -1, "Use parentheses" ) self.use_parens = wx.CheckBox( panel, -1, "Use parentheses" )
self.select_on_entry = wxCheckBox( panel, -1, "Select on entry" ) self.select_on_entry = wx.CheckBox( panel, -1, "Select on entry" )
self.select_on_entry.SetValue( True ) self.select_on_entry.SetValue( True )
label = wxStaticText( panel, -1, "Resulting numeric control:" ) label = wx.StaticText( panel, -1, "Resulting numeric control:" )
font = label.GetFont() font = label.GetFont()
font.SetWeight(wxBOLD) font.SetWeight(wx.BOLD)
label.SetFont(font) label.SetFont(font)
self.target_ctl = wxMaskedNumCtrl( panel, -1, name="target control" ) self.target_ctl = mnum.wxMaskedNumCtrl( panel, -1, name="target control" )
label_numselect = wxStaticText( panel, -1, """\ label_numselect = wx.StaticText( panel, -1, """\
Programmatically set the above Programmatically set the above
value entry ctrl:""") value entry ctrl:""")
self.numselect = wxComboBox(panel, -1, choices = [ '0', '111', '222.22', '-3', '54321.666666666', '-1353.978', self.numselect = wx.ComboBox(panel, -1, choices = [ '0', '111', '222.22', '-3', '54321.666666666', '-1353.978',
'1234567', '-1234567', '123456789', '-123456789.1', '1234567', '-1234567', '123456789', '-123456789.1',
'1234567890.', '-9876543210.9' ]) '1234567890.', '-9876543210.9' ])
grid1 = wxFlexGridSizer( 0, 4, 0, 0 ) grid1 = wx.FlexGridSizer( 0, 4, 0, 0 )
grid1.Add( intlabel, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5) grid1.Add( intlabel, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
grid1.Add( self.integerwidth, 0, wxALIGN_LEFT|wxALL, 5 ) grid1.Add( self.integerwidth, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
grid1.Add( groupcharlabel, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5) grid1.Add( groupcharlabel, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
grid1.Add( self.groupchar, 0, wxALIGN_LEFT|wxALL, 5 ) grid1.Add( self.groupchar, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
grid1.Add( fraclabel, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5 ) grid1.Add( fraclabel, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5 )
grid1.Add( self.fractionwidth, 0, wxALIGN_LEFT|wxALL, 5 ) grid1.Add( self.fractionwidth, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
grid1.Add( decimalcharlabel, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5) grid1.Add( decimalcharlabel, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
grid1.Add( self.decimalchar, 0, wxALIGN_LEFT|wxALL, 5 ) grid1.Add( self.decimalchar, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
grid1.Add( self.set_min, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5 ) grid1.Add( self.set_min, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5 )
grid1.Add( self.min, 0, wxALIGN_LEFT|wxALL, 5 ) grid1.Add( self.min, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
grid1.Add( (5,5), 0, wxALIGN_LEFT|wxALL, 5) grid1.Add( (5,5), 0, wx.ALIGN_LEFT|wx.ALL, 5)
grid1.Add( (5,5), 0, wxALIGN_LEFT|wxALL, 5) grid1.Add( (5,5), 0, wx.ALIGN_LEFT|wx.ALL, 5)
grid1.Add( self.set_max, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5 ) grid1.Add( self.set_max, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5 )
grid1.Add( self.max, 0, wxALIGN_LEFT|wxALL, 5 ) grid1.Add( self.max, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
grid1.Add( (5,5), 0, wxALIGN_LEFT|wxALL, 5) grid1.Add( (5,5), 0, wx.ALIGN_LEFT|wx.ALL, 5)
grid1.Add( (5,5), 0, wxALIGN_LEFT|wxALL, 5) grid1.Add( (5,5), 0, wx.ALIGN_LEFT|wx.ALL, 5)
grid1.Add( self.limit_target, 0, wxALIGN_LEFT|wxALL, 5 ) grid1.Add( self.limit_target, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
grid1.Add( self.allow_none, 0, wxALIGN_LEFT|wxALL, 5 ) grid1.Add( self.allow_none, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
hbox1 = wxBoxSizer( wxHORIZONTAL ) hbox1 = wx.BoxSizer( wx.HORIZONTAL )
hbox1.Add( (17,5), 0, wxALIGN_LEFT|wxALL, 5) hbox1.Add( (17,5), 0, wx.ALIGN_LEFT|wx.ALL, 5)
hbox1.Add( self.group_digits, 0, wxALIGN_LEFT|wxLEFT, 5 ) hbox1.Add( self.group_digits, 0, wx.ALIGN_LEFT|wx.LEFT, 5 )
grid1.Add( hbox1, 0, wxALIGN_LEFT|wxALL, 5) grid1.Add( hbox1, 0, wx.ALIGN_LEFT|wx.ALL, 5)
grid1.Add( (5,5), 0, wxALIGN_LEFT|wxALL, 5) grid1.Add( (5,5), 0, wx.ALIGN_LEFT|wx.ALL, 5)
grid1.Add( self.allow_negative, 0, wxALIGN_LEFT|wxALL, 5 ) grid1.Add( self.allow_negative, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
grid1.Add( self.use_parens, 0, wxALIGN_LEFT|wxALL, 5 ) grid1.Add( self.use_parens, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
hbox2 = wxBoxSizer( wxHORIZONTAL ) hbox2 = wx.BoxSizer( wx.HORIZONTAL )
hbox2.Add( (17,5), 0, wxALIGN_LEFT|wxALL, 5) hbox2.Add( (17,5), 0, wx.ALIGN_LEFT|wx.ALL, 5)
hbox2.Add( self.select_on_entry, 0, wxALIGN_LEFT|wxLEFT, 5 ) hbox2.Add( self.select_on_entry, 0, wx.ALIGN_LEFT|wx.LEFT, 5 )
grid1.Add( hbox2, 0, wxALIGN_LEFT|wxALL, 5) grid1.Add( hbox2, 0, wx.ALIGN_LEFT|wx.ALL, 5)
grid1.Add( (5,5), 0, wxALIGN_LEFT|wxALL, 5) grid1.Add( (5,5), 0, wx.ALIGN_LEFT|wx.ALL, 5)
grid2 = wxFlexGridSizer( 0, 2, 0, 0 ) grid2 = wx.FlexGridSizer( 0, 2, 0, 0 )
grid2.Add( label, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5 ) grid2.Add( label, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5 )
grid2.Add( self.target_ctl, 0, wxALIGN_LEFT|wxALL, 5 ) grid2.Add( self.target_ctl, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
grid2.Add( (5,5), 0, wxALIGN_LEFT|wxALL, 5) grid2.Add( (5,5), 0, wx.ALIGN_LEFT|wx.ALL, 5)
grid2.Add( (5,5), 0, wxALIGN_LEFT|wxALL, 5) grid2.Add( (5,5), 0, wx.ALIGN_LEFT|wx.ALL, 5)
grid2.Add( label_numselect, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5 ) grid2.Add( label_numselect, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5 )
grid2.Add( self.numselect, 0, wxALIGN_LEFT|wxALL, 5 ) grid2.Add( self.numselect, 0, wx.ALIGN_LEFT|wx.ALL, 5 )
grid2.Add( (5,5), 0, wxALIGN_LEFT|wxALL, 5) grid2.Add( (5,5), 0, wx.ALIGN_LEFT|wx.ALL, 5)
grid2.Add( (5,5), 0, wxALIGN_LEFT|wxALL, 5) grid2.Add( (5,5), 0, wx.ALIGN_LEFT|wx.ALL, 5)
grid2.AddGrowableCol(1) grid2.AddGrowableCol(1)
self.outer_box = wxBoxSizer( wxVERTICAL ) self.outer_box = wx.BoxSizer( wx.VERTICAL )
self.outer_box.Add(header, 0, wxALIGN_LEFT|wxTOP|wxLEFT, 20) self.outer_box.Add(header, 0, wx.ALIGN_LEFT|wx.TOP|wx.LEFT, 20)
self.outer_box.Add( grid1, 0, wxALIGN_CENTRE|wxLEFT|wxBOTTOM|wxRIGHT, 20 ) self.outer_box.Add( grid1, 0, wx.ALIGN_CENTRE|wx.LEFT|wx.BOTTOM|wx.RIGHT, 20 )
self.outer_box.Add( grid2, 0, wxALIGN_LEFT|wxALL, 20 ) self.outer_box.Add( grid2, 0, wx.ALIGN_LEFT|wx.ALL, 20 )
self.grid2 = grid2 self.grid2 = grid2
panel.SetAutoLayout( True ) panel.SetAutoLayout( True )
@@ -146,34 +148,35 @@ value entry ctrl:""")
panel.Move( (50,10) ) panel.Move( (50,10) )
self.panel = panel self.panel = panel
EVT_MASKEDNUM( self, self.integerwidth.GetId(), self.OnSetIntWidth ) mnum.EVT_MASKEDNUM( self, self.integerwidth.GetId(), self.OnSetIntWidth )
EVT_MASKEDNUM( self, self.fractionwidth.GetId(), self.OnSetFractionWidth ) mnum.EVT_MASKEDNUM( self, self.fractionwidth.GetId(), self.OnSetFractionWidth )
EVT_TEXT( self, self.groupchar.GetId(), self.OnSetGroupChar ) self.Bind(wx.EVT_TEXT, self.OnSetGroupChar, self.groupchar )
EVT_TEXT( self, self.decimalchar.GetId(), self.OnSetDecimalChar ) self.Bind(wx.EVT_TEXT, self.OnSetDecimalChar, self.decimalchar )
EVT_CHECKBOX( self, self.set_min.GetId(), self.OnSetMin ) self.Bind(wx.EVT_CHECKBOX, self.OnSetMin, self.set_min )
EVT_CHECKBOX( self, self.set_max.GetId(), self.OnSetMax ) self.Bind(wx.EVT_CHECKBOX, self.OnSetMax, self.set_max )
EVT_MASKEDNUM( self, self.min.GetId(), self.SetTargetMinMax ) mnum.EVT_MASKEDNUM( self, self.min.GetId(), self.SetTargetMinMax )
EVT_MASKEDNUM( self, self.max.GetId(), self.SetTargetMinMax ) mnum.EVT_MASKEDNUM( self, self.max.GetId(), self.SetTargetMinMax )
EVT_CHECKBOX( self, self.limit_target.GetId(), self.SetTargetMinMax ) self.Bind(wx.EVT_CHECKBOX, self.SetTargetMinMax, self.limit_target )
EVT_CHECKBOX( self, self.allow_none.GetId(), self.OnSetAllowNone ) self.Bind(wx.EVT_CHECKBOX, self.OnSetAllowNone, self.allow_none )
EVT_CHECKBOX( self, self.group_digits.GetId(), self.OnSetGroupDigits ) self.Bind(wx.EVT_CHECKBOX, self.OnSetGroupDigits, self.group_digits )
EVT_CHECKBOX( self, self.allow_negative.GetId(), self.OnSetAllowNegative ) self.Bind(wx.EVT_CHECKBOX, self.OnSetAllowNegative, self.allow_negative )
EVT_CHECKBOX( self, self.use_parens.GetId(), self.OnSetUseParens ) self.Bind(wx.EVT_CHECKBOX, self.OnSetUseParens, self.use_parens )
EVT_CHECKBOX( self, self.select_on_entry.GetId(), self.OnSetSelectOnEntry ) self.Bind(wx.EVT_CHECKBOX, self.OnSetSelectOnEntry, self.select_on_entry )
EVT_MASKEDNUM( self, self.target_ctl.GetId(), self.OnTargetChange ) mnum.EVT_MASKEDNUM( self, self.target_ctl.GetId(), self.OnTargetChange )
EVT_COMBOBOX( self, self.numselect.GetId(), self.OnNumberSelect ) self.Bind(wx.EVT_COMBOBOX, self.OnNumberSelect, self.numselect )
def OnSetIntWidth(self, event ): def OnSetIntWidth(self, event ):
width = self.integerwidth.GetValue() width = self.integerwidth.GetValue()
if width < 1: if width < 1:
self.log.write("integer width must be positive\n") self.log.write("integer width must be positive\n")
self.integerwidth.SetForegroundColour(wxRED) self.integerwidth.SetForegroundColour(wx.RED)
else: else:
self.integerwidth.SetForegroundColour(wxBLACK) self.integerwidth.SetForegroundColour(wx.BLACK)
self.log.write("setting integer width to %d\n" % width) self.log.write("setting integer width to %d\n" % width)
self.target_ctl.SetParameters( integerWidth = width) self.target_ctl.SetParameters( integerWidth = width)
# Now resize and fit the dialog as appropriate: # Now resize and fit the dialog as appropriate:
@@ -196,9 +199,9 @@ value entry ctrl:""")
char = self.groupchar.GetValue() char = self.groupchar.GetValue()
if self.target_ctl.GetDecimalChar() == char: if self.target_ctl.GetDecimalChar() == char:
self.log.write("group and decimal chars must be different\n") self.log.write("group and decimal chars must be different\n")
self.groupchar.SetForegroundColour(wxRED) self.groupchar.SetForegroundColour(wx.RED)
else: else:
self.groupchar.SetForegroundColour(wxBLACK) self.groupchar.SetForegroundColour(wx.BLACK)
self.log.write("setting group char to %s\n" % char) self.log.write("setting group char to %s\n" % char)
self.target_ctl.SetGroupChar( char ) self.target_ctl.SetGroupChar( char )
@@ -206,9 +209,9 @@ value entry ctrl:""")
char = self.decimalchar.GetValue() char = self.decimalchar.GetValue()
if self.target_ctl.GetGroupChar() == char: if self.target_ctl.GetGroupChar() == char:
self.log.write("group and decimal chars must be different\n") self.log.write("group and decimal chars must be different\n")
self.decimalchar.SetForegroundColour(wxRED) self.decimalchar.SetForegroundColour(wx.RED)
else: else:
self.decimalchar.SetForegroundColour(wxBLACK) self.decimalchar.SetForegroundColour(wx.BLACK)
self.log.write("setting decimal char to %s\n" % char) self.log.write("setting decimal char to %s\n" % char)
self.target_ctl.SetDecimalChar( char ) self.target_ctl.SetDecimalChar( char )
@@ -238,9 +241,9 @@ value entry ctrl:""")
self.log.write( "min (%d) won't fit in control -- bound not set\n" % min ) self.log.write( "min (%d) won't fit in control -- bound not set\n" % min )
else: else:
self.log.write( "min (%d) > current max (%d) -- bound not set\n" % ( min, self.target_ctl.GetMax() ) ) self.log.write( "min (%d) > current max (%d) -- bound not set\n" % ( min, self.target_ctl.GetMax() ) )
self.min.SetParameters( signedForegroundColour=wxRED, foregroundColour=wxRED ) self.min.SetParameters( signedForegroundColour=wx.RED, foregroundColour=wx.RED )
else: else:
self.min.SetParameters( signedForegroundColour=wxBLACK, foregroundColour=wxBLACK ) self.min.SetParameters( signedForegroundColour=wx.BLACK, foregroundColour=wx.BLACK )
self.min.Refresh() self.min.Refresh()
if max != cur_max and not self.target_ctl.SetMax( max ): if max != cur_max and not self.target_ctl.SetMax( max ):
@@ -248,9 +251,9 @@ value entry ctrl:""")
self.log.write( "max (%d) won't fit in control -- bound not set\n" % max ) self.log.write( "max (%d) won't fit in control -- bound not set\n" % max )
else: else:
self.log.write( "max (%d) < current min (%d) -- bound not set\n" % ( max, self.target_ctl.GetMin() ) ) self.log.write( "max (%d) < current min (%d) -- bound not set\n" % ( max, self.target_ctl.GetMin() ) )
self.max.SetParameters( signedForegroundColour=wxRED, foregroundColour=wxRED ) self.max.SetParameters( signedForegroundColour=wx.RED, foregroundColour=wx.RED )
else: else:
self.max.SetParameters( signedForegroundColour=wxBLACK, foregroundColour=wxBLACK ) self.max.SetParameters( signedForegroundColour=wx.BLACK, foregroundColour=wx.BLACK )
self.max.Refresh() self.max.Refresh()
if min != cur_min or max != cur_max: if min != cur_min or max != cur_max:
@@ -327,7 +330,7 @@ def runTest( frame, nb, log ):
return win return win
#---------------------------------------------------------------------- #----------------------------------------------------------------------
overview = overviewdoc overview = mnum.__doc__
if __name__ == '__main__': if __name__ == '__main__':
import sys,os import sys,os

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