[英]How do I execute a callback when the Enter key is pressed after entering text into a Text widget?
[英]How to Capture the Value of a Text Widget after the Tab Key is Pressed in Tkinter?
我有一個示例腳本(如下所示),其中每次按下“ Tab”鍵時,我只是試圖捕獲tkinter文本小部件的值。 有兩個功能可以幫助解決這個問題。 在選項卡更改值之前,應運行並顯示文本小部件的值。 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()函數的輸出。 因此,我假設類后綁定由於某種原因無法正常工作。 但是,如果我將綁定從<Tab>
更改為<Key>
則當我在文本小部件中鍵入任何鍵(當然,Tab鍵除外)時 , display_before_value()和display_after_value()都可以正確運行。
提前致謝
如果希望文本在選項卡空間之前顯示,文本在選項卡空間之后顯示,請嘗試使用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函數,該函數顯示文本小部件的值,包括制表符空間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.