2015-09-06 50 views
1

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

问题:

的问题是,只有一个函数运行 - 显示的文本组件之前的标签改变其值的值的功能。

我的系统:

的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()函数的输出。所以我假设后级绑定由于某种原因不起作用。但是,如果我将<Tab>中的绑定更改为<Key>,则当我在文本窗口小部件中键入任意键(当然,Tab键除外)时,display_after_value()和和和都会正确运行。要显示

在此先感谢

+0

因此,当您按下标签页时,是否希望标签空间之前的文本能够被看到,并且标签空间的文本能够被看到之后? –

+0

@BobMarshall - 是的,这是正确的。代码中定义的两个函数都应该处理这两个操作。但是,仅执行display_before_value()函数。 – SizzlingVortex

+0

我的答案解决了这个问题。 –

回答

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功能,打印文本控件的值,而在它的标签空间。 1毫秒后,它转到display_after_value函数,该函数显示包含制表符空间的文本小部件的值。

+0

谢谢!这工作,我可能会接受它作为答案。 我只想看看是否有没有使用.after()方法的替代方案。再次感谢! – SizzlingVortex

相关问题