【发布时间】: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 绑定由于某种原因无法正常工作。但是,如果我将绑定从 <Tab> 更改为 <Key>,那么当我在文本小部件中键入任何键时,display_before_value() 和 display_after_value() 都会正确运行(当然 Tab 键除外)。
提前致谢
【问题讨论】:
-
那么当你按下Tab键的时候,你是希望看到Tab空间之前的文字,然后看到Tab空间之后的文字吗?
-
@BobMarshall -- 是的,这是正确的。代码中定义的两个函数都应该处理这两个操作。但是,只执行了 display_before_value() 函数。
-
我的回答解决了这个问题。
标签: python python-3.x tkinter