将焦点从一个 Text 小部件更改为另一个 [英] Change the focus from one Text widget to another

查看:41
本文介绍了将焦点从一个 Text 小部件更改为另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手,我正在尝试使用 Tkinter 创建一个简单的 GUI.

I'm new to Python and I'm trying to create a simple GUI using Tkinter.

在许多用户界面中,经常点击选项卡按钮会将焦点从一个文本小部件更改为另一个.每当我在文本小部件中时,选项卡只会缩进文本光标.

So often in many user interfaces, hitting the tab button will change the focus from one Text widget to another. Whenever I'm in a Text widget, tab only indents the text cursor.

有谁知道这是否可以配置?

Does anyone know if this is configurable?

推荐答案

使用 Tkinter 很容易做到这一点.

This is very easy to do with Tkinter.

要完成这项工作,需要做一些事情.首先,您需要确保标准行为不会发生.也就是说,您不希望 tab 既插入一个 tab 又将焦点移到下一个小部件.默认情况下,事件在标准行为发生之前由特定小部件处理(通常在类绑定中).Tk 有一个简单的内置机制来阻止事件进一步处理.

There are a couple of things that have to happen to make this work. First, you need to make sure that the standard behavior doesn't happen. That is, you don't want tab to both insert a tab and move focus to the next widget. By default events are processed by a specific widget prior to where the standard behavior occurs (typically in class bindings). Tk has a simple built-in mechanism to stop events from further processing.

其次,您需要确保将焦点发送到适当的小部件.内置支持确定下一个小部件是什么.

Second, you need to make sure you send focus to the appropriate widget. There is built-in support for determining what the next widget is.

例如:

def focus_next_window(event):
    event.widget.tk_focusNext().focus()
    return("break")

text_widget=Text(...)
text_widget.bind("<Tab>", focus_next_window)

关于此代码的要点:

  • 方法 tk_focusNext() 返回键盘遍历层次结构中的下一个小部件.
  • 方法 focus() 将焦点设置到该小部件
  • 返回 "break" 很重要,因为它可以防止类绑定被触发.正是此类绑定插入了您不想要的制表符.
  • The method tk_focusNext() returns the next widget in the keyboard traversal hierarchy.
  • the method focus() sets the focus to that widget
  • returning "break" is critical in that it prevents the class binding from firing. It is this class binding that inserts the tab character, which you don't want.

如果您希望应用程序中的所有文本小部件具有此行为,您可以使用 bind_class() 方法而不是 bind() 使此绑定影响所有文本小部件.

If you want this behavior for all text widgets in an application you can use the bind_class() method instead of bind() to make this binding affect all text widgets.

您也可以让绑定将焦点发送到非常特定的小部件,但我建议坚持使用默认的遍历顺序,然后确保遍历顺序正确.

You can also have the binding send focus to a very specific widget but I recommend sticking with the default traversal order, then make sure the traversal order is correct.

这篇关于将焦点从一个 Text 小部件更改为另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