cover24213.jpg
Learning Perl/Tk
Nancy Walsh
oreilly.gif
Beijing • Cambridge • Farnham • Köln • Paris • Sebastopol • Taipei • Tokyo
Learning Perl/Tk
by Nancy Walsh
Copyright (c) 1999 O'Reilly & Associates, Inc. All rights reserved.
Printed in the United States of America.
Published by O'Reilly & Associates, Inc., 101 Morris Street, Sebastopol, CA 95472.
Editor:Linda Mui
Editorial and Production Services: TIPS-Technical Publishing, Inc.
Production Editor: Ellie Fountain Maden
Printing History:
January 1999:                  First Edition.
March 1999:                    Minor corrections.
Nutshell Handbook, the Nutshell Handbook logo, and the O'Reilly logo are registered trademarks of O'Reilly & Associates. The use of an emu image in association with Perl/Tk is a trademark of O'Reilly & Associates, Inc. Permission may be granted for non-commercial use; please inquire by sending mail to camel@ora.com.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O'Reilly & Associates, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher assumes no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.
00iv-01.gif
This book is printed on acid-free paper with 85% recycled content, 15% post-consumer waste. O'Reilly & Associates is committed to using paper with the highest recycled content available consistent with high quality.
ISBN: 1-56592-314-6:[5/99]
Table of Contents
Preface
xi
1. Introduction to Perl/Tk
1
A Bit of History About Perl (and Tk)
1
Perl/Tk for Both Unix and Windows 95/NT
2
Why Use a Graphical Interface?
2
Why Use Perl/Tk?
3
Installing the Tk Module
5
Creating Widgets
6
Coding Style
8
Displaying a Widget
9
The Anatomy of an Event Loop
9
Hello World Example
10
Using exit Versus Using destroy
12
Naming Conventions for Widget Types
12
Using print for Diagnostic/Debugging Purposes
13
Designing Your Windows (A Short Lecture)
14
2. Geometry Management
15
Pack
16
Grid
34
Place
47
Geometry Management Summary
56
3. The Basic Button
57
The Button Widget
57
Some Fun Things to Try
80

4. Checkbuttons and Radiobuttons
81
The Checkbutton Widget
81
The Radiobutton Widget
93
Fun Things to Try
101
5. Label and Entry Widgets
102
The Label Widget
102
The Entry Widget
108
Fun Things to Try
123
6. Scrollbars
124
Defining Scrollbar Parts
124
The Scrolled Method
126
The Scrollbar Widget
128
Examples
137
Fun Things to Try
140
7. The Listbox Widget
141
Creating and Filling a Listbox
141
Listbox Options
142
Selection Modes
144
Colors
145
Listbox Style
146
Configuring a Listbox
147
Inserting Items
147
Deleting Items
148
Retrieving Elements
148
Selection Methods
149
Moving to a Specific Index
150
Translating Indexes
150
Counting Items
150
Active Versus Selected
150
Bounding Box
151
Finding an Index by Y Coordinate
151
Scrolling Methods
151
Listbox Example
152
Fun Things to Try
153

8. The Text Widget
154
Creating and Using a Text Widget
154
Text Widget Options
155
A Short Break for a Simple Example
160
Text Indexes
161
Text Tags
164
Inserting Text
171
Deleting Text
172
Retrieving Text
172
Translating Index Values
172
Comparing Index Values
173
Showing an Index
173
Getting the Size of a Character
173
Getting Line Information
173
Searching the Contents of a Text Widget
174
Scrolling
175
Marks
175
Embedding Widgets
176
Internal Debug Flag
179
Fun Things to Try
180
9. The Canvas Widget
181
Creating a Canvas
181
Coordinate System
182
The Scrollable Region
183
Using Bind with a Canvas
184
Canvas Options
184
Creating Items in a Canvas
188
Configuring the Canvas Widget
198
Configuring Items in the Canvas Widget
199
Tags
199
Retrieving Bounding Box Coordinates
202
Translating Coordinates
202
Moving Items Around
202
Changing the Display List
203
Deleting Items
203
Deleting Tags
204
Determining Item Type
204
Set Keyboard Focus
204

Rendering the Canvas as PostScript
204
Scaling the Canvas
205
Scanning
206
A Drawing Program Example
206
Fun Things to Try
209
10. The Scale Widget
210
Creating a Scale
210
Assigning a Callback
213
Orientation
213
Minimum and Maximum Values
213
Displayed Versus Stored Value
214
Adding a Label
214
Displaying Value Increments
214
Changing the Size of the Scale
215
Options You'll Probably Never Need
215
Configuring a Scale
216
Getting the Value of a Scale
216
Setting the Value of a Scale
216
Determining Coordinates
216
Identifying Parts of a Scale
216
Fun Things to Try
217
11. Menus
218
Different Types of Menus
218
The Menubutton Widget
220
Complete Menubutton Examples
236
The Menu Widget
238
Optionmenu Widget
248
Fun Things to Try
250
12. Frames
251
Creating a Frame
251
Frame Style
253
Frames Aren't Interactive
255
Colormap Complications
255
Frame Methods
256
Fun Things to Try
256

