Event for text in Tkinter text widget

后端 未结 3 1120
时光取名叫无心
时光取名叫无心 2020-12-19 20:20

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 defin

3条回答
  •  一向
    一向 (楼主)
    2020-12-19 20:58

    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("", 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()
    

提交回复
热议问题