Added the sample code from wxPython In Action to the samples dir

git-svn-id: https://svn.wxwidgets.org/svn/wx/wxWidgets/trunk@42925 c3d73ce0-8a6f-49c7-b76d-6d57e0e08775
This commit is contained in:
Robin Dunn
2006-11-01 22:36:23 +00:00
parent bb2775b9e8
commit be05b43451
184 changed files with 9122 additions and 0 deletions

View File

@@ -0,0 +1,77 @@
import wx
t1_text = """\
The whole contents of this control
will be placed in the system's
clipboard when you click the copy
button below.
"""
t2_text = """\
If the clipboard contains a text
data object then it will be placed
in this control when you click
the paste button below. Try
copying to and pasting from
other applications too!
"""
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Clipboard",
size=(500,300))
p = wx.Panel(self)
# create the controls
self.t1 = wx.TextCtrl(p, -1, t1_text,
style=wx.TE_MULTILINE|wx.HSCROLL)
self.t2 = wx.TextCtrl(p, -1, t2_text,
style=wx.TE_MULTILINE|wx.HSCROLL)
copy = wx.Button(p, -1, "Copy")
paste = wx.Button(p, -1, "Paste")
# setup the layout with sizers
fgs = wx.FlexGridSizer(2, 2, 5, 5)
fgs.AddGrowableRow(0)
fgs.AddGrowableCol(0)
fgs.AddGrowableCol(1)
fgs.Add(self.t1, 0, wx.EXPAND)
fgs.Add(self.t2, 0, wx.EXPAND)
fgs.Add(copy, 0, wx.EXPAND)
fgs.Add(paste, 0, wx.EXPAND)
border = wx.BoxSizer()
border.Add(fgs, 1, wx.EXPAND|wx.ALL, 5)
p.SetSizer(border)
# Bind events
self.Bind(wx.EVT_BUTTON, self.OnDoCopy, copy)
self.Bind(wx.EVT_BUTTON, self.OnDoPaste, paste)
def OnDoCopy(self, evt):
data = wx.TextDataObject()
data.SetText(self.t1.GetValue())
if wx.TheClipboard.Open():
wx.TheClipboard.SetData(data)
wx.TheClipboard.Close()
else:
wx.MessageBox("Unable to open the clipboard", "Error")
def OnDoPaste(self, evt):
success = False
data = wx.TextDataObject()
if wx.TheClipboard.Open():
success = wx.TheClipboard.GetData(data)
wx.TheClipboard.Close()
if success:
self.t2.SetValue(data.GetText())
else:
wx.MessageBox(
"There is no data in the clipboard in the required format",
"Error")
app = wx.PySimpleApp()
frm = MyFrame()
frm.Show()
app.MainLoop()

View File