13. Toplevel Widgets
257
Creating a Toplevel Widget
257
Toplevel Methods
260
Review
269
Fun Things to Try
269
14. Binding Events
270
The bind Method
270
Arguments Sent to the Callback
272
Defining Event Sequences
273
Event Information
278
Bailing Out of a Callback Created with bind
279
The bindtags Method
280
Ways to Use bind
280
15. Composite Widgets
281
Looking at an Example Sideways
282
Location of Files
283
Creating a Composite Widget Based on Frame
284
Toplevel-Based Composite Widgets
289
16. Methods for Any Widget
290
Building a Family Tree
290
Color-Related Methods
292
Option Databases
293
The Application's Name
295
Widget Existence
295
Is the Widget Mapped?
295
Converting Screen Distances
295
Size of Widget
296
Widget Position
297
Screen Information
298
Atom Methods
300
Ringing a Bell
300
Clipboard Methods
300
Selection Methods
301
Destroying a Widget
302
Focus Methods
302
Grab Methods
303
Interapplication Communication
304

Waiting for Events to Happen
304
Parsing Command-Line Options
306
Time Delays
306
A. Configuring Widgets with configure and cget
309
B. Operating System Differences
331
C. Fonts
334
Index
341

Preface
Perl is a great language for file processing, connecting to databases, and many other tasks that are too tedious to do manually. For many years, however, Perl programs were limited to a command-line interface. The Tk interface changed all that.
The Tk extension to Perl allows you to create graphical interfaces for your programs. Using the modules included with the distribution of Tk, you can create windows with buttons, lists, text, and other types of widgets to help your user navigate within your application.
What You Should Already Know
To get the most out of this book, you should already know the basics of Perl (specifically, Perl version 5). You should be familiar enough with Perl to be able to at least read some code and know what the code is doing. You don't have to be a Perl guru or Perl hacker to learn Perl/Tk, but it will help if you feel comfortable with the language. Here's the laundry list of things you should at least recognize: hashes, arrays, subroutines, and their anonymous versions, $_ and @_.
Perl/Tk utilizes the object-oriented features available in Perl 5, so even if you don't completely understand them, you should be able to recognize them when you see them. The only other thing you'll need is your prior knowledge of other graphical user interfaces (GUIs) and what you did and did not like about them. This helps when deciding what features to include in your own applications. Take a look at the word processor you use on your PC, your web browser, or any program that has buttons and scrollbars and accepts both mouse and keyboard input.
Those applications are pretty major ones; we'll start with much simpler examples and build up from there. We'll be covering each basic widget and all its associated options in detail. You'll learn how to make a window look the way you want it to look. You'll also learn how to make a window user-friendly and attractive.
If you want to know more about Perl in general, you should read Learning Perl, Programming Perl, Advanced Perl Programming, and Perl Cookbook, which are also published by O'Reilly & Associates, Inc. There are also numerous FAQs and documents available on the Web. This book's focus is the Tk extension to Perl, which is a fairly specific portion of Perl.
What's in This Book
Chapter 1, Introduction to Perl/Tk
The first chapter contains some interesting history about Perl and the Tk module. It starts you out with a simple Hello World program and gives a short introduction to event-driven programs.
Chapter 2, Geometry Management
Geometry management is probably the most important concept in using Perl/Tk. It determines how your widgets are to be drawn on the screen (or, in some cases, how not to be drawn on the screen). The three geometry managers-
pack, grid, and place-are covered here. Most examples in the book use pack.
Chapter 3, The Basic Button
The button is the first widget we cover and there are lots of details here. There are also tons of code snippets and screen shots showing different ways to manipulate and mutilate the button widget. Many of the options discussed here are common among the other standard widgets.
Chapter 4, Checkbuttons and Radiobuttons
Checkbuttons and radiobuttons are similar to the standard button, but they look different and are usually programmed differently.
Chapter 5, Label and Entry Widgets
The label is the simplest widget of all. It is usually used with an entry widget, which is why they are included in the same chapter. The entry widget will let you get input from your user.
Chapter 6, Scrollbars
Certain widgets in Perl/Tk can be scrolled, which means they can contain more information than you can see on the screen. Scrollbars are used to navigate the data inside these widgets. Chapter 6 tells you how scrollbars communicate with each widget and what you need to do to create and use them.
Chapter 7, The Listbox Widget
A listbox can contain any sort of data, but it usually contains a list of options from which the user can select. In Chapter 7, you'll learn how to create the listbox, fill it with some items, and change the way the user selects the items from the list.
Chapter 8, The Text Widget
The text widget is a versatile widget you can use for many purposes besides just displaying text. Chapter 8 covers the different things you can put inside a text widget (such as text or other widgets) and how to get the best use out of them.
Chapter 9, The Canvas Widget
A canvas can display objects such as circles, rectangles, text, and even other widgets. Chapter 9 covers all the options and methods available and how to use them.
Chapter 10, The Scale Widget
The scale widget is great for giving the user a range of numbers from which to select so there is no possibility of a user typing in a number out of range or accidentally typing in letters. Chapter 10 includes examples of the scale widget and covers all the methods available for setting it up and using it.
Chapter 11, Menus
Once an application gets complex enough, you will need to put a menu in it. Chapter 11 shows different ways to create menus and how they can best be used in an application.
Chapter 12, Frames
The frame widget is used for organizing your other widgets on the screen to get the look you want. Chapter 12 shows how you can use frames in coordination with a geometry manager (covered in Chapter 2) to make your windows look the way you want them to.
Chapter 13, Toplevel Widgets
An application often needs more than one window in it. You can use a toplevel widget to create a second window. In Chapter 13 you'll learn how to create one and display it. We also cover the numerous methods available for manipulating toplevel widgets.
Chapter 14, Binding Events
One of the best ways to add functionality to your application is to add additional bindings to the widgets. This chapter tells you what a binding is and how to create one and use it.
Chapter 15, Composite Widgets
You can combine widgets to make a much more useful, reusable widget. Many of the additional widgets you can use with Perl/Tk are created this way. Chapter 15 includes an example of a composite widget and gives you some ideas for creating your own.
Chapter 16, Methods for Any Widget
There are several methods available for all widgets in Perl/Tk. We cover them in Chapter 16 and show you how to use them.
Appendix A, Configuring Widgets with configure and cget
Appendix A explains the
configure and cget methods, which are used with every widget. It also includes a table that shows the options and defaults for each widget option.
Appendix B, Operating System Differences
Appendix B covers the differences you'll encounter when you use Perl/Tk on different operating systems, specifically, Unix and Win32.
Appendix C, Fonts
Appendix C covers font usage for Tk, for both Unix and Win32 systems. It also covers the new font syntax in Tk8.
Reading Order
This book was designed and written with two major audiences in mind: people new to Perl/Tk and those who have experience with it.
Perl/Tk Novices
If you have no idea where to start, start at the beginning. This book is designed to lead you into topics by building a foundation of knowledge. We'll start simple with the button widget in Chapter 3, The Basic Button, and move up to more complicated widgets. Using Perl/Tk is not really that hard once you understand the basic fundamentals of how it works.
Somewhat Experienced to Gurus
Okay, so you've written a ton of programs with Perl/Tk and think you know how to do things. Chances are you have found a ''way that works," and have stuck with it. I recommend reading through Chapter 2, Geometry Management, so you have a complete understanding of how the geometry managers work. Then skip around to the widget sections you are interested in. I have included useful snippets of code (and sometimes full programs) that will give you ideas on how to use widgets in different ways. The list of options for each widget are helpful reminders of all those pesky options and how they affect each widget.
Typographical Conventions
The following typographical conventions are used in this book:
Italic
is used for filenames, command names, URLs, and emphasis. In syntax lines, it is used to identify replaceable values.
Constant Width
is used for function and method names and their arguments, and to show literal code in text.
Bold
is used to show default values in syntax lines.
We'd Like to Hear from You
We have tested and verified the information in this book to the best of our ability, but you may find that features have changed (which may in fact resemble bugs). Please let us know about any errors you find, as well as your suggestions for future editions, by writing to:
O'Reilly & Associates, Inc.
101 Morris Street
Sebastopol, CA 95472
1-800-998-9938 (in U.S. or Canada)
1-707-829-0515 (international/local)
1-707-829-0104 (fax)
You can also send us messages electronically. To be put on our mailing list or request a catalog, send email to:
info@oreilly.com
To ask technical questions or comment on the book, send email to:
bookquestions@oreilly.com
We have a web site for the book, where we'll list errata and plans for future editions. Here you'll also find all the source code for programs from the book available for download so you don't have to type it all in.
http://www.oreilly.com/catalog/lperltk
Acknowledgments
This book has taken quite a bit of time out of my life, and I would like to thank the people who helped make it possible and put up with me while I was off writing it: first, my husband Mike, who helped out in so many little ways it is impossible to list them all; our dogs, Brandy and Theo, for keeping my feet warm; our cats, Thumper and Sasha, for keeping the monitor and keyboard anchored to the desk (any typos are completely their fault); my co-worker, Kreg Webb, who suggested this whole crazy idea; and my editor, Linda Mui, for always coming up with positive things to say in addition to the not-so-good things.
I'd also like to thank all the reviewers of the book. They include: Stephen Lidie, Achim Bohnet, Peter Prymmer, Nick Ing-Simmons, and Phivu Nguyen.