1UserGuide(3) User Contributed Perl Documentation UserGuide(3)
2
3
4
6 Tk::UserGuide - Writing Tk applications in Perl 5
7
9 This document is for beginners. It assumes you know some Perl, and
10 have it and Tk running. If you are not currently reading this document
11 courtesy of the widget demonstration program, please be sure to run
12 widget, as it will show you the various widget types supported by Tk
13 and how to use them. widget should be installed in your default path,
14 so type widget at a command prompt.
15
16 Here are links to other novice tutorials:
17
18 <http://www.lehigh.edu/~sol0/ptk/tpj1.html>
19 <http://www.lehigh.edu/~sol0/ptk/perlmonth01/pm1.html>
20
21 Mastering Perl/Tk is the definitive book on Perl/Tk:
22
23 <http://www.oreilly.com/catalog/mastperltk>
24
26 Tk GUI programming is event-driven. (This may already be familiar to
27 you.) In event-driven programs, the main GUI loop is outside of the
28 user program and inside the GUI library. This loop - initiated by
29 calling MainLoop - watches all events of interest and activates the
30 correct handler procedures to handle these events. Some of these
31 handler procedures may be user-supplied; others will be part of the
32 library.
33
34 For a programmer, this means that you're not watching what is
35 happening; instead, you are requested by the toolkit to perform actions
36 whenever necessary. So, you're not watching for 'raise window / close
37 window / redraw window' requests, but you tell the toolkit which
38 routine will handle such cases, and the toolkit will call the
39 procedures when required. These procedures are known as callbacks, and
40 some of them you write yourself.
41
43 Perl programs that use Tk need to include "use Tk". A program should
44 also use "use strict" and the -w switch to ensure the program is
45 working without common errors.
46
47 Any Perl/Tk application starts by creating the Tk MainWindow. You then
48 create items inside the MainWindow, and/or create new windows called
49 Toplevels that also contain child items, before starting the MainLoop,
50 which is the last logical statment in your program. You can also create
51 more items and windows while you're running, using callbacks. Items
52 are only shown on the display after they have been arranged by a
53 geometry manager like pack; more information on this later. MainLoop
54 starts the GUI and handle all events. That's all there is to it! A
55 trivial one-window example is shown below:
56
57 #!/usr/bin/perl -w
58 use Tk;
59 use strict;
60
61 my $mw = MainWindow->new;
62 $mw->Label(-text => 'Hello, world!')->pack;
63 $mw->Button(
64 -text => 'Quit',
65 -command => sub { exit },
66 )->pack;
67 MainLoop;
68
69 Please run this example. It shows you two widget types, a Label and a
70 Button, and how they are packed. When clicked, the Button widget
71 invokes the callback specified by the "-command" option. Finally, note
72 the typical Tk style using "-option" => "value" pairs.
73
75 Tk windows and widgets are hierarchical, i.e. one window includes one
76 or more other windows. You create the first Tk window using
77 "MainWindow->new". This returns a window handle, assigned to $mw in
78 the example above. Keep track of the main handle, commonly called a
79 widget reference.
80
81 You can use any Tk handle to create child widgets within the window (or
82 widget). This is done by calling the Tk constructor method on the
83 variable. In the example above, the "Label" method called from $mw
84 creates a Label widget inside the MainWindow. In the constructor call,
85 you can specify various options; you can later add or change options
86 for any widget using the configure method, which takes the same
87 parameters as the constructor. The one exception to the hierarchical
88 structure is the Toplevel constructor, which creates a new outermost
89 window.
90
91 After you create any widget (other than the MainWindow or Toplevels,
92 you must render it by calling pack. (This is not entirely true; more
93 later)). If you do not need to refer to the widget after construction
94 and packing, call pack off the constructor results, as shown for the
95 Label and Button in the example above. Note that the result of the
96 compound call is the result of pack, which is a valid Tk handle.
97
98 Windows and widgets are deleted by calling destroy on them; this will
99 delete and un-draw the widget and all its children.
100
102 Here is an itemize of the standard Tk widget set.
103
104 Button
105 Canvas
106 Checkbutton
107 Entry
108 Frame
109 Label
110 Labelframe
111 Listbox
112 Menu
113 Menubutton
114 Message
115 Panedwindow
116 Radiobutton
117 Scale
118 Scrollbar
119 Spinbox
120 Text
121 Toplevel
122
123 Perl/Tk provides an equal number of new widgets, above and beyond this
124 core set.
125
126 Adjuster
127 Balloon
128 BrowseEntry
129 ColorEditor
130 Dialog
131 DialogBox
132 DirTree
133 ErrorDialog
134 FBox
135 FileSelect
136 HList
137 LabEntry
138 LabFrame
139 NoteBook
140 Optionmenu
141 Pane
142 ProgressBar
143 ROText
144 Table
145 TextUndo
146 Tiler
147 TList
148 Tree
149
151 Most graphical interfaces are used to set up a set of values and
152 conditions, and then perform the appropriate action. The Tk toolkit is
153 different from your average text-based prompting or menu driven system
154 in that you do not collect settings yourself, and decide on an action
155 based on an input code; instead, you leave these values to your toolkit
156 and only get them when the action is performed.
157
158 So, where a traditional text-based system would look like this:
159
160 #!/usr/bin/perl -w
161 use strict;
162
163 print "Please type a font name\n";
164 my $font = <>; chomp $font;
165 # Validate font
166
167 print "Please type a file name\n";
168 my $filename = <>; chomp $filename;
169 # Validate filename
170
171 print "Type <1> to fax, <2> to print\n";
172 my $option = <>; chomp $option;
173 if ($option eq 1) {
174 print "Faxing $filename in font $font\n";
175 } elsif ($option eq 2) {
176 print "Now sending $filename to printer in font $font\n";
177 }
178
179 The slightly larger example below shows how to do this in Tk. Note the
180 use of callbacks. Note, also, that Tk handles the values, and the
181 subroutine uses the method get to get at the values. If a user changes
182 his mind and wants to change the font again, the application never
183 notices; it's all handled by Tk.
184
185 #!/usr/bin/perl -w
186 use Tk;
187 use strict;
188
189 my $mw = MainWindow->new;
190
191 $mw->Label(-text => 'File Name')->pack;
192 my $filename = $mw->Entry(-width => 20);
193 $filename->pack;
194
195 $mw->Label(-text => 'Font Name')->pack;
196 my $font = $mw->Entry(-width => 10);
197 $font->pack;
198
199 $mw->Button(
200 -text => 'Fax',
201 -command => sub{do_fax($filename, $font)}
202 )->pack;
203
204 $mw->Button(
205 -text => 'Print',
206 -command => sub{do_print($filename, $font)}
207 )->pack;
208
209 MainLoop;
210
211 sub do_fax {
212 my ($file, $font) = @_;
213 my $file_val = $file->get;
214 my $font_val = $font->get;
215 print "Now faxing $file_val in font $font_val\n";
216 }
217
218 sub do_print {
219 my ($file, $font) = @_;
220 my $file_val = $file->get;
221 my $font_val = $font->get;
222 print "Sending file $file_val to printer in font $font_val\n";
223 }
224
226 In the examples above, you must have noticed the pack calls. This is
227 one of the more complicated parts of Tk. The basic idea is that any
228 window or widget should be subject to a Tk geometry manager; the packer
229 is one of the placement managers, and grid is another.
230
231 The actions of the packer are rather simple: when applied to a widget,
232 the packer positions that widget on the indicated position within the
233 remaining space in its parent. By default, the position is on top;
234 this means the next items will be put below. You can also specify the
235 left, right, or bottom positions. Specify position using -side =>
236 'right'.
237
238 Additional packing parameters specify the behavior of the widget when
239 there is some space left in the Frame or when the window size is
240 increased. If widgets should maintain a fixed size, specify nothing;
241 this is the default. For widgets that you want to fill up the current
242 horizontal and/or vertical space, specify -fill => 'x', 'y', or 'both';
243 for widgets that should grow, specify -expand => 1. These parameters
244 are not shown in the example below; see the widget demonstration.
245
246 If you want to group some items within a window that have a different
247 packing order than others, you can include them in a Frame. This is a
248 do-nothing window type that is meant for packing or filling (and to
249 play games with borders and colors).
250
251 The example below shows the use of pack and Frames:
252
253 #!/usr/bin/perl -w
254 use Tk;
255 use strict;
256
257 # Take top and the bottom - now implicit top is in the middle
258 my $mw = MainWindow->new;
259 $mw->title( 'The MainWindow' );
260 $mw->Label(-text => 'At the top (default)')->pack;
261 $mw->Label(-text => 'At the bottom')->pack(-side => 'bottom');
262 $mw->Label(-text => 'The middle remains')->pack;
263
264 # Since left and right are taken, bottom will not work...
265 my $top1 = $mw->Toplevel;
266 $top1->title( 'Toplevel 1' );
267 $top1->Label(-text => 'Left')->pack(-side => 'left');
268 $top1->Label(-text => 'Right')->pack(-side => 'right');
269 $top1->Label(-text => '?Bottom?')->pack(-side => 'bottom');
270
271 # But when you use Frames, things work quite alright
272 my $top2 = $mw->Toplevel;
273 $top2->title( 'Toplevel 2' );
274 my $frame = $top2->Frame;
275 $frame->pack;
276 $frame->Label(-text => 'Left2')->pack(-side => 'left');
277 $frame->Label(-text => 'Right2')->pack(-side => 'right');
278 $top2->Label(-text => 'Bottom2')->pack(-side => 'bottom');
279
280 MainLoop;
281
283 Most real applications require more than one window. As you just saw,
284 you can create more outermost windows by using a Toplevel widget. Each
285 window is independent; destroying a Toplevel window does not affect the
286 others as long as they are not a child of the closed Toplevel.
287 However, exiting the MainWindow will destroy all remaining Toplevel
288 widgets and end the application. The example below shows a trivial
289 three-window application:
290
291 #!/usr/bin/perl -w
292 use Tk;
293 use strict;
294
295 my $mw = MainWindow->new;
296 fill_window($mw, 'Main');
297 my $top1 = $mw->Toplevel;
298 fill_window($top1, 'First top-level');
299 my $top2 = $mw->Toplevel;
300 fill_window($top2, 'Second top-level');
301 MainLoop;
302
303 sub fill_window {
304 my ($window, $header) = @_;
305 $window->Label(-text => $header)->pack;
306 $window->Button(
307 -text => 'close',
308 -command => [$window => 'destroy']
309 )->pack(-side => 'left');
310 $window->Button(
311 -text => 'exit',
312 -command => [$mw => 'destroy']
313 )->pack(-side => 'right');
314 }
315
317 So far, all callback routines shown called a user procedure. You can
318 also have a callback routine call another Tk routine. This is the way
319 that scroll bars are implemented: scroll-bars can call a Tk item or a
320 user procedure, whenever their position has changed. The Tk item that
321 has a scrollbar attached calls the scrollbar when its size or offset
322 has changed. In this way, the items are linked. You can still ask a
323 scrollbar's position, or set it by hand - but the defaults will be
324 taken care of.
325
326 The example below shows a Listbox with a scroll bar. Moving the
327 scrollbar moves the Listbox. Scanning a Listbox (dragging an item with
328 the left mouse button) moves the scrollbar.
329
330 #!/usr/bin/perl -w
331 use Tk;
332 use strict;
333
334 my $mw = MainWindow->new;
335 my $box = $mw->Listbox(
336 -relief => 'sunken',
337 -height => 5,
338 -setgrid => 1,
339 );
340 my @items = qw(One Two Three Four Five Six Seven
341 Eight Nine Ten Eleven Twelve);
342 foreach (@items) {
343 $box->insert('end', $_);
344 }
345 my $scroll = $mw->Scrollbar(-command => ['yview', $box]);
346 $box->configure(-yscrollcommand => ['set', $scroll]);
347 $box->pack(-side => 'left', -fill => 'both', -expand => 1);
348 $scroll->pack(-side => 'right', -fill => 'y');
349
350 MainLoop;
351
352 Note that there's a convenience method Scrolled which helps
353 constructing widgets with automatically managed scrollbars.
354
356 One of the most powerful widgets in Tk is the Canvas window. In a
357 Canvas window, you can draw simple graphics and include other widgets.
358 The Canvas area may be larger than the visible window, and may then be
359 scrolled. Any item you draw on the canvas has its own id, and may
360 optionally have one or more tags. You may refer to any item by its id,
361 and may refer to any group of items by a common tag; you can move,
362 delete, or change groups of items using these tags, and you can bind
363 actions to tags. For a properly designed (often structured) Canvas,
364 you can specify powerful actions quite simply.
365
366 In the example below, actions are bound to circles (single click) and
367 blue items (double-click); obviously, this can be extended to any tag
368 or group of tags.
369
370 #!/usr/bin/perl -w
371 use Tk;
372 use strict;
373
374 # Create B<MainWindow> and canvas
375 my $mw = MainWindow->new;
376 my $canvas = $mw->Canvas;
377 $canvas->pack(-expand => 1, -fill => 'both');
378
379 # Create various items
380 create_item($canvas, 1, 1, 'circle', 'blue', 'Jane');
381 create_item($canvas, 4, 4, 'circle', 'red', 'Peter');
382 create_item($canvas, 4, 1, 'square', 'blue', 'James');
383 create_item($canvas, 1, 4, 'square', 'red', 'Patricia');
384
385 # Single-clicking with left on a 'circle' item invokes a procedure
386 $canvas->bind('circle', '<1>' => sub {handle_circle($canvas)});
387 # Double-clicking with left on a 'blue' item invokes a procedure
388 $canvas->bind('blue', '<Double-1>' => sub {handle_blue($canvas)});
389 MainLoop;
390
391 # Create an item; use parameters as tags (this is not a default!)
392 sub create_item {
393 my ($can, $x, $y, $form, $color, $name) = @_;
394
395 my $x2 = $x + 1;
396 my $y2 = $y + 1;
397 my $kind;
398 $kind = 'oval' if ($form eq 'circle');
399 $kind = 'rectangle' if ($form eq 'square');
400 $can->create(
401 ($kind, "$x" . 'c', "$y" . 'c',
402 "$x2" . 'c', "$y2" . 'c'),
403 -tags => [$form, $color, $name],
404 -fill => $color);
405 }
406
407 # This gets the real name (not current, blue/red, square/circle)
408 # Note: you'll want to return a list in realistic situations...
409 sub get_name {
410 my ($can) = @_;
411 my $item = $can->find('withtag', 'current');
412 my @taglist = $can->gettags($item);
413 my $name;
414 foreach (@taglist) {
415 next if ($_ eq 'current');
416 next if ($_ eq 'red' or $_ eq 'blue');
417 next if ($_ eq 'square' or $_ eq 'circle');
418 $name = $_;
419 last;
420 }
421 return $name;
422 }
423
424 sub handle_circle {
425 my ($can) = @_;
426 my $name = get_name($can);
427 print "Action on circle $name...\n";
428 }
429
430 sub handle_blue {
431 my ($can) = @_;
432 my $name = get_name($can);
433 print "Action on blue item $name...\n";
434 }
435
437 Perl/Tk follows Perl's model of handling Unicode. That is, if a string
438 is correctly flagged as a "character" string in the sense like
439 described in "TERMINOLOGY" in Encode, then Perl/Tk will very probably
440 display and handle this string correctly.
441
442 Note that every variable which is passed somehow into a Perl/Tk method
443 will be implicitely changed into an internally utf8-flagged variable.
444 Semantically nothing changes, as the series of codepoints stays the
445 same, but things will change when variables with high-bit iso-8859-1
446 characters will be passed to the "outer" world. In this case you have
447 to explicitely mark the encoding of your output stream if using IO, or
448 encode the variables using Encode for other style of communication.
449
450 This is the theory, now some examples.
451
452 If you use non-iso-8859-1 characters in the source code, then use
453 either the "use utf8;" or "use encoding 'encodingname'" pragma:
454
455 use utf8;
456 use Tk;
457 my $x = "some characters using utf8 encoding";
458 tkinit->Label(-text => $x)->pack;
459 MainLoop;
460
461 For data that comes from a file you have to specify the encoding unless
462 it's encoded as ascii or iso-8559-1:
463
464 use Tk;
465 open my $FH, "<:encoding(utf-8)", "filename" or die $!;
466 # or for utf-16 data: open my $FH, "<:encoding(utf-16)", "filename" or die $!;
467 my $data = <$FH>;
468 tkinit->Label(-text => $data)->pack;
469 MainLoop;
470
471 Likewise, the encoding must be specified for all data which is read
472 from Tk widgets and that shall be output into a file. For the output,
473 the encoding should be always specified, even if it is iso-8859-1:
474
475 use Tk;
476 $mw = tkinit;
477 $mw->Entry(-textvariable => \$input)->pack;
478 $mw->Button(
479 -text => "Write to file",
480 -command => sub {
481 open my $FH, ">:encoding(iso-8859-1)", "filename" or die $!;
482 print $FH $input;
483 },
484 )->pack;
485 MainLoop;
486
487 Note that Tk is Unicode-capable. So you need to be prepared that the
488 user has the appropriate input methods activated to enter non-ascii
489 characters. If an output encoding is used which does not cover the
490 whole of Unicode codepoints then a warning will be issued when writing
491 the file, like this:
492
493 "\x{20ac}" does not map to iso-8859-1 at /usr/local/lib/perl5/site_perl/5.8.8/mach/Tk.pm line 250.
494
495 Also, the same hexadecimal notation will be used as replacements for
496 the unhandled characters.
497
498 Handling encoding in I/O is pretty simple using the "encoding" PerlIO
499 layer, as described above. In other cases, such as when dealing with
500 databases, encoding the data usually has to be done manually, unless
501 the database driver has some means for automatically do this for you.
502 So when working with a MySQL database, one could use:
503
504 use Tk;
505 use DBI;
506 use Encode qw(encode);
507 $mw = tkinit;
508 $mw->Entry(-textvariable => \$input)->pack;
509 $mw->Button(
510 -text => "Write to database",
511 -command => sub {
512 my $dbh = DBI->connect("dbi:mysql:test", "root", "") or die;
513 my $encoded_input = encode("iso-8859-1", $input);
514 $dbh->do("INSERT INTO testtable VALUES (?)", undef, $encoded_input) or die;
515 },
516 )->pack;
517 MainLoop;
518
519 Unfortunately, there are still places in Perl ignorant of Unicode. One
520 of these places are filenames. Consequently, the file selectors in
521 Perl/Tk do not handle encoding of filenames properly. Currently they
522 suppose that filenames are in iso-8859-1 encoding, at least on Unix
523 systems. As soon as Perl has a concept of filename encodings, then
524 Perl/Tk will also implement such schemes.
525
526
527
528perl v5.38.0 2023-07-21 UserGuide(3)