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. Shift-Tab can be used to change the focus to the previous widget. Control-Tab can be used in the Text widget. When in doubt, 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;

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.

You can use the focusNext and focusPrev methods to actually move the focus to the next or previous widget in focus order:

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

So, what is focus order? First, focus order is constrained to $widget’s Toplevel ...

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