首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Tkinter中按Tab键之后捕获文本Widget的值?

如何在Tkinter中按Tab键之后捕获文本Widget的值?
EN

Stack Overflow用户
提问于 2015-09-06 17:02:38
回答 1查看 486关注 0票数 1

我有一个示例脚本(如下所示),在这个脚本中,每当按下"Tab“键时,我都只是试图捕获tkinter文本小部件的值。在这方面,使用了两个函数。在Tab更改值之前,应该运行并显示文本小部件的值。另一个函数应该在Tab更改值后运行并显示文本小部件的值。

问题:

问题是,只有一个函数运行--在选项卡更改其值之前显示文本小部件值的函数。

My System:

Ubuntu 12.04

Python 3.4.3

Tk 8.5

代码:

代码语言:javascript
复制
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()函数的输出。因此,我假设的类后绑定由于某种原因无法工作。但是,如果我将绑定从display_before_value()更改为<Key>,那么当我在文本小部件中键入任何键(当然,Tab键除外)时,display_after_value()和<Tab>都将正确运行。

提前感谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-06 18:03:36

如果您希望在制表符空间之前显示文本,然后使用制表符空间显示文本,请尝试使用root.after()。下面是一个代码示例:

代码语言:javascript
复制
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()

当按下选项卡键时,将执行display_before_value函数,该函数将打印文本小部件的值,而其中没有选项卡空间。1毫秒后,它转到display_after_value函数,它显示文本小部件的值,包括制表符空间。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32426065

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档