9.21. 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, I've written 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 only requires 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 ...

Get Learning 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.