5.1. The Label Widget

So far, all we have talked about are buttons, buttons, and more buttons. What if we just want to put some informative text on the screen? The label widget does just that. A label is like a button that doesn't do anything. It is a noninteractive widget and by default cannot have the keyboard focus (meaning you can't tab to it) and it does nothing when you click on it.

The label widget is probably the simplest widget. It is similar to a button in that it can show text (or a bitmap), have relief (default is flat), display multiple lines of text, have a different font, and so on. Figure 5.1 shows a simple window, with both a button and label, created with this code:

use Tk;
$mw = MainWindow->new();
$mw->Label(-text => "Label Widget")->pack();
$mw->Button(-text => "Exit", -command => sub { exit })->pack();
MainLoop;
Figure 5.1. A simple window with label and button

Here are some typical uses for a label:

  • Put a label to the left of an entry widget so the user knows what type of data is expected.

  • Put a label above a group of radiobuttons, making their purpose more clear (e.g., "Background Color:"). You can do the same thing with checkbuttons if they happen to be related or along the same theme.

  • Use a label to tell users what they did wrong: "The number entered must ...

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.