The Tk::Square Widget

The Tcl/Tk distribution contains a Square widget that demonstrates the basic structure of a C widget. It’s a simple square of variable size and color that can be moved around a window by dragging it with a mouse. It has a keyboard binding to an “a” that starts and stops an animation that varies the widget’s size over time, so that it appears to throb.

Tcl/Tk Example

Although Perl/Tk code produced Figure 21-1, this Tcl/Tk example creates an identical window. The square widget, .s, is packed, assigned three bindings, and given the keyboard focus. The mouse button bindings move the square to the cursor’s current position, and the “a” binding toggles the animation’s state. In the Perl/Tk version, we’ll see how to move the bindings into the Tk::Square class proper (seems reasonable, since it’s unclear exactly what a square widget should do anyway).

square .s
pack .s -expand yes -fill both

bind .s <1> {move %x %y}
bind .s <B1-Motion> {move %x %y}
bind .s a animate
focus .s
A Tk::Square with a raised relief

Figure 21-1. A Tk::Square with a raised relief

This procedure moves the square to a given position. The (x, y) coordinate comes from the %x and %y binding codes, analogous to the $Tk::event->x and $Tk::event->y calls. The size method returns the pixel length of the square’s side, and the position method actually repositions the square.

proc move {x y} { set a [.s size] .s position [expr $x-($a/2)] ...

Get Mastering Perl/Tk now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.