user3431399
user3431399

Reputation: 499

Event for text in Tkinter text widget

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.

Upvotes: 5

Views: 8774

Answers (3)

Bryan Oakley
Bryan Oakley

Reputation: 385810

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

Upvotes: 10

Mirac7
Mirac7

Reputation: 1646

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

Upvotes: 3

Brionius
Brionius

Reputation: 14098

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.

Upvotes: 2

Related Questions