【问题标题】:How to Capture the Value of a Text Widget after the Tab Key is Pressed in Tkinter?在 Tkinter 中按下 Tab 键后如何捕获文本小部件的值?
【发布时间】:2015-12-02 06:22:19
【问题描述】:

我有一个示例脚本(如下所示),我只是尝试在每次按下“Tab”键时捕获 tkinter 文本小部件的值。有两个函数可以帮助解决这个问题。应该在 Tab 更改值之前运行并显示文本小部件的值。在 Tab 更改值后,另一个函数应该运行并显示文本小部件的值。

问题:

问题是只有一个函数运行——该函数在标签更改其值之前显示文本小部件的值。

我的系统:

Ubuntu 12.04

Python 3.4.3

Tk 8.5

守则:

import tkinter as tk

def display_before_value(value):
        """Display the value of the text widget before the class bindings run"""
        print("The (before) value is:", value)
        return


def display_after_value(value):
        """Display the value of the text widget after the class bindings run"""
        print("The (after) value is:", value)
        return


# Add the widgets
root = tk.Tk()
text = tk.Text(root)

# Add "post class" bindings to the bindtags
new_bindings = list(text.bindtags())
new_bindings.insert(2, "post-class")
new_bindings = tuple(new_bindings)
text.bindtags(new_bindings)
# Show that the bindtags were updated
text.bindtags()
# Outputs ('.140193481878160', 'Text', 'post-class', '.', 'all')

# Add the bindings
text.bind("<Tab>", lambda e: display_before_value(text.get("1.0", tk.END)))
text.bind_class("post-class", "<Tab>", lambda e: display_after_value(text.get("1.0", tk.END)))

# Show the text widget
text.grid()

# Run
root.mainloop()

在命令行/终端中运行上述代码只会显示 display_before_value() 函数的输出。所以我假设 post-class 绑定由于某种原因无法正常工作。但是,如果我将绑定从 &lt;Tab&gt; 更改为 &lt;Key&gt;,那么当我在文本小部件中键入任何键时,display_before_value()display_after_value() 都会正确运行(当然 Tab 键除外)。

提前致谢

【问题讨论】:

  • 那么当你按下Tab键的时候,你是希望看到Tab空间之前的文字,然后看到Tab空间之后的文字吗?
  • @BobMarshall -- 是的,这是正确的。代码中定义的两个函数都应该处理这两个操作。但是,只执行了 display_before_value() 函数。
  • 我的回答解决了这个问题。

标签: python python-3.x tkinter


【解决方案1】:

如果您希望文本显示在制表符之前,文本显示在制表符之后,请尝试使用 root.after()。这是您的代码示例:

import tkinter as tk

def display_before_value(event):
        """Display the value of the text widget before the class bindings run"""
        value = text.get("1.0", tk.END)
        print("The (before) value is:", value)
        root.after(1, display_after_value)
        return

def display_after_value():
        """Display the value of the text widget after the class bindings run"""
        value = text.get("1.0", tk.END)
        print("The (after) value is:", value)
        return

# Add the widgets
root = tk.Tk()
text = tk.Text(root)

# Add the bindings
text.bind("<Tab>", display_before_value)

# Show the text widget
text.grid()

# Run
root.mainloop()

当按下 tab 键时,会执行 display_before_value 函数,该函数打印文本小部件的值,其中不包含 tab 空间。 1 毫秒后,转到 display_after_value 函数,该函数显示文本小部件的值,包括选项卡空间。

【讨论】:

  • 谢谢!这行得通,我可能会接受它作为答案。我只想看看在不使用 .after() 方法的情况下是否会出现任何替代方案。再次感谢!
猜你喜欢
  • 1970-01-01
  • 2010-11-21
  • 2011-09-19
  • 2011-01-16
  • 1970-01-01
  • 1970-01-01
  • 2014-08-19
  • 2022-01-20
  • 2010-09-05
相关资源
最近更新 更多