summaryrefslogtreecommitdiffstats
path: root/Demo
diff options
context:
space:
mode:
Diffstat (limited to 'Demo')
-rwxr-xr-xDemo/tix/samples/Balloon.py2
-rwxr-xr-xDemo/tix/samples/BtnBox.py8
-rwxr-xr-xDemo/tix/samples/CmpImg.py37
-rwxr-xr-xDemo/tix/samples/ComboBox.py20
-rwxr-xr-xDemo/tix/samples/Control.py16
-rwxr-xr-xDemo/tix/samples/DirList.py17
-rwxr-xr-xDemo/tix/samples/DirTree.py11
-rwxr-xr-xDemo/tix/samples/NoteBook.py50
-rwxr-xr-xDemo/tix/samples/OptMenu.py24
-rwxr-xr-xDemo/tix/samples/PanedWin.py2
-rwxr-xr-xDemo/tix/samples/PopMenu.py10
-rwxr-xr-xDemo/tix/samples/SHList1.py21
-rwxr-xr-xDemo/tix/samples/SHList2.py41
-rwxr-xr-xDemo/tix/samples/Tree.py44
-rw-r--r--Demo/tix/tixwidgets.py391
-rwxr-xr-xDemo/tkinter/guido/AttrDialog.py796
-rwxr-xr-xDemo/tkinter/guido/ManPage.py370
-rwxr-xr-xDemo/tkinter/guido/MimeViewer.py242
-rwxr-xr-xDemo/tkinter/guido/ShellWindow.py266
-rw-r--r--Demo/tkinter/guido/canvasevents.py230
-rwxr-xr-xDemo/tkinter/guido/dialog.py68
-rwxr-xr-xDemo/tkinter/guido/electrons.py120
-rwxr-xr-xDemo/tkinter/guido/hanoi.py238
-rwxr-xr-xDemo/tkinter/guido/hello.py14
-rwxr-xr-xDemo/tkinter/guido/kill.py169
-rwxr-xr-xDemo/tkinter/guido/listtree.py46
-rwxr-xr-xDemo/tkinter/guido/mbox.py410
-rw-r--r--Demo/tkinter/guido/newmenubardemo.py36
-rw-r--r--Demo/tkinter/guido/paint.py52
-rwxr-xr-xDemo/tkinter/guido/rmt.py114
-rwxr-xr-xDemo/tkinter/guido/solitaire.py578
-rw-r--r--Demo/tkinter/guido/sortvisu.py834
-rw-r--r--Demo/tkinter/guido/ss1.py2
-rwxr-xr-xDemo/tkinter/guido/svkill.py216
-rwxr-xr-xDemo/tkinter/guido/tkman.py408
-rwxr-xr-xDemo/tkinter/guido/wish.py32
-rw-r--r--Demo/tkinter/matt/00-HELLO-WORLD.py28
-rw-r--r--Demo/tkinter/matt/animation-simple.py30
-rw-r--r--Demo/tkinter/matt/animation-w-velocity-ctrl.py46
-rw-r--r--Demo/tkinter/matt/bind-w-mult-calls-p-type.py40
-rw-r--r--Demo/tkinter/matt/canvas-demo-simple.py22
-rw-r--r--Demo/tkinter/matt/canvas-gridding.py80
-rw-r--r--Demo/tkinter/matt/canvas-moving-or-creating.py73
-rw-r--r--Demo/tkinter/matt/canvas-moving-w-mouse.py54
-rw-r--r--Demo/tkinter/matt/canvas-mult-item-sel.py119
-rw-r--r--Demo/tkinter/matt/canvas-reading-tag-info.py72
-rw-r--r--Demo/tkinter/matt/canvas-w-widget-draw-el.py36
-rw-r--r--Demo/tkinter/matt/canvas-with-scrollbars.py70
-rw-r--r--Demo/tkinter/matt/dialog-box.py86
-rw-r--r--Demo/tkinter/matt/entry-simple.py21
-rw-r--r--Demo/tkinter/matt/entry-with-shared-variable.py63
-rw-r--r--Demo/tkinter/matt/killing-window-w-wm.py38
-rw-r--r--Demo/tkinter/matt/menu-all-types-of-entries.py104
-rw-r--r--Demo/tkinter/matt/menu-simple.py44
-rw-r--r--Demo/tkinter/matt/not-what-you-might-think-1.py22
-rw-r--r--Demo/tkinter/matt/not-what-you-might-think-2.py24
-rw-r--r--Demo/tkinter/matt/packer-and-placer-together.py11
-rw-r--r--Demo/tkinter/matt/packer-simple.py32
-rw-r--r--Demo/tkinter/matt/placer-simple.py5
-rw-r--r--Demo/tkinter/matt/pong-demo-1.py62
-rw-r--r--Demo/tkinter/matt/printing-coords-of-items.py73
-rw-r--r--Demo/tkinter/matt/radiobutton-simple.py86
-rw-r--r--Demo/tkinter/matt/rubber-band-box-demo-1.py78
-rw-r--r--Demo/tkinter/matt/rubber-line-demo-1.py68
-rw-r--r--Demo/tkinter/matt/slider-demo-1.py36
-rw-r--r--Demo/tkinter/matt/subclass-existing-widgets.py7
-rw-r--r--Demo/tkinter/matt/two-radio-groups.py72
-rw-r--r--Demo/tkinter/matt/window-creation-more.py36
-rw-r--r--Demo/tkinter/matt/window-creation-simple.py30
-rw-r--r--Demo/tkinter/matt/window-creation-w-location.py30
-rw-r--r--Demo/xml/elem_count.py2
-rw-r--r--Demo/xml/roundtrip.py4
-rw-r--r--Demo/xml/rss2html.py2
-rwxr-xr-xDemo/zlib/minigzip.py15
-rwxr-xr-xDemo/zlib/zlibdemo.py5
75 files changed, 3813 insertions, 3848 deletions
diff --git a/Demo/tix/samples/Balloon.py b/Demo/tix/samples/Balloon.py
index 825ae6a..2295905 100755
--- a/Demo/tix/samples/Balloon.py
+++ b/Demo/tix/samples/Balloon.py
@@ -17,7 +17,7 @@
import Tix
-TCL_ALL_EVENTS = 0
+TCL_ALL_EVENTS = 0
def RunSample (root):
balloon = DemoBalloon(root)
diff --git a/Demo/tix/samples/BtnBox.py b/Demo/tix/samples/BtnBox.py
index 57d02df..af2a2a8 100755
--- a/Demo/tix/samples/BtnBox.py
+++ b/Demo/tix/samples/BtnBox.py
@@ -1,5 +1,5 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
+#
# $Id$
#
# Tix Demostration Program
@@ -21,7 +21,7 @@ def RunSample(w):
# Create the label on the top of the dialog box
#
top = Tix.Label(w, padx=20, pady=10, bd=1, relief=Tix.RAISED,
- anchor=Tix.CENTER, text='This dialog box is\n a demonstration of the\n tixButtonBox widget')
+ anchor=Tix.CENTER, text='This dialog box is\n a demonstration of the\n tixButtonBox widget')
# Create the button box and add a few buttons in it. Set the
# -width of all the buttons to the same value so that they
@@ -32,9 +32,9 @@ def RunSample(w):
#
box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL)
box.add('ok', text='OK', underline=0, width=5,
- command=lambda w=w: w.destroy())
+ command=lambda w=w: w.destroy())
box.add('close', text='Cancel', underline=0, width=5,
- command=lambda w=w: w.destroy())
+ command=lambda w=w: w.destroy())
box.pack(side=Tix.BOTTOM, fill=Tix.X)
top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1)
diff --git a/Demo/tix/samples/CmpImg.py b/Demo/tix/samples/CmpImg.py
index 4e08df7..4720a10 100755
--- a/Demo/tix/samples/CmpImg.py
+++ b/Demo/tix/samples/CmpImg.py
@@ -1,5 +1,5 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
+#
# $Id$
#
# Tix Demostration Program
@@ -22,13 +22,13 @@ static char * netw_xpm[] = {
/* width height ncolors chars_per_pixel */
"32 32 7 1",
/* colors */
-" s None c None",
-". c #000000000000",
-"X c white",
-"o c #c000c000c000",
-"O c #404040",
-"+ c blue",
-"@ c red",
+" s None c None",
+". c #000000000000",
+"X c white",
+"o c #c000c000c000",
+"O c #404040",
+"+ c blue",
+"@ c red",
/* pixels */
" ",
" .............. ",
@@ -69,11 +69,11 @@ static char * drivea_xpm[] = {
/* width height ncolors chars_per_pixel */
"32 32 5 1",
/* colors */
-" s None c None",
-". c #000000000000",
-"X c white",
-"o c #c000c000c000",
-"O c #800080008000",
+" s None c None",
+". c #000000000000",
+"X c white",
+"o c #c000c000c000",
+"O c #800080008000",
/* pixels */
" ",
" ",
@@ -146,10 +146,10 @@ static unsigned char drivea_bits[] = {
def RunSample(w):
w.img0 = Tix.Image('pixmap', data=network_pixmap)
if not w.img0:
- w.img0 = Tix.Image('bitmap', data=network_bitmap)
+ w.img0 = Tix.Image('bitmap', data=network_bitmap)
w.img1 = Tix.Image('pixmap', data=hard_disk_pixmap)
if not w.img0:
- w.img1 = Tix.Image('bitmap', data=hard_disk_bitmap)
+ w.img1 = Tix.Image('bitmap', data=hard_disk_bitmap)
hdd = Tix.Button(w, padx=4, pady=1, width=120)
net = Tix.Button(w, padx=4, pady=1, width=120)
@@ -163,7 +163,7 @@ def RunSample(w):
w.hdd_img = Tix.Image('compound', window=hdd)
w.hdd_img.tk.call(str(w.hdd_img), 'add', 'line')
w.hdd_img.tk.call(str(w.hdd_img), 'add', 'text', '-text', 'Hard Disk',
- '-underline', '0')
+ '-underline', '0')
w.hdd_img.tk.call(str(w.hdd_img), 'add', 'space', '-width', '7')
w.hdd_img.tk.call(str(w.hdd_img), 'add', 'image', '-image', w.img1)
@@ -175,7 +175,7 @@ def RunSample(w):
w.net_img = Tix.Image('compound', window=net)
w.net_img.tk.call(str(w.net_img), 'add', 'line')
w.net_img.tk.call(str(w.net_img), 'add', 'text', '-text', 'Network',
- '-underline', '0')
+ '-underline', '0')
w.net_img.tk.call(str(w.net_img), 'add', 'space', '-width', '7')
w.net_img.tk.call(str(w.net_img), 'add', 'image', '-image', w.img0)
@@ -184,7 +184,7 @@ def RunSample(w):
net['image'] = w.net_img
close = Tix.Button(w, pady=1, text='Close',
- command=lambda w=w: w.destroy())
+ command=lambda w=w: w.destroy())
hdd.pack(side=Tix.LEFT, padx=10, pady=10, fill=Tix.Y, expand=1)
net.pack(side=Tix.LEFT, padx=10, pady=10, fill=Tix.Y, expand=1)
@@ -194,4 +194,3 @@ if __name__ == '__main__':
root = Tix.Tk()
RunSample(root)
root.mainloop()
-
diff --git a/Demo/tix/samples/ComboBox.py b/Demo/tix/samples/ComboBox.py
index afecea4..9140987 100755
--- a/Demo/tix/samples/ComboBox.py
+++ b/Demo/tix/samples/ComboBox.py
@@ -1,5 +1,5 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
+#
# $Id$
#
# Tix Demostration Program
@@ -27,25 +27,25 @@ def RunSample(w):
# to invent new months?
#
# [Hint] The -options switch sets the options of the subwidgets.
- # [Hint] We set the label.width subwidget option of both comboboxes to
+ # [Hint] We set the label.width subwidget option of both comboboxes to
# be 10 so that their labels appear to be aligned.
#
a = Tix.ComboBox(top, label="Month: ", dropdown=1,
- command=select_month, editable=0, variable=demo_month,
- options='listbox.height 6 label.width 10 label.anchor e')
+ command=select_month, editable=0, variable=demo_month,
+ options='listbox.height 6 label.width 10 label.anchor e')
# $w.top.b is a non-drop-down combo box. It is not editable: we provide
# four choices for the user, but he can enter an alternative year if he
# wants to.
#
# [Hint] Use the padY and anchor options of the label subwidget to
- # align the label with the entry subwidget.
+ # align the label with the entry subwidget.
# [Hint] Notice that you should use padY (the NAME of the option) and not
# pady (the SWITCH of the option).
#
b = Tix.ComboBox(top, label="Year: ", dropdown=0,
- command=select_year, editable=1, variable=demo_year,
- options='listbox.height 4 label.padY 5 label.width 10 label.anchor ne')
+ command=select_year, editable=1, variable=demo_year,
+ options='listbox.height 4 label.padY 5 label.width 10 label.anchor ne')
a.pack(side=Tix.TOP, anchor=Tix.W)
b.pack(side=Tix.TOP, anchor=Tix.W)
@@ -70,7 +70,7 @@ def RunSample(w):
b.insert(Tix.END, '1996')
# Use "tixSetSilent" to set the values of the combo box if you
- # don't want your -command procedures (cbx:select_month and
+ # don't want your -command procedures (cbx:select_month and
# cbx:select_year) to be called.
#
a.set_silent('January')
@@ -78,9 +78,9 @@ def RunSample(w):
box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL)
box.add('ok', text='Ok', underline=0, width=6,
- command=lambda w=w: ok_command(w))
+ command=lambda w=w: ok_command(w))
box.add('cancel', text='Cancel', underline=0, width=6,
- command=lambda w=w: w.destroy())
+ command=lambda w=w: w.destroy())
box.pack(side=Tix.BOTTOM, fill=Tix.X)
top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1)
diff --git a/Demo/tix/samples/Control.py b/Demo/tix/samples/Control.py
index e85ee84..3a344c1 100755
--- a/Demo/tix/samples/Control.py
+++ b/Demo/tix/samples/Control.py
@@ -20,7 +20,7 @@
import Tix
-TCL_ALL_EVENTS = 0
+TCL_ALL_EVENTS = 0
def RunSample (root):
control = DemoControl(root)
@@ -46,7 +46,7 @@ class DemoControl:
# $w.top.a allows only integer values
#
# [Hint] The -options switch sets the options of the subwidgets.
- # [Hint] We set the label.width subwidget option of the Controls to
+ # [Hint] We set the label.width subwidget option of the Controls to
# be 16 so that their labels appear to be aligned.
#
a = Tix.Control(top, label='Number of Engines: ', integer=1,
@@ -83,7 +83,7 @@ class DemoControl:
def okcmd (self):
# tixDemo:Status "Selected %d of %s engines each of thrust %d", (demo_num_engines.get(), demo_maker.get(), demo_thrust.get())
self.quitcmd()
-
+
def quitcmd (self):
self.exit = 0
@@ -100,9 +100,9 @@ def adjust_maker(w, inc):
i = maker_list.index(demo_maker.get())
i = i + inc
if i >= len(maker_list):
- i = 0
+ i = 0
elif i < 0:
- i = len(maker_list) - 1
+ i = len(maker_list) - 1
# In Tcl/Tix we should return the string maker_list[i]. We can't
# do that in Tkinter so we set the global variable. (This works).
@@ -110,10 +110,10 @@ def adjust_maker(w, inc):
def validate_maker(w):
try:
- i = maker_list.index(demo_maker.get())
+ i = maker_list.index(demo_maker.get())
except ValueError:
- # Works here though. Why ? Beats me.
- return maker_list[0]
+ # Works here though. Why ? Beats me.
+ return maker_list[0]
# Works here though. Why ? Beats me.
return maker_list[i]
diff --git a/Demo/tix/samples/DirList.py b/Demo/tix/samples/DirList.py
index 8d7536c..5fd8c0d 100755
--- a/Demo/tix/samples/DirList.py
+++ b/Demo/tix/samples/DirList.py
@@ -1,6 +1,6 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
#
-# $Id$
+# $Id$
#
# Tix Demostration Program
#
@@ -19,21 +19,21 @@
import Tix, os, copy
from Tkconstants import *
-TCL_ALL_EVENTS = 0
+TCL_ALL_EVENTS = 0
def RunSample (root):
dirlist = DemoDirList(root)
dirlist.mainloop()
dirlist.destroy()
-
+
class DemoDirList:
def __init__(self, w):
self.root = w
self.exit = -1
-
+
z = w.winfo_toplevel()
z.wm_protocol("WM_DELETE_WINDOW", lambda self=self: self.quitcmd())
-
+
# Create the tixDirList and the tixLabelEntry widgets on the on the top
# of the dialog box
@@ -48,14 +48,14 @@ class DemoDirList:
#
top.dir = Tix.DirList(top)
top.dir.hlist['width'] = 40
-
+
# When the user presses the ".." button, the selected directory
# is "transferred" into the entry widget
#
top.btn = Tix.Button(top, text = " >> ", pady = 0)
# We use a LabelEntry to hold the installation directory. The user
- # can choose from the DirList widget, or he can type in the directory
+ # can choose from the DirList widget, or he can type in the directory
# manually
#
top.ent = Tix.LabelEntry(top, label="Installation Directory:",
@@ -64,7 +64,7 @@ class DemoDirList:
entry.width 40
label.anchor w
''')
-
+
font = self.root.tk.eval('tix option get fixed_font')
# font = self.root.master.tix_option_get('fixed_font')
top.ent.entry['font'] = font
@@ -129,4 +129,3 @@ if __name__== '__main__' :
for line in traceback.format_exception(t,v,tb):
text = text + line + '\n'
d = tkMessageBox.showerror ( 'Tix Demo Error', text)
-
diff --git a/Demo/tix/samples/DirTree.py b/Demo/tix/samples/DirTree.py
index d007a2b..2e4fe0b 100755
--- a/Demo/tix/samples/DirTree.py
+++ b/Demo/tix/samples/DirTree.py
@@ -1,6 +1,6 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
#
-# $Id$
+# $Id$
#
# Tix Demostration Program
#
@@ -19,7 +19,7 @@
import Tix, os, copy
from Tkconstants import *
-TCL_ALL_EVENTS = 0
+TCL_ALL_EVENTS = 0
def RunSample (root):
dirtree = DemoDirTree(root)
@@ -30,7 +30,7 @@ class DemoDirTree:
def __init__(self, w):
self.root = w
self.exit = -1
-
+
z = w.winfo_toplevel()
z.wm_protocol("WM_DELETE_WINDOW", lambda self=self: self.quitcmd())
@@ -48,14 +48,14 @@ class DemoDirTree:
#
top.dir = Tix.DirTree(top)
top.dir.hlist['width'] = 40
-
+
# When the user presses the ".." button, the selected directory
# is "transferred" into the entry widget
#
top.btn = Tix.Button(top, text = " >> ", pady = 0)
# We use a LabelEntry to hold the installation directory. The user
- # can choose from the DirTree widget, or he can type in the directory
+ # can choose from the DirTree widget, or he can type in the directory
# manually
#
top.ent = Tix.LabelEntry(top, label="Installation Directory:",
@@ -115,4 +115,3 @@ class DemoDirTree:
if __name__== '__main__' :
root=Tix.Tk()
RunSample(root)
-
diff --git a/Demo/tix/samples/NoteBook.py b/Demo/tix/samples/NoteBook.py
index abf3bfd..1e0da3e 100755
--- a/Demo/tix/samples/NoteBook.py
+++ b/Demo/tix/samples/NoteBook.py
@@ -1,5 +1,5 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
+#
# $Id$
#
# Tix Demostration Program
@@ -23,9 +23,9 @@ def RunSample(w):
# notebook, so that they are well-aligned on the screen.
prefix = Tix.OptionName(w)
if prefix:
- prefix = '*'+prefix
+ prefix = '*'+prefix
else:
- prefix = ''
+ prefix = ''
w.option_add(prefix+'*TixControl*entry.width', 10)
w.option_add(prefix+'*TixControl*label.width', 18)
w.option_add(prefix+'*TixControl*label.anchor', Tix.E)
@@ -37,14 +37,14 @@ def RunSample(w):
nb = Tix.NoteBook(w, name='nb', ipadx=6, ipady=6)
nb['bg'] = 'gray'
nb.nbframe['backpagecolor'] = 'gray'
-
+
# Create the two tabs on the notebook. The -underline option
# puts a underline on the first character of the labels of the tabs.
# Keyboard accelerators will be defined automatically according
- # to the underlined character.
+ # to the underlined character.
nb.add('hard_disk', label="Hard Disk", underline=0)
nb.add('network', label="Network", underline=0)
-
+
nb.pack(expand=1, fill=Tix.BOTH, padx=5, pady=5 ,side=Tix.TOP)
#----------------------------------------
@@ -56,62 +56,62 @@ def RunSample(w):
tab=nb.hard_disk
f = Tix.Frame(tab)
common = Tix.Frame(tab)
-
+
f.pack(side=Tix.LEFT, padx=2, pady=2, fill=Tix.BOTH, expand=1)
common.pack(side=Tix.RIGHT, padx=2, fill=Tix.Y)
-
+
a = Tix.Control(f, value=12, label='Access time: ')
w = Tix.Control(f, value=400, label='Write Throughput: ')
r = Tix.Control(f, value=400, label='Read Throughput: ')
c = Tix.Control(f, value=1021, label='Capacity: ')
-
+
a.pack(side=Tix.TOP, padx=20, pady=2)
w.pack(side=Tix.TOP, padx=20, pady=2)
r.pack(side=Tix.TOP, padx=20, pady=2)
c.pack(side=Tix.TOP, padx=20, pady=2)
-
+
# Create the common buttons
createCommonButtons(common)
-
+
#----------------------------------------
- # Create the second page
+ # Create the second page
#----------------------------------------
-
+
tab = nb.network
f = Tix.Frame(tab)
common = Tix.Frame(tab)
-
+
f.pack(side=Tix.LEFT, padx=2, pady=2, fill=Tix.BOTH, expand=1)
common.pack(side=Tix.RIGHT, padx=2, fill=Tix.Y)
-
+
a = Tix.Control(f, value=12, label='Access time: ')
w = Tix.Control(f, value=400, label='Write Throughput: ')
r = Tix.Control(f, value=400, label='Read Throughput: ')
c = Tix.Control(f, value=1021, label='Capacity: ')
u = Tix.Control(f, value=10, label='Users: ')
-
+
a.pack(side=Tix.TOP, padx=20, pady=2)
w.pack(side=Tix.TOP, padx=20, pady=2)
r.pack(side=Tix.TOP, padx=20, pady=2)
c.pack(side=Tix.TOP, padx=20, pady=2)
u.pack(side=Tix.TOP, padx=20, pady=2)
-
+
createCommonButtons(common)
-
+
def doDestroy():
global root
root.destroy()
def createCommonButtons(master):
- ok = Tix.Button(master, name='ok', text='OK', width=6,
- command=doDestroy)
- cancel = Tix.Button(master, name='cancel',
- text='Cancel', width=6,
- command=doDestroy)
-
+ ok = Tix.Button(master, name='ok', text='OK', width=6,
+ command=doDestroy)
+ cancel = Tix.Button(master, name='cancel',
+ text='Cancel', width=6,
+ command=doDestroy)
+
ok.pack(side=Tix.TOP, padx=2, pady=2)
- cancel.pack(side=Tix.TOP, padx=2, pady=2)
+ cancel.pack(side=Tix.TOP, padx=2, pady=2)
if __name__ == '__main__':
root = Tix.Tk()
diff --git a/Demo/tix/samples/OptMenu.py b/Demo/tix/samples/OptMenu.py
index ecb0c86..1d39420 100755
--- a/Demo/tix/samples/OptMenu.py
+++ b/Demo/tix/samples/OptMenu.py
@@ -1,5 +1,5 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
+#
# $Id$
#
# Tix Demostration Program
@@ -16,7 +16,7 @@
import Tix
options = {'text':'Plain Text', 'post':'PostScript', 'html':'HTML',
- 'tex':'LaTeX', 'rtf':'Rich Text Format'}
+ 'tex':'LaTeX', 'rtf':'Rich Text Format'}
def RunSample(w):
global demo_opt_from, demo_opt_to
@@ -27,22 +27,22 @@ def RunSample(w):
top = Tix.Frame(w, bd=1, relief=Tix.RAISED)
from_file = Tix.OptionMenu(top, label="From File Format : ",
- variable=demo_opt_from,
- options = 'label.width 19 label.anchor e menubutton.width 15')
+ variable=demo_opt_from,
+ options = 'label.width 19 label.anchor e menubutton.width 15')
to_file = Tix.OptionMenu(top, label="To File Format : ",
- variable=demo_opt_to,
- options='label.width 19 label.anchor e menubutton.width 15')
+ variable=demo_opt_to,
+ options='label.width 19 label.anchor e menubutton.width 15')
# Add the available options to the two OptionMenu widgets
#
# [Hint] You have to add the options first before you set the
- # global variables "demo_opt_from" and "demo_opt_to". Otherwise
- # the OptionMenu widget will complain about "unknown options"!
+ # global variables "demo_opt_from" and "demo_opt_to". Otherwise
+ # the OptionMenu widget will complain about "unknown options"!
#
for opt in options.keys():
- from_file.add_command(opt, label=options[opt])
- to_file.add_command(opt, label=options[opt])
+ from_file.add_command(opt, label=options[opt])
+ to_file.add_command(opt, label=options[opt])
demo_opt_from.set('html')
demo_opt_to.set('post')
@@ -52,9 +52,9 @@ def RunSample(w):
box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL)
box.add('ok', text='Ok', underline=0, width=6,
- command=lambda w=w: ok_command(w))
+ command=lambda w=w: ok_command(w))
box.add('cancel', text='Cancel', underline=0, width=6,
- command=lambda w=w: w.destroy())
+ command=lambda w=w: w.destroy())
box.pack(side=Tix.BOTTOM, fill=Tix.X)
top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1)
diff --git a/Demo/tix/samples/PanedWin.py b/Demo/tix/samples/PanedWin.py
index bfe10c2..3efc731 100755
--- a/Demo/tix/samples/PanedWin.py
+++ b/Demo/tix/samples/PanedWin.py
@@ -17,7 +17,7 @@
import Tix
-TCL_ALL_EVENTS = 0
+TCL_ALL_EVENTS = 0
def RunSample (root):
panedwin = DemoPanedwin(root)
diff --git a/Demo/tix/samples/PopMenu.py b/Demo/tix/samples/PopMenu.py
index 602eafd..32f3229 100755
--- a/Demo/tix/samples/PopMenu.py
+++ b/Demo/tix/samples/PopMenu.py
@@ -1,6 +1,6 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
#
-# $Id$
+# $Id$
#
# Tix Demostration Program
#
@@ -27,9 +27,9 @@ def RunSample(w):
p.bind_widget(top)
p.bind_widget(but)
- # Set the entries inside the PopupMenu widget.
+ # Set the entries inside the PopupMenu widget.
# [Hint] You have to manipulate the "menu" subwidget.
- # $w.top.p itself is NOT a menu widget.
+ # $w.top.p itself is NOT a menu widget.
# [Hint] Watch carefully how the sub-menu is created
#
p.menu.add_command(label='Desktop', underline=0)
@@ -45,9 +45,9 @@ def RunSample(w):
box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL)
box.add('ok', text='Ok', underline=0, width=6,
- command=lambda w=w: w.destroy())
+ command=lambda w=w: w.destroy())
box.add('cancel', text='Cancel', underline=0, width=6,
- command=lambda w=w: w.destroy())
+ command=lambda w=w: w.destroy())
box.pack(side=Tix.BOTTOM, fill=Tix.X)
top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1)
diff --git a/Demo/tix/samples/SHList1.py b/Demo/tix/samples/SHList1.py
index 0114dc8..7ca7b3e 100755
--- a/Demo/tix/samples/SHList1.py
+++ b/Demo/tix/samples/SHList1.py
@@ -1,5 +1,5 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
+#
# $Id$
#
# Tix Demostration Program
@@ -15,13 +15,13 @@
import Tix
-TCL_ALL_EVENTS = 0
+TCL_ALL_EVENTS = 0
def RunSample (root):
shlist = DemoSHList(root)
shlist.mainloop()
shlist.destroy()
-
+
class DemoSHList:
def __init__(self, w):
self.root = w
@@ -29,7 +29,7 @@ class DemoSHList:
z = w.winfo_toplevel()
z.wm_protocol("WM_DELETE_WINDOW", lambda self=self: self.quitcmd())
-
+
# We create the frame and the ScrolledHList widget
# at the top of the dialog box
#
@@ -61,7 +61,7 @@ class DemoSHList:
hlist=top.a.hlist
- # Let configure the appearance of the HList subwidget
+ # Let configure the appearance of the HList subwidget
#
hlist.config( separator='.', width=25, drawbranch=0, indent=10)
@@ -71,7 +71,7 @@ class DemoSHList:
f=Tix.Frame(hlist, name='sep%d' % count, height=2, width=150,
bd=2, relief=Tix.SUNKEN )
- hlist.add_child( itemtype=Tix.WINDOW,
+ hlist.add_child( itemtype=Tix.WINDOW,
window=f, state=Tix.DISABLED )
hlist.add(boss, itemtype=Tix.TEXT, text=name)
@@ -88,13 +88,13 @@ class DemoSHList:
hlist.add( key, text=name )
# [Hint] Make sure the keys (e.g. 'boss.person') you choose
- # are unique names. If you cannot be sure of this (because of
- # the structure of your database, e.g.) you can use the
- # "add_child" command instead:
+ # are unique names. If you cannot be sure of this (because of
+ # the structure of your database, e.g.) you can use the
+ # "add_child" command instead:
#
# hlist.addchild( boss, text=name)
# ^^^^
- # parent entryPath
+ # parent entryPath
# Use a ButtonBox to hold the buttons.
@@ -129,4 +129,3 @@ class DemoSHList:
if __name__== '__main__' :
root=Tix.Tk()
RunSample(root)
-
diff --git a/Demo/tix/samples/SHList2.py b/Demo/tix/samples/SHList2.py
index e82d1e5..17fd551 100755
--- a/Demo/tix/samples/SHList2.py
+++ b/Demo/tix/samples/SHList2.py
@@ -1,5 +1,5 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
+#
# $Id$
#
# Tix Demostration Program
@@ -13,18 +13,18 @@
# This file demonstrates how to use multiple columns and multiple styles
# in the tixHList widget
#
-# In a tixHList widget, you can have one ore more columns.
+# In a tixHList widget, you can have one ore more columns.
#
import Tix
-TCL_ALL_EVENTS = 0
+TCL_ALL_EVENTS = 0
def RunSample (root):
shlist = DemoSHList(root)
shlist.mainloop()
shlist.destroy()
-
+
class DemoSHList:
def __init__(self, w):
self.root = w
@@ -32,7 +32,7 @@ class DemoSHList:
z = w.winfo_toplevel()
z.wm_protocol("WM_DELETE_WINDOW", lambda self=self: self.quitcmd())
-
+
# We create the frame and the ScrolledHList widget
# at the top of the dialog box
#
@@ -47,7 +47,7 @@ class DemoSHList:
hlist=top.a.hlist
# Create the title for the HList widget
- # >> Notice that we have set the hlist.header subwidget option to true
+ # >> Notice that we have set the hlist.header subwidget option to true
# so that the header is displayed
#
@@ -72,22 +72,22 @@ class DemoSHList:
# This is our little relational database
#
- boss = ('doe', 'John Doe', 'Director')
+ boss = ('doe', 'John Doe', 'Director')
managers = [
- ('jeff', 'Jeff Waxman', 'Manager'),
- ('john', 'John Lee', 'Manager'),
- ('peter', 'Peter Kenson', 'Manager')
+ ('jeff', 'Jeff Waxman', 'Manager'),
+ ('john', 'John Lee', 'Manager'),
+ ('peter', 'Peter Kenson', 'Manager')
]
employees = [
- ('alex', 'john', 'Alex Kellman', 'Clerk'),
- ('alan', 'john', 'Alan Adams', 'Clerk'),
- ('andy', 'peter', 'Andreas Crawford', 'Salesman'),
- ('doug', 'jeff', 'Douglas Bloom', 'Clerk'),
- ('jon', 'peter', 'Jon Baraki', 'Salesman'),
- ('chris', 'jeff', 'Chris Geoffrey', 'Clerk'),
- ('chuck', 'jeff', 'Chuck McLean', 'Cleaner')
+ ('alex', 'john', 'Alex Kellman', 'Clerk'),
+ ('alan', 'john', 'Alan Adams', 'Clerk'),
+ ('andy', 'peter', 'Andreas Crawford', 'Salesman'),
+ ('doug', 'jeff', 'Douglas Bloom', 'Clerk'),
+ ('jon', 'peter', 'Jon Baraki', 'Salesman'),
+ ('chris', 'jeff', 'Chris Geoffrey', 'Clerk'),
+ ('chuck', 'jeff', 'Chuck McLean', 'Cleaner')
]
style['mgr_name'] = Tix.DisplayStyle(Tix.TEXT, refwindow=hlist)
@@ -98,7 +98,7 @@ class DemoSHList:
style['empl_posn'] = Tix.DisplayStyle(Tix.TEXT, padx=8, refwindow=hlist)
- # Let configure the appearance of the HList subwidget
+ # Let configure the appearance of the HList subwidget
#
hlist.config(separator='.', width=25, drawbranch=0, indent=10)
hlist.column_width(0, chars=20)
@@ -124,10 +124,10 @@ class DemoSHList:
for key,mgr,name,posn in employees :
# "." is the separator character we chose above
- entrypath = '.' + mgr + '.' + key
+ entrypath = '.' + mgr + '.' + key
# ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
- # parent entryPath / child's name
+ # parent entryPath / child's name
hlist.add(entrypath, text=name, style=style['empl_name'])
hlist.item_create(entrypath, 1, itemtype=Tix.TEXT,
@@ -166,4 +166,3 @@ class DemoSHList:
if __name__== '__main__' :
root=Tix.Tk()
RunSample(root)
-
diff --git a/Demo/tix/samples/Tree.py b/Demo/tix/samples/Tree.py
index 2fdd7c7..9a7e481 100755
--- a/Demo/tix/samples/Tree.py
+++ b/Demo/tix/samples/Tree.py
@@ -1,5 +1,5 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
+#
# $Id$
#
# Tix Demostration Program
@@ -34,17 +34,17 @@ def RunSample(w):
def adddir(tree, dir):
if dir == '/':
- text = '/'
+ text = '/'
else:
- text = os.path.basename(dir)
+ text = os.path.basename(dir)
tree.hlist.add(dir, itemtype=Tix.IMAGETEXT, text=text,
- image=tree.tk.call('tix', 'getimage', 'folder'))
+ image=tree.tk.call('tix', 'getimage', 'folder'))
try:
- os.listdir(dir)
- tree.setmode(dir, 'open')
+ os.listdir(dir)
+ tree.setmode(dir, 'open')
except os.error:
- # No read permission ?
- pass
+ # No read permission ?
+ pass
# This function is called whenever the user presses the (+) indicator or
# double clicks on a directory whose mode is "open". It loads the files
@@ -57,22 +57,22 @@ def adddir(tree, dir):
def opendir(tree, dir):
entries = tree.hlist.info_children(dir)
if entries:
- # We have already loaded this directory. Let's just
- # show all the child entries
- #
- # Note: since we load the directory only once, it will not be
- # refreshed if the you add or remove files from this
- # directory.
- #
- for entry in entries:
- tree.hlist.show_entry(entry)
+ # We have already loaded this directory. Let's just
+ # show all the child entries
+ #
+ # Note: since we load the directory only once, it will not be
+ # refreshed if the you add or remove files from this
+ # directory.
+ #
+ for entry in entries:
+ tree.hlist.show_entry(entry)
files = os.listdir(dir)
for file in files:
- if os.path.isdir(dir + '/' + file):
- adddir(tree, dir + '/' + file)
- else:
- tree.hlist.add(dir + '/' + file, itemtype=Tix.IMAGETEXT, text=file,
- image=tree.tk.call('tix', 'getimage', 'file'))
+ if os.path.isdir(dir + '/' + file):
+ adddir(tree, dir + '/' + file)
+ else:
+ tree.hlist.add(dir + '/' + file, itemtype=Tix.IMAGETEXT, text=file,
+ image=tree.tk.call('tix', 'getimage', 'file'))
if __name__ == '__main__':
root = Tix.Tk()
diff --git a/Demo/tix/tixwidgets.py b/Demo/tix/tixwidgets.py
index ae7b063..de2e22e 100644
--- a/Demo/tix/tixwidgets.py
+++ b/Demo/tix/tixwidgets.py
@@ -4,38 +4,38 @@
#
# tixwidgets.py --
#
-# For Tix, see http://tix.sourceforge.net
+# For Tix, see http://tix.sourceforge.net
#
-# This is a demo program of some of the Tix widgets available in Python.
-# If you have installed Python & Tix properly, you can execute this as
+# This is a demo program of some of the Tix widgets available in Python.
+# If you have installed Python & Tix properly, you can execute this as
#
-# % python tixwidgets.py
+# % python tixwidgets.py
#
import os, os.path, sys, Tix
from Tkconstants import *
import traceback, tkMessageBox
-TCL_DONT_WAIT = 1<<1
-TCL_WINDOW_EVENTS = 1<<2
-TCL_FILE_EVENTS = 1<<3
-TCL_TIMER_EVENTS = 1<<4
-TCL_IDLE_EVENTS = 1<<5
-TCL_ALL_EVENTS = 0
+TCL_DONT_WAIT = 1<<1
+TCL_WINDOW_EVENTS = 1<<2
+TCL_FILE_EVENTS = 1<<3
+TCL_TIMER_EVENTS = 1<<4
+TCL_IDLE_EVENTS = 1<<5
+TCL_ALL_EVENTS = 0
class Demo:
def __init__(self, top):
self.root = top
self.exit = -1
- self.dir = None # script directory
- self.balloon = None # balloon widget
+ self.dir = None # script directory
+ self.balloon = None # balloon widget
self.useBalloons = Tix.StringVar()
self.useBalloons.set('0')
- self.statusbar = None # status bar widget
- self.welmsg = None # Msg widget
- self.welfont = '' # font name
- self.welsize = '' # font size
+ self.statusbar = None # status bar widget
+ self.welmsg = None # Msg widget
+ self.welfont = '' # font name
+ self.welsize = '' # font size
progname = sys.argv[0]
dirname = os.path.dirname(progname)
@@ -72,7 +72,7 @@ class Demo:
variable=self.useBalloons)
# The trace variable option doesn't seem to work, instead I use 'command'
#apply(w.tk.call, ('trace', 'variable', self.useBalloons, 'w',
- # ToggleHelp))
+ # ToggleHelp))
return w
@@ -130,15 +130,15 @@ class Demo:
# To show Tcl errors - uncomment this to see the listbox bug.
# Tkinter defines a Tcl tkerror procedure that in effect
# silences all background Tcl error reporting.
- # root.tk.eval('if {[info commands tkerror] != ""} {rename tkerror pytkerror}')
+ # root.tk.eval('if {[info commands tkerror] != ""} {rename tkerror pytkerror}')
def quitcmd (self):
"""Quit our mainloop. It is up to you to call root.destroy() after."""
self.exit = 0
def loop(self):
- """This is an explict replacement for _tkinter mainloop()
- It lets you catch keyboard interrupts easier, and avoids
- the 20 msec. dead sleep() which burns a constant CPU."""
+ """This is an explict replacement for _tkinter mainloop()
+ It lets you catch keyboard interrupts easier, and avoids
+ the 20 msec. dead sleep() which burns a constant CPU."""
while self.exit < 0:
# There are 2 whiles here. The outer one lets you continue
# after a ^C interrupt.
@@ -221,9 +221,9 @@ def MkWelcomeBar(top):
b2.pack(side=Tix.LEFT, padx=4, pady=4)
demo.balloon.bind_widget(b1, msg='Choose\na font',
- statusmsg='Choose a font for this page')
+ statusmsg='Choose a font for this page')
demo.balloon.bind_widget(b2, msg='Point size',
- statusmsg='Choose the font size for this page')
+ statusmsg='Choose the font size for this page')
return w
def MkWelcomeText(top):
@@ -233,10 +233,10 @@ def MkWelcomeText(top):
win = w.window
text = 'Welcome to TIX in Python'
title = Tix.Label(win,
- bd=0, width=30, anchor=Tix.N, text=text)
+ bd=0, width=30, anchor=Tix.N, text=text)
msg = Tix.Message(win,
- bd=0, width=400, anchor=Tix.N,
- text='Tix is a set of mega-widgets based on TK. This program \
+ bd=0, width=400, anchor=Tix.N,
+ text='Tix is a set of mega-widgets based on TK. This program \
demonstrates the widgets in the Tix widget set. You can choose the pages \
in this window to look at the corresponding widgets. \n\n\
To quit this program, choose the "File | Exit" command.\n\n\
@@ -250,19 +250,19 @@ def MainTextFont(w):
global demo
if not demo.welmsg:
- return
+ return
font = demo.welfont['value']
point = demo.welsize['value']
if font == 'Times Roman':
- font = 'times'
+ font = 'times'
fontstr = '%s %s' % (font, point)
demo.welmsg['font'] = fontstr
def ToggleHelp():
if demo.useBalloons.get() == '1':
- demo.balloon['state'] = 'both'
+ demo.balloon['state'] = 'both'
else:
- demo.balloon['state'] = 'none'
+ demo.balloon['state'] = 'none'
def MkChoosers(nb, name):
w = nb.page(name)
@@ -307,7 +307,7 @@ def MkCombo(w):
static = Tix.ComboBox(w, label='Static', editable=0, options=options)
editable = Tix.ComboBox(w, label='Editable', editable=1, options=options)
history = Tix.ComboBox(w, label='History', editable=1, history=1,
- anchor=Tix.E, options=options)
+ anchor=Tix.E, options=options)
static.insert(Tix.END, 'January')
static.insert(Tix.END, 'February')
static.insert(Tix.END, 'March')
@@ -340,20 +340,20 @@ states = ['Bengal', 'Delhi', 'Karnataka', 'Tamil Nadu']
def spin_cmd(w, inc):
idx = states.index(demo_spintxt.get()) + inc
if idx < 0:
- idx = len(states) - 1
+ idx = len(states) - 1
elif idx >= len(states):
- idx = 0
+ idx = 0
# following doesn't work.
# return states[idx]
- demo_spintxt.set(states[idx]) # this works
+ demo_spintxt.set(states[idx]) # this works
def spin_validate(w):
global states, demo_spintxt
try:
- i = states.index(demo_spintxt.get())
+ i = states.index(demo_spintxt.get())
except ValueError:
- return states[0]
+ return states[0]
return states[i]
# why this procedure works as opposed to the previous one beats me.
@@ -417,8 +417,8 @@ def MkOptMenu(w):
def MkFileEnt(w):
msg = Tix.Message(w,
- relief=Tix.FLAT, width=240, anchor=Tix.N,
- text='Press the "open file" icon button and a TixFileSelectDialog will popup.')
+ relief=Tix.FLAT, width=240, anchor=Tix.N,
+ text='Press the "open file" icon button and a TixFileSelectDialog will popup.')
ent = Tix.FileEntry(w, label='Select a file : ')
msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3)
ent.pack(side=Tix.TOP, fill=Tix.X, padx=3, pady=3)
@@ -429,8 +429,8 @@ def MkFileBox(w):
and your past selections are recorded.
"""
msg = Tix.Message(w,
- relief=Tix.FLAT, width=240, anchor=Tix.N,
- text='The Tix FileSelectBox is a Motif-style box with various enhancements. For example, you can adjust the size of the two listboxes and your past selections are recorded.')
+ relief=Tix.FLAT, width=240, anchor=Tix.N,
+ text='The Tix FileSelectBox is a Motif-style box with various enhancements. For example, you can adjust the size of the two listboxes and your past selections are recorded.')
box = Tix.FileSelectBox(w)
msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3)
box.pack(side=Tix.TOP, fill=Tix.X, padx=3, pady=3)
@@ -443,8 +443,8 @@ def MkToolBar(w):
options='frame.borderWidth 1'
msg = Tix.Message(w,
- relief=Tix.FLAT, width=240, anchor=Tix.N,
- text='The Select widget is also good for arranging buttons in a tool bar.')
+ relief=Tix.FLAT, width=240, anchor=Tix.N,
+ text='The Select widget is also good for arranging buttons in a tool bar.')
bar = Tix.Frame(w, bd=2, relief=Tix.RAISED)
font = Tix.Select(w, allowzero=1, radio=0, label='', options=options)
para = Tix.Select(w, allowzero=0, radio=1, label='', options=options)
@@ -466,8 +466,8 @@ def MkToolBar(w):
def MkTitle(w):
msg = Tix.Message(w,
- relief=Tix.FLAT, width=240, anchor=Tix.N,
- text='There are many types of "chooser" widgets that allow the user to input different types of information')
+ relief=Tix.FLAT, width=240, anchor=Tix.N,
+ text='There are many types of "chooser" widgets that allow the user to input different types of information')
msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3)
def MkScroll(nb, name):
@@ -494,8 +494,8 @@ def MkSList(w):
top = Tix.Frame(w, width=300, height=330)
bot = Tix.Frame(w)
msg = Tix.Message(top,
- relief=Tix.FLAT, width=200, anchor=Tix.N,
- text='This TixScrolledListBox is configured so that it uses scrollbars only when it is necessary. Use the handles to resize the listbox and watch the scrollbars automatically appear and disappear.')
+ relief=Tix.FLAT, width=200, anchor=Tix.N,
+ text='This TixScrolledListBox is configured so that it uses scrollbars only when it is necessary. Use the handles to resize the listbox and watch the scrollbars automatically appear and disappear.')
list = Tix.ScrolledListBox(top, scrollbar='auto')
list.place(x=50, y=150, width=120, height=80)
@@ -508,8 +508,8 @@ def MkSList(w):
list.listbox.insert(Tix.END, 'Washington')
rh = Tix.ResizeHandle(top, bg='black',
- relief=Tix.RAISED,
- handlesize=8, gridded=1, minwidth=50, minheight=30)
+ relief=Tix.RAISED,
+ handlesize=8, gridded=1, minwidth=50, minheight=30)
btn = Tix.Button(bot, text='Reset', command=lambda w=rh, x=list: SList_reset(w,x))
top.propagate(0)
msg.pack(fill=Tix.X)
@@ -517,7 +517,7 @@ def MkSList(w):
top.pack(expand=1, fill=Tix.BOTH)
bot.pack(fill=Tix.BOTH)
list.bind('<Map>', func=lambda arg=0, rh=rh, list=list:
- list.tk.call('tixDoWhenIdle', str(rh), 'attachwidget', str(list)))
+ list.tk.call('tixDoWhenIdle', str(rh), 'attachwidget', str(list)))
def SList_reset(rh, list):
list.place(x=50, y=150, width=120, height=80)
@@ -539,8 +539,8 @@ def MkSWindow(w):
top = Tix.Frame(w, width=330, height=330)
bot = Tix.Frame(w)
msg = Tix.Message(top,
- relief=Tix.FLAT, width=200, anchor=Tix.N,
- text=text)
+ relief=Tix.FLAT, width=200, anchor=Tix.N,
+ text=text)
win = Tix.ScrolledWindow(top, scrollbar='auto')
@@ -551,8 +551,8 @@ def MkSWindow(w):
win.place(x=30, y=150, width=190, height=120)
rh = Tix.ResizeHandle(top, bg='black',
- relief=Tix.RAISED,
- handlesize=8, gridded=1, minwidth=50, minheight=30)
+ relief=Tix.RAISED,
+ handlesize=8, gridded=1, minwidth=50, minheight=30)
btn = Tix.Button(bot, text='Reset', command=lambda w=rh, x=win: SWindow_reset(w,x))
top.propagate(0)
msg.pack(fill=Tix.X)
@@ -561,7 +561,7 @@ def MkSWindow(w):
bot.pack(fill=Tix.BOTH)
win.bind('<Map>', func=lambda arg=0, rh=rh, win=win:
- win.tk.call('tixDoWhenIdle', str(rh), 'attachwidget', str(win)))
+ win.tk.call('tixDoWhenIdle', str(rh), 'attachwidget', str(win)))
def SWindow_reset(rh, win):
win.place(x=30, y=150, width=190, height=120)
@@ -574,27 +574,27 @@ def MkSText(w):
top = Tix.Frame(w, width=330, height=330)
bot = Tix.Frame(w)
msg = Tix.Message(top,
- relief=Tix.FLAT, width=200, anchor=Tix.N,
- text='The Tix ScrolledWindow widget allows you to scroll any kind of Tk widget. It is more versatile than a scrolled canvas widget.')
+ relief=Tix.FLAT, width=200, anchor=Tix.N,
+ text='The Tix ScrolledWindow widget allows you to scroll any kind of Tk widget. It is more versatile than a scrolled canvas widget.')
win = Tix.ScrolledText(top, scrollbar='auto')
win.text['wrap'] = 'none'
win.text.insert(Tix.END, '''When -scrollbar is set to "auto", the
-scrollbars are shown only when needed.
+scrollbars are shown only when needed.
Additional modifiers can be used to force a
-scrollbar to be shown or hidden. For example,
-"auto -y" means the horizontal scrollbar
-should be shown when needed but the vertical
+scrollbar to be shown or hidden. For example,
+"auto -y" means the horizontal scrollbar
+should be shown when needed but the vertical
scrollbar should always be hidden;
"auto +x" means the vertical scrollbar
-should be shown when needed but the horizontal
+should be shown when needed but the horizontal
scrollbar should always be shown, and so on.'''
)
win.place(x=30, y=150, width=190, height=100)
rh = Tix.ResizeHandle(top, bg='black',
- relief=Tix.RAISED,
- handlesize=8, gridded=1, minwidth=50, minheight=30)
+ relief=Tix.RAISED,
+ handlesize=8, gridded=1, minwidth=50, minheight=30)
btn = Tix.Button(bot, text='Reset', command=lambda w=rh, x=win: SText_reset(w,x))
top.propagate(0)
msg.pack(fill=Tix.X)
@@ -602,7 +602,7 @@ scrollbar should always be shown, and so on.'''
top.pack(expand=1, fill=Tix.BOTH)
bot.pack(fill=Tix.BOTH)
win.bind('<Map>', func=lambda arg=0, rh=rh, win=win:
- win.tk.call('tixDoWhenIdle', str(rh), 'attachwidget', str(win)))
+ win.tk.call('tixDoWhenIdle', str(rh), 'attachwidget', str(win)))
def SText_reset(rh, win):
win.place(x=30, y=150, width=190, height=120)
@@ -628,8 +628,8 @@ def MkPanedWindow(w):
or horizontally.
"""
msg = Tix.Message(w,
- relief=Tix.FLAT, width=240, anchor=Tix.N,
- text='The PanedWindow widget allows the user to interactively manipulate the sizes of several panes. The panes can be arranged either vertically or horizontally.')
+ relief=Tix.FLAT, width=240, anchor=Tix.N,
+ text='The PanedWindow widget allows the user to interactively manipulate the sizes of several panes. The panes can be arranged either vertically or horizontally.')
group = Tix.LabelEntry(w, label='Newsgroup:', options='entry.width 25')
group.entry.insert(0,'comp.lang.python')
pane = Tix.PanedWindow(w, orientation='vertical')
@@ -671,8 +671,8 @@ together with a bitmap, at the same time, inside a TK button widget.
def MkNoteBook(w):
msg = Tix.Message(w,
- relief=Tix.FLAT, width=240, anchor=Tix.N,
- text='The NoteBook widget allows you to layout a complex interface into individual pages.')
+ relief=Tix.FLAT, width=240, anchor=Tix.N,
+ text='The NoteBook widget allows you to layout a complex interface into individual pages.')
# prefix = Tix.OptionName(w)
# if not prefix: prefix = ''
# w.option_add('*' + prefix + '*TixNoteBook*tagPadX', 8)
@@ -738,8 +738,8 @@ def MkDirListWidget(w):
directories.
"""
msg = Tix.Message(w,
- relief=Tix.FLAT, width=240, anchor=Tix.N,
- text='The Tix DirList widget gives a graphical representation of the file system directory and makes it easy for the user to choose and access directories.')
+ relief=Tix.FLAT, width=240, anchor=Tix.N,
+ text='The Tix DirList widget gives a graphical representation of the file system directory and makes it easy for the user to choose and access directories.')
dirlist = Tix.DirList(w, options='hlist.padY 1 hlist.width 25 hlist.height 16')
msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3)
dirlist.pack(side=Tix.TOP, padx=3, pady=3)
@@ -748,8 +748,8 @@ def MkExFileWidget(w):
"""The TixExFileSelectBox widget is more user friendly than the Motif
style FileSelectBox. """
msg = Tix.Message(w,
- relief=Tix.FLAT, width=240, anchor=Tix.N,
- text='The Tix ExFileSelectBox widget is more user friendly than the Motif style FileSelectBox.')
+ relief=Tix.FLAT, width=240, anchor=Tix.N,
+ text='The Tix ExFileSelectBox widget is more user friendly than the Motif style FileSelectBox.')
# There's a bug in the ComboBoxes - the scrolledlistbox is destroyed
box = Tix.ExFileSelectBox(w, bd=2, relief=Tix.RAISED)
msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3)
@@ -758,118 +758,118 @@ def MkExFileWidget(w):
###
### List of all the demos we want to show off
comments = {'widget' : 'Widget Demos', 'image' : 'Image Demos'}
-samples = {'Balloon' : 'Balloon',
- 'Button Box' : 'BtnBox',
- 'Combo Box' : 'ComboBox',
- 'Compound Image' : 'CmpImg',
- 'Directory List' : 'DirList',
- 'Directory Tree' : 'DirTree',
- 'Control' : 'Control',
- 'Notebook' : 'NoteBook',
- 'Option Menu' : 'OptMenu',
- 'Paned Window' : 'PanedWin',
- 'Popup Menu' : 'PopMenu',
- 'ScrolledHList (1)' : 'SHList1',
- 'ScrolledHList (2)' : 'SHList2',
- 'Tree (dynamic)' : 'Tree'
+samples = {'Balloon' : 'Balloon',
+ 'Button Box' : 'BtnBox',
+ 'Combo Box' : 'ComboBox',
+ 'Compound Image' : 'CmpImg',
+ 'Directory List' : 'DirList',
+ 'Directory Tree' : 'DirTree',
+ 'Control' : 'Control',
+ 'Notebook' : 'NoteBook',
+ 'Option Menu' : 'OptMenu',
+ 'Paned Window' : 'PanedWin',
+ 'Popup Menu' : 'PopMenu',
+ 'ScrolledHList (1)' : 'SHList1',
+ 'ScrolledHList (2)' : 'SHList2',
+ 'Tree (dynamic)' : 'Tree'
}
# There are still a lot of demos to be translated:
-## set root {
-## {d "File Selectors" file }
-## {d "Hierachical ListBox" hlist }
-## {d "Tabular ListBox" tlist {c tixTList}}
-## {d "Grid Widget" grid {c tixGrid}}
-## {d "Manager Widgets" manager }
-## {d "Scrolled Widgets" scroll }
-## {d "Miscellaneous Widgets" misc }
-## {d "Image Types" image }
-## }
+## set root {
+## {d "File Selectors" file }
+## {d "Hierachical ListBox" hlist }
+## {d "Tabular ListBox" tlist {c tixTList}}
+## {d "Grid Widget" grid {c tixGrid}}
+## {d "Manager Widgets" manager }
+## {d "Scrolled Widgets" scroll }
+## {d "Miscellaneous Widgets" misc }
+## {d "Image Types" image }
+## }
##
-## set image {
-## {d "Compound Image" cmpimg }
-## {d "XPM Image" xpm {i pixmap}}
-## }
+## set image {
+## {d "Compound Image" cmpimg }
+## {d "XPM Image" xpm {i pixmap}}
+## }
##
-## set cmpimg {
-##done {f "In Buttons" CmpImg.tcl }
-## {f "In NoteBook" CmpImg2.tcl }
-## {f "Notebook Color Tabs" CmpImg4.tcl }
-## {f "Icons" CmpImg3.tcl }
-## }
+## set cmpimg {
+##done {f "In Buttons" CmpImg.tcl }
+## {f "In NoteBook" CmpImg2.tcl }
+## {f "Notebook Color Tabs" CmpImg4.tcl }
+## {f "Icons" CmpImg3.tcl }
+## }
##
-## set xpm {
-## {f "In Button" Xpm.tcl {i pixmap}}
-## {f "In Menu" Xpm1.tcl {i pixmap}}
-## }
+## set xpm {
+## {f "In Button" Xpm.tcl {i pixmap}}
+## {f "In Menu" Xpm1.tcl {i pixmap}}
+## }
##
-## set file {
-##added {f DirList DirList.tcl }
-##added {f DirTree DirTree.tcl }
-## {f DirSelectDialog DirDlg.tcl }
-## {f ExFileSelectDialog EFileDlg.tcl }
-## {f FileSelectDialog FileDlg.tcl }
-## {f FileEntry FileEnt.tcl }
-## }
+## set file {
+##added {f DirList DirList.tcl }
+##added {f DirTree DirTree.tcl }
+## {f DirSelectDialog DirDlg.tcl }
+## {f ExFileSelectDialog EFileDlg.tcl }
+## {f FileSelectDialog FileDlg.tcl }
+## {f FileEntry FileEnt.tcl }
+## }
##
-## set hlist {
-## {f HList HList1.tcl }
-## {f CheckList ChkList.tcl {c tixCheckList}}
-##done {f "ScrolledHList (1)" SHList.tcl }
-##done {f "ScrolledHList (2)" SHList2.tcl }
-##done {f Tree Tree.tcl }
-##done {f "Tree (Dynamic)" DynTree.tcl {v win}}
-## }
+## set hlist {
+## {f HList HList1.tcl }
+## {f CheckList ChkList.tcl {c tixCheckList}}
+##done {f "ScrolledHList (1)" SHList.tcl }
+##done {f "ScrolledHList (2)" SHList2.tcl }
+##done {f Tree Tree.tcl }
+##done {f "Tree (Dynamic)" DynTree.tcl {v win}}
+## }
##
-## set tlist {
-## {f "ScrolledTList (1)" STList1.tcl {c tixTList}}
-## {f "ScrolledTList (2)" STList2.tcl {c tixTList}}
-## }
-## global tcl_platform
-## # This demo hangs windows
-## if {$tcl_platform(platform) != "windows"} {
-##na lappend tlist {f "TList File Viewer" STList3.tcl {c tixTList}}
-## }
+## set tlist {
+## {f "ScrolledTList (1)" STList1.tcl {c tixTList}}
+## {f "ScrolledTList (2)" STList2.tcl {c tixTList}}
+## }
+## global tcl_platform
+## # This demo hangs windows
+## if {$tcl_platform(platform) != "windows"} {
+##na lappend tlist {f "TList File Viewer" STList3.tcl {c tixTList}}
+## }
##
-## set grid {
-##na {f "Simple Grid" SGrid0.tcl {c tixGrid}}
-##na {f "ScrolledGrid" SGrid1.tcl {c tixGrid}}
-##na {f "Editable Grid" EditGrid.tcl {c tixGrid}}
-## }
+## set grid {
+##na {f "Simple Grid" SGrid0.tcl {c tixGrid}}
+##na {f "ScrolledGrid" SGrid1.tcl {c tixGrid}}
+##na {f "Editable Grid" EditGrid.tcl {c tixGrid}}
+## }
##
-## set scroll {
-## {f ScrolledListBox SListBox.tcl }
-## {f ScrolledText SText.tcl }
-## {f ScrolledWindow SWindow.tcl }
-##na {f "Canvas Object View" CObjView.tcl {c tixCObjView}}
-## }
+## set scroll {
+## {f ScrolledListBox SListBox.tcl }
+## {f ScrolledText SText.tcl }
+## {f ScrolledWindow SWindow.tcl }
+##na {f "Canvas Object View" CObjView.tcl {c tixCObjView}}
+## }
##
-## set manager {
-## {f ListNoteBook ListNBK.tcl }
-##done {f NoteBook NoteBook.tcl }
-##done {f PanedWindow PanedWin.tcl }
-## }
+## set manager {
+## {f ListNoteBook ListNBK.tcl }
+##done {f NoteBook NoteBook.tcl }
+##done {f PanedWindow PanedWin.tcl }
+## }
##
-## set misc {
-##done {f Balloon Balloon.tcl }
-##done {f ButtonBox BtnBox.tcl }
-##done {f ComboBox ComboBox.tcl }
-##done {f Control Control.tcl }
-## {f LabelEntry LabEntry.tcl }
-## {f LabelFrame LabFrame.tcl }
-## {f Meter Meter.tcl {c tixMeter}}
-##done {f OptionMenu OptMenu.tcl }
-##done {f PopupMenu PopMenu.tcl }
-## {f Select Select.tcl }
-## {f StdButtonBox StdBBox.tcl }
-## }
+## set misc {
+##done {f Balloon Balloon.tcl }
+##done {f ButtonBox BtnBox.tcl }
+##done {f ComboBox ComboBox.tcl }
+##done {f Control Control.tcl }
+## {f LabelEntry LabEntry.tcl }
+## {f LabelFrame LabFrame.tcl }
+## {f Meter Meter.tcl {c tixMeter}}
+##done {f OptionMenu OptMenu.tcl }
+##done {f PopupMenu PopMenu.tcl }
+## {f Select Select.tcl }
+## {f StdButtonBox StdBBox.tcl }
+## }
##
stypes = {}
stypes['widget'] = ['Balloon', 'Button Box', 'Combo Box', 'Control',
'Directory List', 'Directory Tree',
- 'Notebook', 'Option Menu', 'Popup Menu', 'Paned Window',
- 'ScrolledHList (1)', 'ScrolledHList (2)', 'Tree (dynamic)']
+ 'Notebook', 'Option Menu', 'Popup Menu', 'Paned Window',
+ 'ScrolledHList (1)', 'ScrolledHList (2)', 'Tree (dynamic)']
stypes['image'] = ['Compound Image']
def MkSample(nb, name):
@@ -922,15 +922,15 @@ def MkSample(nb, name):
view['command'] = lambda args=0, w=w,slb=slb,stext=stext,run=run,view=view: Sample_Action(w, slb, stext, run, view, 'view')
for type in ['widget', 'image']:
- if type != 'widget':
- x = Tix.Frame(slb.hlist, bd=2, height=2, width=150,
- relief=Tix.SUNKEN, bg=slb.hlist['bg'])
- slb.hlist.add_child(itemtype=Tix.WINDOW, window=x, state='disabled')
- x = slb.hlist.add_child(itemtype=Tix.TEXT, state='disabled',
- text=comments[type])
- for key in stypes[type]:
- slb.hlist.add_child(x, itemtype=Tix.TEXT, data=key,
- text=key)
+ if type != 'widget':
+ x = Tix.Frame(slb.hlist, bd=2, height=2, width=150,
+ relief=Tix.SUNKEN, bg=slb.hlist['bg'])
+ slb.hlist.add_child(itemtype=Tix.WINDOW, window=x, state='disabled')
+ x = slb.hlist.add_child(itemtype=Tix.TEXT, state='disabled',
+ text=comments[type])
+ for key in stypes[type]:
+ slb.hlist.add_child(x, itemtype=Tix.TEXT, data=key,
+ text=key)
slb.hlist.selection_clear()
run['state'] = 'disabled'
@@ -942,11 +942,11 @@ def Sample_Action(w, slb, stext, run, view, action):
hlist = slb.hlist
anchor = hlist.info_anchor()
if not anchor:
- run['state'] = 'disabled'
- view['state'] = 'disabled'
+ run['state'] = 'disabled'
+ view['state'] = 'disabled'
elif not hlist.info_parent(anchor):
- # a comment
- return
+ # a comment
+ return
run['state'] = 'normal'
view['state'] = 'normal'
@@ -955,17 +955,17 @@ def Sample_Action(w, slb, stext, run, view, action):
prog = samples[key]
if action == 'run':
- exec('import ' + prog)
- w = Tix.Toplevel()
- w.title(title)
- rtn = eval(prog + '.RunSample')
- rtn(w)
+ exec('import ' + prog)
+ w = Tix.Toplevel()
+ w.title(title)
+ rtn = eval(prog + '.RunSample')
+ rtn(w)
elif action == 'view':
- w = Tix.Toplevel()
- w.title('Source view: ' + title)
- LoadFile(w, demo.dir + '/samples/' + prog + '.py')
+ w = Tix.Toplevel()
+ w.title('Source view: ' + title)
+ LoadFile(w, demo.dir + '/samples/' + prog + '.py')
elif action == 'browse':
- ReadFile(stext.text, demo.dir + '/samples/' + prog + '.py')
+ ReadFile(stext.text, demo.dir + '/samples/' + prog + '.py')
def LoadFile(w, fname):
global root
@@ -989,16 +989,15 @@ def ReadFile(w, fname):
w.delete('0.0', Tix.END)
try:
- f = open(fname)
- lines = f.readlines()
- for s in lines:
- w.insert(Tix.END, s)
- f.close()
+ f = open(fname)
+ lines = f.readlines()
+ for s in lines:
+ w.insert(Tix.END, s)
+ f.close()
finally:
-# w.see('1.0')
- w['state'] = old_state
+# w.see('1.0')
+ w['state'] = old_state
if __name__ == '__main__':
root = Tix.Tk()
RunMain(root)
-
diff --git a/Demo/tkinter/guido/AttrDialog.py b/Demo/tkinter/guido/AttrDialog.py
index 4878cb5..86333ad 100755
--- a/Demo/tkinter/guido/AttrDialog.py
+++ b/Demo/tkinter/guido/AttrDialog.py
@@ -16,437 +16,437 @@ from Tkinter import *
class Option:
- varclass = StringVar # May be overridden
-
- def __init__(self, dialog, option):
- self.dialog = dialog
- self.option = option
- self.master = dialog.top
- self.default, self.klass = dialog.options[option]
- self.var = self.varclass(self.master)
- self.frame = Frame(self.master)
- self.frame.pack(fill=X)
- self.label = Label(self.frame, text=(option + ":"))
- self.label.pack(side=LEFT)
- self.update()
- self.addoption()
-
- def refresh(self):
- self.dialog.refresh()
- self.update()
-
- def update(self):
- try:
- self.current = self.dialog.current[self.option]
- except KeyError:
- self.current = self.default
- self.var.set(self.current)
-
- def set(self, e=None): # Should be overridden
- pass
+ varclass = StringVar # May be overridden
+
+ def __init__(self, dialog, option):
+ self.dialog = dialog
+ self.option = option
+ self.master = dialog.top
+ self.default, self.klass = dialog.options[option]
+ self.var = self.varclass(self.master)
+ self.frame = Frame(self.master)
+ self.frame.pack(fill=X)
+ self.label = Label(self.frame, text=(option + ":"))
+ self.label.pack(side=LEFT)
+ self.update()
+ self.addoption()
+
+ def refresh(self):
+ self.dialog.refresh()
+ self.update()
+
+ def update(self):
+ try:
+ self.current = self.dialog.current[self.option]
+ except KeyError:
+ self.current = self.default
+ self.var.set(self.current)
+
+ def set(self, e=None): # Should be overridden
+ pass
class BooleanOption(Option):
- varclass = BooleanVar
+ varclass = BooleanVar
- def addoption(self):
- self.button = Checkbutton(self.frame,
- text='on/off',
- onvalue=1,
- offvalue=0,
- variable=self.var,
- relief=RAISED,
- borderwidth=2,
- command=self.set)
- self.button.pack(side=RIGHT)
+ def addoption(self):
+ self.button = Checkbutton(self.frame,
+ text='on/off',
+ onvalue=1,
+ offvalue=0,
+ variable=self.var,
+ relief=RAISED,
+ borderwidth=2,
+ command=self.set)
+ self.button.pack(side=RIGHT)
class EnumOption(Option):
- def addoption(self):
- self.button = Menubutton(self.frame,
- textvariable=self.var,
- relief=RAISED, borderwidth=2)
- self.button.pack(side=RIGHT)
- self.menu = Menu(self.button)
- self.button['menu'] = self.menu
- for v in self.dialog.classes[self.klass]:
- self.menu.add_radiobutton(
- label=v,
- variable=self.var,
- value=v,
- command=self.set)
+ def addoption(self):
+ self.button = Menubutton(self.frame,
+ textvariable=self.var,
+ relief=RAISED, borderwidth=2)
+ self.button.pack(side=RIGHT)
+ self.menu = Menu(self.button)
+ self.button['menu'] = self.menu
+ for v in self.dialog.classes[self.klass]:
+ self.menu.add_radiobutton(
+ label=v,
+ variable=self.var,
+ value=v,
+ command=self.set)
class StringOption(Option):
- def addoption(self):
- self.entry = Entry(self.frame,
- textvariable=self.var,
- width=10,
- relief=SUNKEN,
- borderwidth=2)
- self.entry.pack(side=RIGHT, fill=X, expand=1)
- self.entry.bind('<Return>', self.set)
+ def addoption(self):
+ self.entry = Entry(self.frame,
+ textvariable=self.var,
+ width=10,
+ relief=SUNKEN,
+ borderwidth=2)
+ self.entry.pack(side=RIGHT, fill=X, expand=1)
+ self.entry.bind('<Return>', self.set)
class ReadonlyOption(Option):
- def addoption(self):
- self.label = Label(self.frame, textvariable=self.var,
- anchor=E)
- self.label.pack(side=RIGHT)
+ def addoption(self):
+ self.label = Label(self.frame, textvariable=self.var,
+ anchor=E)
+ self.label.pack(side=RIGHT)
class Dialog:
- def __init__(self, master):
- self.master = master
- self.fixclasses()
- self.refresh()
- self.top = Toplevel(self.master)
- self.top.title(self.__class__.__name__)
- self.top.minsize(1, 1)
- self.addchoices()
-
- def refresh(self): pass # Must override
-
- def fixclasses(self): pass # May override
-
- def addchoices(self):
- self.choices = {}
- list = []
- for k, dc in self.options.items():
- list.append((k, dc))
- list.sort()
- for k, (d, c) in list:
- try:
- cl = self.classes[c]
- except KeyError:
- cl = 'unknown'
- if type(cl) == TupleType:
- cl = self.enumoption
- elif cl == 'boolean':
- cl = self.booleanoption
- elif cl == 'readonly':
- cl = self.readonlyoption
- else:
- cl = self.stringoption
- self.choices[k] = cl(self, k)
-
- # Must override:
- options = {}
- classes = {}
-
- # May override:
- booleanoption = BooleanOption
- stringoption = StringOption
- enumoption = EnumOption
- readonlyoption = ReadonlyOption
+ def __init__(self, master):
+ self.master = master
+ self.fixclasses()
+ self.refresh()
+ self.top = Toplevel(self.master)
+ self.top.title(self.__class__.__name__)
+ self.top.minsize(1, 1)
+ self.addchoices()
+
+ def refresh(self): pass # Must override
+
+ def fixclasses(self): pass # May override
+
+ def addchoices(self):
+ self.choices = {}
+ list = []
+ for k, dc in self.options.items():
+ list.append((k, dc))
+ list.sort()
+ for k, (d, c) in list:
+ try:
+ cl = self.classes[c]
+ except KeyError:
+ cl = 'unknown'
+ if type(cl) == TupleType:
+ cl = self.enumoption
+ elif cl == 'boolean':
+ cl = self.booleanoption
+ elif cl == 'readonly':
+ cl = self.readonlyoption
+ else:
+ cl = self.stringoption
+ self.choices[k] = cl(self, k)
+
+ # Must override:
+ options = {}
+ classes = {}
+
+ # May override:
+ booleanoption = BooleanOption
+ stringoption = StringOption
+ enumoption = EnumOption
+ readonlyoption = ReadonlyOption
class PackDialog(Dialog):
- def __init__(self, widget):
- self.widget = widget
- Dialog.__init__(self, widget)
-
- def refresh(self):
- self.current = self.widget.info()
- self.current['.class'] = self.widget.winfo_class()
- self.current['.name'] = self.widget._w
-
- class packoption: # Mix-in class
- def set(self, e=None):
- self.current = self.var.get()
- try:
- apply(self.dialog.widget.pack, (),
- {self.option: self.current})
- except TclError, msg:
- print msg
- self.refresh()
-
- class booleanoption(packoption, BooleanOption): pass
- class enumoption(packoption, EnumOption): pass
- class stringoption(packoption, StringOption): pass
- class readonlyoption(packoption, ReadonlyOption): pass
-
- options = {
- '.class': (None, 'Class'),
- '.name': (None, 'Name'),
- 'after': (None, 'Widget'),
- 'anchor': ('center', 'Anchor'),
- 'before': (None, 'Widget'),
- 'expand': ('no', 'Boolean'),
- 'fill': ('none', 'Fill'),
- 'in': (None, 'Widget'),
- 'ipadx': (0, 'Pad'),
- 'ipady': (0, 'Pad'),
- 'padx': (0, 'Pad'),
- 'pady': (0, 'Pad'),
- 'side': ('top', 'Side'),
- }
-
- classes = {
- 'Anchor': (N, NE, E, SE, S, SW, W, NW, CENTER),
- 'Boolean': 'boolean',
- 'Class': 'readonly',
- 'Expand': 'boolean',
- 'Fill': (NONE, X, Y, BOTH),
- 'Name': 'readonly',
- 'Pad': 'pixel',
- 'Side': (TOP, RIGHT, BOTTOM, LEFT),
- 'Widget': 'readonly',
- }
+ def __init__(self, widget):
+ self.widget = widget
+ Dialog.__init__(self, widget)
+
+ def refresh(self):
+ self.current = self.widget.info()
+ self.current['.class'] = self.widget.winfo_class()
+ self.current['.name'] = self.widget._w
+
+ class packoption: # Mix-in class
+ def set(self, e=None):
+ self.current = self.var.get()
+ try:
+ apply(self.dialog.widget.pack, (),
+ {self.option: self.current})
+ except TclError, msg:
+ print msg
+ self.refresh()
+
+ class booleanoption(packoption, BooleanOption): pass
+ class enumoption(packoption, EnumOption): pass
+ class stringoption(packoption, StringOption): pass
+ class readonlyoption(packoption, ReadonlyOption): pass
+
+ options = {
+ '.class': (None, 'Class'),
+ '.name': (None, 'Name'),
+ 'after': (None, 'Widget'),
+ 'anchor': ('center', 'Anchor'),
+ 'before': (None, 'Widget'),
+ 'expand': ('no', 'Boolean'),
+ 'fill': ('none', 'Fill'),
+ 'in': (None, 'Widget'),
+ 'ipadx': (0, 'Pad'),
+ 'ipady': (0, 'Pad'),
+ 'padx': (0, 'Pad'),
+ 'pady': (0, 'Pad'),
+ 'side': ('top', 'Side'),
+ }
+
+ classes = {
+ 'Anchor': (N, NE, E, SE, S, SW, W, NW, CENTER),
+ 'Boolean': 'boolean',
+ 'Class': 'readonly',
+ 'Expand': 'boolean',
+ 'Fill': (NONE, X, Y, BOTH),
+ 'Name': 'readonly',
+ 'Pad': 'pixel',
+ 'Side': (TOP, RIGHT, BOTTOM, LEFT),
+ 'Widget': 'readonly',
+ }
class RemotePackDialog(PackDialog):
- def __init__(self, master, app, widget):
- self.master = master
- self.app = app
- self.widget = widget
- self.refresh()
- self.top = Toplevel(self.master)
- self.top.title(self.app + ' PackDialog')
- self.top.minsize(1, 1)
- self.addchoices()
-
- def refresh(self):
- try:
- words = self.master.tk.splitlist(
- self.master.send(self.app,
- 'pack',
- 'info',
- self.widget))
- except TclError, msg:
- print msg
- return
- dict = {}
- for i in range(0, len(words), 2):
- key = words[i][1:]
- value = words[i+1]
- dict[key] = value
- dict['.class'] = self.master.send(self.app,
- 'winfo',
- 'class',
- self.widget)
- dict['.name'] = self.widget
- self.current = dict
-
- class remotepackoption: # Mix-in class
- def set(self, e=None):
- self.current = self.var.get()
- try:
- self.dialog.master.send(
- self.dialog.app,
- 'pack',
- 'config',
- self.dialog.widget,
- '-'+self.option,
- self.dialog.master.tk.merge(
- self.current))
- except TclError, msg:
- print msg
- self.refresh()
-
- class booleanoption(remotepackoption, BooleanOption): pass
- class enumoption(remotepackoption, EnumOption): pass
- class stringoption(remotepackoption, StringOption): pass
- class readonlyoption(remotepackoption, ReadonlyOption): pass
+ def __init__(self, master, app, widget):
+ self.master = master
+ self.app = app
+ self.widget = widget
+ self.refresh()
+ self.top = Toplevel(self.master)
+ self.top.title(self.app + ' PackDialog')
+ self.top.minsize(1, 1)
+ self.addchoices()
+
+ def refresh(self):
+ try:
+ words = self.master.tk.splitlist(
+ self.master.send(self.app,
+ 'pack',
+ 'info',
+ self.widget))
+ except TclError, msg:
+ print msg
+ return
+ dict = {}
+ for i in range(0, len(words), 2):
+ key = words[i][1:]
+ value = words[i+1]
+ dict[key] = value
+ dict['.class'] = self.master.send(self.app,
+ 'winfo',
+ 'class',
+ self.widget)
+ dict['.name'] = self.widget
+ self.current = dict
+
+ class remotepackoption: # Mix-in class
+ def set(self, e=None):
+ self.current = self.var.get()
+ try:
+ self.dialog.master.send(
+ self.dialog.app,
+ 'pack',
+ 'config',
+ self.dialog.widget,
+ '-'+self.option,
+ self.dialog.master.tk.merge(
+ self.current))
+ except TclError, msg:
+ print msg
+ self.refresh()
+
+ class booleanoption(remotepackoption, BooleanOption): pass
+ class enumoption(remotepackoption, EnumOption): pass
+ class stringoption(remotepackoption, StringOption): pass
+ class readonlyoption(remotepackoption, ReadonlyOption): pass
class WidgetDialog(Dialog):
- def __init__(self, widget):
- self.widget = widget
- self.klass = widget.winfo_class()
- Dialog.__init__(self, widget)
-
- def fixclasses(self):
- if self.addclasses.has_key(self.klass):
- classes = {}
- for c in (self.classes,
- self.addclasses[self.klass]):
- for k in c.keys():
- classes[k] = c[k]
- self.classes = classes
-
- def refresh(self):
- self.configuration = self.widget.config()
- self.update()
- self.current['.class'] = self.widget.winfo_class()
- self.current['.name'] = self.widget._w
-
- def update(self):
- self.current = {}
- self.options = {}
- for k, v in self.configuration.items():
- if len(v) > 4:
- self.current[k] = v[4]
- self.options[k] = v[3], v[2] # default, klass
- self.options['.class'] = (None, 'Class')
- self.options['.name'] = (None, 'Name')
-
- class widgetoption: # Mix-in class
- def set(self, e=None):
- self.current = self.var.get()
- try:
- self.dialog.widget[self.option] = self.current
- except TclError, msg:
- print msg
- self.refresh()
-
- class booleanoption(widgetoption, BooleanOption): pass
- class enumoption(widgetoption, EnumOption): pass
- class stringoption(widgetoption, StringOption): pass
- class readonlyoption(widgetoption, ReadonlyOption): pass
-
- # Universal classes
- classes = {
- 'Anchor': (N, NE, E, SE, S, SW, W, NW, CENTER),
- 'Aspect': 'integer',
- 'Background': 'color',
- 'Bitmap': 'bitmap',
- 'BorderWidth': 'pixel',
- 'Class': 'readonly',
- 'CloseEnough': 'double',
- 'Command': 'command',
- 'Confine': 'boolean',
- 'Cursor': 'cursor',
- 'CursorWidth': 'pixel',
- 'DisabledForeground': 'color',
- 'ExportSelection': 'boolean',
- 'Font': 'font',
- 'Foreground': 'color',
- 'From': 'integer',
- 'Geometry': 'geometry',
- 'Height': 'pixel',
- 'InsertWidth': 'time',
- 'Justify': (LEFT, CENTER, RIGHT),
- 'Label': 'string',
- 'Length': 'pixel',
- 'MenuName': 'widget',
- 'Name': 'readonly',
- 'OffTime': 'time',
- 'OnTime': 'time',
- 'Orient': (HORIZONTAL, VERTICAL),
- 'Pad': 'pixel',
- 'Relief': (RAISED, SUNKEN, FLAT, RIDGE, GROOVE),
- 'RepeatDelay': 'time',
- 'RepeatInterval': 'time',
- 'ScrollCommand': 'command',
- 'ScrollIncrement': 'pixel',
- 'ScrollRegion': 'rectangle',
- 'ShowValue': 'boolean',
- 'SetGrid': 'boolean',
- 'Sliderforeground': 'color',
- 'SliderLength': 'pixel',
- 'Text': 'string',
- 'TickInterval': 'integer',
- 'To': 'integer',
- 'Underline': 'index',
- 'Variable': 'variable',
- 'Value': 'string',
- 'Width': 'pixel',
- 'Wrap': (NONE, CHAR, WORD),
- }
-
- # Classes that (may) differ per widget type
- _tristate = {'State': (NORMAL, ACTIVE, DISABLED)}
- _bistate = {'State': (NORMAL, DISABLED)}
- addclasses = {
- 'Button': _tristate,
- 'Radiobutton': _tristate,
- 'Checkbutton': _tristate,
- 'Entry': _bistate,
- 'Text': _bistate,
- 'Menubutton': _tristate,
- 'Slider': _bistate,
- }
+ def __init__(self, widget):
+ self.widget = widget
+ self.klass = widget.winfo_class()
+ Dialog.__init__(self, widget)
+
+ def fixclasses(self):
+ if self.addclasses.has_key(self.klass):
+ classes = {}
+ for c in (self.classes,
+ self.addclasses[self.klass]):
+ for k in c.keys():
+ classes[k] = c[k]
+ self.classes = classes
+
+ def refresh(self):
+ self.configuration = self.widget.config()
+ self.update()
+ self.current['.class'] = self.widget.winfo_class()
+ self.current['.name'] = self.widget._w
+
+ def update(self):
+ self.current = {}
+ self.options = {}
+ for k, v in self.configuration.items():
+ if len(v) > 4:
+ self.current[k] = v[4]
+ self.options[k] = v[3], v[2] # default, klass
+ self.options['.class'] = (None, 'Class')
+ self.options['.name'] = (None, 'Name')
+
+ class widgetoption: # Mix-in class
+ def set(self, e=None):
+ self.current = self.var.get()
+ try:
+ self.dialog.widget[self.option] = self.current
+ except TclError, msg:
+ print msg
+ self.refresh()
+
+ class booleanoption(widgetoption, BooleanOption): pass
+ class enumoption(widgetoption, EnumOption): pass
+ class stringoption(widgetoption, StringOption): pass
+ class readonlyoption(widgetoption, ReadonlyOption): pass
+
+ # Universal classes
+ classes = {
+ 'Anchor': (N, NE, E, SE, S, SW, W, NW, CENTER),
+ 'Aspect': 'integer',
+ 'Background': 'color',
+ 'Bitmap': 'bitmap',
+ 'BorderWidth': 'pixel',
+ 'Class': 'readonly',
+ 'CloseEnough': 'double',
+ 'Command': 'command',
+ 'Confine': 'boolean',
+ 'Cursor': 'cursor',
+ 'CursorWidth': 'pixel',
+ 'DisabledForeground': 'color',
+ 'ExportSelection': 'boolean',
+ 'Font': 'font',
+ 'Foreground': 'color',
+ 'From': 'integer',
+ 'Geometry': 'geometry',
+ 'Height': 'pixel',
+ 'InsertWidth': 'time',
+ 'Justify': (LEFT, CENTER, RIGHT),
+ 'Label': 'string',
+ 'Length': 'pixel',
+ 'MenuName': 'widget',
+ 'Name': 'readonly',
+ 'OffTime': 'time',
+ 'OnTime': 'time',
+ 'Orient': (HORIZONTAL, VERTICAL),
+ 'Pad': 'pixel',
+ 'Relief': (RAISED, SUNKEN, FLAT, RIDGE, GROOVE),
+ 'RepeatDelay': 'time',
+ 'RepeatInterval': 'time',
+ 'ScrollCommand': 'command',
+ 'ScrollIncrement': 'pixel',
+ 'ScrollRegion': 'rectangle',
+ 'ShowValue': 'boolean',
+ 'SetGrid': 'boolean',
+ 'Sliderforeground': 'color',
+ 'SliderLength': 'pixel',
+ 'Text': 'string',
+ 'TickInterval': 'integer',
+ 'To': 'integer',
+ 'Underline': 'index',
+ 'Variable': 'variable',
+ 'Value': 'string',
+ 'Width': 'pixel',
+ 'Wrap': (NONE, CHAR, WORD),
+ }
+
+ # Classes that (may) differ per widget type
+ _tristate = {'State': (NORMAL, ACTIVE, DISABLED)}
+ _bistate = {'State': (NORMAL, DISABLED)}
+ addclasses = {
+ 'Button': _tristate,
+ 'Radiobutton': _tristate,
+ 'Checkbutton': _tristate,
+ 'Entry': _bistate,
+ 'Text': _bistate,
+ 'Menubutton': _tristate,
+ 'Slider': _bistate,
+ }
class RemoteWidgetDialog(WidgetDialog):
- def __init__(self, master, app, widget):
- self.app = app
- self.widget = widget
- self.klass = master.send(self.app,
- 'winfo',
- 'class',
- self.widget)
- Dialog.__init__(self, master)
-
- def refresh(self):
- try:
- items = self.master.tk.splitlist(
- self.master.send(self.app,
- self.widget,
- 'config'))
- except TclError, msg:
- print msg
- return
- dict = {}
- for item in items:
- words = self.master.tk.splitlist(item)
- key = words[0][1:]
- value = (key,) + words[1:]
- dict[key] = value
- self.configuration = dict
- self.update()
- self.current['.class'] = self.klass
- self.current['.name'] = self.widget
-
- class remotewidgetoption: # Mix-in class
- def set(self, e=None):
- self.current = self.var.get()
- try:
- self.dialog.master.send(
- self.dialog.app,
- self.dialog.widget,
- 'config',
- '-'+self.option,
- self.current)
- except TclError, msg:
- print msg
- self.refresh()
-
- class booleanoption(remotewidgetoption, BooleanOption): pass
- class enumoption(remotewidgetoption, EnumOption): pass
- class stringoption(remotewidgetoption, StringOption): pass
- class readonlyoption(remotewidgetoption, ReadonlyOption): pass
+ def __init__(self, master, app, widget):
+ self.app = app
+ self.widget = widget
+ self.klass = master.send(self.app,
+ 'winfo',
+ 'class',
+ self.widget)
+ Dialog.__init__(self, master)
+
+ def refresh(self):
+ try:
+ items = self.master.tk.splitlist(
+ self.master.send(self.app,
+ self.widget,
+ 'config'))
+ except TclError, msg:
+ print msg
+ return
+ dict = {}
+ for item in items:
+ words = self.master.tk.splitlist(item)
+ key = words[0][1:]
+ value = (key,) + words[1:]
+ dict[key] = value
+ self.configuration = dict
+ self.update()
+ self.current['.class'] = self.klass
+ self.current['.name'] = self.widget
+
+ class remotewidgetoption: # Mix-in class
+ def set(self, e=None):
+ self.current = self.var.get()
+ try:
+ self.dialog.master.send(
+ self.dialog.app,
+ self.dialog.widget,
+ 'config',
+ '-'+self.option,
+ self.current)
+ except TclError, msg:
+ print msg
+ self.refresh()
+
+ class booleanoption(remotewidgetoption, BooleanOption): pass
+ class enumoption(remotewidgetoption, EnumOption): pass
+ class stringoption(remotewidgetoption, StringOption): pass
+ class readonlyoption(remotewidgetoption, ReadonlyOption): pass
def test():
- import sys
- root = Tk()
- root.minsize(1, 1)
- if sys.argv[1:]:
- remotetest(root, sys.argv[1])
- else:
- frame = Frame(root, name='frame')
- frame.pack(expand=1, fill=BOTH)
- button = Button(frame, name='button', text='button')
- button.pack(expand=1)
- canvas = Canvas(frame, name='canvas')
- canvas.pack()
- fpd = PackDialog(frame)
- fwd = WidgetDialog(frame)
- bpd = PackDialog(button)
- bwd = WidgetDialog(button)
- cpd = PackDialog(canvas)
- cwd = WidgetDialog(canvas)
- root.mainloop()
+ import sys
+ root = Tk()
+ root.minsize(1, 1)
+ if sys.argv[1:]:
+ remotetest(root, sys.argv[1])
+ else:
+ frame = Frame(root, name='frame')
+ frame.pack(expand=1, fill=BOTH)
+ button = Button(frame, name='button', text='button')
+ button.pack(expand=1)
+ canvas = Canvas(frame, name='canvas')
+ canvas.pack()
+ fpd = PackDialog(frame)
+ fwd = WidgetDialog(frame)
+ bpd = PackDialog(button)
+ bwd = WidgetDialog(button)
+ cpd = PackDialog(canvas)
+ cwd = WidgetDialog(canvas)
+ root.mainloop()
def remotetest(root, app):
- from listtree import listtree
- list = listtree(root, app)
- list.bind('<Any-Double-1>', opendialogs)
- list.app = app # Pass it on to handler
+ from listtree import listtree
+ list = listtree(root, app)
+ list.bind('<Any-Double-1>', opendialogs)
+ list.app = app # Pass it on to handler
def opendialogs(e):
- import string
- list = e.widget
- sel = list.curselection()
- for i in sel:
- item = list.get(i)
- widget = string.split(item)[0]
- RemoteWidgetDialog(list, list.app, widget)
- if widget == '.': continue
- try:
- RemotePackDialog(list, list.app, widget)
- except TclError, msg:
- print msg
+ import string
+ list = e.widget
+ sel = list.curselection()
+ for i in sel:
+ item = list.get(i)
+ widget = string.split(item)[0]
+ RemoteWidgetDialog(list, list.app, widget)
+ if widget == '.': continue
+ try:
+ RemotePackDialog(list, list.app, widget)
+ except TclError, msg:
+ print msg
test()
diff --git a/Demo/tkinter/guido/ManPage.py b/Demo/tkinter/guido/ManPage.py
index ccd21b4..7d6fe00 100755
--- a/Demo/tkinter/guido/ManPage.py
+++ b/Demo/tkinter/guido/ManPage.py
@@ -12,173 +12,173 @@ ITALICFONT = '*-Courier-Medium-O-Normal-*-120-*'
# XXX Recognizing footers is system dependent
# (This one works for IRIX 5.2 and Solaris 2.2)
footerprog = regex.compile(
- '^ Page [1-9][0-9]*[ \t]+\|^.*Last change:.*[1-9][0-9]*\n')
+ '^ Page [1-9][0-9]*[ \t]+\|^.*Last change:.*[1-9][0-9]*\n')
emptyprog = regex.compile('^[ \t]*\n')
ulprog = regex.compile('^[ \t]*[Xv!_][Xv!_ \t]*\n')
# Basic Man Page class -- does not disable editing
class EditableManPage(ScrolledText):
- # Initialize instance
- def __init__(self, master=None, **cnf):
- # Initialize base class
- apply(ScrolledText.__init__, (self, master), cnf)
-
- # Define tags for formatting styles
- self.tag_config('X', underline=1)
- self.tag_config('!', font=BOLDFONT)
- self.tag_config('_', font=ITALICFONT)
-
- # Set state to idle
- self.fp = None
- self.lineno = 0
-
- # Test whether we are busy parsing a file
- def busy(self):
- return self.fp != None
-
- # Ensure we're not busy
- def kill(self):
- if self.busy():
- self._endparser()
-
- # Parse a file, in the background
- def asyncparsefile(self, fp):
- self._startparser(fp)
- self.tk.createfilehandler(fp, _tkinter.READABLE,
- self._filehandler)
-
- parsefile = asyncparsefile # Alias
-
- # I/O handler used by background parsing
- def _filehandler(self, fp, mask):
- nextline = self.fp.readline()
- if not nextline:
- self._endparser()
- return
- self._parseline(nextline)
-
- # Parse a file, now (cannot be aborted)
- def syncparsefile(self, fp):
- from select import select
- def avail(fp=fp, tout=0.0, select=select):
- return select([fp], [], [], tout)[0]
- height = self.getint(self['height'])
- self._startparser(fp)
- while 1:
- nextline = fp.readline()
- if not nextline:
- break
- self._parseline(nextline)
- self._endparser()
-
- # Initialize parsing from a particular file -- must not be busy
- def _startparser(self, fp):
- if self.busy():
- raise RuntimeError, 'startparser: still busy'
- fp.fileno() # Test for file-ness
- self.fp = fp
- self.lineno = 0
- self.ok = 0
- self.empty = 0
- self.buffer = None
- savestate = self['state']
- self['state'] = NORMAL
- self.delete('1.0', END)
- self['state'] = savestate
-
- # End parsing -- must be busy, need not be at EOF
- def _endparser(self):
- if not self.busy():
- raise RuntimeError, 'endparser: not busy'
- if self.buffer:
- self._parseline('')
- try:
- self.tk.deletefilehandler(self.fp)
- except TclError, msg:
- pass
- self.fp.close()
- self.fp = None
- del self.ok, self.empty, self.buffer
-
- # Parse a single line
- def _parseline(self, nextline):
- if not self.buffer:
- # Save this line -- we need one line read-ahead
- self.buffer = nextline
- return
- if emptyprog.match(self.buffer) >= 0:
- # Buffered line was empty -- set a flag
- self.empty = 1
- self.buffer = nextline
- return
- textline = self.buffer
- if ulprog.match(nextline) >= 0:
- # Next line is properties for buffered line
- propline = nextline
- self.buffer = None
- else:
- # Next line is read-ahead
- propline = None
- self.buffer = nextline
- if not self.ok:
- # First non blank line after footer must be header
- # -- skip that too
- self.ok = 1
- self.empty = 0
- return
- if footerprog.match(textline) >= 0:
- # Footer -- start skipping until next non-blank line
- self.ok = 0
- self.empty = 0
- return
- savestate = self['state']
- self['state'] = NORMAL
- if TkVersion >= 4.0:
- self.mark_set('insert', 'end-1c')
- else:
- self.mark_set('insert', END)
- if self.empty:
- # One or more previous lines were empty
- # -- insert one blank line in the text
- self._insert_prop('\n')
- self.lineno = self.lineno + 1
- self.empty = 0
- if not propline:
- # No properties
- self._insert_prop(textline)
- else:
- # Search for properties
- p = ''
- j = 0
- for i in range(min(len(propline), len(textline))):
- if propline[i] != p:
- if j < i:
- self._insert_prop(textline[j:i], p)
- j = i
- p = propline[i]
- self._insert_prop(textline[j:])
- self.lineno = self.lineno + 1
- self['state'] = savestate
-
- # Insert a string at the end, with at most one property (tag)
- def _insert_prop(self, str, prop = ' '):
- here = self.index(AtInsert())
- self.insert(AtInsert(), str)
- if TkVersion <= 4.0:
- tags = self.tag_names(here)
- for tag in tags:
- self.tag_remove(tag, here, AtInsert())
- if prop != ' ':
- self.tag_add(prop, here, AtInsert())
+ # Initialize instance
+ def __init__(self, master=None, **cnf):
+ # Initialize base class
+ apply(ScrolledText.__init__, (self, master), cnf)
+
+ # Define tags for formatting styles
+ self.tag_config('X', underline=1)
+ self.tag_config('!', font=BOLDFONT)
+ self.tag_config('_', font=ITALICFONT)
+
+ # Set state to idle
+ self.fp = None
+ self.lineno = 0
+
+ # Test whether we are busy parsing a file
+ def busy(self):
+ return self.fp != None
+
+ # Ensure we're not busy
+ def kill(self):
+ if self.busy():
+ self._endparser()
+
+ # Parse a file, in the background
+ def asyncparsefile(self, fp):
+ self._startparser(fp)
+ self.tk.createfilehandler(fp, _tkinter.READABLE,
+ self._filehandler)
+
+ parsefile = asyncparsefile # Alias
+
+ # I/O handler used by background parsing
+ def _filehandler(self, fp, mask):
+ nextline = self.fp.readline()
+ if not nextline:
+ self._endparser()
+ return
+ self._parseline(nextline)
+
+ # Parse a file, now (cannot be aborted)
+ def syncparsefile(self, fp):
+ from select import select
+ def avail(fp=fp, tout=0.0, select=select):
+ return select([fp], [], [], tout)[0]
+ height = self.getint(self['height'])
+ self._startparser(fp)
+ while 1:
+ nextline = fp.readline()
+ if not nextline:
+ break
+ self._parseline(nextline)
+ self._endparser()
+
+ # Initialize parsing from a particular file -- must not be busy
+ def _startparser(self, fp):
+ if self.busy():
+ raise RuntimeError, 'startparser: still busy'
+ fp.fileno() # Test for file-ness
+ self.fp = fp
+ self.lineno = 0
+ self.ok = 0
+ self.empty = 0
+ self.buffer = None
+ savestate = self['state']
+ self['state'] = NORMAL
+ self.delete('1.0', END)
+ self['state'] = savestate
+
+ # End parsing -- must be busy, need not be at EOF
+ def _endparser(self):
+ if not self.busy():
+ raise RuntimeError, 'endparser: not busy'
+ if self.buffer:
+ self._parseline('')
+ try:
+ self.tk.deletefilehandler(self.fp)
+ except TclError, msg:
+ pass
+ self.fp.close()
+ self.fp = None
+ del self.ok, self.empty, self.buffer
+
+ # Parse a single line
+ def _parseline(self, nextline):
+ if not self.buffer:
+ # Save this line -- we need one line read-ahead
+ self.buffer = nextline
+ return
+ if emptyprog.match(self.buffer) >= 0:
+ # Buffered line was empty -- set a flag
+ self.empty = 1
+ self.buffer = nextline
+ return
+ textline = self.buffer
+ if ulprog.match(nextline) >= 0:
+ # Next line is properties for buffered line
+ propline = nextline
+ self.buffer = None
+ else:
+ # Next line is read-ahead
+ propline = None
+ self.buffer = nextline
+ if not self.ok:
+ # First non blank line after footer must be header
+ # -- skip that too
+ self.ok = 1
+ self.empty = 0
+ return
+ if footerprog.match(textline) >= 0:
+ # Footer -- start skipping until next non-blank line
+ self.ok = 0
+ self.empty = 0
+ return
+ savestate = self['state']
+ self['state'] = NORMAL
+ if TkVersion >= 4.0:
+ self.mark_set('insert', 'end-1c')
+ else:
+ self.mark_set('insert', END)
+ if self.empty:
+ # One or more previous lines were empty
+ # -- insert one blank line in the text
+ self._insert_prop('\n')
+ self.lineno = self.lineno + 1
+ self.empty = 0
+ if not propline:
+ # No properties
+ self._insert_prop(textline)
+ else:
+ # Search for properties
+ p = ''
+ j = 0
+ for i in range(min(len(propline), len(textline))):
+ if propline[i] != p:
+ if j < i:
+ self._insert_prop(textline[j:i], p)
+ j = i
+ p = propline[i]
+ self._insert_prop(textline[j:])
+ self.lineno = self.lineno + 1
+ self['state'] = savestate
+
+ # Insert a string at the end, with at most one property (tag)
+ def _insert_prop(self, str, prop = ' '):
+ here = self.index(AtInsert())
+ self.insert(AtInsert(), str)
+ if TkVersion <= 4.0:
+ tags = self.tag_names(here)
+ for tag in tags:
+ self.tag_remove(tag, here, AtInsert())
+ if prop != ' ':
+ self.tag_add(prop, here, AtInsert())
# Readonly Man Page class -- disables editing, otherwise the same
class ReadonlyManPage(EditableManPage):
- # Initialize instance
- def __init__(self, master=None, **cnf):
- cnf['state'] = DISABLED
- apply(EditableManPage.__init__, (self, master), cnf)
+ # Initialize instance
+ def __init__(self, master=None, **cnf):
+ cnf['state'] = DISABLED
+ apply(EditableManPage.__init__, (self, master), cnf)
# Alias
ManPage = ReadonlyManPage
@@ -187,34 +187,34 @@ ManPage = ReadonlyManPage
# usage: ManPage [manpage]; or ManPage [-f] file
# -f means that the file is nroff -man output run through ul -i
def test():
- import os
- import sys
- # XXX This directory may be different on your system
- MANDIR = '/usr/local/man/mann'
- DEFAULTPAGE = 'Tcl'
- formatted = 0
- if sys.argv[1:] and sys.argv[1] == '-f':
- formatted = 1
- del sys.argv[1]
- if sys.argv[1:]:
- name = sys.argv[1]
- else:
- name = DEFAULTPAGE
- if not formatted:
- if name[-2:-1] != '.':
- name = name + '.n'
- name = os.path.join(MANDIR, name)
- root = Tk()
- root.minsize(1, 1)
- manpage = ManPage(root, relief=SUNKEN, borderwidth=2)
- manpage.pack(expand=1, fill=BOTH)
- if formatted:
- fp = open(name, 'r')
- else:
- fp = os.popen('nroff -man %s | ul -i' % name, 'r')
- manpage.parsefile(fp)
- root.mainloop()
+ import os
+ import sys
+ # XXX This directory may be different on your system
+ MANDIR = '/usr/local/man/mann'
+ DEFAULTPAGE = 'Tcl'
+ formatted = 0
+ if sys.argv[1:] and sys.argv[1] == '-f':
+ formatted = 1
+ del sys.argv[1]
+ if sys.argv[1:]:
+ name = sys.argv[1]
+ else:
+ name = DEFAULTPAGE
+ if not formatted:
+ if name[-2:-1] != '.':
+ name = name + '.n'
+ name = os.path.join(MANDIR, name)
+ root = Tk()
+ root.minsize(1, 1)
+ manpage = ManPage(root, relief=SUNKEN, borderwidth=2)
+ manpage.pack(expand=1, fill=BOTH)
+ if formatted:
+ fp = open(name, 'r')
+ else:
+ fp = os.popen('nroff -man %s | ul -i' % name, 'r')
+ manpage.parsefile(fp)
+ root.mainloop()
# Run the test program when called as a script
if __name__ == '__main__':
- test()
+ test()
diff --git a/Demo/tkinter/guido/MimeViewer.py b/Demo/tkinter/guido/MimeViewer.py
index 2b98579..7494425 100755
--- a/Demo/tkinter/guido/MimeViewer.py
+++ b/Demo/tkinter/guido/MimeViewer.py
@@ -9,135 +9,135 @@ from Tkinter import *
from ScrolledText import ScrolledText
class MimeViewer:
- def __init__(self, parent, title, msg):
- self.title = title
- self.msg = msg
- self.frame = Frame(parent, {'relief': 'raised', 'bd': 2})
- self.frame.packing = {'expand': 0, 'fill': 'both'}
- self.button = Checkbutton(self.frame,
- {'text': title,
- 'command': self.toggle})
- self.button.pack({'anchor': 'w'})
- headertext = msg.getheadertext(
- lambda x: x != 'received' and x[:5] != 'x400-')
- height = countlines(headertext, 4)
- if height:
- self.htext = ScrolledText(self.frame,
- {'height': height,
- 'width': 80,
- 'wrap': 'none',
- 'relief': 'raised',
- 'bd': 2})
- self.htext.packing = {'expand': 1, 'fill': 'both',
- 'after': self.button}
- self.htext.insert('end', headertext)
- else:
- self.htext = Frame(self.frame,
- {'relief': 'raised', 'bd': 2})
- self.htext.packing = {'side': 'top',
- 'ipady': 2,
- 'fill': 'x',
- 'after': self.button}
- body = msg.getbody()
- if type(body) == StringType:
- self.pad = None
- height = countlines(body, 10)
- if height:
- self.btext = ScrolledText(self.frame,
- {'height': height,
- 'width': 80,
- 'wrap': 'none',
- 'relief': 'raised',
- 'bd': 2})
- self.btext.packing = {'expand': 1,
- 'fill': 'both'}
- self.btext.insert('end', body)
- else:
- self.btext = None
- self.parts = None
- else:
- self.pad = Frame(self.frame,
- {'relief': 'flat', 'bd': 2})
- self.pad.packing = {'side': 'left', 'ipadx': 10,
- 'fill': 'y', 'after': self.htext}
- self.parts = []
- for i in range(len(body)):
- p = MimeViewer(self.frame,
- '%s.%d' % (title, i+1),
- body[i])
- self.parts.append(p)
- self.btext = None
- self.collapsed = 1
- def pack(self):
- self.frame.pack(self.frame.packing)
- def destroy(self):
- self.frame.destroy()
- def show(self):
- if self.collapsed:
- self.button.invoke()
- def toggle(self):
- if self.collapsed:
- self.explode()
- else:
- self.collapse()
- def collapse(self):
- self.collapsed = 1
- for comp in self.htext, self.btext, self.pad:
- if comp:
- comp.forget()
- if self.parts:
- for part in self.parts:
- part.frame.forget()
- self.frame.pack({'expand': 0})
- def explode(self):
- self.collapsed = 0
- for comp in self.htext, self.btext, self.pad:
- if comp: comp.pack(comp.packing)
- if self.parts:
- for part in self.parts:
- part.pack()
- self.frame.pack({'expand': 1})
+ def __init__(self, parent, title, msg):
+ self.title = title
+ self.msg = msg
+ self.frame = Frame(parent, {'relief': 'raised', 'bd': 2})
+ self.frame.packing = {'expand': 0, 'fill': 'both'}
+ self.button = Checkbutton(self.frame,
+ {'text': title,
+ 'command': self.toggle})
+ self.button.pack({'anchor': 'w'})
+ headertext = msg.getheadertext(
+ lambda x: x != 'received' and x[:5] != 'x400-')
+ height = countlines(headertext, 4)
+ if height:
+ self.htext = ScrolledText(self.frame,
+ {'height': height,
+ 'width': 80,
+ 'wrap': 'none',
+ 'relief': 'raised',
+ 'bd': 2})
+ self.htext.packing = {'expand': 1, 'fill': 'both',
+ 'after': self.button}
+ self.htext.insert('end', headertext)
+ else:
+ self.htext = Frame(self.frame,
+ {'relief': 'raised', 'bd': 2})
+ self.htext.packing = {'side': 'top',
+ 'ipady': 2,
+ 'fill': 'x',
+ 'after': self.button}
+ body = msg.getbody()
+ if type(body) == StringType:
+ self.pad = None
+ height = countlines(body, 10)
+ if height:
+ self.btext = ScrolledText(self.frame,
+ {'height': height,
+ 'width': 80,
+ 'wrap': 'none',
+ 'relief': 'raised',
+ 'bd': 2})
+ self.btext.packing = {'expand': 1,
+ 'fill': 'both'}
+ self.btext.insert('end', body)
+ else:
+ self.btext = None
+ self.parts = None
+ else:
+ self.pad = Frame(self.frame,
+ {'relief': 'flat', 'bd': 2})
+ self.pad.packing = {'side': 'left', 'ipadx': 10,
+ 'fill': 'y', 'after': self.htext}
+ self.parts = []
+ for i in range(len(body)):
+ p = MimeViewer(self.frame,
+ '%s.%d' % (title, i+1),
+ body[i])
+ self.parts.append(p)
+ self.btext = None
+ self.collapsed = 1
+ def pack(self):
+ self.frame.pack(self.frame.packing)
+ def destroy(self):
+ self.frame.destroy()
+ def show(self):
+ if self.collapsed:
+ self.button.invoke()
+ def toggle(self):
+ if self.collapsed:
+ self.explode()
+ else:
+ self.collapse()
+ def collapse(self):
+ self.collapsed = 1
+ for comp in self.htext, self.btext, self.pad:
+ if comp:
+ comp.forget()
+ if self.parts:
+ for part in self.parts:
+ part.frame.forget()
+ self.frame.pack({'expand': 0})
+ def explode(self):
+ self.collapsed = 0
+ for comp in self.htext, self.btext, self.pad:
+ if comp: comp.pack(comp.packing)
+ if self.parts:
+ for part in self.parts:
+ part.pack()
+ self.frame.pack({'expand': 1})
def countlines(str, limit):
- i = 0
- n = 0
- while n < limit:
- i = string.find(str, '\n', i)
- if i < 0: break
- n = n+1
- i = i+1
- return n
+ i = 0
+ n = 0
+ while n < limit:
+ i = string.find(str, '\n', i)
+ if i < 0: break
+ n = n+1
+ i = i+1
+ return n
def main():
- import sys
- import getopt
- import mhlib
- opts, args = getopt.getopt(sys.argv[1:], '')
- for o, a in opts:
- pass
- message = None
- folder = 'inbox'
- for arg in args:
- if arg[:1] == '+':
- folder = arg[1:]
- else:
- message = string.atoi(arg)
+ import sys
+ import getopt
+ import mhlib
+ opts, args = getopt.getopt(sys.argv[1:], '')
+ for o, a in opts:
+ pass
+ message = None
+ folder = 'inbox'
+ for arg in args:
+ if arg[:1] == '+':
+ folder = arg[1:]
+ else:
+ message = string.atoi(arg)
- mh = mhlib.MH()
- f = mh.openfolder(folder)
- if not message:
- message = f.getcurrent()
- m = f.openmessage(message)
+ mh = mhlib.MH()
+ f = mh.openfolder(folder)
+ if not message:
+ message = f.getcurrent()
+ m = f.openmessage(message)
- root = Tk()
- tk = root.tk
+ root = Tk()
+ tk = root.tk
- top = MimeViewer(root, '+%s/%d' % (folder, message), m)
- top.pack()
- top.show()
+ top = MimeViewer(root, '+%s/%d' % (folder, message), m)
+ top.pack()
+ top.show()
- root.minsize(1, 1)
+ root.minsize(1, 1)
- tk.mainloop()
+ tk.mainloop()
if __name__ == '__main__': main()
diff --git a/Demo/tkinter/guido/ShellWindow.py b/Demo/tkinter/guido/ShellWindow.py
index 98fe30f..609101b 100755
--- a/Demo/tkinter/guido/ShellWindow.py
+++ b/Demo/tkinter/guido/ShellWindow.py
@@ -10,142 +10,142 @@ BUFSIZE = 512
class ShellWindow(ScrolledText):
- def __init__(self, master=None, shell=None, **cnf):
- if not shell:
- try:
- shell = os.environ['SHELL']
- except KeyError:
- shell = '/bin/sh'
- shell = shell + ' -i'
- args = string.split(shell)
- shell = args[0]
-
- apply(ScrolledText.__init__, (self, master), cnf)
- self.pos = '1.0'
- self.bind('<Return>', self.inputhandler)
- self.bind('<Control-c>', self.sigint)
- self.bind('<Control-t>', self.sigterm)
- self.bind('<Control-k>', self.sigkill)
- self.bind('<Control-d>', self.sendeof)
-
- self.pid, self.fromchild, self.tochild = spawn(shell, args)
- self.tk.createfilehandler(self.fromchild, READABLE,
- self.outputhandler)
-
- def outputhandler(self, file, mask):
- data = os.read(file, BUFSIZE)
- if not data:
- self.tk.deletefilehandler(file)
- pid, sts = os.waitpid(self.pid, 0)
- print 'pid', pid, 'status', sts
- self.pid = None
- detail = sts>>8
- cause = sts & 0xff
- if cause == 0:
- msg = "exit status %d" % detail
- else:
- msg = "killed by signal %d" % (cause & 0x7f)
- if cause & 0x80:
- msg = msg + " -- core dumped"
- Dialog(self.master,
- text=msg,
- title="Exit status",
- bitmap='warning',
- default=0,
- strings=('OK',))
- return
- self.insert(END, data)
- self.pos = self.index("end - 1 char")
- self.yview_pickplace(END)
-
- def inputhandler(self, *args):
- if not self.pid:
- self.no_process()
- return "break"
- self.insert(END, "\n")
- line = self.get(self.pos, "end - 1 char")
- self.pos = self.index(END)
- os.write(self.tochild, line)
- return "break"
-
- def sendeof(self, *args):
- if not self.pid:
- self.no_process()
- return "break"
- os.close(self.tochild)
- return "break"
-
- def sendsig(self, sig):
- if not self.pid:
- self.no_process()
- return "break"
- os.kill(self.pid, sig)
- return "break"
-
- def sigint(self, *args):
- return self.sendsig(signal.SIGINT)
-
- def sigquit(self, *args):
- return self.sendsig(signal.SIGQUIT)
-
- def sigterm(self, *args):
- return self.sendsig(signal.SIGTERM)
-
- def sigkill(self, *args):
- return self.sendsig(signal.SIGKILL)
-
- def no_process(self):
- Dialog(self.master,
- text="No active process",
- title="No process",
- bitmap='error',
- default=0,
- strings=('OK',))
-
-MAXFD = 100 # Max number of file descriptors (os.getdtablesize()???)
+ def __init__(self, master=None, shell=None, **cnf):
+ if not shell:
+ try:
+ shell = os.environ['SHELL']
+ except KeyError:
+ shell = '/bin/sh'
+ shell = shell + ' -i'
+ args = string.split(shell)
+ shell = args[0]
+
+ apply(ScrolledText.__init__, (self, master), cnf)
+ self.pos = '1.0'
+ self.bind('<Return>', self.inputhandler)
+ self.bind('<Control-c>', self.sigint)
+ self.bind('<Control-t>', self.sigterm)
+ self.bind('<Control-k>', self.sigkill)
+ self.bind('<Control-d>', self.sendeof)
+
+ self.pid, self.fromchild, self.tochild = spawn(shell, args)
+ self.tk.createfilehandler(self.fromchild, READABLE,
+ self.outputhandler)
+
+ def outputhandler(self, file, mask):
+ data = os.read(file, BUFSIZE)
+ if not data:
+ self.tk.deletefilehandler(file)
+ pid, sts = os.waitpid(self.pid, 0)
+ print 'pid', pid, 'status', sts
+ self.pid = None
+ detail = sts>>8
+ cause = sts & 0xff
+ if cause == 0:
+ msg = "exit status %d" % detail
+ else:
+ msg = "killed by signal %d" % (cause & 0x7f)
+ if cause & 0x80:
+ msg = msg + " -- core dumped"
+ Dialog(self.master,
+ text=msg,
+ title="Exit status",
+ bitmap='warning',
+ default=0,
+ strings=('OK',))
+ return
+ self.insert(END, data)
+ self.pos = self.index("end - 1 char")
+ self.yview_pickplace(END)
+
+ def inputhandler(self, *args):
+ if not self.pid:
+ self.no_process()
+ return "break"
+ self.insert(END, "\n")
+ line = self.get(self.pos, "end - 1 char")
+ self.pos = self.index(END)
+ os.write(self.tochild, line)
+ return "break"
+
+ def sendeof(self, *args):
+ if not self.pid:
+ self.no_process()
+ return "break"
+ os.close(self.tochild)
+ return "break"
+
+ def sendsig(self, sig):
+ if not self.pid:
+ self.no_process()
+ return "break"
+ os.kill(self.pid, sig)
+ return "break"
+
+ def sigint(self, *args):
+ return self.sendsig(signal.SIGINT)
+
+ def sigquit(self, *args):
+ return self.sendsig(signal.SIGQUIT)
+
+ def sigterm(self, *args):
+ return self.sendsig(signal.SIGTERM)
+
+ def sigkill(self, *args):
+ return self.sendsig(signal.SIGKILL)
+
+ def no_process(self):
+ Dialog(self.master,
+ text="No active process",
+ title="No process",
+ bitmap='error',
+ default=0,
+ strings=('OK',))
+
+MAXFD = 100 # Max number of file descriptors (os.getdtablesize()???)
def spawn(prog, args):
- p2cread, p2cwrite = os.pipe()
- c2pread, c2pwrite = os.pipe()
- pid = os.fork()
- if pid == 0:
- # Child
- for i in 0, 1, 2:
- try:
- os.close(i)
- except os.error:
- pass
- if os.dup(p2cread) <> 0:
- sys.stderr.write('popen2: bad read dup\n')
- if os.dup(c2pwrite) <> 1:
- sys.stderr.write('popen2: bad write dup\n')
- if os.dup(c2pwrite) <> 2:
- sys.stderr.write('popen2: bad write dup\n')
- for i in range(3, MAXFD):
- try:
- os.close(i)
- except:
- pass
- try:
- os.execvp(prog, args)
- finally:
- sys.stderr.write('execvp failed\n')
- os._exit(1)
- os.close(p2cread)
- os.close(c2pwrite)
- return pid, c2pread, p2cwrite
+ p2cread, p2cwrite = os.pipe()
+ c2pread, c2pwrite = os.pipe()
+ pid = os.fork()
+ if pid == 0:
+ # Child
+ for i in 0, 1, 2:
+ try:
+ os.close(i)
+ except os.error:
+ pass
+ if os.dup(p2cread) <> 0:
+ sys.stderr.write('popen2: bad read dup\n')
+ if os.dup(c2pwrite) <> 1:
+ sys.stderr.write('popen2: bad write dup\n')
+ if os.dup(c2pwrite) <> 2:
+ sys.stderr.write('popen2: bad write dup\n')
+ for i in range(3, MAXFD):
+ try:
+ os.close(i)
+ except:
+ pass
+ try:
+ os.execvp(prog, args)
+ finally:
+ sys.stderr.write('execvp failed\n')
+ os._exit(1)
+ os.close(p2cread)
+ os.close(c2pwrite)
+ return pid, c2pread, p2cwrite
def test():
- shell = string.join(sys.argv[1:])
- root = Tk()
- root.minsize(1, 1)
- if shell:
- w = ShellWindow(root, shell=shell)
- else:
- w = ShellWindow(root)
- w.pack(expand=1, fill=BOTH)
- w.focus_set()
- w.tk.mainloop()
+ shell = string.join(sys.argv[1:])
+ root = Tk()
+ root.minsize(1, 1)
+ if shell:
+ w = ShellWindow(root, shell=shell)
+ else:
+ w = ShellWindow(root)
+ w.pack(expand=1, fill=BOTH)
+ w.focus_set()
+ w.tk.mainloop()
if __name__ == '__main__':
- test()
+ test()
diff --git a/Demo/tkinter/guido/canvasevents.py b/Demo/tkinter/guido/canvasevents.py
index 60f4096..74ed76f 100644
--- a/Demo/tkinter/guido/canvasevents.py
+++ b/Demo/tkinter/guido/canvasevents.py
@@ -9,7 +9,7 @@ from Canvas import Oval, Group, CanvasText
class Group(Group):
def bind(self, sequence=None, command=None):
- return self.canvas.tag_bind(self.id, sequence, command)
+ return self.canvas.tag_bind(self.id, sequence, command)
class Object:
@@ -33,45 +33,45 @@ class Object:
"""
def __init__(self, canvas, x=0, y=0, fill='red', text='object'):
- self.canvas = canvas
- self.x = x
- self.y = y
- self.pile = None
- self.group = Group(self.canvas)
- self.createitems(fill, text)
+ self.canvas = canvas
+ self.x = x
+ self.y = y
+ self.pile = None
+ self.group = Group(self.canvas)
+ self.createitems(fill, text)
def __str__(self):
- return str(self.group)
+ return str(self.group)
def createitems(self, fill, text):
- self.__oval = Oval(self.canvas,
- self.x-20, self.y-10, self.x+20, self.y+10,
- fill=fill, width=3)
- self.group.addtag_withtag(self.__oval)
- self.__text = CanvasText(self.canvas,
- self.x, self.y, text=text)
- self.group.addtag_withtag(self.__text)
+ self.__oval = Oval(self.canvas,
+ self.x-20, self.y-10, self.x+20, self.y+10,
+ fill=fill, width=3)
+ self.group.addtag_withtag(self.__oval)
+ self.__text = CanvasText(self.canvas,
+ self.x, self.y, text=text)
+ self.group.addtag_withtag(self.__text)
def moveby(self, dx, dy):
- if dx == dy == 0:
- return
- self.group.move(dx, dy)
- self.x = self.x + dx
- self.y = self.y + dy
+ if dx == dy == 0:
+ return
+ self.group.move(dx, dy)
+ self.x = self.x + dx
+ self.y = self.y + dy
def moveto(self, x, y):
- self.moveby(x - self.x, y - self.y)
+ self.moveby(x - self.x, y - self.y)
def transfer(self, pile):
- if self.pile:
- self.pile.delete(self)
- self.pile = None
- self.pile = pile
- if self.pile:
- self.pile.add(self)
+ if self.pile:
+ self.pile.delete(self)
+ self.pile = None
+ self.pile = pile
+ if self.pile:
+ self.pile.add(self)
def tkraise(self):
- self.group.tkraise()
+ self.group.tkraise()
class Bottom(Object):
@@ -79,10 +79,10 @@ class Bottom(Object):
"""An object to serve as the bottom of a pile."""
def createitems(self, *args):
- self.__oval = Oval(self.canvas,
- self.x-20, self.y-10, self.x+20, self.y+10,
- fill='gray', outline='')
- self.group.addtag_withtag(self.__oval)
+ self.__oval = Oval(self.canvas,
+ self.x-20, self.y-10, self.x+20, self.y+10,
+ fill='gray', outline='')
+ self.group.addtag_withtag(self.__oval)
class Pile:
@@ -90,86 +90,86 @@ class Pile:
"""A group of graphical objects."""
def __init__(self, canvas, x, y, tag=None):
- self.canvas = canvas
- self.x = x
- self.y = y
- self.objects = []
- self.bottom = Bottom(self.canvas, self.x, self.y)
- self.group = Group(self.canvas, tag=tag)
- self.group.addtag_withtag(self.bottom.group)
- self.bindhandlers()
+ self.canvas = canvas
+ self.x = x
+ self.y = y
+ self.objects = []
+ self.bottom = Bottom(self.canvas, self.x, self.y)
+ self.group = Group(self.canvas, tag=tag)
+ self.group.addtag_withtag(self.bottom.group)
+ self.bindhandlers()
def bindhandlers(self):
- self.group.bind('<1>', self.clickhandler)
- self.group.bind('<Double-1>', self.doubleclickhandler)
+ self.group.bind('<1>', self.clickhandler)
+ self.group.bind('<Double-1>', self.doubleclickhandler)
def add(self, object):
- self.objects.append(object)
- self.group.addtag_withtag(object.group)
- self.position(object)
+ self.objects.append(object)
+ self.group.addtag_withtag(object.group)
+ self.position(object)
def delete(self, object):
- object.group.dtag(self.group)
- self.objects.remove(object)
+ object.group.dtag(self.group)
+ self.objects.remove(object)
def position(self, object):
- object.tkraise()
- i = self.objects.index(object)
- object.moveto(self.x + i*4, self.y + i*8)
+ object.tkraise()
+ i = self.objects.index(object)
+ object.moveto(self.x + i*4, self.y + i*8)
def clickhandler(self, event):
- pass
+ pass
def doubleclickhandler(self, event):
- pass
+ pass
class MovingPile(Pile):
def bindhandlers(self):
- Pile.bindhandlers(self)
- self.group.bind('<B1-Motion>', self.motionhandler)
- self.group.bind('<ButtonRelease-1>', self.releasehandler)
+ Pile.bindhandlers(self)
+ self.group.bind('<B1-Motion>', self.motionhandler)
+ self.group.bind('<ButtonRelease-1>', self.releasehandler)
movethis = None
def clickhandler(self, event):
- tags = self.canvas.gettags('current')
- for i in range(len(self.objects)):
- o = self.objects[i]
- if o.group.tag in tags:
- break
- else:
- self.movethis = None
- return
- self.movethis = self.objects[i:]
- for o in self.movethis:
- o.tkraise()
- self.lastx = event.x
- self.lasty = event.y
+ tags = self.canvas.gettags('current')
+ for i in range(len(self.objects)):
+ o = self.objects[i]
+ if o.group.tag in tags:
+ break
+ else:
+ self.movethis = None
+ return
+ self.movethis = self.objects[i:]
+ for o in self.movethis:
+ o.tkraise()
+ self.lastx = event.x
+ self.lasty = event.y
doubleclickhandler = clickhandler
def motionhandler(self, event):
- if not self.movethis:
- return
- dx = event.x - self.lastx
- dy = event.y - self.lasty
- self.lastx = event.x
- self.lasty = event.y
- for o in self.movethis:
- o.moveby(dx, dy)
+ if not self.movethis:
+ return
+ dx = event.x - self.lastx
+ dy = event.y - self.lasty
+ self.lastx = event.x
+ self.lasty = event.y
+ for o in self.movethis:
+ o.moveby(dx, dy)
def releasehandler(self, event):
- objects = self.movethis
- if not objects:
- return
- self.movethis = None
- self.finishmove(objects)
+ objects = self.movethis
+ if not objects:
+ return
+ self.movethis = None
+ self.finishmove(objects)
def finishmove(self, objects):
- for o in objects:
- self.position(o)
+ for o in objects:
+ self.position(o)
class Pile1(MovingPile):
@@ -179,29 +179,29 @@ class Pile1(MovingPile):
tag = 'p1'
def __init__(self, demo):
- self.demo = demo
- MovingPile.__init__(self, self.demo.canvas, self.x, self.y, self.tag)
+ self.demo = demo
+ MovingPile.__init__(self, self.demo.canvas, self.x, self.y, self.tag)
def doubleclickhandler(self, event):
- try:
- o = self.objects[-1]
- except IndexError:
- return
- o.transfer(self.other())
- MovingPile.doubleclickhandler(self, event)
+ try:
+ o = self.objects[-1]
+ except IndexError:
+ return
+ o.transfer(self.other())
+ MovingPile.doubleclickhandler(self, event)
def other(self):
- return self.demo.p2
+ return self.demo.p2
def finishmove(self, objects):
- o = objects[0]
- p = self.other()
- x, y = o.x, o.y
- if (x-p.x)**2 + (y-p.y)**2 < (x-self.x)**2 + (y-self.y)**2:
- for o in objects:
- o.transfer(p)
- else:
- MovingPile.finishmove(self, objects)
+ o = objects[0]
+ p = self.other()
+ x, y = o.x, o.y
+ if (x-p.x)**2 + (y-p.y)**2 < (x-self.x)**2 + (y-self.y)**2:
+ for o in objects:
+ o.transfer(p)
+ else:
+ MovingPile.finishmove(self, objects)
class Pile2(Pile1):
@@ -210,26 +210,26 @@ class Pile2(Pile1):
tag = 'p2'
def other(self):
- return self.demo.p1
+ return self.demo.p1
class Demo:
def __init__(self, master):
- self.master = master
- self.canvas = Canvas(master,
- width=200, height=200,
- background='yellow',
- relief=SUNKEN, borderwidth=2)
- self.canvas.pack(expand=1, fill=BOTH)
- self.p1 = Pile1(self)
- self.p2 = Pile2(self)
- o1 = Object(self.canvas, fill='red', text='o1')
- o2 = Object(self.canvas, fill='green', text='o2')
- o3 = Object(self.canvas, fill='light blue', text='o3')
- o1.transfer(self.p1)
- o2.transfer(self.p1)
- o3.transfer(self.p2)
+ self.master = master
+ self.canvas = Canvas(master,
+ width=200, height=200,
+ background='yellow',
+ relief=SUNKEN, borderwidth=2)
+ self.canvas.pack(expand=1, fill=BOTH)
+ self.p1 = Pile1(self)
+ self.p2 = Pile2(self)
+ o1 = Object(self.canvas, fill='red', text='o1')
+ o2 = Object(self.canvas, fill='green', text='o2')
+ o3 = Object(self.canvas, fill='light blue', text='o3')
+ o1.transfer(self.p1)
+ o2.transfer(self.p1)
+ o3.transfer(self.p2)
# Main function, run when invoked as a stand-alone Python program.
diff --git a/Demo/tkinter/guido/dialog.py b/Demo/tkinter/guido/dialog.py
index 1f794ae..50d84b9 100755
--- a/Demo/tkinter/guido/dialog.py
+++ b/Demo/tkinter/guido/dialog.py
@@ -25,11 +25,11 @@ def dialog(master, title, text, bitmap, default, *args):
# 2. Fill the top part with the bitmap and message.
msg = Message(top, width='3i', text=text,
- font='-Adobe-Times-Medium-R-Normal-*-180-*')
+ font='-Adobe-Times-Medium-R-Normal-*-180-*')
msg.pack(side=RIGHT, expand=1, fill=BOTH, padx='3m', pady='3m')
if bitmap:
- bm = Label(top, bitmap=bitmap)
- bm.pack(side=LEFT, padx='3m', pady='3m')
+ bm = Label(top, bitmap=bitmap)
+ bm.pack(side=LEFT, padx='3m', pady='3m')
# 3. Create a row of buttons at the bottom of the dialog.
@@ -37,27 +37,27 @@ def dialog(master, title, text, bitmap, default, *args):
buttons = []
i = 0
for but in args:
- b = Button(bot, text=but, command=lambda v=var,i=i: v.set(i))
- buttons.append(b)
- if i == default:
- bd = Frame(bot, relief=SUNKEN, borderwidth=1)
- bd.pack(side=LEFT, expand=1, padx='3m', pady='2m')
- b.lift()
- b.pack (in_=bd, side=LEFT,
- padx='2m', pady='2m', ipadx='2m', ipady='1m')
- else:
- b.pack (side=LEFT, expand=1,
- padx='3m', pady='3m', ipadx='2m', ipady='1m')
- i = i+1
+ b = Button(bot, text=but, command=lambda v=var,i=i: v.set(i))
+ buttons.append(b)
+ if i == default:
+ bd = Frame(bot, relief=SUNKEN, borderwidth=1)
+ bd.pack(side=LEFT, expand=1, padx='3m', pady='2m')
+ b.lift()
+ b.pack (in_=bd, side=LEFT,
+ padx='2m', pady='2m', ipadx='2m', ipady='1m')
+ else:
+ b.pack (side=LEFT, expand=1,
+ padx='3m', pady='3m', ipadx='2m', ipady='1m')
+ i = i+1
# 4. Set up a binding for <Return>, if there's a default,
# set a grab, and claim the focus too.
if default >= 0:
- w.bind('<Return>',
- lambda e, b=buttons[default], v=var, i=default:
- (b.flash(),
- v.set(i)))
+ w.bind('<Return>',
+ lambda e, b=buttons[default], v=var, i=default:
+ (b.flash(),
+ v.set(i)))
oldFocus = w.focus_get()
w.grab_set()
@@ -75,23 +75,23 @@ def dialog(master, title, text, bitmap, default, *args):
def go():
i = dialog(mainWidget,
- 'Not Responding',
- "The file server isn't responding right now; "
- "I'll keep trying.",
- '',
- -1,
- 'OK')
+ 'Not Responding',
+ "The file server isn't responding right now; "
+ "I'll keep trying.",
+ '',
+ -1,
+ 'OK')
print 'pressed button', i
i = dialog(mainWidget,
- 'File Modified',
- 'File "tcl.h" has been modified since '
- 'the last time it was saved. '
- 'Do you want to save it before exiting the application?',
- 'warning',
- 0,
- 'Save File',
- 'Discard Changes',
- 'Return To Editor')
+ 'File Modified',
+ 'File "tcl.h" has been modified since '
+ 'the last time it was saved. '
+ 'Do you want to save it before exiting the application?',
+ 'warning',
+ 0,
+ 'Save File',
+ 'Discard Changes',
+ 'Return To Editor')
print 'pressed button', i
def test():
diff --git a/Demo/tkinter/guido/electrons.py b/Demo/tkinter/guido/electrons.py
index 97dad2d7..fdc558f 100755
--- a/Demo/tkinter/guido/electrons.py
+++ b/Demo/tkinter/guido/electrons.py
@@ -1,6 +1,6 @@
#! /usr/bin/env python
-# Simulate "electrons" migrating across the screen.
+# Simulate "electrons" migrating across the screen.
# An optional bitmap file in can be in the background.
#
# Usage: electrons [n [bitmapfile]]
@@ -18,74 +18,74 @@ import random
# The graphical interface
class Electrons:
- # Create our objects
- def __init__(self, n, bitmap = None):
- self.n = n
- self.tk = tk = Tk()
- self.canvas = c = Canvas(tk)
- c.pack()
- width, height = tk.getint(c['width']), tk.getint(c['height'])
-
- # Add background bitmap
- if bitmap:
- self.bitmap = c.create_bitmap(width/2, height/2,
- bitmap=bitmap,
- foreground='blue')
-
- self.pieces = []
- x1, y1, x2, y2 = 10,70,14,74
- for i in range(n):
- p = c.create_oval(x1, y1, x2, y2, fill='red')
- self.pieces.append(p)
- y1, y2 = y1 +2, y2 + 2
- self.tk.update()
-
- def random_move(self, n):
- c = self.canvas
- for p in self.pieces:
- x = random.choice(range(-2,4))
- y = random.choice(range(-3,4))
- c.move(p, x, y)
- self.tk.update()
-
- # Run -- allow 500 movemens
- def run(self):
- try:
- for i in range(500):
- self.random_move(self.n)
- except TclError:
- try:
- self.tk.destroy()
- except TclError:
- pass
+ # Create our objects
+ def __init__(self, n, bitmap = None):
+ self.n = n
+ self.tk = tk = Tk()
+ self.canvas = c = Canvas(tk)
+ c.pack()
+ width, height = tk.getint(c['width']), tk.getint(c['height'])
+
+ # Add background bitmap
+ if bitmap:
+ self.bitmap = c.create_bitmap(width/2, height/2,
+ bitmap=bitmap,
+ foreground='blue')
+
+ self.pieces = []
+ x1, y1, x2, y2 = 10,70,14,74
+ for i in range(n):
+ p = c.create_oval(x1, y1, x2, y2, fill='red')
+ self.pieces.append(p)
+ y1, y2 = y1 +2, y2 + 2
+ self.tk.update()
+
+ def random_move(self, n):
+ c = self.canvas
+ for p in self.pieces:
+ x = random.choice(range(-2,4))
+ y = random.choice(range(-3,4))
+ c.move(p, x, y)
+ self.tk.update()
+
+ # Run -- allow 500 movemens
+ def run(self):
+ try:
+ for i in range(500):
+ self.random_move(self.n)
+ except TclError:
+ try:
+ self.tk.destroy()
+ except TclError:
+ pass
# Main program
def main():
- import sys, string
+ import sys, string
- # First argument is number of electrons, default 30
- if sys.argv[1:]:
- n = string.atoi(sys.argv[1])
- else:
- n = 30
+ # First argument is number of electrons, default 30
+ if sys.argv[1:]:
+ n = string.atoi(sys.argv[1])
+ else:
+ n = 30
- # Second argument is bitmap file, default none
- if sys.argv[2:]:
- bitmap = sys.argv[2]
- # Reverse meaning of leading '@' compared to Tk
- if bitmap[0] == '@': bitmap = bitmap[1:]
- else: bitmap = '@' + bitmap
- else:
- bitmap = None
+ # Second argument is bitmap file, default none
+ if sys.argv[2:]:
+ bitmap = sys.argv[2]
+ # Reverse meaning of leading '@' compared to Tk
+ if bitmap[0] == '@': bitmap = bitmap[1:]
+ else: bitmap = '@' + bitmap
+ else:
+ bitmap = None
- # Create the graphical objects...
- h = Electrons(n, bitmap)
+ # Create the graphical objects...
+ h = Electrons(n, bitmap)
- # ...and run!
- h.run()
+ # ...and run!
+ h.run()
# Call main when run as script
if __name__ == '__main__':
- main()
+ main()
diff --git a/Demo/tkinter/guido/hanoi.py b/Demo/tkinter/guido/hanoi.py
index 9e566c4..078c246 100755
--- a/Demo/tkinter/guido/hanoi.py
+++ b/Demo/tkinter/guido/hanoi.py
@@ -16,139 +16,139 @@ from Tkinter import *
# Basic Towers-of-Hanoi algorithm: move n pieces from a to b, using c
# as temporary. For each move, call report()
def hanoi(n, a, b, c, report):
- if n <= 0: return
- hanoi(n-1, a, c, b, report)
- report(n, a, b)
- hanoi(n-1, c, b, a, report)
+ if n <= 0: return
+ hanoi(n-1, a, c, b, report)
+ report(n, a, b)
+ hanoi(n-1, c, b, a, report)
# The graphical interface
class Tkhanoi:
- # Create our objects
- def __init__(self, n, bitmap = None):
- self.n = n
- self.tk = tk = Tk()
- self.canvas = c = Canvas(tk)
- c.pack()
- width, height = tk.getint(c['width']), tk.getint(c['height'])
-
- # Add background bitmap
- if bitmap:
- self.bitmap = c.create_bitmap(width/2, height/2,
- bitmap=bitmap,
- foreground='blue')
-
- # Generate pegs
- pegwidth = 10
- pegheight = height/2
- pegdist = width/3
- x1, y1 = (pegdist-pegwidth)/2, height*1/3
- x2, y2 = x1+pegwidth, y1+pegheight
- self.pegs = []
- p = c.create_rectangle(x1, y1, x2, y2, fill='black')
- self.pegs.append(p)
- x1, x2 = x1+pegdist, x2+pegdist
- p = c.create_rectangle(x1, y1, x2, y2, fill='black')
- self.pegs.append(p)
- x1, x2 = x1+pegdist, x2+pegdist
- p = c.create_rectangle(x1, y1, x2, y2, fill='black')
- self.pegs.append(p)
- self.tk.update()
-
- # Generate pieces
- pieceheight = pegheight/16
- maxpiecewidth = pegdist*2/3
- minpiecewidth = 2*pegwidth
- self.pegstate = [[], [], []]
- self.pieces = {}
- x1, y1 = (pegdist-maxpiecewidth)/2, y2-pieceheight-2
- x2, y2 = x1+maxpiecewidth, y1+pieceheight
- dx = (maxpiecewidth-minpiecewidth) / (2*max(1, n-1))
- for i in range(n, 0, -1):
- p = c.create_rectangle(x1, y1, x2, y2, fill='red')
- self.pieces[i] = p
- self.pegstate[0].append(i)
- x1, x2 = x1 + dx, x2-dx
- y1, y2 = y1 - pieceheight-2, y2-pieceheight-2
- self.tk.update()
- self.tk.after(25)
-
- # Run -- never returns
- def run(self):
- while 1:
- hanoi(self.n, 0, 1, 2, self.report)
- hanoi(self.n, 1, 2, 0, self.report)
- hanoi(self.n, 2, 0, 1, self.report)
- hanoi(self.n, 0, 2, 1, self.report)
- hanoi(self.n, 2, 1, 0, self.report)
- hanoi(self.n, 1, 0, 2, self.report)
-
- # Reporting callback for the actual hanoi function
- def report(self, i, a, b):
- if self.pegstate[a][-1] != i: raise RuntimeError # Assertion
- del self.pegstate[a][-1]
- p = self.pieces[i]
- c = self.canvas
-
- # Lift the piece above peg a
- ax1, ay1, ax2, ay2 = c.bbox(self.pegs[a])
- while 1:
- x1, y1, x2, y2 = c.bbox(p)
- if y2 < ay1: break
- c.move(p, 0, -1)
- self.tk.update()
-
- # Move it towards peg b
- bx1, by1, bx2, by2 = c.bbox(self.pegs[b])
- newcenter = (bx1+bx2)/2
- while 1:
- x1, y1, x2, y2 = c.bbox(p)
- center = (x1+x2)/2
- if center == newcenter: break
- if center > newcenter: c.move(p, -1, 0)
- else: c.move(p, 1, 0)
- self.tk.update()
-
- # Move it down on top of the previous piece
- pieceheight = y2-y1
- newbottom = by2 - pieceheight*len(self.pegstate[b]) - 2
- while 1:
- x1, y1, x2, y2 = c.bbox(p)
- if y2 >= newbottom: break
- c.move(p, 0, 1)
- self.tk.update()
-
- # Update peg state
- self.pegstate[b].append(i)
+ # Create our objects
+ def __init__(self, n, bitmap = None):
+ self.n = n
+ self.tk = tk = Tk()
+ self.canvas = c = Canvas(tk)
+ c.pack()
+ width, height = tk.getint(c['width']), tk.getint(c['height'])
+
+ # Add background bitmap
+ if bitmap:
+ self.bitmap = c.create_bitmap(width/2, height/2,
+ bitmap=bitmap,
+ foreground='blue')
+
+ # Generate pegs
+ pegwidth = 10
+ pegheight = height/2
+ pegdist = width/3
+ x1, y1 = (pegdist-pegwidth)/2, height*1/3
+ x2, y2 = x1+pegwidth, y1+pegheight
+ self.pegs = []
+ p = c.create_rectangle(x1, y1, x2, y2, fill='black')
+ self.pegs.append(p)
+ x1, x2 = x1+pegdist, x2+pegdist
+ p = c.create_rectangle(x1, y1, x2, y2, fill='black')
+ self.pegs.append(p)
+ x1, x2 = x1+pegdist, x2+pegdist
+ p = c.create_rectangle(x1, y1, x2, y2, fill='black')
+ self.pegs.append(p)
+ self.tk.update()
+
+ # Generate pieces
+ pieceheight = pegheight/16
+ maxpiecewidth = pegdist*2/3
+ minpiecewidth = 2*pegwidth
+ self.pegstate = [[], [], []]
+ self.pieces = {}
+ x1, y1 = (pegdist-maxpiecewidth)/2, y2-pieceheight-2
+ x2, y2 = x1+maxpiecewidth, y1+pieceheight
+ dx = (maxpiecewidth-minpiecewidth) / (2*max(1, n-1))
+ for i in range(n, 0, -1):
+ p = c.create_rectangle(x1, y1, x2, y2, fill='red')
+ self.pieces[i] = p
+ self.pegstate[0].append(i)
+ x1, x2 = x1 + dx, x2-dx
+ y1, y2 = y1 - pieceheight-2, y2-pieceheight-2
+ self.tk.update()
+ self.tk.after(25)
+
+ # Run -- never returns
+ def run(self):
+ while 1:
+ hanoi(self.n, 0, 1, 2, self.report)
+ hanoi(self.n, 1, 2, 0, self.report)
+ hanoi(self.n, 2, 0, 1, self.report)
+ hanoi(self.n, 0, 2, 1, self.report)
+ hanoi(self.n, 2, 1, 0, self.report)
+ hanoi(self.n, 1, 0, 2, self.report)
+
+ # Reporting callback for the actual hanoi function
+ def report(self, i, a, b):
+ if self.pegstate[a][-1] != i: raise RuntimeError # Assertion
+ del self.pegstate[a][-1]
+ p = self.pieces[i]
+ c = self.canvas
+
+ # Lift the piece above peg a
+ ax1, ay1, ax2, ay2 = c.bbox(self.pegs[a])
+ while 1:
+ x1, y1, x2, y2 = c.bbox(p)
+ if y2 < ay1: break
+ c.move(p, 0, -1)
+ self.tk.update()
+
+ # Move it towards peg b
+ bx1, by1, bx2, by2 = c.bbox(self.pegs[b])
+ newcenter = (bx1+bx2)/2
+ while 1:
+ x1, y1, x2, y2 = c.bbox(p)
+ center = (x1+x2)/2
+ if center == newcenter: break
+ if center > newcenter: c.move(p, -1, 0)
+ else: c.move(p, 1, 0)
+ self.tk.update()
+
+ # Move it down on top of the previous piece
+ pieceheight = y2-y1
+ newbottom = by2 - pieceheight*len(self.pegstate[b]) - 2
+ while 1:
+ x1, y1, x2, y2 = c.bbox(p)
+ if y2 >= newbottom: break
+ c.move(p, 0, 1)
+ self.tk.update()
+
+ # Update peg state
+ self.pegstate[b].append(i)
# Main program
def main():
- import sys, string
+ import sys, string
- # First argument is number of pegs, default 4
- if sys.argv[1:]:
- n = string.atoi(sys.argv[1])
- else:
- n = 4
+ # First argument is number of pegs, default 4
+ if sys.argv[1:]:
+ n = string.atoi(sys.argv[1])
+ else:
+ n = 4
- # Second argument is bitmap file, default none
- if sys.argv[2:]:
- bitmap = sys.argv[2]
- # Reverse meaning of leading '@' compared to Tk
- if bitmap[0] == '@': bitmap = bitmap[1:]
- else: bitmap = '@' + bitmap
- else:
- bitmap = None
+ # Second argument is bitmap file, default none
+ if sys.argv[2:]:
+ bitmap = sys.argv[2]
+ # Reverse meaning of leading '@' compared to Tk
+ if bitmap[0] == '@': bitmap = bitmap[1:]
+ else: bitmap = '@' + bitmap
+ else:
+ bitmap = None
- # Create the graphical objects...
- h = Tkhanoi(n, bitmap)
+ # Create the graphical objects...
+ h = Tkhanoi(n, bitmap)
- # ...and run!
- h.run()
+ # ...and run!
+ h.run()
# Call main when run as script
if __name__ == '__main__':
- main()
+ main()
diff --git a/Demo/tkinter/guido/hello.py b/Demo/tkinter/guido/hello.py
index 237204f..358a7ec 100755
--- a/Demo/tkinter/guido/hello.py
+++ b/Demo/tkinter/guido/hello.py
@@ -4,14 +4,14 @@ import sys
from Tkinter import *
def main():
- root = Tk()
- button = Button(root)
- button['text'] = 'Hello, world'
- button['command'] = quit_callback # See below
- button.pack()
- root.mainloop()
+ root = Tk()
+ button = Button(root)
+ button['text'] = 'Hello, world'
+ button['command'] = quit_callback # See below
+ button.pack()
+ root.mainloop()
def quit_callback():
- sys.exit(0)
+ sys.exit(0)
main()
diff --git a/Demo/tkinter/guido/kill.py b/Demo/tkinter/guido/kill.py
index 577af8b..e7df261 100755
--- a/Demo/tkinter/guido/kill.py
+++ b/Demo/tkinter/guido/kill.py
@@ -8,92 +8,91 @@ import commands
import os
class BarButton(Menubutton):
- def __init__(self, master=None, **cnf):
- apply(Menubutton.__init__, (self, master), cnf)
- self.pack(side=LEFT)
- self.menu = Menu(self, name='menu')
- self['menu'] = self.menu
+ def __init__(self, master=None, **cnf):
+ apply(Menubutton.__init__, (self, master), cnf)
+ self.pack(side=LEFT)
+ self.menu = Menu(self, name='menu')
+ self['menu'] = self.menu
class Kill(Frame):
- # List of (name, option, pid_column)
- format_list = [('Default', '', 0),
- ('Long', '-l', 2),
- ('User', '-u', 1),
- ('Jobs', '-j', 1),
- ('Signal', '-s', 1),
- ('Memory', '-m', 0),
- ('VM', '-v', 0),
- ('Hex', '-X', 0)]
- def kill(self, selected):
- c = self.format_list[self.format.get()][2]
- pid = split(selected)[c]
- os.system('kill -9 ' + pid)
- self.do_update()
- def do_update(self):
- name, option, column = self.format_list[self.format.get()]
- s = commands.getoutput('ps -w ' + option)
- list = splitfields(s, '\n')
- self.header.set(list[0])
- del list[0]
- y = self.frame.vscroll.get()[0]
- self.frame.list.delete(0, AtEnd())
- for line in list:
- self.frame.list.insert(0, line)
- self.frame.list.yview(int(y))
- def do_motion(self, e):
- e.widget.select_clear(0, END)
- e.widget.select_set(e.widget.nearest(e.y))
- def do_leave(self, e):
- e.widget.select_clear(0, END)
- def do_1(self, e):
- self.kill(e.widget.get(e.widget.nearest(e.y)))
- def __init__(self, master=None, **cnf):
- Frame.__init__(self, master, cnf)
- self.pack(expand=1, fill=BOTH)
- self.bar = Frame(self, name='bar', relief=RAISED,
- borderwidth=2)
- self.bar.pack(fill=X)
- self.bar.file = BarButton(self.bar, text='File')
- self.bar.file.menu.add_command(
- label='Quit', command=self.quit)
- self.bar.view = BarButton(self.bar, text='View')
- self.format = IntVar(self)
- self.format.set(2)
- for num in range(len(self.format_list)):
- self.bar.view.menu.add_radiobutton(
- label=self.format_list[num][0],
- command=self.do_update,
- variable=self.format,
- value=num)
- #self.bar.view.menu.add_separator()
- #XXX ...
- self.bar.tk_menuBar(self.bar.file, self.bar.view)
- self.frame = Frame(self, relief=RAISED, borderwidth=2)
- self.frame.pack(expand=1, fill=BOTH)
- self.header = StringVar(self)
- self.frame.label = Label(self.frame, relief=FLAT, anchor=NW,
- borderwidth=0,
- textvariable=self.header)
- self.frame.label.pack(fill=X)
- self.frame.vscroll = Scrollbar(self.frame, orient=VERTICAL)
- self.frame.list = Listbox(self.frame, relief=SUNKEN,
- selectbackground='#eed5b7',
- selectborderwidth=0,
- yscroll=self.frame.vscroll.set)
- self.frame.vscroll['command'] = self.frame.list.yview
- self.frame.vscroll.pack(side=RIGHT, fill=Y)
- self.frame.list.pack(expand=1, fill=BOTH)
- self.update = Button(self, text="Update",
- command=self.do_update)
- self.update.pack(expand=1, fill=X)
- self.frame.list.bind('<Motion>', self.do_motion)
- self.frame.list.bind('<Leave>', self.do_leave)
- self.frame.list.bind('<1>', self.do_1)
- self.do_update()
+ # List of (name, option, pid_column)
+ format_list = [('Default', '', 0),
+ ('Long', '-l', 2),
+ ('User', '-u', 1),
+ ('Jobs', '-j', 1),
+ ('Signal', '-s', 1),
+ ('Memory', '-m', 0),
+ ('VM', '-v', 0),
+ ('Hex', '-X', 0)]
+ def kill(self, selected):
+ c = self.format_list[self.format.get()][2]
+ pid = split(selected)[c]
+ os.system('kill -9 ' + pid)
+ self.do_update()
+ def do_update(self):
+ name, option, column = self.format_list[self.format.get()]
+ s = commands.getoutput('ps -w ' + option)
+ list = splitfields(s, '\n')
+ self.header.set(list[0])
+ del list[0]
+ y = self.frame.vscroll.get()[0]
+ self.frame.list.delete(0, AtEnd())
+ for line in list:
+ self.frame.list.insert(0, line)
+ self.frame.list.yview(int(y))
+ def do_motion(self, e):
+ e.widget.select_clear(0, END)
+ e.widget.select_set(e.widget.nearest(e.y))
+ def do_leave(self, e):
+ e.widget.select_clear(0, END)
+ def do_1(self, e):
+ self.kill(e.widget.get(e.widget.nearest(e.y)))
+ def __init__(self, master=None, **cnf):
+ Frame.__init__(self, master, cnf)
+ self.pack(expand=1, fill=BOTH)
+ self.bar = Frame(self, name='bar', relief=RAISED,
+ borderwidth=2)
+ self.bar.pack(fill=X)
+ self.bar.file = BarButton(self.bar, text='File')
+ self.bar.file.menu.add_command(
+ label='Quit', command=self.quit)
+ self.bar.view = BarButton(self.bar, text='View')
+ self.format = IntVar(self)
+ self.format.set(2)
+ for num in range(len(self.format_list)):
+ self.bar.view.menu.add_radiobutton(
+ label=self.format_list[num][0],
+ command=self.do_update,
+ variable=self.format,
+ value=num)
+ #self.bar.view.menu.add_separator()
+ #XXX ...
+ self.bar.tk_menuBar(self.bar.file, self.bar.view)
+ self.frame = Frame(self, relief=RAISED, borderwidth=2)
+ self.frame.pack(expand=1, fill=BOTH)
+ self.header = StringVar(self)
+ self.frame.label = Label(self.frame, relief=FLAT, anchor=NW,
+ borderwidth=0,
+ textvariable=self.header)
+ self.frame.label.pack(fill=X)
+ self.frame.vscroll = Scrollbar(self.frame, orient=VERTICAL)
+ self.frame.list = Listbox(self.frame, relief=SUNKEN,
+ selectbackground='#eed5b7',
+ selectborderwidth=0,
+ yscroll=self.frame.vscroll.set)
+ self.frame.vscroll['command'] = self.frame.list.yview
+ self.frame.vscroll.pack(side=RIGHT, fill=Y)
+ self.frame.list.pack(expand=1, fill=BOTH)
+ self.update = Button(self, text="Update",
+ command=self.do_update)
+ self.update.pack(expand=1, fill=X)
+ self.frame.list.bind('<Motion>', self.do_motion)
+ self.frame.list.bind('<Leave>', self.do_leave)
+ self.frame.list.bind('<1>', self.do_1)
+ self.do_update()
if __name__ == '__main__':
- kill = Kill(None, borderwidth=5)
- kill.winfo_toplevel().title('Tkinter Process Killer')
- kill.winfo_toplevel().minsize(1, 1)
- kill.mainloop()
-
+ kill = Kill(None, borderwidth=5)
+ kill.winfo_toplevel().title('Tkinter Process Killer')
+ kill.winfo_toplevel().minsize(1, 1)
+ kill.mainloop()
diff --git a/Demo/tkinter/guido/listtree.py b/Demo/tkinter/guido/listtree.py
index 523f209..d28ce49 100755
--- a/Demo/tkinter/guido/listtree.py
+++ b/Demo/tkinter/guido/listtree.py
@@ -6,32 +6,32 @@ import string
from Tkinter import *
def listtree(master, app):
- list = Listbox(master, name='list')
- list.pack(expand=1, fill=BOTH)
- listnodes(list, app, '.', 0)
- return list
+ list = Listbox(master, name='list')
+ list.pack(expand=1, fill=BOTH)
+ listnodes(list, app, '.', 0)
+ return list
def listnodes(list, app, widget, level):
- klass = list.send(app, 'winfo', 'class', widget)
-## i = string.rindex(widget, '.')
-## list.insert(END, '%s%s (%s)' % ((level-1)*'. ', widget[i:], klass))
- list.insert(END, '%s (%s)' % (widget, klass))
- children = list.tk.splitlist(
- list.send(app, 'winfo', 'children', widget))
- for c in children:
- listnodes(list, app, c, level+1)
+ klass = list.send(app, 'winfo', 'class', widget)
+## i = string.rindex(widget, '.')
+## list.insert(END, '%s%s (%s)' % ((level-1)*'. ', widget[i:], klass))
+ list.insert(END, '%s (%s)' % (widget, klass))
+ children = list.tk.splitlist(
+ list.send(app, 'winfo', 'children', widget))
+ for c in children:
+ listnodes(list, app, c, level+1)
def main():
- if not sys.argv[1:]:
- sys.stderr.write('Usage: listtree appname\n')
- sys.exit(2)
- app = sys.argv[1]
- tk = Tk()
- tk.minsize(1, 1)
- f = Frame(tk, name='f')
- f.pack(expand=1, fill=BOTH)
- list = listtree(f, app)
- tk.mainloop()
+ if not sys.argv[1:]:
+ sys.stderr.write('Usage: listtree appname\n')
+ sys.exit(2)
+ app = sys.argv[1]
+ tk = Tk()
+ tk.minsize(1, 1)
+ f = Frame(tk, name='f')
+ f.pack(expand=1, fill=BOTH)
+ list = listtree(f, app)
+ tk.mainloop()
if __name__ == '__main__':
- main()
+ main()
diff --git a/Demo/tkinter/guido/mbox.py b/Demo/tkinter/guido/mbox.py
index 6d7a410..9b16f6b 100755
--- a/Demo/tkinter/guido/mbox.py
+++ b/Demo/tkinter/guido/mbox.py
@@ -16,270 +16,270 @@ from dialog import dialog
mailbox = os.environ['HOME'] + '/Mail'
def main():
- global root, tk, top, mid, bot
- global folderbox, foldermenu, scanbox, scanmenu, viewer
- global folder, seq
- global mh, mhf
-
- # Parse command line options
+ global root, tk, top, mid, bot
+ global folderbox, foldermenu, scanbox, scanmenu, viewer
+ global folder, seq
+ global mh, mhf
+
+ # Parse command line options
- folder = 'inbox'
- seq = 'all'
- try:
- opts, args = getopt.getopt(sys.argv[1:], '')
- except getopt.error, msg:
- print msg
- sys.exit(2)
- for arg in args:
- if arg[:1] == '+':
- folder = arg[1:]
- else:
- seq = arg
+ folder = 'inbox'
+ seq = 'all'
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], '')
+ except getopt.error, msg:
+ print msg
+ sys.exit(2)
+ for arg in args:
+ if arg[:1] == '+':
+ folder = arg[1:]
+ else:
+ seq = arg
- # Initialize MH
+ # Initialize MH
- mh = mhlib.MH()
- mhf = mh.openfolder(folder)
+ mh = mhlib.MH()
+ mhf = mh.openfolder(folder)
- # Build widget hierarchy
+ # Build widget hierarchy
- root = Tk()
- tk = root.tk
+ root = Tk()
+ tk = root.tk
- top = Frame(root)
- top.pack({'expand': 1, 'fill': 'both'})
+ top = Frame(root)
+ top.pack({'expand': 1, 'fill': 'both'})
- # Build right part: folder list
+ # Build right part: folder list
- right = Frame(top)
- right.pack({'fill': 'y', 'side': 'right'})
+ right = Frame(top)
+ right.pack({'fill': 'y', 'side': 'right'})
- folderbar = Scrollbar(right, {'relief': 'sunken', 'bd': 2})
- folderbar.pack({'fill': 'y', 'side': 'right'})
+ folderbar = Scrollbar(right, {'relief': 'sunken', 'bd': 2})
+ folderbar.pack({'fill': 'y', 'side': 'right'})
- folderbox = Listbox(right, {'exportselection': 0})
- folderbox.pack({'expand': 1, 'fill': 'both', 'side': 'left'})
+ folderbox = Listbox(right, {'exportselection': 0})
+ folderbox.pack({'expand': 1, 'fill': 'both', 'side': 'left'})
- foldermenu = Menu(root)
- foldermenu.add('command',
- {'label': 'Open Folder',
- 'command': open_folder})
- foldermenu.add('separator')
- foldermenu.add('command',
- {'label': 'Quit',
- 'command': 'exit'})
- foldermenu.bind('<ButtonRelease-3>', folder_unpost)
+ foldermenu = Menu(root)
+ foldermenu.add('command',
+ {'label': 'Open Folder',
+ 'command': open_folder})
+ foldermenu.add('separator')
+ foldermenu.add('command',
+ {'label': 'Quit',
+ 'command': 'exit'})
+ foldermenu.bind('<ButtonRelease-3>', folder_unpost)
- folderbox['yscrollcommand'] = (folderbar, 'set')
- folderbar['command'] = (folderbox, 'yview')
- folderbox.bind('<Double-1>', open_folder, 1)
- folderbox.bind('<3>', folder_post)
+ folderbox['yscrollcommand'] = (folderbar, 'set')
+ folderbar['command'] = (folderbox, 'yview')
+ folderbox.bind('<Double-1>', open_folder, 1)
+ folderbox.bind('<3>', folder_post)
- # Build left part: scan list
+ # Build left part: scan list
- left = Frame(top)
- left.pack({'expand': 1, 'fill': 'both', 'side': 'left'})
+ left = Frame(top)
+ left.pack({'expand': 1, 'fill': 'both', 'side': 'left'})
- scanbar = Scrollbar(left, {'relief': 'sunken', 'bd': 2})
- scanbar.pack({'fill': 'y', 'side': 'right'})
+ scanbar = Scrollbar(left, {'relief': 'sunken', 'bd': 2})
+ scanbar.pack({'fill': 'y', 'side': 'right'})
- scanbox = Listbox(left, {'font': 'fixed'})
- scanbox.pack({'expand': 1, 'fill': 'both', 'side': 'left'})
+ scanbox = Listbox(left, {'font': 'fixed'})
+ scanbox.pack({'expand': 1, 'fill': 'both', 'side': 'left'})
- scanmenu = Menu(root)
- scanmenu.add('command',
- {'label': 'Open Message',
- 'command': open_message})
- scanmenu.add('command',
- {'label': 'Remove Message',
- 'command': remove_message})
- scanmenu.add('command',
- {'label': 'Refile Message',
- 'command': refile_message})
- scanmenu.add('separator')
- scanmenu.add('command',
- {'label': 'Quit',
- 'command': 'exit'})
- scanmenu.bind('<ButtonRelease-3>', scan_unpost)
+ scanmenu = Menu(root)
+ scanmenu.add('command',
+ {'label': 'Open Message',
+ 'command': open_message})
+ scanmenu.add('command',
+ {'label': 'Remove Message',
+ 'command': remove_message})
+ scanmenu.add('command',
+ {'label': 'Refile Message',
+ 'command': refile_message})
+ scanmenu.add('separator')
+ scanmenu.add('command',
+ {'label': 'Quit',
+ 'command': 'exit'})
+ scanmenu.bind('<ButtonRelease-3>', scan_unpost)
- scanbox['yscrollcommand'] = (scanbar, 'set')
- scanbar['command'] = (scanbox, 'yview')
- scanbox.bind('<Double-1>', open_message)
- scanbox.bind('<3>', scan_post)
+ scanbox['yscrollcommand'] = (scanbar, 'set')
+ scanbar['command'] = (scanbox, 'yview')
+ scanbox.bind('<Double-1>', open_message)
+ scanbox.bind('<3>', scan_post)
- # Separator between middle and bottom part
+ # Separator between middle and bottom part
- rule2 = Frame(root, {'bg': 'black'})
- rule2.pack({'fill': 'x'})
+ rule2 = Frame(root, {'bg': 'black'})
+ rule2.pack({'fill': 'x'})
- # Build bottom part: current message
+ # Build bottom part: current message
- bot = Frame(root)
- bot.pack({'expand': 1, 'fill': 'both'})
- #
- viewer = None
+ bot = Frame(root)
+ bot.pack({'expand': 1, 'fill': 'both'})
+ #
+ viewer = None
- # Window manager commands
+ # Window manager commands
- root.minsize(800, 1) # Make window resizable
+ root.minsize(800, 1) # Make window resizable
- # Fill folderbox with text
+ # Fill folderbox with text
- setfolders()
+ setfolders()
- # Fill scanbox with text
+ # Fill scanbox with text
- rescan()
+ rescan()
- # Enter mainloop
+ # Enter mainloop
- root.mainloop()
+ root.mainloop()
def folder_post(e):
- x, y = e.x_root, e.y_root
- foldermenu.post(x - 10, y - 10)
- foldermenu.grab_set()
+ x, y = e.x_root, e.y_root
+ foldermenu.post(x - 10, y - 10)
+ foldermenu.grab_set()
def folder_unpost(e):
- tk.call('update', 'idletasks')
- foldermenu.grab_release()
- foldermenu.unpost()
- foldermenu.invoke('active')
+ tk.call('update', 'idletasks')
+ foldermenu.grab_release()
+ foldermenu.unpost()
+ foldermenu.invoke('active')
def scan_post(e):
- x, y = e.x_root, e.y_root
- scanmenu.post(x - 10, y - 10)
- scanmenu.grab_set()
+ x, y = e.x_root, e.y_root
+ scanmenu.post(x - 10, y - 10)
+ scanmenu.grab_set()
def scan_unpost(e):
- tk.call('update', 'idletasks')
- scanmenu.grab_release()
- scanmenu.unpost()
- scanmenu.invoke('active')
+ tk.call('update', 'idletasks')
+ scanmenu.grab_release()
+ scanmenu.unpost()
+ scanmenu.invoke('active')
scanparser = regex.compile('^ *\([0-9]+\)')
def open_folder(e=None):
- global folder, mhf
- sel = folderbox.curselection()
- if len(sel) != 1:
- if len(sel) > 1:
- msg = "Please open one folder at a time"
- else:
- msg = "Please select a folder to open"
- dialog(root, "Can't Open Folder", msg, "", 0, "OK")
- return
- i = sel[0]
- folder = folderbox.get(i)
- mhf = mh.openfolder(folder)
- rescan()
+ global folder, mhf
+ sel = folderbox.curselection()
+ if len(sel) != 1:
+ if len(sel) > 1:
+ msg = "Please open one folder at a time"
+ else:
+ msg = "Please select a folder to open"
+ dialog(root, "Can't Open Folder", msg, "", 0, "OK")
+ return
+ i = sel[0]
+ folder = folderbox.get(i)
+ mhf = mh.openfolder(folder)
+ rescan()
def open_message(e=None):
- global viewer
- sel = scanbox.curselection()
- if len(sel) != 1:
- if len(sel) > 1:
- msg = "Please open one message at a time"
- else:
- msg = "Please select a message to open"
- dialog(root, "Can't Open Message", msg, "", 0, "OK")
- return
- cursor = scanbox['cursor']
- scanbox['cursor'] = 'watch'
- tk.call('update', 'idletasks')
- i = sel[0]
- line = scanbox.get(i)
- if scanparser.match(line) >= 0:
- num = string.atoi(scanparser.group(1))
- m = mhf.openmessage(num)
- if viewer: viewer.destroy()
- from MimeViewer import MimeViewer
- viewer = MimeViewer(bot, '+%s/%d' % (folder, num), m)
- viewer.pack()
- viewer.show()
- scanbox['cursor'] = cursor
+ global viewer
+ sel = scanbox.curselection()
+ if len(sel) != 1:
+ if len(sel) > 1:
+ msg = "Please open one message at a time"
+ else:
+ msg = "Please select a message to open"
+ dialog(root, "Can't Open Message", msg, "", 0, "OK")
+ return
+ cursor = scanbox['cursor']
+ scanbox['cursor'] = 'watch'
+ tk.call('update', 'idletasks')
+ i = sel[0]
+ line = scanbox.get(i)
+ if scanparser.match(line) >= 0:
+ num = string.atoi(scanparser.group(1))
+ m = mhf.openmessage(num)
+ if viewer: viewer.destroy()
+ from MimeViewer import MimeViewer
+ viewer = MimeViewer(bot, '+%s/%d' % (folder, num), m)
+ viewer.pack()
+ viewer.show()
+ scanbox['cursor'] = cursor
def interestingheader(header):
- return header != 'received'
+ return header != 'received'
def remove_message(e=None):
- itop = scanbox.nearest(0)
- sel = scanbox.curselection()
- if not sel:
- dialog(root, "No Message To Remove",
- "Please select a message to remove", "", 0, "OK")
- return
- todo = []
- for i in sel:
- line = scanbox.get(i)
- if scanparser.match(line) >= 0:
- todo.append(string.atoi(scanparser.group(1)))
- mhf.removemessages(todo)
- rescan()
- fixfocus(min(todo), itop)
+ itop = scanbox.nearest(0)
+ sel = scanbox.curselection()
+ if not sel:
+ dialog(root, "No Message To Remove",
+ "Please select a message to remove", "", 0, "OK")
+ return
+ todo = []
+ for i in sel:
+ line = scanbox.get(i)
+ if scanparser.match(line) >= 0:
+ todo.append(string.atoi(scanparser.group(1)))
+ mhf.removemessages(todo)
+ rescan()
+ fixfocus(min(todo), itop)
lastrefile = ''
tofolder = None
def refile_message(e=None):
- global lastrefile, tofolder
- itop = scanbox.nearest(0)
- sel = scanbox.curselection()
- if not sel:
- dialog(root, "No Message To Refile",
- "Please select a message to refile", "", 0, "OK")
- return
- foldersel = folderbox.curselection()
- if len(foldersel) != 1:
- if not foldersel:
- msg = "Please select a folder to refile to"
- else:
- msg = "Please select exactly one folder to refile to"
- dialog(root, "No Folder To Refile", msg, "", 0, "OK")
- return
- refileto = folderbox.get(foldersel[0])
- todo = []
- for i in sel:
- line = scanbox.get(i)
- if scanparser.match(line) >= 0:
- todo.append(string.atoi(scanparser.group(1)))
- if lastrefile != refileto or not tofolder:
- lastrefile = refileto
- tofolder = None
- tofolder = mh.openfolder(lastrefile)
- mhf.refilemessages(todo, tofolder)
- rescan()
- fixfocus(min(todo), itop)
+ global lastrefile, tofolder
+ itop = scanbox.nearest(0)
+ sel = scanbox.curselection()
+ if not sel:
+ dialog(root, "No Message To Refile",
+ "Please select a message to refile", "", 0, "OK")
+ return
+ foldersel = folderbox.curselection()
+ if len(foldersel) != 1:
+ if not foldersel:
+ msg = "Please select a folder to refile to"
+ else:
+ msg = "Please select exactly one folder to refile to"
+ dialog(root, "No Folder To Refile", msg, "", 0, "OK")
+ return
+ refileto = folderbox.get(foldersel[0])
+ todo = []
+ for i in sel:
+ line = scanbox.get(i)
+ if scanparser.match(line) >= 0:
+ todo.append(string.atoi(scanparser.group(1)))
+ if lastrefile != refileto or not tofolder:
+ lastrefile = refileto
+ tofolder = None
+ tofolder = mh.openfolder(lastrefile)
+ mhf.refilemessages(todo, tofolder)
+ rescan()
+ fixfocus(min(todo), itop)
def fixfocus(near, itop):
- n = scanbox.size()
- for i in range(n):
- line = scanbox.get(repr(i))
- if scanparser.match(line) >= 0:
- num = string.atoi(scanparser.group(1))
- if num >= near:
- break
- else:
- i = 'end'
- scanbox.select_from(i)
- scanbox.yview(itop)
+ n = scanbox.size()
+ for i in range(n):
+ line = scanbox.get(repr(i))
+ if scanparser.match(line) >= 0:
+ num = string.atoi(scanparser.group(1))
+ if num >= near:
+ break
+ else:
+ i = 'end'
+ scanbox.select_from(i)
+ scanbox.yview(itop)
def setfolders():
- folderbox.delete(0, 'end')
- for fn in mh.listallfolders():
- folderbox.insert('end', fn)
+ folderbox.delete(0, 'end')
+ for fn in mh.listallfolders():
+ folderbox.insert('end', fn)
def rescan():
- global viewer
- if viewer:
- viewer.destroy()
- viewer = None
- scanbox.delete(0, 'end')
- for line in scanfolder(folder, seq):
- scanbox.insert('end', line)
+ global viewer
+ if viewer:
+ viewer.destroy()
+ viewer = None
+ scanbox.delete(0, 'end')
+ for line in scanfolder(folder, seq):
+ scanbox.insert('end', line)
def scanfolder(folder = 'inbox', sequence = 'all'):
- return map(
- lambda line: line[:-1],
- os.popen('scan +%s %s' % (folder, sequence), 'r').readlines())
+ return map(
+ lambda line: line[:-1],
+ os.popen('scan +%s %s' % (folder, sequence), 'r').readlines())
main()
diff --git a/Demo/tkinter/guido/newmenubardemo.py b/Demo/tkinter/guido/newmenubardemo.py
index cafbf63..57bf13c 100644
--- a/Demo/tkinter/guido/newmenubardemo.py
+++ b/Demo/tkinter/guido/newmenubardemo.py
@@ -7,35 +7,35 @@ from Tkinter import *
class App:
def __init__(self, master):
- self.master = master
+ self.master = master
- self.menubar = Menu(self.master)
+ self.menubar = Menu(self.master)
- self.filemenu = Menu(self.menubar)
-
- self.filemenu.add_command(label="New")
- self.filemenu.add_command(label="Open...")
- self.filemenu.add_command(label="Close")
- self.filemenu.add_separator()
- self.filemenu.add_command(label="Quit", command=self.master.quit)
+ self.filemenu = Menu(self.menubar)
- self.editmenu = Menu(self.menubar)
+ self.filemenu.add_command(label="New")
+ self.filemenu.add_command(label="Open...")
+ self.filemenu.add_command(label="Close")
+ self.filemenu.add_separator()
+ self.filemenu.add_command(label="Quit", command=self.master.quit)
- self.editmenu.add_command(label="Cut")
- self.editmenu.add_command(label="Copy")
- self.editmenu.add_command(label="Paste")
+ self.editmenu = Menu(self.menubar)
+
+ self.editmenu.add_command(label="Cut")
+ self.editmenu.add_command(label="Copy")
+ self.editmenu.add_command(label="Paste")
self.helpmenu = Menu(self.menubar, name='help')
self.helpmenu.add_command(label="About...")
- self.menubar.add_cascade(label="File", menu=self.filemenu)
- self.menubar.add_cascade(label="Edit", menu=self.editmenu)
- self.menubar.add_cascade(label="Help", menu=self.helpmenu)
+ self.menubar.add_cascade(label="File", menu=self.filemenu)
+ self.menubar.add_cascade(label="Edit", menu=self.editmenu)
+ self.menubar.add_cascade(label="Help", menu=self.helpmenu)
- self.top = Toplevel(menu=self.menubar)
+ self.top = Toplevel(menu=self.menubar)
- # Rest of app goes here...
+ # Rest of app goes here...
def main():
root = Tk()
diff --git a/Demo/tkinter/guido/paint.py b/Demo/tkinter/guido/paint.py
index 743d500..d46e20b 100644
--- a/Demo/tkinter/guido/paint.py
+++ b/Demo/tkinter/guido/paint.py
@@ -12,12 +12,12 @@ here and hope that the person who requested it sees this!
All this does is put up a canvas and draw a smooth black line
whenever you have the mouse button down, but hopefully it will
-be enough to start with.. It would be easy enough to add some
+be enough to start with.. It would be easy enough to add some
options like other shapes or colors...
- yours,
- dave mitchell
- davem@magnet.com
+ yours,
+ dave mitchell
+ davem@magnet.com
"""
from Tkinter import *
@@ -28,33 +28,33 @@ b1 = "up"
xold, yold = None, None
def main():
- root = Tk()
- drawing_area = Canvas(root)
- drawing_area.pack()
- drawing_area.bind("<Motion>", motion)
- drawing_area.bind("<ButtonPress-1>", b1down)
- drawing_area.bind("<ButtonRelease-1>", b1up)
- root.mainloop()
+ root = Tk()
+ drawing_area = Canvas(root)
+ drawing_area.pack()
+ drawing_area.bind("<Motion>", motion)
+ drawing_area.bind("<ButtonPress-1>", b1down)
+ drawing_area.bind("<ButtonRelease-1>", b1up)
+ root.mainloop()
def b1down(event):
- global b1
- b1 = "down" # you only want to draw when the button is down
- # because "Motion" events happen -all the time-
+ global b1
+ b1 = "down" # you only want to draw when the button is down
+ # because "Motion" events happen -all the time-
def b1up(event):
- global b1, xold, yold
- b1 = "up"
- xold = None # reset the line when you let go of the button
- yold = None
+ global b1, xold, yold
+ b1 = "up"
+ xold = None # reset the line when you let go of the button
+ yold = None
def motion(event):
- if b1 == "down":
- global xold, yold
- if xold != None and yold != None:
- event.widget.create_line(xold,yold,event.x,event.y,smooth=TRUE)
- # here's where you draw it. smooth. neat.
- xold = event.x
- yold = event.y
+ if b1 == "down":
+ global xold, yold
+ if xold != None and yold != None:
+ event.widget.create_line(xold,yold,event.x,event.y,smooth=TRUE)
+ # here's where you draw it. smooth. neat.
+ xold = event.x
+ yold = event.y
if __name__ == "__main__":
- main()
+ main()
diff --git a/Demo/tkinter/guido/rmt.py b/Demo/tkinter/guido/rmt.py
index 6e9a828..440650c 100755
--- a/Demo/tkinter/guido/rmt.py
+++ b/Demo/tkinter/guido/rmt.py
@@ -28,7 +28,7 @@ s = Scrollbar(f, relief=FLAT)
s.pack(side=RIGHT, fill=Y)
t = Text(f, relief=RAISED, borderwidth=2, yscrollcommand=s.set, setgrid=1)
t.pack(side=LEFT, fill=BOTH, expand=1)
-t.tag_config('bold', font='-Adobe-Courier-Bold-R-Normal-*-120-*')
+t.tag_config('bold', font='-Adobe-Courier-Bold-R-Normal-*-120-*')
s['command'] = t.yview
root.title('Tk Remote Controller')
@@ -42,7 +42,7 @@ file_m = Menu(file)
file['menu'] = file_m
file_m_apps = Menu(file_m, tearoff=0)
file_m.add_cascade(label='Select Application', underline=0,
- menu=file_m_apps)
+ menu=file_m_apps)
file_m.add_command(label='Quit', underline=0, command=sys.exit)
# 3. Create bindings for text widget to allow commands to be
@@ -51,46 +51,46 @@ file_m.add_command(label='Quit', underline=0, command=sys.exit)
# insertion point).
def single1(e):
- x = e.x
- y = e.y
- t.setvar('tk_priv(selectMode)', 'char')
- t.mark_set('anchor', At(x, y))
- # Should focus W
+ x = e.x
+ y = e.y
+ t.setvar('tk_priv(selectMode)', 'char')
+ t.mark_set('anchor', At(x, y))
+ # Should focus W
t.bind('<1>', single1)
def double1(e):
- x = e.x
- y = e.y
- t.setvar('tk_priv(selectMode)', 'word')
- t.tk_textSelectTo(At(x, y))
+ x = e.x
+ y = e.y
+ t.setvar('tk_priv(selectMode)', 'word')
+ t.tk_textSelectTo(At(x, y))
t.bind('<Double-1>', double1)
def triple1(e):
- x = e.x
- y = e.y
- t.setvar('tk_priv(selectMode)', 'line')
- t.tk_textSelectTo(At(x, y))
+ x = e.x
+ y = e.y
+ t.setvar('tk_priv(selectMode)', 'line')
+ t.tk_textSelectTo(At(x, y))
t.bind('<Triple-1>', triple1)
def returnkey(e):
- t.insert(AtInsert(), '\n')
- invoke()
+ t.insert(AtInsert(), '\n')
+ invoke()
t.bind('<Return>', returnkey)
def controlv(e):
- t.insert(AtInsert(), t.selection_get())
- t.yview_pickplace(AtInsert())
- if t.index(AtInsert())[-2:] == '.0':
- invoke()
+ t.insert(AtInsert(), t.selection_get())
+ t.yview_pickplace(AtInsert())
+ if t.index(AtInsert())[-2:] == '.0':
+ invoke()
t.bind('<Control-v>', controlv)
# 4. Procedure to backspace over one character, as long as
# the character isn't part of the prompt.
def backspace(e):
- if t.index('promptEnd') != t.index('insert - 1 char'):
- t.delete('insert - 1 char', AtInsert())
- t.yview_pickplace(AtInsert())
+ if t.index('promptEnd') != t.index('insert - 1 char'):
+ t.delete('insert - 1 char', AtInsert())
+ t.yview_pickplace(AtInsert())
t.bind('<BackSpace>', backspace)
t.bind('<Control-h>', backspace)
t.bind('<Delete>', backspace)
@@ -103,49 +103,49 @@ t.bind('<Delete>', backspace)
# a new prompt.
def invoke():
- cmd = t.get('promptEnd + 1 char', AtInsert())
- if t.getboolean(tk.call('info', 'complete', cmd)): # XXX
- if app == root.winfo_name():
- msg = tk.call('eval', cmd) # XXX
- else:
- msg = t.send(app, cmd)
- if msg:
- t.insert(AtInsert(), msg + '\n')
- prompt()
- t.yview_pickplace(AtInsert())
+ cmd = t.get('promptEnd + 1 char', AtInsert())
+ if t.getboolean(tk.call('info', 'complete', cmd)): # XXX
+ if app == root.winfo_name():
+ msg = tk.call('eval', cmd) # XXX
+ else:
+ msg = t.send(app, cmd)
+ if msg:
+ t.insert(AtInsert(), msg + '\n')
+ prompt()
+ t.yview_pickplace(AtInsert())
def prompt():
- t.insert(AtInsert(), app + ': ')
- t.mark_set('promptEnd', 'insert - 1 char')
- t.tag_add('bold', 'insert linestart', 'promptEnd')
+ t.insert(AtInsert(), app + ': ')
+ t.mark_set('promptEnd', 'insert - 1 char')
+ t.tag_add('bold', 'insert linestart', 'promptEnd')
# 6. Procedure to select a new application. Also changes
# the prompt on the current command line to reflect the new
# name.
def newApp(appName):
- global app
- app = appName
- t.delete('promptEnd linestart', 'promptEnd')
- t.insert('promptEnd', appName + ':')
- t.tag_add('bold', 'promptEnd linestart', 'promptEnd')
+ global app
+ app = appName
+ t.delete('promptEnd linestart', 'promptEnd')
+ t.insert('promptEnd', appName + ':')
+ t.tag_add('bold', 'promptEnd linestart', 'promptEnd')
def fillAppsMenu():
- file_m_apps.add('command')
- file_m_apps.delete(0, 'last')
- names = root.winfo_interps()
- names = map(None, names) # convert tuple to list
- names.sort()
- for name in names:
- try:
- root.send(name, 'winfo name .')
- except TclError:
- # Inoperative window -- ignore it
- pass
- else:
- file_m_apps.add_command(
- label=name,
- command=lambda name=name: newApp(name))
+ file_m_apps.add('command')
+ file_m_apps.delete(0, 'last')
+ names = root.winfo_interps()
+ names = map(None, names) # convert tuple to list
+ names.sort()
+ for name in names:
+ try:
+ root.send(name, 'winfo name .')
+ except TclError:
+ # Inoperative window -- ignore it
+ pass
+ else:
+ file_m_apps.add_command(
+ label=name,
+ command=lambda name=name: newApp(name))
file_m_apps['postcommand'] = fillAppsMenu
mBar.tk_menuBar(file)
diff --git a/Demo/tkinter/guido/solitaire.py b/Demo/tkinter/guido/solitaire.py
index a205afd..50a8b26 100755
--- a/Demo/tkinter/guido/solitaire.py
+++ b/Demo/tkinter/guido/solitaire.py
@@ -11,7 +11,7 @@ Limitations:
- No keyboard shortcuts.
- Less fancy animation when you win.
- The determination of which stack you drag to is more relaxed.
-
+
Apology:
I'm not much of a card player, so my terminology in these comments may
@@ -35,7 +35,7 @@ from Canvas import Rectangle, CanvasText, Group, Window
class Group(Group):
def bind(self, sequence=None, command=None):
- return self.canvas.tag_bind(self.id, sequence, command)
+ return self.canvas.tag_bind(self.id, sequence, command)
# Constants determining the size and lay-out of cards and stacks. We
@@ -135,7 +135,7 @@ class Card:
Semi-public read-only instance variables (XXX should be made
private):
-
+
group -- the Canvas.Group representing the card
x, y -- the position of the card's top left corner
@@ -150,68 +150,68 @@ class Card:
"""
def __init__(self, suit, value, canvas):
- """Card constructor.
+ """Card constructor.
- Arguments are the card's suit and value, and the canvas widget.
+ Arguments are the card's suit and value, and the canvas widget.
- The card is created at position (0, 0), with its face down
- (adding it to a stack will position it according to that
- stack's rules).
+ The card is created at position (0, 0), with its face down
+ (adding it to a stack will position it according to that
+ stack's rules).
- """
- self.suit = suit
- self.value = value
- self.color = COLOR[suit]
- self.face_shown = 0
+ """
+ self.suit = suit
+ self.value = value
+ self.color = COLOR[suit]
+ self.face_shown = 0
- self.x = self.y = 0
- self.group = Group(canvas)
+ self.x = self.y = 0
+ self.group = Group(canvas)
- text = "%s %s" % (VALNAMES[value], suit)
- self.__text = CanvasText(canvas, CARDWIDTH/2, 0,
- anchor=N, fill=self.color, text=text)
- self.group.addtag_withtag(self.__text)
+ text = "%s %s" % (VALNAMES[value], suit)
+ self.__text = CanvasText(canvas, CARDWIDTH/2, 0,
+ anchor=N, fill=self.color, text=text)
+ self.group.addtag_withtag(self.__text)
- self.__rect = Rectangle(canvas, 0, 0, CARDWIDTH, CARDHEIGHT,
- outline='black', fill='white')
- self.group.addtag_withtag(self.__rect)
+ self.__rect = Rectangle(canvas, 0, 0, CARDWIDTH, CARDHEIGHT,
+ outline='black', fill='white')
+ self.group.addtag_withtag(self.__rect)
- self.__back = Rectangle(canvas, MARGIN, MARGIN,
- CARDWIDTH-MARGIN, CARDHEIGHT-MARGIN,
- outline='black', fill='blue')
- self.group.addtag_withtag(self.__back)
+ self.__back = Rectangle(canvas, MARGIN, MARGIN,
+ CARDWIDTH-MARGIN, CARDHEIGHT-MARGIN,
+ outline='black', fill='blue')
+ self.group.addtag_withtag(self.__back)
def __repr__(self):
- """Return a string for debug print statements."""
- return "Card(%r, %r)" % (self.suit, self.value)
+ """Return a string for debug print statements."""
+ return "Card(%r, %r)" % (self.suit, self.value)
def moveto(self, x, y):
- """Move the card to absolute position (x, y)."""
- self.moveby(x - self.x, y - self.y)
+ """Move the card to absolute position (x, y)."""
+ self.moveby(x - self.x, y - self.y)
def moveby(self, dx, dy):
- """Move the card by (dx, dy)."""
- self.x = self.x + dx
- self.y = self.y + dy
- self.group.move(dx, dy)
+ """Move the card by (dx, dy)."""
+ self.x = self.x + dx
+ self.y = self.y + dy
+ self.group.move(dx, dy)
def tkraise(self):
- """Raise the card above all other objects in its canvas."""
- self.group.tkraise()
+ """Raise the card above all other objects in its canvas."""
+ self.group.tkraise()
def showface(self):
- """Turn the card's face up."""
- self.tkraise()
- self.__rect.tkraise()
- self.__text.tkraise()
- self.face_shown = 1
+ """Turn the card's face up."""
+ self.tkraise()
+ self.__rect.tkraise()
+ self.__text.tkraise()
+ self.face_shown = 1
def showback(self):
- """Turn the card's face down."""
- self.tkraise()
- self.__rect.tkraise()
- self.__back.tkraise()
- self.face_shown = 0
+ """Turn the card's face down."""
+ self.tkraise()
+ self.__rect.tkraise()
+ self.__back.tkraise()
+ self.face_shown = 0
class Stack:
@@ -240,7 +240,7 @@ class Stack:
The default user (single) click handler shows the top card
face up. The default user double click handler calls the user
- single click handler.
+ single click handler.
usermovehandler(cards) -- called to complete a subpile move
@@ -255,133 +255,133 @@ class Stack:
The default event handlers turn the top card of the stack with
its face up on a (single or double) click, and also support
moving a subpile around.
-
+
startmoving(event) -- begin a move operation
finishmoving() -- finish a move operation
"""
def __init__(self, x, y, game=None):
- """Stack constructor.
-
- Arguments are the stack's nominal x and y position (the top
- left corner of the first card placed in the stack), and the
- game object (which is used to get the canvas; subclasses use
- the game object to find other stacks).
-
- """
- self.x = x
- self.y = y
- self.game = game
- self.cards = []
- self.group = Group(self.game.canvas)
- self.group.bind('<1>', self.clickhandler)
- self.group.bind('<Double-1>', self.doubleclickhandler)
- self.group.bind('<B1-Motion>', self.motionhandler)
- self.group.bind('<ButtonRelease-1>', self.releasehandler)
- self.makebottom()
+ """Stack constructor.
+
+ Arguments are the stack's nominal x and y position (the top
+ left corner of the first card placed in the stack), and the
+ game object (which is used to get the canvas; subclasses use
+ the game object to find other stacks).
+
+ """
+ self.x = x
+ self.y = y
+ self.game = game
+ self.cards = []
+ self.group = Group(self.game.canvas)
+ self.group.bind('<1>', self.clickhandler)
+ self.group.bind('<Double-1>', self.doubleclickhandler)
+ self.group.bind('<B1-Motion>', self.motionhandler)
+ self.group.bind('<ButtonRelease-1>', self.releasehandler)
+ self.makebottom()
def makebottom(self):
- pass
+ pass
def __repr__(self):
- """Return a string for debug print statements."""
- return "%s(%d, %d)" % (self.__class__.__name__, self.x, self.y)
+ """Return a string for debug print statements."""
+ return "%s(%d, %d)" % (self.__class__.__name__, self.x, self.y)
# Public methods
def add(self, card):
- self.cards.append(card)
- card.tkraise()
- self.position(card)
- self.group.addtag_withtag(card.group)
+ self.cards.append(card)
+ card.tkraise()
+ self.position(card)
+ self.group.addtag_withtag(card.group)
def delete(self, card):
- self.cards.remove(card)
- card.group.dtag(self.group)
+ self.cards.remove(card)
+ card.group.dtag(self.group)
def showtop(self):
- if self.cards:
- self.cards[-1].showface()
+ if self.cards:
+ self.cards[-1].showface()
def deal(self):
- if not self.cards:
- return None
- card = self.cards[-1]
- self.delete(card)
- return card
+ if not self.cards:
+ return None
+ card = self.cards[-1]
+ self.delete(card)
+ return card
# Subclass overridable methods
def position(self, card):
- card.moveto(self.x, self.y)
+ card.moveto(self.x, self.y)
def userclickhandler(self):
- self.showtop()
+ self.showtop()
def userdoubleclickhandler(self):
- self.userclickhandler()
+ self.userclickhandler()
def usermovehandler(self, cards):
- for card in cards:
- self.position(card)
+ for card in cards:
+ self.position(card)
# Event handlers
def clickhandler(self, event):
- self.finishmoving() # In case we lost an event
- self.userclickhandler()
- self.startmoving(event)
+ self.finishmoving() # In case we lost an event
+ self.userclickhandler()
+ self.startmoving(event)
def motionhandler(self, event):
- self.keepmoving(event)
+ self.keepmoving(event)
def releasehandler(self, event):
- self.keepmoving(event)
- self.finishmoving()
+ self.keepmoving(event)
+ self.finishmoving()
def doubleclickhandler(self, event):
- self.finishmoving() # In case we lost an event
- self.userdoubleclickhandler()
- self.startmoving(event)
+ self.finishmoving() # In case we lost an event
+ self.userdoubleclickhandler()
+ self.startmoving(event)
# Move internals
moving = None
def startmoving(self, event):
- self.moving = None
- tags = self.game.canvas.gettags('current')
- for i in range(len(self.cards)):
- card = self.cards[i]
- if card.group.tag in tags:
- break
- else:
- return
- if not card.face_shown:
- return
- self.moving = self.cards[i:]
- self.lastx = event.x
- self.lasty = event.y
- for card in self.moving:
- card.tkraise()
+ self.moving = None
+ tags = self.game.canvas.gettags('current')
+ for i in range(len(self.cards)):
+ card = self.cards[i]
+ if card.group.tag in tags:
+ break
+ else:
+ return
+ if not card.face_shown:
+ return
+ self.moving = self.cards[i:]
+ self.lastx = event.x
+ self.lasty = event.y
+ for card in self.moving:
+ card.tkraise()
def keepmoving(self, event):
- if not self.moving:
- return
- dx = event.x - self.lastx
- dy = event.y - self.lasty
- self.lastx = event.x
- self.lasty = event.y
- if dx or dy:
- for card in self.moving:
- card.moveby(dx, dy)
+ if not self.moving:
+ return
+ dx = event.x - self.lastx
+ dy = event.y - self.lasty
+ self.lastx = event.x
+ self.lasty = event.y
+ if dx or dy:
+ for card in self.moving:
+ card.moveby(dx, dy)
def finishmoving(self):
- cards = self.moving
- self.moving = None
- if cards:
- self.usermovehandler(cards)
+ cards = self.moving
+ self.moving = None
+ if cards:
+ self.usermovehandler(cards)
class Deck(Stack):
@@ -400,37 +400,37 @@ class Deck(Stack):
"""
def makebottom(self):
- bottom = Rectangle(self.game.canvas,
- self.x, self.y,
- self.x+CARDWIDTH, self.y+CARDHEIGHT,
- outline='black', fill=BACKGROUND)
- self.group.addtag_withtag(bottom)
+ bottom = Rectangle(self.game.canvas,
+ self.x, self.y,
+ self.x+CARDWIDTH, self.y+CARDHEIGHT,
+ outline='black', fill=BACKGROUND)
+ self.group.addtag_withtag(bottom)
def fill(self):
- for suit in ALLSUITS:
- for value in ALLVALUES:
- self.add(Card(suit, value, self.game.canvas))
+ for suit in ALLSUITS:
+ for value in ALLVALUES:
+ self.add(Card(suit, value, self.game.canvas))
def shuffle(self):
- n = len(self.cards)
- newcards = []
- for i in randperm(n):
- newcards.append(self.cards[i])
- self.cards = newcards
+ n = len(self.cards)
+ newcards = []
+ for i in randperm(n):
+ newcards.append(self.cards[i])
+ self.cards = newcards
def userclickhandler(self):
- opendeck = self.game.opendeck
- card = self.deal()
- if not card:
- while 1:
- card = opendeck.deal()
- if not card:
- break
- self.add(card)
- card.showback()
- else:
- self.game.opendeck.add(card)
- card.showface()
+ opendeck = self.game.opendeck
+ card = self.deal()
+ if not card:
+ while 1:
+ card = opendeck.deal()
+ if not card:
+ break
+ self.add(card)
+ card.showback()
+ else:
+ self.game.opendeck.add(card)
+ card.showface()
def randperm(n):
@@ -438,191 +438,191 @@ def randperm(n):
r = range(n)
x = []
while r:
- i = random.choice(r)
- x.append(i)
- r.remove(i)
+ i = random.choice(r)
+ x.append(i)
+ r.remove(i)
return x
class OpenStack(Stack):
def acceptable(self, cards):
- return 0
+ return 0
def usermovehandler(self, cards):
- card = cards[0]
- stack = self.game.closeststack(card)
- if not stack or stack is self or not stack.acceptable(cards):
- Stack.usermovehandler(self, cards)
- else:
- for card in cards:
- self.delete(card)
- stack.add(card)
- self.game.wincheck()
+ card = cards[0]
+ stack = self.game.closeststack(card)
+ if not stack or stack is self or not stack.acceptable(cards):
+ Stack.usermovehandler(self, cards)
+ else:
+ for card in cards:
+ self.delete(card)
+ stack.add(card)
+ self.game.wincheck()
def userdoubleclickhandler(self):
- if not self.cards:
- return
- card = self.cards[-1]
- if not card.face_shown:
- self.userclickhandler()
- return
- for s in self.game.suits:
- if s.acceptable([card]):
- self.delete(card)
- s.add(card)
- self.game.wincheck()
- break
+ if not self.cards:
+ return
+ card = self.cards[-1]
+ if not card.face_shown:
+ self.userclickhandler()
+ return
+ for s in self.game.suits:
+ if s.acceptable([card]):
+ self.delete(card)
+ s.add(card)
+ self.game.wincheck()
+ break
class SuitStack(OpenStack):
def makebottom(self):
- bottom = Rectangle(self.game.canvas,
- self.x, self.y,
- self.x+CARDWIDTH, self.y+CARDHEIGHT,
- outline='black', fill='')
+ bottom = Rectangle(self.game.canvas,
+ self.x, self.y,
+ self.x+CARDWIDTH, self.y+CARDHEIGHT,
+ outline='black', fill='')
def userclickhandler(self):
- pass
+ pass
def userdoubleclickhandler(self):
- pass
+ pass
def acceptable(self, cards):
- if len(cards) != 1:
- return 0
- card = cards[0]
- if not self.cards:
- return card.value == ACE
- topcard = self.cards[-1]
- return card.suit == topcard.suit and card.value == topcard.value + 1
+ if len(cards) != 1:
+ return 0
+ card = cards[0]
+ if not self.cards:
+ return card.value == ACE
+ topcard = self.cards[-1]
+ return card.suit == topcard.suit and card.value == topcard.value + 1
class RowStack(OpenStack):
def acceptable(self, cards):
- card = cards[0]
- if not self.cards:
- return card.value == KING
- topcard = self.cards[-1]
- if not topcard.face_shown:
- return 0
- return card.color != topcard.color and card.value == topcard.value - 1
+ card = cards[0]
+ if not self.cards:
+ return card.value == KING
+ topcard = self.cards[-1]
+ if not topcard.face_shown:
+ return 0
+ return card.color != topcard.color and card.value == topcard.value - 1
def position(self, card):
- y = self.y
- for c in self.cards:
- if c == card:
- break
- if c.face_shown:
- y = y + 2*MARGIN
- else:
- y = y + OFFSET
- card.moveto(self.x, y)
+ y = self.y
+ for c in self.cards:
+ if c == card:
+ break
+ if c.face_shown:
+ y = y + 2*MARGIN
+ else:
+ y = y + OFFSET
+ card.moveto(self.x, y)
class Solitaire:
def __init__(self, master):
- self.master = master
-
- self.canvas = Canvas(self.master,
- background=BACKGROUND,
- highlightthickness=0,
- width=NROWS*XSPACING,
- height=3*YSPACING + 20 + MARGIN)
- self.canvas.pack(fill=BOTH, expand=TRUE)
-
- self.dealbutton = Button(self.canvas,
- text="Deal",
- highlightthickness=0,
- background=BACKGROUND,
- activebackground="green",
- command=self.deal)
- Window(self.canvas, MARGIN, 3*YSPACING + 20,
- window=self.dealbutton, anchor=SW)
-
- x = MARGIN
- y = MARGIN
-
- self.deck = Deck(x, y, self)
-
- x = x + XSPACING
- self.opendeck = OpenStack(x, y, self)
-
- x = x + XSPACING
- self.suits = []
- for i in range(NSUITS):
- x = x + XSPACING
- self.suits.append(SuitStack(x, y, self))
-
- x = MARGIN
- y = y + YSPACING
-
- self.rows = []
- for i in range(NROWS):
- self.rows.append(RowStack(x, y, self))
- x = x + XSPACING
-
- self.openstacks = [self.opendeck] + self.suits + self.rows
-
- self.deck.fill()
- self.deal()
+ self.master = master
+
+ self.canvas = Canvas(self.master,
+ background=BACKGROUND,
+ highlightthickness=0,
+ width=NROWS*XSPACING,
+ height=3*YSPACING + 20 + MARGIN)
+ self.canvas.pack(fill=BOTH, expand=TRUE)
+
+ self.dealbutton = Button(self.canvas,
+ text="Deal",
+ highlightthickness=0,
+ background=BACKGROUND,
+ activebackground="green",
+ command=self.deal)
+ Window(self.canvas, MARGIN, 3*YSPACING + 20,
+ window=self.dealbutton, anchor=SW)
+
+ x = MARGIN
+ y = MARGIN
+
+ self.deck = Deck(x, y, self)
+
+ x = x + XSPACING
+ self.opendeck = OpenStack(x, y, self)
+
+ x = x + XSPACING
+ self.suits = []
+ for i in range(NSUITS):
+ x = x + XSPACING
+ self.suits.append(SuitStack(x, y, self))
+
+ x = MARGIN
+ y = y + YSPACING
+
+ self.rows = []
+ for i in range(NROWS):
+ self.rows.append(RowStack(x, y, self))
+ x = x + XSPACING
+
+ self.openstacks = [self.opendeck] + self.suits + self.rows
+
+ self.deck.fill()
+ self.deal()
def wincheck(self):
- for s in self.suits:
- if len(s.cards) != NVALUES:
- return
- self.win()
- self.deal()
+ for s in self.suits:
+ if len(s.cards) != NVALUES:
+ return
+ self.win()
+ self.deal()
def win(self):
- """Stupid animation when you win."""
- cards = []
- for s in self.openstacks:
- cards = cards + s.cards
- while cards:
- card = random.choice(cards)
- cards.remove(card)
- self.animatedmoveto(card, self.deck)
+ """Stupid animation when you win."""
+ cards = []
+ for s in self.openstacks:
+ cards = cards + s.cards
+ while cards:
+ card = random.choice(cards)
+ cards.remove(card)
+ self.animatedmoveto(card, self.deck)
def animatedmoveto(self, card, dest):
- for i in range(10, 0, -1):
- dx, dy = (dest.x-card.x)/i, (dest.y-card.y)/i
- card.moveby(dx, dy)
- self.master.update_idletasks()
+ for i in range(10, 0, -1):
+ dx, dy = (dest.x-card.x)/i, (dest.y-card.y)/i
+ card.moveby(dx, dy)
+ self.master.update_idletasks()
def closeststack(self, card):
- closest = None
- cdist = 999999999
- # Since we only compare distances,
- # we don't bother to take the square root.
- for stack in self.openstacks:
- dist = (stack.x - card.x)**2 + (stack.y - card.y)**2
- if dist < cdist:
- closest = stack
- cdist = dist
- return closest
+ closest = None
+ cdist = 999999999
+ # Since we only compare distances,
+ # we don't bother to take the square root.
+ for stack in self.openstacks:
+ dist = (stack.x - card.x)**2 + (stack.y - card.y)**2
+ if dist < cdist:
+ closest = stack
+ cdist = dist
+ return closest
def deal(self):
- self.reset()
- self.deck.shuffle()
- for i in range(NROWS):
- for r in self.rows[i:]:
- card = self.deck.deal()
- r.add(card)
- for r in self.rows:
- r.showtop()
+ self.reset()
+ self.deck.shuffle()
+ for i in range(NROWS):
+ for r in self.rows[i:]:
+ card = self.deck.deal()
+ r.add(card)
+ for r in self.rows:
+ r.showtop()
def reset(self):
- for stack in self.openstacks:
- while 1:
- card = stack.deal()
- if not card:
- break
- self.deck.add(card)
- card.showback()
+ for stack in self.openstacks:
+ while 1:
+ card = stack.deal()
+ if not card:
+ break
+ self.deck.add(card)
+ card.showback()
# Main function, run when invoked as a stand-alone Python program.
diff --git a/Demo/tkinter/guido/sortvisu.py b/Demo/tkinter/guido/sortvisu.py
index 6fe4002..f18f2c1 100644
--- a/Demo/tkinter/guido/sortvisu.py
+++ b/Demo/tkinter/guido/sortvisu.py
@@ -32,302 +32,302 @@ WIDTH = 6
class Array:
def __init__(self, master, data=None):
- self.master = master
- self.frame = Frame(self.master)
- self.frame.pack(fill=X)
- self.label = Label(self.frame)
- self.label.pack()
- self.canvas = Canvas(self.frame)
- self.canvas.pack()
- self.report = Label(self.frame)
- self.report.pack()
- self.left = Line(self.canvas, 0, 0, 0, 0)
- self.right = Line(self.canvas, 0, 0, 0, 0)
- self.pivot = Line(self.canvas, 0, 0, 0, 0)
- self.items = []
- self.size = self.maxvalue = 0
- if data:
- self.setdata(data)
+ self.master = master
+ self.frame = Frame(self.master)
+ self.frame.pack(fill=X)
+ self.label = Label(self.frame)
+ self.label.pack()
+ self.canvas = Canvas(self.frame)
+ self.canvas.pack()
+ self.report = Label(self.frame)
+ self.report.pack()
+ self.left = Line(self.canvas, 0, 0, 0, 0)
+ self.right = Line(self.canvas, 0, 0, 0, 0)
+ self.pivot = Line(self.canvas, 0, 0, 0, 0)
+ self.items = []
+ self.size = self.maxvalue = 0
+ if data:
+ self.setdata(data)
def setdata(self, data):
- olditems = self.items
- self.items = []
- for item in olditems:
- item.delete()
- self.size = len(data)
- self.maxvalue = max(data)
- self.canvas.config(width=(self.size+1)*XGRID,
- height=(self.maxvalue+1)*YGRID)
- for i in range(self.size):
- self.items.append(ArrayItem(self, i, data[i]))
- self.reset("Sort demo, size %d" % self.size)
+ olditems = self.items
+ self.items = []
+ for item in olditems:
+ item.delete()
+ self.size = len(data)
+ self.maxvalue = max(data)
+ self.canvas.config(width=(self.size+1)*XGRID,
+ height=(self.maxvalue+1)*YGRID)
+ for i in range(self.size):
+ self.items.append(ArrayItem(self, i, data[i]))
+ self.reset("Sort demo, size %d" % self.size)
speed = "normal"
def setspeed(self, speed):
- self.speed = speed
+ self.speed = speed
def destroy(self):
- self.frame.destroy()
+ self.frame.destroy()
in_mainloop = 0
stop_mainloop = 0
def cancel(self):
- self.stop_mainloop = 1
- if self.in_mainloop:
- self.master.quit()
+ self.stop_mainloop = 1
+ if self.in_mainloop:
+ self.master.quit()
def step(self):
- if self.in_mainloop:
- self.master.quit()
+ if self.in_mainloop:
+ self.master.quit()
- Cancelled = "Array.Cancelled" # Exception
+ Cancelled = "Array.Cancelled" # Exception
def wait(self, msecs):
- if self.speed == "fastest":
- msecs = 0
- elif self.speed == "fast":
- msecs = msecs/10
- elif self.speed == "single-step":
- msecs = 1000000000
- if not self.stop_mainloop:
- self.master.update()
- id = self.master.after(msecs, self.master.quit)
- self.in_mainloop = 1
- self.master.mainloop()
- self.master.after_cancel(id)
- self.in_mainloop = 0
- if self.stop_mainloop:
- self.stop_mainloop = 0
- self.message("Cancelled")
- raise Array.Cancelled
+ if self.speed == "fastest":
+ msecs = 0
+ elif self.speed == "fast":
+ msecs = msecs/10
+ elif self.speed == "single-step":
+ msecs = 1000000000
+ if not self.stop_mainloop:
+ self.master.update()
+ id = self.master.after(msecs, self.master.quit)
+ self.in_mainloop = 1
+ self.master.mainloop()
+ self.master.after_cancel(id)
+ self.in_mainloop = 0
+ if self.stop_mainloop:
+ self.stop_mainloop = 0
+ self.message("Cancelled")
+ raise Array.Cancelled
def getsize(self):
- return self.size
+ return self.size
def show_partition(self, first, last):
- for i in range(self.size):
- item = self.items[i]
- if first <= i < last:
- item.item.config(fill='red')
- else:
- item.item.config(fill='orange')
- self.hide_left_right_pivot()
+ for i in range(self.size):
+ item = self.items[i]
+ if first <= i < last:
+ item.item.config(fill='red')
+ else:
+ item.item.config(fill='orange')
+ self.hide_left_right_pivot()
def hide_partition(self):
- for i in range(self.size):
- item = self.items[i]
- item.item.config(fill='red')
- self.hide_left_right_pivot()
+ for i in range(self.size):
+ item = self.items[i]
+ item.item.config(fill='red')
+ self.hide_left_right_pivot()
def show_left(self, left):
- if not 0 <= left < self.size:
- self.hide_left()
- return
- x1, y1, x2, y2 = self.items[left].position()
-## top, bot = HIRO
- self.left.coords([(x1-2, 0), (x1-2, 9999)])
- self.master.update()
+ if not 0 <= left < self.size:
+ self.hide_left()
+ return
+ x1, y1, x2, y2 = self.items[left].position()
+## top, bot = HIRO
+ self.left.coords([(x1-2, 0), (x1-2, 9999)])
+ self.master.update()
def show_right(self, right):
- if not 0 <= right < self.size:
- self.hide_right()
- return
- x1, y1, x2, y2 = self.items[right].position()
- self.right.coords(((x2+2, 0), (x2+2, 9999)))
- self.master.update()
+ if not 0 <= right < self.size:
+ self.hide_right()
+ return
+ x1, y1, x2, y2 = self.items[right].position()
+ self.right.coords(((x2+2, 0), (x2+2, 9999)))
+ self.master.update()
def hide_left_right_pivot(self):
- self.hide_left()
- self.hide_right()
- self.hide_pivot()
+ self.hide_left()
+ self.hide_right()
+ self.hide_pivot()
def hide_left(self):
- self.left.coords(((0, 0), (0, 0)))
+ self.left.coords(((0, 0), (0, 0)))
def hide_right(self):
- self.right.coords(((0, 0), (0, 0)))
+ self.right.coords(((0, 0), (0, 0)))
def show_pivot(self, pivot):
- x1, y1, x2, y2 = self.items[pivot].position()
- self.pivot.coords(((0, y1-2), (9999, y1-2)))
+ x1, y1, x2, y2 = self.items[pivot].position()
+ self.pivot.coords(((0, y1-2), (9999, y1-2)))
def hide_pivot(self):
- self.pivot.coords(((0, 0), (0, 0)))
+ self.pivot.coords(((0, 0), (0, 0)))
def swap(self, i, j):
- if i == j: return
- self.countswap()
- item = self.items[i]
- other = self.items[j]
- self.items[i], self.items[j] = other, item
- item.swapwith(other)
+ if i == j: return
+ self.countswap()
+ item = self.items[i]
+ other = self.items[j]
+ self.items[i], self.items[j] = other, item
+ item.swapwith(other)
def compare(self, i, j):
- self.countcompare()
- item = self.items[i]
- other = self.items[j]
- return item.compareto(other)
+ self.countcompare()
+ item = self.items[i]
+ other = self.items[j]
+ return item.compareto(other)
def reset(self, msg):
- self.ncompares = 0
- self.nswaps = 0
- self.message(msg)
- self.updatereport()
- self.hide_partition()
+ self.ncompares = 0
+ self.nswaps = 0
+ self.message(msg)
+ self.updatereport()
+ self.hide_partition()
def message(self, msg):
- self.label.config(text=msg)
+ self.label.config(text=msg)
def countswap(self):
- self.nswaps = self.nswaps + 1
- self.updatereport()
+ self.nswaps = self.nswaps + 1
+ self.updatereport()
def countcompare(self):
- self.ncompares = self.ncompares + 1
- self.updatereport()
+ self.ncompares = self.ncompares + 1
+ self.updatereport()
def updatereport(self):
- text = "%d cmps, %d swaps" % (self.ncompares, self.nswaps)
- self.report.config(text=text)
+ text = "%d cmps, %d swaps" % (self.ncompares, self.nswaps)
+ self.report.config(text=text)
class ArrayItem:
def __init__(self, array, index, value):
- self.array = array
- self.index = index
- self.value = value
- x1, y1, x2, y2 = self.position()
- self.item = Rectangle(array.canvas, x1, y1, x2, y2,
- fill='red', outline='black', width=1)
- self.item.bind('<Button-1>', self.mouse_down)
- self.item.bind('<Button1-Motion>', self.mouse_move)
- self.item.bind('<ButtonRelease-1>', self.mouse_up)
+ self.array = array
+ self.index = index
+ self.value = value
+ x1, y1, x2, y2 = self.position()
+ self.item = Rectangle(array.canvas, x1, y1, x2, y2,
+ fill='red', outline='black', width=1)
+ self.item.bind('<Button-1>', self.mouse_down)
+ self.item.bind('<Button1-Motion>', self.mouse_move)
+ self.item.bind('<ButtonRelease-1>', self.mouse_up)
def delete(self):
- item = self.item
- self.array = None
- self.item = None
- item.delete()
+ item = self.item
+ self.array = None
+ self.item = None
+ item.delete()
def mouse_down(self, event):
- self.lastx = event.x
- self.lasty = event.y
- self.origx = event.x
- self.origy = event.y
- self.item.tkraise()
-
+ self.lastx = event.x
+ self.lasty = event.y
+ self.origx = event.x
+ self.origy = event.y
+ self.item.tkraise()
+
def mouse_move(self, event):
- self.item.move(event.x - self.lastx, event.y - self.lasty)
- self.lastx = event.x
- self.lasty = event.y
+ self.item.move(event.x - self.lastx, event.y - self.lasty)
+ self.lastx = event.x
+ self.lasty = event.y
def mouse_up(self, event):
- i = self.nearestindex(event.x)
- if i >= self.array.getsize():
- i = self.array.getsize() - 1
- if i < 0:
- i = 0
- other = self.array.items[i]
- here = self.index
- self.array.items[here], self.array.items[i] = other, self
- self.index = i
- x1, y1, x2, y2 = self.position()
- self.item.coords(((x1, y1), (x2, y2)))
- other.setindex(here)
+ i = self.nearestindex(event.x)
+ if i >= self.array.getsize():
+ i = self.array.getsize() - 1
+ if i < 0:
+ i = 0
+ other = self.array.items[i]
+ here = self.index
+ self.array.items[here], self.array.items[i] = other, self
+ self.index = i
+ x1, y1, x2, y2 = self.position()
+ self.item.coords(((x1, y1), (x2, y2)))
+ other.setindex(here)
def setindex(self, index):
- nsteps = steps(self.index, index)
- if not nsteps: return
- if self.array.speed == "fastest":
- nsteps = 0
- oldpts = self.position()
- self.index = index
- newpts = self.position()
- trajectory = interpolate(oldpts, newpts, nsteps)
- self.item.tkraise()
- for pts in trajectory:
- self.item.coords((pts[:2], pts[2:]))
- self.array.wait(50)
+ nsteps = steps(self.index, index)
+ if not nsteps: return
+ if self.array.speed == "fastest":
+ nsteps = 0
+ oldpts = self.position()
+ self.index = index
+ newpts = self.position()
+ trajectory = interpolate(oldpts, newpts, nsteps)
+ self.item.tkraise()
+ for pts in trajectory:
+ self.item.coords((pts[:2], pts[2:]))
+ self.array.wait(50)
def swapwith(self, other):
- nsteps = steps(self.index, other.index)
- if not nsteps: return
- if self.array.speed == "fastest":
- nsteps = 0
- myoldpts = self.position()
- otheroldpts = other.position()
- self.index, other.index = other.index, self.index
- mynewpts = self.position()
- othernewpts = other.position()
- myfill = self.item['fill']
- otherfill = other.item['fill']
- self.item.config(fill='green')
- other.item.config(fill='yellow')
- self.array.master.update()
- if self.array.speed == "single-step":
- self.item.coords((mynewpts[:2], mynewpts[2:]))
- other.item.coords((othernewpts[:2], othernewpts[2:]))
- self.array.master.update()
- self.item.config(fill=myfill)
- other.item.config(fill=otherfill)
- self.array.wait(0)
- return
- mytrajectory = interpolate(myoldpts, mynewpts, nsteps)
- othertrajectory = interpolate(otheroldpts, othernewpts, nsteps)
- if self.value > other.value:
- self.item.tkraise()
- other.item.tkraise()
- else:
- other.item.tkraise()
- self.item.tkraise()
- try:
- for i in range(len(mytrajectory)):
- mypts = mytrajectory[i]
- otherpts = othertrajectory[i]
- self.item.coords((mypts[:2], mypts[2:]))
- other.item.coords((otherpts[:2], otherpts[2:]))
- self.array.wait(50)
- finally:
- mypts = mytrajectory[-1]
- otherpts = othertrajectory[-1]
- self.item.coords((mypts[:2], mypts[2:]))
- other.item.coords((otherpts[:2], otherpts[2:]))
- self.item.config(fill=myfill)
- other.item.config(fill=otherfill)
+ nsteps = steps(self.index, other.index)
+ if not nsteps: return
+ if self.array.speed == "fastest":
+ nsteps = 0
+ myoldpts = self.position()
+ otheroldpts = other.position()
+ self.index, other.index = other.index, self.index
+ mynewpts = self.position()
+ othernewpts = other.position()
+ myfill = self.item['fill']
+ otherfill = other.item['fill']
+ self.item.config(fill='green')
+ other.item.config(fill='yellow')
+ self.array.master.update()
+ if self.array.speed == "single-step":
+ self.item.coords((mynewpts[:2], mynewpts[2:]))
+ other.item.coords((othernewpts[:2], othernewpts[2:]))
+ self.array.master.update()
+ self.item.config(fill=myfill)
+ other.item.config(fill=otherfill)
+ self.array.wait(0)
+ return
+ mytrajectory = interpolate(myoldpts, mynewpts, nsteps)
+ othertrajectory = interpolate(otheroldpts, othernewpts, nsteps)
+ if self.value > other.value:
+ self.item.tkraise()
+ other.item.tkraise()
+ else:
+ other.item.tkraise()
+ self.item.tkraise()
+ try:
+ for i in range(len(mytrajectory)):
+ mypts = mytrajectory[i]
+ otherpts = othertrajectory[i]
+ self.item.coords((mypts[:2], mypts[2:]))
+ other.item.coords((otherpts[:2], otherpts[2:]))
+ self.array.wait(50)
+ finally:
+ mypts = mytrajectory[-1]
+ otherpts = othertrajectory[-1]
+ self.item.coords((mypts[:2], mypts[2:]))
+ other.item.coords((otherpts[:2], otherpts[2:]))
+ self.item.config(fill=myfill)
+ other.item.config(fill=otherfill)
def compareto(self, other):
- myfill = self.item['fill']
- otherfill = other.item['fill']
- outcome = cmp(self.value, other.value)
- if outcome < 0:
- myflash = 'white'
- otherflash = 'black'
- elif outcome > 0:
- myflash = 'black'
- otherflash = 'white'
- else:
- myflash = otherflash = 'grey'
- try:
- self.item.config(fill=myflash)
- other.item.config(fill=otherflash)
- self.array.wait(500)
- finally:
- self.item.config(fill=myfill)
- other.item.config(fill=otherfill)
- return outcome
+ myfill = self.item['fill']
+ otherfill = other.item['fill']
+ outcome = cmp(self.value, other.value)
+ if outcome < 0:
+ myflash = 'white'
+ otherflash = 'black'
+ elif outcome > 0:
+ myflash = 'black'
+ otherflash = 'white'
+ else:
+ myflash = otherflash = 'grey'
+ try:
+ self.item.config(fill=myflash)
+ other.item.config(fill=otherflash)
+ self.array.wait(500)
+ finally:
+ self.item.config(fill=myfill)
+ other.item.config(fill=otherfill)
+ return outcome
def position(self):
- x1 = (self.index+1)*XGRID - WIDTH/2
- x2 = x1+WIDTH
- y2 = (self.array.maxvalue+1)*YGRID
- y1 = y2 - (self.value)*YGRID
- return x1, y1, x2, y2
+ x1 = (self.index+1)*XGRID - WIDTH/2
+ x2 = x1+WIDTH
+ y2 = (self.array.maxvalue+1)*YGRID
+ y1 = y2 - (self.value)*YGRID
+ return x1, y1, x2, y2
def nearestindex(self, x):
- return int(round(float(x)/XGRID)) - 1
+ return int(round(float(x)/XGRID)) - 1
# Subroutines that don't need an object
@@ -335,22 +335,22 @@ class ArrayItem:
def steps(here, there):
nsteps = abs(here - there)
if nsteps <= 3:
- nsteps = nsteps * 3
+ nsteps = nsteps * 3
elif nsteps <= 5:
- nsteps = nsteps * 2
+ nsteps = nsteps * 2
elif nsteps > 10:
- nsteps = 10
+ nsteps = 10
return nsteps
def interpolate(oldpts, newpts, n):
if len(oldpts) != len(newpts):
- raise ValueError, "can't interpolate arrays of different length"
+ raise ValueError, "can't interpolate arrays of different length"
pts = [0]*len(oldpts)
res = [tuple(oldpts)]
for i in range(1, n):
- for k in range(len(pts)):
- pts[k] = oldpts[k] + (newpts[k] - oldpts[k])*i/n
- res.append(tuple(pts))
+ for k in range(len(pts)):
+ pts[k] = oldpts[k] + (newpts[k] - oldpts[k])*i/n
+ res.append(tuple(pts))
res.append(tuple(newpts))
return res
@@ -371,110 +371,110 @@ def randomize(array):
array.reset("Randomizing")
n = array.getsize()
for i in range(n):
- j = random.randint(0, n-1)
- array.swap(i, j)
+ j = random.randint(0, n-1)
+ array.swap(i, j)
array.message("Randomized")
def insertionsort(array):
size = array.getsize()
array.reset("Insertion sort")
for i in range(1, size):
- j = i-1
- while j >= 0:
- if array.compare(j, j+1) <= 0:
- break
- array.swap(j, j+1)
- j = j-1
+ j = i-1
+ while j >= 0:
+ if array.compare(j, j+1) <= 0:
+ break
+ array.swap(j, j+1)
+ j = j-1
array.message("Sorted")
def selectionsort(array):
size = array.getsize()
array.reset("Selection sort")
try:
- for i in range(size):
- array.show_partition(i, size)
- for j in range(i+1, size):
- if array.compare(i, j) > 0:
- array.swap(i, j)
- array.message("Sorted")
+ for i in range(size):
+ array.show_partition(i, size)
+ for j in range(i+1, size):
+ if array.compare(i, j) > 0:
+ array.swap(i, j)
+ array.message("Sorted")
finally:
- array.hide_partition()
+ array.hide_partition()
def bubblesort(array):
size = array.getsize()
array.reset("Bubble sort")
for i in range(size):
- for j in range(1, size):
- if array.compare(j-1, j) > 0:
- array.swap(j-1, j)
+ for j in range(1, size):
+ if array.compare(j-1, j) > 0:
+ array.swap(j-1, j)
array.message("Sorted")
def quicksort(array):
size = array.getsize()
array.reset("Quicksort")
try:
- stack = [(0, size)]
- while stack:
- first, last = stack[-1]
- del stack[-1]
- array.show_partition(first, last)
- if last-first < 5:
- array.message("Insertion sort")
- for i in range(first+1, last):
- j = i-1
- while j >= first:
- if array.compare(j, j+1) <= 0:
- break
- array.swap(j, j+1)
- j = j-1
- continue
- array.message("Choosing pivot")
- j, i, k = first, (first+last)/2, last-1
- if array.compare(k, i) < 0:
- array.swap(k, i)
- if array.compare(k, j) < 0:
- array.swap(k, j)
- if array.compare(j, i) < 0:
- array.swap(j, i)
- pivot = j
- array.show_pivot(pivot)
- array.message("Pivot at left of partition")
- array.wait(1000)
- left = first
- right = last
- while 1:
- array.message("Sweep right pointer")
- right = right-1
- array.show_right(right)
- while right > first and array.compare(right, pivot) >= 0:
- right = right-1
- array.show_right(right)
- array.message("Sweep left pointer")
- left = left+1
- array.show_left(left)
- while left < last and array.compare(left, pivot) <= 0:
- left = left+1
- array.show_left(left)
- if left > right:
- array.message("End of partition")
- break
- array.message("Swap items")
- array.swap(left, right)
- array.message("Swap pivot back")
- array.swap(pivot, right)
- n1 = right-first
- n2 = last-left
- if n1 > 1: stack.append((first, right))
- if n2 > 1: stack.append((left, last))
- array.message("Sorted")
+ stack = [(0, size)]
+ while stack:
+ first, last = stack[-1]
+ del stack[-1]
+ array.show_partition(first, last)
+ if last-first < 5:
+ array.message("Insertion sort")
+ for i in range(first+1, last):
+ j = i-1
+ while j >= first:
+ if array.compare(j, j+1) <= 0:
+ break
+ array.swap(j, j+1)
+ j = j-1
+ continue
+ array.message("Choosing pivot")
+ j, i, k = first, (first+last)/2, last-1
+ if array.compare(k, i) < 0:
+ array.swap(k, i)
+ if array.compare(k, j) < 0:
+ array.swap(k, j)
+ if array.compare(j, i) < 0:
+ array.swap(j, i)
+ pivot = j
+ array.show_pivot(pivot)
+ array.message("Pivot at left of partition")
+ array.wait(1000)
+ left = first
+ right = last
+ while 1:
+ array.message("Sweep right pointer")
+ right = right-1
+ array.show_right(right)
+ while right > first and array.compare(right, pivot) >= 0:
+ right = right-1
+ array.show_right(right)
+ array.message("Sweep left pointer")
+ left = left+1
+ array.show_left(left)
+ while left < last and array.compare(left, pivot) <= 0:
+ left = left+1
+ array.show_left(left)
+ if left > right:
+ array.message("End of partition")
+ break
+ array.message("Swap items")
+ array.swap(left, right)
+ array.message("Swap pivot back")
+ array.swap(pivot, right)
+ n1 = right-first
+ n2 = last-left
+ if n1 > 1: stack.append((first, right))
+ if n2 > 1: stack.append((left, last))
+ array.message("Sorted")
finally:
- array.hide_partition()
+ array.hide_partition()
def demosort(array):
while 1:
- for alg in [quicksort, insertionsort, selectionsort, bubblesort]:
- randomize(array)
- alg(array)
+ for alg in [quicksort, insertionsort, selectionsort, bubblesort]:
+ randomize(array)
+ alg(array)
# Sort demo class -- usable as a Grail applet
@@ -482,144 +482,144 @@ def demosort(array):
class SortDemo:
def __init__(self, master, size=15):
- self.master = master
- self.size = size
- self.busy = 0
- self.array = Array(self.master)
-
- self.botframe = Frame(master)
- self.botframe.pack(side=BOTTOM)
- self.botleftframe = Frame(self.botframe)
- self.botleftframe.pack(side=LEFT, fill=Y)
- self.botrightframe = Frame(self.botframe)
- self.botrightframe.pack(side=RIGHT, fill=Y)
-
- self.b_qsort = Button(self.botleftframe,
- text="Quicksort", command=self.c_qsort)
- self.b_qsort.pack(fill=X)
- self.b_isort = Button(self.botleftframe,
- text="Insertion sort", command=self.c_isort)
- self.b_isort.pack(fill=X)
- self.b_ssort = Button(self.botleftframe,
- text="Selection sort", command=self.c_ssort)
- self.b_ssort.pack(fill=X)
- self.b_bsort = Button(self.botleftframe,
- text="Bubble sort", command=self.c_bsort)
- self.b_bsort.pack(fill=X)
-
- # Terrible hack to overcome limitation of OptionMenu...
- class MyIntVar(IntVar):
- def __init__(self, master, demo):
- self.demo = demo
- IntVar.__init__(self, master)
- def set(self, value):
- IntVar.set(self, value)
- if str(value) != '0':
- self.demo.resize(value)
-
- self.v_size = MyIntVar(self.master, self)
- self.v_size.set(size)
- sizes = [1, 2, 3, 4] + range(5, 55, 5)
- if self.size not in sizes:
- sizes.append(self.size)
- sizes.sort()
- self.m_size = apply(OptionMenu,
- (self.botleftframe, self.v_size) + tuple(sizes))
- self.m_size.pack(fill=X)
-
- self.v_speed = StringVar(self.master)
- self.v_speed.set("normal")
- self.m_speed = OptionMenu(self.botleftframe, self.v_speed,
- "single-step", "normal", "fast", "fastest")
- self.m_speed.pack(fill=X)
-
- self.b_step = Button(self.botleftframe,
- text="Step", command=self.c_step)
- self.b_step.pack(fill=X)
-
- self.b_randomize = Button(self.botrightframe,
- text="Randomize", command=self.c_randomize)
- self.b_randomize.pack(fill=X)
- self.b_uniform = Button(self.botrightframe,
- text="Uniform", command=self.c_uniform)
- self.b_uniform.pack(fill=X)
- self.b_distinct = Button(self.botrightframe,
- text="Distinct", command=self.c_distinct)
- self.b_distinct.pack(fill=X)
- self.b_demo = Button(self.botrightframe,
- text="Demo", command=self.c_demo)
- self.b_demo.pack(fill=X)
- self.b_cancel = Button(self.botrightframe,
- text="Cancel", command=self.c_cancel)
- self.b_cancel.pack(fill=X)
- self.b_cancel.config(state=DISABLED)
- self.b_quit = Button(self.botrightframe,
- text="Quit", command=self.c_quit)
- self.b_quit.pack(fill=X)
+ self.master = master
+ self.size = size
+ self.busy = 0
+ self.array = Array(self.master)
+
+ self.botframe = Frame(master)
+ self.botframe.pack(side=BOTTOM)
+ self.botleftframe = Frame(self.botframe)
+ self.botleftframe.pack(side=LEFT, fill=Y)
+ self.botrightframe = Frame(self.botframe)
+ self.botrightframe.pack(side=RIGHT, fill=Y)
+
+ self.b_qsort = Button(self.botleftframe,
+ text="Quicksort", command=self.c_qsort)
+ self.b_qsort.pack(fill=X)
+ self.b_isort = Button(self.botleftframe,
+ text="Insertion sort", command=self.c_isort)
+ self.b_isort.pack(fill=X)
+ self.b_ssort = Button(self.botleftframe,
+ text="Selection sort", command=self.c_ssort)
+ self.b_ssort.pack(fill=X)
+ self.b_bsort = Button(self.botleftframe,
+ text="Bubble sort", command=self.c_bsort)
+ self.b_bsort.pack(fill=X)
+
+ # Terrible hack to overcome limitation of OptionMenu...
+ class MyIntVar(IntVar):
+ def __init__(self, master, demo):
+ self.demo = demo
+ IntVar.__init__(self, master)
+ def set(self, value):
+ IntVar.set(self, value)
+ if str(value) != '0':
+ self.demo.resize(value)
+
+ self.v_size = MyIntVar(self.master, self)
+ self.v_size.set(size)
+ sizes = [1, 2, 3, 4] + range(5, 55, 5)
+ if self.size not in sizes:
+ sizes.append(self.size)
+ sizes.sort()
+ self.m_size = apply(OptionMenu,
+ (self.botleftframe, self.v_size) + tuple(sizes))
+ self.m_size.pack(fill=X)
+
+ self.v_speed = StringVar(self.master)
+ self.v_speed.set("normal")
+ self.m_speed = OptionMenu(self.botleftframe, self.v_speed,
+ "single-step", "normal", "fast", "fastest")
+ self.m_speed.pack(fill=X)
+
+ self.b_step = Button(self.botleftframe,
+ text="Step", command=self.c_step)
+ self.b_step.pack(fill=X)
+
+ self.b_randomize = Button(self.botrightframe,
+ text="Randomize", command=self.c_randomize)
+ self.b_randomize.pack(fill=X)
+ self.b_uniform = Button(self.botrightframe,
+ text="Uniform", command=self.c_uniform)
+ self.b_uniform.pack(fill=X)
+ self.b_distinct = Button(self.botrightframe,
+ text="Distinct", command=self.c_distinct)
+ self.b_distinct.pack(fill=X)
+ self.b_demo = Button(self.botrightframe,
+ text="Demo", command=self.c_demo)
+ self.b_demo.pack(fill=X)
+ self.b_cancel = Button(self.botrightframe,
+ text="Cancel", command=self.c_cancel)
+ self.b_cancel.pack(fill=X)
+ self.b_cancel.config(state=DISABLED)
+ self.b_quit = Button(self.botrightframe,
+ text="Quit", command=self.c_quit)
+ self.b_quit.pack(fill=X)
def resize(self, newsize):
- if self.busy:
- self.master.bell()
- return
- self.size = newsize
- self.array.setdata(range(1, self.size+1))
+ if self.busy:
+ self.master.bell()
+ return
+ self.size = newsize
+ self.array.setdata(range(1, self.size+1))
def c_qsort(self):
- self.run(quicksort)
+ self.run(quicksort)
def c_isort(self):
- self.run(insertionsort)
+ self.run(insertionsort)
def c_ssort(self):
- self.run(selectionsort)
+ self.run(selectionsort)
def c_bsort(self):
- self.run(bubblesort)
+ self.run(bubblesort)
def c_demo(self):
- self.run(demosort)
+ self.run(demosort)
def c_randomize(self):
- self.run(randomize)
+ self.run(randomize)
def c_uniform(self):
- self.run(uniform)
+ self.run(uniform)
def c_distinct(self):
- self.run(distinct)
+ self.run(distinct)
def run(self, func):
- if self.busy:
- self.master.bell()
- return
- self.busy = 1
- self.array.setspeed(self.v_speed.get())
- self.b_cancel.config(state=NORMAL)
- try:
- func(self.array)
- except Array.Cancelled:
- pass
- self.b_cancel.config(state=DISABLED)
- self.busy = 0
+ if self.busy:
+ self.master.bell()
+ return
+ self.busy = 1
+ self.array.setspeed(self.v_speed.get())
+ self.b_cancel.config(state=NORMAL)
+ try:
+ func(self.array)
+ except Array.Cancelled:
+ pass
+ self.b_cancel.config(state=DISABLED)
+ self.busy = 0
def c_cancel(self):
- if not self.busy:
- self.master.bell()
- return
- self.array.cancel()
+ if not self.busy:
+ self.master.bell()
+ return
+ self.array.cancel()
def c_step(self):
- if not self.busy:
- self.master.bell()
- return
- self.v_speed.set("single-step")
- self.array.setspeed("single-step")
- self.array.step()
+ if not self.busy:
+ self.master.bell()
+ return
+ self.v_speed.set("single-step")
+ self.array.setspeed("single-step")
+ self.array.step()
def c_quit(self):
- if self.busy:
- self.array.cancel()
- self.master.after_idle(self.master.quit)
+ if self.busy:
+ self.array.cancel()
+ self.master.after_idle(self.master.quit)
# Main program -- for stand-alone operation outside Grail
diff --git a/Demo/tkinter/guido/ss1.py b/Demo/tkinter/guido/ss1.py
index 95b3d81..8935475 100644
--- a/Demo/tkinter/guido/ss1.py
+++ b/Demo/tkinter/guido/ss1.py
@@ -315,7 +315,7 @@ class BaseCell:
"""Abstract base class for sheet cells.
Subclasses may but needn't provide the following APIs:
-
+
cell.reset() -- prepare for recalculation
cell.recalc(rexec) -> value -- recalculate formula
cell.format() -> (value, alignment) -- return formatted value
diff --git a/Demo/tkinter/guido/svkill.py b/Demo/tkinter/guido/svkill.py
index 1c54e4b..69f7f3b 100755
--- a/Demo/tkinter/guido/svkill.py
+++ b/Demo/tkinter/guido/svkill.py
@@ -5,7 +5,7 @@
from Tkinter import *
if TkVersion < 4.0:
- raise ImportError, "This version of svkill requires Tk 4.0 or later"
+ raise ImportError, "This version of svkill requires Tk 4.0 or later"
from string import splitfields
from string import split
@@ -15,114 +15,114 @@ import os
user = os.environ['LOGNAME']
class BarButton(Menubutton):
- def __init__(self, master=None, **cnf):
- apply(Menubutton.__init__, (self, master), cnf)
- self.pack(side=LEFT)
- self.menu = Menu(self, name='menu')
- self['menu'] = self.menu
+ def __init__(self, master=None, **cnf):
+ apply(Menubutton.__init__, (self, master), cnf)
+ self.pack(side=LEFT)
+ self.menu = Menu(self, name='menu')
+ self['menu'] = self.menu
class Kill(Frame):
- # List of (name, option, pid_column)
- view_list = [
- ('Default', ''),
- ('Every (-e)', '-e'),
- ('Non process group leaders (-d)', '-d'),
- ('Non leaders with tty (-a)', '-a'),
- ('For this user (-u %s)' % user, '-u %s' % user),
- ]
- format_list = [
- ('Default', '', 0),
- ('Long (-l)', '-l', 3),
- ('Full (-f)', '-f', 1),
- ('Full Long (-f -l)', '-l -f', 3),
- ('Session and group ID (-j)', '-j', 0),
- ('Scheduler properties (-c)', '-c', 0),
- ]
- def kill(self, selected):
- c = self.format_list[self.format.get()][2]
- pid = split(selected)[c]
- os.system('kill -9 ' + pid)
- self.do_update()
- def do_update(self):
- format = self.format_list[self.format.get()][1]
- view = self.view_list[self.view.get()][1]
- s = commands.getoutput('ps %s %s' % (view, format))
- list = splitfields(s, '\n')
- self.header.set(list[0] + ' ')
- del list[0]
- self.frame.list.delete(0, AtEnd())
- for line in list:
- self.frame.list.insert(0, line)
- def do_motion(self, e):
- e.widget.select_clear('0', 'end')
- e.widget.select_set(e.widget.nearest(e.y))
- def do_leave(self, e):
- e.widget.select_clear('0', 'end')
- def do_1(self, e):
- self.kill(e.widget.get(e.widget.nearest(e.y)))
- def __init__(self, master=None, **cnf):
- apply(Frame.__init__, (self, master), cnf)
- self.pack(expand=1, fill=BOTH)
- self.bar = Frame(self, name='bar', relief=RAISED,
- borderwidth=2)
- self.bar.pack(fill=X)
- self.bar.file = BarButton(self.bar, text='File')
- self.bar.file.menu.add_command(
- label='Quit', command=self.quit)
- self.bar.view = BarButton(self.bar, text='View')
- self.bar.format = BarButton(self.bar, text='Format')
- self.view = IntVar(self)
- self.view.set(0)
- self.format = IntVar(self)
- self.format.set(0)
- for num in range(len(self.view_list)):
- label, option = self.view_list[num]
- self.bar.view.menu.add_radiobutton(
- label=label,
- command=self.do_update,
- variable=self.view,
- value=num)
- for num in range(len(self.format_list)):
- label, option, col = self.format_list[num]
- self.bar.format.menu.add_radiobutton(
- label=label,
- command=self.do_update,
- variable=self.format,
- value=num)
- self.bar.tk_menuBar(self.bar.file,
- self.bar.view,
- self.bar.format)
- self.frame = Frame(self, relief=RAISED, borderwidth=2)
- self.frame.pack(expand=1, fill=BOTH)
- self.header = StringVar(self)
- self.frame.label = Label(
- self.frame, relief=FLAT, anchor=NW, borderwidth=0,
- font='*-Courier-Bold-R-Normal-*-120-*',
- textvariable=self.header)
- self.frame.label.pack(fill=Y, anchor=W)
- self.frame.vscroll = Scrollbar(self.frame, orient=VERTICAL)
- self.frame.list = Listbox(
- self.frame,
- relief=SUNKEN,
- font='*-Courier-Medium-R-Normal-*-120-*',
- width=40, height=10,
- selectbackground='#eed5b7',
- selectborderwidth=0,
- selectmode=BROWSE,
- yscroll=self.frame.vscroll.set)
- self.frame.vscroll['command'] = self.frame.list.yview
- self.frame.vscroll.pack(side=RIGHT, fill=Y)
- self.frame.list.pack(expand=1, fill=BOTH)
- self.update = Button(self, text='Update',
- command=self.do_update)
- self.update.pack(fill=X)
- self.frame.list.bind('<Motion>', self.do_motion)
- self.frame.list.bind('<Leave>', self.do_leave)
- self.frame.list.bind('<1>', self.do_1)
- self.do_update()
+ # List of (name, option, pid_column)
+ view_list = [
+ ('Default', ''),
+ ('Every (-e)', '-e'),
+ ('Non process group leaders (-d)', '-d'),
+ ('Non leaders with tty (-a)', '-a'),
+ ('For this user (-u %s)' % user, '-u %s' % user),
+ ]
+ format_list = [
+ ('Default', '', 0),
+ ('Long (-l)', '-l', 3),
+ ('Full (-f)', '-f', 1),
+ ('Full Long (-f -l)', '-l -f', 3),
+ ('Session and group ID (-j)', '-j', 0),
+ ('Scheduler properties (-c)', '-c', 0),
+ ]
+ def kill(self, selected):
+ c = self.format_list[self.format.get()][2]
+ pid = split(selected)[c]
+ os.system('kill -9 ' + pid)
+ self.do_update()
+ def do_update(self):
+ format = self.format_list[self.format.get()][1]
+ view = self.view_list[self.view.get()][1]
+ s = commands.getoutput('ps %s %s' % (view, format))
+ list = splitfields(s, '\n')
+ self.header.set(list[0] + ' ')
+ del list[0]
+ self.frame.list.delete(0, AtEnd())
+ for line in list:
+ self.frame.list.insert(0, line)
+ def do_motion(self, e):
+ e.widget.select_clear('0', 'end')
+ e.widget.select_set(e.widget.nearest(e.y))
+ def do_leave(self, e):
+ e.widget.select_clear('0', 'end')
+ def do_1(self, e):
+ self.kill(e.widget.get(e.widget.nearest(e.y)))
+ def __init__(self, master=None, **cnf):
+ apply(Frame.__init__, (self, master), cnf)
+ self.pack(expand=1, fill=BOTH)
+ self.bar = Frame(self, name='bar', relief=RAISED,
+ borderwidth=2)
+ self.bar.pack(fill=X)
+ self.bar.file = BarButton(self.bar, text='File')
+ self.bar.file.menu.add_command(
+ label='Quit', command=self.quit)
+ self.bar.view = BarButton(self.bar, text='View')
+ self.bar.format = BarButton(self.bar, text='Format')
+ self.view = IntVar(self)
+ self.view.set(0)
+ self.format = IntVar(self)
+ self.format.set(0)
+ for num in range(len(self.view_list)):
+ label, option = self.view_list[num]
+ self.bar.view.menu.add_radiobutton(
+ label=label,
+ command=self.do_update,
+ variable=self.view,
+ value=num)
+ for num in range(len(self.format_list)):
+ label, option, col = self.format_list[num]
+ self.bar.format.menu.add_radiobutton(
+ label=label,
+ command=self.do_update,
+ variable=self.format,
+ value=num)
+ self.bar.tk_menuBar(self.bar.file,
+ self.bar.view,
+ self.bar.format)
+ self.frame = Frame(self, relief=RAISED, borderwidth=2)
+ self.frame.pack(expand=1, fill=BOTH)
+ self.header = StringVar(self)
+ self.frame.label = Label(
+ self.frame, relief=FLAT, anchor=NW, borderwidth=0,
+ font='*-Courier-Bold-R-Normal-*-120-*',
+ textvariable=self.header)
+ self.frame.label.pack(fill=Y, anchor=W)
+ self.frame.vscroll = Scrollbar(self.frame, orient=VERTICAL)
+ self.frame.list = Listbox(
+ self.frame,
+ relief=SUNKEN,
+ font='*-Courier-Medium-R-Normal-*-120-*',
+ width=40, height=10,
+ selectbackground='#eed5b7',
+ selectborderwidth=0,
+ selectmode=BROWSE,
+ yscroll=self.frame.vscroll.set)
+ self.frame.vscroll['command'] = self.frame.list.yview
+ self.frame.vscroll.pack(side=RIGHT, fill=Y)
+ self.frame.list.pack(expand=1, fill=BOTH)
+ self.update = Button(self, text='Update',
+ command=self.do_update)
+ self.update.pack(fill=X)
+ self.frame.list.bind('<Motion>', self.do_motion)
+ self.frame.list.bind('<Leave>', self.do_leave)
+ self.frame.list.bind('<1>', self.do_1)
+ self.do_update()
if __name__ == '__main__':
- kill = Kill(None, borderwidth=5)
- kill.winfo_toplevel().title('Tkinter Process Killer (SYSV)')
- kill.winfo_toplevel().minsize(1, 1)
- kill.mainloop()
+ kill = Kill(None, borderwidth=5)
+ kill.winfo_toplevel().title('Tkinter Process Killer (SYSV)')
+ kill.winfo_toplevel().minsize(1, 1)
+ kill.mainloop()
diff --git a/Demo/tkinter/guido/tkman.py b/Demo/tkinter/guido/tkman.py
index 84672fc..11d9690 100755
--- a/Demo/tkinter/guido/tkman.py
+++ b/Demo/tkinter/guido/tkman.py
@@ -15,253 +15,253 @@ MAN3DIRLIST = ['/depot/sundry/man/man3','/usr/local/man/man3']
foundmanndir = 0
for dir in MANNDIRLIST:
if os.path.exists(dir):
- MANNDIR = dir
- foundmanndir = 1
+ MANNDIR = dir
+ foundmanndir = 1
foundman3dir = 0
for dir in MAN3DIRLIST:
if os.path.exists(dir):
- MAN3DIR = dir
- foundman3dir = 1
+ MAN3DIR = dir
+ foundman3dir = 1
if not foundmanndir or not foundman3dir:
sys.stderr.write('\n')
if not foundmanndir:
- msg = """\
+ msg = """\
Failed to find mann directory.
-Please add the correct entry to the MANNDIRLIST
+Please add the correct entry to the MANNDIRLIST
at the top of %s script.""" % \
sys.argv[0]
- sys.stderr.write("%s\n\n" % msg)
+ sys.stderr.write("%s\n\n" % msg)
if not foundman3dir:
- msg = """\
+ msg = """\
Failed to find man3 directory.
-Please add the correct entry to the MAN3DIRLIST
+Please add the correct entry to the MAN3DIRLIST
at the top of %s script.""" % \
sys.argv[0]
- sys.stderr.write("%s\n\n" % msg)
+ sys.stderr.write("%s\n\n" % msg)
sys.exit(1)
del foundmanndir
del foundman3dir
def listmanpages(mandir):
- files = os.listdir(mandir)
- names = []
- for file in files:
- if file[-2:-1] == '.' and (file[-1] in 'ln123456789'):
- names.append(file[:-2])
- names.sort()
- return names
+ files = os.listdir(mandir)
+ names = []
+ for file in files:
+ if file[-2:-1] == '.' and (file[-1] in 'ln123456789'):
+ names.append(file[:-2])
+ names.sort()
+ return names
class SelectionBox:
- def __init__(self, master=None):
- self.choices = []
+ def __init__(self, master=None):
+ self.choices = []
- self.frame = Frame(master, name="frame")
- self.frame.pack(expand=1, fill=BOTH)
- self.master = self.frame.master
- self.subframe = Frame(self.frame, name="subframe")
- self.subframe.pack(expand=0, fill=BOTH)
- self.leftsubframe = Frame(self.subframe, name='leftsubframe')
- self.leftsubframe.pack(side=LEFT, expand=1, fill=BOTH)
- self.rightsubframe = Frame(self.subframe, name='rightsubframe')
- self.rightsubframe.pack(side=RIGHT, expand=1, fill=BOTH)
- self.chaptervar = StringVar(master)
- self.chapter = Menubutton(self.rightsubframe, name='chapter',
- text='Directory', relief=RAISED,
- borderwidth=2)
- self.chapter.pack(side=TOP)
- self.chaptermenu = Menu(self.chapter, name='chaptermenu')
- self.chaptermenu.add_radiobutton(label='C functions',
- value=MAN3DIR,
- variable=self.chaptervar,
- command=self.newchapter)
- self.chaptermenu.add_radiobutton(label='Tcl/Tk functions',
- value=MANNDIR,
- variable=self.chaptervar,
- command=self.newchapter)
- self.chapter['menu'] = self.chaptermenu
- self.listbox = Listbox(self.rightsubframe, name='listbox',
- relief=SUNKEN, borderwidth=2,
- width=20, height=5)
- self.listbox.pack(expand=1, fill=BOTH)
- self.l1 = Button(self.leftsubframe, name='l1',
- text='Display manual page named:',
- command=self.entry_cb)
- self.l1.pack(side=TOP)
- self.entry = Entry(self.leftsubframe, name='entry',
- relief=SUNKEN, borderwidth=2,
- width=20)
- self.entry.pack(expand=0, fill=X)
- self.l2frame = Frame(self.leftsubframe, name='l2frame')
- self.l2frame.pack(expand=0, fill=NONE)
- self.l2 = Button(self.l2frame, name='l2',
- text='Search regexp:',
- command=self.search_cb)
- self.l2.pack(side=LEFT)
- self.casevar = BooleanVar()
- self.casesense = Checkbutton(self.l2frame, name='casesense',
- text='Case sensitive',
- variable=self.casevar,
- relief=FLAT)
- self.casesense.pack(side=LEFT)
- self.search = Entry(self.leftsubframe, name='search',
- relief=SUNKEN, borderwidth=2,
- width=20)
- self.search.pack(expand=0, fill=X)
- self.title = Label(self.leftsubframe, name='title',
- text='(none)')
- self.title.pack(side=BOTTOM)
- self.text = ManPage(self.frame, name='text',
- relief=SUNKEN, borderwidth=2,
- wrap=NONE, width=72,
- selectbackground='pink')
- self.text.pack(expand=1, fill=BOTH)
+ self.frame = Frame(master, name="frame")
+ self.frame.pack(expand=1, fill=BOTH)
+ self.master = self.frame.master
+ self.subframe = Frame(self.frame, name="subframe")
+ self.subframe.pack(expand=0, fill=BOTH)
+ self.leftsubframe = Frame(self.subframe, name='leftsubframe')
+ self.leftsubframe.pack(side=LEFT, expand=1, fill=BOTH)
+ self.rightsubframe = Frame(self.subframe, name='rightsubframe')
+ self.rightsubframe.pack(side=RIGHT, expand=1, fill=BOTH)
+ self.chaptervar = StringVar(master)
+ self.chapter = Menubutton(self.rightsubframe, name='chapter',
+ text='Directory', relief=RAISED,
+ borderwidth=2)
+ self.chapter.pack(side=TOP)
+ self.chaptermenu = Menu(self.chapter, name='chaptermenu')
+ self.chaptermenu.add_radiobutton(label='C functions',
+ value=MAN3DIR,
+ variable=self.chaptervar,
+ command=self.newchapter)
+ self.chaptermenu.add_radiobutton(label='Tcl/Tk functions',
+ value=MANNDIR,
+ variable=self.chaptervar,
+ command=self.newchapter)
+ self.chapter['menu'] = self.chaptermenu
+ self.listbox = Listbox(self.rightsubframe, name='listbox',
+ relief=SUNKEN, borderwidth=2,
+ width=20, height=5)
+ self.listbox.pack(expand=1, fill=BOTH)
+ self.l1 = Button(self.leftsubframe, name='l1',
+ text='Display manual page named:',
+ command=self.entry_cb)
+ self.l1.pack(side=TOP)
+ self.entry = Entry(self.leftsubframe, name='entry',
+ relief=SUNKEN, borderwidth=2,
+ width=20)
+ self.entry.pack(expand=0, fill=X)
+ self.l2frame = Frame(self.leftsubframe, name='l2frame')
+ self.l2frame.pack(expand=0, fill=NONE)
+ self.l2 = Button(self.l2frame, name='l2',
+ text='Search regexp:',
+ command=self.search_cb)
+ self.l2.pack(side=LEFT)
+ self.casevar = BooleanVar()
+ self.casesense = Checkbutton(self.l2frame, name='casesense',
+ text='Case sensitive',
+ variable=self.casevar,
+ relief=FLAT)
+ self.casesense.pack(side=LEFT)
+ self.search = Entry(self.leftsubframe, name='search',
+ relief=SUNKEN, borderwidth=2,
+ width=20)
+ self.search.pack(expand=0, fill=X)
+ self.title = Label(self.leftsubframe, name='title',
+ text='(none)')
+ self.title.pack(side=BOTTOM)
+ self.text = ManPage(self.frame, name='text',
+ relief=SUNKEN, borderwidth=2,
+ wrap=NONE, width=72,
+ selectbackground='pink')
+ self.text.pack(expand=1, fill=BOTH)
- self.entry.bind('<Return>', self.entry_cb)
- self.search.bind('<Return>', self.search_cb)
- self.listbox.bind('<Double-1>', self.listbox_cb)
+ self.entry.bind('<Return>', self.entry_cb)
+ self.search.bind('<Return>', self.search_cb)
+ self.listbox.bind('<Double-1>', self.listbox_cb)
- self.entry.bind('<Tab>', self.entry_tab)
- self.search.bind('<Tab>', self.search_tab)
- self.text.bind('<Tab>', self.text_tab)
+ self.entry.bind('<Tab>', self.entry_tab)
+ self.search.bind('<Tab>', self.search_tab)
+ self.text.bind('<Tab>', self.text_tab)
- self.entry.focus_set()
+ self.entry.focus_set()
- self.chaptervar.set(MANNDIR)
- self.newchapter()
+ self.chaptervar.set(MANNDIR)
+ self.newchapter()
- def newchapter(self):
- mandir = self.chaptervar.get()
- self.choices = []
- self.addlist(listmanpages(mandir))
+ def newchapter(self):
+ mandir = self.chaptervar.get()
+ self.choices = []
+ self.addlist(listmanpages(mandir))
- def addchoice(self, choice):
- if choice not in self.choices:
- self.choices.append(choice)
- self.choices.sort()
- self.update()
+ def addchoice(self, choice):
+ if choice not in self.choices:
+ self.choices.append(choice)
+ self.choices.sort()
+ self.update()
- def addlist(self, list):
- self.choices[len(self.choices):] = list
- self.choices.sort()
- self.update()
+ def addlist(self, list):
+ self.choices[len(self.choices):] = list
+ self.choices.sort()
+ self.update()
- def entry_cb(self, *e):
- self.update()
+ def entry_cb(self, *e):
+ self.update()
- def listbox_cb(self, e):
- selection = self.listbox.curselection()
- if selection and len(selection) == 1:
- name = self.listbox.get(selection[0])
- self.show_page(name)
+ def listbox_cb(self, e):
+ selection = self.listbox.curselection()
+ if selection and len(selection) == 1:
+ name = self.listbox.get(selection[0])
+ self.show_page(name)
- def search_cb(self, *e):
- self.search_string(self.search.get())
+ def search_cb(self, *e):
+ self.search_string(self.search.get())
- def entry_tab(self, e):
- self.search.focus_set()
+ def entry_tab(self, e):
+ self.search.focus_set()
- def search_tab(self, e):
- self.entry.focus_set()
+ def search_tab(self, e):
+ self.entry.focus_set()
- def text_tab(self, e):
- self.entry.focus_set()
+ def text_tab(self, e):
+ self.entry.focus_set()
- def updatelist(self):
- key = self.entry.get()
- ok = filter(lambda name, key=key, n=len(key): name[:n]==key,
- self.choices)
- if not ok:
- self.frame.bell()
- self.listbox.delete(0, AtEnd())
- exactmatch = 0
- for item in ok:
- if item == key: exactmatch = 1
- self.listbox.insert(AtEnd(), item)
- if exactmatch:
- return key
- n = self.listbox.size()
- if n == 1:
- return self.listbox.get(0)
- # Else return None, meaning not a unique selection
+ def updatelist(self):
+ key = self.entry.get()
+ ok = filter(lambda name, key=key, n=len(key): name[:n]==key,
+ self.choices)
+ if not ok:
+ self.frame.bell()
+ self.listbox.delete(0, AtEnd())
+ exactmatch = 0
+ for item in ok:
+ if item == key: exactmatch = 1
+ self.listbox.insert(AtEnd(), item)
+ if exactmatch:
+ return key
+ n = self.listbox.size()
+ if n == 1:
+ return self.listbox.get(0)
+ # Else return None, meaning not a unique selection
- def update(self):
- name = self.updatelist()
- if name:
- self.show_page(name)
- self.entry.delete(0, AtEnd())
- self.updatelist()
+ def update(self):
+ name = self.updatelist()
+ if name:
+ self.show_page(name)
+ self.entry.delete(0, AtEnd())
+ self.updatelist()
- def show_page(self, name):
- file = '%s/%s.?' % (self.chaptervar.get(), name)
- fp = os.popen('nroff -man %s | ul -i' % file, 'r')
- self.text.kill()
- self.title['text'] = name
- self.text.parsefile(fp)
+ def show_page(self, name):
+ file = '%s/%s.?' % (self.chaptervar.get(), name)
+ fp = os.popen('nroff -man %s | ul -i' % file, 'r')
+ self.text.kill()
+ self.title['text'] = name
+ self.text.parsefile(fp)
- def search_string(self, search):
- if not search:
- self.frame.bell()
- print 'Empty search string'
- return
- if not self.casevar.get():
- map = regex.casefold
- else:
- map = None
- try:
- if map:
- prog = regex.compile(search, map)
- else:
- prog = regex.compile(search)
- except regex.error, msg:
- self.frame.bell()
- print 'Regex error:', msg
- return
- here = self.text.index(AtInsert())
- lineno = string.atoi(here[:string.find(here, '.')])
- end = self.text.index(AtEnd())
- endlineno = string.atoi(end[:string.find(end, '.')])
- wraplineno = lineno
- found = 0
- while 1:
- lineno = lineno + 1
- if lineno > endlineno:
- if wraplineno <= 0:
- break
- endlineno = wraplineno
- lineno = 0
- wraplineno = 0
- line = self.text.get('%d.0 linestart' % lineno,
- '%d.0 lineend' % lineno)
- i = prog.search(line)
- if i >= 0:
- found = 1
- n = max(1, len(prog.group(0)))
- try:
- self.text.tag_remove('sel',
- AtSelFirst(),
- AtSelLast())
- except TclError:
- pass
- self.text.tag_add('sel',
- '%d.%d' % (lineno, i),
- '%d.%d' % (lineno, i+n))
- self.text.mark_set(AtInsert(),
- '%d.%d' % (lineno, i))
- self.text.yview_pickplace(AtInsert())
- break
- if not found:
- self.frame.bell()
+ def search_string(self, search):
+ if not search:
+ self.frame.bell()
+ print 'Empty search string'
+ return
+ if not self.casevar.get():
+ map = regex.casefold
+ else:
+ map = None
+ try:
+ if map:
+ prog = regex.compile(search, map)
+ else:
+ prog = regex.compile(search)
+ except regex.error, msg:
+ self.frame.bell()
+ print 'Regex error:', msg
+ return
+ here = self.text.index(AtInsert())
+ lineno = string.atoi(here[:string.find(here, '.')])
+ end = self.text.index(AtEnd())
+ endlineno = string.atoi(end[:string.find(end, '.')])
+ wraplineno = lineno
+ found = 0
+ while 1:
+ lineno = lineno + 1
+ if lineno > endlineno:
+ if wraplineno <= 0:
+ break
+ endlineno = wraplineno
+ lineno = 0
+ wraplineno = 0
+ line = self.text.get('%d.0 linestart' % lineno,
+ '%d.0 lineend' % lineno)
+ i = prog.search(line)
+ if i >= 0:
+ found = 1
+ n = max(1, len(prog.group(0)))
+ try:
+ self.text.tag_remove('sel',
+ AtSelFirst(),
+ AtSelLast())
+ except TclError:
+ pass
+ self.text.tag_add('sel',
+ '%d.%d' % (lineno, i),
+ '%d.%d' % (lineno, i+n))
+ self.text.mark_set(AtInsert(),
+ '%d.%d' % (lineno, i))
+ self.text.yview_pickplace(AtInsert())
+ break
+ if not found:
+ self.frame.bell()
def main():
- root = Tk()
- sb = SelectionBox(root)
- if sys.argv[1:]:
- sb.show_page(sys.argv[1])
- root.minsize(1, 1)
- root.mainloop()
+ root = Tk()
+ sb = SelectionBox(root)
+ if sys.argv[1:]:
+ sb.show_page(sys.argv[1])
+ root.minsize(1, 1)
+ root.mainloop()
main()
diff --git a/Demo/tkinter/guido/wish.py b/Demo/tkinter/guido/wish.py
index 4f6fdee..0a61ad8 100755
--- a/Demo/tkinter/guido/wish.py
+++ b/Demo/tkinter/guido/wish.py
@@ -9,19 +9,19 @@ tk.call('update')
cmd = ''
while 1:
- if cmd: prompt = ''
- else: prompt = '% '
- try:
- line = raw_input(prompt)
- except EOFError:
- break
- cmd = cmd + (line + '\n')
- if tk.getboolean(tk.call('info', 'complete', cmd)):
- tk.record(line)
- try:
- result = tk.call('eval', cmd)
- except _tkinter.TclError, msg:
- print 'TclError:', msg
- else:
- if result: print result
- cmd = ''
+ if cmd: prompt = ''
+ else: prompt = '% '
+ try:
+ line = raw_input(prompt)
+ except EOFError:
+ break
+ cmd = cmd + (line + '\n')
+ if tk.getboolean(tk.call('info', 'complete', cmd)):
+ tk.record(line)
+ try:
+ result = tk.call('eval', cmd)
+ except _tkinter.TclError, msg:
+ print 'TclError:', msg
+ else:
+ if result: print result
+ cmd = ''
diff --git a/Demo/tkinter/matt/00-HELLO-WORLD.py b/Demo/tkinter/matt/00-HELLO-WORLD.py
index a32941b..1c3151b 100644
--- a/Demo/tkinter/matt/00-HELLO-WORLD.py
+++ b/Demo/tkinter/matt/00-HELLO-WORLD.py
@@ -1,27 +1,27 @@
from Tkinter import *
-# note that there is no explicit call to start Tk.
-# Tkinter is smart enough to start the system if it's not already going.
+# note that there is no explicit call to start Tk.
+# Tkinter is smart enough to start the system if it's not already going.
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
-
- self.QUIT.pack(side=LEFT, fill=BOTH)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
- # a hello button
- self.hi_there = Button(self, text='Hello',
- command=self.printit)
- self.hi_there.pack(side=LEFT)
+ self.QUIT.pack(side=LEFT, fill=BOTH)
+
+ # a hello button
+ self.hi_there = Button(self, text='Hello',
+ command=self.printit)
+ self.hi_there.pack(side=LEFT)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
test.mainloop()
diff --git a/Demo/tkinter/matt/animation-simple.py b/Demo/tkinter/matt/animation-simple.py
index 435d6fa..b52e1dc 100644
--- a/Demo/tkinter/matt/animation-simple.py
+++ b/Demo/tkinter/matt/animation-simple.py
@@ -4,30 +4,30 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=LEFT, fill=BOTH)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=LEFT, fill=BOTH)
- self.draw = Canvas(self, width="5i", height="5i")
+ self.draw = Canvas(self, width="5i", height="5i")
- # all of these work..
- self.draw.create_rectangle(0, 0, 10, 10, tags="thing", fill="blue")
- self.draw.pack(side=LEFT)
+ # all of these work..
+ self.draw.create_rectangle(0, 0, 10, 10, tags="thing", fill="blue")
+ self.draw.pack(side=LEFT)
def moveThing(self, *args):
- # move 1/10 of an inch every 1/10 sec (1" per second, smoothly)
- self.draw.move("thing", "0.01i", "0.01i")
- self.after(10, self.moveThing)
+ # move 1/10 of an inch every 1/10 sec (1" per second, smoothly)
+ self.draw.move("thing", "0.01i", "0.01i")
+ self.after(10, self.moveThing)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
- self.after(10, self.moveThing)
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
+ self.after(10, self.moveThing)
test = Test()
diff --git a/Demo/tkinter/matt/animation-w-velocity-ctrl.py b/Demo/tkinter/matt/animation-w-velocity-ctrl.py
index f3332f2..e676338 100644
--- a/Demo/tkinter/matt/animation-w-velocity-ctrl.py
+++ b/Demo/tkinter/matt/animation-w-velocity-ctrl.py
@@ -1,42 +1,42 @@
from Tkinter import *
-# this is the same as simple-demo-1.py, but uses
-# subclassing.
-# note that there is no explicit call to start Tk.
-# Tkinter is smart enough to start the system if it's not already going.
+# this is the same as simple-demo-1.py, but uses
+# subclassing.
+# note that there is no explicit call to start Tk.
+# Tkinter is smart enough to start the system if it's not already going.
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=BOTTOM, fill=BOTH)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=BOTTOM, fill=BOTH)
- self.draw = Canvas(self, width="5i", height="5i")
+ self.draw = Canvas(self, width="5i", height="5i")
- self.speed = Scale(self, orient=HORIZONTAL, from_=-100, to=100)
+ self.speed = Scale(self, orient=HORIZONTAL, from_=-100, to=100)
- self.speed.pack(side=BOTTOM, fill=X)
+ self.speed.pack(side=BOTTOM, fill=X)
- # all of these work..
- self.draw.create_rectangle(0, 0, 10, 10, tags="thing", fill="blue")
- self.draw.pack(side=LEFT)
+ # all of these work..
+ self.draw.create_rectangle(0, 0, 10, 10, tags="thing", fill="blue")
+ self.draw.pack(side=LEFT)
def moveThing(self, *args):
- velocity = self.speed.get()
- str = float(velocity) / 1000.0
- str = "%ri" % (str,)
- self.draw.move("thing", str, str)
- self.after(10, self.moveThing)
+ velocity = self.speed.get()
+ str = float(velocity) / 1000.0
+ str = "%ri" % (str,)
+ self.draw.move("thing", str, str)
+ self.after(10, self.moveThing)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
- self.after(10, self.moveThing)
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
+ self.after(10, self.moveThing)
test = Test()
diff --git a/Demo/tkinter/matt/bind-w-mult-calls-p-type.py b/Demo/tkinter/matt/bind-w-mult-calls-p-type.py
index 0907e41..f3220da 100644
--- a/Demo/tkinter/matt/bind-w-mult-calls-p-type.py
+++ b/Demo/tkinter/matt/bind-w-mult-calls-p-type.py
@@ -1,34 +1,34 @@
from Tkinter import *
-import string
+import string
# This program shows how to use a simple type-in box
class App(Frame):
def __init__(self, master=None):
- Frame.__init__(self, master)
- self.pack()
+ Frame.__init__(self, master)
+ self.pack()
- self.entrythingy = Entry()
- self.entrythingy.pack()
+ self.entrythingy = Entry()
+ self.entrythingy.pack()
- # and here we get a callback when the user hits return. we could
- # make the key that triggers the callback anything we wanted to.
- # other typical options might be <Key-Tab> or <Key> (for anything)
- self.entrythingy.bind('<Key-Return>', self.print_contents)
+ # and here we get a callback when the user hits return. we could
+ # make the key that triggers the callback anything we wanted to.
+ # other typical options might be <Key-Tab> or <Key> (for anything)
+ self.entrythingy.bind('<Key-Return>', self.print_contents)
- # Note that here is where we bind a completely different callback to
- # the same event. We pass "+" here to indicate that we wish to ADD
- # this callback to the list associated with this event type.
- # Not specifying "+" would simply override whatever callback was
- # defined on this event.
- self.entrythingy.bind('<Key-Return>', self.print_something_else, "+")
+ # Note that here is where we bind a completely different callback to
+ # the same event. We pass "+" here to indicate that we wish to ADD
+ # this callback to the list associated with this event type.
+ # Not specifying "+" would simply override whatever callback was
+ # defined on this event.
+ self.entrythingy.bind('<Key-Return>', self.print_something_else, "+")
def print_contents(self, event):
- print "hi. contents of entry is now ---->", self.entrythingy.get()
+ print "hi. contents of entry is now ---->", self.entrythingy.get()
def print_something_else(self, event):
- print "hi. Now doing something completely different"
+ print "hi. Now doing something completely different"
root = App()
@@ -37,8 +37,8 @@ root.mainloop()
-# secret tip for experts: if you pass *any* non-false value as
-# the third parameter to bind(), Tkinter.py will accumulate
+# secret tip for experts: if you pass *any* non-false value as
+# the third parameter to bind(), Tkinter.py will accumulate
# callbacks instead of overwriting. I use "+" here because that's
-# the Tk notation for getting this sort of behavior. The perfect GUI
+# the Tk notation for getting this sort of behavior. The perfect GUI
# interface would use a less obscure notation.
diff --git a/Demo/tkinter/matt/canvas-demo-simple.py b/Demo/tkinter/matt/canvas-demo-simple.py
index d989626..a01679a 100644
--- a/Demo/tkinter/matt/canvas-demo-simple.py
+++ b/Demo/tkinter/matt/canvas-demo-simple.py
@@ -4,24 +4,24 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=BOTTOM, fill=BOTH)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=BOTTOM, fill=BOTH)
- self.draw = Canvas(self, width="5i", height="5i")
+ self.draw = Canvas(self, width="5i", height="5i")
- # see the other demos for other ways of specifying coords for a polygon
- self.draw.create_rectangle(0, 0, "3i", "3i", fill="black")
+ # see the other demos for other ways of specifying coords for a polygon
+ self.draw.create_rectangle(0, 0, "3i", "3i", fill="black")
- self.draw.pack(side=LEFT)
+ self.draw.pack(side=LEFT)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
diff --git a/Demo/tkinter/matt/canvas-gridding.py b/Demo/tkinter/matt/canvas-gridding.py
index b200ea4..3c52b91 100644
--- a/Demo/tkinter/matt/canvas-gridding.py
+++ b/Demo/tkinter/matt/canvas-gridding.py
@@ -1,60 +1,60 @@
from Tkinter import *
-# this is the same as simple-demo-1.py, but uses
-# subclassing.
-# note that there is no explicit call to start Tk.
-# Tkinter is smart enough to start the system if it's not already going.
+# this is the same as simple-demo-1.py, but uses
+# subclassing.
+# note that there is no explicit call to start Tk.
+# Tkinter is smart enough to start the system if it's not already going.
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT',
- background='red',
- foreground='white',
- height=3,
- command=self.quit)
- self.QUIT.pack(side=BOTTOM, fill=BOTH)
+ self.QUIT = Button(self, text='QUIT',
+ background='red',
+ foreground='white',
+ height=3,
+ command=self.quit)
+ self.QUIT.pack(side=BOTTOM, fill=BOTH)
- self.canvasObject = Canvas(self, width="5i", height="5i")
- self.canvasObject.pack(side=LEFT)
+ self.canvasObject = Canvas(self, width="5i", height="5i")
+ self.canvasObject.pack(side=LEFT)
def mouseDown(self, event):
- # canvas x and y take the screen coords from the event and translate
- # them into the coordinate system of the canvas object
- self.startx = self.canvasObject.canvasx(event.x, self.griddingSize)
- self.starty = self.canvasObject.canvasy(event.y, self.griddingSize)
+ # canvas x and y take the screen coords from the event and translate
+ # them into the coordinate system of the canvas object
+ self.startx = self.canvasObject.canvasx(event.x, self.griddingSize)
+ self.starty = self.canvasObject.canvasy(event.y, self.griddingSize)
def mouseMotion(self, event):
- # canvas x and y take the screen coords from the event and translate
- # them into the coordinate system of the canvas object
- x = self.canvasObject.canvasx(event.x, self.griddingSize)
- y = self.canvasObject.canvasy(event.y, self.griddingSize)
-
- if (self.startx != event.x) and (self.starty != event.y) :
- self.canvasObject.delete(self.rubberbandBox)
- self.rubberbandBox = self.canvasObject.create_rectangle(
- self.startx, self.starty, x, y)
- # this flushes the output, making sure that
- # the rectangle makes it to the screen
- # before the next event is handled
- self.update_idletasks()
+ # canvas x and y take the screen coords from the event and translate
+ # them into the coordinate system of the canvas object
+ x = self.canvasObject.canvasx(event.x, self.griddingSize)
+ y = self.canvasObject.canvasy(event.y, self.griddingSize)
+
+ if (self.startx != event.x) and (self.starty != event.y) :
+ self.canvasObject.delete(self.rubberbandBox)
+ self.rubberbandBox = self.canvasObject.create_rectangle(
+ self.startx, self.starty, x, y)
+ # this flushes the output, making sure that
+ # the rectangle makes it to the screen
+ # before the next event is handled
+ self.update_idletasks()
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
- # this is a "tagOrId" for the rectangle we draw on the canvas
- self.rubberbandBox = None
+ # this is a "tagOrId" for the rectangle we draw on the canvas
+ self.rubberbandBox = None
- # this is the size of the gridding squares
- self.griddingSize = 50
+ # this is the size of the gridding squares
+ self.griddingSize = 50
+
+ Widget.bind(self.canvasObject, "<Button-1>", self.mouseDown)
+ Widget.bind(self.canvasObject, "<Button1-Motion>", self.mouseMotion)
- Widget.bind(self.canvasObject, "<Button-1>", self.mouseDown)
- Widget.bind(self.canvasObject, "<Button1-Motion>", self.mouseMotion)
-
test = Test()
diff --git a/Demo/tkinter/matt/canvas-moving-or-creating.py b/Demo/tkinter/matt/canvas-moving-or-creating.py
index 74729a6..5327c08 100644
--- a/Demo/tkinter/matt/canvas-moving-or-creating.py
+++ b/Demo/tkinter/matt/canvas-moving-or-creating.py
@@ -1,6 +1,6 @@
from Tkinter import *
-# this file demonstrates a more sophisticated movement --
+# this file demonstrates a more sophisticated movement --
# move dots or create new ones if you click outside the dots
class Test(Frame):
@@ -8,58 +8,55 @@ class Test(Frame):
###### Event callbacks for THE CANVAS (not the stuff drawn on it)
###################################################################
def mouseDown(self, event):
- # see if we're inside a dot. If we are, it
- # gets tagged as CURRENT for free by tk.
- if not event.widget.find_withtag(CURRENT):
- # there is no dot here, so we can make one,
- # and bind some interesting behavior to it.
- # ------
- # create a dot, and mark it as CURRENT
- fred = self.draw.create_oval(
- event.x - 10, event.y -10, event.x +10, event.y + 10,
- fill="green", tags=CURRENT)
-
- self.draw.tag_bind(fred, "<Any-Enter>", self.mouseEnter)
- self.draw.tag_bind(fred, "<Any-Leave>", self.mouseLeave)
-
- self.lastx = event.x
- self.lasty = event.y
+ # see if we're inside a dot. If we are, it
+ # gets tagged as CURRENT for free by tk.
+ if not event.widget.find_withtag(CURRENT):
+ # there is no dot here, so we can make one,
+ # and bind some interesting behavior to it.
+ # ------
+ # create a dot, and mark it as CURRENT
+ fred = self.draw.create_oval(
+ event.x - 10, event.y -10, event.x +10, event.y + 10,
+ fill="green", tags=CURRENT)
+
+ self.draw.tag_bind(fred, "<Any-Enter>", self.mouseEnter)
+ self.draw.tag_bind(fred, "<Any-Leave>", self.mouseLeave)
+
+ self.lastx = event.x
+ self.lasty = event.y
def mouseMove(self, event):
- self.draw.move(CURRENT, event.x - self.lastx, event.y - self.lasty)
- self.lastx = event.x
- self.lasty = event.y
+ self.draw.move(CURRENT, event.x - self.lastx, event.y - self.lasty)
+ self.lastx = event.x
+ self.lasty = event.y
###################################################################
###### Event callbacks for canvas ITEMS (stuff drawn on the canvas)
###################################################################
def mouseEnter(self, event):
# the CURRENT tag is applied to the object the cursor is over.
- # this happens automatically.
- self.draw.itemconfig(CURRENT, fill="red")
+ # this happens automatically.
+ self.draw.itemconfig(CURRENT, fill="red")
def mouseLeave(self, event):
- # the CURRENT tag is applied to the object the cursor is over.
- # this happens automatically.
- self.draw.itemconfig(CURRENT, fill="blue")
+ # the CURRENT tag is applied to the object the cursor is over.
+ # this happens automatically.
+ self.draw.itemconfig(CURRENT, fill="blue")
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=LEFT, fill=BOTH)
- self.draw = Canvas(self, width="5i", height="5i")
- self.draw.pack(side=LEFT)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=LEFT, fill=BOTH)
+ self.draw = Canvas(self, width="5i", height="5i")
+ self.draw.pack(side=LEFT)
- Widget.bind(self.draw, "<1>", self.mouseDown)
- Widget.bind(self.draw, "<B1-Motion>", self.mouseMove)
+ Widget.bind(self.draw, "<1>", self.mouseDown)
+ Widget.bind(self.draw, "<B1-Motion>", self.mouseMove)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
test.mainloop()
-
-
-
diff --git a/Demo/tkinter/matt/canvas-moving-w-mouse.py b/Demo/tkinter/matt/canvas-moving-w-mouse.py
index 447e290..81785d8 100644
--- a/Demo/tkinter/matt/canvas-moving-w-mouse.py
+++ b/Demo/tkinter/matt/canvas-moving-w-mouse.py
@@ -7,49 +7,49 @@ class Test(Frame):
###### Event callbacks for THE CANVAS (not the stuff drawn on it)
###################################################################
def mouseDown(self, event):
- # remember where the mouse went down
- self.lastx = event.x
- self.lasty = event.y
+ # remember where the mouse went down
+ self.lastx = event.x
+ self.lasty = event.y
def mouseMove(self, event):
- # whatever the mouse is over gets tagged as CURRENT for free by tk.
- self.draw.move(CURRENT, event.x - self.lastx, event.y - self.lasty)
- self.lastx = event.x
- self.lasty = event.y
+ # whatever the mouse is over gets tagged as CURRENT for free by tk.
+ self.draw.move(CURRENT, event.x - self.lastx, event.y - self.lasty)
+ self.lastx = event.x
+ self.lasty = event.y
###################################################################
###### Event callbacks for canvas ITEMS (stuff drawn on the canvas)
###################################################################
def mouseEnter(self, event):
# the CURRENT tag is applied to the object the cursor is over.
- # this happens automatically.
- self.draw.itemconfig(CURRENT, fill="red")
-
+ # this happens automatically.
+ self.draw.itemconfig(CURRENT, fill="red")
+
def mouseLeave(self, event):
- # the CURRENT tag is applied to the object the cursor is over.
- # this happens automatically.
- self.draw.itemconfig(CURRENT, fill="blue")
+ # the CURRENT tag is applied to the object the cursor is over.
+ # this happens automatically.
+ self.draw.itemconfig(CURRENT, fill="blue")
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=LEFT, fill=BOTH)
- self.draw = Canvas(self, width="5i", height="5i")
- self.draw.pack(side=LEFT)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=LEFT, fill=BOTH)
+ self.draw = Canvas(self, width="5i", height="5i")
+ self.draw.pack(side=LEFT)
- fred = self.draw.create_oval(0, 0, 20, 20,
- fill="green", tags="selected")
+ fred = self.draw.create_oval(0, 0, 20, 20,
+ fill="green", tags="selected")
- self.draw.tag_bind(fred, "<Any-Enter>", self.mouseEnter)
- self.draw.tag_bind(fred, "<Any-Leave>", self.mouseLeave)
+ self.draw.tag_bind(fred, "<Any-Enter>", self.mouseEnter)
+ self.draw.tag_bind(fred, "<Any-Leave>", self.mouseLeave)
- Widget.bind(self.draw, "<1>", self.mouseDown)
- Widget.bind(self.draw, "<B1-Motion>", self.mouseMove)
+ Widget.bind(self.draw, "<1>", self.mouseDown)
+ Widget.bind(self.draw, "<B1-Motion>", self.mouseMove)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
test.mainloop()
diff --git a/Demo/tkinter/matt/canvas-mult-item-sel.py b/Demo/tkinter/matt/canvas-mult-item-sel.py
index 2368733..a4f267c 100644
--- a/Demo/tkinter/matt/canvas-mult-item-sel.py
+++ b/Demo/tkinter/matt/canvas-mult-item-sel.py
@@ -1,6 +1,6 @@
from Tkinter import *
-# allows moving dots with multiple selection.
+# allows moving dots with multiple selection.
SELECTED_COLOR = "red"
UNSELECTED_COLOR = "blue"
@@ -10,72 +10,69 @@ class Test(Frame):
###### Event callbacks for THE CANVAS (not the stuff drawn on it)
###################################################################
def mouseDown(self, event):
- # see if we're inside a dot. If we are, it
- # gets tagged as CURRENT for free by tk.
-
- if not event.widget.find_withtag(CURRENT):
- # we clicked outside of all dots on the canvas. unselect all.
-
- # re-color everything back to an unselected color
- self.draw.itemconfig("selected", fill=UNSELECTED_COLOR)
- # unselect everything
- self.draw.dtag("selected")
- else:
- # mark as "selected" the thing the cursor is under
- self.draw.addtag("selected", "withtag", CURRENT)
- # color it as selected
- self.draw.itemconfig("selected", fill=SELECTED_COLOR)
-
- self.lastx = event.x
- self.lasty = event.y
-
-
+ # see if we're inside a dot. If we are, it
+ # gets tagged as CURRENT for free by tk.
+
+ if not event.widget.find_withtag(CURRENT):
+ # we clicked outside of all dots on the canvas. unselect all.
+
+ # re-color everything back to an unselected color
+ self.draw.itemconfig("selected", fill=UNSELECTED_COLOR)
+ # unselect everything
+ self.draw.dtag("selected")
+ else:
+ # mark as "selected" the thing the cursor is under
+ self.draw.addtag("selected", "withtag", CURRENT)
+ # color it as selected
+ self.draw.itemconfig("selected", fill=SELECTED_COLOR)
+
+ self.lastx = event.x
+ self.lasty = event.y
+
+
def mouseMove(self, event):
- self.draw.move("selected", event.x - self.lastx, event.y - self.lasty)
- self.lastx = event.x
- self.lasty = event.y
+ self.draw.move("selected", event.x - self.lastx, event.y - self.lasty)
+ self.lastx = event.x
+ self.lasty = event.y
def makeNewDot(self):
- # create a dot, and mark it as current
- fred = self.draw.create_oval(0, 0, 20, 20,
- fill=SELECTED_COLOR, tags=CURRENT)
- # and make it selected
- self.draw.addtag("selected", "withtag", CURRENT)
-
+ # create a dot, and mark it as current
+ fred = self.draw.create_oval(0, 0, 20, 20,
+ fill=SELECTED_COLOR, tags=CURRENT)
+ # and make it selected
+ self.draw.addtag("selected", "withtag", CURRENT)
+
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
-
- ################
- # make the canvas and bind some behavior to it
- ################
- self.draw = Canvas(self, width="5i", height="5i")
- Widget.bind(self.draw, "<1>", self.mouseDown)
- Widget.bind(self.draw, "<B1-Motion>", self.mouseMove)
-
- # and other things.....
- self.button = Button(self, text="make a new dot", foreground="blue",
- command=self.makeNewDot)
-
- message = ("%s dots are selected and can be dragged.\n"
- "%s are not selected.\n"
- "Click in a dot to select it.\n"
- "Click on empty space to deselect all dots."
- ) % (SELECTED_COLOR, UNSELECTED_COLOR)
- self.label = Message(self, width="5i", text=message)
-
- self.QUIT.pack(side=BOTTOM, fill=BOTH)
- self.label.pack(side=BOTTOM, fill=X, expand=1)
- self.button.pack(side=BOTTOM, fill=X)
- self.draw.pack(side=LEFT)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
- def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ ################
+ # make the canvas and bind some behavior to it
+ ################
+ self.draw = Canvas(self, width="5i", height="5i")
+ Widget.bind(self.draw, "<1>", self.mouseDown)
+ Widget.bind(self.draw, "<B1-Motion>", self.mouseMove)
-test = Test()
-test.mainloop()
+ # and other things.....
+ self.button = Button(self, text="make a new dot", foreground="blue",
+ command=self.makeNewDot)
+
+ message = ("%s dots are selected and can be dragged.\n"
+ "%s are not selected.\n"
+ "Click in a dot to select it.\n"
+ "Click on empty space to deselect all dots."
+ ) % (SELECTED_COLOR, UNSELECTED_COLOR)
+ self.label = Message(self, width="5i", text=message)
+ self.QUIT.pack(side=BOTTOM, fill=BOTH)
+ self.label.pack(side=BOTTOM, fill=X, expand=1)
+ self.button.pack(side=BOTTOM, fill=X)
+ self.draw.pack(side=LEFT)
+ def __init__(self, master=None):
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
+test = Test()
+test.mainloop()
diff --git a/Demo/tkinter/matt/canvas-reading-tag-info.py b/Demo/tkinter/matt/canvas-reading-tag-info.py
index 7044691..f57ea18 100644
--- a/Demo/tkinter/matt/canvas-reading-tag-info.py
+++ b/Demo/tkinter/matt/canvas-reading-tag-info.py
@@ -3,46 +3,46 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=BOTTOM, fill=BOTH)
-
- self.drawing = Canvas(self, width="5i", height="5i")
-
- # make a shape
- pgon = self.drawing.create_polygon(
- 10, 10, 110, 10, 110, 110, 10 , 110,
- fill="red", tags=("weee", "foo", "groo"))
-
- # this is how you query an object for its attributes
- # config options FOR CANVAS ITEMS always come back in tuples of length 5.
- # 0 attribute name
- # 1 BLANK
- # 2 BLANK
- # 3 default value
- # 4 current value
- # the blank spots are for consistency with the config command that
- # is used for widgets. (remember, this is for ITEMS drawn
- # on a canvas widget, not widgets)
- option_value = self.drawing.itemconfig(pgon, "stipple")
- print "pgon's current stipple value is -->", option_value[4], "<--"
- option_value = self.drawing.itemconfig(pgon, "fill")
- print "pgon's current fill value is -->", option_value[4], "<--"
- print " when he is usually colored -->", option_value[3], "<--"
-
- ## here we print out all the tags associated with this object
- option_value = self.drawing.itemconfig(pgon, "tags")
- print "pgon's tags are", option_value[4]
-
- self.drawing.pack(side=LEFT)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=BOTTOM, fill=BOTH)
+
+ self.drawing = Canvas(self, width="5i", height="5i")
+
+ # make a shape
+ pgon = self.drawing.create_polygon(
+ 10, 10, 110, 10, 110, 110, 10 , 110,
+ fill="red", tags=("weee", "foo", "groo"))
+
+ # this is how you query an object for its attributes
+ # config options FOR CANVAS ITEMS always come back in tuples of length 5.
+ # 0 attribute name
+ # 1 BLANK
+ # 2 BLANK
+ # 3 default value
+ # 4 current value
+ # the blank spots are for consistency with the config command that
+ # is used for widgets. (remember, this is for ITEMS drawn
+ # on a canvas widget, not widgets)
+ option_value = self.drawing.itemconfig(pgon, "stipple")
+ print "pgon's current stipple value is -->", option_value[4], "<--"
+ option_value = self.drawing.itemconfig(pgon, "fill")
+ print "pgon's current fill value is -->", option_value[4], "<--"
+ print " when he is usually colored -->", option_value[3], "<--"
+
+ ## here we print out all the tags associated with this object
+ option_value = self.drawing.itemconfig(pgon, "tags")
+ print "pgon's tags are", option_value[4]
+
+ self.drawing.pack(side=LEFT)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
diff --git a/Demo/tkinter/matt/canvas-w-widget-draw-el.py b/Demo/tkinter/matt/canvas-w-widget-draw-el.py
index a1bb3b5..5b26210 100644
--- a/Demo/tkinter/matt/canvas-w-widget-draw-el.py
+++ b/Demo/tkinter/matt/canvas-w-widget-draw-el.py
@@ -4,32 +4,32 @@ from Tkinter import *
class Test(Frame):
def printhi(self):
- print "hi"
+ print "hi"
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=BOTTOM, fill=BOTH)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=BOTTOM, fill=BOTH)
- self.draw = Canvas(self, width="5i", height="5i")
+ self.draw = Canvas(self, width="5i", height="5i")
- self.button = Button(self, text="this is a button",
- command=self.printhi)
+ self.button = Button(self, text="this is a button",
+ command=self.printhi)
- # note here the coords are given in pixels (form the
- # upper right and corner of the window, as usual for X)
- # but might just have well been given in inches or points or
- # whatever...use the "anchor" option to control what point of the
- # widget (in this case the button) gets mapped to the given x, y.
- # you can specify corners, edges, center, etc...
- self.draw.create_window(300, 300, window=self.button)
+ # note here the coords are given in pixels (form the
+ # upper right and corner of the window, as usual for X)
+ # but might just have well been given in inches or points or
+ # whatever...use the "anchor" option to control what point of the
+ # widget (in this case the button) gets mapped to the given x, y.
+ # you can specify corners, edges, center, etc...
+ self.draw.create_window(300, 300, window=self.button)
- self.draw.pack(side=LEFT)
+ self.draw.pack(side=LEFT)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
diff --git a/Demo/tkinter/matt/canvas-with-scrollbars.py b/Demo/tkinter/matt/canvas-with-scrollbars.py
index 60c7b13..81ef25a 100644
--- a/Demo/tkinter/matt/canvas-with-scrollbars.py
+++ b/Demo/tkinter/matt/canvas-with-scrollbars.py
@@ -1,59 +1,59 @@
from Tkinter import *
-# This example program creates a scroling canvas, and demonstrates
+# This example program creates a scroling canvas, and demonstrates
# how to tie scrollbars and canvses together. The mechanism
# is analogus for listboxes and other widgets with
# "xscroll" and "yscroll" configuration options.
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def createWidgets(self):
- self.question = Label(self, text="Can Find The BLUE Square??????")
- self.question.pack()
+ self.question = Label(self, text="Can Find The BLUE Square??????")
+ self.question.pack()
- self.QUIT = Button(self, text='QUIT', background='red',
- height=3, command=self.quit)
- self.QUIT.pack(side=BOTTOM, fill=BOTH)
- spacer = Frame(self, height="0.25i")
- spacer.pack(side=BOTTOM)
+ self.QUIT = Button(self, text='QUIT', background='red',
+ height=3, command=self.quit)
+ self.QUIT.pack(side=BOTTOM, fill=BOTH)
+ spacer = Frame(self, height="0.25i")
+ spacer.pack(side=BOTTOM)
- # notice that the scroll region (20" x 20") is larger than
- # displayed size of the widget (5" x 5")
- self.draw = Canvas(self, width="5i", height="5i",
- background="white",
- scrollregion=(0, 0, "20i", "20i"))
+ # notice that the scroll region (20" x 20") is larger than
+ # displayed size of the widget (5" x 5")
+ self.draw = Canvas(self, width="5i", height="5i",
+ background="white",
+ scrollregion=(0, 0, "20i", "20i"))
- self.draw.scrollX = Scrollbar(self, orient=HORIZONTAL)
- self.draw.scrollY = Scrollbar(self, orient=VERTICAL)
+ self.draw.scrollX = Scrollbar(self, orient=HORIZONTAL)
+ self.draw.scrollY = Scrollbar(self, orient=VERTICAL)
- # now tie the three together. This is standard boilerplate text
- self.draw['xscrollcommand'] = self.draw.scrollX.set
- self.draw['yscrollcommand'] = self.draw.scrollY.set
- self.draw.scrollX['command'] = self.draw.xview
- self.draw.scrollY['command'] = self.draw.yview
+ # now tie the three together. This is standard boilerplate text
+ self.draw['xscrollcommand'] = self.draw.scrollX.set
+ self.draw['yscrollcommand'] = self.draw.scrollY.set
+ self.draw.scrollX['command'] = self.draw.xview
+ self.draw.scrollY['command'] = self.draw.yview
- # draw something. Note that the first square
- # is visible, but you need to scroll to see the second one.
- self.draw.create_rectangle(0, 0, "3.5i", "3.5i", fill="black")
- self.draw.create_rectangle("10i", "10i", "13.5i", "13.5i", fill="blue")
+ # draw something. Note that the first square
+ # is visible, but you need to scroll to see the second one.
+ self.draw.create_rectangle(0, 0, "3.5i", "3.5i", fill="black")
+ self.draw.create_rectangle("10i", "10i", "13.5i", "13.5i", fill="blue")
- # pack 'em up
- self.draw.scrollX.pack(side=BOTTOM, fill=X)
- self.draw.scrollY.pack(side=RIGHT, fill=Y)
- self.draw.pack(side=LEFT)
+ # pack 'em up
+ self.draw.scrollX.pack(side=BOTTOM, fill=X)
+ self.draw.scrollY.pack(side=RIGHT, fill=Y)
+ self.draw.pack(side=LEFT)
- def scrollCanvasX(self, *args):
- print "scrolling", args
- print self.draw.scrollX.get()
+ def scrollCanvasX(self, *args):
+ print "scrolling", args
+ print self.draw.scrollX.get()
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
diff --git a/Demo/tkinter/matt/dialog-box.py b/Demo/tkinter/matt/dialog-box.py
index cbfe29f..dea8f39 100644
--- a/Demo/tkinter/matt/dialog-box.py
+++ b/Demo/tkinter/matt/dialog-box.py
@@ -6,59 +6,59 @@ from Dialog import Dialog
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def makeWindow(self):
- """Create a top-level dialog with some buttons.
+ """Create a top-level dialog with some buttons.
- This uses the Dialog class, which is a wrapper around the Tcl/Tk
- tk_dialog script. The function returns 0 if the user clicks 'yes'
- or 1 if the user clicks 'no'.
- """
- # the parameters to this call are as follows:
- d = Dialog(
- self, ## name of a toplevel window
- title="fred the dialog box",## title on the window
- text="click on a choice", ## message to appear in window
- bitmap="info", ## bitmap (if any) to appear;
- ## if none, use ""
- # legal values here are:
- # string what it looks like
- # ----------------------------------------------
- # error a circle with a slash through it
- # grey25 grey square
- # grey50 darker grey square
- # hourglass use for "wait.."
- # info a large, lower case "i"
- # questhead a human head with a "?" in it
- # question a large "?"
- # warning a large "!"
- # @fname X bitmap where fname is the path to the file
- #
- default=0, # the index of the default button choice.
- # hitting return selects this
- strings=("yes", "no"))
- # values of the 'strings' key are the labels for the
- # buttons that appear left to right in the dialog box
- return d.num
+ This uses the Dialog class, which is a wrapper around the Tcl/Tk
+ tk_dialog script. The function returns 0 if the user clicks 'yes'
+ or 1 if the user clicks 'no'.
+ """
+ # the parameters to this call are as follows:
+ d = Dialog(
+ self, ## name of a toplevel window
+ title="fred the dialog box",## title on the window
+ text="click on a choice", ## message to appear in window
+ bitmap="info", ## bitmap (if any) to appear;
+ ## if none, use ""
+ # legal values here are:
+ # string what it looks like
+ # ----------------------------------------------
+ # error a circle with a slash through it
+ # grey25 grey square
+ # grey50 darker grey square
+ # hourglass use for "wait.."
+ # info a large, lower case "i"
+ # questhead a human head with a "?" in it
+ # question a large "?"
+ # warning a large "!"
+ # @fname X bitmap where fname is the path to the file
+ #
+ default=0, # the index of the default button choice.
+ # hitting return selects this
+ strings=("yes", "no"))
+ # values of the 'strings' key are the labels for the
+ # buttons that appear left to right in the dialog box
+ return d.num
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=LEFT, fill=BOTH)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=LEFT, fill=BOTH)
- # a hello button
- self.hi_there = Button(self, text='Make a New Window',
- command=self.makeWindow)
- self.hi_there.pack(side=LEFT)
+ # a hello button
+ self.hi_there = Button(self, text='Make a New Window',
+ command=self.makeWindow)
+ self.hi_there.pack(side=LEFT)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.windownum = 0
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.windownum = 0
+ self.createWidgets()
test = Test()
test.mainloop()
diff --git a/Demo/tkinter/matt/entry-simple.py b/Demo/tkinter/matt/entry-simple.py
index cf82b89..5146e6f 100644
--- a/Demo/tkinter/matt/entry-simple.py
+++ b/Demo/tkinter/matt/entry-simple.py
@@ -1,25 +1,24 @@
from Tkinter import *
-import string
+import string
# This program shows how to use a simple type-in box
class App(Frame):
def __init__(self, master=None):
- Frame.__init__(self, master)
- self.pack()
+ Frame.__init__(self, master)
+ self.pack()
- self.entrythingy = Entry()
- self.entrythingy.pack()
+ self.entrythingy = Entry()
+ self.entrythingy.pack()
- # and here we get a callback when the user hits return. we could
- # make the key that triggers the callback anything we wanted to.
- # other typical options might be <Key-Tab> or <Key> (for anything)
- self.entrythingy.bind('<Key-Return>', self.print_contents)
+ # and here we get a callback when the user hits return. we could
+ # make the key that triggers the callback anything we wanted to.
+ # other typical options might be <Key-Tab> or <Key> (for anything)
+ self.entrythingy.bind('<Key-Return>', self.print_contents)
def print_contents(self, event):
- print "hi. contents of entry is now ---->", self.entrythingy.get()
+ print "hi. contents of entry is now ---->", self.entrythingy.get()
root = App()
root.master.title("Foo")
root.mainloop()
-
diff --git a/Demo/tkinter/matt/entry-with-shared-variable.py b/Demo/tkinter/matt/entry-with-shared-variable.py
index 360f973..2b76162 100644
--- a/Demo/tkinter/matt/entry-with-shared-variable.py
+++ b/Demo/tkinter/matt/entry-with-shared-variable.py
@@ -1,47 +1,46 @@
from Tkinter import *
-import string
+import string
# This program shows how to make a typein box shadow a program variable.
class App(Frame):
def __init__(self, master=None):
- Frame.__init__(self, master)
- self.pack()
-
- self.entrythingy = Entry(self)
- self.entrythingy.pack()
-
- self.button = Button(self, text="Uppercase The Entry",
- command=self.upper)
- self.button.pack()
-
- # here we have the text in the entry widget tied to a variable.
- # changes in the variable are echoed in the widget and vice versa.
- # Very handy.
- # there are other Variable types. See Tkinter.py for all
- # the other variable types that can be shadowed
- self.contents = StringVar()
- self.contents.set("this is a variable")
- self.entrythingy.config(textvariable=self.contents)
-
- # and here we get a callback when the user hits return. we could
- # make the key that triggers the callback anything we wanted to.
- # other typical options might be <Key-Tab> or <Key> (for anything)
- self.entrythingy.bind('<Key-Return>', self.print_contents)
+ Frame.__init__(self, master)
+ self.pack()
+
+ self.entrythingy = Entry(self)
+ self.entrythingy.pack()
+
+ self.button = Button(self, text="Uppercase The Entry",
+ command=self.upper)
+ self.button.pack()
+
+ # here we have the text in the entry widget tied to a variable.
+ # changes in the variable are echoed in the widget and vice versa.
+ # Very handy.
+ # there are other Variable types. See Tkinter.py for all
+ # the other variable types that can be shadowed
+ self.contents = StringVar()
+ self.contents.set("this is a variable")
+ self.entrythingy.config(textvariable=self.contents)
+
+ # and here we get a callback when the user hits return. we could
+ # make the key that triggers the callback anything we wanted to.
+ # other typical options might be <Key-Tab> or <Key> (for anything)
+ self.entrythingy.bind('<Key-Return>', self.print_contents)
def upper(self):
- # notice here, we don't actually refer to the entry box.
- # we just operate on the string variable and we
+ # notice here, we don't actually refer to the entry box.
+ # we just operate on the string variable and we
# because it's being looked at by the entry widget, changing
- # the variable changes the entry widget display automatically.
- # the strange get/set operators are clunky, true...
- str = string.upper(self.contents.get())
- self.contents.set(str)
+ # the variable changes the entry widget display automatically.
+ # the strange get/set operators are clunky, true...
+ str = string.upper(self.contents.get())
+ self.contents.set(str)
def print_contents(self, event):
- print "hi. contents of entry is now ---->", self.contents.get()
+ print "hi. contents of entry is now ---->", self.contents.get()
root = App()
root.master.title("Foo")
root.mainloop()
-
diff --git a/Demo/tkinter/matt/killing-window-w-wm.py b/Demo/tkinter/matt/killing-window-w-wm.py
index 805a6bc..6a0e2fe 100644
--- a/Demo/tkinter/matt/killing-window-w-wm.py
+++ b/Demo/tkinter/matt/killing-window-w-wm.py
@@ -1,8 +1,8 @@
from Tkinter import *
-# This file shows how to trap the killing of a window
+# This file shows how to trap the killing of a window
# when the user uses window manager menus (typ. upper left hand corner
-# menu in the decoration border).
+# menu in the decoration border).
### ******* this isn't really called -- read the comments
@@ -11,31 +11,31 @@ def my_delete_callback():
class Test(Frame):
def deathHandler(self, event):
- print self, "is now getting nuked. performing some save here...."
+ print self, "is now getting nuked. performing some save here...."
def createWidgets(self):
- # a hello button
- self.hi_there = Button(self, text='Hello')
- self.hi_there.pack(side=LEFT)
+ # a hello button
+ self.hi_there = Button(self, text='Hello')
+ self.hi_there.pack(side=LEFT)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
- ###
- ### PREVENT WM kills from happening
- ###
+ ###
+ ### PREVENT WM kills from happening
+ ###
- # the docs would have you do this:
+ # the docs would have you do this:
-# self.master.protocol("WM_DELETE_WINDOW", my_delete_callback)
+# self.master.protocol("WM_DELETE_WINDOW", my_delete_callback)
- # unfortunately, some window managers will not send this request to a window.
- # the "protocol" function seems incapable of trapping these "aggressive" window kills.
- # this line of code catches everything, tho. The window is deleted, but you have a chance
- # of cleaning up first.
- self.bind_all("<Destroy>", self.deathHandler)
+ # unfortunately, some window managers will not send this request to a window.
+ # the "protocol" function seems incapable of trapping these "aggressive" window kills.
+ # this line of code catches everything, tho. The window is deleted, but you have a chance
+ # of cleaning up first.
+ self.bind_all("<Destroy>", self.deathHandler)
test = Test()
diff --git a/Demo/tkinter/matt/menu-all-types-of-entries.py b/Demo/tkinter/matt/menu-all-types-of-entries.py
index 1ac51c8..f4afe4a 100644
--- a/Demo/tkinter/matt/menu-all-types-of-entries.py
+++ b/Demo/tkinter/matt/menu-all-types-of-entries.py
@@ -1,16 +1,16 @@
from Tkinter import *
-# some vocabulary to keep from getting confused. This terminology
-# is something I cooked up for this file, but follows the man pages
+# some vocabulary to keep from getting confused. This terminology
+# is something I cooked up for this file, but follows the man pages
# pretty closely
-#
-#
-#
+#
+#
+#
# This is a MENUBUTTON
# V
# +-------------+
# | |
-#
+#
# +------------++------------++------------+
# | || || |
# | File || Edit || Options | <-------- the MENUBAR
@@ -22,7 +22,7 @@ from Tkinter import *
# | | <-------- This is a MENU. The lines of text in the menu are
# | | MENU ENTRIES
# | +---------------+
-# | Open Files > | file1 |
+# | Open Files > | file1 |
# | | file2 |
# | | another file | <------ this cascading part is also a MENU
# +----------------| |
@@ -53,11 +53,11 @@ def print_anchovies():
print "anchovies?", anchovies
def makeCommandMenu():
- # make menu button
- Command_button = Menubutton(mBar, text='Simple Button Commands',
- underline=0)
+ # make menu button
+ Command_button = Menubutton(mBar, text='Simple Button Commands',
+ underline=0)
Command_button.pack(side=LEFT, padx="2m")
-
+
# make the pulldown part of the File menu. The parameter passed is the master.
# we attach it to the button as a python attribute called "menu" by convention.
# hopefully this isn't too confusing...
@@ -68,28 +68,28 @@ def makeCommandMenu():
# undo is the 0th entry...
Command_button.menu.entryconfig(0, state=DISABLED)
- Command_button.menu.add_command(label='New...', underline=0,
- command=new_file)
- Command_button.menu.add_command(label='Open...', underline=0,
- command=open_file)
+ Command_button.menu.add_command(label='New...', underline=0,
+ command=new_file)
+ Command_button.menu.add_command(label='Open...', underline=0,
+ command=open_file)
Command_button.menu.add_command(label='Different Font', underline=0,
- font='-*-helvetica-*-r-*-*-*-180-*-*-*-*-*-*',
- command=print_something)
-
+ font='-*-helvetica-*-r-*-*-*-180-*-*-*-*-*-*',
+ command=print_something)
+
# we can make bitmaps be menu entries too. File format is X11 bitmap.
# if you use XV, save it under X11 bitmap format. duh-uh.,..
Command_button.menu.add_command(
- bitmap="info")
- #bitmap='@/home/mjc4y/dilbert/project.status.is.doomed.last.panel.bm')
-
+ bitmap="info")
+ #bitmap='@/home/mjc4y/dilbert/project.status.is.doomed.last.panel.bm')
+
# this is just a line
Command_button.menu.add('separator')
# change the color
- Command_button.menu.add_command(label='Quit', underline=0,
- background='red',
- activebackground='green',
- command=Command_button.quit)
+ Command_button.menu.add_command(label='Quit', underline=0,
+ background='red',
+ activebackground='green',
+ command=Command_button.quit)
# set up a pointer from the file menubutton back to the file menu
Command_button['menu'] = Command_button.menu
@@ -99,10 +99,10 @@ def makeCommandMenu():
def makeCascadeMenu():
- # make menu button
+ # make menu button
Cascade_button = Menubutton(mBar, text='Cascading Menus', underline=0)
Cascade_button.pack(side=LEFT, padx="2m")
-
+
# the primary pulldown
Cascade_button.menu = Menu(Cascade_button)
@@ -125,12 +125,12 @@ def makeCascadeMenu():
Cascade_button.menu.choices.add_command(label='Rocky Road')
Cascade_button.menu.choices.add_command(label='BubbleGum')
Cascade_button.menu.choices.add_cascade(
- label='Wierd Flavors',
- menu=Cascade_button.menu.choices.wierdones)
+ label='Wierd Flavors',
+ menu=Cascade_button.menu.choices.wierdones)
# and finally, the definition for the top level
- Cascade_button.menu.add_cascade(label='more choices',
- menu=Cascade_button.menu.choices)
+ Cascade_button.menu.add_cascade(label='more choices',
+ menu=Cascade_button.menu.choices)
Cascade_button['menu'] = Cascade_button.menu
@@ -138,39 +138,39 @@ def makeCascadeMenu():
def makeCheckbuttonMenu():
global fred
- # make menu button
- Checkbutton_button = Menubutton(mBar, text='Checkbutton Menus',
- underline=0)
+ # make menu button
+ Checkbutton_button = Menubutton(mBar, text='Checkbutton Menus',
+ underline=0)
Checkbutton_button.pack(side=LEFT, padx='2m')
-
+
# the primary pulldown
Checkbutton_button.menu = Menu(Checkbutton_button)
# and all the check buttons. Note that the "variable" "onvalue" and "offvalue" options
- # are not supported correctly at present. You have to do all your application
+ # are not supported correctly at present. You have to do all your application
# work through the calback.
Checkbutton_button.menu.add_checkbutton(label='Pepperoni')
Checkbutton_button.menu.add_checkbutton(label='Sausage')
Checkbutton_button.menu.add_checkbutton(label='Extra Cheese')
# so here's a callback
- Checkbutton_button.menu.add_checkbutton(label='Anchovy',
- command=print_anchovies)
+ Checkbutton_button.menu.add_checkbutton(label='Anchovy',
+ command=print_anchovies)
- # and start with anchovies selected to be on. Do this by
+ # and start with anchovies selected to be on. Do this by
# calling invoke on this menu option. To refer to the "anchovy" menu
# entry we need to know it's index. To do this, we use the index method
- # which takes arguments of several forms:
+ # which takes arguments of several forms:
#
# argument what it does
# -----------------------------------
- # a number -- this is useless.
+ # a number -- this is useless.
# "last" -- last option in the menu
# "none" -- used with the activate command. see the man page on menus
# "active" -- the currently active menu option. A menu option is made active
# with the 'activate' method
# "@number" -- where 'number' is an integer and is treated like a y coordinate in pixels
- # string pattern -- this is the option used below, and attempts to match "labels" using the
+ # string pattern -- this is the option used below, and attempts to match "labels" using the
# rules of Tcl_StringMatch
Checkbutton_button.menu.invoke(Checkbutton_button.menu.index('Anchovy'))
@@ -181,16 +181,16 @@ def makeCheckbuttonMenu():
def makeRadiobuttonMenu():
- # make menu button
- Radiobutton_button = Menubutton(mBar, text='Radiobutton Menus',
- underline=0)
+ # make menu button
+ Radiobutton_button = Menubutton(mBar, text='Radiobutton Menus',
+ underline=0)
Radiobutton_button.pack(side=LEFT, padx='2m')
-
+
# the primary pulldown
Radiobutton_button.menu = Menu(Radiobutton_button)
# and all the Radio buttons. Note that the "variable" "onvalue" and "offvalue" options
- # are not supported correctly at present. You have to do all your application
+ # are not supported correctly at present. You have to do all your application
# work through the calback.
Radiobutton_button.menu.add_radiobutton(label='Republican')
Radiobutton_button.menu.add_radiobutton(label='Democrat')
@@ -209,7 +209,7 @@ def makeRadiobuttonMenu():
return Radiobutton_button
-def makeDisabledMenu():
+def makeDisabledMenu():
Dummy_button = Menubutton(mBar, text='Dead Menu', underline=0)
Dummy_button.pack(side=LEFT, padx='2m')
@@ -233,7 +233,7 @@ Checkbutton_button = makeCheckbuttonMenu()
Radiobutton_button = makeRadiobuttonMenu()
NoMenu = makeDisabledMenu()
-# finally, install the buttons in the menu bar.
+# finally, install the buttons in the menu bar.
# This allows for scanning from one menubutton to the next.
mBar.tk_menuBar(Command_button, Cascade_button, Checkbutton_button, Radiobutton_button, NoMenu)
@@ -242,9 +242,3 @@ root.title('menu demo')
root.iconname('menu demo')
root.mainloop()
-
-
-
-
-
-
diff --git a/Demo/tkinter/matt/menu-simple.py b/Demo/tkinter/matt/menu-simple.py
index 28f2c9e..46b5364 100644
--- a/Demo/tkinter/matt/menu-simple.py
+++ b/Demo/tkinter/matt/menu-simple.py
@@ -1,16 +1,16 @@
from Tkinter import *
-# some vocabulary to keep from getting confused. This terminology
-# is something I cooked up for this file, but follows the man pages
+# some vocabulary to keep from getting confused. This terminology
+# is something I cooked up for this file, but follows the man pages
# pretty closely
-#
-#
-#
+#
+#
+#
# This is a MENUBUTTON
# V
# +-------------+
# | |
-#
+#
# +------------++------------++------------+
# | || || |
# | File || Edit || Options | <-------- the MENUBAR
@@ -22,7 +22,7 @@ from Tkinter import *
# | | <------ This is a MENU. The lines of text in the menu are
# | | MENU ENTRIES
# | +---------------+
-# | Open Files > | file1 |
+# | Open Files > | file1 |
# | | file2 |
# | | another file | <------ this cascading part is also a MENU
# +----------------| |
@@ -46,19 +46,19 @@ def makeFileMenu():
File_button = Menubutton(mBar, text='File', underline=0)
File_button.pack(side=LEFT, padx="1m")
File_button.menu = Menu(File_button)
-
- # add an item. The first param is a menu entry type,
+
+ # add an item. The first param is a menu entry type,
# must be one of: "cascade", "checkbutton", "command", "radiobutton", "seperator"
# see menu-demo-2.py for examples of use
- File_button.menu.add_command(label='New...', underline=0,
- command=new_file)
-
-
- File_button.menu.add_command(label='Open...', underline=0,
- command=open_file)
-
- File_button.menu.add_command(label='Quit', underline=0,
- command='exit')
+ File_button.menu.add_command(label='New...', underline=0,
+ command=new_file)
+
+
+ File_button.menu.add_command(label='Open...', underline=0,
+ command=open_file)
+
+ File_button.menu.add_command(label='Quit', underline=0,
+ command='exit')
# set up a pointer from the file menubutton back to the file menu
File_button['menu'] = File_button.menu
@@ -102,7 +102,7 @@ mBar.pack(fill=X)
File_button = makeFileMenu()
Edit_button = makeEditMenu()
-# finally, install the buttons in the menu bar.
+# finally, install the buttons in the menu bar.
# This allows for scanning from one menubutton to the next.
mBar.tk_menuBar(File_button, Edit_button)
@@ -110,9 +110,3 @@ root.title('menu demo')
root.iconname('packer')
root.mainloop()
-
-
-
-
-
-
diff --git a/Demo/tkinter/matt/not-what-you-might-think-1.py b/Demo/tkinter/matt/not-what-you-might-think-1.py
index 24de2ef..7b20f02 100644
--- a/Demo/tkinter/matt/not-what-you-might-think-1.py
+++ b/Demo/tkinter/matt/not-what-you-might-think-1.py
@@ -4,21 +4,21 @@ from Tkinter import *
class Test(Frame):
def createWidgets(self):
- self.Gpanel = Frame(self, width='1i', height='1i',
- background='green')
- self.Gpanel.pack(side=LEFT)
+ self.Gpanel = Frame(self, width='1i', height='1i',
+ background='green')
+ self.Gpanel.pack(side=LEFT)
- # a QUIT button
- self.Gpanel.QUIT = Button(self.Gpanel, text='QUIT',
- foreground='red',
- command=self.quit)
- self.Gpanel.QUIT.pack(side=LEFT)
+ # a QUIT button
+ self.Gpanel.QUIT = Button(self.Gpanel, text='QUIT',
+ foreground='red',
+ command=self.quit)
+ self.Gpanel.QUIT.pack(side=LEFT)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
diff --git a/Demo/tkinter/matt/not-what-you-might-think-2.py b/Demo/tkinter/matt/not-what-you-might-think-2.py
index c01854e..9ee197c 100644
--- a/Demo/tkinter/matt/not-what-you-might-think-2.py
+++ b/Demo/tkinter/matt/not-what-you-might-think-2.py
@@ -4,23 +4,23 @@ from Tkinter import *
class Test(Frame):
def createWidgets(self):
- self.Gpanel = Frame(self, width='1i', height='1i',
- background='green')
+ self.Gpanel = Frame(self, width='1i', height='1i',
+ background='green')
- # this line turns off the recalculation of geometry by masters.
- self.Gpanel.propagate(0)
+ # this line turns off the recalculation of geometry by masters.
+ self.Gpanel.propagate(0)
- self.Gpanel.pack(side=LEFT)
+ self.Gpanel.pack(side=LEFT)
- # a QUIT button
- self.Gpanel.QUIT = Button(self.Gpanel, text='QUIT', foreground='red',
- command=self.quit)
- self.Gpanel.QUIT.pack(side=LEFT)
+ # a QUIT button
+ self.Gpanel.QUIT = Button(self.Gpanel, text='QUIT', foreground='red',
+ command=self.quit)
+ self.Gpanel.QUIT.pack(side=LEFT)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
diff --git a/Demo/tkinter/matt/packer-and-placer-together.py b/Demo/tkinter/matt/packer-and-placer-together.py
index 4ceec54..184d56b 100644
--- a/Demo/tkinter/matt/packer-and-placer-together.py
+++ b/Demo/tkinter/matt/packer-and-placer-together.py
@@ -1,6 +1,6 @@
from Tkinter import *
-# This is a program that tests the placer geom manager in conjunction with
+# This is a program that tests the placer geom manager in conjunction with
# the packer. The background (green) is packed, while the widget inside is placed
@@ -17,15 +17,15 @@ def createWidgets(top):
# area is inaccesssible.
f = Frame(top, width=200, height=200, background='green')
- # note that we use a different manager here.
- # This way, the top level frame widget resizes when the
- # application window does.
+ # note that we use a different manager here.
+ # This way, the top level frame widget resizes when the
+ # application window does.
f.pack(fill=BOTH, expand=1)
# now make a button
f.button = Button(f, foreground='red', text='amazing', command=dothis)
- # and place it so that the nw corner is
+ # and place it so that the nw corner is
# 1/2 way along the top X edge of its' parent
f.button.place(relx=0.5, rely=0.0, anchor=NW)
@@ -39,4 +39,3 @@ app = createWidgets(root)
root.geometry("400x400")
root.maxsize(1000, 1000)
root.mainloop()
-
diff --git a/Demo/tkinter/matt/packer-simple.py b/Demo/tkinter/matt/packer-simple.py
index 7773cae..f55f1be 100644
--- a/Demo/tkinter/matt/packer-simple.py
+++ b/Demo/tkinter/matt/packer-simple.py
@@ -3,30 +3,30 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print self.hi_there["command"]
+ print self.hi_there["command"]
def createWidgets(self):
- # a hello button
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=LEFT, fill=BOTH)
+ # a hello button
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=LEFT, fill=BOTH)
- self.hi_there = Button(self, text='Hello',
- command=self.printit)
- self.hi_there.pack(side=LEFT)
+ self.hi_there = Button(self, text='Hello',
+ command=self.printit)
+ self.hi_there.pack(side=LEFT)
- # note how Packer defaults to side=TOP
+ # note how Packer defaults to side=TOP
- self.guy2 = Button(self, text='button 2')
- self.guy2.pack()
+ self.guy2 = Button(self, text='button 2')
+ self.guy2.pack()
- self.guy3 = Button(self, text='button 3')
- self.guy3.pack()
+ self.guy3 = Button(self, text='button 3')
+ self.guy3.pack()
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
test.mainloop()
diff --git a/Demo/tkinter/matt/placer-simple.py b/Demo/tkinter/matt/placer-simple.py
index b7cae7e..30d9e9e 100644
--- a/Demo/tkinter/matt/placer-simple.py
+++ b/Demo/tkinter/matt/placer-simple.py
@@ -15,7 +15,7 @@ def createWidgets(top):
# area is inaccesssible.
f = Frame(top, width=200, height=200, background='green')
- # place it so the upper left hand corner of
+ # place it so the upper left hand corner of
# the frame is in the upper left corner of
# the parent
f.place(relx=0.0, rely=0.0)
@@ -23,7 +23,7 @@ def createWidgets(top):
# now make a button
f.button = Button(f, foreground='red', text='amazing', command=dothis)
- # and place it so that the nw corner is
+ # and place it so that the nw corner is
# 1/2 way along the top X edge of its' parent
f.button.place(relx=0.5, rely=0.0, anchor=NW)
@@ -37,4 +37,3 @@ app = createWidgets(root)
root.geometry("400x400")
root.maxsize(1000, 1000)
root.mainloop()
-
diff --git a/Demo/tkinter/matt/pong-demo-1.py b/Demo/tkinter/matt/pong-demo-1.py
index a27f334..7fcf800 100644
--- a/Demo/tkinter/matt/pong-demo-1.py
+++ b/Demo/tkinter/matt/pong-demo-1.py
@@ -5,48 +5,48 @@ import string
class Pong(Frame):
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=LEFT, fill=BOTH)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=LEFT, fill=BOTH)
- ## The playing field
- self.draw = Canvas(self, width="5i", height="5i")
+ ## The playing field
+ self.draw = Canvas(self, width="5i", height="5i")
- ## The speed control for the ball
- self.speed = Scale(self, orient=HORIZONTAL, label="ball speed",
- from_=-100, to=100)
+ ## The speed control for the ball
+ self.speed = Scale(self, orient=HORIZONTAL, label="ball speed",
+ from_=-100, to=100)
- self.speed.pack(side=BOTTOM, fill=X)
+ self.speed.pack(side=BOTTOM, fill=X)
- # The ball
- self.ball = self.draw.create_oval("0i", "0i", "0.10i", "0.10i",
- fill="red")
- self.x = 0.05
- self.y = 0.05
- self.velocity_x = 0.3
- self.velocity_y = 0.5
+ # The ball
+ self.ball = self.draw.create_oval("0i", "0i", "0.10i", "0.10i",
+ fill="red")
+ self.x = 0.05
+ self.y = 0.05
+ self.velocity_x = 0.3
+ self.velocity_y = 0.5
- self.draw.pack(side=LEFT)
+ self.draw.pack(side=LEFT)
def moveBall(self, *args):
- if (self.x > 5.0) or (self.x < 0.0):
- self.velocity_x = -1.0 * self.velocity_x
- if (self.y > 5.0) or (self.y < 0.0):
- self.velocity_y = -1.0 * self.velocity_y
+ if (self.x > 5.0) or (self.x < 0.0):
+ self.velocity_x = -1.0 * self.velocity_x
+ if (self.y > 5.0) or (self.y < 0.0):
+ self.velocity_y = -1.0 * self.velocity_y
- deltax = (self.velocity_x * self.speed.get() / 100.0)
- deltay = (self.velocity_y * self.speed.get() / 100.0)
- self.x = self.x + deltax
- self.y = self.y + deltay
+ deltax = (self.velocity_x * self.speed.get() / 100.0)
+ deltay = (self.velocity_y * self.speed.get() / 100.0)
+ self.x = self.x + deltax
+ self.y = self.y + deltay
- self.draw.move(self.ball, "%ri" % deltax, "%ri" % deltay)
- self.after(10, self.moveBall)
+ self.draw.move(self.ball, "%ri" % deltax, "%ri" % deltay)
+ self.after(10, self.moveBall)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
- self.after(10, self.moveBall)
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
+ self.after(10, self.moveBall)
game = Pong()
diff --git a/Demo/tkinter/matt/printing-coords-of-items.py b/Demo/tkinter/matt/printing-coords-of-items.py
index 6400fd8..a37733d 100644
--- a/Demo/tkinter/matt/printing-coords-of-items.py
+++ b/Demo/tkinter/matt/printing-coords-of-items.py
@@ -7,58 +7,55 @@ class Test(Frame):
###### Event callbacks for THE CANVAS (not the stuff drawn on it)
###################################################################
def mouseDown(self, event):
- # see if we're inside a dot. If we are, it
- # gets tagged as CURRENT for free by tk.
-
- if not event.widget.find_withtag(CURRENT):
- # there is no dot here, so we can make one,
- # and bind some interesting behavior to it.
- # ------
- # create a dot, and mark it as current
- fred = self.draw.create_oval(
- event.x - 10, event.y -10, event.x +10, event.y + 10,
- fill="green")
- self.draw.tag_bind(fred, "<Enter>", self.mouseEnter)
- self.draw.tag_bind(fred, "<Leave>", self.mouseLeave)
- self.lastx = event.x
- self.lasty = event.y
+ # see if we're inside a dot. If we are, it
+ # gets tagged as CURRENT for free by tk.
+
+ if not event.widget.find_withtag(CURRENT):
+ # there is no dot here, so we can make one,
+ # and bind some interesting behavior to it.
+ # ------
+ # create a dot, and mark it as current
+ fred = self.draw.create_oval(
+ event.x - 10, event.y -10, event.x +10, event.y + 10,
+ fill="green")
+ self.draw.tag_bind(fred, "<Enter>", self.mouseEnter)
+ self.draw.tag_bind(fred, "<Leave>", self.mouseLeave)
+ self.lastx = event.x
+ self.lasty = event.y
def mouseMove(self, event):
- self.draw.move(CURRENT, event.x - self.lastx, event.y - self.lasty)
- self.lastx = event.x
- self.lasty = event.y
+ self.draw.move(CURRENT, event.x - self.lastx, event.y - self.lasty)
+ self.lastx = event.x
+ self.lasty = event.y
###################################################################
###### Event callbacks for canvas ITEMS (stuff drawn on the canvas)
###################################################################
def mouseEnter(self, event):
# the "current" tag is applied to the object the cursor is over.
- # this happens automatically.
- self.draw.itemconfig(CURRENT, fill="red")
- print self.draw.coords(CURRENT)
-
+ # this happens automatically.
+ self.draw.itemconfig(CURRENT, fill="red")
+ print self.draw.coords(CURRENT)
+
def mouseLeave(self, event):
- # the "current" tag is applied to the object the cursor is over.
- # this happens automatically.
- self.draw.itemconfig(CURRENT, fill="blue")
+ # the "current" tag is applied to the object the cursor is over.
+ # this happens automatically.
+ self.draw.itemconfig(CURRENT, fill="blue")
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=LEFT, fill=BOTH)
- self.draw = Canvas(self, width="5i", height="5i")
- self.draw.pack(side=LEFT)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=LEFT, fill=BOTH)
+ self.draw = Canvas(self, width="5i", height="5i")
+ self.draw.pack(side=LEFT)
- Widget.bind(self.draw, "<1>", self.mouseDown)
- Widget.bind(self.draw, "<B1-Motion>", self.mouseMove)
+ Widget.bind(self.draw, "<1>", self.mouseDown)
+ Widget.bind(self.draw, "<B1-Motion>", self.mouseMove)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
test.mainloop()
-
-
-
diff --git a/Demo/tkinter/matt/radiobutton-simple.py b/Demo/tkinter/matt/radiobutton-simple.py
index 65dfe52..e9d6afe 100644
--- a/Demo/tkinter/matt/radiobutton-simple.py
+++ b/Demo/tkinter/matt/radiobutton-simple.py
@@ -1,10 +1,10 @@
from Tkinter import *
-# This is a demo program that shows how to
-# create radio buttons and how to get other widgets to
-# share the information in a radio button.
-#
-# There are other ways of doing this too, but
+# This is a demo program that shows how to
+# create radio buttons and how to get other widgets to
+# share the information in a radio button.
+#
+# There are other ways of doing this too, but
# the "variable" option of radiobuttons seems to be the easiest.
#
# note how each button has a value it sets the variable to as it gets hit.
@@ -12,50 +12,50 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def createWidgets(self):
- self.flavor = StringVar()
- self.flavor.set("chocolate")
-
- self.radioframe = Frame(self)
- self.radioframe.pack()
-
- # 'text' is the label
- # 'variable' is the name of the variable that all these radio buttons share
- # 'value' is the value this variable takes on when the radio button is selected
- # 'anchor' makes the text appear left justified (default is centered. ick)
- self.radioframe.choc = Radiobutton(
- self.radioframe, text="Chocolate Flavor",
- variable=self.flavor, value="chocolate",
- anchor=W)
- self.radioframe.choc.pack(fill=X)
-
- self.radioframe.straw = Radiobutton(
- self.radioframe, text="Strawberry Flavor",
- variable=self.flavor, value="strawberry",
- anchor=W)
- self.radioframe.straw.pack(fill=X)
-
- self.radioframe.lemon = Radiobutton(
- self.radioframe, text="Lemon Flavor",
- variable=self.flavor, value="lemon",
- anchor=W)
- self.radioframe.lemon.pack(fill=X)
-
- # this is a text entry that lets you type in the name of a flavor too.
- self.entry = Entry(self, textvariable=self.flavor)
- self.entry.pack(fill=X)
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=BOTTOM, fill=BOTH)
+ self.flavor = StringVar()
+ self.flavor.set("chocolate")
+
+ self.radioframe = Frame(self)
+ self.radioframe.pack()
+
+ # 'text' is the label
+ # 'variable' is the name of the variable that all these radio buttons share
+ # 'value' is the value this variable takes on when the radio button is selected
+ # 'anchor' makes the text appear left justified (default is centered. ick)
+ self.radioframe.choc = Radiobutton(
+ self.radioframe, text="Chocolate Flavor",
+ variable=self.flavor, value="chocolate",
+ anchor=W)
+ self.radioframe.choc.pack(fill=X)
+
+ self.radioframe.straw = Radiobutton(
+ self.radioframe, text="Strawberry Flavor",
+ variable=self.flavor, value="strawberry",
+ anchor=W)
+ self.radioframe.straw.pack(fill=X)
+
+ self.radioframe.lemon = Radiobutton(
+ self.radioframe, text="Lemon Flavor",
+ variable=self.flavor, value="lemon",
+ anchor=W)
+ self.radioframe.lemon.pack(fill=X)
+
+ # this is a text entry that lets you type in the name of a flavor too.
+ self.entry = Entry(self, textvariable=self.flavor)
+ self.entry.pack(fill=X)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=BOTTOM, fill=BOTH)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
diff --git a/Demo/tkinter/matt/rubber-band-box-demo-1.py b/Demo/tkinter/matt/rubber-band-box-demo-1.py
index 5196bf7..b00518e 100644
--- a/Demo/tkinter/matt/rubber-band-box-demo-1.py
+++ b/Demo/tkinter/matt/rubber-band-box-demo-1.py
@@ -2,55 +2,55 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT',
- background='red',
- foreground='white',
- height=3,
- command=self.quit)
- self.QUIT.pack(side=BOTTOM, fill=BOTH)
+ self.QUIT = Button(self, text='QUIT',
+ background='red',
+ foreground='white',
+ height=3,
+ command=self.quit)
+ self.QUIT.pack(side=BOTTOM, fill=BOTH)
- self.canvasObject = Canvas(self, width="5i", height="5i")
- self.canvasObject.pack(side=LEFT)
+ self.canvasObject = Canvas(self, width="5i", height="5i")
+ self.canvasObject.pack(side=LEFT)
def mouseDown(self, event):
- # canvas x and y take the screen coords from the event and translate
- # them into the coordinate system of the canvas object
- self.startx = self.canvasObject.canvasx(event.x)
- self.starty = self.canvasObject.canvasy(event.y)
+ # canvas x and y take the screen coords from the event and translate
+ # them into the coordinate system of the canvas object
+ self.startx = self.canvasObject.canvasx(event.x)
+ self.starty = self.canvasObject.canvasy(event.y)
def mouseMotion(self, event):
- # canvas x and y take the screen coords from the event and translate
- # them into the coordinate system of the canvas object
- x = self.canvasObject.canvasx(event.x)
- y = self.canvasObject.canvasy(event.y)
-
- if (self.startx != event.x) and (self.starty != event.y) :
- self.canvasObject.delete(self.rubberbandBox)
- self.rubberbandBox = self.canvasObject.create_rectangle(
- self.startx, self.starty, x, y)
- # this flushes the output, making sure that
- # the rectangle makes it to the screen
- # before the next event is handled
- self.update_idletasks()
+ # canvas x and y take the screen coords from the event and translate
+ # them into the coordinate system of the canvas object
+ x = self.canvasObject.canvasx(event.x)
+ y = self.canvasObject.canvasy(event.y)
+
+ if (self.startx != event.x) and (self.starty != event.y) :
+ self.canvasObject.delete(self.rubberbandBox)
+ self.rubberbandBox = self.canvasObject.create_rectangle(
+ self.startx, self.starty, x, y)
+ # this flushes the output, making sure that
+ # the rectangle makes it to the screen
+ # before the next event is handled
+ self.update_idletasks()
def mouseUp(self, event):
- self.canvasObject.delete(self.rubberbandBox)
-
+ self.canvasObject.delete(self.rubberbandBox)
+
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
-
- # this is a "tagOrId" for the rectangle we draw on the canvas
- self.rubberbandBox = None
-
- # and the bindings that make it work..
- Widget.bind(self.canvasObject, "<Button-1>", self.mouseDown)
- Widget.bind(self.canvasObject, "<Button1-Motion>", self.mouseMotion)
- Widget.bind(self.canvasObject, "<Button1-ButtonRelease>", self.mouseUp)
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
+
+ # this is a "tagOrId" for the rectangle we draw on the canvas
+ self.rubberbandBox = None
+
+ # and the bindings that make it work..
+ Widget.bind(self.canvasObject, "<Button-1>", self.mouseDown)
+ Widget.bind(self.canvasObject, "<Button1-Motion>", self.mouseMotion)
+ Widget.bind(self.canvasObject, "<Button1-ButtonRelease>", self.mouseUp)
test = Test()
diff --git a/Demo/tkinter/matt/rubber-line-demo-1.py b/Demo/tkinter/matt/rubber-line-demo-1.py
index f6d8535..59b8bd9 100644
--- a/Demo/tkinter/matt/rubber-line-demo-1.py
+++ b/Demo/tkinter/matt/rubber-line-demo-1.py
@@ -2,49 +2,49 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT',
- background='red',
- foreground='white',
- height=3,
- command=self.quit)
- self.QUIT.pack(side=BOTTOM, fill=BOTH)
+ self.QUIT = Button(self, text='QUIT',
+ background='red',
+ foreground='white',
+ height=3,
+ command=self.quit)
+ self.QUIT.pack(side=BOTTOM, fill=BOTH)
- self.canvasObject = Canvas(self, width="5i", height="5i")
- self.canvasObject.pack(side=LEFT)
+ self.canvasObject = Canvas(self, width="5i", height="5i")
+ self.canvasObject.pack(side=LEFT)
def mouseDown(self, event):
- # canvas x and y take the screen coords from the event and translate
- # them into the coordinate system of the canvas object
- self.startx = self.canvasObject.canvasx(event.x)
- self.starty = self.canvasObject.canvasy(event.y)
+ # canvas x and y take the screen coords from the event and translate
+ # them into the coordinate system of the canvas object
+ self.startx = self.canvasObject.canvasx(event.x)
+ self.starty = self.canvasObject.canvasy(event.y)
def mouseMotion(self, event):
- # canvas x and y take the screen coords from the event and translate
- # them into the coordinate system of the canvas object
- x = self.canvasObject.canvasx(event.x)
- y = self.canvasObject.canvasy(event.y)
-
- if (self.startx != event.x) and (self.starty != event.y) :
- self.canvasObject.delete(self.rubberbandLine)
- self.rubberbandLine = self.canvasObject.create_line(
- self.startx, self.starty, x, y)
- # this flushes the output, making sure that
- # the rectangle makes it to the screen
- # before the next event is handled
- self.update_idletasks()
+ # canvas x and y take the screen coords from the event and translate
+ # them into the coordinate system of the canvas object
+ x = self.canvasObject.canvasx(event.x)
+ y = self.canvasObject.canvasy(event.y)
+
+ if (self.startx != event.x) and (self.starty != event.y) :
+ self.canvasObject.delete(self.rubberbandLine)
+ self.rubberbandLine = self.canvasObject.create_line(
+ self.startx, self.starty, x, y)
+ # this flushes the output, making sure that
+ # the rectangle makes it to the screen
+ # before the next event is handled
+ self.update_idletasks()
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
- # this is a "tagOrId" for the rectangle we draw on the canvas
- self.rubberbandLine = None
- Widget.bind(self.canvasObject, "<Button-1>", self.mouseDown)
- Widget.bind(self.canvasObject, "<Button1-Motion>", self.mouseMotion)
-
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
+ # this is a "tagOrId" for the rectangle we draw on the canvas
+ self.rubberbandLine = None
+ Widget.bind(self.canvasObject, "<Button-1>", self.mouseDown)
+ Widget.bind(self.canvasObject, "<Button1-Motion>", self.mouseMotion)
+
test = Test()
diff --git a/Demo/tkinter/matt/slider-demo-1.py b/Demo/tkinter/matt/slider-demo-1.py
index 40395df..db6114b 100644
--- a/Demo/tkinter/matt/slider-demo-1.py
+++ b/Demo/tkinter/matt/slider-demo-1.py
@@ -5,32 +5,32 @@ from Tkinter import *
class Test(Frame):
def print_value(self, val):
- print "slider now at", val
+ print "slider now at", val
- def reset(self):
- self.slider.set(0)
+ def reset(self):
+ self.slider.set(0)
def createWidgets(self):
- self.slider = Scale(self, from_=0, to=100,
- orient=HORIZONTAL,
- length="3i",
- label="happy slider",
- command=self.print_value)
+ self.slider = Scale(self, from_=0, to=100,
+ orient=HORIZONTAL,
+ length="3i",
+ label="happy slider",
+ command=self.print_value)
- self.reset = Button(self, text='reset slider',
- command=self.reset)
+ self.reset = Button(self, text='reset slider',
+ command=self.reset)
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
- self.slider.pack(side=LEFT)
- self.reset.pack(side=LEFT)
- self.QUIT.pack(side=LEFT, fill=BOTH)
+ self.slider.pack(side=LEFT)
+ self.reset.pack(side=LEFT)
+ self.QUIT.pack(side=LEFT, fill=BOTH)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
test.mainloop()
diff --git a/Demo/tkinter/matt/subclass-existing-widgets.py b/Demo/tkinter/matt/subclass-existing-widgets.py
index e79dd5c..0e08f92 100644
--- a/Demo/tkinter/matt/subclass-existing-widgets.py
+++ b/Demo/tkinter/matt/subclass-existing-widgets.py
@@ -5,9 +5,9 @@ from Tkinter import *
class New_Button(Button):
def callback(self):
- print self.counter
- self.counter = self.counter + 1
-
+ print self.counter
+ self.counter = self.counter + 1
+
def createWidgets(top):
f = Frame(top)
f.pack()
@@ -26,4 +26,3 @@ def createWidgets(top):
root = Tk()
createWidgets(root)
root.mainloop()
-
diff --git a/Demo/tkinter/matt/two-radio-groups.py b/Demo/tkinter/matt/two-radio-groups.py
index 5c17333..9fd8f4f 100644
--- a/Demo/tkinter/matt/two-radio-groups.py
+++ b/Demo/tkinter/matt/two-radio-groups.py
@@ -1,44 +1,44 @@
from Tkinter import *
-# The way to think about this is that each radio button menu
-# controls a different variable -- clicking on one of the
-# mutually exclusive choices in a radiobutton assigns some value
-# to an application variable you provide. When you define a
-# radiobutton menu choice, you have the option of specifying the
-# name of a varaible and value to assign to that variable when
-# that choice is selected. This clever mechanism relieves you,
-# the programmer, from having to write a dumb callback that
-# probably wouldn't have done anything more than an assignment
-# anyway. The Tkinter options for this follow their Tk
-# counterparts:
-# {"variable" : my_flavor_variable, "value" : "strawberry"}
+# The way to think about this is that each radio button menu
+# controls a different variable -- clicking on one of the
+# mutually exclusive choices in a radiobutton assigns some value
+# to an application variable you provide. When you define a
+# radiobutton menu choice, you have the option of specifying the
+# name of a varaible and value to assign to that variable when
+# that choice is selected. This clever mechanism relieves you,
+# the programmer, from having to write a dumb callback that
+# probably wouldn't have done anything more than an assignment
+# anyway. The Tkinter options for this follow their Tk
+# counterparts:
+# {"variable" : my_flavor_variable, "value" : "strawberry"}
# where my_flavor_variable is an instance of one of the
# subclasses of Variable, provided in Tkinter.py (there is
-# StringVar(), IntVar(), DoubleVar() and BooleanVar() to choose
-# from)
+# StringVar(), IntVar(), DoubleVar() and BooleanVar() to choose
+# from)
def makePoliticalParties(var):
- # make menu button
- Radiobutton_button = Menubutton(mBar, text='Political Party',
- underline=0)
+ # make menu button
+ Radiobutton_button = Menubutton(mBar, text='Political Party',
+ underline=0)
Radiobutton_button.pack(side=LEFT, padx='2m')
-
+
# the primary pulldown
Radiobutton_button.menu = Menu(Radiobutton_button)
- Radiobutton_button.menu.add_radiobutton(label='Republican',
- variable=var, value=1)
+ Radiobutton_button.menu.add_radiobutton(label='Republican',
+ variable=var, value=1)
+
+ Radiobutton_button.menu.add('radiobutton', {'label': 'Democrat',
+ 'variable' : var,
+ 'value' : 2})
- Radiobutton_button.menu.add('radiobutton', {'label': 'Democrat',
- 'variable' : var,
- 'value' : 2})
+ Radiobutton_button.menu.add('radiobutton', {'label': 'Libertarian',
+ 'variable' : var,
+ 'value' : 3})
- Radiobutton_button.menu.add('radiobutton', {'label': 'Libertarian',
- 'variable' : var,
- 'value' : 3})
-
var.set(2)
# set up a pointer from the file menubutton back to the file menu
@@ -48,22 +48,22 @@ def makePoliticalParties(var):
def makeFlavors(var):
- # make menu button
- Radiobutton_button = Menubutton(mBar, text='Flavors',
- underline=0)
+ # make menu button
+ Radiobutton_button = Menubutton(mBar, text='Flavors',
+ underline=0)
Radiobutton_button.pack(side=LEFT, padx='2m')
# the primary pulldown
Radiobutton_button.menu = Menu(Radiobutton_button)
Radiobutton_button.menu.add_radiobutton(label='Strawberry',
- variable=var, value='Strawberry')
+ variable=var, value='Strawberry')
Radiobutton_button.menu.add_radiobutton(label='Chocolate',
- variable=var, value='Chocolate')
+ variable=var, value='Chocolate')
Radiobutton_button.menu.add_radiobutton(label='Rocky Road',
- variable=var, value='Rocky Road')
+ variable=var, value='Rocky Road')
# choose a default
var.set("Chocolate")
@@ -88,7 +88,7 @@ root = Tk()
mBar = Frame(root, relief=RAISED, borderwidth=2)
mBar.pack(fill=X)
-# make two application variables,
+# make two application variables,
# one to control each radio button set
party = IntVar()
flavor = StringVar()
@@ -96,12 +96,12 @@ flavor = StringVar()
Radiobutton_button = makePoliticalParties(party)
Radiobutton_button2 = makeFlavors(flavor)
-# finally, install the buttons in the menu bar.
+# finally, install the buttons in the menu bar.
# This allows for scanning from one menubutton to the next.
mBar.tk_menuBar(Radiobutton_button, Radiobutton_button2)
b = Button(root, text="print party and flavor", foreground="red",
- command=printStuff)
+ command=printStuff)
b.pack(side=TOP)
root.title('menu demo')
diff --git a/Demo/tkinter/matt/window-creation-more.py b/Demo/tkinter/matt/window-creation-more.py
index 492027a..eb0eb6f 100644
--- a/Demo/tkinter/matt/window-creation-more.py
+++ b/Demo/tkinter/matt/window-creation-more.py
@@ -5,31 +5,31 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def makeWindow(self):
- fred = Toplevel()
- fred.label = Button(fred,
- text="This is window number %d." % self.windownum,
- command=self.makeWindow)
- fred.label.pack()
- self.windownum = self.windownum + 1
+ fred = Toplevel()
+ fred.label = Button(fred,
+ text="This is window number %d." % self.windownum,
+ command=self.makeWindow)
+ fred.label.pack()
+ self.windownum = self.windownum + 1
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=LEFT, fill=BOTH)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=LEFT, fill=BOTH)
- # a hello button
- self.hi_there = Button(self, text='Make a New Window',
- command=self.makeWindow)
- self.hi_there.pack(side=LEFT)
+ # a hello button
+ self.hi_there = Button(self, text='Make a New Window',
+ command=self.makeWindow)
+ self.hi_there.pack(side=LEFT)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.windownum = 0
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.windownum = 0
+ self.createWidgets()
test = Test()
test.mainloop()
diff --git a/Demo/tkinter/matt/window-creation-simple.py b/Demo/tkinter/matt/window-creation-simple.py
index 969fefb..c990ed9 100644
--- a/Demo/tkinter/matt/window-creation-simple.py
+++ b/Demo/tkinter/matt/window-creation-simple.py
@@ -4,28 +4,28 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def makeWindow(self):
- fred = Toplevel()
- fred.label = Label(fred, text="Here's a new window")
- fred.label.pack()
+ fred = Toplevel()
+ fred.label = Label(fred, text="Here's a new window")
+ fred.label.pack()
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
-
- self.QUIT.pack(side=LEFT, fill=BOTH)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
- # a hello button
- self.hi_there = Button(self, text='Make a New Window',
- command=self.makeWindow)
- self.hi_there.pack(side=LEFT)
+ self.QUIT.pack(side=LEFT, fill=BOTH)
+
+ # a hello button
+ self.hi_there = Button(self, text='Make a New Window',
+ command=self.makeWindow)
+ self.hi_there.pack(side=LEFT)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
test.mainloop()
diff --git a/Demo/tkinter/matt/window-creation-w-location.py b/Demo/tkinter/matt/window-creation-w-location.py
index 0ec4e09..3f2b5b0 100644
--- a/Demo/tkinter/matt/window-creation-w-location.py
+++ b/Demo/tkinter/matt/window-creation-w-location.py
@@ -17,29 +17,29 @@ class QuitButton(Button):
class Test(Frame):
def makeWindow(self, *args):
- fred = Toplevel()
+ fred = Toplevel()
- fred.label = Canvas (fred, width="2i", height="2i")
+ fred.label = Canvas (fred, width="2i", height="2i")
- fred.label.create_line("0", "0", "2i", "2i")
- fred.label.create_line("0", "2i", "2i", "0")
- fred.label.pack()
+ fred.label.create_line("0", "0", "2i", "2i")
+ fred.label.create_line("0", "2i", "2i", "0")
+ fred.label.pack()
- ##centerWindow(fred, self.master)
+ ##centerWindow(fred, self.master)
def createWidgets(self):
- self.QUIT = QuitButton(self)
- self.QUIT.pack(side=LEFT, fill=BOTH)
+ self.QUIT = QuitButton(self)
+ self.QUIT.pack(side=LEFT, fill=BOTH)
- self.makeWindow = Button(self, text='Make a New Window',
- width=50, height=20,
- command=self.makeWindow)
- self.makeWindow.pack(side=LEFT)
+ self.makeWindow = Button(self, text='Make a New Window',
+ width=50, height=20,
+ command=self.makeWindow)
+ self.makeWindow.pack(side=LEFT)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
test.mainloop()
diff --git a/Demo/xml/elem_count.py b/Demo/xml/elem_count.py
index 4316199..7b53189 100644
--- a/Demo/xml/elem_count.py
+++ b/Demo/xml/elem_count.py
@@ -30,7 +30,7 @@ class FancyCounter(handler.ContentHandler):
for pair in self._attr_types.items():
print "%20s %d" % pair
-
+
parser = make_parser()
parser.setContentHandler(FancyCounter())
parser.parse(sys.argv[1])
diff --git a/Demo/xml/roundtrip.py b/Demo/xml/roundtrip.py
index e42bf1b..8d7d437 100644
--- a/Demo/xml/roundtrip.py
+++ b/Demo/xml/roundtrip.py
@@ -16,7 +16,7 @@ class ContentGenerator(handler.ContentHandler):
self._out = out
# ContentHandler methods
-
+
def startDocument(self):
self._out.write('<?xml version="1.0" encoding="iso-8859-1"?>\n')
@@ -34,7 +34,7 @@ class ContentGenerator(handler.ContentHandler):
def ignorableWhitespace(self, content):
self._out.write(content)
-
+
def processingInstruction(self, target, data):
self._out.write('<?%s %s?>' % (target, data))
diff --git a/Demo/xml/rss2html.py b/Demo/xml/rss2html.py
index df5d1c7..15c9891 100644
--- a/Demo/xml/rss2html.py
+++ b/Demo/xml/rss2html.py
@@ -80,7 +80,7 @@ class RSSHandler(handler.ContentHandler):
if name == "rss":
self._out.write(bottom)
-
+
def characters(self, content):
self._text = self._text + content
diff --git a/Demo/zlib/minigzip.py b/Demo/zlib/minigzip.py
index dc99d9b..e2801de 100755
--- a/Demo/zlib/minigzip.py
+++ b/Demo/zlib/minigzip.py
@@ -9,7 +9,7 @@ def write32(output, value):
output.write(chr(value & 255)) ; value=value / 256
output.write(chr(value & 255)) ; value=value / 256
output.write(chr(value & 255))
-
+
def read32(input):
v=ord(input.read(1))
v=v+ (ord(input.read(1))<<8 )
@@ -19,9 +19,9 @@ def read32(input):
import zlib, sys
if len(sys.argv)!=2:
- print 'Usage: minigzip.py <filename>'
- print ' The file will be compressed or decompressed.'
- sys.exit(0)
+ print 'Usage: minigzip.py <filename>'
+ print ' The file will be compressed or decompressed.'
+ sys.exit(0)
filename=sys.argv[1]
compressing=1 ; outputname=filename+'.gz'
@@ -64,7 +64,7 @@ else:
# extra flags, and OS byte.
if flag & FEXTRA:
# Read & discard the extra field, if present
- xlen=ord(input.read(1))
+ xlen=ord(input.read(1))
xlen=xlen+256*ord(input.read(1))
input.read(xlen)
if flag & FNAME:
@@ -92,11 +92,11 @@ else:
decompdata=decompobj.flush()
output.write(decompdata) ; length=length+len(decompdata)
crcval=zlib.crc32(decompdata, crcval)
-
+
# We've read to the end of the file, so we have to rewind in order
# to reread the 8 bytes containing the CRC and the file size. The
# decompressor is smart and knows when to stop, so feeding it
- # extra data is harmless.
+ # extra data is harmless.
input.seek(-8, 2)
crc32=read32(input)
isize=read32(input)
@@ -104,4 +104,3 @@ else:
if isize!=length: print 'Incorrect length of data produced'
input.close() ; output.close()
-
diff --git a/Demo/zlib/zlibdemo.py b/Demo/zlib/zlibdemo.py
index 7c56e3e..5a0ab63 100755
--- a/Demo/zlib/zlibdemo.py
+++ b/Demo/zlib/zlibdemo.py
@@ -4,7 +4,7 @@ import zlib, sys
if len(sys.argv)>1: filename=sys.argv[1]
else: filename='zlibdemo.py'
print 'Reading', filename
-f=open(filename, 'r') # Get the data to compress
+f=open(filename, 'r') # Get the data to compress
s=f.read()
f.close()
@@ -24,7 +24,7 @@ decompressor=zlib.decompressobj()
comptext=decomp=''
for i in range(0, len(s), chunk):
comptext=comptext+compressor.compress(s[i:i+chunk])
-comptext=comptext+compressor.flush() # Don't forget to call flush()!!
+comptext=comptext+compressor.flush() # Don't forget to call flush()!!
for i in range(0, len(comptext), chunk):
decomp=decomp+decompressor.decompress(comptext[i:i+chunk])
@@ -33,4 +33,3 @@ decomp=decomp+decompressor.flush()
print 'Progressive compression (level 9):'
print ' Original:', len(s), 'Compressed:', len(comptext),
print 'Uncompressed:', len(decomp)
-