O'Reilly logo

Mastering Perl/Tk by Nancy Walsh, Stephen Lidie

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

A Drawing Program Example

The Canvas widget is very versatile and can be useful for displaying different types of items. One of the first things that comes to mind when people think of a Canvas is a drawing program. To save you the trouble, here is a rudimentary drawing program called Quick Draw you can use to draw rectangles, ovals, and lines. You can also change the thickness of the objects before you draw them. It requires only a tiny bit of error-checking to make it a slicker program. Here’s the code:

use Tk; $mw = MainWindow->new; $mw->title("Quick Draw"); $f = $mw->Frame(-relief => 'groove', -bd => 2, -label => "Draw:")->pack(-side => 'left', -fill => 'y'); $draw_item = "rectangle"; $f->Radiobutton(-variable => \$draw_item, -text => "Rectangle", -value => "rectangle", -command => \&bind_start)->pack(-anchor => 'w'); $f->Radiobutton(-variable => \$draw_item, -text => "Oval", -value => "oval", -command => \&bind_start)->pack(-anchor => 'w'); $f->Radiobutton(-variable => \$draw_item, -text => "Line", -value => "line", -command => \&bind_start)->pack(-anchor => 'w'); $f->Label(-text => "Line Width:")->pack(-anchor => 'w'); $thickness = 1; $f->Entry(-textvariable => \$thickness)->pack(-anchor => 'w'); $c = $mw->Scrolled("Canvas", -cursor => "crosshair")->pack( -side => "left", -fill => 'both', -expand => 1); $canvas = $c->Subwidget("canvas"); &bind_start( ); MainLoop; sub bind_start { # If there is a "Motion" binding, we need to allow the user # to finish drawing the item before ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required