Tkinter 文本小部件中的文本事件 [英] Event for text in Tkinter text widget
本文介绍了Tkinter 文本小部件中的文本事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以知道是否可以为 tkinter 文本小部件中的文本创建事件?例如,我在文本框中单击一个单词,会弹出一个小窗口并给出该单词的简要定义.
May I know is it possible to create a event for a text in tkinter text widget? Example, I click on a word on text box, and a small window will pop out and give a brief definition of the word.
推荐答案
您可以向文本小部件添加绑定,就像添加任何其他小部件一样.我认为这就是您所说的创建事件"的意思.
You can add bindings to a text widget just like you can with any other widget. I think that's what you mean by "create a event".
在下面的示例中,我绑定到释放鼠标按钮并突出显示光标下的单词.你可以很容易地弹出一个窗口,在其他地方显示这个词,等等.
In the following example I bind to the release of the mouse button and highlight the word under the cursor. You can just as easily pop up a window, display the word somewhere else, etc.
import Tkinter as tk
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.text = tk.Text(self, wrap="none")
self.text.pack(fill="both", expand=True)
self.text.bind("<ButtonRelease-1>", self._on_click)
self.text.tag_configure("highlight", background="green", foreground="black")
with open(__file__, "rU") as f:
data = f.read()
self.text.insert("1.0", data)
def _on_click(self, event):
self.text.tag_remove("highlight", "1.0", "end")
self.text.tag_add("highlight", "insert wordstart", "insert wordend")
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()
这篇关于Tkinter 文本小部件中的文本事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文