@@ -0,0 +1,152 @@
"""
This sample shows how to put multiple objects in the clipboard, one of
which uses a custom data format. In this case we use a Python
dictionary of values for our custom format, and we also put a textual
representation of the dictionary. To test this, run two instances of
this program, enter data in one and click the copy button. Then click
the paste button in the other instance. Also paste into a text editor
to see the data in the standard text format.
"""
import wx
import cPickle
import pprint
class TestFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, "Copy/Paste Test")
panel = wx.Panel(self)
# First create the controls
topLbl = wx.StaticText(panel, -1, "Account Information")
topLbl.SetFont(wx.Font(18, wx.SWISS, wx.NORMAL, wx.BOLD))
nameLbl = wx.StaticText(panel, -1, "Name:")
self.name = wx.TextCtrl(panel, -1, "");
addrLbl = wx.StaticText(panel, -1, "Address:")
self.addr1 = wx.TextCtrl(panel, -1, "");
self.addr2 = wx.TextCtrl(panel, -1, "");
cstLbl = wx.StaticText(panel, -1, "City, State, Zip:")
self.city = wx.TextCtrl(panel, -1, "", size=(150,-1));
self.state = wx.TextCtrl(panel, -1, "", size=(50,-1));
self.zip = wx.TextCtrl(panel, -1, "", size=(70,-1));
phoneLbl = wx.StaticText(panel, -1, "Phone:")
self.phone = wx.TextCtrl(panel, -1, "");
emailLbl = wx.StaticText(panel, -1, "Email:")
self.email = wx.TextCtrl(panel, -1, "");
copyBtn = wx.Button(panel, -1, "Copy")
pasteBtn = wx.Button(panel, -1, "Paste")
self.Bind(wx.EVT_BUTTON, self.OnCopy, copyBtn)
self.Bind(wx.EVT_BUTTON, self.OnPaste, pasteBtn)
# Now do the layout.
# mainSizer is the top-level one that manages everything
mainSizer = wx.BoxSizer(wx.VERTICAL)
mainSizer.Add(topLbl, 0, wx.ALL, 5)
mainSizer.Add(wx.StaticLine(panel), 0,
wx.EXPAND|wx.TOP|wx.BOTTOM, 5)
# addrSizer is a grid that holds all of the address info
addrSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
addrSizer.AddGrowableCol(1)
addrSizer.Add(nameLbl, 0,
wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
addrSizer.Add(self.name, 0, wx.EXPAND)
addrSizer.Add(addrLbl, 0,
wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
addrSizer.Add(self.addr1, 0, wx.EXPAND)
addrSizer.Add((10,10)) # some empty space
addrSizer.Add(self.addr2, 0, wx.EXPAND)
addrSizer.Add(cstLbl, 0,
wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
# the city, state, zip fields are in a sub-sizer
cstSizer = wx.BoxSizer(wx.HORIZONTAL)
cstSizer.Add(self.city, 1)
cstSizer.Add(self.state, 0, wx.LEFT|wx.RIGHT, 5)
cstSizer.Add(self.zip)
addrSizer.Add(cstSizer, 0, wx.EXPAND)
addrSizer.Add(phoneLbl, 0,
wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
addrSizer.Add(self.phone, 0, wx.EXPAND)
addrSizer.Add(emailLbl, 0,
wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
addrSizer.Add(self.email, 0, wx.EXPAND)
# now add the addrSizer to the mainSizer
mainSizer.Add(addrSizer, 0, wx.EXPAND|wx.ALL, 10)
# The buttons sizer will put them in a row with resizeable
# gaps between and on either side of the buttons
btnSizer = wx.BoxSizer(wx.HORIZONTAL)
btnSizer.Add((20,20), 1)
btnSizer.Add(copyBtn)
btnSizer.Add((20,20), 1)
btnSizer.Add(pasteBtn)
btnSizer.Add((20,20), 1)
mainSizer.Add(btnSizer, 0, wx.EXPAND|wx.BOTTOM, 10)
panel.SetSizer(mainSizer)
# Fit the frame to the needs of the sizer. The frame will
# automatically resize the panel as needed. Also prevent the
# frame from getting smaller than this size.
mainSizer.Fit(self)
self.SetMinSize(self.GetSize())
fieldNames = ["name", "addr1", "addr2",
"city", "state", "zip", "phone", "email"]
def OnCopy(self, evt):
# make a dictionary of values
fieldData = {}
for name in self.fieldNames:
tc = getattr(self, name)
fieldData[name] = tc.GetValue()
# pickle it and put in a custom data object
cdo = wx.CustomDataObject("ContactDictFormat")
cdo.SetData(cPickle.dumps(fieldData))
# also make a text representaion
tdo = wx.TextDataObject(pprint.pformat(fieldData))
# and put them both in the clipboard
dataobj = wx.DataObjectComposite()
dataobj.Add(cdo)
dataobj.Add(tdo)
if wx.TheClipboard.Open():
wx.TheClipboard.SetData(dataobj)
wx.TheClipboard.Close()
def OnPaste(self, evt):
# Get the custom format object and put it into
# the entry fields
cdo = wx.CustomDataObject("ContactDictFormat")
if wx.TheClipboard.Open():
success = wx.TheClipboard.GetData(cdo)
wx.TheClipboard.Close()
if success:
data = cdo.GetData()
fieldData = cPickle.loads(data)
for name in self.fieldNames:
tc = getattr(self, name)
tc.SetValue(fieldData[name])
app = wx.PySimpleApp()
TestFrame().Show()
app.MainLoop()

View File

@@ -0,0 +1,70 @@
import wx
class DragController(wx.Control):
"""
Just a little control to handle dragging the text from a text
control. We use a separate control so as to not interfere with
the native drag-select functionality of the native text control.
"""
def __init__(self, parent, source, size=(25,25)):
wx.Control.__init__(self, parent, -1, size=size,
style=wx.SIMPLE_BORDER)
self.source = source
self.SetMinSize(size)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
def OnPaint(self, evt):
# draw a simple arrow
dc = wx.BufferedPaintDC(self)
dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
dc.Clear()
w, h = dc.GetSize()
y = h/2
dc.SetPen(wx.Pen("dark blue", 2))
dc.DrawLine(w/8, y, w-w/8, y)
dc.DrawLine(w-w/8, y, w/2, h/4)
dc.DrawLine(w-w/8, y, w/2, 3*h/4)
def OnLeftDown(self, evt):
text = self.source.GetValue()
data = wx.TextDataObject(text)
dropSource = wx.DropSource(self)
dropSource.SetData(data)
result = dropSource.DoDragDrop(wx.Drag_AllowMove)
# if the user wants to move the data then we should delete it
# from the source
if result == wx.DragMove:
self.source.SetValue("")
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Drop Source")
p = wx.Panel(self)
# create the controls
label1 = wx.StaticText(p, -1, "Put some text in this control:")
label2 = wx.StaticText(p, -1,
"Then drag from the neighboring bitmap and\n"
"drop in an application that accepts dropped\n"
"text, such as MS Word.")
text = wx.TextCtrl(p, -1, "Some text")
dragctl = DragController(p, text)
# setup the layout with sizers
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(label1, 0, wx.ALL, 5)
hrow = wx.BoxSizer(wx.HORIZONTAL)
hrow.Add(text, 1, wx.RIGHT, 5)
hrow.Add(dragctl, 0)
sizer.Add(hrow, 0, wx.EXPAND|wx.ALL, 5)
sizer.Add(label2, 0, wx.ALL, 5)
p.SetSizer(sizer)
sizer.Fit(self)
app = wx.PySimpleApp()
frm = MyFrame()
frm.Show()
app.MainLoop()

View File

@@ -0,0 +1,40 @@
import wx
class MyFileDropTarget(wx.FileDropTarget):
def __init__(self, window):
wx.FileDropTarget.__init__(self)
self.window = window
def OnDropFiles(self, x, y, filenames):
self.window.AppendText("\n%d file(s) dropped at (%d,%d):\n" %
(len(filenames), x, y))
for file in filenames:
self.window.AppendText("\t%s\n" % file)
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Drop Target",
size=(500,300))
p = wx.Panel(self)
# create the controls
label = wx.StaticText(p, -1, "Drop some files here:")
text = wx.TextCtrl(p, -1, "",
style=wx.TE_MULTILINE|wx.HSCROLL)
# setup the layout with sizers
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(label, 0, wx.ALL, 5)
sizer.Add(text, 1, wx.EXPAND|wx.ALL, 5)
p.SetSizer(sizer)
# make the text control be a drop target
dt = MyFileDropTarget(text)
text.SetDropTarget(dt)
app = wx.PySimpleApp()
frm = MyFrame()
frm.Show()
app.MainLoop()

View File

@@ -0,0 +1,38 @@
import wx
from wx.lib.filebrowsebutton import FileBrowseButton
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="wx.Sound",
size=(500,100))
p = wx.Panel(self)
# create the controls
self.fbb = FileBrowseButton(p,
labelText="Select WAV file:",
fileMask="*.wav")
btn = wx.Button(p, -1, "Play")
self.Bind(wx.EVT_BUTTON, self.OnPlaySound, btn)
# setup the layout with sizers
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(self.fbb, 1, wx.ALIGN_CENTER_VERTICAL)
sizer.Add(btn, 0, wx.ALIGN_CENTER_VERTICAL)
border = wx.BoxSizer(wx.VERTICAL)
border.Add(sizer, 0, wx.EXPAND|wx.ALL, 15)
p.SetSizer(border)
def OnPlaySound(self, evt):
filename = self.fbb.GetValue()
self.sound = wx.Sound(filename)
if self.sound.IsOk():
self.sound.Play(wx.SOUND_ASYNC)
else:
wx.MessageBox("Invalid sound file", "Error")
app = wx.PySimpleApp()
frm = MyFrame()
frm.Show()
app.MainLoop()

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,39 @@
import wx
import time
class ClockWindow(wx.Window):
def __init__(self, parent):
wx.Window.__init__(self, parent)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
self.timer.Start(1000)
def Draw(self, dc):
t = time.localtime(time.time())
st = time.strftime("%I:%M:%S", t)
w, h = self.GetClientSize()
dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
dc.Clear()
dc.SetFont(wx.Font(30, wx.SWISS, wx.NORMAL, wx.NORMAL))
tw, th = dc.GetTextExtent(st)
dc.DrawText(st, (w-tw)/2, (h)/2 - th/2)
def OnTimer(self, evt):
dc = wx.BufferedDC(wx.ClientDC(self))
self.Draw(dc)
def OnPaint(self, evt):
dc = wx.BufferedPaintDC(self)
self.Draw(dc)
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="wx.Timer")
ClockWindow(self)
app = wx.PySimpleApp()
frm = MyFrame()
frm.Show()
app.MainLoop()

View File

@@ -0,0 +1,101 @@
import wx
import threading
import random
class WorkerThread(threading.Thread):
"""
This just simulates some long-running task that periodically sends
a message to the GUI thread.
"""
def __init__(self, threadNum, window):
threading.Thread.__init__(self)
self.threadNum = threadNum
self.window = window
self.timeToQuit = threading.Event()
self.timeToQuit.clear()
self.messageCount = random.randint(10,20)
self.messageDelay = 0.1 + 2.0 * random.random()
def stop(self):
self.timeToQuit.set()
def run(self):
msg = "Thread %d iterating %d times with a delay of %1.4f\n" \
% (self.threadNum, self.messageCount, self.messageDelay)
wx.CallAfter(self.window.LogMessage, msg)
for i in range(1, self.messageCount+1):
self.timeToQuit.wait(self.messageDelay)
if self.timeToQuit.isSet():
break
msg = "Message %d from thread %d\n" % (i, self.threadNum)
wx.CallAfter(self.window.LogMessage, msg)
else:
wx.CallAfter(self.window.ThreadFinished, self)
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Multi-threaded GUI")
self.threads = []
self.count = 0
panel = wx.Panel(self)
startBtn = wx.Button(panel, -1, "Start a thread")
stopBtn = wx.Button(panel, -1, "Stop all threads")
self.tc = wx.StaticText(panel, -1, "Worker Threads: 00")
self.log = wx.TextCtrl(panel, -1, "",
style=wx.TE_RICH|wx.TE_MULTILINE)
inner = wx.BoxSizer(wx.HORIZONTAL)
inner.Add(startBtn, 0, wx.RIGHT, 15)
inner.Add(stopBtn, 0, wx.RIGHT, 15)
inner.Add(self.tc, 0, wx.ALIGN_CENTER_VERTICAL)
main = wx.BoxSizer(wx.VERTICAL)
main.Add(inner, 0, wx.ALL, 5)
main.Add(self.log, 1, wx.EXPAND|wx.ALL, 5)
panel.SetSizer(main)
self.Bind(wx.EVT_BUTTON, self.OnStartButton, startBtn)
self.Bind(wx.EVT_BUTTON, self.OnStopButton, stopBtn)
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
self.UpdateCount()
def OnStartButton(self, evt):
self.count += 1
thread = WorkerThread(self.count, self)
self.threads.append(thread)
self.UpdateCount()
thread.start()
def OnStopButton(self, evt):
self.StopThreads()
self.UpdateCount()
def OnCloseWindow(self, evt):
self.StopThreads()
self.Destroy()
def StopThreads(self):
while self.threads:
thread = self.threads[0]
thread.stop()
self.threads.remove(thread)
def UpdateCount(self):
self.tc.SetLabel("Worker Threads: %d" % len(self.threads))
def LogMessage(self, msg):
self.log.AppendText(msg)
def ThreadFinished(self, thread):
self.threads.remove(thread)
self.UpdateCount()
app = wx.PySimpleApp()
frm = MyFrame()
frm.Show()
app.MainLoop()

View File

@@ -0,0 +1,43 @@
"""
XRC is an XML-based resource format for wxPython. With it you can
define the layout of widgets, and then load that XRC at runtime to
create the layout. There are several GUI designers available that
understand the XRC format, a simple one called XRCed comes with
wxPython.
"""
import wx
import wx.xrc
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="XRC Sample",
size=(400,225))
res = wx.xrc.XmlResource("xrcsample.xrc")
panel = res.LoadPanel(self, "ID_PANEL")
self.Bind(wx.EVT_BUTTON, self.OnOk,
wx.xrc.XRCCTRL(self, "ID_OK"))
self.Bind(wx.EVT_BUTTON, self.OnCancel,
wx.xrc.XRCCTRL(self, "ID_CANCEL"))
def OnOk(self, evt):
namectrl = wx.xrc.XRCCTRL(self, "ID_NAME")
name = namectrl.GetValue()
emailctrl = wx.xrc.XRCCTRL(self, "ID_EMAIL")
email = emailctrl.GetValue()
phonectrl = wx.xrc.XRCCTRL(self, "ID_PHONE")
phone = phonectrl.GetValue()
print "You entered:\n name: %s\n email: %s\n phone: %s\n" \
% (name, email, phone)
def OnCancel(self, evt):
self.Close()
app = wx.PySimpleApp(redirect=True)
frm = MyFrame()
frm.Show()
app.MainLoop()

View File

@@ -0,0 +1,94 @@
<?xml version="1.0" encoding="iso-8859-1"?>
<resource>
<object class="wxPanel" name="ID_PANEL">
<object class="wxGridBagSizer">
<object class="sizeritem">
<object class="wxStaticText">
<label>Name:</label>
</object>
<flag>wxALIGN_RIGHT</flag>
<cellpos>1,1</cellpos>
</object>
<vgap>5</vgap>
<hgap>5</hgap>
<object class="sizeritem">
<object class="wxTextCtrl" name="ID_NAME">
<size>200,-1</size>
</object>
<flag>wxEXPAND</flag>
<cellpos>1,2</cellpos>
</object>
<object class="sizeritem">
<object class="wxStaticText">
<label>Email:</label>
</object>
<flag>wxALIGN_RIGHT</flag>
<cellpos>2,1</cellpos>
</object>
<object class="sizeritem">
<object class="wxTextCtrl" name="ID_EMAIL"/>
<flag>wxEXPAND</flag>
<cellpos>2,2</cellpos>
</object>
<object class="sizeritem">
<object class="wxStaticText">
<label>Phone:</label>
</object>
<flag>wxALIGN_RIGHT</flag>
<cellpos>3,1</cellpos>
</object>
<object class="sizeritem">
<object class="wxTextCtrl" name="ID_PHONE"/>
<flag>wxEXPAND</flag>
<cellpos>3,2</cellpos>
</object>
<growablecols>2</growablecols>
<object class="sizeritem">
<object class="wxBoxSizer">
<orient>wxVERTICAL</orient>
<object class="sizeritem">
<object class="wxStaticLine">
<style>wxLI_HORIZONTAL</style>
</object>
<flag>wxEXPAND|wxALIGN_CENTRE_VERTICAL</flag>
</object>
</object>
<flag>wxEXPAND</flag>
<cellpos>5,0</cellpos>
<cellspan>1,4</cellspan>
</object>
<object class="sizeritem">
<object class="wxBoxSizer">
<orient>wxHORIZONTAL</orient>
<object class="spacer">
<size>10,10</size>
<option>1</option>
</object>
<object class="sizeritem">
<object class="wxButton" name="ID_OK">
<label>OK</label>
<default>1</default>
</object>
</object>
<object class="spacer">
<size>10,10</size>
<option>1</option>
<flag></flag>
</object>
<object class="sizeritem">
<object class="wxButton" name="ID_CANCEL">
<label>Cancel</label>
</object>
</object>
<object class="spacer">
<size>10,10</size>
<option>1</option>
</object>
</object>
<flag>wxEXPAND</flag>
<cellpos>6,0</cellpos>
<cellspan>1,4</cellspan>
</object>
</object>
</object>
</resource>