Tk Source Code

Artifact [79526325]
Login

Artifact 79526325f34465d23b9385f485530cc942058f70:

Attachment "itemconf.tcl" to ticket [3109856f] added by hobbs 2010-11-16 06:59:01.
#!/usr/bin/env tclsh

package require Tk

set c [canvas .c -borderwidth 0 -highlightthickness 0]
pack $c -fill both -expand 1

pack [button .fill -text "Fill" -command [list fill $c]] -fill x
pack [button .run -text "Run" -command [list run $c]] -fill x
pack [button .exit -text "Exit" -command exit] -fill x

set objs [list]

proc fill {c} {
    global objs
    $c delete all
    set objs [list]
    for {set i 0} {$i < 20} {incr i} {
	for {set j 0} {$j < 20} {incr j} {
	    lappend objs [$c create rect [expr {$i*10}] [expr {$j*10}] \
			      [expr {$i*10+10}] [expr {$j*10+10}] \
			      -fill #888 -outline #888]
	}
    }
}

proc random {rng} { return [expr {int(rand()*$rng)}] }
proc randelem {lst} { return [lindex $lst [random [llength $lst]]] }

proc run {c {iters 1000}} {
    global objs
    while {$iters > 0} {
	set obj [randelem $objs]
	set r [random 255]
	set g [random 255]
	set b [random 255]
	set col [format #%02x%02x%02x $r $g $b]
	$c itemconfigure $obj -fill $col -outline $col
	update idletasks

	incr iters -1
    }
}

fill $c

# r = tk.Tk()
#
# c = tk.Canvas(r)
# c.pack(fill=tk.BOTH, expand=tk.YES)
#
# # draw 400 rectangles
# objs = []
# for i in range(20):
#    for j in range(20):
#        obj = c.create_rectangle(i*10, j*10, i*10+10, j*10+10,
# fill='#888888', outline='#888888')
#        objs.append(obj)
#
# def run():
#    # loop indefinitely and randomly change the canvas item colours
#    while True:
#        obj = random.choice(objs)
#        red = random.randint(0,255)
#        green = random.randint(0,255)
#        blue = random.randint(0,255)
#        colour = '#%02x%02x%02x' %(red, green, blue)
#        c.itemconfigure(obj, fill=colour, outline=colour)
#        r.update()
#
# tk.Button(r, text='Run', command=run).pack()
# tk.Button(r, text='Close', command=r.destroy).pack()