Tcl/Tk Tutorial on Tk Events

events in its simplest form is handled with the help of commands. a simple example for event handling is event handling with button and is shown below −

#!/usr/bin/wish

proc myevent { } {
   puts "event triggered"
}
pack [button .mybutton1  -text "button 1"   -command myevent]

when we run the above program, we will get the following output −

event example

a simple program to show delay text animation event is shown below −

#!/usr/bin/wish

proc delay {} {
   for {set j 0} {$j < 100000} {incr j} {} 
}

label .mylabel -text "hello................" -width 25
pack .mylabel
set str "hello................"
for {set i [string length $str]} {$i > -2} {set i [expr $i-1]} {
   .mylabel configure -text [string range $str 0 $i]
   update
   delay
}

when we run the program, we will get the following output in animated way −

event example3

event after delay

the syntax for event after delay is shown below −

after milliseconds number command

a simple program to show after delay event is shown below −

#!/usr/bin/wish

proc addtext {} {
   label .mylabel -text "hello................" -width 25
   pack .mylabel
}
after 1000 addtext

when we run the program, we will get the following output after one second −

event example2

you can cancel an event using the after cancel command as shown below −

#!/usr/bin/wish

proc addtext {} {
   label .mylabel -text "hello................" -width 25
   pack .mylabel
}
after 1000 addtext
after cancel addtext

event binding

the syntax for event binding is as shown below −

bind arguments 

keyboard events example

#!/usr/bin/wish

bind .  {puts "key pressed: %k "}

when we run the program and press a letter x, we will get the following output −

key pressed: x 

mouse events example

#!/usr/bin/wish

bind .  {puts "button %b pressed : %x %y "}

when we run the program and press the left mouse button, we will get an output similar to the following −

button 1 pressed : 89 90 

linking events with button example

#!/usr/bin/wish

proc myevent { } {
   puts "event triggered"
}
pack [button .mybutton1  -text "button 1"   -command myevent]
bind .  ".mybutton1 invoke"

when we run the program and press enter, we will get the following output −

event triggered