Event for text in Tkinter text widget

后端 未结 3 1097
时光取名叫无心
时光取名叫无心 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:52

    Here's a simple example:

    from tkinter import *
    
    def callback(event):
        info_window = Tk()
        info_window.overrideredirect(1)
        info_window.geometry("200x24+{0}+{1}".format(event.x_root-100, event.y_root-12))
    
        label = Label(info_window, text="Word definition goes here.")
        label.pack(fill=BOTH)
    
        info_window.bind_all("<Leave>", lambda e: info_window.destroy())  # Remove popup when pointer leaves the window
        info_window.mainloop()
    
    root = Tk()
    
    text = Text(root)
    text.insert(END, "Hello, world!")
    text.pack()
    
    text.tag_add("tag", "1.7", "1.12")
    text.tag_config("tag", foreground="blue")
    text.tag_bind("tag", "<Button-1>", callback)
    
    root.mainloop()
    

    Clicking on "world" will pop up a small window which disappears when mouse pointer leaves the widget

    0 讨论(0)
  • 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("<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()
    
    0 讨论(0)
  • 2020-12-19 20:58

    Yes, it is possible. You can add a tag to a word or text region using the tag_add function, then use the tag_bind method (with a <Button> event) to make the text "clickable".

    You can create a new TopLevel widget to pop up a new window in the callback function.

    0 讨论(0)
提交回复
热议问题