Whitespace normalization, via reindent.py.

This commit is contained in:
Tim Peters 2004-07-18 06:16:08 +00:00
parent e6ddc8b20b
commit 182b5aca27
453 changed files with 31318 additions and 31452 deletions

View file

@ -17,7 +17,7 @@
import Tix import Tix
TCL_ALL_EVENTS = 0 TCL_ALL_EVENTS = 0
def RunSample (root): def RunSample (root):
balloon = DemoBalloon(root) balloon = DemoBalloon(root)

View file

@ -21,7 +21,7 @@ def RunSample(w):
# Create the label on the top of the dialog box # Create the label on the top of the dialog box
# #
top = Tix.Label(w, padx=20, pady=10, bd=1, relief=Tix.RAISED, 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 # 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 # -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 = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL)
box.add('ok', text='OK', underline=0, width=5, 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, 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) box.pack(side=Tix.BOTTOM, fill=Tix.X)
top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1) top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1)

View file

@ -22,13 +22,13 @@ static char * netw_xpm[] = {
/* width height ncolors chars_per_pixel */ /* width height ncolors chars_per_pixel */
"32 32 7 1", "32 32 7 1",
/* colors */ /* colors */
" s None c None", " s None c None",
". c #000000000000", ". c #000000000000",
"X c white", "X c white",
"o c #c000c000c000", "o c #c000c000c000",
"O c #404040", "O c #404040",
"+ c blue", "+ c blue",
"@ c red", "@ c red",
/* pixels */ /* pixels */
" ", " ",
" .............. ", " .............. ",
@ -69,11 +69,11 @@ static char * drivea_xpm[] = {
/* width height ncolors chars_per_pixel */ /* width height ncolors chars_per_pixel */
"32 32 5 1", "32 32 5 1",
/* colors */ /* colors */
" s None c None", " s None c None",
". c #000000000000", ". c #000000000000",
"X c white", "X c white",
"o c #c000c000c000", "o c #c000c000c000",
"O c #800080008000", "O c #800080008000",
/* pixels */ /* pixels */
" ", " ",
" ", " ",
@ -146,10 +146,10 @@ static unsigned char drivea_bits[] = {
def RunSample(w): def RunSample(w):
w.img0 = Tix.Image('pixmap', data=network_pixmap) w.img0 = Tix.Image('pixmap', data=network_pixmap)
if not w.img0: 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) w.img1 = Tix.Image('pixmap', data=hard_disk_pixmap)
if not w.img0: 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) hdd = Tix.Button(w, padx=4, pady=1, width=120)
net = 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 = 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', 'line')
w.hdd_img.tk.call(str(w.hdd_img), 'add', 'text', '-text', 'Hard Disk', 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', 'space', '-width', '7')
w.hdd_img.tk.call(str(w.hdd_img), 'add', 'image', '-image', w.img1) 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 = 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', 'line')
w.net_img.tk.call(str(w.net_img), 'add', 'text', '-text', 'Network', 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', 'space', '-width', '7')
w.net_img.tk.call(str(w.net_img), 'add', 'image', '-image', w.img0) 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 net['image'] = w.net_img
close = Tix.Button(w, pady=1, text='Close', 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) 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) net.pack(side=Tix.LEFT, padx=10, pady=10, fill=Tix.Y, expand=1)
@ -194,4 +194,3 @@ if __name__ == '__main__':
root = Tix.Tk() root = Tix.Tk()
RunSample(root) RunSample(root)
root.mainloop() root.mainloop()

View file

@ -31,21 +31,21 @@ def RunSample(w):
# be 10 so that their labels appear to be aligned. # be 10 so that their labels appear to be aligned.
# #
a = Tix.ComboBox(top, label="Month: ", dropdown=1, a = Tix.ComboBox(top, label="Month: ", dropdown=1,
command=select_month, editable=0, variable=demo_month, command=select_month, editable=0, variable=demo_month,
options='listbox.height 6 label.width 10 label.anchor e') 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 # $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 # four choices for the user, but he can enter an alternative year if he
# wants to. # wants to.
# #
# [Hint] Use the padY and anchor options of the label subwidget 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 # [Hint] Notice that you should use padY (the NAME of the option) and not
# pady (the SWITCH of the option). # pady (the SWITCH of the option).
# #
b = Tix.ComboBox(top, label="Year: ", dropdown=0, b = Tix.ComboBox(top, label="Year: ", dropdown=0,
command=select_year, editable=1, variable=demo_year, command=select_year, editable=1, variable=demo_year,
options='listbox.height 4 label.padY 5 label.width 10 label.anchor ne') options='listbox.height 4 label.padY 5 label.width 10 label.anchor ne')
a.pack(side=Tix.TOP, anchor=Tix.W) a.pack(side=Tix.TOP, anchor=Tix.W)
b.pack(side=Tix.TOP, anchor=Tix.W) b.pack(side=Tix.TOP, anchor=Tix.W)
@ -78,9 +78,9 @@ def RunSample(w):
box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL) box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL)
box.add('ok', text='Ok', underline=0, width=6, 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, 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) box.pack(side=Tix.BOTTOM, fill=Tix.X)
top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1) top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1)

View file

@ -20,7 +20,7 @@
import Tix import Tix
TCL_ALL_EVENTS = 0 TCL_ALL_EVENTS = 0
def RunSample (root): def RunSample (root):
control = DemoControl(root) control = DemoControl(root)
@ -100,9 +100,9 @@ def adjust_maker(w, inc):
i = maker_list.index(demo_maker.get()) i = maker_list.index(demo_maker.get())
i = i + inc i = i + inc
if i >= len(maker_list): if i >= len(maker_list):
i = 0 i = 0
elif 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 # 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). # 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): def validate_maker(w):
try: try:
i = maker_list.index(demo_maker.get()) i = maker_list.index(demo_maker.get())
except ValueError: except ValueError:
# Works here though. Why ? Beats me. # Works here though. Why ? Beats me.
return maker_list[0] return maker_list[0]
# Works here though. Why ? Beats me. # Works here though. Why ? Beats me.
return maker_list[i] return maker_list[i]

View file

@ -1,6 +1,6 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- # -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
# #
# $Id$ # $Id$
# #
# Tix Demostration Program # Tix Demostration Program
# #
@ -19,7 +19,7 @@
import Tix, os, copy import Tix, os, copy
from Tkconstants import * from Tkconstants import *
TCL_ALL_EVENTS = 0 TCL_ALL_EVENTS = 0
def RunSample (root): def RunSample (root):
dirlist = DemoDirList(root) dirlist = DemoDirList(root)
@ -129,4 +129,3 @@ if __name__== '__main__' :
for line in traceback.format_exception(t,v,tb): for line in traceback.format_exception(t,v,tb):
text = text + line + '\n' text = text + line + '\n'
d = tkMessageBox.showerror ( 'Tix Demo Error', text) d = tkMessageBox.showerror ( 'Tix Demo Error', text)

View file

@ -1,6 +1,6 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- # -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
# #
# $Id$ # $Id$
# #
# Tix Demostration Program # Tix Demostration Program
# #
@ -19,7 +19,7 @@
import Tix, os, copy import Tix, os, copy
from Tkconstants import * from Tkconstants import *
TCL_ALL_EVENTS = 0 TCL_ALL_EVENTS = 0
def RunSample (root): def RunSample (root):
dirtree = DemoDirTree(root) dirtree = DemoDirTree(root)
@ -115,4 +115,3 @@ class DemoDirTree:
if __name__== '__main__' : if __name__== '__main__' :
root=Tix.Tk() root=Tix.Tk()
RunSample(root) RunSample(root)

View file

@ -23,9 +23,9 @@ def RunSample(w):
# notebook, so that they are well-aligned on the screen. # notebook, so that they are well-aligned on the screen.
prefix = Tix.OptionName(w) prefix = Tix.OptionName(w)
if prefix: if prefix:
prefix = '*'+prefix prefix = '*'+prefix
else: else:
prefix = '' prefix = ''
w.option_add(prefix+'*TixControl*entry.width', 10) w.option_add(prefix+'*TixControl*entry.width', 10)
w.option_add(prefix+'*TixControl*label.width', 18) w.option_add(prefix+'*TixControl*label.width', 18)
w.option_add(prefix+'*TixControl*label.anchor', Tix.E) w.option_add(prefix+'*TixControl*label.anchor', Tix.E)
@ -105,10 +105,10 @@ def doDestroy():
def createCommonButtons(master): def createCommonButtons(master):
ok = Tix.Button(master, name='ok', text='OK', width=6, ok = Tix.Button(master, name='ok', text='OK', width=6,
command=doDestroy) command=doDestroy)
cancel = Tix.Button(master, name='cancel', cancel = Tix.Button(master, name='cancel',
text='Cancel', width=6, text='Cancel', width=6,
command=doDestroy) command=doDestroy)
ok.pack(side=Tix.TOP, padx=2, pady=2) 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)

View file

@ -16,7 +16,7 @@
import Tix import Tix
options = {'text':'Plain Text', 'post':'PostScript', 'html':'HTML', options = {'text':'Plain Text', 'post':'PostScript', 'html':'HTML',
'tex':'LaTeX', 'rtf':'Rich Text Format'} 'tex':'LaTeX', 'rtf':'Rich Text Format'}
def RunSample(w): def RunSample(w):
global demo_opt_from, demo_opt_to global demo_opt_from, demo_opt_to
@ -27,22 +27,22 @@ def RunSample(w):
top = Tix.Frame(w, bd=1, relief=Tix.RAISED) top = Tix.Frame(w, bd=1, relief=Tix.RAISED)
from_file = Tix.OptionMenu(top, label="From File Format : ", from_file = Tix.OptionMenu(top, label="From File Format : ",
variable=demo_opt_from, variable=demo_opt_from,
options = 'label.width 19 label.anchor e menubutton.width 15') options = 'label.width 19 label.anchor e menubutton.width 15')
to_file = Tix.OptionMenu(top, label="To File Format : ", to_file = Tix.OptionMenu(top, label="To File Format : ",
variable=demo_opt_to, variable=demo_opt_to,
options='label.width 19 label.anchor e menubutton.width 15') options='label.width 19 label.anchor e menubutton.width 15')
# Add the available options to the two OptionMenu widgets # Add the available options to the two OptionMenu widgets
# #
# [Hint] You have to add the options first before you set the # [Hint] You have to add the options first before you set the
# global variables "demo_opt_from" and "demo_opt_to". Otherwise # global variables "demo_opt_from" and "demo_opt_to". Otherwise
# the OptionMenu widget will complain about "unknown options"! # the OptionMenu widget will complain about "unknown options"!
# #
for opt in options.keys(): for opt in options.keys():
from_file.add_command(opt, label=options[opt]) from_file.add_command(opt, label=options[opt])
to_file.add_command(opt, label=options[opt]) to_file.add_command(opt, label=options[opt])
demo_opt_from.set('html') demo_opt_from.set('html')
demo_opt_to.set('post') demo_opt_to.set('post')
@ -52,9 +52,9 @@ def RunSample(w):
box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL) box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL)
box.add('ok', text='Ok', underline=0, width=6, 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, 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) box.pack(side=Tix.BOTTOM, fill=Tix.X)
top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1) top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1)

View file

@ -17,7 +17,7 @@
import Tix import Tix
TCL_ALL_EVENTS = 0 TCL_ALL_EVENTS = 0
def RunSample (root): def RunSample (root):
panedwin = DemoPanedwin(root) panedwin = DemoPanedwin(root)

View file

@ -1,6 +1,6 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- # -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
# #
# $Id$ # $Id$
# #
# Tix Demostration Program # Tix Demostration Program
# #
@ -29,7 +29,7 @@ def RunSample(w):
# Set the entries inside the PopupMenu widget. # Set the entries inside the PopupMenu widget.
# [Hint] You have to manipulate the "menu" subwidget. # [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 # [Hint] Watch carefully how the sub-menu is created
# #
p.menu.add_command(label='Desktop', underline=0) p.menu.add_command(label='Desktop', underline=0)
@ -45,9 +45,9 @@ def RunSample(w):
box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL) box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL)
box.add('ok', text='Ok', underline=0, width=6, 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, 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) box.pack(side=Tix.BOTTOM, fill=Tix.X)
top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1) top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1)

View file

@ -15,7 +15,7 @@
import Tix import Tix
TCL_ALL_EVENTS = 0 TCL_ALL_EVENTS = 0
def RunSample (root): def RunSample (root):
shlist = DemoSHList(root) shlist = DemoSHList(root)
@ -88,9 +88,9 @@ class DemoSHList:
hlist.add( key, text=name ) hlist.add( key, text=name )
# [Hint] Make sure the keys (e.g. 'boss.person') you choose # [Hint] Make sure the keys (e.g. 'boss.person') you choose
# are unique names. If you cannot be sure of this (because of # are unique names. If you cannot be sure of this (because of
# the structure of your database, e.g.) you can use the # the structure of your database, e.g.) you can use the
# "add_child" command instead: # "add_child" command instead:
# #
# hlist.addchild( boss, text=name) # hlist.addchild( boss, text=name)
# ^^^^ # ^^^^
@ -129,4 +129,3 @@ class DemoSHList:
if __name__== '__main__' : if __name__== '__main__' :
root=Tix.Tk() root=Tix.Tk()
RunSample(root) RunSample(root)

View file

@ -18,7 +18,7 @@
import Tix import Tix
TCL_ALL_EVENTS = 0 TCL_ALL_EVENTS = 0
def RunSample (root): def RunSample (root):
shlist = DemoSHList(root) shlist = DemoSHList(root)
@ -47,7 +47,7 @@ class DemoSHList:
hlist=top.a.hlist hlist=top.a.hlist
# Create the title for the HList widget # 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 # so that the header is displayed
# #
@ -72,22 +72,22 @@ class DemoSHList:
# This is our little relational database # This is our little relational database
# #
boss = ('doe', 'John Doe', 'Director') boss = ('doe', 'John Doe', 'Director')
managers = [ managers = [
('jeff', 'Jeff Waxman', 'Manager'), ('jeff', 'Jeff Waxman', 'Manager'),
('john', 'John Lee', 'Manager'), ('john', 'John Lee', 'Manager'),
('peter', 'Peter Kenson', 'Manager') ('peter', 'Peter Kenson', 'Manager')
] ]
employees = [ employees = [
('alex', 'john', 'Alex Kellman', 'Clerk'), ('alex', 'john', 'Alex Kellman', 'Clerk'),
('alan', 'john', 'Alan Adams', 'Clerk'), ('alan', 'john', 'Alan Adams', 'Clerk'),
('andy', 'peter', 'Andreas Crawford', 'Salesman'), ('andy', 'peter', 'Andreas Crawford', 'Salesman'),
('doug', 'jeff', 'Douglas Bloom', 'Clerk'), ('doug', 'jeff', 'Douglas Bloom', 'Clerk'),
('jon', 'peter', 'Jon Baraki', 'Salesman'), ('jon', 'peter', 'Jon Baraki', 'Salesman'),
('chris', 'jeff', 'Chris Geoffrey', 'Clerk'), ('chris', 'jeff', 'Chris Geoffrey', 'Clerk'),
('chuck', 'jeff', 'Chuck McLean', 'Cleaner') ('chuck', 'jeff', 'Chuck McLean', 'Cleaner')
] ]
style['mgr_name'] = Tix.DisplayStyle(Tix.TEXT, refwindow=hlist) style['mgr_name'] = Tix.DisplayStyle(Tix.TEXT, refwindow=hlist)
@ -127,7 +127,7 @@ class DemoSHList:
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.add(entrypath, text=name, style=style['empl_name'])
hlist.item_create(entrypath, 1, itemtype=Tix.TEXT, hlist.item_create(entrypath, 1, itemtype=Tix.TEXT,
@ -166,4 +166,3 @@ class DemoSHList:
if __name__== '__main__' : if __name__== '__main__' :
root=Tix.Tk() root=Tix.Tk()
RunSample(root) RunSample(root)

View file

@ -34,17 +34,17 @@ def RunSample(w):
def adddir(tree, dir): def adddir(tree, dir):
if dir == '/': if dir == '/':
text = '/' text = '/'
else: else:
text = os.path.basename(dir) text = os.path.basename(dir)
tree.hlist.add(dir, itemtype=Tix.IMAGETEXT, text=text, tree.hlist.add(dir, itemtype=Tix.IMAGETEXT, text=text,
image=tree.tk.call('tix', 'getimage', 'folder')) image=tree.tk.call('tix', 'getimage', 'folder'))
try: try:
os.listdir(dir) os.listdir(dir)
tree.setmode(dir, 'open') tree.setmode(dir, 'open')
except os.error: except os.error:
# No read permission ? # No read permission ?
pass pass
# This function is called whenever the user presses the (+) indicator or # This function is called whenever the user presses the (+) indicator or
# double clicks on a directory whose mode is "open". It loads the files # 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): def opendir(tree, dir):
entries = tree.hlist.info_children(dir) entries = tree.hlist.info_children(dir)
if entries: if entries:
# We have already loaded this directory. Let's just # We have already loaded this directory. Let's just
# show all the child entries # show all the child entries
# #
# Note: since we load the directory only once, it will not be # Note: since we load the directory only once, it will not be
# refreshed if the you add or remove files from this # refreshed if the you add or remove files from this
# directory. # directory.
# #
for entry in entries: for entry in entries:
tree.hlist.show_entry(entry) tree.hlist.show_entry(entry)
files = os.listdir(dir) files = os.listdir(dir)
for file in files: for file in files:
if os.path.isdir(dir + '/' + file): if os.path.isdir(dir + '/' + file):
adddir(tree, dir + '/' + file) adddir(tree, dir + '/' + file)
else: else:
tree.hlist.add(dir + '/' + file, itemtype=Tix.IMAGETEXT, text=file, tree.hlist.add(dir + '/' + file, itemtype=Tix.IMAGETEXT, text=file,
image=tree.tk.call('tix', 'getimage', 'file')) image=tree.tk.call('tix', 'getimage', 'file'))
if __name__ == '__main__': if __name__ == '__main__':
root = Tix.Tk() root = Tix.Tk()

View file

@ -4,38 +4,38 @@
# #
# tixwidgets.py -- # 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. # 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 # If you have installed Python & Tix properly, you can execute this as
# #
# % python tixwidgets.py # % python tixwidgets.py
# #
import os, os.path, sys, Tix import os, os.path, sys, Tix
from Tkconstants import * from Tkconstants import *
import traceback, tkMessageBox import traceback, tkMessageBox
TCL_DONT_WAIT = 1<<1 TCL_DONT_WAIT = 1<<1
TCL_WINDOW_EVENTS = 1<<2 TCL_WINDOW_EVENTS = 1<<2
TCL_FILE_EVENTS = 1<<3 TCL_FILE_EVENTS = 1<<3
TCL_TIMER_EVENTS = 1<<4 TCL_TIMER_EVENTS = 1<<4
TCL_IDLE_EVENTS = 1<<5 TCL_IDLE_EVENTS = 1<<5
TCL_ALL_EVENTS = 0 TCL_ALL_EVENTS = 0
class Demo: class Demo:
def __init__(self, top): def __init__(self, top):
self.root = top self.root = top
self.exit = -1 self.exit = -1
self.dir = None # script directory self.dir = None # script directory
self.balloon = None # balloon widget self.balloon = None # balloon widget
self.useBalloons = Tix.StringVar() self.useBalloons = Tix.StringVar()
self.useBalloons.set('0') self.useBalloons.set('0')
self.statusbar = None # status bar widget self.statusbar = None # status bar widget
self.welmsg = None # Msg widget self.welmsg = None # Msg widget
self.welfont = '' # font name self.welfont = '' # font name
self.welsize = '' # font size self.welsize = '' # font size
progname = sys.argv[0] progname = sys.argv[0]
dirname = os.path.dirname(progname) dirname = os.path.dirname(progname)
@ -72,7 +72,7 @@ class Demo:
variable=self.useBalloons) variable=self.useBalloons)
# The trace variable option doesn't seem to work, instead I use 'command' # The trace variable option doesn't seem to work, instead I use 'command'
#apply(w.tk.call, ('trace', 'variable', self.useBalloons, 'w', #apply(w.tk.call, ('trace', 'variable', self.useBalloons, 'w',
# ToggleHelp)) # ToggleHelp))
return w return w
@ -130,15 +130,15 @@ class Demo:
# To show Tcl errors - uncomment this to see the listbox bug. # To show Tcl errors - uncomment this to see the listbox bug.
# Tkinter defines a Tcl tkerror procedure that in effect # Tkinter defines a Tcl tkerror procedure that in effect
# silences all background Tcl error reporting. # 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): def quitcmd (self):
"""Quit our mainloop. It is up to you to call root.destroy() after.""" """Quit our mainloop. It is up to you to call root.destroy() after."""
self.exit = 0 self.exit = 0
def loop(self): def loop(self):
"""This is an explict replacement for _tkinter mainloop() """This is an explict replacement for _tkinter mainloop()
It lets you catch keyboard interrupts easier, and avoids It lets you catch keyboard interrupts easier, and avoids
the 20 msec. dead sleep() which burns a constant CPU.""" the 20 msec. dead sleep() which burns a constant CPU."""
while self.exit < 0: while self.exit < 0:
# There are 2 whiles here. The outer one lets you continue # There are 2 whiles here. The outer one lets you continue
# after a ^C interrupt. # after a ^C interrupt.
@ -221,9 +221,9 @@ def MkWelcomeBar(top):
b2.pack(side=Tix.LEFT, padx=4, pady=4) b2.pack(side=Tix.LEFT, padx=4, pady=4)
demo.balloon.bind_widget(b1, msg='Choose\na font', 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', 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 return w
def MkWelcomeText(top): def MkWelcomeText(top):
@ -233,10 +233,10 @@ def MkWelcomeText(top):
win = w.window win = w.window
text = 'Welcome to TIX in Python' text = 'Welcome to TIX in Python'
title = Tix.Label(win, 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, msg = Tix.Message(win,
bd=0, width=400, anchor=Tix.N, bd=0, width=400, anchor=Tix.N,
text='Tix is a set of mega-widgets based on TK. This program \ 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 \ demonstrates the widgets in the Tix widget set. You can choose the pages \
in this window to look at the corresponding widgets. \n\n\ in this window to look at the corresponding widgets. \n\n\
To quit this program, choose the "File | Exit" command.\n\n\ To quit this program, choose the "File | Exit" command.\n\n\
@ -250,19 +250,19 @@ def MainTextFont(w):
global demo global demo
if not demo.welmsg: if not demo.welmsg:
return return
font = demo.welfont['value'] font = demo.welfont['value']
point = demo.welsize['value'] point = demo.welsize['value']
if font == 'Times Roman': if font == 'Times Roman':
font = 'times' font = 'times'
fontstr = '%s %s' % (font, point) fontstr = '%s %s' % (font, point)
demo.welmsg['font'] = fontstr demo.welmsg['font'] = fontstr
def ToggleHelp(): def ToggleHelp():
if demo.useBalloons.get() == '1': if demo.useBalloons.get() == '1':
demo.balloon['state'] = 'both' demo.balloon['state'] = 'both'
else: else:
demo.balloon['state'] = 'none' demo.balloon['state'] = 'none'
def MkChoosers(nb, name): def MkChoosers(nb, name):
w = nb.page(name) w = nb.page(name)
@ -307,7 +307,7 @@ def MkCombo(w):
static = Tix.ComboBox(w, label='Static', editable=0, options=options) static = Tix.ComboBox(w, label='Static', editable=0, options=options)
editable = Tix.ComboBox(w, label='Editable', editable=1, options=options) editable = Tix.ComboBox(w, label='Editable', editable=1, options=options)
history = Tix.ComboBox(w, label='History', editable=1, history=1, 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, 'January')
static.insert(Tix.END, 'February') static.insert(Tix.END, 'February')
static.insert(Tix.END, 'March') static.insert(Tix.END, 'March')
@ -340,20 +340,20 @@ states = ['Bengal', 'Delhi', 'Karnataka', 'Tamil Nadu']
def spin_cmd(w, inc): def spin_cmd(w, inc):
idx = states.index(demo_spintxt.get()) + inc idx = states.index(demo_spintxt.get()) + inc
if idx < 0: if idx < 0:
idx = len(states) - 1 idx = len(states) - 1
elif idx >= len(states): elif idx >= len(states):
idx = 0 idx = 0
# following doesn't work. # following doesn't work.
# return states[idx] # return states[idx]
demo_spintxt.set(states[idx]) # this works demo_spintxt.set(states[idx]) # this works
def spin_validate(w): def spin_validate(w):
global states, demo_spintxt global states, demo_spintxt
try: try:
i = states.index(demo_spintxt.get()) i = states.index(demo_spintxt.get())
except ValueError: except ValueError:
return states[0] return states[0]
return states[i] return states[i]
# why this procedure works as opposed to the previous one beats me. # why this procedure works as opposed to the previous one beats me.
@ -417,8 +417,8 @@ def MkOptMenu(w):
def MkFileEnt(w): def MkFileEnt(w):
msg = Tix.Message(w, msg = Tix.Message(w,
relief=Tix.FLAT, width=240, anchor=Tix.N, relief=Tix.FLAT, width=240, anchor=Tix.N,
text='Press the "open file" icon button and a TixFileSelectDialog will popup.') text='Press the "open file" icon button and a TixFileSelectDialog will popup.')
ent = Tix.FileEntry(w, label='Select a file : ') ent = Tix.FileEntry(w, label='Select a file : ')
msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3) 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) 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. and your past selections are recorded.
""" """
msg = Tix.Message(w, msg = Tix.Message(w,
relief=Tix.FLAT, width=240, anchor=Tix.N, 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.') 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) box = Tix.FileSelectBox(w)
msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3) 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) box.pack(side=Tix.TOP, fill=Tix.X, padx=3, pady=3)
@ -443,8 +443,8 @@ def MkToolBar(w):
options='frame.borderWidth 1' options='frame.borderWidth 1'
msg = Tix.Message(w, msg = Tix.Message(w,
relief=Tix.FLAT, width=240, anchor=Tix.N, relief=Tix.FLAT, width=240, anchor=Tix.N,
text='The Select widget is also good for arranging buttons in a tool bar.') text='The Select widget is also good for arranging buttons in a tool bar.')
bar = Tix.Frame(w, bd=2, relief=Tix.RAISED) bar = Tix.Frame(w, bd=2, relief=Tix.RAISED)
font = Tix.Select(w, allowzero=1, radio=0, label='', options=options) font = Tix.Select(w, allowzero=1, radio=0, label='', options=options)
para = Tix.Select(w, allowzero=0, radio=1, label='', options=options) para = Tix.Select(w, allowzero=0, radio=1, label='', options=options)
@ -466,8 +466,8 @@ def MkToolBar(w):
def MkTitle(w): def MkTitle(w):
msg = Tix.Message(w, msg = Tix.Message(w,
relief=Tix.FLAT, width=240, anchor=Tix.N, 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') 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) msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3)
def MkScroll(nb, name): def MkScroll(nb, name):
@ -494,8 +494,8 @@ def MkSList(w):
top = Tix.Frame(w, width=300, height=330) top = Tix.Frame(w, width=300, height=330)
bot = Tix.Frame(w) bot = Tix.Frame(w)
msg = Tix.Message(top, msg = Tix.Message(top,
relief=Tix.FLAT, width=200, anchor=Tix.N, 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.') 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 = Tix.ScrolledListBox(top, scrollbar='auto')
list.place(x=50, y=150, width=120, height=80) list.place(x=50, y=150, width=120, height=80)
@ -508,8 +508,8 @@ def MkSList(w):
list.listbox.insert(Tix.END, 'Washington') list.listbox.insert(Tix.END, 'Washington')
rh = Tix.ResizeHandle(top, bg='black', rh = Tix.ResizeHandle(top, bg='black',
relief=Tix.RAISED, relief=Tix.RAISED,
handlesize=8, gridded=1, minwidth=50, minheight=30) handlesize=8, gridded=1, minwidth=50, minheight=30)
btn = Tix.Button(bot, text='Reset', command=lambda w=rh, x=list: SList_reset(w,x)) btn = Tix.Button(bot, text='Reset', command=lambda w=rh, x=list: SList_reset(w,x))
top.propagate(0) top.propagate(0)
msg.pack(fill=Tix.X) msg.pack(fill=Tix.X)
@ -517,7 +517,7 @@ def MkSList(w):
top.pack(expand=1, fill=Tix.BOTH) top.pack(expand=1, fill=Tix.BOTH)
bot.pack(fill=Tix.BOTH) bot.pack(fill=Tix.BOTH)
list.bind('<Map>', func=lambda arg=0, rh=rh, list=list: 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): def SList_reset(rh, list):
list.place(x=50, y=150, width=120, height=80) 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) top = Tix.Frame(w, width=330, height=330)
bot = Tix.Frame(w) bot = Tix.Frame(w)
msg = Tix.Message(top, msg = Tix.Message(top,
relief=Tix.FLAT, width=200, anchor=Tix.N, relief=Tix.FLAT, width=200, anchor=Tix.N,
text=text) text=text)
win = Tix.ScrolledWindow(top, scrollbar='auto') win = Tix.ScrolledWindow(top, scrollbar='auto')
@ -551,8 +551,8 @@ def MkSWindow(w):
win.place(x=30, y=150, width=190, height=120) win.place(x=30, y=150, width=190, height=120)
rh = Tix.ResizeHandle(top, bg='black', rh = Tix.ResizeHandle(top, bg='black',
relief=Tix.RAISED, relief=Tix.RAISED,
handlesize=8, gridded=1, minwidth=50, minheight=30) handlesize=8, gridded=1, minwidth=50, minheight=30)
btn = Tix.Button(bot, text='Reset', command=lambda w=rh, x=win: SWindow_reset(w,x)) btn = Tix.Button(bot, text='Reset', command=lambda w=rh, x=win: SWindow_reset(w,x))
top.propagate(0) top.propagate(0)
msg.pack(fill=Tix.X) msg.pack(fill=Tix.X)
@ -561,7 +561,7 @@ def MkSWindow(w):
bot.pack(fill=Tix.BOTH) bot.pack(fill=Tix.BOTH)
win.bind('<Map>', func=lambda arg=0, rh=rh, win=win: 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): def SWindow_reset(rh, win):
win.place(x=30, y=150, width=190, height=120) win.place(x=30, y=150, width=190, height=120)
@ -574,8 +574,8 @@ def MkSText(w):
top = Tix.Frame(w, width=330, height=330) top = Tix.Frame(w, width=330, height=330)
bot = Tix.Frame(w) bot = Tix.Frame(w)
msg = Tix.Message(top, msg = Tix.Message(top,
relief=Tix.FLAT, width=200, anchor=Tix.N, 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.') 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 = Tix.ScrolledText(top, scrollbar='auto')
win.text['wrap'] = 'none' win.text['wrap'] = 'none'
@ -593,8 +593,8 @@ scrollbar should always be shown, and so on.'''
win.place(x=30, y=150, width=190, height=100) win.place(x=30, y=150, width=190, height=100)
rh = Tix.ResizeHandle(top, bg='black', rh = Tix.ResizeHandle(top, bg='black',
relief=Tix.RAISED, relief=Tix.RAISED,
handlesize=8, gridded=1, minwidth=50, minheight=30) handlesize=8, gridded=1, minwidth=50, minheight=30)
btn = Tix.Button(bot, text='Reset', command=lambda w=rh, x=win: SText_reset(w,x)) btn = Tix.Button(bot, text='Reset', command=lambda w=rh, x=win: SText_reset(w,x))
top.propagate(0) top.propagate(0)
msg.pack(fill=Tix.X) msg.pack(fill=Tix.X)
@ -602,7 +602,7 @@ scrollbar should always be shown, and so on.'''
top.pack(expand=1, fill=Tix.BOTH) top.pack(expand=1, fill=Tix.BOTH)
bot.pack(fill=Tix.BOTH) bot.pack(fill=Tix.BOTH)
win.bind('<Map>', func=lambda arg=0, rh=rh, win=win: 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): def SText_reset(rh, win):
win.place(x=30, y=150, width=190, height=120) win.place(x=30, y=150, width=190, height=120)
@ -628,8 +628,8 @@ def MkPanedWindow(w):
or horizontally. or horizontally.
""" """
msg = Tix.Message(w, msg = Tix.Message(w,
relief=Tix.FLAT, width=240, anchor=Tix.N, 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.') 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 = Tix.LabelEntry(w, label='Newsgroup:', options='entry.width 25')
group.entry.insert(0,'comp.lang.python') group.entry.insert(0,'comp.lang.python')
pane = Tix.PanedWindow(w, orientation='vertical') 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): def MkNoteBook(w):
msg = Tix.Message(w, msg = Tix.Message(w,
relief=Tix.FLAT, width=240, anchor=Tix.N, relief=Tix.FLAT, width=240, anchor=Tix.N,
text='The NoteBook widget allows you to layout a complex interface into individual pages.') text='The NoteBook widget allows you to layout a complex interface into individual pages.')
# prefix = Tix.OptionName(w) # prefix = Tix.OptionName(w)
# if not prefix: prefix = '' # if not prefix: prefix = ''
# w.option_add('*' + prefix + '*TixNoteBook*tagPadX', 8) # w.option_add('*' + prefix + '*TixNoteBook*tagPadX', 8)
@ -738,8 +738,8 @@ def MkDirListWidget(w):
directories. directories.
""" """
msg = Tix.Message(w, msg = Tix.Message(w,
relief=Tix.FLAT, width=240, anchor=Tix.N, 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.') 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') 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) msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3)
dirlist.pack(side=Tix.TOP, 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 """The TixExFileSelectBox widget is more user friendly than the Motif
style FileSelectBox. """ style FileSelectBox. """
msg = Tix.Message(w, msg = Tix.Message(w,
relief=Tix.FLAT, width=240, anchor=Tix.N, relief=Tix.FLAT, width=240, anchor=Tix.N,
text='The Tix ExFileSelectBox widget is more user friendly than the Motif style FileSelectBox.') 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 # There's a bug in the ComboBoxes - the scrolledlistbox is destroyed
box = Tix.ExFileSelectBox(w, bd=2, relief=Tix.RAISED) box = Tix.ExFileSelectBox(w, bd=2, relief=Tix.RAISED)
msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3) 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 ### List of all the demos we want to show off
comments = {'widget' : 'Widget Demos', 'image' : 'Image Demos'} comments = {'widget' : 'Widget Demos', 'image' : 'Image Demos'}
samples = {'Balloon' : 'Balloon', samples = {'Balloon' : 'Balloon',
'Button Box' : 'BtnBox', 'Button Box' : 'BtnBox',
'Combo Box' : 'ComboBox', 'Combo Box' : 'ComboBox',
'Compound Image' : 'CmpImg', 'Compound Image' : 'CmpImg',
'Directory List' : 'DirList', 'Directory List' : 'DirList',
'Directory Tree' : 'DirTree', 'Directory Tree' : 'DirTree',
'Control' : 'Control', 'Control' : 'Control',
'Notebook' : 'NoteBook', 'Notebook' : 'NoteBook',
'Option Menu' : 'OptMenu', 'Option Menu' : 'OptMenu',
'Paned Window' : 'PanedWin', 'Paned Window' : 'PanedWin',
'Popup Menu' : 'PopMenu', 'Popup Menu' : 'PopMenu',
'ScrolledHList (1)' : 'SHList1', 'ScrolledHList (1)' : 'SHList1',
'ScrolledHList (2)' : 'SHList2', 'ScrolledHList (2)' : 'SHList2',
'Tree (dynamic)' : 'Tree' 'Tree (dynamic)' : 'Tree'
} }
# There are still a lot of demos to be translated: # There are still a lot of demos to be translated:
## set root { ## set root {
## {d "File Selectors" file } ## {d "File Selectors" file }
## {d "Hierachical ListBox" hlist } ## {d "Hierachical ListBox" hlist }
## {d "Tabular ListBox" tlist {c tixTList}} ## {d "Tabular ListBox" tlist {c tixTList}}
## {d "Grid Widget" grid {c tixGrid}} ## {d "Grid Widget" grid {c tixGrid}}
## {d "Manager Widgets" manager } ## {d "Manager Widgets" manager }
## {d "Scrolled Widgets" scroll } ## {d "Scrolled Widgets" scroll }
## {d "Miscellaneous Widgets" misc } ## {d "Miscellaneous Widgets" misc }
## {d "Image Types" image } ## {d "Image Types" image }
## } ## }
## ##
## set image { ## set image {
## {d "Compound Image" cmpimg } ## {d "Compound Image" cmpimg }
## {d "XPM Image" xpm {i pixmap}} ## {d "XPM Image" xpm {i pixmap}}
## } ## }
## ##
## set cmpimg { ## set cmpimg {
##done {f "In Buttons" CmpImg.tcl } ##done {f "In Buttons" CmpImg.tcl }
## {f "In NoteBook" CmpImg2.tcl } ## {f "In NoteBook" CmpImg2.tcl }
## {f "Notebook Color Tabs" CmpImg4.tcl } ## {f "Notebook Color Tabs" CmpImg4.tcl }
## {f "Icons" CmpImg3.tcl } ## {f "Icons" CmpImg3.tcl }
## } ## }
## ##
## set xpm { ## set xpm {
## {f "In Button" Xpm.tcl {i pixmap}} ## {f "In Button" Xpm.tcl {i pixmap}}
## {f "In Menu" Xpm1.tcl {i pixmap}} ## {f "In Menu" Xpm1.tcl {i pixmap}}
## } ## }
## ##
## set file { ## set file {
##added {f DirList DirList.tcl } ##added {f DirList DirList.tcl }
##added {f DirTree DirTree.tcl } ##added {f DirTree DirTree.tcl }
## {f DirSelectDialog DirDlg.tcl } ## {f DirSelectDialog DirDlg.tcl }
## {f ExFileSelectDialog EFileDlg.tcl } ## {f ExFileSelectDialog EFileDlg.tcl }
## {f FileSelectDialog FileDlg.tcl } ## {f FileSelectDialog FileDlg.tcl }
## {f FileEntry FileEnt.tcl } ## {f FileEntry FileEnt.tcl }
## } ## }
## ##
## set hlist { ## set hlist {
## {f HList HList1.tcl } ## {f HList HList1.tcl }
## {f CheckList ChkList.tcl {c tixCheckList}} ## {f CheckList ChkList.tcl {c tixCheckList}}
##done {f "ScrolledHList (1)" SHList.tcl } ##done {f "ScrolledHList (1)" SHList.tcl }
##done {f "ScrolledHList (2)" SHList2.tcl } ##done {f "ScrolledHList (2)" SHList2.tcl }
##done {f Tree Tree.tcl } ##done {f Tree Tree.tcl }
##done {f "Tree (Dynamic)" DynTree.tcl {v win}} ##done {f "Tree (Dynamic)" DynTree.tcl {v win}}
## } ## }
## ##
## set tlist { ## set tlist {
## {f "ScrolledTList (1)" STList1.tcl {c tixTList}} ## {f "ScrolledTList (1)" STList1.tcl {c tixTList}}
## {f "ScrolledTList (2)" STList2.tcl {c tixTList}} ## {f "ScrolledTList (2)" STList2.tcl {c tixTList}}
## } ## }
## global tcl_platform ## global tcl_platform
## # This demo hangs windows ## # This demo hangs windows
## if {$tcl_platform(platform) != "windows"} { ## if {$tcl_platform(platform) != "windows"} {
##na lappend tlist {f "TList File Viewer" STList3.tcl {c tixTList}} ##na lappend tlist {f "TList File Viewer" STList3.tcl {c tixTList}}
## } ## }
## ##
## set grid { ## set grid {
##na {f "Simple Grid" SGrid0.tcl {c tixGrid}} ##na {f "Simple Grid" SGrid0.tcl {c tixGrid}}
##na {f "ScrolledGrid" SGrid1.tcl {c tixGrid}} ##na {f "ScrolledGrid" SGrid1.tcl {c tixGrid}}
##na {f "Editable Grid" EditGrid.tcl {c tixGrid}} ##na {f "Editable Grid" EditGrid.tcl {c tixGrid}}
## } ## }
## ##
## set scroll { ## set scroll {
## {f ScrolledListBox SListBox.tcl } ## {f ScrolledListBox SListBox.tcl }
## {f ScrolledText SText.tcl } ## {f ScrolledText SText.tcl }
## {f ScrolledWindow SWindow.tcl } ## {f ScrolledWindow SWindow.tcl }
##na {f "Canvas Object View" CObjView.tcl {c tixCObjView}} ##na {f "Canvas Object View" CObjView.tcl {c tixCObjView}}
## } ## }
## ##
## set manager { ## set manager {
## {f ListNoteBook ListNBK.tcl } ## {f ListNoteBook ListNBK.tcl }
##done {f NoteBook NoteBook.tcl } ##done {f NoteBook NoteBook.tcl }
##done {f PanedWindow PanedWin.tcl } ##done {f PanedWindow PanedWin.tcl }
## } ## }
## ##
## set misc { ## set misc {
##done {f Balloon Balloon.tcl } ##done {f Balloon Balloon.tcl }
##done {f ButtonBox BtnBox.tcl } ##done {f ButtonBox BtnBox.tcl }
##done {f ComboBox ComboBox.tcl } ##done {f ComboBox ComboBox.tcl }
##done {f Control Control.tcl } ##done {f Control Control.tcl }
## {f LabelEntry LabEntry.tcl } ## {f LabelEntry LabEntry.tcl }
## {f LabelFrame LabFrame.tcl } ## {f LabelFrame LabFrame.tcl }
## {f Meter Meter.tcl {c tixMeter}} ## {f Meter Meter.tcl {c tixMeter}}
##done {f OptionMenu OptMenu.tcl } ##done {f OptionMenu OptMenu.tcl }
##done {f PopupMenu PopMenu.tcl } ##done {f PopupMenu PopMenu.tcl }
## {f Select Select.tcl } ## {f Select Select.tcl }
## {f StdButtonBox StdBBox.tcl } ## {f StdButtonBox StdBBox.tcl }
## } ## }
## ##
stypes = {} stypes = {}
stypes['widget'] = ['Balloon', 'Button Box', 'Combo Box', 'Control', stypes['widget'] = ['Balloon', 'Button Box', 'Combo Box', 'Control',
'Directory List', 'Directory Tree', 'Directory List', 'Directory Tree',
'Notebook', 'Option Menu', 'Popup Menu', 'Paned Window', 'Notebook', 'Option Menu', 'Popup Menu', 'Paned Window',
'ScrolledHList (1)', 'ScrolledHList (2)', 'Tree (dynamic)'] 'ScrolledHList (1)', 'ScrolledHList (2)', 'Tree (dynamic)']
stypes['image'] = ['Compound Image'] stypes['image'] = ['Compound Image']
def MkSample(nb, name): 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') 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']: for type in ['widget', 'image']:
if type != 'widget': if type != 'widget':
x = Tix.Frame(slb.hlist, bd=2, height=2, width=150, x = Tix.Frame(slb.hlist, bd=2, height=2, width=150,
relief=Tix.SUNKEN, bg=slb.hlist['bg']) relief=Tix.SUNKEN, bg=slb.hlist['bg'])
slb.hlist.add_child(itemtype=Tix.WINDOW, window=x, state='disabled') slb.hlist.add_child(itemtype=Tix.WINDOW, window=x, state='disabled')
x = slb.hlist.add_child(itemtype=Tix.TEXT, state='disabled', x = slb.hlist.add_child(itemtype=Tix.TEXT, state='disabled',
text=comments[type]) text=comments[type])
for key in stypes[type]: for key in stypes[type]:
slb.hlist.add_child(x, itemtype=Tix.TEXT, data=key, slb.hlist.add_child(x, itemtype=Tix.TEXT, data=key,
text=key) text=key)
slb.hlist.selection_clear() slb.hlist.selection_clear()
run['state'] = 'disabled' run['state'] = 'disabled'
@ -942,11 +942,11 @@ def Sample_Action(w, slb, stext, run, view, action):
hlist = slb.hlist hlist = slb.hlist
anchor = hlist.info_anchor() anchor = hlist.info_anchor()
if not anchor: if not anchor:
run['state'] = 'disabled' run['state'] = 'disabled'
view['state'] = 'disabled' view['state'] = 'disabled'
elif not hlist.info_parent(anchor): elif not hlist.info_parent(anchor):
# a comment # a comment
return return
run['state'] = 'normal' run['state'] = 'normal'
view['state'] = 'normal' view['state'] = 'normal'
@ -955,17 +955,17 @@ def Sample_Action(w, slb, stext, run, view, action):
prog = samples[key] prog = samples[key]
if action == 'run': if action == 'run':
exec('import ' + prog) exec('import ' + prog)
w = Tix.Toplevel() w = Tix.Toplevel()
w.title(title) w.title(title)
rtn = eval(prog + '.RunSample') rtn = eval(prog + '.RunSample')
rtn(w) rtn(w)
elif action == 'view': elif action == 'view':
w = Tix.Toplevel() w = Tix.Toplevel()
w.title('Source view: ' + title) w.title('Source view: ' + title)
LoadFile(w, demo.dir + '/samples/' + prog + '.py') LoadFile(w, demo.dir + '/samples/' + prog + '.py')
elif action == 'browse': elif action == 'browse':
ReadFile(stext.text, demo.dir + '/samples/' + prog + '.py') ReadFile(stext.text, demo.dir + '/samples/' + prog + '.py')
def LoadFile(w, fname): def LoadFile(w, fname):
global root global root
@ -989,16 +989,15 @@ def ReadFile(w, fname):
w.delete('0.0', Tix.END) w.delete('0.0', Tix.END)
try: try:
f = open(fname) f = open(fname)
lines = f.readlines() lines = f.readlines()
for s in lines: for s in lines:
w.insert(Tix.END, s) w.insert(Tix.END, s)
f.close() f.close()
finally: finally:
# w.see('1.0') # w.see('1.0')
w['state'] = old_state w['state'] = old_state
if __name__ == '__main__': if __name__ == '__main__':
root = Tix.Tk() root = Tix.Tk()
RunMain(root) RunMain(root)

View file

@ -16,437 +16,437 @@ from Tkinter import *
class Option: class Option:
varclass = StringVar # May be overridden varclass = StringVar # May be overridden
def __init__(self, dialog, option): def __init__(self, dialog, option):
self.dialog = dialog self.dialog = dialog
self.option = option self.option = option
self.master = dialog.top self.master = dialog.top
self.default, self.klass = dialog.options[option] self.default, self.klass = dialog.options[option]
self.var = self.varclass(self.master) self.var = self.varclass(self.master)
self.frame = Frame(self.master) self.frame = Frame(self.master)
self.frame.pack(fill=X) self.frame.pack(fill=X)
self.label = Label(self.frame, text=(option + ":")) self.label = Label(self.frame, text=(option + ":"))
self.label.pack(side=LEFT) self.label.pack(side=LEFT)
self.update() self.update()
self.addoption() self.addoption()
def refresh(self): def refresh(self):
self.dialog.refresh() self.dialog.refresh()
self.update() self.update()
def update(self): def update(self):
try: try:
self.current = self.dialog.current[self.option] self.current = self.dialog.current[self.option]
except KeyError: except KeyError:
self.current = self.default self.current = self.default
self.var.set(self.current) self.var.set(self.current)
def set(self, e=None): # Should be overridden def set(self, e=None): # Should be overridden
pass pass
class BooleanOption(Option): class BooleanOption(Option):
varclass = BooleanVar varclass = BooleanVar
def addoption(self): def addoption(self):
self.button = Checkbutton(self.frame, self.button = Checkbutton(self.frame,
text='on/off', text='on/off',
onvalue=1, onvalue=1,
offvalue=0, offvalue=0,
variable=self.var, variable=self.var,
relief=RAISED, relief=RAISED,
borderwidth=2, borderwidth=2,
command=self.set) command=self.set)
self.button.pack(side=RIGHT) self.button.pack(side=RIGHT)
class EnumOption(Option): class EnumOption(Option):
def addoption(self): def addoption(self):
self.button = Menubutton(self.frame, self.button = Menubutton(self.frame,
textvariable=self.var, textvariable=self.var,
relief=RAISED, borderwidth=2) relief=RAISED, borderwidth=2)
self.button.pack(side=RIGHT) self.button.pack(side=RIGHT)
self.menu = Menu(self.button) self.menu = Menu(self.button)
self.button['menu'] = self.menu self.button['menu'] = self.menu
for v in self.dialog.classes[self.klass]: for v in self.dialog.classes[self.klass]:
self.menu.add_radiobutton( self.menu.add_radiobutton(
label=v, label=v,
variable=self.var, variable=self.var,
value=v, value=v,
command=self.set) command=self.set)
class StringOption(Option): class StringOption(Option):
def addoption(self): def addoption(self):
self.entry = Entry(self.frame, self.entry = Entry(self.frame,
textvariable=self.var, textvariable=self.var,
width=10, width=10,
relief=SUNKEN, relief=SUNKEN,
borderwidth=2) borderwidth=2)
self.entry.pack(side=RIGHT, fill=X, expand=1) self.entry.pack(side=RIGHT, fill=X, expand=1)
self.entry.bind('<Return>', self.set) self.entry.bind('<Return>', self.set)
class ReadonlyOption(Option): class ReadonlyOption(Option):
def addoption(self): def addoption(self):
self.label = Label(self.frame, textvariable=self.var, self.label = Label(self.frame, textvariable=self.var,
anchor=E) anchor=E)
self.label.pack(side=RIGHT) self.label.pack(side=RIGHT)
class Dialog: class Dialog:
def __init__(self, master): def __init__(self, master):
self.master = master self.master = master
self.fixclasses() self.fixclasses()
self.refresh() self.refresh()
self.top = Toplevel(self.master) self.top = Toplevel(self.master)
self.top.title(self.__class__.__name__) self.top.title(self.__class__.__name__)
self.top.minsize(1, 1) self.top.minsize(1, 1)
self.addchoices() self.addchoices()
def refresh(self): pass # Must override def refresh(self): pass # Must override
def fixclasses(self): pass # May override def fixclasses(self): pass # May override
def addchoices(self): def addchoices(self):
self.choices = {} self.choices = {}
list = [] list = []
for k, dc in self.options.items(): for k, dc in self.options.items():
list.append((k, dc)) list.append((k, dc))
list.sort() list.sort()
for k, (d, c) in list: for k, (d, c) in list:
try: try:
cl = self.classes[c] cl = self.classes[c]
except KeyError: except KeyError:
cl = 'unknown' cl = 'unknown'
if type(cl) == TupleType: if type(cl) == TupleType:
cl = self.enumoption cl = self.enumoption
elif cl == 'boolean': elif cl == 'boolean':
cl = self.booleanoption cl = self.booleanoption
elif cl == 'readonly': elif cl == 'readonly':
cl = self.readonlyoption cl = self.readonlyoption
else: else:
cl = self.stringoption cl = self.stringoption
self.choices[k] = cl(self, k) self.choices[k] = cl(self, k)
# Must override: # Must override:
options = {} options = {}
classes = {} classes = {}
# May override: # May override:
booleanoption = BooleanOption booleanoption = BooleanOption
stringoption = StringOption stringoption = StringOption
enumoption = EnumOption enumoption = EnumOption
readonlyoption = ReadonlyOption readonlyoption = ReadonlyOption
class PackDialog(Dialog): class PackDialog(Dialog):
def __init__(self, widget): def __init__(self, widget):
self.widget = widget self.widget = widget
Dialog.__init__(self, widget) Dialog.__init__(self, widget)
def refresh(self): def refresh(self):
self.current = self.widget.info() self.current = self.widget.info()
self.current['.class'] = self.widget.winfo_class() self.current['.class'] = self.widget.winfo_class()
self.current['.name'] = self.widget._w self.current['.name'] = self.widget._w
class packoption: # Mix-in class class packoption: # Mix-in class
def set(self, e=None): def set(self, e=None):
self.current = self.var.get() self.current = self.var.get()
try: try:
apply(self.dialog.widget.pack, (), apply(self.dialog.widget.pack, (),
{self.option: self.current}) {self.option: self.current})
except TclError, msg: except TclError, msg:
print msg print msg
self.refresh() self.refresh()
class booleanoption(packoption, BooleanOption): pass class booleanoption(packoption, BooleanOption): pass
class enumoption(packoption, EnumOption): pass class enumoption(packoption, EnumOption): pass
class stringoption(packoption, StringOption): pass class stringoption(packoption, StringOption): pass
class readonlyoption(packoption, ReadonlyOption): pass class readonlyoption(packoption, ReadonlyOption): pass
options = { options = {
'.class': (None, 'Class'), '.class': (None, 'Class'),
'.name': (None, 'Name'), '.name': (None, 'Name'),
'after': (None, 'Widget'), 'after': (None, 'Widget'),
'anchor': ('center', 'Anchor'), 'anchor': ('center', 'Anchor'),
'before': (None, 'Widget'), 'before': (None, 'Widget'),
'expand': ('no', 'Boolean'), 'expand': ('no', 'Boolean'),
'fill': ('none', 'Fill'), 'fill': ('none', 'Fill'),
'in': (None, 'Widget'), 'in': (None, 'Widget'),
'ipadx': (0, 'Pad'), 'ipadx': (0, 'Pad'),
'ipady': (0, 'Pad'), 'ipady': (0, 'Pad'),
'padx': (0, 'Pad'), 'padx': (0, 'Pad'),
'pady': (0, 'Pad'), 'pady': (0, 'Pad'),
'side': ('top', 'Side'), 'side': ('top', 'Side'),
} }
classes = { classes = {
'Anchor': (N, NE, E, SE, S, SW, W, NW, CENTER), 'Anchor': (N, NE, E, SE, S, SW, W, NW, CENTER),
'Boolean': 'boolean', 'Boolean': 'boolean',
'Class': 'readonly', 'Class': 'readonly',
'Expand': 'boolean', 'Expand': 'boolean',
'Fill': (NONE, X, Y, BOTH), 'Fill': (NONE, X, Y, BOTH),
'Name': 'readonly', 'Name': 'readonly',
'Pad': 'pixel', 'Pad': 'pixel',
'Side': (TOP, RIGHT, BOTTOM, LEFT), 'Side': (TOP, RIGHT, BOTTOM, LEFT),
'Widget': 'readonly', 'Widget': 'readonly',
} }
class RemotePackDialog(PackDialog): class RemotePackDialog(PackDialog):
def __init__(self, master, app, widget): def __init__(self, master, app, widget):
self.master = master self.master = master
self.app = app self.app = app
self.widget = widget self.widget = widget
self.refresh() self.refresh()
self.top = Toplevel(self.master) self.top = Toplevel(self.master)
self.top.title(self.app + ' PackDialog') self.top.title(self.app + ' PackDialog')
self.top.minsize(1, 1) self.top.minsize(1, 1)
self.addchoices() self.addchoices()
def refresh(self): def refresh(self):
try: try:
words = self.master.tk.splitlist( words = self.master.tk.splitlist(
self.master.send(self.app, self.master.send(self.app,
'pack', 'pack',
'info', 'info',
self.widget)) self.widget))
except TclError, msg: except TclError, msg:
print msg print msg
return return
dict = {} dict = {}
for i in range(0, len(words), 2): for i in range(0, len(words), 2):
key = words[i][1:] key = words[i][1:]
value = words[i+1] value = words[i+1]
dict[key] = value dict[key] = value
dict['.class'] = self.master.send(self.app, dict['.class'] = self.master.send(self.app,
'winfo', 'winfo',
'class', 'class',
self.widget) self.widget)
dict['.name'] = self.widget dict['.name'] = self.widget
self.current = dict self.current = dict
class remotepackoption: # Mix-in class class remotepackoption: # Mix-in class
def set(self, e=None): def set(self, e=None):
self.current = self.var.get() self.current = self.var.get()
try: try:
self.dialog.master.send( self.dialog.master.send(
self.dialog.app, self.dialog.app,
'pack', 'pack',
'config', 'config',
self.dialog.widget, self.dialog.widget,
'-'+self.option, '-'+self.option,
self.dialog.master.tk.merge( self.dialog.master.tk.merge(
self.current)) self.current))
except TclError, msg: except TclError, msg:
print msg print msg
self.refresh() self.refresh()
class booleanoption(remotepackoption, BooleanOption): pass class booleanoption(remotepackoption, BooleanOption): pass
class enumoption(remotepackoption, EnumOption): pass class enumoption(remotepackoption, EnumOption): pass
class stringoption(remotepackoption, StringOption): pass class stringoption(remotepackoption, StringOption): pass
class readonlyoption(remotepackoption, ReadonlyOption): pass class readonlyoption(remotepackoption, ReadonlyOption): pass
class WidgetDialog(Dialog): class WidgetDialog(Dialog):
def __init__(self, widget): def __init__(self, widget):
self.widget = widget self.widget = widget
self.klass = widget.winfo_class() self.klass = widget.winfo_class()
Dialog.__init__(self, widget) Dialog.__init__(self, widget)
def fixclasses(self): def fixclasses(self):
if self.addclasses.has_key(self.klass): if self.addclasses.has_key(self.klass):
classes = {} classes = {}
for c in (self.classes, for c in (self.classes,
self.addclasses[self.klass]): self.addclasses[self.klass]):
for k in c.keys(): for k in c.keys():
classes[k] = c[k] classes[k] = c[k]
self.classes = classes self.classes = classes
def refresh(self): def refresh(self):
self.configuration = self.widget.config() self.configuration = self.widget.config()
self.update() self.update()
self.current['.class'] = self.widget.winfo_class() self.current['.class'] = self.widget.winfo_class()
self.current['.name'] = self.widget._w self.current['.name'] = self.widget._w
def update(self): def update(self):
self.current = {} self.current = {}
self.options = {} self.options = {}
for k, v in self.configuration.items(): for k, v in self.configuration.items():
if len(v) > 4: if len(v) > 4:
self.current[k] = v[4] self.current[k] = v[4]
self.options[k] = v[3], v[2] # default, klass self.options[k] = v[3], v[2] # default, klass
self.options['.class'] = (None, 'Class') self.options['.class'] = (None, 'Class')
self.options['.name'] = (None, 'Name') self.options['.name'] = (None, 'Name')
class widgetoption: # Mix-in class class widgetoption: # Mix-in class
def set(self, e=None): def set(self, e=None):
self.current = self.var.get() self.current = self.var.get()
try: try:
self.dialog.widget[self.option] = self.current self.dialog.widget[self.option] = self.current
except TclError, msg: except TclError, msg:
print msg print msg
self.refresh() self.refresh()
class booleanoption(widgetoption, BooleanOption): pass class booleanoption(widgetoption, BooleanOption): pass
class enumoption(widgetoption, EnumOption): pass class enumoption(widgetoption, EnumOption): pass
class stringoption(widgetoption, StringOption): pass class stringoption(widgetoption, StringOption): pass
class readonlyoption(widgetoption, ReadonlyOption): pass class readonlyoption(widgetoption, ReadonlyOption): pass
# Universal classes # Universal classes
classes = { classes = {
'Anchor': (N, NE, E, SE, S, SW, W, NW, CENTER), 'Anchor': (N, NE, E, SE, S, SW, W, NW, CENTER),
'Aspect': 'integer', 'Aspect': 'integer',
'Background': 'color', 'Background': 'color',
'Bitmap': 'bitmap', 'Bitmap': 'bitmap',
'BorderWidth': 'pixel', 'BorderWidth': 'pixel',
'Class': 'readonly', 'Class': 'readonly',
'CloseEnough': 'double', 'CloseEnough': 'double',
'Command': 'command', 'Command': 'command',
'Confine': 'boolean', 'Confine': 'boolean',
'Cursor': 'cursor', 'Cursor': 'cursor',
'CursorWidth': 'pixel', 'CursorWidth': 'pixel',
'DisabledForeground': 'color', 'DisabledForeground': 'color',
'ExportSelection': 'boolean', 'ExportSelection': 'boolean',
'Font': 'font', 'Font': 'font',
'Foreground': 'color', 'Foreground': 'color',
'From': 'integer', 'From': 'integer',
'Geometry': 'geometry', 'Geometry': 'geometry',
'Height': 'pixel', 'Height': 'pixel',
'InsertWidth': 'time', 'InsertWidth': 'time',
'Justify': (LEFT, CENTER, RIGHT), 'Justify': (LEFT, CENTER, RIGHT),
'Label': 'string', 'Label': 'string',
'Length': 'pixel', 'Length': 'pixel',
'MenuName': 'widget', 'MenuName': 'widget',
'Name': 'readonly', 'Name': 'readonly',
'OffTime': 'time', 'OffTime': 'time',
'OnTime': 'time', 'OnTime': 'time',
'Orient': (HORIZONTAL, VERTICAL), 'Orient': (HORIZONTAL, VERTICAL),
'Pad': 'pixel', 'Pad': 'pixel',
'Relief': (RAISED, SUNKEN, FLAT, RIDGE, GROOVE), 'Relief': (RAISED, SUNKEN, FLAT, RIDGE, GROOVE),
'RepeatDelay': 'time', 'RepeatDelay': 'time',
'RepeatInterval': 'time', 'RepeatInterval': 'time',
'ScrollCommand': 'command', 'ScrollCommand': 'command',
'ScrollIncrement': 'pixel', 'ScrollIncrement': 'pixel',
'ScrollRegion': 'rectangle', 'ScrollRegion': 'rectangle',
'ShowValue': 'boolean', 'ShowValue': 'boolean',
'SetGrid': 'boolean', 'SetGrid': 'boolean',
'Sliderforeground': 'color', 'Sliderforeground': 'color',
'SliderLength': 'pixel', 'SliderLength': 'pixel',
'Text': 'string', 'Text': 'string',
'TickInterval': 'integer', 'TickInterval': 'integer',
'To': 'integer', 'To': 'integer',
'Underline': 'index', 'Underline': 'index',
'Variable': 'variable', 'Variable': 'variable',
'Value': 'string', 'Value': 'string',
'Width': 'pixel', 'Width': 'pixel',
'Wrap': (NONE, CHAR, WORD), 'Wrap': (NONE, CHAR, WORD),
} }
# Classes that (may) differ per widget type # Classes that (may) differ per widget type
_tristate = {'State': (NORMAL, ACTIVE, DISABLED)} _tristate = {'State': (NORMAL, ACTIVE, DISABLED)}
_bistate = {'State': (NORMAL, DISABLED)} _bistate = {'State': (NORMAL, DISABLED)}
addclasses = { addclasses = {
'Button': _tristate, 'Button': _tristate,
'Radiobutton': _tristate, 'Radiobutton': _tristate,
'Checkbutton': _tristate, 'Checkbutton': _tristate,
'Entry': _bistate, 'Entry': _bistate,
'Text': _bistate, 'Text': _bistate,
'Menubutton': _tristate, 'Menubutton': _tristate,
'Slider': _bistate, 'Slider': _bistate,
} }
class RemoteWidgetDialog(WidgetDialog): class RemoteWidgetDialog(WidgetDialog):
def __init__(self, master, app, widget): def __init__(self, master, app, widget):
self.app = app self.app = app
self.widget = widget self.widget = widget
self.klass = master.send(self.app, self.klass = master.send(self.app,
'winfo', 'winfo',
'class', 'class',
self.widget) self.widget)
Dialog.__init__(self, master) Dialog.__init__(self, master)
def refresh(self): def refresh(self):
try: try:
items = self.master.tk.splitlist( items = self.master.tk.splitlist(
self.master.send(self.app, self.master.send(self.app,
self.widget, self.widget,
'config')) 'config'))
except TclError, msg: except TclError, msg:
print msg print msg
return return
dict = {} dict = {}
for item in items: for item in items:
words = self.master.tk.splitlist(item) words = self.master.tk.splitlist(item)
key = words[0][1:] key = words[0][1:]
value = (key,) + words[1:] value = (key,) + words[1:]
dict[key] = value dict[key] = value
self.configuration = dict self.configuration = dict
self.update() self.update()
self.current['.class'] = self.klass self.current['.class'] = self.klass
self.current['.name'] = self.widget self.current['.name'] = self.widget
class remotewidgetoption: # Mix-in class class remotewidgetoption: # Mix-in class
def set(self, e=None): def set(self, e=None):
self.current = self.var.get() self.current = self.var.get()
try: try:
self.dialog.master.send( self.dialog.master.send(
self.dialog.app, self.dialog.app,
self.dialog.widget, self.dialog.widget,
'config', 'config',
'-'+self.option, '-'+self.option,
self.current) self.current)
except TclError, msg: except TclError, msg:
print msg print msg
self.refresh() self.refresh()
class booleanoption(remotewidgetoption, BooleanOption): pass class booleanoption(remotewidgetoption, BooleanOption): pass
class enumoption(remotewidgetoption, EnumOption): pass class enumoption(remotewidgetoption, EnumOption): pass
class stringoption(remotewidgetoption, StringOption): pass class stringoption(remotewidgetoption, StringOption): pass
class readonlyoption(remotewidgetoption, ReadonlyOption): pass class readonlyoption(remotewidgetoption, ReadonlyOption): pass
def test(): def test():
import sys import sys
root = Tk() root = Tk()
root.minsize(1, 1) root.minsize(1, 1)
if sys.argv[1:]: if sys.argv[1:]:
remotetest(root, sys.argv[1]) remotetest(root, sys.argv[1])
else: else:
frame = Frame(root, name='frame') frame = Frame(root, name='frame')
frame.pack(expand=1, fill=BOTH) frame.pack(expand=1, fill=BOTH)
button = Button(frame, name='button', text='button') button = Button(frame, name='button', text='button')
button.pack(expand=1) button.pack(expand=1)
canvas = Canvas(frame, name='canvas') canvas = Canvas(frame, name='canvas')
canvas.pack() canvas.pack()
fpd = PackDialog(frame) fpd = PackDialog(frame)
fwd = WidgetDialog(frame) fwd = WidgetDialog(frame)
bpd = PackDialog(button) bpd = PackDialog(button)
bwd = WidgetDialog(button) bwd = WidgetDialog(button)
cpd = PackDialog(canvas) cpd = PackDialog(canvas)
cwd = WidgetDialog(canvas) cwd = WidgetDialog(canvas)
root.mainloop() root.mainloop()
def remotetest(root, app): def remotetest(root, app):
from listtree import listtree from listtree import listtree
list = listtree(root, app) list = listtree(root, app)
list.bind('<Any-Double-1>', opendialogs) list.bind('<Any-Double-1>', opendialogs)
list.app = app # Pass it on to handler list.app = app # Pass it on to handler
def opendialogs(e): def opendialogs(e):
import string import string
list = e.widget list = e.widget
sel = list.curselection() sel = list.curselection()
for i in sel: for i in sel:
item = list.get(i) item = list.get(i)
widget = string.split(item)[0] widget = string.split(item)[0]
RemoteWidgetDialog(list, list.app, widget) RemoteWidgetDialog(list, list.app, widget)
if widget == '.': continue if widget == '.': continue
try: try:
RemotePackDialog(list, list.app, widget) RemotePackDialog(list, list.app, widget)
except TclError, msg: except TclError, msg:
print msg print msg
test() test()

View file

@ -12,173 +12,173 @@ ITALICFONT = '*-Courier-Medium-O-Normal-*-120-*'
# XXX Recognizing footers is system dependent # XXX Recognizing footers is system dependent
# (This one works for IRIX 5.2 and Solaris 2.2) # (This one works for IRIX 5.2 and Solaris 2.2)
footerprog = regex.compile( 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') emptyprog = regex.compile('^[ \t]*\n')
ulprog = regex.compile('^[ \t]*[Xv!_][Xv!_ \t]*\n') ulprog = regex.compile('^[ \t]*[Xv!_][Xv!_ \t]*\n')
# Basic Man Page class -- does not disable editing # Basic Man Page class -- does not disable editing
class EditableManPage(ScrolledText): class EditableManPage(ScrolledText):
# Initialize instance # Initialize instance
def __init__(self, master=None, **cnf): def __init__(self, master=None, **cnf):
# Initialize base class # Initialize base class
apply(ScrolledText.__init__, (self, master), cnf) apply(ScrolledText.__init__, (self, master), cnf)
# Define tags for formatting styles # Define tags for formatting styles
self.tag_config('X', underline=1) self.tag_config('X', underline=1)
self.tag_config('!', font=BOLDFONT) self.tag_config('!', font=BOLDFONT)
self.tag_config('_', font=ITALICFONT) self.tag_config('_', font=ITALICFONT)
# Set state to idle # Set state to idle
self.fp = None self.fp = None
self.lineno = 0 self.lineno = 0
# Test whether we are busy parsing a file # Test whether we are busy parsing a file
def busy(self): def busy(self):
return self.fp != None return self.fp != None
# Ensure we're not busy # Ensure we're not busy
def kill(self): def kill(self):
if self.busy(): if self.busy():
self._endparser() self._endparser()
# Parse a file, in the background # Parse a file, in the background
def asyncparsefile(self, fp): def asyncparsefile(self, fp):
self._startparser(fp) self._startparser(fp)
self.tk.createfilehandler(fp, _tkinter.READABLE, self.tk.createfilehandler(fp, _tkinter.READABLE,
self._filehandler) self._filehandler)
parsefile = asyncparsefile # Alias parsefile = asyncparsefile # Alias
# I/O handler used by background parsing # I/O handler used by background parsing
def _filehandler(self, fp, mask): def _filehandler(self, fp, mask):
nextline = self.fp.readline() nextline = self.fp.readline()
if not nextline: if not nextline:
self._endparser() self._endparser()
return return
self._parseline(nextline) self._parseline(nextline)
# Parse a file, now (cannot be aborted) # Parse a file, now (cannot be aborted)
def syncparsefile(self, fp): def syncparsefile(self, fp):
from select import select from select import select
def avail(fp=fp, tout=0.0, select=select): def avail(fp=fp, tout=0.0, select=select):
return select([fp], [], [], tout)[0] return select([fp], [], [], tout)[0]
height = self.getint(self['height']) height = self.getint(self['height'])
self._startparser(fp) self._startparser(fp)
while 1: while 1:
nextline = fp.readline() nextline = fp.readline()
if not nextline: if not nextline:
break break
self._parseline(nextline) self._parseline(nextline)
self._endparser() self._endparser()
# Initialize parsing from a particular file -- must not be busy # Initialize parsing from a particular file -- must not be busy
def _startparser(self, fp): def _startparser(self, fp):
if self.busy(): if self.busy():
raise RuntimeError, 'startparser: still busy' raise RuntimeError, 'startparser: still busy'
fp.fileno() # Test for file-ness fp.fileno() # Test for file-ness
self.fp = fp self.fp = fp
self.lineno = 0 self.lineno = 0
self.ok = 0 self.ok = 0
self.empty = 0 self.empty = 0
self.buffer = None self.buffer = None
savestate = self['state'] savestate = self['state']
self['state'] = NORMAL self['state'] = NORMAL
self.delete('1.0', END) self.delete('1.0', END)
self['state'] = savestate self['state'] = savestate
# End parsing -- must be busy, need not be at EOF # End parsing -- must be busy, need not be at EOF
def _endparser(self): def _endparser(self):
if not self.busy(): if not self.busy():
raise RuntimeError, 'endparser: not busy' raise RuntimeError, 'endparser: not busy'
if self.buffer: if self.buffer:
self._parseline('') self._parseline('')
try: try:
self.tk.deletefilehandler(self.fp) self.tk.deletefilehandler(self.fp)
except TclError, msg: except TclError, msg:
pass pass
self.fp.close() self.fp.close()
self.fp = None self.fp = None
del self.ok, self.empty, self.buffer del self.ok, self.empty, self.buffer
# Parse a single line # Parse a single line
def _parseline(self, nextline): def _parseline(self, nextline):
if not self.buffer: if not self.buffer:
# Save this line -- we need one line read-ahead # Save this line -- we need one line read-ahead
self.buffer = nextline self.buffer = nextline
return return
if emptyprog.match(self.buffer) >= 0: if emptyprog.match(self.buffer) >= 0:
# Buffered line was empty -- set a flag # Buffered line was empty -- set a flag
self.empty = 1 self.empty = 1
self.buffer = nextline self.buffer = nextline
return return
textline = self.buffer textline = self.buffer
if ulprog.match(nextline) >= 0: if ulprog.match(nextline) >= 0:
# Next line is properties for buffered line # Next line is properties for buffered line
propline = nextline propline = nextline
self.buffer = None self.buffer = None
else: else:
# Next line is read-ahead # Next line is read-ahead
propline = None propline = None
self.buffer = nextline self.buffer = nextline
if not self.ok: if not self.ok:
# First non blank line after footer must be header # First non blank line after footer must be header
# -- skip that too # -- skip that too
self.ok = 1 self.ok = 1
self.empty = 0 self.empty = 0
return return
if footerprog.match(textline) >= 0: if footerprog.match(textline) >= 0:
# Footer -- start skipping until next non-blank line # Footer -- start skipping until next non-blank line
self.ok = 0 self.ok = 0
self.empty = 0 self.empty = 0
return return
savestate = self['state'] savestate = self['state']
self['state'] = NORMAL self['state'] = NORMAL
if TkVersion >= 4.0: if TkVersion >= 4.0:
self.mark_set('insert', 'end-1c') self.mark_set('insert', 'end-1c')
else: else:
self.mark_set('insert', END) self.mark_set('insert', END)
if self.empty: if self.empty:
# One or more previous lines were empty # One or more previous lines were empty
# -- insert one blank line in the text # -- insert one blank line in the text
self._insert_prop('\n') self._insert_prop('\n')
self.lineno = self.lineno + 1 self.lineno = self.lineno + 1
self.empty = 0 self.empty = 0
if not propline: if not propline:
# No properties # No properties
self._insert_prop(textline) self._insert_prop(textline)
else: else:
# Search for properties # Search for properties
p = '' p = ''
j = 0 j = 0
for i in range(min(len(propline), len(textline))): for i in range(min(len(propline), len(textline))):
if propline[i] != p: if propline[i] != p:
if j < i: if j < i:
self._insert_prop(textline[j:i], p) self._insert_prop(textline[j:i], p)
j = i j = i
p = propline[i] p = propline[i]
self._insert_prop(textline[j:]) self._insert_prop(textline[j:])
self.lineno = self.lineno + 1 self.lineno = self.lineno + 1
self['state'] = savestate self['state'] = savestate
# Insert a string at the end, with at most one property (tag) # Insert a string at the end, with at most one property (tag)
def _insert_prop(self, str, prop = ' '): def _insert_prop(self, str, prop = ' '):
here = self.index(AtInsert()) here = self.index(AtInsert())
self.insert(AtInsert(), str) self.insert(AtInsert(), str)
if TkVersion <= 4.0: if TkVersion <= 4.0:
tags = self.tag_names(here) tags = self.tag_names(here)
for tag in tags: for tag in tags:
self.tag_remove(tag, here, AtInsert()) self.tag_remove(tag, here, AtInsert())
if prop != ' ': if prop != ' ':
self.tag_add(prop, here, AtInsert()) self.tag_add(prop, here, AtInsert())
# Readonly Man Page class -- disables editing, otherwise the same # Readonly Man Page class -- disables editing, otherwise the same
class ReadonlyManPage(EditableManPage): class ReadonlyManPage(EditableManPage):
# Initialize instance # Initialize instance
def __init__(self, master=None, **cnf): def __init__(self, master=None, **cnf):
cnf['state'] = DISABLED cnf['state'] = DISABLED
apply(EditableManPage.__init__, (self, master), cnf) apply(EditableManPage.__init__, (self, master), cnf)
# Alias # Alias
ManPage = ReadonlyManPage ManPage = ReadonlyManPage
@ -187,34 +187,34 @@ ManPage = ReadonlyManPage
# usage: ManPage [manpage]; or ManPage [-f] file # usage: ManPage [manpage]; or ManPage [-f] file
# -f means that the file is nroff -man output run through ul -i # -f means that the file is nroff -man output run through ul -i
def test(): def test():
import os import os
import sys import sys
# XXX This directory may be different on your system # XXX This directory may be different on your system
MANDIR = '/usr/local/man/mann' MANDIR = '/usr/local/man/mann'
DEFAULTPAGE = 'Tcl' DEFAULTPAGE = 'Tcl'
formatted = 0 formatted = 0
if sys.argv[1:] and sys.argv[1] == '-f': if sys.argv[1:] and sys.argv[1] == '-f':
formatted = 1 formatted = 1
del sys.argv[1] del sys.argv[1]
if sys.argv[1:]: if sys.argv[1:]:
name = sys.argv[1] name = sys.argv[1]
else: else:
name = DEFAULTPAGE name = DEFAULTPAGE
if not formatted: if not formatted:
if name[-2:-1] != '.': if name[-2:-1] != '.':
name = name + '.n' name = name + '.n'
name = os.path.join(MANDIR, name) name = os.path.join(MANDIR, name)
root = Tk() root = Tk()
root.minsize(1, 1) root.minsize(1, 1)
manpage = ManPage(root, relief=SUNKEN, borderwidth=2) manpage = ManPage(root, relief=SUNKEN, borderwidth=2)
manpage.pack(expand=1, fill=BOTH) manpage.pack(expand=1, fill=BOTH)
if formatted: if formatted:
fp = open(name, 'r') fp = open(name, 'r')
else: else:
fp = os.popen('nroff -man %s | ul -i' % name, 'r') fp = os.popen('nroff -man %s | ul -i' % name, 'r')
manpage.parsefile(fp) manpage.parsefile(fp)
root.mainloop() root.mainloop()
# Run the test program when called as a script # Run the test program when called as a script
if __name__ == '__main__': if __name__ == '__main__':
test() test()

View file

@ -9,135 +9,135 @@ from Tkinter import *
from ScrolledText import ScrolledText from ScrolledText import ScrolledText
class MimeViewer: class MimeViewer:
def __init__(self, parent, title, msg): def __init__(self, parent, title, msg):
self.title = title self.title = title
self.msg = msg self.msg = msg
self.frame = Frame(parent, {'relief': 'raised', 'bd': 2}) self.frame = Frame(parent, {'relief': 'raised', 'bd': 2})
self.frame.packing = {'expand': 0, 'fill': 'both'} self.frame.packing = {'expand': 0, 'fill': 'both'}
self.button = Checkbutton(self.frame, self.button = Checkbutton(self.frame,
{'text': title, {'text': title,
'command': self.toggle}) 'command': self.toggle})
self.button.pack({'anchor': 'w'}) self.button.pack({'anchor': 'w'})
headertext = msg.getheadertext( headertext = msg.getheadertext(
lambda x: x != 'received' and x[:5] != 'x400-') lambda x: x != 'received' and x[:5] != 'x400-')
height = countlines(headertext, 4) height = countlines(headertext, 4)
if height: if height:
self.htext = ScrolledText(self.frame, self.htext = ScrolledText(self.frame,
{'height': height, {'height': height,
'width': 80, 'width': 80,
'wrap': 'none', 'wrap': 'none',
'relief': 'raised', 'relief': 'raised',
'bd': 2}) 'bd': 2})
self.htext.packing = {'expand': 1, 'fill': 'both', self.htext.packing = {'expand': 1, 'fill': 'both',
'after': self.button} 'after': self.button}
self.htext.insert('end', headertext) self.htext.insert('end', headertext)
else: else:
self.htext = Frame(self.frame, self.htext = Frame(self.frame,
{'relief': 'raised', 'bd': 2}) {'relief': 'raised', 'bd': 2})
self.htext.packing = {'side': 'top', self.htext.packing = {'side': 'top',
'ipady': 2, 'ipady': 2,
'fill': 'x', 'fill': 'x',
'after': self.button} 'after': self.button}
body = msg.getbody() body = msg.getbody()
if type(body) == StringType: if type(body) == StringType:
self.pad = None self.pad = None
height = countlines(body, 10) height = countlines(body, 10)
if height: if height:
self.btext = ScrolledText(self.frame, self.btext = ScrolledText(self.frame,
{'height': height, {'height': height,
'width': 80, 'width': 80,
'wrap': 'none', 'wrap': 'none',
'relief': 'raised', 'relief': 'raised',
'bd': 2}) 'bd': 2})
self.btext.packing = {'expand': 1, self.btext.packing = {'expand': 1,
'fill': 'both'} 'fill': 'both'}
self.btext.insert('end', body) self.btext.insert('end', body)
else: else:
self.btext = None self.btext = None
self.parts = None self.parts = None
else: else:
self.pad = Frame(self.frame, self.pad = Frame(self.frame,
{'relief': 'flat', 'bd': 2}) {'relief': 'flat', 'bd': 2})
self.pad.packing = {'side': 'left', 'ipadx': 10, self.pad.packing = {'side': 'left', 'ipadx': 10,
'fill': 'y', 'after': self.htext} 'fill': 'y', 'after': self.htext}
self.parts = [] self.parts = []
for i in range(len(body)): for i in range(len(body)):
p = MimeViewer(self.frame, p = MimeViewer(self.frame,
'%s.%d' % (title, i+1), '%s.%d' % (title, i+1),
body[i]) body[i])
self.parts.append(p) self.parts.append(p)
self.btext = None self.btext = None
self.collapsed = 1 self.collapsed = 1
def pack(self): def pack(self):
self.frame.pack(self.frame.packing) self.frame.pack(self.frame.packing)
def destroy(self): def destroy(self):
self.frame.destroy() self.frame.destroy()
def show(self): def show(self):
if self.collapsed: if self.collapsed:
self.button.invoke() self.button.invoke()
def toggle(self): def toggle(self):
if self.collapsed: if self.collapsed:
self.explode() self.explode()
else: else:
self.collapse() self.collapse()
def collapse(self): def collapse(self):
self.collapsed = 1 self.collapsed = 1
for comp in self.htext, self.btext, self.pad: for comp in self.htext, self.btext, self.pad:
if comp: if comp:
comp.forget() comp.forget()
if self.parts: if self.parts:
for part in self.parts: for part in self.parts:
part.frame.forget() part.frame.forget()
self.frame.pack({'expand': 0}) self.frame.pack({'expand': 0})
def explode(self): def explode(self):
self.collapsed = 0 self.collapsed = 0
for comp in self.htext, self.btext, self.pad: for comp in self.htext, self.btext, self.pad:
if comp: comp.pack(comp.packing) if comp: comp.pack(comp.packing)
if self.parts: if self.parts:
for part in self.parts: for part in self.parts:
part.pack() part.pack()
self.frame.pack({'expand': 1}) self.frame.pack({'expand': 1})
def countlines(str, limit): def countlines(str, limit):
i = 0 i = 0
n = 0 n = 0
while n < limit: while n < limit:
i = string.find(str, '\n', i) i = string.find(str, '\n', i)
if i < 0: break if i < 0: break
n = n+1 n = n+1
i = i+1 i = i+1
return n return n
def main(): def main():
import sys import sys
import getopt import getopt
import mhlib import mhlib
opts, args = getopt.getopt(sys.argv[1:], '') opts, args = getopt.getopt(sys.argv[1:], '')
for o, a in opts: for o, a in opts:
pass pass
message = None message = None
folder = 'inbox' folder = 'inbox'
for arg in args: for arg in args:
if arg[:1] == '+': if arg[:1] == '+':
folder = arg[1:] folder = arg[1:]
else: else:
message = string.atoi(arg) message = string.atoi(arg)
mh = mhlib.MH() mh = mhlib.MH()
f = mh.openfolder(folder) f = mh.openfolder(folder)
if not message: if not message:
message = f.getcurrent() message = f.getcurrent()
m = f.openmessage(message) m = f.openmessage(message)
root = Tk() root = Tk()
tk = root.tk tk = root.tk
top = MimeViewer(root, '+%s/%d' % (folder, message), m) top = MimeViewer(root, '+%s/%d' % (folder, message), m)
top.pack() top.pack()
top.show() top.show()
root.minsize(1, 1) root.minsize(1, 1)
tk.mainloop() tk.mainloop()
if __name__ == '__main__': main() if __name__ == '__main__': main()

View file

@ -10,142 +10,142 @@ BUFSIZE = 512
class ShellWindow(ScrolledText): class ShellWindow(ScrolledText):
def __init__(self, master=None, shell=None, **cnf): def __init__(self, master=None, shell=None, **cnf):
if not shell: if not shell:
try: try:
shell = os.environ['SHELL'] shell = os.environ['SHELL']
except KeyError: except KeyError:
shell = '/bin/sh' shell = '/bin/sh'
shell = shell + ' -i' shell = shell + ' -i'
args = string.split(shell) args = string.split(shell)
shell = args[0] shell = args[0]
apply(ScrolledText.__init__, (self, master), cnf) apply(ScrolledText.__init__, (self, master), cnf)
self.pos = '1.0' self.pos = '1.0'
self.bind('<Return>', self.inputhandler) self.bind('<Return>', self.inputhandler)
self.bind('<Control-c>', self.sigint) self.bind('<Control-c>', self.sigint)
self.bind('<Control-t>', self.sigterm) self.bind('<Control-t>', self.sigterm)
self.bind('<Control-k>', self.sigkill) self.bind('<Control-k>', self.sigkill)
self.bind('<Control-d>', self.sendeof) self.bind('<Control-d>', self.sendeof)
self.pid, self.fromchild, self.tochild = spawn(shell, args) self.pid, self.fromchild, self.tochild = spawn(shell, args)
self.tk.createfilehandler(self.fromchild, READABLE, self.tk.createfilehandler(self.fromchild, READABLE,
self.outputhandler) self.outputhandler)
def outputhandler(self, file, mask): def outputhandler(self, file, mask):
data = os.read(file, BUFSIZE) data = os.read(file, BUFSIZE)
if not data: if not data:
self.tk.deletefilehandler(file) self.tk.deletefilehandler(file)
pid, sts = os.waitpid(self.pid, 0) pid, sts = os.waitpid(self.pid, 0)
print 'pid', pid, 'status', sts print 'pid', pid, 'status', sts
self.pid = None self.pid = None
detail = sts>>8 detail = sts>>8
cause = sts & 0xff cause = sts & 0xff
if cause == 0: if cause == 0:
msg = "exit status %d" % detail msg = "exit status %d" % detail
else: else:
msg = "killed by signal %d" % (cause & 0x7f) msg = "killed by signal %d" % (cause & 0x7f)
if cause & 0x80: if cause & 0x80:
msg = msg + " -- core dumped" msg = msg + " -- core dumped"
Dialog(self.master, Dialog(self.master,
text=msg, text=msg,
title="Exit status", title="Exit status",
bitmap='warning', bitmap='warning',
default=0, default=0,
strings=('OK',)) strings=('OK',))
return return
self.insert(END, data) self.insert(END, data)
self.pos = self.index("end - 1 char") self.pos = self.index("end - 1 char")
self.yview_pickplace(END) self.yview_pickplace(END)
def inputhandler(self, *args): def inputhandler(self, *args):
if not self.pid: if not self.pid:
self.no_process() self.no_process()
return "break" return "break"
self.insert(END, "\n") self.insert(END, "\n")
line = self.get(self.pos, "end - 1 char") line = self.get(self.pos, "end - 1 char")
self.pos = self.index(END) self.pos = self.index(END)
os.write(self.tochild, line) os.write(self.tochild, line)
return "break" return "break"
def sendeof(self, *args): def sendeof(self, *args):
if not self.pid: if not self.pid:
self.no_process() self.no_process()
return "break" return "break"
os.close(self.tochild) os.close(self.tochild)
return "break" return "break"
def sendsig(self, sig): def sendsig(self, sig):
if not self.pid: if not self.pid:
self.no_process() self.no_process()
return "break" return "break"
os.kill(self.pid, sig) os.kill(self.pid, sig)
return "break" return "break"
def sigint(self, *args): def sigint(self, *args):
return self.sendsig(signal.SIGINT) return self.sendsig(signal.SIGINT)
def sigquit(self, *args): def sigquit(self, *args):
return self.sendsig(signal.SIGQUIT) return self.sendsig(signal.SIGQUIT)
def sigterm(self, *args): def sigterm(self, *args):
return self.sendsig(signal.SIGTERM) return self.sendsig(signal.SIGTERM)
def sigkill(self, *args): def sigkill(self, *args):
return self.sendsig(signal.SIGKILL) return self.sendsig(signal.SIGKILL)
def no_process(self): def no_process(self):
Dialog(self.master, Dialog(self.master,
text="No active process", text="No active process",
title="No process", title="No process",
bitmap='error', bitmap='error',
default=0, default=0,
strings=('OK',)) strings=('OK',))
MAXFD = 100 # Max number of file descriptors (os.getdtablesize()???) MAXFD = 100 # Max number of file descriptors (os.getdtablesize()???)
def spawn(prog, args): def spawn(prog, args):
p2cread, p2cwrite = os.pipe() p2cread, p2cwrite = os.pipe()
c2pread, c2pwrite = os.pipe() c2pread, c2pwrite = os.pipe()
pid = os.fork() pid = os.fork()
if pid == 0: if pid == 0:
# Child # Child
for i in 0, 1, 2: for i in 0, 1, 2:
try: try:
os.close(i) os.close(i)
except os.error: except os.error:
pass pass
if os.dup(p2cread) <> 0: if os.dup(p2cread) <> 0:
sys.stderr.write('popen2: bad read dup\n') sys.stderr.write('popen2: bad read dup\n')
if os.dup(c2pwrite) <> 1: if os.dup(c2pwrite) <> 1:
sys.stderr.write('popen2: bad write dup\n') sys.stderr.write('popen2: bad write dup\n')
if os.dup(c2pwrite) <> 2: if os.dup(c2pwrite) <> 2:
sys.stderr.write('popen2: bad write dup\n') sys.stderr.write('popen2: bad write dup\n')
for i in range(3, MAXFD): for i in range(3, MAXFD):
try: try:
os.close(i) os.close(i)
except: except:
pass pass
try: try:
os.execvp(prog, args) os.execvp(prog, args)
finally: finally:
sys.stderr.write('execvp failed\n') sys.stderr.write('execvp failed\n')
os._exit(1) os._exit(1)
os.close(p2cread) os.close(p2cread)
os.close(c2pwrite) os.close(c2pwrite)
return pid, c2pread, p2cwrite return pid, c2pread, p2cwrite
def test(): def test():
shell = string.join(sys.argv[1:]) shell = string.join(sys.argv[1:])
root = Tk() root = Tk()
root.minsize(1, 1) root.minsize(1, 1)
if shell: if shell:
w = ShellWindow(root, shell=shell) w = ShellWindow(root, shell=shell)
else: else:
w = ShellWindow(root) w = ShellWindow(root)
w.pack(expand=1, fill=BOTH) w.pack(expand=1, fill=BOTH)
w.focus_set() w.focus_set()
w.tk.mainloop() w.tk.mainloop()
if __name__ == '__main__': if __name__ == '__main__':
test() test()

View file

@ -9,7 +9,7 @@ from Canvas import Oval, Group, CanvasText
class Group(Group): class Group(Group):
def bind(self, sequence=None, command=None): 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: class Object:
@ -33,45 +33,45 @@ class Object:
""" """
def __init__(self, canvas, x=0, y=0, fill='red', text='object'): def __init__(self, canvas, x=0, y=0, fill='red', text='object'):
self.canvas = canvas self.canvas = canvas
self.x = x self.x = x
self.y = y self.y = y
self.pile = None self.pile = None
self.group = Group(self.canvas) self.group = Group(self.canvas)
self.createitems(fill, text) self.createitems(fill, text)
def __str__(self): def __str__(self):
return str(self.group) return str(self.group)
def createitems(self, fill, text): def createitems(self, fill, text):
self.__oval = Oval(self.canvas, self.__oval = Oval(self.canvas,
self.x-20, self.y-10, self.x+20, self.y+10, self.x-20, self.y-10, self.x+20, self.y+10,
fill=fill, width=3) fill=fill, width=3)
self.group.addtag_withtag(self.__oval) self.group.addtag_withtag(self.__oval)
self.__text = CanvasText(self.canvas, self.__text = CanvasText(self.canvas,
self.x, self.y, text=text) self.x, self.y, text=text)
self.group.addtag_withtag(self.__text) self.group.addtag_withtag(self.__text)
def moveby(self, dx, dy): def moveby(self, dx, dy):
if dx == dy == 0: if dx == dy == 0:
return return
self.group.move(dx, dy) self.group.move(dx, dy)
self.x = self.x + dx self.x = self.x + dx
self.y = self.y + dy self.y = self.y + dy
def moveto(self, x, y): 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): def transfer(self, pile):
if self.pile: if self.pile:
self.pile.delete(self) self.pile.delete(self)
self.pile = None self.pile = None
self.pile = pile self.pile = pile
if self.pile: if self.pile:
self.pile.add(self) self.pile.add(self)
def tkraise(self): def tkraise(self):
self.group.tkraise() self.group.tkraise()
class Bottom(Object): class Bottom(Object):
@ -79,10 +79,10 @@ class Bottom(Object):
"""An object to serve as the bottom of a pile.""" """An object to serve as the bottom of a pile."""
def createitems(self, *args): def createitems(self, *args):
self.__oval = Oval(self.canvas, self.__oval = Oval(self.canvas,
self.x-20, self.y-10, self.x+20, self.y+10, self.x-20, self.y-10, self.x+20, self.y+10,
fill='gray', outline='') fill='gray', outline='')
self.group.addtag_withtag(self.__oval) self.group.addtag_withtag(self.__oval)
class Pile: class Pile:
@ -90,86 +90,86 @@ class Pile:
"""A group of graphical objects.""" """A group of graphical objects."""
def __init__(self, canvas, x, y, tag=None): def __init__(self, canvas, x, y, tag=None):
self.canvas = canvas self.canvas = canvas
self.x = x self.x = x
self.y = y self.y = y
self.objects = [] self.objects = []
self.bottom = Bottom(self.canvas, self.x, self.y) self.bottom = Bottom(self.canvas, self.x, self.y)
self.group = Group(self.canvas, tag=tag) self.group = Group(self.canvas, tag=tag)
self.group.addtag_withtag(self.bottom.group) self.group.addtag_withtag(self.bottom.group)
self.bindhandlers() self.bindhandlers()
def bindhandlers(self): def bindhandlers(self):
self.group.bind('<1>', self.clickhandler) self.group.bind('<1>', self.clickhandler)
self.group.bind('<Double-1>', self.doubleclickhandler) self.group.bind('<Double-1>', self.doubleclickhandler)
def add(self, object): def add(self, object):
self.objects.append(object) self.objects.append(object)
self.group.addtag_withtag(object.group) self.group.addtag_withtag(object.group)
self.position(object) self.position(object)
def delete(self, object): def delete(self, object):
object.group.dtag(self.group) object.group.dtag(self.group)
self.objects.remove(object) self.objects.remove(object)
def position(self, object): def position(self, object):
object.tkraise() object.tkraise()
i = self.objects.index(object) i = self.objects.index(object)
object.moveto(self.x + i*4, self.y + i*8) object.moveto(self.x + i*4, self.y + i*8)
def clickhandler(self, event): def clickhandler(self, event):
pass pass
def doubleclickhandler(self, event): def doubleclickhandler(self, event):
pass pass
class MovingPile(Pile): class MovingPile(Pile):
def bindhandlers(self): def bindhandlers(self):
Pile.bindhandlers(self) Pile.bindhandlers(self)
self.group.bind('<B1-Motion>', self.motionhandler) self.group.bind('<B1-Motion>', self.motionhandler)
self.group.bind('<ButtonRelease-1>', self.releasehandler) self.group.bind('<ButtonRelease-1>', self.releasehandler)
movethis = None movethis = None
def clickhandler(self, event): def clickhandler(self, event):
tags = self.canvas.gettags('current') tags = self.canvas.gettags('current')
for i in range(len(self.objects)): for i in range(len(self.objects)):
o = self.objects[i] o = self.objects[i]
if o.group.tag in tags: if o.group.tag in tags:
break break
else: else:
self.movethis = None self.movethis = None
return return
self.movethis = self.objects[i:] self.movethis = self.objects[i:]
for o in self.movethis: for o in self.movethis:
o.tkraise() o.tkraise()
self.lastx = event.x self.lastx = event.x
self.lasty = event.y self.lasty = event.y
doubleclickhandler = clickhandler doubleclickhandler = clickhandler
def motionhandler(self, event): def motionhandler(self, event):
if not self.movethis: if not self.movethis:
return return
dx = event.x - self.lastx dx = event.x - self.lastx
dy = event.y - self.lasty dy = event.y - self.lasty
self.lastx = event.x self.lastx = event.x
self.lasty = event.y self.lasty = event.y
for o in self.movethis: for o in self.movethis:
o.moveby(dx, dy) o.moveby(dx, dy)
def releasehandler(self, event): def releasehandler(self, event):
objects = self.movethis objects = self.movethis
if not objects: if not objects:
return return
self.movethis = None self.movethis = None
self.finishmove(objects) self.finishmove(objects)
def finishmove(self, objects): def finishmove(self, objects):
for o in objects: for o in objects:
self.position(o) self.position(o)
class Pile1(MovingPile): class Pile1(MovingPile):
@ -179,29 +179,29 @@ class Pile1(MovingPile):
tag = 'p1' tag = 'p1'
def __init__(self, demo): def __init__(self, demo):
self.demo = demo self.demo = demo
MovingPile.__init__(self, self.demo.canvas, self.x, self.y, self.tag) MovingPile.__init__(self, self.demo.canvas, self.x, self.y, self.tag)
def doubleclickhandler(self, event): def doubleclickhandler(self, event):
try: try:
o = self.objects[-1] o = self.objects[-1]
except IndexError: except IndexError:
return return
o.transfer(self.other()) o.transfer(self.other())
MovingPile.doubleclickhandler(self, event) MovingPile.doubleclickhandler(self, event)
def other(self): def other(self):
return self.demo.p2 return self.demo.p2
def finishmove(self, objects): def finishmove(self, objects):
o = objects[0] o = objects[0]
p = self.other() p = self.other()
x, y = o.x, o.y x, y = o.x, o.y
if (x-p.x)**2 + (y-p.y)**2 < (x-self.x)**2 + (y-self.y)**2: if (x-p.x)**2 + (y-p.y)**2 < (x-self.x)**2 + (y-self.y)**2:
for o in objects: for o in objects:
o.transfer(p) o.transfer(p)
else: else:
MovingPile.finishmove(self, objects) MovingPile.finishmove(self, objects)
class Pile2(Pile1): class Pile2(Pile1):
@ -210,26 +210,26 @@ class Pile2(Pile1):
tag = 'p2' tag = 'p2'
def other(self): def other(self):
return self.demo.p1 return self.demo.p1
class Demo: class Demo:
def __init__(self, master): def __init__(self, master):
self.master = master self.master = master
self.canvas = Canvas(master, self.canvas = Canvas(master,
width=200, height=200, width=200, height=200,
background='yellow', background='yellow',
relief=SUNKEN, borderwidth=2) relief=SUNKEN, borderwidth=2)
self.canvas.pack(expand=1, fill=BOTH) self.canvas.pack(expand=1, fill=BOTH)
self.p1 = Pile1(self) self.p1 = Pile1(self)
self.p2 = Pile2(self) self.p2 = Pile2(self)
o1 = Object(self.canvas, fill='red', text='o1') o1 = Object(self.canvas, fill='red', text='o1')
o2 = Object(self.canvas, fill='green', text='o2') o2 = Object(self.canvas, fill='green', text='o2')
o3 = Object(self.canvas, fill='light blue', text='o3') o3 = Object(self.canvas, fill='light blue', text='o3')
o1.transfer(self.p1) o1.transfer(self.p1)
o2.transfer(self.p1) o2.transfer(self.p1)
o3.transfer(self.p2) o3.transfer(self.p2)
# Main function, run when invoked as a stand-alone Python program. # Main function, run when invoked as a stand-alone Python program.

View file

@ -25,11 +25,11 @@ def dialog(master, title, text, bitmap, default, *args):
# 2. Fill the top part with the bitmap and message. # 2. Fill the top part with the bitmap and message.
msg = Message(top, width='3i', text=text, 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') msg.pack(side=RIGHT, expand=1, fill=BOTH, padx='3m', pady='3m')
if bitmap: if bitmap:
bm = Label(top, bitmap=bitmap) bm = Label(top, bitmap=bitmap)
bm.pack(side=LEFT, padx='3m', pady='3m') bm.pack(side=LEFT, padx='3m', pady='3m')
# 3. Create a row of buttons at the bottom of the dialog. # 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 = [] buttons = []
i = 0 i = 0
for but in args: for but in args:
b = Button(bot, text=but, command=lambda v=var,i=i: v.set(i)) b = Button(bot, text=but, command=lambda v=var,i=i: v.set(i))
buttons.append(b) buttons.append(b)
if i == default: if i == default:
bd = Frame(bot, relief=SUNKEN, borderwidth=1) bd = Frame(bot, relief=SUNKEN, borderwidth=1)
bd.pack(side=LEFT, expand=1, padx='3m', pady='2m') bd.pack(side=LEFT, expand=1, padx='3m', pady='2m')
b.lift() b.lift()
b.pack (in_=bd, side=LEFT, b.pack (in_=bd, side=LEFT,
padx='2m', pady='2m', ipadx='2m', ipady='1m') padx='2m', pady='2m', ipadx='2m', ipady='1m')
else: else:
b.pack (side=LEFT, expand=1, b.pack (side=LEFT, expand=1,
padx='3m', pady='3m', ipadx='2m', ipady='1m') padx='3m', pady='3m', ipadx='2m', ipady='1m')
i = i+1 i = i+1
# 4. Set up a binding for <Return>, if there's a default, # 4. Set up a binding for <Return>, if there's a default,
# set a grab, and claim the focus too. # set a grab, and claim the focus too.
if default >= 0: if default >= 0:
w.bind('<Return>', w.bind('<Return>',
lambda e, b=buttons[default], v=var, i=default: lambda e, b=buttons[default], v=var, i=default:
(b.flash(), (b.flash(),
v.set(i))) v.set(i)))
oldFocus = w.focus_get() oldFocus = w.focus_get()
w.grab_set() w.grab_set()
@ -75,23 +75,23 @@ def dialog(master, title, text, bitmap, default, *args):
def go(): def go():
i = dialog(mainWidget, i = dialog(mainWidget,
'Not Responding', 'Not Responding',
"The file server isn't responding right now; " "The file server isn't responding right now; "
"I'll keep trying.", "I'll keep trying.",
'', '',
-1, -1,
'OK') 'OK')
print 'pressed button', i print 'pressed button', i
i = dialog(mainWidget, i = dialog(mainWidget,
'File Modified', 'File Modified',
'File "tcl.h" has been modified since ' 'File "tcl.h" has been modified since '
'the last time it was saved. ' 'the last time it was saved. '
'Do you want to save it before exiting the application?', 'Do you want to save it before exiting the application?',
'warning', 'warning',
0, 0,
'Save File', 'Save File',
'Discard Changes', 'Discard Changes',
'Return To Editor') 'Return To Editor')
print 'pressed button', i print 'pressed button', i
def test(): def test():

View file

@ -18,74 +18,74 @@ import random
# The graphical interface # The graphical interface
class Electrons: class Electrons:
# Create our objects # Create our objects
def __init__(self, n, bitmap = None): def __init__(self, n, bitmap = None):
self.n = n self.n = n
self.tk = tk = Tk() self.tk = tk = Tk()
self.canvas = c = Canvas(tk) self.canvas = c = Canvas(tk)
c.pack() c.pack()
width, height = tk.getint(c['width']), tk.getint(c['height']) width, height = tk.getint(c['width']), tk.getint(c['height'])
# Add background bitmap # Add background bitmap
if bitmap: if bitmap:
self.bitmap = c.create_bitmap(width/2, height/2, self.bitmap = c.create_bitmap(width/2, height/2,
bitmap=bitmap, bitmap=bitmap,
foreground='blue') foreground='blue')
self.pieces = [] self.pieces = []
x1, y1, x2, y2 = 10,70,14,74 x1, y1, x2, y2 = 10,70,14,74
for i in range(n): for i in range(n):
p = c.create_oval(x1, y1, x2, y2, fill='red') p = c.create_oval(x1, y1, x2, y2, fill='red')
self.pieces.append(p) self.pieces.append(p)
y1, y2 = y1 +2, y2 + 2 y1, y2 = y1 +2, y2 + 2
self.tk.update() self.tk.update()
def random_move(self, n): def random_move(self, n):
c = self.canvas c = self.canvas
for p in self.pieces: for p in self.pieces:
x = random.choice(range(-2,4)) x = random.choice(range(-2,4))
y = random.choice(range(-3,4)) y = random.choice(range(-3,4))
c.move(p, x, y) c.move(p, x, y)
self.tk.update() self.tk.update()
# Run -- allow 500 movemens # Run -- allow 500 movemens
def run(self): def run(self):
try: try:
for i in range(500): for i in range(500):
self.random_move(self.n) self.random_move(self.n)
except TclError: except TclError:
try: try:
self.tk.destroy() self.tk.destroy()
except TclError: except TclError:
pass pass
# Main program # Main program
def main(): def main():
import sys, string import sys, string
# First argument is number of electrons, default 30 # First argument is number of electrons, default 30
if sys.argv[1:]: if sys.argv[1:]:
n = string.atoi(sys.argv[1]) n = string.atoi(sys.argv[1])
else: else:
n = 30 n = 30
# Second argument is bitmap file, default none # Second argument is bitmap file, default none
if sys.argv[2:]: if sys.argv[2:]:
bitmap = sys.argv[2] bitmap = sys.argv[2]
# Reverse meaning of leading '@' compared to Tk # Reverse meaning of leading '@' compared to Tk
if bitmap[0] == '@': bitmap = bitmap[1:] if bitmap[0] == '@': bitmap = bitmap[1:]
else: bitmap = '@' + bitmap else: bitmap = '@' + bitmap
else: else:
bitmap = None bitmap = None
# Create the graphical objects... # Create the graphical objects...
h = Electrons(n, bitmap) h = Electrons(n, bitmap)
# ...and run! # ...and run!
h.run() h.run()
# Call main when run as script # Call main when run as script
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View file

@ -16,139 +16,139 @@ from Tkinter import *
# Basic Towers-of-Hanoi algorithm: move n pieces from a to b, using c # Basic Towers-of-Hanoi algorithm: move n pieces from a to b, using c
# as temporary. For each move, call report() # as temporary. For each move, call report()
def hanoi(n, a, b, c, report): def hanoi(n, a, b, c, report):
if n <= 0: return if n <= 0: return
hanoi(n-1, a, c, b, report) hanoi(n-1, a, c, b, report)
report(n, a, b) report(n, a, b)
hanoi(n-1, c, b, a, report) hanoi(n-1, c, b, a, report)
# The graphical interface # The graphical interface
class Tkhanoi: class Tkhanoi:
# Create our objects # Create our objects
def __init__(self, n, bitmap = None): def __init__(self, n, bitmap = None):
self.n = n self.n = n
self.tk = tk = Tk() self.tk = tk = Tk()
self.canvas = c = Canvas(tk) self.canvas = c = Canvas(tk)
c.pack() c.pack()
width, height = tk.getint(c['width']), tk.getint(c['height']) width, height = tk.getint(c['width']), tk.getint(c['height'])
# Add background bitmap # Add background bitmap
if bitmap: if bitmap:
self.bitmap = c.create_bitmap(width/2, height/2, self.bitmap = c.create_bitmap(width/2, height/2,
bitmap=bitmap, bitmap=bitmap,
foreground='blue') foreground='blue')
# Generate pegs # Generate pegs
pegwidth = 10 pegwidth = 10
pegheight = height/2 pegheight = height/2
pegdist = width/3 pegdist = width/3
x1, y1 = (pegdist-pegwidth)/2, height*1/3 x1, y1 = (pegdist-pegwidth)/2, height*1/3
x2, y2 = x1+pegwidth, y1+pegheight x2, y2 = x1+pegwidth, y1+pegheight
self.pegs = [] self.pegs = []
p = c.create_rectangle(x1, y1, x2, y2, fill='black') p = c.create_rectangle(x1, y1, x2, y2, fill='black')
self.pegs.append(p) self.pegs.append(p)
x1, x2 = x1+pegdist, x2+pegdist x1, x2 = x1+pegdist, x2+pegdist
p = c.create_rectangle(x1, y1, x2, y2, fill='black') p = c.create_rectangle(x1, y1, x2, y2, fill='black')
self.pegs.append(p) self.pegs.append(p)
x1, x2 = x1+pegdist, x2+pegdist x1, x2 = x1+pegdist, x2+pegdist
p = c.create_rectangle(x1, y1, x2, y2, fill='black') p = c.create_rectangle(x1, y1, x2, y2, fill='black')
self.pegs.append(p) self.pegs.append(p)
self.tk.update() self.tk.update()
# Generate pieces # Generate pieces
pieceheight = pegheight/16 pieceheight = pegheight/16
maxpiecewidth = pegdist*2/3 maxpiecewidth = pegdist*2/3
minpiecewidth = 2*pegwidth minpiecewidth = 2*pegwidth
self.pegstate = [[], [], []] self.pegstate = [[], [], []]
self.pieces = {} self.pieces = {}
x1, y1 = (pegdist-maxpiecewidth)/2, y2-pieceheight-2 x1, y1 = (pegdist-maxpiecewidth)/2, y2-pieceheight-2
x2, y2 = x1+maxpiecewidth, y1+pieceheight x2, y2 = x1+maxpiecewidth, y1+pieceheight
dx = (maxpiecewidth-minpiecewidth) / (2*max(1, n-1)) dx = (maxpiecewidth-minpiecewidth) / (2*max(1, n-1))
for i in range(n, 0, -1): for i in range(n, 0, -1):
p = c.create_rectangle(x1, y1, x2, y2, fill='red') p = c.create_rectangle(x1, y1, x2, y2, fill='red')
self.pieces[i] = p self.pieces[i] = p
self.pegstate[0].append(i) self.pegstate[0].append(i)
x1, x2 = x1 + dx, x2-dx x1, x2 = x1 + dx, x2-dx
y1, y2 = y1 - pieceheight-2, y2-pieceheight-2 y1, y2 = y1 - pieceheight-2, y2-pieceheight-2
self.tk.update() self.tk.update()
self.tk.after(25) self.tk.after(25)
# Run -- never returns # Run -- never returns
def run(self): def run(self):
while 1: while 1:
hanoi(self.n, 0, 1, 2, self.report) hanoi(self.n, 0, 1, 2, self.report)
hanoi(self.n, 1, 2, 0, self.report) hanoi(self.n, 1, 2, 0, self.report)
hanoi(self.n, 2, 0, 1, self.report) hanoi(self.n, 2, 0, 1, self.report)
hanoi(self.n, 0, 2, 1, self.report) hanoi(self.n, 0, 2, 1, self.report)
hanoi(self.n, 2, 1, 0, self.report) hanoi(self.n, 2, 1, 0, self.report)
hanoi(self.n, 1, 0, 2, self.report) hanoi(self.n, 1, 0, 2, self.report)
# Reporting callback for the actual hanoi function # Reporting callback for the actual hanoi function
def report(self, i, a, b): def report(self, i, a, b):
if self.pegstate[a][-1] != i: raise RuntimeError # Assertion if self.pegstate[a][-1] != i: raise RuntimeError # Assertion
del self.pegstate[a][-1] del self.pegstate[a][-1]
p = self.pieces[i] p = self.pieces[i]
c = self.canvas c = self.canvas
# Lift the piece above peg a # Lift the piece above peg a
ax1, ay1, ax2, ay2 = c.bbox(self.pegs[a]) ax1, ay1, ax2, ay2 = c.bbox(self.pegs[a])
while 1: while 1:
x1, y1, x2, y2 = c.bbox(p) x1, y1, x2, y2 = c.bbox(p)
if y2 < ay1: break if y2 < ay1: break
c.move(p, 0, -1) c.move(p, 0, -1)
self.tk.update() self.tk.update()
# Move it towards peg b # Move it towards peg b
bx1, by1, bx2, by2 = c.bbox(self.pegs[b]) bx1, by1, bx2, by2 = c.bbox(self.pegs[b])
newcenter = (bx1+bx2)/2 newcenter = (bx1+bx2)/2
while 1: while 1:
x1, y1, x2, y2 = c.bbox(p) x1, y1, x2, y2 = c.bbox(p)
center = (x1+x2)/2 center = (x1+x2)/2
if center == newcenter: break if center == newcenter: break
if center > newcenter: c.move(p, -1, 0) if center > newcenter: c.move(p, -1, 0)
else: c.move(p, 1, 0) else: c.move(p, 1, 0)
self.tk.update() self.tk.update()
# Move it down on top of the previous piece # Move it down on top of the previous piece
pieceheight = y2-y1 pieceheight = y2-y1
newbottom = by2 - pieceheight*len(self.pegstate[b]) - 2 newbottom = by2 - pieceheight*len(self.pegstate[b]) - 2
while 1: while 1:
x1, y1, x2, y2 = c.bbox(p) x1, y1, x2, y2 = c.bbox(p)
if y2 >= newbottom: break if y2 >= newbottom: break
c.move(p, 0, 1) c.move(p, 0, 1)
self.tk.update() self.tk.update()
# Update peg state # Update peg state
self.pegstate[b].append(i) self.pegstate[b].append(i)
# Main program # Main program
def main(): def main():
import sys, string import sys, string
# First argument is number of pegs, default 4 # First argument is number of pegs, default 4
if sys.argv[1:]: if sys.argv[1:]:
n = string.atoi(sys.argv[1]) n = string.atoi(sys.argv[1])
else: else:
n = 4 n = 4
# Second argument is bitmap file, default none # Second argument is bitmap file, default none
if sys.argv[2:]: if sys.argv[2:]:
bitmap = sys.argv[2] bitmap = sys.argv[2]
# Reverse meaning of leading '@' compared to Tk # Reverse meaning of leading '@' compared to Tk
if bitmap[0] == '@': bitmap = bitmap[1:] if bitmap[0] == '@': bitmap = bitmap[1:]
else: bitmap = '@' + bitmap else: bitmap = '@' + bitmap
else: else:
bitmap = None bitmap = None
# Create the graphical objects... # Create the graphical objects...
h = Tkhanoi(n, bitmap) h = Tkhanoi(n, bitmap)
# ...and run! # ...and run!
h.run() h.run()
# Call main when run as script # Call main when run as script
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View file

@ -4,14 +4,14 @@ import sys
from Tkinter import * from Tkinter import *
def main(): def main():
root = Tk() root = Tk()
button = Button(root) button = Button(root)
button['text'] = 'Hello, world' button['text'] = 'Hello, world'
button['command'] = quit_callback # See below button['command'] = quit_callback # See below
button.pack() button.pack()
root.mainloop() root.mainloop()
def quit_callback(): def quit_callback():
sys.exit(0) sys.exit(0)
main() main()

View file

@ -8,92 +8,91 @@ import commands
import os import os
class BarButton(Menubutton): class BarButton(Menubutton):
def __init__(self, master=None, **cnf): def __init__(self, master=None, **cnf):
apply(Menubutton.__init__, (self, master), cnf) apply(Menubutton.__init__, (self, master), cnf)
self.pack(side=LEFT) self.pack(side=LEFT)
self.menu = Menu(self, name='menu') self.menu = Menu(self, name='menu')
self['menu'] = self.menu self['menu'] = self.menu
class Kill(Frame): class Kill(Frame):
# List of (name, option, pid_column) # List of (name, option, pid_column)
format_list = [('Default', '', 0), format_list = [('Default', '', 0),
('Long', '-l', 2), ('Long', '-l', 2),
('User', '-u', 1), ('User', '-u', 1),
('Jobs', '-j', 1), ('Jobs', '-j', 1),
('Signal', '-s', 1), ('Signal', '-s', 1),
('Memory', '-m', 0), ('Memory', '-m', 0),
('VM', '-v', 0), ('VM', '-v', 0),
('Hex', '-X', 0)] ('Hex', '-X', 0)]
def kill(self, selected): def kill(self, selected):
c = self.format_list[self.format.get()][2] c = self.format_list[self.format.get()][2]
pid = split(selected)[c] pid = split(selected)[c]
os.system('kill -9 ' + pid) os.system('kill -9 ' + pid)
self.do_update() self.do_update()
def do_update(self): def do_update(self):
name, option, column = self.format_list[self.format.get()] name, option, column = self.format_list[self.format.get()]
s = commands.getoutput('ps -w ' + option) s = commands.getoutput('ps -w ' + option)
list = splitfields(s, '\n') list = splitfields(s, '\n')
self.header.set(list[0]) self.header.set(list[0])
del list[0] del list[0]
y = self.frame.vscroll.get()[0] y = self.frame.vscroll.get()[0]
self.frame.list.delete(0, AtEnd()) self.frame.list.delete(0, AtEnd())
for line in list: for line in list:
self.frame.list.insert(0, line) self.frame.list.insert(0, line)
self.frame.list.yview(int(y)) self.frame.list.yview(int(y))
def do_motion(self, e): def do_motion(self, e):
e.widget.select_clear(0, END) e.widget.select_clear(0, END)
e.widget.select_set(e.widget.nearest(e.y)) e.widget.select_set(e.widget.nearest(e.y))
def do_leave(self, e): def do_leave(self, e):
e.widget.select_clear(0, END) e.widget.select_clear(0, END)
def do_1(self, e): def do_1(self, e):
self.kill(e.widget.get(e.widget.nearest(e.y))) self.kill(e.widget.get(e.widget.nearest(e.y)))
def __init__(self, master=None, **cnf): def __init__(self, master=None, **cnf):
Frame.__init__(self, master, cnf) Frame.__init__(self, master, cnf)
self.pack(expand=1, fill=BOTH) self.pack(expand=1, fill=BOTH)
self.bar = Frame(self, name='bar', relief=RAISED, self.bar = Frame(self, name='bar', relief=RAISED,
borderwidth=2) borderwidth=2)
self.bar.pack(fill=X) self.bar.pack(fill=X)
self.bar.file = BarButton(self.bar, text='File') self.bar.file = BarButton(self.bar, text='File')
self.bar.file.menu.add_command( self.bar.file.menu.add_command(
label='Quit', command=self.quit) label='Quit', command=self.quit)
self.bar.view = BarButton(self.bar, text='View') self.bar.view = BarButton(self.bar, text='View')
self.format = IntVar(self) self.format = IntVar(self)
self.format.set(2) self.format.set(2)
for num in range(len(self.format_list)): for num in range(len(self.format_list)):
self.bar.view.menu.add_radiobutton( self.bar.view.menu.add_radiobutton(
label=self.format_list[num][0], label=self.format_list[num][0],
command=self.do_update, command=self.do_update,
variable=self.format, variable=self.format,
value=num) value=num)
#self.bar.view.menu.add_separator() #self.bar.view.menu.add_separator()
#XXX ... #XXX ...
self.bar.tk_menuBar(self.bar.file, self.bar.view) self.bar.tk_menuBar(self.bar.file, self.bar.view)
self.frame = Frame(self, relief=RAISED, borderwidth=2) self.frame = Frame(self, relief=RAISED, borderwidth=2)
self.frame.pack(expand=1, fill=BOTH) self.frame.pack(expand=1, fill=BOTH)
self.header = StringVar(self) self.header = StringVar(self)
self.frame.label = Label(self.frame, relief=FLAT, anchor=NW, self.frame.label = Label(self.frame, relief=FLAT, anchor=NW,
borderwidth=0, borderwidth=0,
textvariable=self.header) textvariable=self.header)
self.frame.label.pack(fill=X) self.frame.label.pack(fill=X)
self.frame.vscroll = Scrollbar(self.frame, orient=VERTICAL) self.frame.vscroll = Scrollbar(self.frame, orient=VERTICAL)
self.frame.list = Listbox(self.frame, relief=SUNKEN, self.frame.list = Listbox(self.frame, relief=SUNKEN,
selectbackground='#eed5b7', selectbackground='#eed5b7',
selectborderwidth=0, selectborderwidth=0,
yscroll=self.frame.vscroll.set) yscroll=self.frame.vscroll.set)
self.frame.vscroll['command'] = self.frame.list.yview self.frame.vscroll['command'] = self.frame.list.yview
self.frame.vscroll.pack(side=RIGHT, fill=Y) self.frame.vscroll.pack(side=RIGHT, fill=Y)
self.frame.list.pack(expand=1, fill=BOTH) self.frame.list.pack(expand=1, fill=BOTH)
self.update = Button(self, text="Update", self.update = Button(self, text="Update",
command=self.do_update) command=self.do_update)
self.update.pack(expand=1, fill=X) self.update.pack(expand=1, fill=X)
self.frame.list.bind('<Motion>', self.do_motion) self.frame.list.bind('<Motion>', self.do_motion)
self.frame.list.bind('<Leave>', self.do_leave) self.frame.list.bind('<Leave>', self.do_leave)
self.frame.list.bind('<1>', self.do_1) self.frame.list.bind('<1>', self.do_1)
self.do_update() self.do_update()
if __name__ == '__main__': if __name__ == '__main__':
kill = Kill(None, borderwidth=5) kill = Kill(None, borderwidth=5)
kill.winfo_toplevel().title('Tkinter Process Killer') kill.winfo_toplevel().title('Tkinter Process Killer')
kill.winfo_toplevel().minsize(1, 1) kill.winfo_toplevel().minsize(1, 1)
kill.mainloop() kill.mainloop()

View file

@ -6,32 +6,32 @@ import string
from Tkinter import * from Tkinter import *
def listtree(master, app): def listtree(master, app):
list = Listbox(master, name='list') list = Listbox(master, name='list')
list.pack(expand=1, fill=BOTH) list.pack(expand=1, fill=BOTH)
listnodes(list, app, '.', 0) listnodes(list, app, '.', 0)
return list return list
def listnodes(list, app, widget, level): def listnodes(list, app, widget, level):
klass = list.send(app, 'winfo', 'class', widget) klass = list.send(app, 'winfo', 'class', widget)
## i = string.rindex(widget, '.') ## i = string.rindex(widget, '.')
## list.insert(END, '%s%s (%s)' % ((level-1)*'. ', widget[i:], klass)) ## list.insert(END, '%s%s (%s)' % ((level-1)*'. ', widget[i:], klass))
list.insert(END, '%s (%s)' % (widget, klass)) list.insert(END, '%s (%s)' % (widget, klass))
children = list.tk.splitlist( children = list.tk.splitlist(
list.send(app, 'winfo', 'children', widget)) list.send(app, 'winfo', 'children', widget))
for c in children: for c in children:
listnodes(list, app, c, level+1) listnodes(list, app, c, level+1)
def main(): def main():
if not sys.argv[1:]: if not sys.argv[1:]:
sys.stderr.write('Usage: listtree appname\n') sys.stderr.write('Usage: listtree appname\n')
sys.exit(2) sys.exit(2)
app = sys.argv[1] app = sys.argv[1]
tk = Tk() tk = Tk()
tk.minsize(1, 1) tk.minsize(1, 1)
f = Frame(tk, name='f') f = Frame(tk, name='f')
f.pack(expand=1, fill=BOTH) f.pack(expand=1, fill=BOTH)
list = listtree(f, app) list = listtree(f, app)
tk.mainloop() tk.mainloop()
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View file

@ -16,270 +16,270 @@ from dialog import dialog
mailbox = os.environ['HOME'] + '/Mail' mailbox = os.environ['HOME'] + '/Mail'
def main(): def main():
global root, tk, top, mid, bot global root, tk, top, mid, bot
global folderbox, foldermenu, scanbox, scanmenu, viewer global folderbox, foldermenu, scanbox, scanmenu, viewer
global folder, seq global folder, seq
global mh, mhf global mh, mhf
# Parse command line options # Parse command line options
folder = 'inbox' folder = 'inbox'
seq = 'all' seq = 'all'
try: try:
opts, args = getopt.getopt(sys.argv[1:], '') opts, args = getopt.getopt(sys.argv[1:], '')
except getopt.error, msg: except getopt.error, msg:
print msg print msg
sys.exit(2) sys.exit(2)
for arg in args: for arg in args:
if arg[:1] == '+': if arg[:1] == '+':
folder = arg[1:] folder = arg[1:]
else: else:
seq = arg seq = arg
# Initialize MH # Initialize MH
mh = mhlib.MH() mh = mhlib.MH()
mhf = mh.openfolder(folder) mhf = mh.openfolder(folder)
# Build widget hierarchy # Build widget hierarchy
root = Tk() root = Tk()
tk = root.tk tk = root.tk
top = Frame(root) top = Frame(root)
top.pack({'expand': 1, 'fill': 'both'}) top.pack({'expand': 1, 'fill': 'both'})
# Build right part: folder list # Build right part: folder list
right = Frame(top) right = Frame(top)
right.pack({'fill': 'y', 'side': 'right'}) right.pack({'fill': 'y', 'side': 'right'})
folderbar = Scrollbar(right, {'relief': 'sunken', 'bd': 2}) folderbar = Scrollbar(right, {'relief': 'sunken', 'bd': 2})
folderbar.pack({'fill': 'y', 'side': 'right'}) folderbar.pack({'fill': 'y', 'side': 'right'})
folderbox = Listbox(right, {'exportselection': 0}) folderbox = Listbox(right, {'exportselection': 0})
folderbox.pack({'expand': 1, 'fill': 'both', 'side': 'left'}) folderbox.pack({'expand': 1, 'fill': 'both', 'side': 'left'})
foldermenu = Menu(root) foldermenu = Menu(root)
foldermenu.add('command', foldermenu.add('command',
{'label': 'Open Folder', {'label': 'Open Folder',
'command': open_folder}) 'command': open_folder})
foldermenu.add('separator') foldermenu.add('separator')
foldermenu.add('command', foldermenu.add('command',
{'label': 'Quit', {'label': 'Quit',
'command': 'exit'}) 'command': 'exit'})
foldermenu.bind('<ButtonRelease-3>', folder_unpost) foldermenu.bind('<ButtonRelease-3>', folder_unpost)
folderbox['yscrollcommand'] = (folderbar, 'set') folderbox['yscrollcommand'] = (folderbar, 'set')
folderbar['command'] = (folderbox, 'yview') folderbar['command'] = (folderbox, 'yview')
folderbox.bind('<Double-1>', open_folder, 1) folderbox.bind('<Double-1>', open_folder, 1)
folderbox.bind('<3>', folder_post) folderbox.bind('<3>', folder_post)
# Build left part: scan list # Build left part: scan list
left = Frame(top) left = Frame(top)
left.pack({'expand': 1, 'fill': 'both', 'side': 'left'}) left.pack({'expand': 1, 'fill': 'both', 'side': 'left'})
scanbar = Scrollbar(left, {'relief': 'sunken', 'bd': 2}) scanbar = Scrollbar(left, {'relief': 'sunken', 'bd': 2})
scanbar.pack({'fill': 'y', 'side': 'right'}) scanbar.pack({'fill': 'y', 'side': 'right'})
scanbox = Listbox(left, {'font': 'fixed'}) scanbox = Listbox(left, {'font': 'fixed'})
scanbox.pack({'expand': 1, 'fill': 'both', 'side': 'left'}) scanbox.pack({'expand': 1, 'fill': 'both', 'side': 'left'})
scanmenu = Menu(root) scanmenu = Menu(root)
scanmenu.add('command', scanmenu.add('command',
{'label': 'Open Message', {'label': 'Open Message',
'command': open_message}) 'command': open_message})
scanmenu.add('command', scanmenu.add('command',
{'label': 'Remove Message', {'label': 'Remove Message',
'command': remove_message}) 'command': remove_message})
scanmenu.add('command', scanmenu.add('command',
{'label': 'Refile Message', {'label': 'Refile Message',
'command': refile_message}) 'command': refile_message})
scanmenu.add('separator') scanmenu.add('separator')
scanmenu.add('command', scanmenu.add('command',
{'label': 'Quit', {'label': 'Quit',
'command': 'exit'}) 'command': 'exit'})
scanmenu.bind('<ButtonRelease-3>', scan_unpost) scanmenu.bind('<ButtonRelease-3>', scan_unpost)
scanbox['yscrollcommand'] = (scanbar, 'set') scanbox['yscrollcommand'] = (scanbar, 'set')
scanbar['command'] = (scanbox, 'yview') scanbar['command'] = (scanbox, 'yview')
scanbox.bind('<Double-1>', open_message) scanbox.bind('<Double-1>', open_message)
scanbox.bind('<3>', scan_post) scanbox.bind('<3>', scan_post)
# Separator between middle and bottom part # Separator between middle and bottom part
rule2 = Frame(root, {'bg': 'black'}) rule2 = Frame(root, {'bg': 'black'})
rule2.pack({'fill': 'x'}) rule2.pack({'fill': 'x'})
# Build bottom part: current message # Build bottom part: current message
bot = Frame(root) bot = Frame(root)
bot.pack({'expand': 1, 'fill': 'both'}) bot.pack({'expand': 1, 'fill': 'both'})
# #
viewer = None 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): def folder_post(e):
x, y = e.x_root, e.y_root x, y = e.x_root, e.y_root
foldermenu.post(x - 10, y - 10) foldermenu.post(x - 10, y - 10)
foldermenu.grab_set() foldermenu.grab_set()
def folder_unpost(e): def folder_unpost(e):
tk.call('update', 'idletasks') tk.call('update', 'idletasks')
foldermenu.grab_release() foldermenu.grab_release()
foldermenu.unpost() foldermenu.unpost()
foldermenu.invoke('active') foldermenu.invoke('active')
def scan_post(e): def scan_post(e):
x, y = e.x_root, e.y_root x, y = e.x_root, e.y_root
scanmenu.post(x - 10, y - 10) scanmenu.post(x - 10, y - 10)
scanmenu.grab_set() scanmenu.grab_set()
def scan_unpost(e): def scan_unpost(e):
tk.call('update', 'idletasks') tk.call('update', 'idletasks')
scanmenu.grab_release() scanmenu.grab_release()
scanmenu.unpost() scanmenu.unpost()
scanmenu.invoke('active') scanmenu.invoke('active')
scanparser = regex.compile('^ *\([0-9]+\)') scanparser = regex.compile('^ *\([0-9]+\)')
def open_folder(e=None): def open_folder(e=None):
global folder, mhf global folder, mhf
sel = folderbox.curselection() sel = folderbox.curselection()
if len(sel) != 1: if len(sel) != 1:
if len(sel) > 1: if len(sel) > 1:
msg = "Please open one folder at a time" msg = "Please open one folder at a time"
else: else:
msg = "Please select a folder to open" msg = "Please select a folder to open"
dialog(root, "Can't Open Folder", msg, "", 0, "OK") dialog(root, "Can't Open Folder", msg, "", 0, "OK")
return return
i = sel[0] i = sel[0]
folder = folderbox.get(i) folder = folderbox.get(i)
mhf = mh.openfolder(folder) mhf = mh.openfolder(folder)
rescan() rescan()
def open_message(e=None): def open_message(e=None):
global viewer global viewer
sel = scanbox.curselection() sel = scanbox.curselection()
if len(sel) != 1: if len(sel) != 1:
if len(sel) > 1: if len(sel) > 1:
msg = "Please open one message at a time" msg = "Please open one message at a time"
else: else:
msg = "Please select a message to open" msg = "Please select a message to open"
dialog(root, "Can't Open Message", msg, "", 0, "OK") dialog(root, "Can't Open Message", msg, "", 0, "OK")
return return
cursor = scanbox['cursor'] cursor = scanbox['cursor']
scanbox['cursor'] = 'watch' scanbox['cursor'] = 'watch'
tk.call('update', 'idletasks') tk.call('update', 'idletasks')
i = sel[0] i = sel[0]
line = scanbox.get(i) line = scanbox.get(i)
if scanparser.match(line) >= 0: if scanparser.match(line) >= 0:
num = string.atoi(scanparser.group(1)) num = string.atoi(scanparser.group(1))
m = mhf.openmessage(num) m = mhf.openmessage(num)
if viewer: viewer.destroy() if viewer: viewer.destroy()
from MimeViewer import MimeViewer from MimeViewer import MimeViewer
viewer = MimeViewer(bot, '+%s/%d' % (folder, num), m) viewer = MimeViewer(bot, '+%s/%d' % (folder, num), m)
viewer.pack() viewer.pack()
viewer.show() viewer.show()
scanbox['cursor'] = cursor scanbox['cursor'] = cursor
def interestingheader(header): def interestingheader(header):
return header != 'received' return header != 'received'
def remove_message(e=None): def remove_message(e=None):
itop = scanbox.nearest(0) itop = scanbox.nearest(0)
sel = scanbox.curselection() sel = scanbox.curselection()
if not sel: if not sel:
dialog(root, "No Message To Remove", dialog(root, "No Message To Remove",
"Please select a message to remove", "", 0, "OK") "Please select a message to remove", "", 0, "OK")
return return
todo = [] todo = []
for i in sel: for i in sel:
line = scanbox.get(i) line = scanbox.get(i)
if scanparser.match(line) >= 0: if scanparser.match(line) >= 0:
todo.append(string.atoi(scanparser.group(1))) todo.append(string.atoi(scanparser.group(1)))
mhf.removemessages(todo) mhf.removemessages(todo)
rescan() rescan()
fixfocus(min(todo), itop) fixfocus(min(todo), itop)
lastrefile = '' lastrefile = ''
tofolder = None tofolder = None
def refile_message(e=None): def refile_message(e=None):
global lastrefile, tofolder global lastrefile, tofolder
itop = scanbox.nearest(0) itop = scanbox.nearest(0)
sel = scanbox.curselection() sel = scanbox.curselection()
if not sel: if not sel:
dialog(root, "No Message To Refile", dialog(root, "No Message To Refile",
"Please select a message to refile", "", 0, "OK") "Please select a message to refile", "", 0, "OK")
return return
foldersel = folderbox.curselection() foldersel = folderbox.curselection()
if len(foldersel) != 1: if len(foldersel) != 1:
if not foldersel: if not foldersel:
msg = "Please select a folder to refile to" msg = "Please select a folder to refile to"
else: else:
msg = "Please select exactly one folder to refile to" msg = "Please select exactly one folder to refile to"
dialog(root, "No Folder To Refile", msg, "", 0, "OK") dialog(root, "No Folder To Refile", msg, "", 0, "OK")
return return
refileto = folderbox.get(foldersel[0]) refileto = folderbox.get(foldersel[0])
todo = [] todo = []
for i in sel: for i in sel:
line = scanbox.get(i) line = scanbox.get(i)
if scanparser.match(line) >= 0: if scanparser.match(line) >= 0:
todo.append(string.atoi(scanparser.group(1))) todo.append(string.atoi(scanparser.group(1)))
if lastrefile != refileto or not tofolder: if lastrefile != refileto or not tofolder:
lastrefile = refileto lastrefile = refileto
tofolder = None tofolder = None
tofolder = mh.openfolder(lastrefile) tofolder = mh.openfolder(lastrefile)
mhf.refilemessages(todo, tofolder) mhf.refilemessages(todo, tofolder)
rescan() rescan()
fixfocus(min(todo), itop) fixfocus(min(todo), itop)
def fixfocus(near, itop): def fixfocus(near, itop):
n = scanbox.size() n = scanbox.size()
for i in range(n): for i in range(n):
line = scanbox.get(repr(i)) line = scanbox.get(repr(i))
if scanparser.match(line) >= 0: if scanparser.match(line) >= 0:
num = string.atoi(scanparser.group(1)) num = string.atoi(scanparser.group(1))
if num >= near: if num >= near:
break break
else: else:
i = 'end' i = 'end'
scanbox.select_from(i) scanbox.select_from(i)
scanbox.yview(itop) scanbox.yview(itop)
def setfolders(): def setfolders():
folderbox.delete(0, 'end') folderbox.delete(0, 'end')
for fn in mh.listallfolders(): for fn in mh.listallfolders():
folderbox.insert('end', fn) folderbox.insert('end', fn)
def rescan(): def rescan():
global viewer global viewer
if viewer: if viewer:
viewer.destroy() viewer.destroy()
viewer = None viewer = None
scanbox.delete(0, 'end') scanbox.delete(0, 'end')
for line in scanfolder(folder, seq): for line in scanfolder(folder, seq):
scanbox.insert('end', line) scanbox.insert('end', line)
def scanfolder(folder = 'inbox', sequence = 'all'): def scanfolder(folder = 'inbox', sequence = 'all'):
return map( return map(
lambda line: line[:-1], lambda line: line[:-1],
os.popen('scan +%s %s' % (folder, sequence), 'r').readlines()) os.popen('scan +%s %s' % (folder, sequence), 'r').readlines())
main() main()

View file

@ -7,35 +7,35 @@ from Tkinter import *
class App: class App:
def __init__(self, master): 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 = Menu(self.menubar)
self.filemenu.add_command(label="New") self.filemenu.add_command(label="New")
self.filemenu.add_command(label="Open...") self.filemenu.add_command(label="Open...")
self.filemenu.add_command(label="Close") self.filemenu.add_command(label="Close")
self.filemenu.add_separator() self.filemenu.add_separator()
self.filemenu.add_command(label="Quit", command=self.master.quit) self.filemenu.add_command(label="Quit", command=self.master.quit)
self.editmenu = Menu(self.menubar) self.editmenu = Menu(self.menubar)
self.editmenu.add_command(label="Cut") self.editmenu.add_command(label="Cut")
self.editmenu.add_command(label="Copy") self.editmenu.add_command(label="Copy")
self.editmenu.add_command(label="Paste") self.editmenu.add_command(label="Paste")
self.helpmenu = Menu(self.menubar, name='help') self.helpmenu = Menu(self.menubar, name='help')
self.helpmenu.add_command(label="About...") self.helpmenu.add_command(label="About...")
self.menubar.add_cascade(label="File", menu=self.filemenu) self.menubar.add_cascade(label="File", menu=self.filemenu)
self.menubar.add_cascade(label="Edit", menu=self.editmenu) self.menubar.add_cascade(label="Edit", menu=self.editmenu)
self.menubar.add_cascade(label="Help", menu=self.helpmenu) 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(): def main():
root = Tk() root = Tk()

View file

@ -15,9 +15,9 @@ 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... options like other shapes or colors...
yours, yours,
dave mitchell dave mitchell
davem@magnet.com davem@magnet.com
""" """
from Tkinter import * from Tkinter import *
@ -28,33 +28,33 @@ b1 = "up"
xold, yold = None, None xold, yold = None, None
def main(): def main():
root = Tk() root = Tk()
drawing_area = Canvas(root) drawing_area = Canvas(root)
drawing_area.pack() drawing_area.pack()
drawing_area.bind("<Motion>", motion) drawing_area.bind("<Motion>", motion)
drawing_area.bind("<ButtonPress-1>", b1down) drawing_area.bind("<ButtonPress-1>", b1down)
drawing_area.bind("<ButtonRelease-1>", b1up) drawing_area.bind("<ButtonRelease-1>", b1up)
root.mainloop() root.mainloop()
def b1down(event): def b1down(event):
global b1 global b1
b1 = "down" # you only want to draw when the button is down b1 = "down" # you only want to draw when the button is down
# because "Motion" events happen -all the time- # because "Motion" events happen -all the time-
def b1up(event): def b1up(event):
global b1, xold, yold global b1, xold, yold
b1 = "up" b1 = "up"
xold = None # reset the line when you let go of the button xold = None # reset the line when you let go of the button
yold = None yold = None
def motion(event): def motion(event):
if b1 == "down": if b1 == "down":
global xold, yold global xold, yold
if xold != None and yold != None: if xold != None and yold != None:
event.widget.create_line(xold,yold,event.x,event.y,smooth=TRUE) event.widget.create_line(xold,yold,event.x,event.y,smooth=TRUE)
# here's where you draw it. smooth. neat. # here's where you draw it. smooth. neat.
xold = event.x xold = event.x
yold = event.y yold = event.y
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View file

@ -42,7 +42,7 @@ file_m = Menu(file)
file['menu'] = file_m file['menu'] = file_m
file_m_apps = Menu(file_m, tearoff=0) file_m_apps = Menu(file_m, tearoff=0)
file_m.add_cascade(label='Select Application', underline=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) file_m.add_command(label='Quit', underline=0, command=sys.exit)
# 3. Create bindings for text widget to allow commands to be # 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). # insertion point).
def single1(e): def single1(e):
x = e.x x = e.x
y = e.y y = e.y
t.setvar('tk_priv(selectMode)', 'char') t.setvar('tk_priv(selectMode)', 'char')
t.mark_set('anchor', At(x, y)) t.mark_set('anchor', At(x, y))
# Should focus W # Should focus W
t.bind('<1>', single1) t.bind('<1>', single1)
def double1(e): def double1(e):
x = e.x x = e.x
y = e.y y = e.y
t.setvar('tk_priv(selectMode)', 'word') t.setvar('tk_priv(selectMode)', 'word')
t.tk_textSelectTo(At(x, y)) t.tk_textSelectTo(At(x, y))
t.bind('<Double-1>', double1) t.bind('<Double-1>', double1)
def triple1(e): def triple1(e):
x = e.x x = e.x
y = e.y y = e.y
t.setvar('tk_priv(selectMode)', 'line') t.setvar('tk_priv(selectMode)', 'line')
t.tk_textSelectTo(At(x, y)) t.tk_textSelectTo(At(x, y))
t.bind('<Triple-1>', triple1) t.bind('<Triple-1>', triple1)
def returnkey(e): def returnkey(e):
t.insert(AtInsert(), '\n') t.insert(AtInsert(), '\n')
invoke() invoke()
t.bind('<Return>', returnkey) t.bind('<Return>', returnkey)
def controlv(e): def controlv(e):
t.insert(AtInsert(), t.selection_get()) t.insert(AtInsert(), t.selection_get())
t.yview_pickplace(AtInsert()) t.yview_pickplace(AtInsert())
if t.index(AtInsert())[-2:] == '.0': if t.index(AtInsert())[-2:] == '.0':
invoke() invoke()
t.bind('<Control-v>', controlv) t.bind('<Control-v>', controlv)
# 4. Procedure to backspace over one character, as long as # 4. Procedure to backspace over one character, as long as
# the character isn't part of the prompt. # the character isn't part of the prompt.
def backspace(e): def backspace(e):
if t.index('promptEnd') != t.index('insert - 1 char'): if t.index('promptEnd') != t.index('insert - 1 char'):
t.delete('insert - 1 char', AtInsert()) t.delete('insert - 1 char', AtInsert())
t.yview_pickplace(AtInsert()) t.yview_pickplace(AtInsert())
t.bind('<BackSpace>', backspace) t.bind('<BackSpace>', backspace)
t.bind('<Control-h>', backspace) t.bind('<Control-h>', backspace)
t.bind('<Delete>', backspace) t.bind('<Delete>', backspace)
@ -103,49 +103,49 @@ t.bind('<Delete>', backspace)
# a new prompt. # a new prompt.
def invoke(): def invoke():
cmd = t.get('promptEnd + 1 char', AtInsert()) cmd = t.get('promptEnd + 1 char', AtInsert())
if t.getboolean(tk.call('info', 'complete', cmd)): # XXX if t.getboolean(tk.call('info', 'complete', cmd)): # XXX
if app == root.winfo_name(): if app == root.winfo_name():
msg = tk.call('eval', cmd) # XXX msg = tk.call('eval', cmd) # XXX
else: else:
msg = t.send(app, cmd) msg = t.send(app, cmd)
if msg: if msg:
t.insert(AtInsert(), msg + '\n') t.insert(AtInsert(), msg + '\n')
prompt() prompt()
t.yview_pickplace(AtInsert()) t.yview_pickplace(AtInsert())
def prompt(): def prompt():
t.insert(AtInsert(), app + ': ') t.insert(AtInsert(), app + ': ')
t.mark_set('promptEnd', 'insert - 1 char') t.mark_set('promptEnd', 'insert - 1 char')
t.tag_add('bold', 'insert linestart', 'promptEnd') t.tag_add('bold', 'insert linestart', 'promptEnd')
# 6. Procedure to select a new application. Also changes # 6. Procedure to select a new application. Also changes
# the prompt on the current command line to reflect the new # the prompt on the current command line to reflect the new
# name. # name.
def newApp(appName): def newApp(appName):
global app global app
app = appName app = appName
t.delete('promptEnd linestart', 'promptEnd') t.delete('promptEnd linestart', 'promptEnd')
t.insert('promptEnd', appName + ':') t.insert('promptEnd', appName + ':')
t.tag_add('bold', 'promptEnd linestart', 'promptEnd') t.tag_add('bold', 'promptEnd linestart', 'promptEnd')
def fillAppsMenu(): def fillAppsMenu():
file_m_apps.add('command') file_m_apps.add('command')
file_m_apps.delete(0, 'last') file_m_apps.delete(0, 'last')
names = root.winfo_interps() names = root.winfo_interps()
names = map(None, names) # convert tuple to list names = map(None, names) # convert tuple to list
names.sort() names.sort()
for name in names: for name in names:
try: try:
root.send(name, 'winfo name .') root.send(name, 'winfo name .')
except TclError: except TclError:
# Inoperative window -- ignore it # Inoperative window -- ignore it
pass pass
else: else:
file_m_apps.add_command( file_m_apps.add_command(
label=name, label=name,
command=lambda name=name: newApp(name)) command=lambda name=name: newApp(name))
file_m_apps['postcommand'] = fillAppsMenu file_m_apps['postcommand'] = fillAppsMenu
mBar.tk_menuBar(file) mBar.tk_menuBar(file)

View file

@ -35,7 +35,7 @@ from Canvas import Rectangle, CanvasText, Group, Window
class Group(Group): class Group(Group):
def bind(self, sequence=None, command=None): 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 # Constants determining the size and lay-out of cards and stacks. We
@ -150,68 +150,68 @@ class Card:
""" """
def __init__(self, suit, value, canvas): 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 The card is created at position (0, 0), with its face down
(adding it to a stack will position it according to that (adding it to a stack will position it according to that
stack's rules). stack's rules).
""" """
self.suit = suit self.suit = suit
self.value = value self.value = value
self.color = COLOR[suit] self.color = COLOR[suit]
self.face_shown = 0 self.face_shown = 0
self.x = self.y = 0 self.x = self.y = 0
self.group = Group(canvas) self.group = Group(canvas)
text = "%s %s" % (VALNAMES[value], suit) text = "%s %s" % (VALNAMES[value], suit)
self.__text = CanvasText(canvas, CARDWIDTH/2, 0, self.__text = CanvasText(canvas, CARDWIDTH/2, 0,
anchor=N, fill=self.color, text=text) anchor=N, fill=self.color, text=text)
self.group.addtag_withtag(self.__text) self.group.addtag_withtag(self.__text)
self.__rect = Rectangle(canvas, 0, 0, CARDWIDTH, CARDHEIGHT, self.__rect = Rectangle(canvas, 0, 0, CARDWIDTH, CARDHEIGHT,
outline='black', fill='white') outline='black', fill='white')
self.group.addtag_withtag(self.__rect) self.group.addtag_withtag(self.__rect)
self.__back = Rectangle(canvas, MARGIN, MARGIN, self.__back = Rectangle(canvas, MARGIN, MARGIN,
CARDWIDTH-MARGIN, CARDHEIGHT-MARGIN, CARDWIDTH-MARGIN, CARDHEIGHT-MARGIN,
outline='black', fill='blue') outline='black', fill='blue')
self.group.addtag_withtag(self.__back) self.group.addtag_withtag(self.__back)
def __repr__(self): def __repr__(self):
"""Return a string for debug print statements.""" """Return a string for debug print statements."""
return "Card(%r, %r)" % (self.suit, self.value) return "Card(%r, %r)" % (self.suit, self.value)
def moveto(self, x, y): def moveto(self, x, y):
"""Move the card to absolute position (x, y).""" """Move the card to absolute position (x, y)."""
self.moveby(x - self.x, y - self.y) self.moveby(x - self.x, y - self.y)
def moveby(self, dx, dy): def moveby(self, dx, dy):
"""Move the card by (dx, dy).""" """Move the card by (dx, dy)."""
self.x = self.x + dx self.x = self.x + dx
self.y = self.y + dy self.y = self.y + dy
self.group.move(dx, dy) self.group.move(dx, dy)
def tkraise(self): def tkraise(self):
"""Raise the card above all other objects in its canvas.""" """Raise the card above all other objects in its canvas."""
self.group.tkraise() self.group.tkraise()
def showface(self): def showface(self):
"""Turn the card's face up.""" """Turn the card's face up."""
self.tkraise() self.tkraise()
self.__rect.tkraise() self.__rect.tkraise()
self.__text.tkraise() self.__text.tkraise()
self.face_shown = 1 self.face_shown = 1
def showback(self): def showback(self):
"""Turn the card's face down.""" """Turn the card's face down."""
self.tkraise() self.tkraise()
self.__rect.tkraise() self.__rect.tkraise()
self.__back.tkraise() self.__back.tkraise()
self.face_shown = 0 self.face_shown = 0
class Stack: class Stack:
@ -240,7 +240,7 @@ class Stack:
The default user (single) click handler shows the top card The default user (single) click handler shows the top card
face up. The default user double click handler calls the user 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 usermovehandler(cards) -- called to complete a subpile move
@ -262,126 +262,126 @@ class Stack:
""" """
def __init__(self, x, y, game=None): def __init__(self, x, y, game=None):
"""Stack constructor. """Stack constructor.
Arguments are the stack's nominal x and y position (the top Arguments are the stack's nominal x and y position (the top
left corner of the first card placed in the stack), and the left corner of the first card placed in the stack), and the
game object (which is used to get the canvas; subclasses use game object (which is used to get the canvas; subclasses use
the game object to find other stacks). the game object to find other stacks).
""" """
self.x = x self.x = x
self.y = y self.y = y
self.game = game self.game = game
self.cards = [] self.cards = []
self.group = Group(self.game.canvas) self.group = Group(self.game.canvas)
self.group.bind('<1>', self.clickhandler) self.group.bind('<1>', self.clickhandler)
self.group.bind('<Double-1>', self.doubleclickhandler) self.group.bind('<Double-1>', self.doubleclickhandler)
self.group.bind('<B1-Motion>', self.motionhandler) self.group.bind('<B1-Motion>', self.motionhandler)
self.group.bind('<ButtonRelease-1>', self.releasehandler) self.group.bind('<ButtonRelease-1>', self.releasehandler)
self.makebottom() self.makebottom()
def makebottom(self): def makebottom(self):
pass pass
def __repr__(self): def __repr__(self):
"""Return a string for debug print statements.""" """Return a string for debug print statements."""
return "%s(%d, %d)" % (self.__class__.__name__, self.x, self.y) return "%s(%d, %d)" % (self.__class__.__name__, self.x, self.y)
# Public methods # Public methods
def add(self, card): def add(self, card):
self.cards.append(card) self.cards.append(card)
card.tkraise() card.tkraise()
self.position(card) self.position(card)
self.group.addtag_withtag(card.group) self.group.addtag_withtag(card.group)
def delete(self, card): def delete(self, card):
self.cards.remove(card) self.cards.remove(card)
card.group.dtag(self.group) card.group.dtag(self.group)
def showtop(self): def showtop(self):
if self.cards: if self.cards:
self.cards[-1].showface() self.cards[-1].showface()
def deal(self): def deal(self):
if not self.cards: if not self.cards:
return None return None
card = self.cards[-1] card = self.cards[-1]
self.delete(card) self.delete(card)
return card return card
# Subclass overridable methods # Subclass overridable methods
def position(self, card): def position(self, card):
card.moveto(self.x, self.y) card.moveto(self.x, self.y)
def userclickhandler(self): def userclickhandler(self):
self.showtop() self.showtop()
def userdoubleclickhandler(self): def userdoubleclickhandler(self):
self.userclickhandler() self.userclickhandler()
def usermovehandler(self, cards): def usermovehandler(self, cards):
for card in cards: for card in cards:
self.position(card) self.position(card)
# Event handlers # Event handlers
def clickhandler(self, event): def clickhandler(self, event):
self.finishmoving() # In case we lost an event self.finishmoving() # In case we lost an event
self.userclickhandler() self.userclickhandler()
self.startmoving(event) self.startmoving(event)
def motionhandler(self, event): def motionhandler(self, event):
self.keepmoving(event) self.keepmoving(event)
def releasehandler(self, event): def releasehandler(self, event):
self.keepmoving(event) self.keepmoving(event)
self.finishmoving() self.finishmoving()
def doubleclickhandler(self, event): def doubleclickhandler(self, event):
self.finishmoving() # In case we lost an event self.finishmoving() # In case we lost an event
self.userdoubleclickhandler() self.userdoubleclickhandler()
self.startmoving(event) self.startmoving(event)
# Move internals # Move internals
moving = None moving = None
def startmoving(self, event): def startmoving(self, event):
self.moving = None self.moving = None
tags = self.game.canvas.gettags('current') tags = self.game.canvas.gettags('current')
for i in range(len(self.cards)): for i in range(len(self.cards)):
card = self.cards[i] card = self.cards[i]
if card.group.tag in tags: if card.group.tag in tags:
break break
else: else:
return return
if not card.face_shown: if not card.face_shown:
return return
self.moving = self.cards[i:] self.moving = self.cards[i:]
self.lastx = event.x self.lastx = event.x
self.lasty = event.y self.lasty = event.y
for card in self.moving: for card in self.moving:
card.tkraise() card.tkraise()
def keepmoving(self, event): def keepmoving(self, event):
if not self.moving: if not self.moving:
return return
dx = event.x - self.lastx dx = event.x - self.lastx
dy = event.y - self.lasty dy = event.y - self.lasty
self.lastx = event.x self.lastx = event.x
self.lasty = event.y self.lasty = event.y
if dx or dy: if dx or dy:
for card in self.moving: for card in self.moving:
card.moveby(dx, dy) card.moveby(dx, dy)
def finishmoving(self): def finishmoving(self):
cards = self.moving cards = self.moving
self.moving = None self.moving = None
if cards: if cards:
self.usermovehandler(cards) self.usermovehandler(cards)
class Deck(Stack): class Deck(Stack):
@ -400,37 +400,37 @@ class Deck(Stack):
""" """
def makebottom(self): def makebottom(self):
bottom = Rectangle(self.game.canvas, bottom = Rectangle(self.game.canvas,
self.x, self.y, self.x, self.y,
self.x+CARDWIDTH, self.y+CARDHEIGHT, self.x+CARDWIDTH, self.y+CARDHEIGHT,
outline='black', fill=BACKGROUND) outline='black', fill=BACKGROUND)
self.group.addtag_withtag(bottom) self.group.addtag_withtag(bottom)
def fill(self): def fill(self):
for suit in ALLSUITS: for suit in ALLSUITS:
for value in ALLVALUES: for value in ALLVALUES:
self.add(Card(suit, value, self.game.canvas)) self.add(Card(suit, value, self.game.canvas))
def shuffle(self): def shuffle(self):
n = len(self.cards) n = len(self.cards)
newcards = [] newcards = []
for i in randperm(n): for i in randperm(n):
newcards.append(self.cards[i]) newcards.append(self.cards[i])
self.cards = newcards self.cards = newcards
def userclickhandler(self): def userclickhandler(self):
opendeck = self.game.opendeck opendeck = self.game.opendeck
card = self.deal() card = self.deal()
if not card: if not card:
while 1: while 1:
card = opendeck.deal() card = opendeck.deal()
if not card: if not card:
break break
self.add(card) self.add(card)
card.showback() card.showback()
else: else:
self.game.opendeck.add(card) self.game.opendeck.add(card)
card.showface() card.showface()
def randperm(n): def randperm(n):
@ -438,191 +438,191 @@ def randperm(n):
r = range(n) r = range(n)
x = [] x = []
while r: while r:
i = random.choice(r) i = random.choice(r)
x.append(i) x.append(i)
r.remove(i) r.remove(i)
return x return x
class OpenStack(Stack): class OpenStack(Stack):
def acceptable(self, cards): def acceptable(self, cards):
return 0 return 0
def usermovehandler(self, cards): def usermovehandler(self, cards):
card = cards[0] card = cards[0]
stack = self.game.closeststack(card) stack = self.game.closeststack(card)
if not stack or stack is self or not stack.acceptable(cards): if not stack or stack is self or not stack.acceptable(cards):
Stack.usermovehandler(self, cards) Stack.usermovehandler(self, cards)
else: else:
for card in cards: for card in cards:
self.delete(card) self.delete(card)
stack.add(card) stack.add(card)
self.game.wincheck() self.game.wincheck()
def userdoubleclickhandler(self): def userdoubleclickhandler(self):
if not self.cards: if not self.cards:
return return
card = self.cards[-1] card = self.cards[-1]
if not card.face_shown: if not card.face_shown:
self.userclickhandler() self.userclickhandler()
return return
for s in self.game.suits: for s in self.game.suits:
if s.acceptable([card]): if s.acceptable([card]):
self.delete(card) self.delete(card)
s.add(card) s.add(card)
self.game.wincheck() self.game.wincheck()
break break
class SuitStack(OpenStack): class SuitStack(OpenStack):
def makebottom(self): def makebottom(self):
bottom = Rectangle(self.game.canvas, bottom = Rectangle(self.game.canvas,
self.x, self.y, self.x, self.y,
self.x+CARDWIDTH, self.y+CARDHEIGHT, self.x+CARDWIDTH, self.y+CARDHEIGHT,
outline='black', fill='') outline='black', fill='')
def userclickhandler(self): def userclickhandler(self):
pass pass
def userdoubleclickhandler(self): def userdoubleclickhandler(self):
pass pass
def acceptable(self, cards): def acceptable(self, cards):
if len(cards) != 1: if len(cards) != 1:
return 0 return 0
card = cards[0] card = cards[0]
if not self.cards: if not self.cards:
return card.value == ACE return card.value == ACE
topcard = self.cards[-1] topcard = self.cards[-1]
return card.suit == topcard.suit and card.value == topcard.value + 1 return card.suit == topcard.suit and card.value == topcard.value + 1
class RowStack(OpenStack): class RowStack(OpenStack):
def acceptable(self, cards): def acceptable(self, cards):
card = cards[0] card = cards[0]
if not self.cards: if not self.cards:
return card.value == KING return card.value == KING
topcard = self.cards[-1] topcard = self.cards[-1]
if not topcard.face_shown: if not topcard.face_shown:
return 0 return 0
return card.color != topcard.color and card.value == topcard.value - 1 return card.color != topcard.color and card.value == topcard.value - 1
def position(self, card): def position(self, card):
y = self.y y = self.y
for c in self.cards: for c in self.cards:
if c == card: if c == card:
break break
if c.face_shown: if c.face_shown:
y = y + 2*MARGIN y = y + 2*MARGIN
else: else:
y = y + OFFSET y = y + OFFSET
card.moveto(self.x, y) card.moveto(self.x, y)
class Solitaire: class Solitaire:
def __init__(self, master): def __init__(self, master):
self.master = master self.master = master
self.canvas = Canvas(self.master, self.canvas = Canvas(self.master,
background=BACKGROUND, background=BACKGROUND,
highlightthickness=0, highlightthickness=0,
width=NROWS*XSPACING, width=NROWS*XSPACING,
height=3*YSPACING + 20 + MARGIN) height=3*YSPACING + 20 + MARGIN)
self.canvas.pack(fill=BOTH, expand=TRUE) self.canvas.pack(fill=BOTH, expand=TRUE)
self.dealbutton = Button(self.canvas, self.dealbutton = Button(self.canvas,
text="Deal", text="Deal",
highlightthickness=0, highlightthickness=0,
background=BACKGROUND, background=BACKGROUND,
activebackground="green", activebackground="green",
command=self.deal) command=self.deal)
Window(self.canvas, MARGIN, 3*YSPACING + 20, Window(self.canvas, MARGIN, 3*YSPACING + 20,
window=self.dealbutton, anchor=SW) window=self.dealbutton, anchor=SW)
x = MARGIN x = MARGIN
y = MARGIN y = MARGIN
self.deck = Deck(x, y, self) self.deck = Deck(x, y, self)
x = x + XSPACING x = x + XSPACING
self.opendeck = OpenStack(x, y, self) self.opendeck = OpenStack(x, y, self)
x = x + XSPACING x = x + XSPACING
self.suits = [] self.suits = []
for i in range(NSUITS): for i in range(NSUITS):
x = x + XSPACING x = x + XSPACING
self.suits.append(SuitStack(x, y, self)) self.suits.append(SuitStack(x, y, self))
x = MARGIN x = MARGIN
y = y + YSPACING y = y + YSPACING
self.rows = [] self.rows = []
for i in range(NROWS): for i in range(NROWS):
self.rows.append(RowStack(x, y, self)) self.rows.append(RowStack(x, y, self))
x = x + XSPACING x = x + XSPACING
self.openstacks = [self.opendeck] + self.suits + self.rows self.openstacks = [self.opendeck] + self.suits + self.rows
self.deck.fill() self.deck.fill()
self.deal() self.deal()
def wincheck(self): def wincheck(self):
for s in self.suits: for s in self.suits:
if len(s.cards) != NVALUES: if len(s.cards) != NVALUES:
return return
self.win() self.win()
self.deal() self.deal()
def win(self): def win(self):
"""Stupid animation when you win.""" """Stupid animation when you win."""
cards = [] cards = []
for s in self.openstacks: for s in self.openstacks:
cards = cards + s.cards cards = cards + s.cards
while cards: while cards:
card = random.choice(cards) card = random.choice(cards)
cards.remove(card) cards.remove(card)
self.animatedmoveto(card, self.deck) self.animatedmoveto(card, self.deck)
def animatedmoveto(self, card, dest): def animatedmoveto(self, card, dest):
for i in range(10, 0, -1): for i in range(10, 0, -1):
dx, dy = (dest.x-card.x)/i, (dest.y-card.y)/i dx, dy = (dest.x-card.x)/i, (dest.y-card.y)/i
card.moveby(dx, dy) card.moveby(dx, dy)
self.master.update_idletasks() self.master.update_idletasks()
def closeststack(self, card): def closeststack(self, card):
closest = None closest = None
cdist = 999999999 cdist = 999999999
# Since we only compare distances, # Since we only compare distances,
# we don't bother to take the square root. # we don't bother to take the square root.
for stack in self.openstacks: for stack in self.openstacks:
dist = (stack.x - card.x)**2 + (stack.y - card.y)**2 dist = (stack.x - card.x)**2 + (stack.y - card.y)**2
if dist < cdist: if dist < cdist:
closest = stack closest = stack
cdist = dist cdist = dist
return closest return closest
def deal(self): def deal(self):
self.reset() self.reset()
self.deck.shuffle() self.deck.shuffle()
for i in range(NROWS): for i in range(NROWS):
for r in self.rows[i:]: for r in self.rows[i:]:
card = self.deck.deal() card = self.deck.deal()
r.add(card) r.add(card)
for r in self.rows: for r in self.rows:
r.showtop() r.showtop()
def reset(self): def reset(self):
for stack in self.openstacks: for stack in self.openstacks:
while 1: while 1:
card = stack.deal() card = stack.deal()
if not card: if not card:
break break
self.deck.add(card) self.deck.add(card)
card.showback() card.showback()
# Main function, run when invoked as a stand-alone Python program. # Main function, run when invoked as a stand-alone Python program.

View file

@ -32,302 +32,302 @@ WIDTH = 6
class Array: class Array:
def __init__(self, master, data=None): def __init__(self, master, data=None):
self.master = master self.master = master
self.frame = Frame(self.master) self.frame = Frame(self.master)
self.frame.pack(fill=X) self.frame.pack(fill=X)
self.label = Label(self.frame) self.label = Label(self.frame)
self.label.pack() self.label.pack()
self.canvas = Canvas(self.frame) self.canvas = Canvas(self.frame)
self.canvas.pack() self.canvas.pack()
self.report = Label(self.frame) self.report = Label(self.frame)
self.report.pack() self.report.pack()
self.left = Line(self.canvas, 0, 0, 0, 0) self.left = Line(self.canvas, 0, 0, 0, 0)
self.right = 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.pivot = Line(self.canvas, 0, 0, 0, 0)
self.items = [] self.items = []
self.size = self.maxvalue = 0 self.size = self.maxvalue = 0
if data: if data:
self.setdata(data) self.setdata(data)
def setdata(self, data): def setdata(self, data):
olditems = self.items olditems = self.items
self.items = [] self.items = []
for item in olditems: for item in olditems:
item.delete() item.delete()
self.size = len(data) self.size = len(data)
self.maxvalue = max(data) self.maxvalue = max(data)
self.canvas.config(width=(self.size+1)*XGRID, self.canvas.config(width=(self.size+1)*XGRID,
height=(self.maxvalue+1)*YGRID) height=(self.maxvalue+1)*YGRID)
for i in range(self.size): for i in range(self.size):
self.items.append(ArrayItem(self, i, data[i])) self.items.append(ArrayItem(self, i, data[i]))
self.reset("Sort demo, size %d" % self.size) self.reset("Sort demo, size %d" % self.size)
speed = "normal" speed = "normal"
def setspeed(self, speed): def setspeed(self, speed):
self.speed = speed self.speed = speed
def destroy(self): def destroy(self):
self.frame.destroy() self.frame.destroy()
in_mainloop = 0 in_mainloop = 0
stop_mainloop = 0 stop_mainloop = 0
def cancel(self): def cancel(self):
self.stop_mainloop = 1 self.stop_mainloop = 1
if self.in_mainloop: if self.in_mainloop:
self.master.quit() self.master.quit()
def step(self): def step(self):
if self.in_mainloop: if self.in_mainloop:
self.master.quit() self.master.quit()
Cancelled = "Array.Cancelled" # Exception Cancelled = "Array.Cancelled" # Exception
def wait(self, msecs): def wait(self, msecs):
if self.speed == "fastest": if self.speed == "fastest":
msecs = 0 msecs = 0
elif self.speed == "fast": elif self.speed == "fast":
msecs = msecs/10 msecs = msecs/10
elif self.speed == "single-step": elif self.speed == "single-step":
msecs = 1000000000 msecs = 1000000000
if not self.stop_mainloop: if not self.stop_mainloop:
self.master.update() self.master.update()
id = self.master.after(msecs, self.master.quit) id = self.master.after(msecs, self.master.quit)
self.in_mainloop = 1 self.in_mainloop = 1
self.master.mainloop() self.master.mainloop()
self.master.after_cancel(id) self.master.after_cancel(id)
self.in_mainloop = 0 self.in_mainloop = 0
if self.stop_mainloop: if self.stop_mainloop:
self.stop_mainloop = 0 self.stop_mainloop = 0
self.message("Cancelled") self.message("Cancelled")
raise Array.Cancelled raise Array.Cancelled
def getsize(self): def getsize(self):
return self.size return self.size
def show_partition(self, first, last): def show_partition(self, first, last):
for i in range(self.size): for i in range(self.size):
item = self.items[i] item = self.items[i]
if first <= i < last: if first <= i < last:
item.item.config(fill='red') item.item.config(fill='red')
else: else:
item.item.config(fill='orange') item.item.config(fill='orange')
self.hide_left_right_pivot() self.hide_left_right_pivot()
def hide_partition(self): def hide_partition(self):
for i in range(self.size): for i in range(self.size):
item = self.items[i] item = self.items[i]
item.item.config(fill='red') item.item.config(fill='red')
self.hide_left_right_pivot() self.hide_left_right_pivot()
def show_left(self, left): def show_left(self, left):
if not 0 <= left < self.size: if not 0 <= left < self.size:
self.hide_left() self.hide_left()
return return
x1, y1, x2, y2 = self.items[left].position() x1, y1, x2, y2 = self.items[left].position()
## top, bot = HIRO ## top, bot = HIRO
self.left.coords([(x1-2, 0), (x1-2, 9999)]) self.left.coords([(x1-2, 0), (x1-2, 9999)])
self.master.update() self.master.update()
def show_right(self, right): def show_right(self, right):
if not 0 <= right < self.size: if not 0 <= right < self.size:
self.hide_right() self.hide_right()
return return
x1, y1, x2, y2 = self.items[right].position() x1, y1, x2, y2 = self.items[right].position()
self.right.coords(((x2+2, 0), (x2+2, 9999))) self.right.coords(((x2+2, 0), (x2+2, 9999)))
self.master.update() self.master.update()
def hide_left_right_pivot(self): def hide_left_right_pivot(self):
self.hide_left() self.hide_left()
self.hide_right() self.hide_right()
self.hide_pivot() self.hide_pivot()
def hide_left(self): def hide_left(self):
self.left.coords(((0, 0), (0, 0))) self.left.coords(((0, 0), (0, 0)))
def hide_right(self): def hide_right(self):
self.right.coords(((0, 0), (0, 0))) self.right.coords(((0, 0), (0, 0)))
def show_pivot(self, pivot): def show_pivot(self, pivot):
x1, y1, x2, y2 = self.items[pivot].position() x1, y1, x2, y2 = self.items[pivot].position()
self.pivot.coords(((0, y1-2), (9999, y1-2))) self.pivot.coords(((0, y1-2), (9999, y1-2)))
def hide_pivot(self): def hide_pivot(self):
self.pivot.coords(((0, 0), (0, 0))) self.pivot.coords(((0, 0), (0, 0)))
def swap(self, i, j): def swap(self, i, j):
if i == j: return if i == j: return
self.countswap() self.countswap()
item = self.items[i] item = self.items[i]
other = self.items[j] other = self.items[j]
self.items[i], self.items[j] = other, item self.items[i], self.items[j] = other, item
item.swapwith(other) item.swapwith(other)
def compare(self, i, j): def compare(self, i, j):
self.countcompare() self.countcompare()
item = self.items[i] item = self.items[i]
other = self.items[j] other = self.items[j]
return item.compareto(other) return item.compareto(other)
def reset(self, msg): def reset(self, msg):
self.ncompares = 0 self.ncompares = 0
self.nswaps = 0 self.nswaps = 0
self.message(msg) self.message(msg)
self.updatereport() self.updatereport()
self.hide_partition() self.hide_partition()
def message(self, msg): def message(self, msg):
self.label.config(text=msg) self.label.config(text=msg)
def countswap(self): def countswap(self):
self.nswaps = self.nswaps + 1 self.nswaps = self.nswaps + 1
self.updatereport() self.updatereport()
def countcompare(self): def countcompare(self):
self.ncompares = self.ncompares + 1 self.ncompares = self.ncompares + 1
self.updatereport() self.updatereport()
def updatereport(self): def updatereport(self):
text = "%d cmps, %d swaps" % (self.ncompares, self.nswaps) text = "%d cmps, %d swaps" % (self.ncompares, self.nswaps)
self.report.config(text=text) self.report.config(text=text)
class ArrayItem: class ArrayItem:
def __init__(self, array, index, value): def __init__(self, array, index, value):
self.array = array self.array = array
self.index = index self.index = index
self.value = value self.value = value
x1, y1, x2, y2 = self.position() x1, y1, x2, y2 = self.position()
self.item = Rectangle(array.canvas, x1, y1, x2, y2, self.item = Rectangle(array.canvas, x1, y1, x2, y2,
fill='red', outline='black', width=1) fill='red', outline='black', width=1)
self.item.bind('<Button-1>', self.mouse_down) self.item.bind('<Button-1>', self.mouse_down)
self.item.bind('<Button1-Motion>', self.mouse_move) self.item.bind('<Button1-Motion>', self.mouse_move)
self.item.bind('<ButtonRelease-1>', self.mouse_up) self.item.bind('<ButtonRelease-1>', self.mouse_up)
def delete(self): def delete(self):
item = self.item item = self.item
self.array = None self.array = None
self.item = None self.item = None
item.delete() item.delete()
def mouse_down(self, event): def mouse_down(self, event):
self.lastx = event.x self.lastx = event.x
self.lasty = event.y self.lasty = event.y
self.origx = event.x self.origx = event.x
self.origy = event.y self.origy = event.y
self.item.tkraise() self.item.tkraise()
def mouse_move(self, event): def mouse_move(self, event):
self.item.move(event.x - self.lastx, event.y - self.lasty) self.item.move(event.x - self.lastx, event.y - self.lasty)
self.lastx = event.x self.lastx = event.x
self.lasty = event.y self.lasty = event.y
def mouse_up(self, event): def mouse_up(self, event):
i = self.nearestindex(event.x) i = self.nearestindex(event.x)
if i >= self.array.getsize(): if i >= self.array.getsize():
i = self.array.getsize() - 1 i = self.array.getsize() - 1
if i < 0: if i < 0:
i = 0 i = 0
other = self.array.items[i] other = self.array.items[i]
here = self.index here = self.index
self.array.items[here], self.array.items[i] = other, self self.array.items[here], self.array.items[i] = other, self
self.index = i self.index = i
x1, y1, x2, y2 = self.position() x1, y1, x2, y2 = self.position()
self.item.coords(((x1, y1), (x2, y2))) self.item.coords(((x1, y1), (x2, y2)))
other.setindex(here) other.setindex(here)
def setindex(self, index): def setindex(self, index):
nsteps = steps(self.index, index) nsteps = steps(self.index, index)
if not nsteps: return if not nsteps: return
if self.array.speed == "fastest": if self.array.speed == "fastest":
nsteps = 0 nsteps = 0
oldpts = self.position() oldpts = self.position()
self.index = index self.index = index
newpts = self.position() newpts = self.position()
trajectory = interpolate(oldpts, newpts, nsteps) trajectory = interpolate(oldpts, newpts, nsteps)
self.item.tkraise() self.item.tkraise()
for pts in trajectory: for pts in trajectory:
self.item.coords((pts[:2], pts[2:])) self.item.coords((pts[:2], pts[2:]))
self.array.wait(50) self.array.wait(50)
def swapwith(self, other): def swapwith(self, other):
nsteps = steps(self.index, other.index) nsteps = steps(self.index, other.index)
if not nsteps: return if not nsteps: return
if self.array.speed == "fastest": if self.array.speed == "fastest":
nsteps = 0 nsteps = 0
myoldpts = self.position() myoldpts = self.position()
otheroldpts = other.position() otheroldpts = other.position()
self.index, other.index = other.index, self.index self.index, other.index = other.index, self.index
mynewpts = self.position() mynewpts = self.position()
othernewpts = other.position() othernewpts = other.position()
myfill = self.item['fill'] myfill = self.item['fill']
otherfill = other.item['fill'] otherfill = other.item['fill']
self.item.config(fill='green') self.item.config(fill='green')
other.item.config(fill='yellow') other.item.config(fill='yellow')
self.array.master.update() self.array.master.update()
if self.array.speed == "single-step": if self.array.speed == "single-step":
self.item.coords((mynewpts[:2], mynewpts[2:])) self.item.coords((mynewpts[:2], mynewpts[2:]))
other.item.coords((othernewpts[:2], othernewpts[2:])) other.item.coords((othernewpts[:2], othernewpts[2:]))
self.array.master.update() self.array.master.update()
self.item.config(fill=myfill) self.item.config(fill=myfill)
other.item.config(fill=otherfill) other.item.config(fill=otherfill)
self.array.wait(0) self.array.wait(0)
return return
mytrajectory = interpolate(myoldpts, mynewpts, nsteps) mytrajectory = interpolate(myoldpts, mynewpts, nsteps)
othertrajectory = interpolate(otheroldpts, othernewpts, nsteps) othertrajectory = interpolate(otheroldpts, othernewpts, nsteps)
if self.value > other.value: if self.value > other.value:
self.item.tkraise() self.item.tkraise()
other.item.tkraise() other.item.tkraise()
else: else:
other.item.tkraise() other.item.tkraise()
self.item.tkraise() self.item.tkraise()
try: try:
for i in range(len(mytrajectory)): for i in range(len(mytrajectory)):
mypts = mytrajectory[i] mypts = mytrajectory[i]
otherpts = othertrajectory[i] otherpts = othertrajectory[i]
self.item.coords((mypts[:2], mypts[2:])) self.item.coords((mypts[:2], mypts[2:]))
other.item.coords((otherpts[:2], otherpts[2:])) other.item.coords((otherpts[:2], otherpts[2:]))
self.array.wait(50) self.array.wait(50)
finally: finally:
mypts = mytrajectory[-1] mypts = mytrajectory[-1]
otherpts = othertrajectory[-1] otherpts = othertrajectory[-1]
self.item.coords((mypts[:2], mypts[2:])) self.item.coords((mypts[:2], mypts[2:]))
other.item.coords((otherpts[:2], otherpts[2:])) other.item.coords((otherpts[:2], otherpts[2:]))
self.item.config(fill=myfill) self.item.config(fill=myfill)
other.item.config(fill=otherfill) other.item.config(fill=otherfill)
def compareto(self, other): def compareto(self, other):
myfill = self.item['fill'] myfill = self.item['fill']
otherfill = other.item['fill'] otherfill = other.item['fill']
outcome = cmp(self.value, other.value) outcome = cmp(self.value, other.value)
if outcome < 0: if outcome < 0:
myflash = 'white' myflash = 'white'
otherflash = 'black' otherflash = 'black'
elif outcome > 0: elif outcome > 0:
myflash = 'black' myflash = 'black'
otherflash = 'white' otherflash = 'white'
else: else:
myflash = otherflash = 'grey' myflash = otherflash = 'grey'
try: try:
self.item.config(fill=myflash) self.item.config(fill=myflash)
other.item.config(fill=otherflash) other.item.config(fill=otherflash)
self.array.wait(500) self.array.wait(500)
finally: finally:
self.item.config(fill=myfill) self.item.config(fill=myfill)
other.item.config(fill=otherfill) other.item.config(fill=otherfill)
return outcome return outcome
def position(self): def position(self):
x1 = (self.index+1)*XGRID - WIDTH/2 x1 = (self.index+1)*XGRID - WIDTH/2
x2 = x1+WIDTH x2 = x1+WIDTH
y2 = (self.array.maxvalue+1)*YGRID y2 = (self.array.maxvalue+1)*YGRID
y1 = y2 - (self.value)*YGRID y1 = y2 - (self.value)*YGRID
return x1, y1, x2, y2 return x1, y1, x2, y2
def nearestindex(self, x): 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 # Subroutines that don't need an object
@ -335,22 +335,22 @@ class ArrayItem:
def steps(here, there): def steps(here, there):
nsteps = abs(here - there) nsteps = abs(here - there)
if nsteps <= 3: if nsteps <= 3:
nsteps = nsteps * 3 nsteps = nsteps * 3
elif nsteps <= 5: elif nsteps <= 5:
nsteps = nsteps * 2 nsteps = nsteps * 2
elif nsteps > 10: elif nsteps > 10:
nsteps = 10 nsteps = 10
return nsteps return nsteps
def interpolate(oldpts, newpts, n): def interpolate(oldpts, newpts, n):
if len(oldpts) != len(newpts): 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) pts = [0]*len(oldpts)
res = [tuple(oldpts)] res = [tuple(oldpts)]
for i in range(1, n): for i in range(1, n):
for k in range(len(pts)): for k in range(len(pts)):
pts[k] = oldpts[k] + (newpts[k] - oldpts[k])*i/n pts[k] = oldpts[k] + (newpts[k] - oldpts[k])*i/n
res.append(tuple(pts)) res.append(tuple(pts))
res.append(tuple(newpts)) res.append(tuple(newpts))
return res return res
@ -371,110 +371,110 @@ def randomize(array):
array.reset("Randomizing") array.reset("Randomizing")
n = array.getsize() n = array.getsize()
for i in range(n): for i in range(n):
j = random.randint(0, n-1) j = random.randint(0, n-1)
array.swap(i, j) array.swap(i, j)
array.message("Randomized") array.message("Randomized")
def insertionsort(array): def insertionsort(array):
size = array.getsize() size = array.getsize()
array.reset("Insertion sort") array.reset("Insertion sort")
for i in range(1, size): for i in range(1, size):
j = i-1 j = i-1
while j >= 0: while j >= 0:
if array.compare(j, j+1) <= 0: if array.compare(j, j+1) <= 0:
break break
array.swap(j, j+1) array.swap(j, j+1)
j = j-1 j = j-1
array.message("Sorted") array.message("Sorted")
def selectionsort(array): def selectionsort(array):
size = array.getsize() size = array.getsize()
array.reset("Selection sort") array.reset("Selection sort")
try: try:
for i in range(size): for i in range(size):
array.show_partition(i, size) array.show_partition(i, size)
for j in range(i+1, size): for j in range(i+1, size):
if array.compare(i, j) > 0: if array.compare(i, j) > 0:
array.swap(i, j) array.swap(i, j)
array.message("Sorted") array.message("Sorted")
finally: finally:
array.hide_partition() array.hide_partition()
def bubblesort(array): def bubblesort(array):
size = array.getsize() size = array.getsize()
array.reset("Bubble sort") array.reset("Bubble sort")
for i in range(size): for i in range(size):
for j in range(1, size): for j in range(1, size):
if array.compare(j-1, j) > 0: if array.compare(j-1, j) > 0:
array.swap(j-1, j) array.swap(j-1, j)
array.message("Sorted") array.message("Sorted")
def quicksort(array): def quicksort(array):
size = array.getsize() size = array.getsize()
array.reset("Quicksort") array.reset("Quicksort")
try: try:
stack = [(0, size)] stack = [(0, size)]
while stack: while stack:
first, last = stack[-1] first, last = stack[-1]
del stack[-1] del stack[-1]
array.show_partition(first, last) array.show_partition(first, last)
if last-first < 5: if last-first < 5:
array.message("Insertion sort") array.message("Insertion sort")
for i in range(first+1, last): for i in range(first+1, last):
j = i-1 j = i-1
while j >= first: while j >= first:
if array.compare(j, j+1) <= 0: if array.compare(j, j+1) <= 0:
break break
array.swap(j, j+1) array.swap(j, j+1)
j = j-1 j = j-1
continue continue
array.message("Choosing pivot") array.message("Choosing pivot")
j, i, k = first, (first+last)/2, last-1 j, i, k = first, (first+last)/2, last-1
if array.compare(k, i) < 0: if array.compare(k, i) < 0:
array.swap(k, i) array.swap(k, i)
if array.compare(k, j) < 0: if array.compare(k, j) < 0:
array.swap(k, j) array.swap(k, j)
if array.compare(j, i) < 0: if array.compare(j, i) < 0:
array.swap(j, i) array.swap(j, i)
pivot = j pivot = j
array.show_pivot(pivot) array.show_pivot(pivot)
array.message("Pivot at left of partition") array.message("Pivot at left of partition")
array.wait(1000) array.wait(1000)
left = first left = first
right = last right = last
while 1: while 1:
array.message("Sweep right pointer") array.message("Sweep right pointer")
right = right-1 right = right-1
array.show_right(right) array.show_right(right)
while right > first and array.compare(right, pivot) >= 0: while right > first and array.compare(right, pivot) >= 0:
right = right-1 right = right-1
array.show_right(right) array.show_right(right)
array.message("Sweep left pointer") array.message("Sweep left pointer")
left = left+1 left = left+1
array.show_left(left) array.show_left(left)
while left < last and array.compare(left, pivot) <= 0: while left < last and array.compare(left, pivot) <= 0:
left = left+1 left = left+1
array.show_left(left) array.show_left(left)
if left > right: if left > right:
array.message("End of partition") array.message("End of partition")
break break
array.message("Swap items") array.message("Swap items")
array.swap(left, right) array.swap(left, right)
array.message("Swap pivot back") array.message("Swap pivot back")
array.swap(pivot, right) array.swap(pivot, right)
n1 = right-first n1 = right-first
n2 = last-left n2 = last-left
if n1 > 1: stack.append((first, right)) if n1 > 1: stack.append((first, right))
if n2 > 1: stack.append((left, last)) if n2 > 1: stack.append((left, last))
array.message("Sorted") array.message("Sorted")
finally: finally:
array.hide_partition() array.hide_partition()
def demosort(array): def demosort(array):
while 1: while 1:
for alg in [quicksort, insertionsort, selectionsort, bubblesort]: for alg in [quicksort, insertionsort, selectionsort, bubblesort]:
randomize(array) randomize(array)
alg(array) alg(array)
# Sort demo class -- usable as a Grail applet # Sort demo class -- usable as a Grail applet
@ -482,144 +482,144 @@ def demosort(array):
class SortDemo: class SortDemo:
def __init__(self, master, size=15): def __init__(self, master, size=15):
self.master = master self.master = master
self.size = size self.size = size
self.busy = 0 self.busy = 0
self.array = Array(self.master) self.array = Array(self.master)
self.botframe = Frame(master) self.botframe = Frame(master)
self.botframe.pack(side=BOTTOM) self.botframe.pack(side=BOTTOM)
self.botleftframe = Frame(self.botframe) self.botleftframe = Frame(self.botframe)
self.botleftframe.pack(side=LEFT, fill=Y) self.botleftframe.pack(side=LEFT, fill=Y)
self.botrightframe = Frame(self.botframe) self.botrightframe = Frame(self.botframe)
self.botrightframe.pack(side=RIGHT, fill=Y) self.botrightframe.pack(side=RIGHT, fill=Y)
self.b_qsort = Button(self.botleftframe, self.b_qsort = Button(self.botleftframe,
text="Quicksort", command=self.c_qsort) text="Quicksort", command=self.c_qsort)
self.b_qsort.pack(fill=X) self.b_qsort.pack(fill=X)
self.b_isort = Button(self.botleftframe, self.b_isort = Button(self.botleftframe,
text="Insertion sort", command=self.c_isort) text="Insertion sort", command=self.c_isort)
self.b_isort.pack(fill=X) self.b_isort.pack(fill=X)
self.b_ssort = Button(self.botleftframe, self.b_ssort = Button(self.botleftframe,
text="Selection sort", command=self.c_ssort) text="Selection sort", command=self.c_ssort)
self.b_ssort.pack(fill=X) self.b_ssort.pack(fill=X)
self.b_bsort = Button(self.botleftframe, self.b_bsort = Button(self.botleftframe,
text="Bubble sort", command=self.c_bsort) text="Bubble sort", command=self.c_bsort)
self.b_bsort.pack(fill=X) self.b_bsort.pack(fill=X)
# Terrible hack to overcome limitation of OptionMenu... # Terrible hack to overcome limitation of OptionMenu...
class MyIntVar(IntVar): class MyIntVar(IntVar):
def __init__(self, master, demo): def __init__(self, master, demo):
self.demo = demo self.demo = demo
IntVar.__init__(self, master) IntVar.__init__(self, master)
def set(self, value): def set(self, value):
IntVar.set(self, value) IntVar.set(self, value)
if str(value) != '0': if str(value) != '0':
self.demo.resize(value) self.demo.resize(value)
self.v_size = MyIntVar(self.master, self) self.v_size = MyIntVar(self.master, self)
self.v_size.set(size) self.v_size.set(size)
sizes = [1, 2, 3, 4] + range(5, 55, 5) sizes = [1, 2, 3, 4] + range(5, 55, 5)
if self.size not in sizes: if self.size not in sizes:
sizes.append(self.size) sizes.append(self.size)
sizes.sort() sizes.sort()
self.m_size = apply(OptionMenu, self.m_size = apply(OptionMenu,
(self.botleftframe, self.v_size) + tuple(sizes)) (self.botleftframe, self.v_size) + tuple(sizes))
self.m_size.pack(fill=X) self.m_size.pack(fill=X)
self.v_speed = StringVar(self.master) self.v_speed = StringVar(self.master)
self.v_speed.set("normal") self.v_speed.set("normal")
self.m_speed = OptionMenu(self.botleftframe, self.v_speed, self.m_speed = OptionMenu(self.botleftframe, self.v_speed,
"single-step", "normal", "fast", "fastest") "single-step", "normal", "fast", "fastest")
self.m_speed.pack(fill=X) self.m_speed.pack(fill=X)
self.b_step = Button(self.botleftframe, self.b_step = Button(self.botleftframe,
text="Step", command=self.c_step) text="Step", command=self.c_step)
self.b_step.pack(fill=X) self.b_step.pack(fill=X)
self.b_randomize = Button(self.botrightframe, self.b_randomize = Button(self.botrightframe,
text="Randomize", command=self.c_randomize) text="Randomize", command=self.c_randomize)
self.b_randomize.pack(fill=X) self.b_randomize.pack(fill=X)
self.b_uniform = Button(self.botrightframe, self.b_uniform = Button(self.botrightframe,
text="Uniform", command=self.c_uniform) text="Uniform", command=self.c_uniform)
self.b_uniform.pack(fill=X) self.b_uniform.pack(fill=X)
self.b_distinct = Button(self.botrightframe, self.b_distinct = Button(self.botrightframe,
text="Distinct", command=self.c_distinct) text="Distinct", command=self.c_distinct)
self.b_distinct.pack(fill=X) self.b_distinct.pack(fill=X)
self.b_demo = Button(self.botrightframe, self.b_demo = Button(self.botrightframe,
text="Demo", command=self.c_demo) text="Demo", command=self.c_demo)
self.b_demo.pack(fill=X) self.b_demo.pack(fill=X)
self.b_cancel = Button(self.botrightframe, self.b_cancel = Button(self.botrightframe,
text="Cancel", command=self.c_cancel) text="Cancel", command=self.c_cancel)
self.b_cancel.pack(fill=X) self.b_cancel.pack(fill=X)
self.b_cancel.config(state=DISABLED) self.b_cancel.config(state=DISABLED)
self.b_quit = Button(self.botrightframe, self.b_quit = Button(self.botrightframe,
text="Quit", command=self.c_quit) text="Quit", command=self.c_quit)
self.b_quit.pack(fill=X) self.b_quit.pack(fill=X)
def resize(self, newsize): def resize(self, newsize):
if self.busy: if self.busy:
self.master.bell() self.master.bell()
return return
self.size = newsize self.size = newsize
self.array.setdata(range(1, self.size+1)) self.array.setdata(range(1, self.size+1))
def c_qsort(self): def c_qsort(self):
self.run(quicksort) self.run(quicksort)
def c_isort(self): def c_isort(self):
self.run(insertionsort) self.run(insertionsort)
def c_ssort(self): def c_ssort(self):
self.run(selectionsort) self.run(selectionsort)
def c_bsort(self): def c_bsort(self):
self.run(bubblesort) self.run(bubblesort)
def c_demo(self): def c_demo(self):
self.run(demosort) self.run(demosort)
def c_randomize(self): def c_randomize(self):
self.run(randomize) self.run(randomize)
def c_uniform(self): def c_uniform(self):
self.run(uniform) self.run(uniform)
def c_distinct(self): def c_distinct(self):
self.run(distinct) self.run(distinct)
def run(self, func): def run(self, func):
if self.busy: if self.busy:
self.master.bell() self.master.bell()
return return
self.busy = 1 self.busy = 1
self.array.setspeed(self.v_speed.get()) self.array.setspeed(self.v_speed.get())
self.b_cancel.config(state=NORMAL) self.b_cancel.config(state=NORMAL)
try: try:
func(self.array) func(self.array)
except Array.Cancelled: except Array.Cancelled:
pass pass
self.b_cancel.config(state=DISABLED) self.b_cancel.config(state=DISABLED)
self.busy = 0 self.busy = 0
def c_cancel(self): def c_cancel(self):
if not self.busy: if not self.busy:
self.master.bell() self.master.bell()
return return
self.array.cancel() self.array.cancel()
def c_step(self): def c_step(self):
if not self.busy: if not self.busy:
self.master.bell() self.master.bell()
return return
self.v_speed.set("single-step") self.v_speed.set("single-step")
self.array.setspeed("single-step") self.array.setspeed("single-step")
self.array.step() self.array.step()
def c_quit(self): def c_quit(self):
if self.busy: if self.busy:
self.array.cancel() self.array.cancel()
self.master.after_idle(self.master.quit) self.master.after_idle(self.master.quit)
# Main program -- for stand-alone operation outside Grail # Main program -- for stand-alone operation outside Grail

View file

@ -5,7 +5,7 @@
from Tkinter import * from Tkinter import *
if TkVersion < 4.0: 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 splitfields
from string import split from string import split
@ -15,114 +15,114 @@ import os
user = os.environ['LOGNAME'] user = os.environ['LOGNAME']
class BarButton(Menubutton): class BarButton(Menubutton):
def __init__(self, master=None, **cnf): def __init__(self, master=None, **cnf):
apply(Menubutton.__init__, (self, master), cnf) apply(Menubutton.__init__, (self, master), cnf)
self.pack(side=LEFT) self.pack(side=LEFT)
self.menu = Menu(self, name='menu') self.menu = Menu(self, name='menu')
self['menu'] = self.menu self['menu'] = self.menu
class Kill(Frame): class Kill(Frame):
# List of (name, option, pid_column) # List of (name, option, pid_column)
view_list = [ view_list = [
('Default', ''), ('Default', ''),
('Every (-e)', '-e'), ('Every (-e)', '-e'),
('Non process group leaders (-d)', '-d'), ('Non process group leaders (-d)', '-d'),
('Non leaders with tty (-a)', '-a'), ('Non leaders with tty (-a)', '-a'),
('For this user (-u %s)' % user, '-u %s' % user), ('For this user (-u %s)' % user, '-u %s' % user),
] ]
format_list = [ format_list = [
('Default', '', 0), ('Default', '', 0),
('Long (-l)', '-l', 3), ('Long (-l)', '-l', 3),
('Full (-f)', '-f', 1), ('Full (-f)', '-f', 1),
('Full Long (-f -l)', '-l -f', 3), ('Full Long (-f -l)', '-l -f', 3),
('Session and group ID (-j)', '-j', 0), ('Session and group ID (-j)', '-j', 0),
('Scheduler properties (-c)', '-c', 0), ('Scheduler properties (-c)', '-c', 0),
] ]
def kill(self, selected): def kill(self, selected):
c = self.format_list[self.format.get()][2] c = self.format_list[self.format.get()][2]
pid = split(selected)[c] pid = split(selected)[c]
os.system('kill -9 ' + pid) os.system('kill -9 ' + pid)
self.do_update() self.do_update()
def do_update(self): def do_update(self):
format = self.format_list[self.format.get()][1] format = self.format_list[self.format.get()][1]
view = self.view_list[self.view.get()][1] view = self.view_list[self.view.get()][1]
s = commands.getoutput('ps %s %s' % (view, format)) s = commands.getoutput('ps %s %s' % (view, format))
list = splitfields(s, '\n') list = splitfields(s, '\n')
self.header.set(list[0] + ' ') self.header.set(list[0] + ' ')
del list[0] del list[0]
self.frame.list.delete(0, AtEnd()) self.frame.list.delete(0, AtEnd())
for line in list: for line in list:
self.frame.list.insert(0, line) self.frame.list.insert(0, line)
def do_motion(self, e): def do_motion(self, e):
e.widget.select_clear('0', 'end') e.widget.select_clear('0', 'end')
e.widget.select_set(e.widget.nearest(e.y)) e.widget.select_set(e.widget.nearest(e.y))
def do_leave(self, e): def do_leave(self, e):
e.widget.select_clear('0', 'end') e.widget.select_clear('0', 'end')
def do_1(self, e): def do_1(self, e):
self.kill(e.widget.get(e.widget.nearest(e.y))) self.kill(e.widget.get(e.widget.nearest(e.y)))
def __init__(self, master=None, **cnf): def __init__(self, master=None, **cnf):
apply(Frame.__init__, (self, master), cnf) apply(Frame.__init__, (self, master), cnf)
self.pack(expand=1, fill=BOTH) self.pack(expand=1, fill=BOTH)
self.bar = Frame(self, name='bar', relief=RAISED, self.bar = Frame(self, name='bar', relief=RAISED,
borderwidth=2) borderwidth=2)
self.bar.pack(fill=X) self.bar.pack(fill=X)
self.bar.file = BarButton(self.bar, text='File') self.bar.file = BarButton(self.bar, text='File')
self.bar.file.menu.add_command( self.bar.file.menu.add_command(
label='Quit', command=self.quit) label='Quit', command=self.quit)
self.bar.view = BarButton(self.bar, text='View') self.bar.view = BarButton(self.bar, text='View')
self.bar.format = BarButton(self.bar, text='Format') self.bar.format = BarButton(self.bar, text='Format')
self.view = IntVar(self) self.view = IntVar(self)
self.view.set(0) self.view.set(0)
self.format = IntVar(self) self.format = IntVar(self)
self.format.set(0) self.format.set(0)
for num in range(len(self.view_list)): for num in range(len(self.view_list)):
label, option = self.view_list[num] label, option = self.view_list[num]
self.bar.view.menu.add_radiobutton( self.bar.view.menu.add_radiobutton(
label=label, label=label,
command=self.do_update, command=self.do_update,
variable=self.view, variable=self.view,
value=num) value=num)
for num in range(len(self.format_list)): for num in range(len(self.format_list)):
label, option, col = self.format_list[num] label, option, col = self.format_list[num]
self.bar.format.menu.add_radiobutton( self.bar.format.menu.add_radiobutton(
label=label, label=label,
command=self.do_update, command=self.do_update,
variable=self.format, variable=self.format,
value=num) value=num)
self.bar.tk_menuBar(self.bar.file, self.bar.tk_menuBar(self.bar.file,
self.bar.view, self.bar.view,
self.bar.format) self.bar.format)
self.frame = Frame(self, relief=RAISED, borderwidth=2) self.frame = Frame(self, relief=RAISED, borderwidth=2)
self.frame.pack(expand=1, fill=BOTH) self.frame.pack(expand=1, fill=BOTH)
self.header = StringVar(self) self.header = StringVar(self)
self.frame.label = Label( self.frame.label = Label(
self.frame, relief=FLAT, anchor=NW, borderwidth=0, self.frame, relief=FLAT, anchor=NW, borderwidth=0,
font='*-Courier-Bold-R-Normal-*-120-*', font='*-Courier-Bold-R-Normal-*-120-*',
textvariable=self.header) textvariable=self.header)
self.frame.label.pack(fill=Y, anchor=W) self.frame.label.pack(fill=Y, anchor=W)
self.frame.vscroll = Scrollbar(self.frame, orient=VERTICAL) self.frame.vscroll = Scrollbar(self.frame, orient=VERTICAL)
self.frame.list = Listbox( self.frame.list = Listbox(
self.frame, self.frame,
relief=SUNKEN, relief=SUNKEN,
font='*-Courier-Medium-R-Normal-*-120-*', font='*-Courier-Medium-R-Normal-*-120-*',
width=40, height=10, width=40, height=10,
selectbackground='#eed5b7', selectbackground='#eed5b7',
selectborderwidth=0, selectborderwidth=0,
selectmode=BROWSE, selectmode=BROWSE,
yscroll=self.frame.vscroll.set) yscroll=self.frame.vscroll.set)
self.frame.vscroll['command'] = self.frame.list.yview self.frame.vscroll['command'] = self.frame.list.yview
self.frame.vscroll.pack(side=RIGHT, fill=Y) self.frame.vscroll.pack(side=RIGHT, fill=Y)
self.frame.list.pack(expand=1, fill=BOTH) self.frame.list.pack(expand=1, fill=BOTH)
self.update = Button(self, text='Update', self.update = Button(self, text='Update',
command=self.do_update) command=self.do_update)
self.update.pack(fill=X) self.update.pack(fill=X)
self.frame.list.bind('<Motion>', self.do_motion) self.frame.list.bind('<Motion>', self.do_motion)
self.frame.list.bind('<Leave>', self.do_leave) self.frame.list.bind('<Leave>', self.do_leave)
self.frame.list.bind('<1>', self.do_1) self.frame.list.bind('<1>', self.do_1)
self.do_update() self.do_update()
if __name__ == '__main__': if __name__ == '__main__':
kill = Kill(None, borderwidth=5) kill = Kill(None, borderwidth=5)
kill.winfo_toplevel().title('Tkinter Process Killer (SYSV)') kill.winfo_toplevel().title('Tkinter Process Killer (SYSV)')
kill.winfo_toplevel().minsize(1, 1) kill.winfo_toplevel().minsize(1, 1)
kill.mainloop() kill.mainloop()

View file

@ -15,253 +15,253 @@ MAN3DIRLIST = ['/depot/sundry/man/man3','/usr/local/man/man3']
foundmanndir = 0 foundmanndir = 0
for dir in MANNDIRLIST: for dir in MANNDIRLIST:
if os.path.exists(dir): if os.path.exists(dir):
MANNDIR = dir MANNDIR = dir
foundmanndir = 1 foundmanndir = 1
foundman3dir = 0 foundman3dir = 0
for dir in MAN3DIRLIST: for dir in MAN3DIRLIST:
if os.path.exists(dir): if os.path.exists(dir):
MAN3DIR = dir MAN3DIR = dir
foundman3dir = 1 foundman3dir = 1
if not foundmanndir or not foundman3dir: if not foundmanndir or not foundman3dir:
sys.stderr.write('\n') sys.stderr.write('\n')
if not foundmanndir: if not foundmanndir:
msg = """\ msg = """\
Failed to find mann directory. 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.""" % \ at the top of %s script.""" % \
sys.argv[0] sys.argv[0]
sys.stderr.write("%s\n\n" % msg) sys.stderr.write("%s\n\n" % msg)
if not foundman3dir: if not foundman3dir:
msg = """\ msg = """\
Failed to find man3 directory. 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.""" % \ at the top of %s script.""" % \
sys.argv[0] sys.argv[0]
sys.stderr.write("%s\n\n" % msg) sys.stderr.write("%s\n\n" % msg)
sys.exit(1) sys.exit(1)
del foundmanndir del foundmanndir
del foundman3dir del foundman3dir
def listmanpages(mandir): def listmanpages(mandir):
files = os.listdir(mandir) files = os.listdir(mandir)
names = [] names = []
for file in files: for file in files:
if file[-2:-1] == '.' and (file[-1] in 'ln123456789'): if file[-2:-1] == '.' and (file[-1] in 'ln123456789'):
names.append(file[:-2]) names.append(file[:-2])
names.sort() names.sort()
return names return names
class SelectionBox: class SelectionBox:
def __init__(self, master=None): def __init__(self, master=None):
self.choices = [] self.choices = []
self.frame = Frame(master, name="frame") self.frame = Frame(master, name="frame")
self.frame.pack(expand=1, fill=BOTH) self.frame.pack(expand=1, fill=BOTH)
self.master = self.frame.master self.master = self.frame.master
self.subframe = Frame(self.frame, name="subframe") self.subframe = Frame(self.frame, name="subframe")
self.subframe.pack(expand=0, fill=BOTH) self.subframe.pack(expand=0, fill=BOTH)
self.leftsubframe = Frame(self.subframe, name='leftsubframe') self.leftsubframe = Frame(self.subframe, name='leftsubframe')
self.leftsubframe.pack(side=LEFT, expand=1, fill=BOTH) self.leftsubframe.pack(side=LEFT, expand=1, fill=BOTH)
self.rightsubframe = Frame(self.subframe, name='rightsubframe') self.rightsubframe = Frame(self.subframe, name='rightsubframe')
self.rightsubframe.pack(side=RIGHT, expand=1, fill=BOTH) self.rightsubframe.pack(side=RIGHT, expand=1, fill=BOTH)
self.chaptervar = StringVar(master) self.chaptervar = StringVar(master)
self.chapter = Menubutton(self.rightsubframe, name='chapter', self.chapter = Menubutton(self.rightsubframe, name='chapter',
text='Directory', relief=RAISED, text='Directory', relief=RAISED,
borderwidth=2) borderwidth=2)
self.chapter.pack(side=TOP) self.chapter.pack(side=TOP)
self.chaptermenu = Menu(self.chapter, name='chaptermenu') self.chaptermenu = Menu(self.chapter, name='chaptermenu')
self.chaptermenu.add_radiobutton(label='C functions', self.chaptermenu.add_radiobutton(label='C functions',
value=MAN3DIR, value=MAN3DIR,
variable=self.chaptervar, variable=self.chaptervar,
command=self.newchapter) command=self.newchapter)
self.chaptermenu.add_radiobutton(label='Tcl/Tk functions', self.chaptermenu.add_radiobutton(label='Tcl/Tk functions',
value=MANNDIR, value=MANNDIR,
variable=self.chaptervar, variable=self.chaptervar,
command=self.newchapter) command=self.newchapter)
self.chapter['menu'] = self.chaptermenu self.chapter['menu'] = self.chaptermenu
self.listbox = Listbox(self.rightsubframe, name='listbox', self.listbox = Listbox(self.rightsubframe, name='listbox',
relief=SUNKEN, borderwidth=2, relief=SUNKEN, borderwidth=2,
width=20, height=5) width=20, height=5)
self.listbox.pack(expand=1, fill=BOTH) self.listbox.pack(expand=1, fill=BOTH)
self.l1 = Button(self.leftsubframe, name='l1', self.l1 = Button(self.leftsubframe, name='l1',
text='Display manual page named:', text='Display manual page named:',
command=self.entry_cb) command=self.entry_cb)
self.l1.pack(side=TOP) self.l1.pack(side=TOP)
self.entry = Entry(self.leftsubframe, name='entry', self.entry = Entry(self.leftsubframe, name='entry',
relief=SUNKEN, borderwidth=2, relief=SUNKEN, borderwidth=2,
width=20) width=20)
self.entry.pack(expand=0, fill=X) self.entry.pack(expand=0, fill=X)
self.l2frame = Frame(self.leftsubframe, name='l2frame') self.l2frame = Frame(self.leftsubframe, name='l2frame')
self.l2frame.pack(expand=0, fill=NONE) self.l2frame.pack(expand=0, fill=NONE)
self.l2 = Button(self.l2frame, name='l2', self.l2 = Button(self.l2frame, name='l2',
text='Search regexp:', text='Search regexp:',
command=self.search_cb) command=self.search_cb)
self.l2.pack(side=LEFT) self.l2.pack(side=LEFT)
self.casevar = BooleanVar() self.casevar = BooleanVar()
self.casesense = Checkbutton(self.l2frame, name='casesense', self.casesense = Checkbutton(self.l2frame, name='casesense',
text='Case sensitive', text='Case sensitive',
variable=self.casevar, variable=self.casevar,
relief=FLAT) relief=FLAT)
self.casesense.pack(side=LEFT) self.casesense.pack(side=LEFT)
self.search = Entry(self.leftsubframe, name='search', self.search = Entry(self.leftsubframe, name='search',
relief=SUNKEN, borderwidth=2, relief=SUNKEN, borderwidth=2,
width=20) width=20)
self.search.pack(expand=0, fill=X) self.search.pack(expand=0, fill=X)
self.title = Label(self.leftsubframe, name='title', self.title = Label(self.leftsubframe, name='title',
text='(none)') text='(none)')
self.title.pack(side=BOTTOM) self.title.pack(side=BOTTOM)
self.text = ManPage(self.frame, name='text', self.text = ManPage(self.frame, name='text',
relief=SUNKEN, borderwidth=2, relief=SUNKEN, borderwidth=2,
wrap=NONE, width=72, wrap=NONE, width=72,
selectbackground='pink') selectbackground='pink')
self.text.pack(expand=1, fill=BOTH) self.text.pack(expand=1, fill=BOTH)
self.entry.bind('<Return>', self.entry_cb) self.entry.bind('<Return>', self.entry_cb)
self.search.bind('<Return>', self.search_cb) self.search.bind('<Return>', self.search_cb)
self.listbox.bind('<Double-1>', self.listbox_cb) self.listbox.bind('<Double-1>', self.listbox_cb)
self.entry.bind('<Tab>', self.entry_tab) self.entry.bind('<Tab>', self.entry_tab)
self.search.bind('<Tab>', self.search_tab) self.search.bind('<Tab>', self.search_tab)
self.text.bind('<Tab>', self.text_tab) self.text.bind('<Tab>', self.text_tab)
self.entry.focus_set() self.entry.focus_set()
self.chaptervar.set(MANNDIR) self.chaptervar.set(MANNDIR)
self.newchapter() self.newchapter()
def newchapter(self): def newchapter(self):
mandir = self.chaptervar.get() mandir = self.chaptervar.get()
self.choices = [] self.choices = []
self.addlist(listmanpages(mandir)) self.addlist(listmanpages(mandir))
def addchoice(self, choice): def addchoice(self, choice):
if choice not in self.choices: if choice not in self.choices:
self.choices.append(choice) self.choices.append(choice)
self.choices.sort() self.choices.sort()
self.update() self.update()
def addlist(self, list): def addlist(self, list):
self.choices[len(self.choices):] = list self.choices[len(self.choices):] = list
self.choices.sort() self.choices.sort()
self.update() self.update()
def entry_cb(self, *e): def entry_cb(self, *e):
self.update() self.update()
def listbox_cb(self, e): def listbox_cb(self, e):
selection = self.listbox.curselection() selection = self.listbox.curselection()
if selection and len(selection) == 1: if selection and len(selection) == 1:
name = self.listbox.get(selection[0]) name = self.listbox.get(selection[0])
self.show_page(name) self.show_page(name)
def search_cb(self, *e): def search_cb(self, *e):
self.search_string(self.search.get()) self.search_string(self.search.get())
def entry_tab(self, e): def entry_tab(self, e):
self.search.focus_set() self.search.focus_set()
def search_tab(self, e): def search_tab(self, e):
self.entry.focus_set() self.entry.focus_set()
def text_tab(self, e): def text_tab(self, e):
self.entry.focus_set() self.entry.focus_set()
def updatelist(self): def updatelist(self):
key = self.entry.get() key = self.entry.get()
ok = filter(lambda name, key=key, n=len(key): name[:n]==key, ok = filter(lambda name, key=key, n=len(key): name[:n]==key,
self.choices) self.choices)
if not ok: if not ok:
self.frame.bell() self.frame.bell()
self.listbox.delete(0, AtEnd()) self.listbox.delete(0, AtEnd())
exactmatch = 0 exactmatch = 0
for item in ok: for item in ok:
if item == key: exactmatch = 1 if item == key: exactmatch = 1
self.listbox.insert(AtEnd(), item) self.listbox.insert(AtEnd(), item)
if exactmatch: if exactmatch:
return key return key
n = self.listbox.size() n = self.listbox.size()
if n == 1: if n == 1:
return self.listbox.get(0) return self.listbox.get(0)
# Else return None, meaning not a unique selection # Else return None, meaning not a unique selection
def update(self): def update(self):
name = self.updatelist() name = self.updatelist()
if name: if name:
self.show_page(name) self.show_page(name)
self.entry.delete(0, AtEnd()) self.entry.delete(0, AtEnd())
self.updatelist() self.updatelist()
def show_page(self, name): def show_page(self, name):
file = '%s/%s.?' % (self.chaptervar.get(), name) file = '%s/%s.?' % (self.chaptervar.get(), name)
fp = os.popen('nroff -man %s | ul -i' % file, 'r') fp = os.popen('nroff -man %s | ul -i' % file, 'r')
self.text.kill() self.text.kill()
self.title['text'] = name self.title['text'] = name
self.text.parsefile(fp) self.text.parsefile(fp)
def search_string(self, search): def search_string(self, search):
if not search: if not search:
self.frame.bell() self.frame.bell()
print 'Empty search string' print 'Empty search string'
return return
if not self.casevar.get(): if not self.casevar.get():
map = regex.casefold map = regex.casefold
else: else:
map = None map = None
try: try:
if map: if map:
prog = regex.compile(search, map) prog = regex.compile(search, map)
else: else:
prog = regex.compile(search) prog = regex.compile(search)
except regex.error, msg: except regex.error, msg:
self.frame.bell() self.frame.bell()
print 'Regex error:', msg print 'Regex error:', msg
return return
here = self.text.index(AtInsert()) here = self.text.index(AtInsert())
lineno = string.atoi(here[:string.find(here, '.')]) lineno = string.atoi(here[:string.find(here, '.')])
end = self.text.index(AtEnd()) end = self.text.index(AtEnd())
endlineno = string.atoi(end[:string.find(end, '.')]) endlineno = string.atoi(end[:string.find(end, '.')])
wraplineno = lineno wraplineno = lineno
found = 0 found = 0
while 1: while 1:
lineno = lineno + 1 lineno = lineno + 1
if lineno > endlineno: if lineno > endlineno:
if wraplineno <= 0: if wraplineno <= 0:
break break
endlineno = wraplineno endlineno = wraplineno
lineno = 0 lineno = 0
wraplineno = 0 wraplineno = 0
line = self.text.get('%d.0 linestart' % lineno, line = self.text.get('%d.0 linestart' % lineno,
'%d.0 lineend' % lineno) '%d.0 lineend' % lineno)
i = prog.search(line) i = prog.search(line)
if i >= 0: if i >= 0:
found = 1 found = 1
n = max(1, len(prog.group(0))) n = max(1, len(prog.group(0)))
try: try:
self.text.tag_remove('sel', self.text.tag_remove('sel',
AtSelFirst(), AtSelFirst(),
AtSelLast()) AtSelLast())
except TclError: except TclError:
pass pass
self.text.tag_add('sel', self.text.tag_add('sel',
'%d.%d' % (lineno, i), '%d.%d' % (lineno, i),
'%d.%d' % (lineno, i+n)) '%d.%d' % (lineno, i+n))
self.text.mark_set(AtInsert(), self.text.mark_set(AtInsert(),
'%d.%d' % (lineno, i)) '%d.%d' % (lineno, i))
self.text.yview_pickplace(AtInsert()) self.text.yview_pickplace(AtInsert())
break break
if not found: if not found:
self.frame.bell() self.frame.bell()
def main(): def main():
root = Tk() root = Tk()
sb = SelectionBox(root) sb = SelectionBox(root)
if sys.argv[1:]: if sys.argv[1:]:
sb.show_page(sys.argv[1]) sb.show_page(sys.argv[1])
root.minsize(1, 1) root.minsize(1, 1)
root.mainloop() root.mainloop()
main() main()

View file

@ -9,19 +9,19 @@ tk.call('update')
cmd = '' cmd = ''
while 1: while 1:
if cmd: prompt = '' if cmd: prompt = ''
else: prompt = '% ' else: prompt = '% '
try: try:
line = raw_input(prompt) line = raw_input(prompt)
except EOFError: except EOFError:
break break
cmd = cmd + (line + '\n') cmd = cmd + (line + '\n')
if tk.getboolean(tk.call('info', 'complete', cmd)): if tk.getboolean(tk.call('info', 'complete', cmd)):
tk.record(line) tk.record(line)
try: try:
result = tk.call('eval', cmd) result = tk.call('eval', cmd)
except _tkinter.TclError, msg: except _tkinter.TclError, msg:
print 'TclError:', msg print 'TclError:', msg
else: else:
if result: print result if result: print result
cmd = '' cmd = ''

View file

@ -5,23 +5,23 @@ from Tkinter import *
class Test(Frame): class Test(Frame):
def printit(self): def printit(self):
print "hi" print "hi"
def createWidgets(self): def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red', self.QUIT = Button(self, text='QUIT', foreground='red',
command=self.quit) command=self.quit)
self.QUIT.pack(side=LEFT, fill=BOTH) self.QUIT.pack(side=LEFT, fill=BOTH)
# a hello button # a hello button
self.hi_there = Button(self, text='Hello', self.hi_there = Button(self, text='Hello',
command=self.printit) command=self.printit)
self.hi_there.pack(side=LEFT) self.hi_there.pack(side=LEFT)
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.createWidgets() self.createWidgets()
test = Test() test = Test()
test.mainloop() test.mainloop()

View file

@ -4,30 +4,30 @@ from Tkinter import *
class Test(Frame): class Test(Frame):
def printit(self): def printit(self):
print "hi" print "hi"
def createWidgets(self): def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red', self.QUIT = Button(self, text='QUIT', foreground='red',
command=self.quit) command=self.quit)
self.QUIT.pack(side=LEFT, fill=BOTH) 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.. # all of these work..
self.draw.create_rectangle(0, 0, 10, 10, tags="thing", fill="blue") self.draw.create_rectangle(0, 0, 10, 10, tags="thing", fill="blue")
self.draw.pack(side=LEFT) self.draw.pack(side=LEFT)
def moveThing(self, *args): def moveThing(self, *args):
# move 1/10 of an inch every 1/10 sec (1" per second, smoothly) # move 1/10 of an inch every 1/10 sec (1" per second, smoothly)
self.draw.move("thing", "0.01i", "0.01i") self.draw.move("thing", "0.01i", "0.01i")
self.after(10, self.moveThing) self.after(10, self.moveThing)
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.createWidgets() self.createWidgets()
self.after(10, self.moveThing) self.after(10, self.moveThing)
test = Test() test = Test()

View file

@ -8,35 +8,35 @@ from Tkinter import *
class Test(Frame): class Test(Frame):
def printit(self): def printit(self):
print "hi" print "hi"
def createWidgets(self): def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red', self.QUIT = Button(self, text='QUIT', foreground='red',
command=self.quit) command=self.quit)
self.QUIT.pack(side=BOTTOM, fill=BOTH) 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.. # all of these work..
self.draw.create_rectangle(0, 0, 10, 10, tags="thing", fill="blue") self.draw.create_rectangle(0, 0, 10, 10, tags="thing", fill="blue")
self.draw.pack(side=LEFT) self.draw.pack(side=LEFT)
def moveThing(self, *args): def moveThing(self, *args):
velocity = self.speed.get() velocity = self.speed.get()
str = float(velocity) / 1000.0 str = float(velocity) / 1000.0
str = "%ri" % (str,) str = "%ri" % (str,)
self.draw.move("thing", str, str) self.draw.move("thing", str, str)
self.after(10, self.moveThing) self.after(10, self.moveThing)
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.createWidgets() self.createWidgets()
self.after(10, self.moveThing) self.after(10, self.moveThing)
test = Test() test = Test()

View file

@ -5,30 +5,30 @@ import string
class App(Frame): class App(Frame):
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
self.pack() self.pack()
self.entrythingy = Entry() self.entrythingy = Entry()
self.entrythingy.pack() self.entrythingy.pack()
# and here we get a callback when the user hits return. we could # and here we get a callback when the user hits return. we could
# make the key that triggers the callback anything we wanted to. # make the key that triggers the callback anything we wanted to.
# other typical options might be <Key-Tab> or <Key> (for anything) # other typical options might be <Key-Tab> or <Key> (for anything)
self.entrythingy.bind('<Key-Return>', self.print_contents) self.entrythingy.bind('<Key-Return>', self.print_contents)
# Note that here is where we bind a completely different callback to # 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 # the same event. We pass "+" here to indicate that we wish to ADD
# this callback to the list associated with this event type. # this callback to the list associated with this event type.
# Not specifying "+" would simply override whatever callback was # Not specifying "+" would simply override whatever callback was
# defined on this event. # defined on this event.
self.entrythingy.bind('<Key-Return>', self.print_something_else, "+") self.entrythingy.bind('<Key-Return>', self.print_something_else, "+")
def print_contents(self, event): 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): def print_something_else(self, event):
print "hi. Now doing something completely different" print "hi. Now doing something completely different"
root = App() root = App()

View file

@ -4,24 +4,24 @@ from Tkinter import *
class Test(Frame): class Test(Frame):
def printit(self): def printit(self):
print "hi" print "hi"
def createWidgets(self): def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red', self.QUIT = Button(self, text='QUIT', foreground='red',
command=self.quit) command=self.quit)
self.QUIT.pack(side=BOTTOM, fill=BOTH) 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 # 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.create_rectangle(0, 0, "3i", "3i", fill="black")
self.draw.pack(side=LEFT) self.draw.pack(side=LEFT)
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.createWidgets() self.createWidgets()
test = Test() test = Test()

View file

@ -7,53 +7,53 @@ from Tkinter import *
class Test(Frame): class Test(Frame):
def printit(self): def printit(self):
print "hi" print "hi"
def createWidgets(self): def createWidgets(self):
self.QUIT = Button(self, text='QUIT', self.QUIT = Button(self, text='QUIT',
background='red', background='red',
foreground='white', foreground='white',
height=3, height=3,
command=self.quit) command=self.quit)
self.QUIT.pack(side=BOTTOM, fill=BOTH) self.QUIT.pack(side=BOTTOM, fill=BOTH)
self.canvasObject = Canvas(self, width="5i", height="5i") self.canvasObject = Canvas(self, width="5i", height="5i")
self.canvasObject.pack(side=LEFT) self.canvasObject.pack(side=LEFT)
def mouseDown(self, event): def mouseDown(self, event):
# canvas x and y take the screen coords from the event and translate # canvas x and y take the screen coords from the event and translate
# them into the coordinate system of the canvas object # them into the coordinate system of the canvas object
self.startx = self.canvasObject.canvasx(event.x, self.griddingSize) self.startx = self.canvasObject.canvasx(event.x, self.griddingSize)
self.starty = self.canvasObject.canvasy(event.y, self.griddingSize) self.starty = self.canvasObject.canvasy(event.y, self.griddingSize)
def mouseMotion(self, event): def mouseMotion(self, event):
# canvas x and y take the screen coords from the event and translate # canvas x and y take the screen coords from the event and translate
# them into the coordinate system of the canvas object # them into the coordinate system of the canvas object
x = self.canvasObject.canvasx(event.x, self.griddingSize) x = self.canvasObject.canvasx(event.x, self.griddingSize)
y = self.canvasObject.canvasy(event.y, self.griddingSize) y = self.canvasObject.canvasy(event.y, self.griddingSize)
if (self.startx != event.x) and (self.starty != event.y) : if (self.startx != event.x) and (self.starty != event.y) :
self.canvasObject.delete(self.rubberbandBox) self.canvasObject.delete(self.rubberbandBox)
self.rubberbandBox = self.canvasObject.create_rectangle( self.rubberbandBox = self.canvasObject.create_rectangle(
self.startx, self.starty, x, y) self.startx, self.starty, x, y)
# this flushes the output, making sure that # this flushes the output, making sure that
# the rectangle makes it to the screen # the rectangle makes it to the screen
# before the next event is handled # before the next event is handled
self.update_idletasks() self.update_idletasks()
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.createWidgets() self.createWidgets()
# this is a "tagOrId" for the rectangle we draw on the canvas # this is a "tagOrId" for the rectangle we draw on the canvas
self.rubberbandBox = None self.rubberbandBox = None
# this is the size of the gridding squares # this is the size of the gridding squares
self.griddingSize = 50 self.griddingSize = 50
Widget.bind(self.canvasObject, "<Button-1>", self.mouseDown) Widget.bind(self.canvasObject, "<Button-1>", self.mouseDown)
Widget.bind(self.canvasObject, "<Button1-Motion>", self.mouseMotion) Widget.bind(self.canvasObject, "<Button1-Motion>", self.mouseMotion)
test = Test() test = Test()

View file

@ -8,58 +8,55 @@ class Test(Frame):
###### Event callbacks for THE CANVAS (not the stuff drawn on it) ###### Event callbacks for THE CANVAS (not the stuff drawn on it)
################################################################### ###################################################################
def mouseDown(self, event): def mouseDown(self, event):
# see if we're inside a dot. If we are, it # see if we're inside a dot. If we are, it
# gets tagged as CURRENT for free by tk. # gets tagged as CURRENT for free by tk.
if not event.widget.find_withtag(CURRENT): if not event.widget.find_withtag(CURRENT):
# there is no dot here, so we can make one, # there is no dot here, so we can make one,
# and bind some interesting behavior to it. # and bind some interesting behavior to it.
# ------ # ------
# create a dot, and mark it as CURRENT # create a dot, and mark it as CURRENT
fred = self.draw.create_oval( fred = self.draw.create_oval(
event.x - 10, event.y -10, event.x +10, event.y + 10, event.x - 10, event.y -10, event.x +10, event.y + 10,
fill="green", tags=CURRENT) fill="green", tags=CURRENT)
self.draw.tag_bind(fred, "<Any-Enter>", self.mouseEnter) self.draw.tag_bind(fred, "<Any-Enter>", self.mouseEnter)
self.draw.tag_bind(fred, "<Any-Leave>", self.mouseLeave) self.draw.tag_bind(fred, "<Any-Leave>", self.mouseLeave)
self.lastx = event.x self.lastx = event.x
self.lasty = event.y self.lasty = event.y
def mouseMove(self, event): def mouseMove(self, event):
self.draw.move(CURRENT, event.x - self.lastx, event.y - self.lasty) self.draw.move(CURRENT, event.x - self.lastx, event.y - self.lasty)
self.lastx = event.x self.lastx = event.x
self.lasty = event.y self.lasty = event.y
################################################################### ###################################################################
###### Event callbacks for canvas ITEMS (stuff drawn on the canvas) ###### Event callbacks for canvas ITEMS (stuff drawn on the canvas)
################################################################### ###################################################################
def mouseEnter(self, event): def mouseEnter(self, event):
# the CURRENT tag is applied to the object the cursor is over. # the CURRENT tag is applied to the object the cursor is over.
# this happens automatically. # this happens automatically.
self.draw.itemconfig(CURRENT, fill="red") self.draw.itemconfig(CURRENT, fill="red")
def mouseLeave(self, event): def mouseLeave(self, event):
# the CURRENT tag is applied to the object the cursor is over. # the CURRENT tag is applied to the object the cursor is over.
# this happens automatically. # this happens automatically.
self.draw.itemconfig(CURRENT, fill="blue") self.draw.itemconfig(CURRENT, fill="blue")
def createWidgets(self): def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red', self.QUIT = Button(self, text='QUIT', foreground='red',
command=self.quit) command=self.quit)
self.QUIT.pack(side=LEFT, fill=BOTH) self.QUIT.pack(side=LEFT, fill=BOTH)
self.draw = Canvas(self, width="5i", height="5i") self.draw = Canvas(self, width="5i", height="5i")
self.draw.pack(side=LEFT) self.draw.pack(side=LEFT)
Widget.bind(self.draw, "<1>", self.mouseDown) Widget.bind(self.draw, "<1>", self.mouseDown)
Widget.bind(self.draw, "<B1-Motion>", self.mouseMove) Widget.bind(self.draw, "<B1-Motion>", self.mouseMove)
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.createWidgets() self.createWidgets()
test = Test() test = Test()
test.mainloop() test.mainloop()

View file

@ -7,49 +7,49 @@ class Test(Frame):
###### Event callbacks for THE CANVAS (not the stuff drawn on it) ###### Event callbacks for THE CANVAS (not the stuff drawn on it)
################################################################### ###################################################################
def mouseDown(self, event): def mouseDown(self, event):
# remember where the mouse went down # remember where the mouse went down
self.lastx = event.x self.lastx = event.x
self.lasty = event.y self.lasty = event.y
def mouseMove(self, event): def mouseMove(self, event):
# whatever the mouse is over gets tagged as CURRENT for free by tk. # 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.draw.move(CURRENT, event.x - self.lastx, event.y - self.lasty)
self.lastx = event.x self.lastx = event.x
self.lasty = event.y self.lasty = event.y
################################################################### ###################################################################
###### Event callbacks for canvas ITEMS (stuff drawn on the canvas) ###### Event callbacks for canvas ITEMS (stuff drawn on the canvas)
################################################################### ###################################################################
def mouseEnter(self, event): def mouseEnter(self, event):
# the CURRENT tag is applied to the object the cursor is over. # the CURRENT tag is applied to the object the cursor is over.
# this happens automatically. # this happens automatically.
self.draw.itemconfig(CURRENT, fill="red") self.draw.itemconfig(CURRENT, fill="red")
def mouseLeave(self, event): def mouseLeave(self, event):
# the CURRENT tag is applied to the object the cursor is over. # the CURRENT tag is applied to the object the cursor is over.
# this happens automatically. # this happens automatically.
self.draw.itemconfig(CURRENT, fill="blue") self.draw.itemconfig(CURRENT, fill="blue")
def createWidgets(self): def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red', self.QUIT = Button(self, text='QUIT', foreground='red',
command=self.quit) command=self.quit)
self.QUIT.pack(side=LEFT, fill=BOTH) self.QUIT.pack(side=LEFT, fill=BOTH)
self.draw = Canvas(self, width="5i", height="5i") self.draw = Canvas(self, width="5i", height="5i")
self.draw.pack(side=LEFT) self.draw.pack(side=LEFT)
fred = self.draw.create_oval(0, 0, 20, 20, fred = self.draw.create_oval(0, 0, 20, 20,
fill="green", tags="selected") fill="green", tags="selected")
self.draw.tag_bind(fred, "<Any-Enter>", self.mouseEnter) self.draw.tag_bind(fred, "<Any-Enter>", self.mouseEnter)
self.draw.tag_bind(fred, "<Any-Leave>", self.mouseLeave) self.draw.tag_bind(fred, "<Any-Leave>", self.mouseLeave)
Widget.bind(self.draw, "<1>", self.mouseDown) Widget.bind(self.draw, "<1>", self.mouseDown)
Widget.bind(self.draw, "<B1-Motion>", self.mouseMove) Widget.bind(self.draw, "<B1-Motion>", self.mouseMove)
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.createWidgets() self.createWidgets()
test = Test() test = Test()
test.mainloop() test.mainloop()

View file

@ -10,72 +10,69 @@ class Test(Frame):
###### Event callbacks for THE CANVAS (not the stuff drawn on it) ###### Event callbacks for THE CANVAS (not the stuff drawn on it)
################################################################### ###################################################################
def mouseDown(self, event): def mouseDown(self, event):
# see if we're inside a dot. If we are, it # see if we're inside a dot. If we are, it
# gets tagged as CURRENT for free by tk. # gets tagged as CURRENT for free by tk.
if not event.widget.find_withtag(CURRENT): if not event.widget.find_withtag(CURRENT):
# we clicked outside of all dots on the canvas. unselect all. # we clicked outside of all dots on the canvas. unselect all.
# re-color everything back to an unselected color # re-color everything back to an unselected color
self.draw.itemconfig("selected", fill=UNSELECTED_COLOR) self.draw.itemconfig("selected", fill=UNSELECTED_COLOR)
# unselect everything # unselect everything
self.draw.dtag("selected") self.draw.dtag("selected")
else: else:
# mark as "selected" the thing the cursor is under # mark as "selected" the thing the cursor is under
self.draw.addtag("selected", "withtag", CURRENT) self.draw.addtag("selected", "withtag", CURRENT)
# color it as selected # color it as selected
self.draw.itemconfig("selected", fill=SELECTED_COLOR) self.draw.itemconfig("selected", fill=SELECTED_COLOR)
self.lastx = event.x self.lastx = event.x
self.lasty = event.y self.lasty = event.y
def mouseMove(self, event): def mouseMove(self, event):
self.draw.move("selected", event.x - self.lastx, event.y - self.lasty) self.draw.move("selected", event.x - self.lastx, event.y - self.lasty)
self.lastx = event.x self.lastx = event.x
self.lasty = event.y self.lasty = event.y
def makeNewDot(self): def makeNewDot(self):
# create a dot, and mark it as current # create a dot, and mark it as current
fred = self.draw.create_oval(0, 0, 20, 20, fred = self.draw.create_oval(0, 0, 20, 20,
fill=SELECTED_COLOR, tags=CURRENT) fill=SELECTED_COLOR, tags=CURRENT)
# and make it selected # and make it selected
self.draw.addtag("selected", "withtag", CURRENT) self.draw.addtag("selected", "withtag", CURRENT)
def createWidgets(self): def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red', self.QUIT = Button(self, text='QUIT', foreground='red',
command=self.quit) command=self.quit)
################ ################
# make the canvas and bind some behavior to it # make the canvas and bind some behavior to it
################ ################
self.draw = Canvas(self, width="5i", height="5i") self.draw = Canvas(self, width="5i", height="5i")
Widget.bind(self.draw, "<1>", self.mouseDown) Widget.bind(self.draw, "<1>", self.mouseDown)
Widget.bind(self.draw, "<B1-Motion>", self.mouseMove) Widget.bind(self.draw, "<B1-Motion>", self.mouseMove)
# and other things..... # and other things.....
self.button = Button(self, text="make a new dot", foreground="blue", self.button = Button(self, text="make a new dot", foreground="blue",
command=self.makeNewDot) command=self.makeNewDot)
message = ("%s dots are selected and can be dragged.\n" message = ("%s dots are selected and can be dragged.\n"
"%s are not selected.\n" "%s are not selected.\n"
"Click in a dot to select it.\n" "Click in a dot to select it.\n"
"Click on empty space to deselect all dots." "Click on empty space to deselect all dots."
) % (SELECTED_COLOR, UNSELECTED_COLOR) ) % (SELECTED_COLOR, UNSELECTED_COLOR)
self.label = Message(self, width="5i", text=message) self.label = Message(self, width="5i", text=message)
self.QUIT.pack(side=BOTTOM, fill=BOTH) self.QUIT.pack(side=BOTTOM, fill=BOTH)
self.label.pack(side=BOTTOM, fill=X, expand=1) self.label.pack(side=BOTTOM, fill=X, expand=1)
self.button.pack(side=BOTTOM, fill=X) self.button.pack(side=BOTTOM, fill=X)
self.draw.pack(side=LEFT) self.draw.pack(side=LEFT)
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.createWidgets() self.createWidgets()
test = Test() test = Test()
test.mainloop() test.mainloop()

View file

@ -3,46 +3,46 @@ from Tkinter import *
class Test(Frame): class Test(Frame):
def printit(self): def printit(self):
print "hi" print "hi"
def createWidgets(self): def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red', self.QUIT = Button(self, text='QUIT', foreground='red',
command=self.quit) command=self.quit)
self.QUIT.pack(side=BOTTOM, fill=BOTH) self.QUIT.pack(side=BOTTOM, fill=BOTH)
self.drawing = Canvas(self, width="5i", height="5i") self.drawing = Canvas(self, width="5i", height="5i")
# make a shape # make a shape
pgon = self.drawing.create_polygon( pgon = self.drawing.create_polygon(
10, 10, 110, 10, 110, 110, 10 , 110, 10, 10, 110, 10, 110, 110, 10 , 110,
fill="red", tags=("weee", "foo", "groo")) fill="red", tags=("weee", "foo", "groo"))
# this is how you query an object for its attributes # this is how you query an object for its attributes
# config options FOR CANVAS ITEMS always come back in tuples of length 5. # config options FOR CANVAS ITEMS always come back in tuples of length 5.
# 0 attribute name # 0 attribute name
# 1 BLANK # 1 BLANK
# 2 BLANK # 2 BLANK
# 3 default value # 3 default value
# 4 current value # 4 current value
# the blank spots are for consistency with the config command that # the blank spots are for consistency with the config command that
# is used for widgets. (remember, this is for ITEMS drawn # is used for widgets. (remember, this is for ITEMS drawn
# on a canvas widget, not widgets) # on a canvas widget, not widgets)
option_value = self.drawing.itemconfig(pgon, "stipple") option_value = self.drawing.itemconfig(pgon, "stipple")
print "pgon's current stipple value is -->", option_value[4], "<--" print "pgon's current stipple value is -->", option_value[4], "<--"
option_value = self.drawing.itemconfig(pgon, "fill") option_value = self.drawing.itemconfig(pgon, "fill")
print "pgon's current fill value is -->", option_value[4], "<--" print "pgon's current fill value is -->", option_value[4], "<--"
print " when he is usually colored -->", option_value[3], "<--" print " when he is usually colored -->", option_value[3], "<--"
## here we print out all the tags associated with this object ## here we print out all the tags associated with this object
option_value = self.drawing.itemconfig(pgon, "tags") option_value = self.drawing.itemconfig(pgon, "tags")
print "pgon's tags are", option_value[4] print "pgon's tags are", option_value[4]
self.drawing.pack(side=LEFT) self.drawing.pack(side=LEFT)
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.createWidgets() self.createWidgets()
test = Test() test = Test()

View file

@ -4,32 +4,32 @@ from Tkinter import *
class Test(Frame): class Test(Frame):
def printhi(self): def printhi(self):
print "hi" print "hi"
def createWidgets(self): def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red', self.QUIT = Button(self, text='QUIT', foreground='red',
command=self.quit) command=self.quit)
self.QUIT.pack(side=BOTTOM, fill=BOTH) 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", self.button = Button(self, text="this is a button",
command=self.printhi) command=self.printhi)
# note here the coords are given in pixels (form the # note here the coords are given in pixels (form the
# upper right and corner of the window, as usual for X) # upper right and corner of the window, as usual for X)
# but might just have well been given in inches or points or # but might just have well been given in inches or points or
# whatever...use the "anchor" option to control what point of the # whatever...use the "anchor" option to control what point of the
# widget (in this case the button) gets mapped to the given x, y. # widget (in this case the button) gets mapped to the given x, y.
# you can specify corners, edges, center, etc... # you can specify corners, edges, center, etc...
self.draw.create_window(300, 300, window=self.button) self.draw.create_window(300, 300, window=self.button)
self.draw.pack(side=LEFT) self.draw.pack(side=LEFT)
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.createWidgets() self.createWidgets()
test = Test() test = Test()

View file

@ -7,53 +7,53 @@ from Tkinter import *
class Test(Frame): class Test(Frame):
def printit(self): def printit(self):
print "hi" print "hi"
def createWidgets(self): def createWidgets(self):
self.question = Label(self, text="Can Find The BLUE Square??????") self.question = Label(self, text="Can Find The BLUE Square??????")
self.question.pack() self.question.pack()
self.QUIT = Button(self, text='QUIT', background='red', self.QUIT = Button(self, text='QUIT', background='red',
height=3, command=self.quit) height=3, command=self.quit)
self.QUIT.pack(side=BOTTOM, fill=BOTH) self.QUIT.pack(side=BOTTOM, fill=BOTH)
spacer = Frame(self, height="0.25i") spacer = Frame(self, height="0.25i")
spacer.pack(side=BOTTOM) spacer.pack(side=BOTTOM)
# notice that the scroll region (20" x 20") is larger than # notice that the scroll region (20" x 20") is larger than
# displayed size of the widget (5" x 5") # displayed size of the widget (5" x 5")
self.draw = Canvas(self, width="5i", height="5i", self.draw = Canvas(self, width="5i", height="5i",
background="white", background="white",
scrollregion=(0, 0, "20i", "20i")) scrollregion=(0, 0, "20i", "20i"))
self.draw.scrollX = Scrollbar(self, orient=HORIZONTAL) self.draw.scrollX = Scrollbar(self, orient=HORIZONTAL)
self.draw.scrollY = Scrollbar(self, orient=VERTICAL) self.draw.scrollY = Scrollbar(self, orient=VERTICAL)
# now tie the three together. This is standard boilerplate text # now tie the three together. This is standard boilerplate text
self.draw['xscrollcommand'] = self.draw.scrollX.set self.draw['xscrollcommand'] = self.draw.scrollX.set
self.draw['yscrollcommand'] = self.draw.scrollY.set self.draw['yscrollcommand'] = self.draw.scrollY.set
self.draw.scrollX['command'] = self.draw.xview self.draw.scrollX['command'] = self.draw.xview
self.draw.scrollY['command'] = self.draw.yview self.draw.scrollY['command'] = self.draw.yview
# draw something. Note that the first square # draw something. Note that the first square
# is visible, but you need to scroll to see the second one. # 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(0, 0, "3.5i", "3.5i", fill="black")
self.draw.create_rectangle("10i", "10i", "13.5i", "13.5i", fill="blue") self.draw.create_rectangle("10i", "10i", "13.5i", "13.5i", fill="blue")
# pack 'em up # pack 'em up
self.draw.scrollX.pack(side=BOTTOM, fill=X) self.draw.scrollX.pack(side=BOTTOM, fill=X)
self.draw.scrollY.pack(side=RIGHT, fill=Y) self.draw.scrollY.pack(side=RIGHT, fill=Y)
self.draw.pack(side=LEFT) self.draw.pack(side=LEFT)
def scrollCanvasX(self, *args): def scrollCanvasX(self, *args):
print "scrolling", args print "scrolling", args
print self.draw.scrollX.get() print self.draw.scrollX.get()
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.createWidgets() self.createWidgets()
test = Test() test = Test()

View file

@ -6,59 +6,59 @@ from Dialog import Dialog
class Test(Frame): class Test(Frame):
def printit(self): def printit(self):
print "hi" print "hi"
def makeWindow(self): 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 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' tk_dialog script. The function returns 0 if the user clicks 'yes'
or 1 if the user clicks 'no'. or 1 if the user clicks 'no'.
""" """
# the parameters to this call are as follows: # the parameters to this call are as follows:
d = Dialog( d = Dialog(
self, ## name of a toplevel window self, ## name of a toplevel window
title="fred the dialog box",## title on the window title="fred the dialog box",## title on the window
text="click on a choice", ## message to appear in window text="click on a choice", ## message to appear in window
bitmap="info", ## bitmap (if any) to appear; bitmap="info", ## bitmap (if any) to appear;
## if none, use "" ## if none, use ""
# legal values here are: # legal values here are:
# string what it looks like # string what it looks like
# ---------------------------------------------- # ----------------------------------------------
# error a circle with a slash through it # error a circle with a slash through it
# grey25 grey square # grey25 grey square
# grey50 darker grey square # grey50 darker grey square
# hourglass use for "wait.." # hourglass use for "wait.."
# info a large, lower case "i" # info a large, lower case "i"
# questhead a human head with a "?" in it # questhead a human head with a "?" in it
# question a large "?" # question a large "?"
# warning a large "!" # warning a large "!"
# @fname X bitmap where fname is the path to the file # @fname X bitmap where fname is the path to the file
# #
default=0, # the index of the default button choice. default=0, # the index of the default button choice.
# hitting return selects this # hitting return selects this
strings=("yes", "no")) strings=("yes", "no"))
# values of the 'strings' key are the labels for the # values of the 'strings' key are the labels for the
# buttons that appear left to right in the dialog box # buttons that appear left to right in the dialog box
return d.num return d.num
def createWidgets(self): def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red', self.QUIT = Button(self, text='QUIT', foreground='red',
command=self.quit) command=self.quit)
self.QUIT.pack(side=LEFT, fill=BOTH) self.QUIT.pack(side=LEFT, fill=BOTH)
# a hello button # a hello button
self.hi_there = Button(self, text='Make a New Window', self.hi_there = Button(self, text='Make a New Window',
command=self.makeWindow) command=self.makeWindow)
self.hi_there.pack(side=LEFT) self.hi_there.pack(side=LEFT)
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.windownum = 0 self.windownum = 0
self.createWidgets() self.createWidgets()
test = Test() test = Test()
test.mainloop() test.mainloop()

View file

@ -5,21 +5,20 @@ import string
class App(Frame): class App(Frame):
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
self.pack() self.pack()
self.entrythingy = Entry() self.entrythingy = Entry()
self.entrythingy.pack() self.entrythingy.pack()
# and here we get a callback when the user hits return. we could # and here we get a callback when the user hits return. we could
# make the key that triggers the callback anything we wanted to. # make the key that triggers the callback anything we wanted to.
# other typical options might be <Key-Tab> or <Key> (for anything) # other typical options might be <Key-Tab> or <Key> (for anything)
self.entrythingy.bind('<Key-Return>', self.print_contents) self.entrythingy.bind('<Key-Return>', self.print_contents)
def print_contents(self, event): 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 = App()
root.master.title("Foo") root.master.title("Foo")
root.mainloop() root.mainloop()

View file

@ -5,43 +5,42 @@ import string
class App(Frame): class App(Frame):
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
self.pack() self.pack()
self.entrythingy = Entry(self) self.entrythingy = Entry(self)
self.entrythingy.pack() self.entrythingy.pack()
self.button = Button(self, text="Uppercase The Entry", self.button = Button(self, text="Uppercase The Entry",
command=self.upper) command=self.upper)
self.button.pack() self.button.pack()
# here we have the text in the entry widget tied to a variable. # 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. # changes in the variable are echoed in the widget and vice versa.
# Very handy. # Very handy.
# there are other Variable types. See Tkinter.py for all # there are other Variable types. See Tkinter.py for all
# the other variable types that can be shadowed # the other variable types that can be shadowed
self.contents = StringVar() self.contents = StringVar()
self.contents.set("this is a variable") self.contents.set("this is a variable")
self.entrythingy.config(textvariable=self.contents) self.entrythingy.config(textvariable=self.contents)
# and here we get a callback when the user hits return. we could # and here we get a callback when the user hits return. we could
# make the key that triggers the callback anything we wanted to. # make the key that triggers the callback anything we wanted to.
# other typical options might be <Key-Tab> or <Key> (for anything) # other typical options might be <Key-Tab> or <Key> (for anything)
self.entrythingy.bind('<Key-Return>', self.print_contents) self.entrythingy.bind('<Key-Return>', self.print_contents)
def upper(self): def upper(self):
# notice here, we don't actually refer to the entry box. # notice here, we don't actually refer to the entry box.
# we just operate on the string variable and we # we just operate on the string variable and we
# because it's being looked at by the entry widget, changing # because it's being looked at by the entry widget, changing
# the variable changes the entry widget display automatically. # the variable changes the entry widget display automatically.
# the strange get/set operators are clunky, true... # the strange get/set operators are clunky, true...
str = string.upper(self.contents.get()) str = string.upper(self.contents.get())
self.contents.set(str) self.contents.set(str)
def print_contents(self, event): 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 = App()
root.master.title("Foo") root.master.title("Foo")
root.mainloop() root.mainloop()

View file

@ -11,31 +11,31 @@ def my_delete_callback():
class Test(Frame): class Test(Frame):
def deathHandler(self, event): 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): def createWidgets(self):
# a hello button # a hello button
self.hi_there = Button(self, text='Hello') self.hi_there = Button(self, text='Hello')
self.hi_there.pack(side=LEFT) self.hi_there.pack(side=LEFT)
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.createWidgets() 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. # unfortunately, some window managers will not send this request to a window.
# the "protocol" function seems incapable of trapping these "aggressive" window kills. # 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 # this line of code catches everything, tho. The window is deleted, but you have a chance
# of cleaning up first. # of cleaning up first.
self.bind_all("<Destroy>", self.deathHandler) self.bind_all("<Destroy>", self.deathHandler)
test = Test() test = Test()

View file

@ -55,7 +55,7 @@ def print_anchovies():
def makeCommandMenu(): def makeCommandMenu():
# make menu button # make menu button
Command_button = Menubutton(mBar, text='Simple Button Commands', Command_button = Menubutton(mBar, text='Simple Button Commands',
underline=0) underline=0)
Command_button.pack(side=LEFT, padx="2m") Command_button.pack(side=LEFT, padx="2m")
# make the pulldown part of the File menu. The parameter passed is the master. # make the pulldown part of the File menu. The parameter passed is the master.
@ -69,27 +69,27 @@ def makeCommandMenu():
Command_button.menu.entryconfig(0, state=DISABLED) Command_button.menu.entryconfig(0, state=DISABLED)
Command_button.menu.add_command(label='New...', underline=0, Command_button.menu.add_command(label='New...', underline=0,
command=new_file) command=new_file)
Command_button.menu.add_command(label='Open...', underline=0, Command_button.menu.add_command(label='Open...', underline=0,
command=open_file) command=open_file)
Command_button.menu.add_command(label='Different Font', underline=0, Command_button.menu.add_command(label='Different Font', underline=0,
font='-*-helvetica-*-r-*-*-*-180-*-*-*-*-*-*', font='-*-helvetica-*-r-*-*-*-180-*-*-*-*-*-*',
command=print_something) command=print_something)
# we can make bitmaps be menu entries too. File format is X11 bitmap. # 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.,.. # if you use XV, save it under X11 bitmap format. duh-uh.,..
Command_button.menu.add_command( Command_button.menu.add_command(
bitmap="info") bitmap="info")
#bitmap='@/home/mjc4y/dilbert/project.status.is.doomed.last.panel.bm') #bitmap='@/home/mjc4y/dilbert/project.status.is.doomed.last.panel.bm')
# this is just a line # this is just a line
Command_button.menu.add('separator') Command_button.menu.add('separator')
# change the color # change the color
Command_button.menu.add_command(label='Quit', underline=0, Command_button.menu.add_command(label='Quit', underline=0,
background='red', background='red',
activebackground='green', activebackground='green',
command=Command_button.quit) command=Command_button.quit)
# set up a pointer from the file menubutton back to the file menu # set up a pointer from the file menubutton back to the file menu
Command_button['menu'] = Command_button.menu Command_button['menu'] = Command_button.menu
@ -125,12 +125,12 @@ def makeCascadeMenu():
Cascade_button.menu.choices.add_command(label='Rocky Road') Cascade_button.menu.choices.add_command(label='Rocky Road')
Cascade_button.menu.choices.add_command(label='BubbleGum') Cascade_button.menu.choices.add_command(label='BubbleGum')
Cascade_button.menu.choices.add_cascade( Cascade_button.menu.choices.add_cascade(
label='Wierd Flavors', label='Wierd Flavors',
menu=Cascade_button.menu.choices.wierdones) menu=Cascade_button.menu.choices.wierdones)
# and finally, the definition for the top level # and finally, the definition for the top level
Cascade_button.menu.add_cascade(label='more choices', Cascade_button.menu.add_cascade(label='more choices',
menu=Cascade_button.menu.choices) menu=Cascade_button.menu.choices)
Cascade_button['menu'] = Cascade_button.menu Cascade_button['menu'] = Cascade_button.menu
@ -140,7 +140,7 @@ def makeCheckbuttonMenu():
global fred global fred
# make menu button # make menu button
Checkbutton_button = Menubutton(mBar, text='Checkbutton Menus', Checkbutton_button = Menubutton(mBar, text='Checkbutton Menus',
underline=0) underline=0)
Checkbutton_button.pack(side=LEFT, padx='2m') Checkbutton_button.pack(side=LEFT, padx='2m')
# the primary pulldown # the primary pulldown
@ -155,7 +155,7 @@ def makeCheckbuttonMenu():
# so here's a callback # so here's a callback
Checkbutton_button.menu.add_checkbutton(label='Anchovy', Checkbutton_button.menu.add_checkbutton(label='Anchovy',
command=print_anchovies) 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 # calling invoke on this menu option. To refer to the "anchovy" menu
@ -183,7 +183,7 @@ def makeCheckbuttonMenu():
def makeRadiobuttonMenu(): def makeRadiobuttonMenu():
# make menu button # make menu button
Radiobutton_button = Menubutton(mBar, text='Radiobutton Menus', Radiobutton_button = Menubutton(mBar, text='Radiobutton Menus',
underline=0) underline=0)
Radiobutton_button.pack(side=LEFT, padx='2m') Radiobutton_button.pack(side=LEFT, padx='2m')
# the primary pulldown # the primary pulldown
@ -242,9 +242,3 @@ root.title('menu demo')
root.iconname('menu demo') root.iconname('menu demo')
root.mainloop() root.mainloop()

View file

@ -51,14 +51,14 @@ def makeFileMenu():
# must be one of: "cascade", "checkbutton", "command", "radiobutton", "seperator" # must be one of: "cascade", "checkbutton", "command", "radiobutton", "seperator"
# see menu-demo-2.py for examples of use # see menu-demo-2.py for examples of use
File_button.menu.add_command(label='New...', underline=0, File_button.menu.add_command(label='New...', underline=0,
command=new_file) command=new_file)
File_button.menu.add_command(label='Open...', underline=0, File_button.menu.add_command(label='Open...', underline=0,
command=open_file) command=open_file)
File_button.menu.add_command(label='Quit', underline=0, File_button.menu.add_command(label='Quit', underline=0,
command='exit') command='exit')
# set up a pointer from the file menubutton back to the file menu # set up a pointer from the file menubutton back to the file menu
File_button['menu'] = File_button.menu File_button['menu'] = File_button.menu
@ -110,9 +110,3 @@ root.title('menu demo')
root.iconname('packer') root.iconname('packer')
root.mainloop() root.mainloop()

View file

@ -4,21 +4,21 @@ from Tkinter import *
class Test(Frame): class Test(Frame):
def createWidgets(self): def createWidgets(self):
self.Gpanel = Frame(self, width='1i', height='1i', self.Gpanel = Frame(self, width='1i', height='1i',
background='green') background='green')
self.Gpanel.pack(side=LEFT) self.Gpanel.pack(side=LEFT)
# a QUIT button # a QUIT button
self.Gpanel.QUIT = Button(self.Gpanel, text='QUIT', self.Gpanel.QUIT = Button(self.Gpanel, text='QUIT',
foreground='red', foreground='red',
command=self.quit) command=self.quit)
self.Gpanel.QUIT.pack(side=LEFT) self.Gpanel.QUIT.pack(side=LEFT)
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.createWidgets() self.createWidgets()
test = Test() test = Test()

View file

@ -4,23 +4,23 @@ from Tkinter import *
class Test(Frame): class Test(Frame):
def createWidgets(self): def createWidgets(self):
self.Gpanel = Frame(self, width='1i', height='1i', self.Gpanel = Frame(self, width='1i', height='1i',
background='green') background='green')
# this line turns off the recalculation of geometry by masters. # this line turns off the recalculation of geometry by masters.
self.Gpanel.propagate(0) self.Gpanel.propagate(0)
self.Gpanel.pack(side=LEFT) self.Gpanel.pack(side=LEFT)
# a QUIT button # a QUIT button
self.Gpanel.QUIT = Button(self.Gpanel, text='QUIT', foreground='red', self.Gpanel.QUIT = Button(self.Gpanel, text='QUIT', foreground='red',
command=self.quit) command=self.quit)
self.Gpanel.QUIT.pack(side=LEFT) self.Gpanel.QUIT.pack(side=LEFT)
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.createWidgets() self.createWidgets()
test = Test() test = Test()

View file

@ -39,4 +39,3 @@ app = createWidgets(root)
root.geometry("400x400") root.geometry("400x400")
root.maxsize(1000, 1000) root.maxsize(1000, 1000)
root.mainloop() root.mainloop()

View file

@ -3,30 +3,30 @@ from Tkinter import *
class Test(Frame): class Test(Frame):
def printit(self): def printit(self):
print self.hi_there["command"] print self.hi_there["command"]
def createWidgets(self): def createWidgets(self):
# a hello button # a hello button
self.QUIT = Button(self, text='QUIT', foreground='red', self.QUIT = Button(self, text='QUIT', foreground='red',
command=self.quit) command=self.quit)
self.QUIT.pack(side=LEFT, fill=BOTH) self.QUIT.pack(side=LEFT, fill=BOTH)
self.hi_there = Button(self, text='Hello', self.hi_there = Button(self, text='Hello',
command=self.printit) command=self.printit)
self.hi_there.pack(side=LEFT) 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 = Button(self, text='button 2')
self.guy2.pack() self.guy2.pack()
self.guy3 = Button(self, text='button 3') self.guy3 = Button(self, text='button 3')
self.guy3.pack() self.guy3.pack()
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.createWidgets() self.createWidgets()
test = Test() test = Test()
test.mainloop() test.mainloop()

View file

@ -37,4 +37,3 @@ app = createWidgets(root)
root.geometry("400x400") root.geometry("400x400")
root.maxsize(1000, 1000) root.maxsize(1000, 1000)
root.mainloop() root.mainloop()

View file

@ -5,48 +5,48 @@ import string
class Pong(Frame): class Pong(Frame):
def createWidgets(self): def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red', self.QUIT = Button(self, text='QUIT', foreground='red',
command=self.quit) command=self.quit)
self.QUIT.pack(side=LEFT, fill=BOTH) self.QUIT.pack(side=LEFT, fill=BOTH)
## The playing field ## The playing field
self.draw = Canvas(self, width="5i", height="5i") self.draw = Canvas(self, width="5i", height="5i")
## The speed control for the ball ## The speed control for the ball
self.speed = Scale(self, orient=HORIZONTAL, label="ball speed", self.speed = Scale(self, orient=HORIZONTAL, label="ball speed",
from_=-100, to=100) from_=-100, to=100)
self.speed.pack(side=BOTTOM, fill=X) self.speed.pack(side=BOTTOM, fill=X)
# The ball # The ball
self.ball = self.draw.create_oval("0i", "0i", "0.10i", "0.10i", self.ball = self.draw.create_oval("0i", "0i", "0.10i", "0.10i",
fill="red") fill="red")
self.x = 0.05 self.x = 0.05
self.y = 0.05 self.y = 0.05
self.velocity_x = 0.3 self.velocity_x = 0.3
self.velocity_y = 0.5 self.velocity_y = 0.5
self.draw.pack(side=LEFT) self.draw.pack(side=LEFT)
def moveBall(self, *args): def moveBall(self, *args):
if (self.x > 5.0) or (self.x < 0.0): if (self.x > 5.0) or (self.x < 0.0):
self.velocity_x = -1.0 * self.velocity_x self.velocity_x = -1.0 * self.velocity_x
if (self.y > 5.0) or (self.y < 0.0): if (self.y > 5.0) or (self.y < 0.0):
self.velocity_y = -1.0 * self.velocity_y self.velocity_y = -1.0 * self.velocity_y
deltax = (self.velocity_x * self.speed.get() / 100.0) deltax = (self.velocity_x * self.speed.get() / 100.0)
deltay = (self.velocity_y * self.speed.get() / 100.0) deltay = (self.velocity_y * self.speed.get() / 100.0)
self.x = self.x + deltax self.x = self.x + deltax
self.y = self.y + deltay self.y = self.y + deltay
self.draw.move(self.ball, "%ri" % deltax, "%ri" % deltay) self.draw.move(self.ball, "%ri" % deltax, "%ri" % deltay)
self.after(10, self.moveBall) self.after(10, self.moveBall)
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.createWidgets() self.createWidgets()
self.after(10, self.moveBall) self.after(10, self.moveBall)
game = Pong() game = Pong()

View file

@ -7,58 +7,55 @@ class Test(Frame):
###### Event callbacks for THE CANVAS (not the stuff drawn on it) ###### Event callbacks for THE CANVAS (not the stuff drawn on it)
################################################################### ###################################################################
def mouseDown(self, event): def mouseDown(self, event):
# see if we're inside a dot. If we are, it # see if we're inside a dot. If we are, it
# gets tagged as CURRENT for free by tk. # gets tagged as CURRENT for free by tk.
if not event.widget.find_withtag(CURRENT): if not event.widget.find_withtag(CURRENT):
# there is no dot here, so we can make one, # there is no dot here, so we can make one,
# and bind some interesting behavior to it. # and bind some interesting behavior to it.
# ------ # ------
# create a dot, and mark it as current # create a dot, and mark it as current
fred = self.draw.create_oval( fred = self.draw.create_oval(
event.x - 10, event.y -10, event.x +10, event.y + 10, event.x - 10, event.y -10, event.x +10, event.y + 10,
fill="green") fill="green")
self.draw.tag_bind(fred, "<Enter>", self.mouseEnter) self.draw.tag_bind(fred, "<Enter>", self.mouseEnter)
self.draw.tag_bind(fred, "<Leave>", self.mouseLeave) self.draw.tag_bind(fred, "<Leave>", self.mouseLeave)
self.lastx = event.x self.lastx = event.x
self.lasty = event.y self.lasty = event.y
def mouseMove(self, event): def mouseMove(self, event):
self.draw.move(CURRENT, event.x - self.lastx, event.y - self.lasty) self.draw.move(CURRENT, event.x - self.lastx, event.y - self.lasty)
self.lastx = event.x self.lastx = event.x
self.lasty = event.y self.lasty = event.y
################################################################### ###################################################################
###### Event callbacks for canvas ITEMS (stuff drawn on the canvas) ###### Event callbacks for canvas ITEMS (stuff drawn on the canvas)
################################################################### ###################################################################
def mouseEnter(self, event): def mouseEnter(self, event):
# the "current" tag is applied to the object the cursor is over. # the "current" tag is applied to the object the cursor is over.
# this happens automatically. # this happens automatically.
self.draw.itemconfig(CURRENT, fill="red") self.draw.itemconfig(CURRENT, fill="red")
print self.draw.coords(CURRENT) print self.draw.coords(CURRENT)
def mouseLeave(self, event): def mouseLeave(self, event):
# the "current" tag is applied to the object the cursor is over. # the "current" tag is applied to the object the cursor is over.
# this happens automatically. # this happens automatically.
self.draw.itemconfig(CURRENT, fill="blue") self.draw.itemconfig(CURRENT, fill="blue")
def createWidgets(self): def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red', self.QUIT = Button(self, text='QUIT', foreground='red',
command=self.quit) command=self.quit)
self.QUIT.pack(side=LEFT, fill=BOTH) self.QUIT.pack(side=LEFT, fill=BOTH)
self.draw = Canvas(self, width="5i", height="5i") self.draw = Canvas(self, width="5i", height="5i")
self.draw.pack(side=LEFT) self.draw.pack(side=LEFT)
Widget.bind(self.draw, "<1>", self.mouseDown) Widget.bind(self.draw, "<1>", self.mouseDown)
Widget.bind(self.draw, "<B1-Motion>", self.mouseMove) Widget.bind(self.draw, "<B1-Motion>", self.mouseMove)
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.createWidgets() self.createWidgets()
test = Test() test = Test()
test.mainloop() test.mainloop()

View file

@ -12,50 +12,50 @@ from Tkinter import *
class Test(Frame): class Test(Frame):
def printit(self): def printit(self):
print "hi" print "hi"
def createWidgets(self): def createWidgets(self):
self.flavor = StringVar() self.flavor = StringVar()
self.flavor.set("chocolate") self.flavor.set("chocolate")
self.radioframe = Frame(self) self.radioframe = Frame(self)
self.radioframe.pack() self.radioframe.pack()
# 'text' is the label # 'text' is the label
# 'variable' is the name of the variable that all these radio buttons share # '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 # '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) # 'anchor' makes the text appear left justified (default is centered. ick)
self.radioframe.choc = Radiobutton( self.radioframe.choc = Radiobutton(
self.radioframe, text="Chocolate Flavor", self.radioframe, text="Chocolate Flavor",
variable=self.flavor, value="chocolate", variable=self.flavor, value="chocolate",
anchor=W) anchor=W)
self.radioframe.choc.pack(fill=X) self.radioframe.choc.pack(fill=X)
self.radioframe.straw = Radiobutton( self.radioframe.straw = Radiobutton(
self.radioframe, text="Strawberry Flavor", self.radioframe, text="Strawberry Flavor",
variable=self.flavor, value="strawberry", variable=self.flavor, value="strawberry",
anchor=W) anchor=W)
self.radioframe.straw.pack(fill=X) self.radioframe.straw.pack(fill=X)
self.radioframe.lemon = Radiobutton( self.radioframe.lemon = Radiobutton(
self.radioframe, text="Lemon Flavor", self.radioframe, text="Lemon Flavor",
variable=self.flavor, value="lemon", variable=self.flavor, value="lemon",
anchor=W) anchor=W)
self.radioframe.lemon.pack(fill=X) self.radioframe.lemon.pack(fill=X)
# this is a text entry that lets you type in the name of a flavor too. # 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 = Entry(self, textvariable=self.flavor)
self.entry.pack(fill=X) self.entry.pack(fill=X)
self.QUIT = Button(self, text='QUIT', foreground='red', self.QUIT = Button(self, text='QUIT', foreground='red',
command=self.quit) command=self.quit)
self.QUIT.pack(side=BOTTOM, fill=BOTH) self.QUIT.pack(side=BOTTOM, fill=BOTH)
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.createWidgets() self.createWidgets()
test = Test() test = Test()

View file

@ -2,55 +2,55 @@ from Tkinter import *
class Test(Frame): class Test(Frame):
def printit(self): def printit(self):
print "hi" print "hi"
def createWidgets(self): def createWidgets(self):
self.QUIT = Button(self, text='QUIT', self.QUIT = Button(self, text='QUIT',
background='red', background='red',
foreground='white', foreground='white',
height=3, height=3,
command=self.quit) command=self.quit)
self.QUIT.pack(side=BOTTOM, fill=BOTH) self.QUIT.pack(side=BOTTOM, fill=BOTH)
self.canvasObject = Canvas(self, width="5i", height="5i") self.canvasObject = Canvas(self, width="5i", height="5i")
self.canvasObject.pack(side=LEFT) self.canvasObject.pack(side=LEFT)
def mouseDown(self, event): def mouseDown(self, event):
# canvas x and y take the screen coords from the event and translate # canvas x and y take the screen coords from the event and translate
# them into the coordinate system of the canvas object # them into the coordinate system of the canvas object
self.startx = self.canvasObject.canvasx(event.x) self.startx = self.canvasObject.canvasx(event.x)
self.starty = self.canvasObject.canvasy(event.y) self.starty = self.canvasObject.canvasy(event.y)
def mouseMotion(self, event): def mouseMotion(self, event):
# canvas x and y take the screen coords from the event and translate # canvas x and y take the screen coords from the event and translate
# them into the coordinate system of the canvas object # them into the coordinate system of the canvas object
x = self.canvasObject.canvasx(event.x) x = self.canvasObject.canvasx(event.x)
y = self.canvasObject.canvasy(event.y) y = self.canvasObject.canvasy(event.y)
if (self.startx != event.x) and (self.starty != event.y) : if (self.startx != event.x) and (self.starty != event.y) :
self.canvasObject.delete(self.rubberbandBox) self.canvasObject.delete(self.rubberbandBox)
self.rubberbandBox = self.canvasObject.create_rectangle( self.rubberbandBox = self.canvasObject.create_rectangle(
self.startx, self.starty, x, y) self.startx, self.starty, x, y)
# this flushes the output, making sure that # this flushes the output, making sure that
# the rectangle makes it to the screen # the rectangle makes it to the screen
# before the next event is handled # before the next event is handled
self.update_idletasks() self.update_idletasks()
def mouseUp(self, event): def mouseUp(self, event):
self.canvasObject.delete(self.rubberbandBox) self.canvasObject.delete(self.rubberbandBox)
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.createWidgets() self.createWidgets()
# this is a "tagOrId" for the rectangle we draw on the canvas # this is a "tagOrId" for the rectangle we draw on the canvas
self.rubberbandBox = None self.rubberbandBox = None
# and the bindings that make it work.. # and the bindings that make it work..
Widget.bind(self.canvasObject, "<Button-1>", self.mouseDown) Widget.bind(self.canvasObject, "<Button-1>", self.mouseDown)
Widget.bind(self.canvasObject, "<Button1-Motion>", self.mouseMotion) Widget.bind(self.canvasObject, "<Button1-Motion>", self.mouseMotion)
Widget.bind(self.canvasObject, "<Button1-ButtonRelease>", self.mouseUp) Widget.bind(self.canvasObject, "<Button1-ButtonRelease>", self.mouseUp)
test = Test() test = Test()

View file

@ -2,48 +2,48 @@ from Tkinter import *
class Test(Frame): class Test(Frame):
def printit(self): def printit(self):
print "hi" print "hi"
def createWidgets(self): def createWidgets(self):
self.QUIT = Button(self, text='QUIT', self.QUIT = Button(self, text='QUIT',
background='red', background='red',
foreground='white', foreground='white',
height=3, height=3,
command=self.quit) command=self.quit)
self.QUIT.pack(side=BOTTOM, fill=BOTH) self.QUIT.pack(side=BOTTOM, fill=BOTH)
self.canvasObject = Canvas(self, width="5i", height="5i") self.canvasObject = Canvas(self, width="5i", height="5i")
self.canvasObject.pack(side=LEFT) self.canvasObject.pack(side=LEFT)
def mouseDown(self, event): def mouseDown(self, event):
# canvas x and y take the screen coords from the event and translate # canvas x and y take the screen coords from the event and translate
# them into the coordinate system of the canvas object # them into the coordinate system of the canvas object
self.startx = self.canvasObject.canvasx(event.x) self.startx = self.canvasObject.canvasx(event.x)
self.starty = self.canvasObject.canvasy(event.y) self.starty = self.canvasObject.canvasy(event.y)
def mouseMotion(self, event): def mouseMotion(self, event):
# canvas x and y take the screen coords from the event and translate # canvas x and y take the screen coords from the event and translate
# them into the coordinate system of the canvas object # them into the coordinate system of the canvas object
x = self.canvasObject.canvasx(event.x) x = self.canvasObject.canvasx(event.x)
y = self.canvasObject.canvasy(event.y) y = self.canvasObject.canvasy(event.y)
if (self.startx != event.x) and (self.starty != event.y) : if (self.startx != event.x) and (self.starty != event.y) :
self.canvasObject.delete(self.rubberbandLine) self.canvasObject.delete(self.rubberbandLine)
self.rubberbandLine = self.canvasObject.create_line( self.rubberbandLine = self.canvasObject.create_line(
self.startx, self.starty, x, y) self.startx, self.starty, x, y)
# this flushes the output, making sure that # this flushes the output, making sure that
# the rectangle makes it to the screen # the rectangle makes it to the screen
# before the next event is handled # before the next event is handled
self.update_idletasks() self.update_idletasks()
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.createWidgets() self.createWidgets()
# this is a "tagOrId" for the rectangle we draw on the canvas # this is a "tagOrId" for the rectangle we draw on the canvas
self.rubberbandLine = None self.rubberbandLine = None
Widget.bind(self.canvasObject, "<Button-1>", self.mouseDown) Widget.bind(self.canvasObject, "<Button-1>", self.mouseDown)
Widget.bind(self.canvasObject, "<Button1-Motion>", self.mouseMotion) Widget.bind(self.canvasObject, "<Button1-Motion>", self.mouseMotion)
test = Test() test = Test()

View file

@ -5,32 +5,32 @@ from Tkinter import *
class Test(Frame): class Test(Frame):
def print_value(self, val): def print_value(self, val):
print "slider now at", val print "slider now at", val
def reset(self): def reset(self):
self.slider.set(0) self.slider.set(0)
def createWidgets(self): def createWidgets(self):
self.slider = Scale(self, from_=0, to=100, self.slider = Scale(self, from_=0, to=100,
orient=HORIZONTAL, orient=HORIZONTAL,
length="3i", length="3i",
label="happy slider", label="happy slider",
command=self.print_value) command=self.print_value)
self.reset = Button(self, text='reset slider', self.reset = Button(self, text='reset slider',
command=self.reset) command=self.reset)
self.QUIT = Button(self, text='QUIT', foreground='red', self.QUIT = Button(self, text='QUIT', foreground='red',
command=self.quit) command=self.quit)
self.slider.pack(side=LEFT) self.slider.pack(side=LEFT)
self.reset.pack(side=LEFT) self.reset.pack(side=LEFT)
self.QUIT.pack(side=LEFT, fill=BOTH) self.QUIT.pack(side=LEFT, fill=BOTH)
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.createWidgets() self.createWidgets()
test = Test() test = Test()
test.mainloop() test.mainloop()

View file

@ -5,8 +5,8 @@ from Tkinter import *
class New_Button(Button): class New_Button(Button):
def callback(self): def callback(self):
print self.counter print self.counter
self.counter = self.counter + 1 self.counter = self.counter + 1
def createWidgets(top): def createWidgets(top):
f = Frame(top) f = Frame(top)
@ -26,4 +26,3 @@ def createWidgets(top):
root = Tk() root = Tk()
createWidgets(root) createWidgets(root)
root.mainloop() root.mainloop()

View file

@ -1,43 +1,43 @@
from Tkinter import * from Tkinter import *
# The way to think about this is that each radio button menu # The way to think about this is that each radio button menu
# controls a different variable -- clicking on one of the # controls a different variable -- clicking on one of the
# mutually exclusive choices in a radiobutton assigns some value # mutually exclusive choices in a radiobutton assigns some value
# to an application variable you provide. When you define a # to an application variable you provide. When you define a
# radiobutton menu choice, you have the option of specifying the # radiobutton menu choice, you have the option of specifying the
# name of a varaible and value to assign to that variable when # name of a varaible and value to assign to that variable when
# that choice is selected. This clever mechanism relieves you, # that choice is selected. This clever mechanism relieves you,
# the programmer, from having to write a dumb callback that # the programmer, from having to write a dumb callback that
# probably wouldn't have done anything more than an assignment # probably wouldn't have done anything more than an assignment
# anyway. The Tkinter options for this follow their Tk # anyway. The Tkinter options for this follow their Tk
# counterparts: # counterparts:
# {"variable" : my_flavor_variable, "value" : "strawberry"} # {"variable" : my_flavor_variable, "value" : "strawberry"}
# where my_flavor_variable is an instance of one of the # where my_flavor_variable is an instance of one of the
# subclasses of Variable, provided in Tkinter.py (there is # subclasses of Variable, provided in Tkinter.py (there is
# StringVar(), IntVar(), DoubleVar() and BooleanVar() to choose # StringVar(), IntVar(), DoubleVar() and BooleanVar() to choose
# from) # from)
def makePoliticalParties(var): def makePoliticalParties(var):
# make menu button # make menu button
Radiobutton_button = Menubutton(mBar, text='Political Party', Radiobutton_button = Menubutton(mBar, text='Political Party',
underline=0) underline=0)
Radiobutton_button.pack(side=LEFT, padx='2m') Radiobutton_button.pack(side=LEFT, padx='2m')
# the primary pulldown # the primary pulldown
Radiobutton_button.menu = Menu(Radiobutton_button) Radiobutton_button.menu = Menu(Radiobutton_button)
Radiobutton_button.menu.add_radiobutton(label='Republican', Radiobutton_button.menu.add_radiobutton(label='Republican',
variable=var, value=1) variable=var, value=1)
Radiobutton_button.menu.add('radiobutton', {'label': 'Democrat', Radiobutton_button.menu.add('radiobutton', {'label': 'Democrat',
'variable' : var, 'variable' : var,
'value' : 2}) 'value' : 2})
Radiobutton_button.menu.add('radiobutton', {'label': 'Libertarian', Radiobutton_button.menu.add('radiobutton', {'label': 'Libertarian',
'variable' : var, 'variable' : var,
'value' : 3}) 'value' : 3})
var.set(2) var.set(2)
@ -50,20 +50,20 @@ def makePoliticalParties(var):
def makeFlavors(var): def makeFlavors(var):
# make menu button # make menu button
Radiobutton_button = Menubutton(mBar, text='Flavors', Radiobutton_button = Menubutton(mBar, text='Flavors',
underline=0) underline=0)
Radiobutton_button.pack(side=LEFT, padx='2m') Radiobutton_button.pack(side=LEFT, padx='2m')
# the primary pulldown # the primary pulldown
Radiobutton_button.menu = Menu(Radiobutton_button) Radiobutton_button.menu = Menu(Radiobutton_button)
Radiobutton_button.menu.add_radiobutton(label='Strawberry', Radiobutton_button.menu.add_radiobutton(label='Strawberry',
variable=var, value='Strawberry') variable=var, value='Strawberry')
Radiobutton_button.menu.add_radiobutton(label='Chocolate', Radiobutton_button.menu.add_radiobutton(label='Chocolate',
variable=var, value='Chocolate') variable=var, value='Chocolate')
Radiobutton_button.menu.add_radiobutton(label='Rocky Road', Radiobutton_button.menu.add_radiobutton(label='Rocky Road',
variable=var, value='Rocky Road') variable=var, value='Rocky Road')
# choose a default # choose a default
var.set("Chocolate") var.set("Chocolate")
@ -101,7 +101,7 @@ Radiobutton_button2 = makeFlavors(flavor)
mBar.tk_menuBar(Radiobutton_button, Radiobutton_button2) mBar.tk_menuBar(Radiobutton_button, Radiobutton_button2)
b = Button(root, text="print party and flavor", foreground="red", b = Button(root, text="print party and flavor", foreground="red",
command=printStuff) command=printStuff)
b.pack(side=TOP) b.pack(side=TOP)
root.title('menu demo') root.title('menu demo')

View file

@ -5,31 +5,31 @@ from Tkinter import *
class Test(Frame): class Test(Frame):
def printit(self): def printit(self):
print "hi" print "hi"
def makeWindow(self): def makeWindow(self):
fred = Toplevel() fred = Toplevel()
fred.label = Button(fred, fred.label = Button(fred,
text="This is window number %d." % self.windownum, text="This is window number %d." % self.windownum,
command=self.makeWindow) command=self.makeWindow)
fred.label.pack() fred.label.pack()
self.windownum = self.windownum + 1 self.windownum = self.windownum + 1
def createWidgets(self): def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red', self.QUIT = Button(self, text='QUIT', foreground='red',
command=self.quit) command=self.quit)
self.QUIT.pack(side=LEFT, fill=BOTH) self.QUIT.pack(side=LEFT, fill=BOTH)
# a hello button # a hello button
self.hi_there = Button(self, text='Make a New Window', self.hi_there = Button(self, text='Make a New Window',
command=self.makeWindow) command=self.makeWindow)
self.hi_there.pack(side=LEFT) self.hi_there.pack(side=LEFT)
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.windownum = 0 self.windownum = 0
self.createWidgets() self.createWidgets()
test = Test() test = Test()
test.mainloop() test.mainloop()

View file

@ -4,28 +4,28 @@ from Tkinter import *
class Test(Frame): class Test(Frame):
def printit(self): def printit(self):
print "hi" print "hi"
def makeWindow(self): def makeWindow(self):
fred = Toplevel() fred = Toplevel()
fred.label = Label(fred, text="Here's a new window") fred.label = Label(fred, text="Here's a new window")
fred.label.pack() fred.label.pack()
def createWidgets(self): def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red', self.QUIT = Button(self, text='QUIT', foreground='red',
command=self.quit) command=self.quit)
self.QUIT.pack(side=LEFT, fill=BOTH) self.QUIT.pack(side=LEFT, fill=BOTH)
# a hello button # a hello button
self.hi_there = Button(self, text='Make a New Window', self.hi_there = Button(self, text='Make a New Window',
command=self.makeWindow) command=self.makeWindow)
self.hi_there.pack(side=LEFT) self.hi_there.pack(side=LEFT)
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.createWidgets() self.createWidgets()
test = Test() test = Test()
test.mainloop() test.mainloop()

View file

@ -17,29 +17,29 @@ class QuitButton(Button):
class Test(Frame): class Test(Frame):
def makeWindow(self, *args): 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", "0", "2i", "2i")
fred.label.create_line("0", "2i", "2i", "0") fred.label.create_line("0", "2i", "2i", "0")
fred.label.pack() fred.label.pack()
##centerWindow(fred, self.master) ##centerWindow(fred, self.master)
def createWidgets(self): def createWidgets(self):
self.QUIT = QuitButton(self) self.QUIT = QuitButton(self)
self.QUIT.pack(side=LEFT, fill=BOTH) self.QUIT.pack(side=LEFT, fill=BOTH)
self.makeWindow = Button(self, text='Make a New Window', self.makeWindow = Button(self, text='Make a New Window',
width=50, height=20, width=50, height=20,
command=self.makeWindow) command=self.makeWindow)
self.makeWindow.pack(side=LEFT) self.makeWindow.pack(side=LEFT)
def __init__(self, master=None): def __init__(self, master=None):
Frame.__init__(self, master) Frame.__init__(self, master)
Pack.config(self) Pack.config(self)
self.createWidgets() self.createWidgets()
test = Test() test = Test()
test.mainloop() test.mainloop()

View file

@ -19,9 +19,9 @@ def read32(input):
import zlib, sys import zlib, sys
if len(sys.argv)!=2: if len(sys.argv)!=2:
print 'Usage: minigzip.py <filename>' print 'Usage: minigzip.py <filename>'
print ' The file will be compressed or decompressed.' print ' The file will be compressed or decompressed.'
sys.exit(0) sys.exit(0)
filename=sys.argv[1] filename=sys.argv[1]
compressing=1 ; outputname=filename+'.gz' compressing=1 ; outputname=filename+'.gz'
@ -104,4 +104,3 @@ else:
if isize!=length: print 'Incorrect length of data produced' if isize!=length: print 'Incorrect length of data produced'
input.close() ; output.close() input.close() ; output.close()

View file

@ -4,7 +4,7 @@ import zlib, sys
if len(sys.argv)>1: filename=sys.argv[1] if len(sys.argv)>1: filename=sys.argv[1]
else: filename='zlibdemo.py' else: filename='zlibdemo.py'
print 'Reading', filename print 'Reading', filename
f=open(filename, 'r') # Get the data to compress f=open(filename, 'r') # Get the data to compress
s=f.read() s=f.read()
f.close() f.close()
@ -24,7 +24,7 @@ decompressor=zlib.decompressobj()
comptext=decomp='' comptext=decomp=''
for i in range(0, len(s), chunk): for i in range(0, len(s), chunk):
comptext=comptext+compressor.compress(s[i:i+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): for i in range(0, len(comptext), chunk):
decomp=decomp+decompressor.decompress(comptext[i:i+chunk]) decomp=decomp+decompressor.decompress(comptext[i:i+chunk])
@ -33,4 +33,3 @@ decomp=decomp+decompressor.flush()
print 'Progressive compression (level 9):' print 'Progressive compression (level 9):'
print ' Original:', len(s), 'Compressed:', len(comptext), print ' Original:', len(s), 'Compressed:', len(comptext),
print 'Uncompressed:', len(decomp) print 'Uncompressed:', len(decomp)

View file

@ -51,4 +51,3 @@ try:
has_key has_key
except NameError: except NameError:
from has_key import has_key from has_key import has_key

View file

@ -190,5 +190,3 @@ if __name__ == '__main__':
finally: finally:
_curses.endwin() _curses.endwin()
for i in L: print i for i in L: print i

View file

@ -6,4 +6,3 @@ Module for using panels with curses.
__revision__ = "$Id$" __revision__ = "$Id$"
from _curses_panel import * from _curses_panel import *

View file

@ -286,4 +286,3 @@ Your selection [default 1]: ''',
if self.show_response: if self.show_response:
print '-'*75, data, '-'*75 print '-'*75, data, '-'*75
return result return result

View file

@ -239,4 +239,3 @@ def run_setup (script_name, script_args=None, stop_after="run"):
return _setup_distribution return _setup_distribution
# run_setup () # run_setup ()

View file

@ -7,4 +7,3 @@ __revision__ = "$Id$"
# If DISTUTILS_DEBUG is anything other than the empty string, we run in # If DISTUTILS_DEBUG is anything other than the empty string, we run in
# debug mode. # debug mode.
DEBUG = os.environ.get('DISTUTILS_DEBUG') DEBUG = os.environ.get('DISTUTILS_DEBUG')

View file

@ -225,4 +225,3 @@ def ensure_relative (path):
if path[0:1] == os.sep: if path[0:1] == os.sep:
path = drive + path[1:] path = drive + path[1:]
return path return path

View file

@ -576,4 +576,3 @@ class MSVCCompiler (CCompiler) :
p = self.get_msvc_paths(name) p = self.get_msvc_paths(name)
if p: if p:
os.environ[name] = string.join(p, ';') os.environ[name] = string.join(p, ';')

View file

@ -206,7 +206,7 @@ class UnixCCompiler(CCompiler):
elif sys.platform[:5] == "hp-ux": elif sys.platform[:5] == "hp-ux":
return "+s -L" + dir return "+s -L" + dir
elif compiler[:3] == "gcc" or compiler[:3] == "g++": elif compiler[:3] == "gcc" or compiler[:3] == "g++":
return "-Wl,-R" + dir return "-Wl,-R" + dir
else: else:
return "-R" + dir return "-R" + dir

View file

@ -14,330 +14,330 @@ Int = type(0)
# different screen locations. Once rendered, it can be queried # different screen locations. Once rendered, it can be queried
# for mouse hits, and parts of the text can be highlighted # for mouse hits, and parts of the text can be highlighted
class Para: class Para:
# #
def __init__(self): def __init__(self):
self.words = [] # The words self.words = [] # The words
self.just = 'l' # Justification: 'l', 'r', 'lr' or 'c' self.just = 'l' # Justification: 'l', 'r', 'lr' or 'c'
self.indent_left = self.indent_right = self.indent_hang = 0 self.indent_left = self.indent_right = self.indent_hang = 0
# Final lay-out parameters, may change # Final lay-out parameters, may change
self.left = self.top = self.right = self.bottom = \ self.left = self.top = self.right = self.bottom = \
self.width = self.height = self.lines = None self.width = self.height = self.lines = None
# #
# Add a word, computing size information for it. # Add a word, computing size information for it.
# Words may also be added manually by appending to self.words # Words may also be added manually by appending to self.words
# Each word should be a 7-tuple: # Each word should be a 7-tuple:
# (font, text, width, space, stretch, ascent, descent) # (font, text, width, space, stretch, ascent, descent)
def addword(self, d, font, text, space, stretch): def addword(self, d, font, text, space, stretch):
if font is not None: if font is not None:
d.setfont(font) d.setfont(font)
width = d.textwidth(text) width = d.textwidth(text)
ascent = d.baseline() ascent = d.baseline()
descent = d.lineheight() - ascent descent = d.lineheight() - ascent
spw = d.textwidth(' ') spw = d.textwidth(' ')
space = space * spw space = space * spw
stretch = stretch * spw stretch = stretch * spw
tuple = (font, text, width, space, stretch, ascent, descent) tuple = (font, text, width, space, stretch, ascent, descent)
self.words.append(tuple) self.words.append(tuple)
# #
# Hooks to begin and end anchors -- insert numbers in the word list! # Hooks to begin and end anchors -- insert numbers in the word list!
def bgn_anchor(self, id): def bgn_anchor(self, id):
self.words.append(id) self.words.append(id)
# #
def end_anchor(self, id): def end_anchor(self, id):
self.words.append(0) self.words.append(0)
# #
# Return the total length (width) of the text added so far, in pixels # Return the total length (width) of the text added so far, in pixels
def getlength(self): def getlength(self):
total = 0 total = 0
for word in self.words: for word in self.words:
if type(word) is not Int: if type(word) is not Int:
total = total + word[2] + word[3] total = total + word[2] + word[3]
return total return total
# #
# Tab to a given position (relative to the current left indent): # Tab to a given position (relative to the current left indent):
# remove all stretch, add fixed space up to the new indent. # remove all stretch, add fixed space up to the new indent.
# If the current position is already at the tab stop, # If the current position is already at the tab stop,
# don't add any new space (but still remove the stretch) # don't add any new space (but still remove the stretch)
def tabto(self, tab): def tabto(self, tab):
total = 0 total = 0
as, de = 1, 0 as, de = 1, 0
for i in range(len(self.words)): for i in range(len(self.words)):
word = self.words[i] word = self.words[i]
if type(word) is Int: continue if type(word) is Int: continue
(fo, te, wi, sp, st, as, de) = word (fo, te, wi, sp, st, as, de) = word
self.words[i] = (fo, te, wi, sp, 0, as, de) self.words[i] = (fo, te, wi, sp, 0, as, de)
total = total + wi + sp total = total + wi + sp
if total < tab: if total < tab:
self.words.append((None, '', 0, tab-total, 0, as, de)) self.words.append((None, '', 0, tab-total, 0, as, de))
# #
# Make a hanging tag: tab to hang, increment indent_left by hang, # Make a hanging tag: tab to hang, increment indent_left by hang,
# and reset indent_hang to -hang # and reset indent_hang to -hang
def makehangingtag(self, hang): def makehangingtag(self, hang):
self.tabto(hang) self.tabto(hang)
self.indent_left = self.indent_left + hang self.indent_left = self.indent_left + hang
self.indent_hang = -hang self.indent_hang = -hang
# #
# Decide where the line breaks will be given some screen width # Decide where the line breaks will be given some screen width
def layout(self, linewidth): def layout(self, linewidth):
self.width = linewidth self.width = linewidth
height = 0 height = 0
self.lines = lines = [] self.lines = lines = []
avail1 = self.width - self.indent_left - self.indent_right avail1 = self.width - self.indent_left - self.indent_right
avail = avail1 - self.indent_hang avail = avail1 - self.indent_hang
words = self.words words = self.words
i = 0 i = 0
n = len(words) n = len(words)
lastfont = None lastfont = None
while i < n: while i < n:
firstfont = lastfont firstfont = lastfont
charcount = 0 charcount = 0
width = 0 width = 0
stretch = 0 stretch = 0
ascent = 0 ascent = 0
descent = 0 descent = 0
lsp = 0 lsp = 0
j = i j = i
while i < n: while i < n:
word = words[i] word = words[i]
if type(word) is Int: if type(word) is Int:
if word > 0 and width >= avail: if word > 0 and width >= avail:
break break
i = i+1 i = i+1
continue continue
fo, te, wi, sp, st, as, de = word fo, te, wi, sp, st, as, de = word
if width + wi > avail and width > 0 and wi > 0: if width + wi > avail and width > 0 and wi > 0:
break break
if fo is not None: if fo is not None:
lastfont = fo lastfont = fo
if width == 0: if width == 0:
firstfont = fo firstfont = fo
charcount = charcount + len(te) + (sp > 0) charcount = charcount + len(te) + (sp > 0)
width = width + wi + sp width = width + wi + sp
lsp = sp lsp = sp
stretch = stretch + st stretch = stretch + st
lst = st lst = st
ascent = max(ascent, as) ascent = max(ascent, as)
descent = max(descent, de) descent = max(descent, de)
i = i+1 i = i+1
while i > j and type(words[i-1]) is Int and \ while i > j and type(words[i-1]) is Int and \
words[i-1] > 0: i = i-1 words[i-1] > 0: i = i-1
width = width - lsp width = width - lsp
if i < n: if i < n:
stretch = stretch - lst stretch = stretch - lst
else: else:
stretch = 0 stretch = 0
tuple = i-j, firstfont, charcount, width, stretch, \ tuple = i-j, firstfont, charcount, width, stretch, \
ascent, descent ascent, descent
lines.append(tuple) lines.append(tuple)
height = height + ascent + descent height = height + ascent + descent
avail = avail1 avail = avail1
self.height = height self.height = height
# #
# Call a function for all words in a line # Call a function for all words in a line
def visit(self, wordfunc, anchorfunc): def visit(self, wordfunc, anchorfunc):
avail1 = self.width - self.indent_left - self.indent_right avail1 = self.width - self.indent_left - self.indent_right
avail = avail1 - self.indent_hang avail = avail1 - self.indent_hang
v = self.top v = self.top
i = 0 i = 0
for tuple in self.lines: for tuple in self.lines:
wordcount, firstfont, charcount, width, stretch, \ wordcount, firstfont, charcount, width, stretch, \
ascent, descent = tuple ascent, descent = tuple
h = self.left + self.indent_left h = self.left + self.indent_left
if i == 0: h = h + self.indent_hang if i == 0: h = h + self.indent_hang
extra = 0 extra = 0
if self.just == 'r': h = h + avail - width if self.just == 'r': h = h + avail - width
elif self.just == 'c': h = h + (avail - width) / 2 elif self.just == 'c': h = h + (avail - width) / 2
elif self.just == 'lr' and stretch > 0: elif self.just == 'lr' and stretch > 0:
extra = avail - width extra = avail - width
v2 = v + ascent + descent v2 = v + ascent + descent
for j in range(i, i+wordcount): for j in range(i, i+wordcount):
word = self.words[j] word = self.words[j]
if type(word) is Int: if type(word) is Int:
ok = anchorfunc(self, tuple, word, \ ok = anchorfunc(self, tuple, word, \
h, v) h, v)
if ok is not None: return ok if ok is not None: return ok
continue continue
fo, te, wi, sp, st, as, de = word fo, te, wi, sp, st, as, de = word
if extra > 0 and stretch > 0: if extra > 0 and stretch > 0:
ex = extra * st / stretch ex = extra * st / stretch
extra = extra - ex extra = extra - ex
stretch = stretch - st stretch = stretch - st
else: else:
ex = 0 ex = 0
h2 = h + wi + sp + ex h2 = h + wi + sp + ex
ok = wordfunc(self, tuple, word, h, v, \ ok = wordfunc(self, tuple, word, h, v, \
h2, v2, (j==i), (j==i+wordcount-1)) h2, v2, (j==i), (j==i+wordcount-1))
if ok is not None: return ok if ok is not None: return ok
h = h2 h = h2
v = v2 v = v2
i = i + wordcount i = i + wordcount
avail = avail1 avail = avail1
# #
# Render a paragraph in "drawing object" d, using the rectangle # Render a paragraph in "drawing object" d, using the rectangle
# given by (left, top, right) with an unspecified bottom. # given by (left, top, right) with an unspecified bottom.
# Return the computed bottom of the text. # Return the computed bottom of the text.
def render(self, d, left, top, right): def render(self, d, left, top, right):
if self.width != right-left: if self.width != right-left:
self.layout(right-left) self.layout(right-left)
self.left = left self.left = left
self.top = top self.top = top
self.right = right self.right = right
self.bottom = self.top + self.height self.bottom = self.top + self.height
self.anchorid = 0 self.anchorid = 0
try: try:
self.d = d self.d = d
self.visit(self.__class__._renderword, \ self.visit(self.__class__._renderword, \
self.__class__._renderanchor) self.__class__._renderanchor)
finally: finally:
self.d = None self.d = None
return self.bottom return self.bottom
# #
def _renderword(self, tuple, word, h, v, h2, v2, isfirst, islast): def _renderword(self, tuple, word, h, v, h2, v2, isfirst, islast):
if word[0] is not None: self.d.setfont(word[0]) if word[0] is not None: self.d.setfont(word[0])
baseline = v + tuple[5] baseline = v + tuple[5]
self.d.text((h, baseline - word[5]), word[1]) self.d.text((h, baseline - word[5]), word[1])
if self.anchorid > 0: if self.anchorid > 0:
self.d.line((h, baseline+2), (h2, baseline+2)) self.d.line((h, baseline+2), (h2, baseline+2))
# #
def _renderanchor(self, tuple, word, h, v): def _renderanchor(self, tuple, word, h, v):
self.anchorid = word self.anchorid = word
# #
# Return which anchor(s) was hit by the mouse # Return which anchor(s) was hit by the mouse
def hitcheck(self, mouseh, mousev): def hitcheck(self, mouseh, mousev):
self.mouseh = mouseh self.mouseh = mouseh
self.mousev = mousev self.mousev = mousev
self.anchorid = 0 self.anchorid = 0
self.hits = [] self.hits = []
self.visit(self.__class__._hitcheckword, \ self.visit(self.__class__._hitcheckword, \
self.__class__._hitcheckanchor) self.__class__._hitcheckanchor)
return self.hits return self.hits
# #
def _hitcheckword(self, tuple, word, h, v, h2, v2, isfirst, islast): def _hitcheckword(self, tuple, word, h, v, h2, v2, isfirst, islast):
if self.anchorid > 0 and h <= self.mouseh <= h2 and \ if self.anchorid > 0 and h <= self.mouseh <= h2 and \
v <= self.mousev <= v2: v <= self.mousev <= v2:
self.hits.append(self.anchorid) self.hits.append(self.anchorid)
# #
def _hitcheckanchor(self, tuple, word, h, v): def _hitcheckanchor(self, tuple, word, h, v):
self.anchorid = word self.anchorid = word
# #
# Return whether the given anchor id is present # Return whether the given anchor id is present
def hasanchor(self, id): def hasanchor(self, id):
return id in self.words or -id in self.words return id in self.words or -id in self.words
# #
# Extract the raw text from the word list, substituting one space # Extract the raw text from the word list, substituting one space
# for non-empty inter-word space, and terminating with '\n' # for non-empty inter-word space, and terminating with '\n'
def extract(self): def extract(self):
text = '' text = ''
for w in self.words: for w in self.words:
if type(w) is not Int: if type(w) is not Int:
word = w[1] word = w[1]
if w[3]: word = word + ' ' if w[3]: word = word + ' '
text = text + word text = text + word
return text + '\n' return text + '\n'
# #
# Return which character position was hit by the mouse, as # Return which character position was hit by the mouse, as
# an offset in the entire text as returned by extract(). # an offset in the entire text as returned by extract().
# Return None if the mouse was not in this paragraph # Return None if the mouse was not in this paragraph
def whereis(self, d, mouseh, mousev): def whereis(self, d, mouseh, mousev):
if mousev < self.top or mousev > self.bottom: if mousev < self.top or mousev > self.bottom:
return None return None
self.mouseh = mouseh self.mouseh = mouseh
self.mousev = mousev self.mousev = mousev
self.lastfont = None self.lastfont = None
self.charcount = 0 self.charcount = 0
try: try:
self.d = d self.d = d
return self.visit(self.__class__._whereisword, \ return self.visit(self.__class__._whereisword, \
self.__class__._whereisanchor) self.__class__._whereisanchor)
finally: finally:
self.d = None self.d = None
# #
def _whereisword(self, tuple, word, h1, v1, h2, v2, isfirst, islast): def _whereisword(self, tuple, word, h1, v1, h2, v2, isfirst, islast):
fo, te, wi, sp, st, as, de = word fo, te, wi, sp, st, as, de = word
if fo is not None: self.lastfont = fo if fo is not None: self.lastfont = fo
h = h1 h = h1
if isfirst: h1 = 0 if isfirst: h1 = 0
if islast: h2 = 999999 if islast: h2 = 999999
if not (v1 <= self.mousev <= v2 and h1 <= self.mouseh <= h2): if not (v1 <= self.mousev <= v2 and h1 <= self.mouseh <= h2):
self.charcount = self.charcount + len(te) + (sp > 0) self.charcount = self.charcount + len(te) + (sp > 0)
return return
if self.lastfont is not None: if self.lastfont is not None:
self.d.setfont(self.lastfont) self.d.setfont(self.lastfont)
cc = 0 cc = 0
for c in te: for c in te:
cw = self.d.textwidth(c) cw = self.d.textwidth(c)
if self.mouseh <= h + cw/2: if self.mouseh <= h + cw/2:
return self.charcount + cc return self.charcount + cc
cc = cc+1 cc = cc+1
h = h+cw h = h+cw
self.charcount = self.charcount + cc self.charcount = self.charcount + cc
if self.mouseh <= (h+h2) / 2: if self.mouseh <= (h+h2) / 2:
return self.charcount return self.charcount
else: else:
return self.charcount + 1 return self.charcount + 1
# #
def _whereisanchor(self, tuple, word, h, v): def _whereisanchor(self, tuple, word, h, v):
pass pass
# #
# Return screen position corresponding to position in paragraph. # Return screen position corresponding to position in paragraph.
# Return tuple (h, vtop, vbaseline, vbottom). # Return tuple (h, vtop, vbaseline, vbottom).
# This is more or less the inverse of whereis() # This is more or less the inverse of whereis()
def screenpos(self, d, pos): def screenpos(self, d, pos):
if pos < 0: if pos < 0:
ascent, descent = self.lines[0][5:7] ascent, descent = self.lines[0][5:7]
return self.left, self.top, self.top + ascent, \ return self.left, self.top, self.top + ascent, \
self.top + ascent + descent self.top + ascent + descent
self.pos = pos self.pos = pos
self.lastfont = None self.lastfont = None
try: try:
self.d = d self.d = d
ok = self.visit(self.__class__._screenposword, \ ok = self.visit(self.__class__._screenposword, \
self.__class__._screenposanchor) self.__class__._screenposanchor)
finally: finally:
self.d = None self.d = None
if ok is None: if ok is None:
ascent, descent = self.lines[-1][5:7] ascent, descent = self.lines[-1][5:7]
ok = self.right, self.bottom - ascent - descent, \ ok = self.right, self.bottom - ascent - descent, \
self.bottom - descent, self.bottom self.bottom - descent, self.bottom
return ok return ok
# #
def _screenposword(self, tuple, word, h1, v1, h2, v2, isfirst, islast): def _screenposword(self, tuple, word, h1, v1, h2, v2, isfirst, islast):
fo, te, wi, sp, st, as, de = word fo, te, wi, sp, st, as, de = word
if fo is not None: self.lastfont = fo if fo is not None: self.lastfont = fo
cc = len(te) + (sp > 0) cc = len(te) + (sp > 0)
if self.pos > cc: if self.pos > cc:
self.pos = self.pos - cc self.pos = self.pos - cc
return return
if self.pos < cc: if self.pos < cc:
self.d.setfont(self.lastfont) self.d.setfont(self.lastfont)
h = h1 + self.d.textwidth(te[:self.pos]) h = h1 + self.d.textwidth(te[:self.pos])
else: else:
h = h2 h = h2
ascent, descent = tuple[5:7] ascent, descent = tuple[5:7]
return h, v1, v1+ascent, v2 return h, v1, v1+ascent, v2
# #
def _screenposanchor(self, tuple, word, h, v): def _screenposanchor(self, tuple, word, h, v):
pass pass
# #
# Invert the stretch of text between pos1 and pos2. # Invert the stretch of text between pos1 and pos2.
# If pos1 is None, the beginning is implied; # If pos1 is None, the beginning is implied;
# if pos2 is None, the end is implied. # if pos2 is None, the end is implied.
# Undoes its own effect when called again with the same arguments # Undoes its own effect when called again with the same arguments
def invert(self, d, pos1, pos2): def invert(self, d, pos1, pos2):
if pos1 is None: if pos1 is None:
pos1 = self.left, self.top, self.top, self.top pos1 = self.left, self.top, self.top, self.top
else: else:
pos1 = self.screenpos(d, pos1) pos1 = self.screenpos(d, pos1)
if pos2 is None: if pos2 is None:
pos2 = self.right, self.bottom,self.bottom,self.bottom pos2 = self.right, self.bottom,self.bottom,self.bottom
else: else:
pos2 = self.screenpos(d, pos2) pos2 = self.screenpos(d, pos2)
h1, top1, baseline1, bottom1 = pos1 h1, top1, baseline1, bottom1 = pos1
h2, top2, baseline2, bottom2 = pos2 h2, top2, baseline2, bottom2 = pos2
if bottom1 <= top2: if bottom1 <= top2:
d.invert((h1, top1), (self.right, bottom1)) d.invert((h1, top1), (self.right, bottom1))
h1 = self.left h1 = self.left
if bottom1 < top2: if bottom1 < top2:
d.invert((h1, bottom1), (self.right, top2)) d.invert((h1, bottom1), (self.right, top2))
top1, bottom1 = top2, bottom2 top1, bottom1 = top2, bottom2
d.invert((h1, top1), (h2, bottom2)) d.invert((h1, top1), (h2, bottom2))

View file

@ -33,35 +33,35 @@
# #
# If no directory is found, ImportError is raised. # If no directory is found, ImportError is raised.
_packs = {} # {pack: [pathname, ...], ...} _packs = {} # {pack: [pathname, ...], ...}
def addpack(pack, *locations): def addpack(pack, *locations):
import os import os
if os.path.isabs(pack): if os.path.isabs(pack):
base = os.path.basename(pack) base = os.path.basename(pack)
else: else:
base = pack base = pack
if _packs.has_key(base): if _packs.has_key(base):
return return
import sys import sys
path = [] path = []
for loc in _flatten(locations) + sys.path: for loc in _flatten(locations) + sys.path:
fn = os.path.join(loc, base) fn = os.path.join(loc, base)
if fn not in path and os.path.isdir(fn): if fn not in path and os.path.isdir(fn):
path.append(fn) path.append(fn)
if pack != base and pack not in path and os.path.isdir(pack): if pack != base and pack not in path and os.path.isdir(pack):
path.append(pack) path.append(pack)
if not path: raise ImportError, 'package ' + pack + ' not found' if not path: raise ImportError, 'package ' + pack + ' not found'
_packs[base] = path _packs[base] = path
for fn in path: for fn in path:
if fn not in sys.path: if fn not in sys.path:
sys.path.append(fn) sys.path.append(fn)
def _flatten(locations): def _flatten(locations):
locs = [] locs = []
for loc in locations: for loc in locations:
if type(loc) == type(''): if type(loc) == type(''):
locs.append(loc) locs.append(loc)
else: else:
locs = locs + _flatten(loc) locs = locs + _flatten(loc)
return locs return locs

View file

@ -36,46 +36,46 @@ identchars = string.ascii_letters + string.digits + '_' # Identifier characters
_namecache = {} # The cache _namecache = {} # The cache
def getcodename(co): def getcodename(co):
try: try:
return co.co_name return co.co_name
except AttributeError: except AttributeError:
pass pass
key = `co` # arbitrary but uniquely identifying string key = `co` # arbitrary but uniquely identifying string
if _namecache.has_key(key): return _namecache[key] if _namecache.has_key(key): return _namecache[key]
filename = co.co_filename filename = co.co_filename
code = co.co_code code = co.co_code
name = '' name = ''
if ord(code[0]) == SET_LINENO: if ord(code[0]) == SET_LINENO:
lineno = ord(code[1]) | ord(code[2]) << 8 lineno = ord(code[1]) | ord(code[2]) << 8
line = linecache.getline(filename, lineno) line = linecache.getline(filename, lineno)
words = line.split() words = line.split()
if len(words) >= 2 and words[0] in ('def', 'class'): if len(words) >= 2 and words[0] in ('def', 'class'):
name = words[1] name = words[1]
for i in range(len(name)): for i in range(len(name)):
if name[i] not in identchars: if name[i] not in identchars:
name = name[:i] name = name[:i]
break break
_namecache[key] = name _namecache[key] = name
return name return name
# Use the above routine to find a function's name. # Use the above routine to find a function's name.
def getfuncname(func): def getfuncname(func):
try: try:
return func.func_name return func.func_name
except AttributeError: except AttributeError:
pass pass
return getcodename(func.func_code) return getcodename(func.func_code)
# A part of the above code to extract just the line number from a code object. # A part of the above code to extract just the line number from a code object.
def getlineno(co): def getlineno(co):
try: try:
return co.co_firstlineno return co.co_firstlineno
except AttributeError: except AttributeError:
pass pass
code = co.co_code code = co.co_code
if ord(code[0]) == SET_LINENO: if ord(code[0]) == SET_LINENO:
return ord(code[1]) | ord(code[2]) << 8 return ord(code[1]) | ord(code[2]) << 8
else: else:
return -1 return -1

View file

@ -23,41 +23,41 @@
# Dump a whole symbol table # Dump a whole symbol table
# #
def dumpsymtab(dict): def dumpsymtab(dict):
for key in dict.keys(): for key in dict.keys():
dumpvar(key, dict[key]) dumpvar(key, dict[key])
# Dump a single variable # Dump a single variable
# #
def dumpvar(name, x): def dumpvar(name, x):
import sys import sys
t = type(x) t = type(x)
if t == type({}): if t == type({}):
print name, '= {}' print name, '= {}'
for key in x.keys(): for key in x.keys():
item = x[key] item = x[key]
if not printable(item): if not printable(item):
print '#', print '#',
print name, '[', `key`, '] =', `item` print name, '[', `key`, '] =', `item`
elif t in (type(''), type(0), type(0.0), type([]), type(())): elif t in (type(''), type(0), type(0.0), type([]), type(())):
if not printable(x): if not printable(x):
print '#', print '#',
print name, '=', `x` print name, '=', `x`
elif t == type(sys): elif t == type(sys):
print 'import', name, '#', x print 'import', name, '#', x
else: else:
print '#', name, '=', x print '#', name, '=', x
# check if a value is printable in a way that can be read back with input() # check if a value is printable in a way that can be read back with input()
# #
def printable(x): def printable(x):
t = type(x) t = type(x)
if t in (type(''), type(0), type(0.0)): if t in (type(''), type(0), type(0.0)):
return 1 return 1
if t in (type([]), type(())): if t in (type([]), type(())):
for item in x: for item in x:
if not printable(item): if not printable(item):
return 0 return 0
return 1 return 1
if x == {}: if x == {}:
return 1 return 1
return 0 return 0

View file

@ -6,21 +6,21 @@ _debug = 0
_prune = ['(*)'] _prune = ['(*)']
def find(pattern, dir = os.curdir): def find(pattern, dir = os.curdir):
list = [] list = []
names = os.listdir(dir) names = os.listdir(dir)
names.sort() names.sort()
for name in names: for name in names:
if name in (os.curdir, os.pardir): if name in (os.curdir, os.pardir):
continue continue
fullname = os.path.join(dir, name) fullname = os.path.join(dir, name)
if fnmatch.fnmatch(name, pattern): if fnmatch.fnmatch(name, pattern):
list.append(fullname) list.append(fullname)
if os.path.isdir(fullname) and not os.path.islink(fullname): if os.path.isdir(fullname) and not os.path.islink(fullname):
for p in _prune: for p in _prune:
if fnmatch.fnmatch(name, p): if fnmatch.fnmatch(name, p):
if _debug: print "skip", `fullname` if _debug: print "skip", `fullname`
break break
else: else:
if _debug: print "descend into", `fullname` if _debug: print "descend into", `fullname`
list = list + find(pattern, fullname) list = list + find(pattern, fullname)
return list return list

File diff suppressed because it is too large Load diff

View file

@ -8,72 +8,72 @@ opt_show_filename = 0
opt_show_lineno = 1 opt_show_lineno = 1
def grep(pat, *files): def grep(pat, *files):
return ggrep(RE_SYNTAX_GREP, pat, files) return ggrep(RE_SYNTAX_GREP, pat, files)
def egrep(pat, *files): def egrep(pat, *files):
return ggrep(RE_SYNTAX_EGREP, pat, files) return ggrep(RE_SYNTAX_EGREP, pat, files)
def emgrep(pat, *files): def emgrep(pat, *files):
return ggrep(RE_SYNTAX_EMACS, pat, files) return ggrep(RE_SYNTAX_EMACS, pat, files)
def ggrep(syntax, pat, files): def ggrep(syntax, pat, files):
if len(files) == 1 and type(files[0]) == type([]): if len(files) == 1 and type(files[0]) == type([]):
files = files[0] files = files[0]
global opt_show_filename global opt_show_filename
opt_show_filename = (len(files) != 1) opt_show_filename = (len(files) != 1)
syntax = regex.set_syntax(syntax) syntax = regex.set_syntax(syntax)
try: try:
prog = regex.compile(pat) prog = regex.compile(pat)
finally: finally:
syntax = regex.set_syntax(syntax) syntax = regex.set_syntax(syntax)
for filename in files: for filename in files:
fp = open(filename, 'r') fp = open(filename, 'r')
lineno = 0 lineno = 0
while 1: while 1:
line = fp.readline() line = fp.readline()
if not line: break if not line: break
lineno = lineno + 1 lineno = lineno + 1
if prog.search(line) >= 0: if prog.search(line) >= 0:
showline(filename, lineno, line, prog) showline(filename, lineno, line, prog)
fp.close() fp.close()
def pgrep(pat, *files): def pgrep(pat, *files):
if len(files) == 1 and type(files[0]) == type([]): if len(files) == 1 and type(files[0]) == type([]):
files = files[0] files = files[0]
global opt_show_filename global opt_show_filename
opt_show_filename = (len(files) != 1) opt_show_filename = (len(files) != 1)
import re import re
prog = re.compile(pat) prog = re.compile(pat)
for filename in files: for filename in files:
fp = open(filename, 'r') fp = open(filename, 'r')
lineno = 0 lineno = 0
while 1: while 1:
line = fp.readline() line = fp.readline()
if not line: break if not line: break
lineno = lineno + 1 lineno = lineno + 1
if prog.search(line): if prog.search(line):
showline(filename, lineno, line, prog) showline(filename, lineno, line, prog)
fp.close() fp.close()
def showline(filename, lineno, line, prog): def showline(filename, lineno, line, prog):
if line[-1:] == '\n': line = line[:-1] if line[-1:] == '\n': line = line[:-1]
if opt_show_lineno: if opt_show_lineno:
prefix = `lineno`.rjust(3) + ': ' prefix = `lineno`.rjust(3) + ': '
else: else:
prefix = '' prefix = ''
if opt_show_filename: if opt_show_filename:
prefix = filename + ': ' + prefix prefix = filename + ': ' + prefix
print prefix + line print prefix + line
if opt_show_where: if opt_show_where:
start, end = prog.regs()[0] start, end = prog.regs()[0]
line = line[:start] line = line[:start]
if '\t' not in line: if '\t' not in line:
prefix = ' ' * (len(prefix) + start) prefix = ' ' * (len(prefix) + start)
else: else:
prefix = ' ' * len(prefix) prefix = ' ' * len(prefix)
for c in line: for c in line:
if c != '\t': c = ' ' if c != '\t': c = ' '
prefix = prefix + c prefix = prefix + c
if start == end: prefix = prefix + '\\' if start == end: prefix = prefix + '\\'
else: prefix = prefix + '^'*(end-start) else: prefix = prefix + '^'*(end-start)
print prefix print prefix

View file

@ -1,15 +1,15 @@
import struct, fcntl import struct, fcntl
def writelock(f): def writelock(f):
_lock(f, fcntl.F_WRLCK) _lock(f, fcntl.F_WRLCK)
def readlock(f): def readlock(f):
_lock(f, fcntl.F_RDLCK) _lock(f, fcntl.F_RDLCK)
def unlock(f): def unlock(f):
_lock(f, fcntl.F_UNLCK) _lock(f, fcntl.F_UNLCK)
def _lock(f, op): def _lock(f, op):
dummy = fcntl.fcntl(f.fileno(), fcntl.F_SETLKW, dummy = fcntl.fcntl(f.fileno(), fcntl.F_SETLKW,
struct.pack('2h8l', op, struct.pack('2h8l', op,
0, 0, 0, 0, 0, 0, 0, 0, 0)) 0, 0, 0, 0, 0, 0, 0, 0, 0))

View file

@ -5,69 +5,69 @@
# the current local name space by default # the current local name space by default
def listattrs(x): def listattrs(x):
try: try:
dictkeys = x.__dict__.keys() dictkeys = x.__dict__.keys()
except (AttributeError, TypeError): except (AttributeError, TypeError):
dictkeys = [] dictkeys = []
# #
try: try:
methods = x.__methods__ methods = x.__methods__
except (AttributeError, TypeError): except (AttributeError, TypeError):
methods = [] methods = []
# #
try: try:
members = x.__members__ members = x.__members__
except (AttributeError, TypeError): except (AttributeError, TypeError):
members = [] members = []
# #
try: try:
the_class = x.__class__ the_class = x.__class__
except (AttributeError, TypeError): except (AttributeError, TypeError):
the_class = None the_class = None
# #
try: try:
bases = x.__bases__ bases = x.__bases__
except (AttributeError, TypeError): except (AttributeError, TypeError):
bases = () bases = ()
# #
total = dictkeys + methods + members total = dictkeys + methods + members
if the_class: if the_class:
# It's a class instace; add the class's attributes # It's a class instace; add the class's attributes
# that are functions (methods)... # that are functions (methods)...
class_attrs = listattrs(the_class) class_attrs = listattrs(the_class)
class_methods = [] class_methods = []
for name in class_attrs: for name in class_attrs:
if is_function(getattr(the_class, name)): if is_function(getattr(the_class, name)):
class_methods.append(name) class_methods.append(name)
total = total + class_methods total = total + class_methods
elif bases: elif bases:
# It's a derived class; add the base class attributes # It's a derived class; add the base class attributes
for base in bases: for base in bases:
base_attrs = listattrs(base) base_attrs = listattrs(base)
total = total + base_attrs total = total + base_attrs
total.sort() total.sort()
return total return total
i = 0 i = 0
while i+1 < len(total): while i+1 < len(total):
if total[i] == total[i+1]: if total[i] == total[i+1]:
del total[i+1] del total[i+1]
else: else:
i = i+1 i = i+1
return total return total
# Helper to recognize functions # Helper to recognize functions
def is_function(x): def is_function(x):
return type(x) == type(is_function) return type(x) == type(is_function)
# Approximation of builtin dir(); but note that this lists the user's # Approximation of builtin dir(); but note that this lists the user's
# variables by default, not the current local name space. # variables by default, not the current local name space.
def dir(x = None): def dir(x = None):
if x is not None: if x is not None:
return listattrs(x) return listattrs(x)
else: else:
import __main__ import __main__
return listattrs(__main__) return listattrs(__main__)

View file

@ -8,104 +8,104 @@ from stat import ST_MTIME
# Print help # Print help
def help(): def help():
print 'All fns have a file open for writing as first parameter' print 'All fns have a file open for writing as first parameter'
print 'pack(f, fullname, name): pack fullname as name' print 'pack(f, fullname, name): pack fullname as name'
print 'packsome(f, directory, namelist): selected files from directory' print 'packsome(f, directory, namelist): selected files from directory'
print 'packall(f, directory): pack all files from directory' print 'packall(f, directory): pack all files from directory'
print 'packnotolder(f, directory, name): pack all files from directory' print 'packnotolder(f, directory, name): pack all files from directory'
print ' that are not older than a file there' print ' that are not older than a file there'
print 'packtree(f, directory): pack entire directory tree' print 'packtree(f, directory): pack entire directory tree'
# Pack one file # Pack one file
def pack(outfp, file, name): def pack(outfp, file, name):
fp = open(file, 'r') fp = open(file, 'r')
outfp.write('echo ' + name + '\n') outfp.write('echo ' + name + '\n')
outfp.write('sed "s/^X//" >"' + name + '" <<"!"\n') outfp.write('sed "s/^X//" >"' + name + '" <<"!"\n')
while 1: while 1:
line = fp.readline() line = fp.readline()
if not line: break if not line: break
if line[-1:] != '\n': if line[-1:] != '\n':
line = line + '\n' line = line + '\n'
outfp.write('X' + line) outfp.write('X' + line)
outfp.write('!\n') outfp.write('!\n')
fp.close() fp.close()
# Pack some files from a directory # Pack some files from a directory
def packsome(outfp, dirname, names): def packsome(outfp, dirname, names):
for name in names: for name in names:
print name print name
file = os.path.join(dirname, name) file = os.path.join(dirname, name)
pack(outfp, file, name) pack(outfp, file, name)
# Pack all files from a directory # Pack all files from a directory
def packall(outfp, dirname): def packall(outfp, dirname):
names = os.listdir(dirname) names = os.listdir(dirname)
try: try:
names.remove('.') names.remove('.')
except: except:
pass pass
try: try:
names.remove('..') names.remove('..')
except: except:
pass pass
names.sort() names.sort()
packsome(outfp, dirname, names) packsome(outfp, dirname, names)
# Pack all files from a directory that are not older than a give one # Pack all files from a directory that are not older than a give one
def packnotolder(outfp, dirname, oldest): def packnotolder(outfp, dirname, oldest):
names = os.listdir(dirname) names = os.listdir(dirname)
try: try:
names.remove('.') names.remove('.')
except: except:
pass pass
try: try:
names.remove('..') names.remove('..')
except: except:
pass pass
oldest = os.path.join(dirname, oldest) oldest = os.path.join(dirname, oldest)
st = os.stat(oldest) st = os.stat(oldest)
mtime = st[ST_MTIME] mtime = st[ST_MTIME]
todo = [] todo = []
for name in names: for name in names:
print name, '...', print name, '...',
st = os.stat(os.path.join(dirname, name)) st = os.stat(os.path.join(dirname, name))
if st[ST_MTIME] >= mtime: if st[ST_MTIME] >= mtime:
print 'Yes.' print 'Yes.'
todo.append(name) todo.append(name)
else: else:
print 'No.' print 'No.'
todo.sort() todo.sort()
packsome(outfp, dirname, todo) packsome(outfp, dirname, todo)
# Pack a whole tree (no exceptions) # Pack a whole tree (no exceptions)
def packtree(outfp, dirname): def packtree(outfp, dirname):
print 'packtree', dirname print 'packtree', dirname
outfp.write('mkdir ' + unixfix(dirname) + '\n') outfp.write('mkdir ' + unixfix(dirname) + '\n')
names = os.listdir(dirname) names = os.listdir(dirname)
try: try:
names.remove('.') names.remove('.')
except: except:
pass pass
try: try:
names.remove('..') names.remove('..')
except: except:
pass pass
subdirs = [] subdirs = []
for name in names: for name in names:
fullname = os.path.join(dirname, name) fullname = os.path.join(dirname, name)
if os.path.isdir(fullname): if os.path.isdir(fullname):
subdirs.append(fullname) subdirs.append(fullname)
else: else:
print 'pack', fullname print 'pack', fullname
pack(outfp, fullname, unixfix(fullname)) pack(outfp, fullname, unixfix(fullname))
for subdirname in subdirs: for subdirname in subdirs:
packtree(outfp, subdirname) packtree(outfp, subdirname)
def unixfix(name): def unixfix(name):
comps = name.split(os.sep) comps = name.split(os.sep)
res = '' res = ''
for comp in comps: for comp in comps:
if comp: if comp:
if res: res = res + '/' if res: res = res + '/'
res = res + comp res = res + comp
return res return res

View file

@ -6,47 +6,47 @@
# taken out by normalize(). # taken out by normalize().
def normalize(p): # Strip unnecessary zero coefficients def normalize(p): # Strip unnecessary zero coefficients
n = len(p) n = len(p)
while n: while n:
if p[n-1]: return p[:n] if p[n-1]: return p[:n]
n = n-1 n = n-1
return [] return []
def plus(a, b): def plus(a, b):
if len(a) < len(b): a, b = b, a # make sure a is the longest if len(a) < len(b): a, b = b, a # make sure a is the longest
res = a[:] # make a copy res = a[:] # make a copy
for i in range(len(b)): for i in range(len(b)):
res[i] = res[i] + b[i] res[i] = res[i] + b[i]
return normalize(res) return normalize(res)
def minus(a, b): def minus(a, b):
neg_b = map(lambda x: -x, b[:]) neg_b = map(lambda x: -x, b[:])
return plus(a, neg_b) return plus(a, neg_b)
def one(power, coeff): # Representation of coeff * x**power def one(power, coeff): # Representation of coeff * x**power
res = [] res = []
for i in range(power): res.append(0) for i in range(power): res.append(0)
return res + [coeff] return res + [coeff]
def times(a, b): def times(a, b):
res = [] res = []
for i in range(len(a)): for i in range(len(a)):
for j in range(len(b)): for j in range(len(b)):
res = plus(res, one(i+j, a[i]*b[j])) res = plus(res, one(i+j, a[i]*b[j]))
return res return res
def power(a, n): # Raise polynomial a to the positive integral power n def power(a, n): # Raise polynomial a to the positive integral power n
if n == 0: return [1] if n == 0: return [1]
if n == 1: return a if n == 1: return a
if n/2*2 == n: if n/2*2 == n:
b = power(a, n/2) b = power(a, n/2)
return times(b, b) return times(b, b)
return times(power(a, n-1), a) return times(power(a, n-1), a)
def der(a): # First derivative def der(a): # First derivative
res = a[1:] res = a[1:]
for i in range(len(res)): for i in range(len(res)):
res[i] = res[i] * (i+1) res[i] = res[i] * (i+1)
return res return res
# Computing a primitive function would require rational arithmetic... # Computing a primitive function would require rational arithmetic...

View file

@ -4,10 +4,10 @@
import whrandom import whrandom
def srand(seed): def srand(seed):
whrandom.seed(seed%256, seed/256%256, seed/65536%256) whrandom.seed(seed%256, seed/256%256, seed/65536%256)
def rand(): def rand():
return int(whrandom.random() * 32768.0) % 32768 return int(whrandom.random() * 32768.0) % 32768
def choice(seq): def choice(seq):
return seq[rand() % len(seq)] return seq[rand() % len(seq)]

View file

@ -12,166 +12,166 @@ def br(): browser(sys.last_traceback)
def tb(): printtb(sys.last_traceback) def tb(): printtb(sys.last_traceback)
def browser(tb): def browser(tb):
if not tb: if not tb:
print 'No traceback.' print 'No traceback.'
return return
tblist = [] tblist = []
while tb: while tb:
tblist.append(tb) tblist.append(tb)
tb = tb.tb_next tb = tb.tb_next
ptr = len(tblist)-1 ptr = len(tblist)-1
tb = tblist[ptr] tb = tblist[ptr]
while 1: while 1:
if tb != tblist[ptr]: if tb != tblist[ptr]:
tb = tblist[ptr] tb = tblist[ptr]
print `ptr` + ':', print `ptr` + ':',
printtbheader(tb) printtbheader(tb)
try: try:
line = raw_input('TB: ') line = raw_input('TB: ')
except KeyboardInterrupt: except KeyboardInterrupt:
print '\n[Interrupted]' print '\n[Interrupted]'
break break
except EOFError: except EOFError:
print '\n[EOF]' print '\n[EOF]'
break break
cmd = line.strip() cmd = line.strip()
if cmd: if cmd:
if cmd == 'quit': if cmd == 'quit':
break break
elif cmd == 'list': elif cmd == 'list':
browserlist(tb) browserlist(tb)
elif cmd == 'up': elif cmd == 'up':
if ptr-1 >= 0: ptr = ptr-1 if ptr-1 >= 0: ptr = ptr-1
else: print 'Bottom of stack.' else: print 'Bottom of stack.'
elif cmd == 'down': elif cmd == 'down':
if ptr+1 < len(tblist): ptr = ptr+1 if ptr+1 < len(tblist): ptr = ptr+1
else: print 'Top of stack.' else: print 'Top of stack.'
elif cmd == 'locals': elif cmd == 'locals':
printsymbols(tb.tb_frame.f_locals) printsymbols(tb.tb_frame.f_locals)
elif cmd == 'globals': elif cmd == 'globals':
printsymbols(tb.tb_frame.f_globals) printsymbols(tb.tb_frame.f_globals)
elif cmd in ('?', 'help'): elif cmd in ('?', 'help'):
browserhelp() browserhelp()
else: else:
browserexec(tb, cmd) browserexec(tb, cmd)
def browserlist(tb): def browserlist(tb):
filename = tb.tb_frame.f_code.co_filename filename = tb.tb_frame.f_code.co_filename
lineno = tb.tb_lineno lineno = tb.tb_lineno
last = lineno last = lineno
first = max(1, last-10) first = max(1, last-10)
for i in range(first, last+1): for i in range(first, last+1):
if i == lineno: prefix = '***' + `i`.rjust(4) + ':' if i == lineno: prefix = '***' + `i`.rjust(4) + ':'
else: prefix = `i`.rjust(7) + ':' else: prefix = `i`.rjust(7) + ':'
line = linecache.getline(filename, i) line = linecache.getline(filename, i)
if line[-1:] == '\n': line = line[:-1] if line[-1:] == '\n': line = line[:-1]
print prefix + line print prefix + line
def browserexec(tb, cmd): def browserexec(tb, cmd):
locals = tb.tb_frame.f_locals locals = tb.tb_frame.f_locals
globals = tb.tb_frame.f_globals globals = tb.tb_frame.f_globals
try: try:
exec cmd+'\n' in globals, locals exec cmd+'\n' in globals, locals
except: except:
t, v = sys.exc_info()[:2] t, v = sys.exc_info()[:2]
print '*** Exception:', print '*** Exception:',
if type(t) is type(''): if type(t) is type(''):
print t, print t,
else: else:
print t.__name__, print t.__name__,
if v is not None: if v is not None:
print ':', v, print ':', v,
print print
print 'Type help to get help.' print 'Type help to get help.'
def browserhelp(): def browserhelp():
print print
print ' This is the traceback browser. Commands are:' print ' This is the traceback browser. Commands are:'
print ' up : move one level up in the call stack' print ' up : move one level up in the call stack'
print ' down : move one level down in the call stack' print ' down : move one level down in the call stack'
print ' locals : print all local variables at this level' print ' locals : print all local variables at this level'
print ' globals : print all global variables at this level' print ' globals : print all global variables at this level'
print ' list : list source code around the failure' print ' list : list source code around the failure'
print ' help : print help (what you are reading now)' print ' help : print help (what you are reading now)'
print ' quit : back to command interpreter' print ' quit : back to command interpreter'
print ' Typing any other 1-line statement will execute it' print ' Typing any other 1-line statement will execute it'
print ' using the current level\'s symbol tables' print ' using the current level\'s symbol tables'
print print
def printtb(tb): def printtb(tb):
while tb: while tb:
print1tb(tb) print1tb(tb)
tb = tb.tb_next tb = tb.tb_next
def print1tb(tb): def print1tb(tb):
printtbheader(tb) printtbheader(tb)
if tb.tb_frame.f_locals is not tb.tb_frame.f_globals: if tb.tb_frame.f_locals is not tb.tb_frame.f_globals:
printsymbols(tb.tb_frame.f_locals) printsymbols(tb.tb_frame.f_locals)
def printtbheader(tb): def printtbheader(tb):
filename = tb.tb_frame.f_code.co_filename filename = tb.tb_frame.f_code.co_filename
lineno = tb.tb_lineno lineno = tb.tb_lineno
info = '"' + filename + '"(' + `lineno` + ')' info = '"' + filename + '"(' + `lineno` + ')'
line = linecache.getline(filename, lineno) line = linecache.getline(filename, lineno)
if line: if line:
info = info + ': ' + line.strip() info = info + ': ' + line.strip()
print info print info
def printsymbols(d): def printsymbols(d):
keys = d.keys() keys = d.keys()
keys.sort() keys.sort()
for name in keys: for name in keys:
print ' ' + name.ljust(12) + ':', print ' ' + name.ljust(12) + ':',
printobject(d[name], 4) printobject(d[name], 4)
print print
def printobject(v, maxlevel): def printobject(v, maxlevel):
if v is None: if v is None:
print 'None', print 'None',
elif type(v) in (type(0), type(0.0)): elif type(v) in (type(0), type(0.0)):
print v, print v,
elif type(v) is type(''): elif type(v) is type(''):
if len(v) > 20: if len(v) > 20:
print `v[:17] + '...'`, print `v[:17] + '...'`,
else: else:
print `v`, print `v`,
elif type(v) is type(()): elif type(v) is type(()):
print '(', print '(',
printlist(v, maxlevel) printlist(v, maxlevel)
print ')', print ')',
elif type(v) is type([]): elif type(v) is type([]):
print '[', print '[',
printlist(v, maxlevel) printlist(v, maxlevel)
print ']', print ']',
elif type(v) is type({}): elif type(v) is type({}):
print '{', print '{',
printdict(v, maxlevel) printdict(v, maxlevel)
print '}', print '}',
else: else:
print v, print v,
def printlist(v, maxlevel): def printlist(v, maxlevel):
n = len(v) n = len(v)
if n == 0: return if n == 0: return
if maxlevel <= 0: if maxlevel <= 0:
print '...', print '...',
return return
for i in range(min(6, n)): for i in range(min(6, n)):
printobject(v[i], maxlevel-1) printobject(v[i], maxlevel-1)
if i+1 < n: print ',', if i+1 < n: print ',',
if n > 6: print '...', if n > 6: print '...',
def printdict(v, maxlevel): def printdict(v, maxlevel):
keys = v.keys() keys = v.keys()
n = len(keys) n = len(keys)
if n == 0: return if n == 0: return
if maxlevel <= 0: if maxlevel <= 0:
print '...', print '...',
return return
keys.sort() keys.sort()
for i in range(min(6, n)): for i in range(min(6, n)):
key = keys[i] key = keys[i]
print `key` + ':', print `key` + ':',
printobject(v[key], maxlevel-1) printobject(v[key], maxlevel-1)
if i+1 < n: print ',', if i+1 < n: print ',',
if n > 6: print '...', if n > 6: print '...',

View file

@ -10,16 +10,16 @@
# If it occurs more than once, remove the first occurrence. # If it occurs more than once, remove the first occurrence.
# #
def remove(item, list): def remove(item, list):
if item in list: list.remove(item) if item in list: list.remove(item)
# Return a string containing a file's contents. # Return a string containing a file's contents.
# #
def readfile(fn): def readfile(fn):
return readopenfile(open(fn, 'r')) return readopenfile(open(fn, 'r'))
# Read an open file until EOF. # Read an open file until EOF.
# #
def readopenfile(fp): def readopenfile(fp):
return fp.read() return fp.read()

View file

@ -30,65 +30,65 @@ P = poly.plus(poly.one(0, 2), poly.one(2, 1)) # 2 + x**2
# Return x modulo y. Returns >= 0 even if x < 0. # Return x modulo y. Returns >= 0 even if x < 0.
def mod(x, y): def mod(x, y):
return divmod(x, y)[1] return divmod(x, y)[1]
# Normalize a polynomial modulo n and modulo p. # Normalize a polynomial modulo n and modulo p.
def norm(a, n, p): def norm(a, n, p):
a = poly.modulo(a, p) a = poly.modulo(a, p)
a = a[:] a = a[:]
for i in range(len(a)): a[i] = mod(a[i], n) for i in range(len(a)): a[i] = mod(a[i], n)
a = poly.normalize(a) a = poly.normalize(a)
return a return a
# Make a list of all n^d elements of the proposed field. # Make a list of all n^d elements of the proposed field.
def make_all(mat): def make_all(mat):
all = [] all = []
for row in mat: for row in mat:
for a in row: for a in row:
all.append(a) all.append(a)
return all return all
def make_elements(n, d): def make_elements(n, d):
if d == 0: return [poly.one(0, 0)] if d == 0: return [poly.one(0, 0)]
sub = make_elements(n, d-1) sub = make_elements(n, d-1)
all = [] all = []
for a in sub: for a in sub:
for i in range(n): for i in range(n):
all.append(poly.plus(a, poly.one(d-1, i))) all.append(poly.plus(a, poly.one(d-1, i)))
return all return all
def make_inv(all, n, p): def make_inv(all, n, p):
x = poly.one(1, 1) x = poly.one(1, 1)
inv = [] inv = []
for a in all: for a in all:
inv.append(norm(poly.times(a, x), n, p)) inv.append(norm(poly.times(a, x), n, p))
return inv return inv
def checkfield(n, p): def checkfield(n, p):
all = make_elements(n, len(p)-1) all = make_elements(n, len(p)-1)
inv = make_inv(all, n, p) inv = make_inv(all, n, p)
all1 = all[:] all1 = all[:]
inv1 = inv[:] inv1 = inv[:]
all1.sort() all1.sort()
inv1.sort() inv1.sort()
if all1 == inv1: print 'BINGO!' if all1 == inv1: print 'BINGO!'
else: else:
print 'Sorry:', n, p print 'Sorry:', n, p
print all print all
print inv print inv
def rj(s, width): def rj(s, width):
if type(s) is not type(''): s = `s` if type(s) is not type(''): s = `s`
n = len(s) n = len(s)
if n >= width: return s if n >= width: return s
return ' '*(width - n) + s return ' '*(width - n) + s
def lj(s, width): def lj(s, width):
if type(s) is not type(''): s = `s` if type(s) is not type(''): s = `s`
n = len(s) n = len(s)
if n >= width: return s if n >= width: return s
return s + ' '*(width - n) return s + ' '*(width - n)

View file

@ -1104,15 +1104,15 @@ class ListNoteBook(TixWidget):
return self.subwidget_list[name] return self.subwidget_list[name]
def page(self, name): def page(self, name):
return self.subwidget(name) return self.subwidget(name)
def pages(self): def pages(self):
# Can't call subwidgets_all directly because we don't want .nbframe # Can't call subwidgets_all directly because we don't want .nbframe
names = self.tk.split(self.tk.call(self._w, 'pages')) names = self.tk.split(self.tk.call(self._w, 'pages'))
ret = [] ret = []
for x in names: for x in names:
ret.append(self.subwidget(x)) ret.append(self.subwidget(x))
return ret return ret
def raise_page(self, name): # raise is a python keyword def raise_page(self, name): # raise is a python keyword
self.tk.call(self._w, 'raise', name) self.tk.call(self._w, 'raise', name)
@ -1737,7 +1737,7 @@ class _dummyNoteBookFrame(NoteBookFrame, TixSubWidget):
class _dummyPanedWindow(PanedWindow, TixSubWidget): class _dummyPanedWindow(PanedWindow, TixSubWidget):
def __init__(self, master, name, destroy_physically=1): def __init__(self, master, name, destroy_physically=1):
TixSubWidget.__init__(self, master, name, destroy_physically) TixSubWidget.__init__(self, master, name, destroy_physically)
######################## ########################
### Utility Routines ### ### Utility Routines ###

View file

@ -213,4 +213,3 @@ if __name__ == "__main__":
saveasfilename=asksaveasfilename() saveasfilename=asksaveasfilename()
print "saveas", saveasfilename.encode(enc) print "saveas", saveasfilename.encode(enc)

View file

@ -942,4 +942,3 @@ def IN6_IS_ADDR_MC_SITELOCAL(a): return \
def IN6_IS_ADDR_MC_ORGLOCAL(a): return \ def IN6_IS_ADDR_MC_ORGLOCAL(a): return \
def IN6_IS_ADDR_MC_GLOBAL(a): return \ def IN6_IS_ADDR_MC_GLOBAL(a): return \

View file

@ -140,4 +140,3 @@ _SYS_SYSMACROS_H = 1
def major(dev): return ( (( (dev) >> 8) & 0xff)) def major(dev): return ( (( (dev) >> 8) & 0xff))
def minor(dev): return ( ((dev) & 0xff)) def minor(dev): return ( ((dev) & 0xff))

View file

@ -1,61 +1,61 @@
RATE_48000 = 48000 RATE_48000 = 48000
RATE_44100 = 44100 RATE_44100 = 44100
RATE_32000 = 32000 RATE_32000 = 32000
RATE_22050 = 22050 RATE_22050 = 22050
RATE_16000 = 16000 RATE_16000 = 16000
RATE_11025 = 11025 RATE_11025 = 11025
RATE_8000 = 8000 RATE_8000 = 8000
SAMPFMT_TWOSCOMP= 1 SAMPFMT_TWOSCOMP= 1
SAMPFMT_FLOAT = 32 SAMPFMT_FLOAT = 32
SAMPFMT_DOUBLE = 64 SAMPFMT_DOUBLE = 64
SAMPLE_8 = 1 SAMPLE_8 = 1
SAMPLE_16 = 2 SAMPLE_16 = 2
# SAMPLE_24 is the low 24 bits of a long, sign extended to 32 bits # SAMPLE_24 is the low 24 bits of a long, sign extended to 32 bits
SAMPLE_24 = 4 SAMPLE_24 = 4
MONO = 1 MONO = 1
STEREO = 2 STEREO = 2
QUADRO = 4 # 4CHANNEL is not a legal Python name QUADRO = 4 # 4CHANNEL is not a legal Python name
INPUT_LINE = 0 INPUT_LINE = 0
INPUT_MIC = 1 INPUT_MIC = 1
INPUT_DIGITAL = 2 INPUT_DIGITAL = 2
MONITOR_OFF = 0 MONITOR_OFF = 0
MONITOR_ON = 1 MONITOR_ON = 1
ERROR_NUMBER = 0 ERROR_NUMBER = 0
ERROR_TYPE = 1 ERROR_TYPE = 1
ERROR_LOCATION_LSP = 2 ERROR_LOCATION_LSP = 2
ERROR_LOCATION_MSP = 3 ERROR_LOCATION_MSP = 3
ERROR_LENGTH = 4 ERROR_LENGTH = 4
ERROR_INPUT_UNDERFLOW = 0 ERROR_INPUT_UNDERFLOW = 0
ERROR_OUTPUT_OVERFLOW = 1 ERROR_OUTPUT_OVERFLOW = 1
# These seem to be not supported anymore: # These seem to be not supported anymore:
##HOLD, RELEASE = 0, 1 ##HOLD, RELEASE = 0, 1
##ATTAIL, ATHEAD, ATMARK, ATTIME = 0, 1, 2, 3 ##ATTAIL, ATHEAD, ATMARK, ATTIME = 0, 1, 2, 3
DEFAULT_DEVICE = 1 DEFAULT_DEVICE = 1
INPUT_SOURCE = 0 INPUT_SOURCE = 0
LEFT_INPUT_ATTEN = 1 LEFT_INPUT_ATTEN = 1
RIGHT_INPUT_ATTEN = 2 RIGHT_INPUT_ATTEN = 2
INPUT_RATE = 3 INPUT_RATE = 3
OUTPUT_RATE = 4 OUTPUT_RATE = 4
LEFT_SPEAKER_GAIN = 5 LEFT_SPEAKER_GAIN = 5
RIGHT_SPEAKER_GAIN = 6 RIGHT_SPEAKER_GAIN = 6
INPUT_COUNT = 7 INPUT_COUNT = 7
OUTPUT_COUNT = 8 OUTPUT_COUNT = 8
UNUSED_COUNT = 9 UNUSED_COUNT = 9
SYNC_INPUT_TO_AES = 10 SYNC_INPUT_TO_AES = 10
SYNC_OUTPUT_TO_AES = 11 SYNC_OUTPUT_TO_AES = 11
MONITOR_CTL = 12 MONITOR_CTL = 12
LEFT_MONITOR_ATTEN = 13 LEFT_MONITOR_ATTEN = 13
RIGHT_MONITOR_ATTEN = 14 RIGHT_MONITOR_ATTEN = 14
ENUM_VALUE = 0 # only certain values are valid ENUM_VALUE = 0 # only certain values are valid
RANGE_VALUE = 1 # any value in range is valid RANGE_VALUE = 1 # any value in range is valid

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