16.16. Focus Methods

When your application is running, you can force a widget to have the keyboard focus by calling focus on that widget:

$widget->focus();

You might want to do this if you have an entry widget into which the user should start typing first. Calling focus right before MainLoop causes the widget to get the focus right away. If you press the Tab key, the focus automatically changes from one widget to the next (remember that you can tell when a widget has the focus by the highlight rectangle around it). There are several methods that allow you to manipulate the focus.

To make the focus follow the mouse around, use focusFollowsMouse:

$widget->focusFollowsMouse();

This method is buggy under both Windows 95 and Unix. A patch just recently came out for Tk8, so if you want to use this method and it isn't working, make sure you get the patch.

To find out which widget has the focus, call focusCurrent:

$who = $widget->focusCurrent();

To force a widget to have the focus even if the application isn't currently active, call focusForce:

$widget->focusForce();

This is not a nice thing to do, so try to not use it.

To find out which widget had the focus last, call focusLast:

$which = $widget->focusLast();

If none of the widgets in the window has the focus, the toplevel is returned.

To find out the order in which the focus will change, you can use the focusNext and focusPrev methods:

$nextwidget = $widget->focusNext();
$prevwidget = $widget->focusPrev();

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.