简体   繁体   中英

Separate command for clicking each line in Python Tkinter Text Widget

Background

Each one of the items appearing in my text widget represent tasks. I am using a Text widget over a ListBox because Text widget allows different colors for different items. The color of each task is its status. Is it possible to set a separate LC command for each task?

I have a split-pane application with tasks on the right (possibly scrollable), and I want clicking on a task to open it up for scrutiny in the pane on the left.

Main Question

Can I in any way activate separate events on left-clicking separate lines in a Python Text Tkinter widget?

Just set a binding on <1> . It's easy to get the line number that was clicked on using the index method of the widget and the x/y coordinate of the event.

Here's a simple example:

import Tkinter as tk

class ExampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.status = tk.Label(self, anchor="w")
        self.status.pack(side="bottom", fill="x")
        self.text = tk.Text(self, wrap="word", width=40, height=8)
        self.text.pack(fill="both", expand=True)
        self.text.bind("<1>", self.on_text_button)
        for n in range(1,20):
            self.text.insert("end", "this is line %s\n" % n)


    def on_text_button(self, event):
        index = self.text.index("@%s,%s" % (event.x, event.y))
        line, char = index.split(".")
        self.status.configure(text="you clicked line %s" % line)

if __name__ == "__main__":
    app = ExampleApp()
    app.mainloop()

I think you can do something like this. tkHyperlinkManger does it ( http://effbot.org/zone/tkinter-text-hyperlink.htm )

Since you're already coloring the lines differently, I assume you're using tag_config . Then all you need is tag_bind to bind a callback to the region of text.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM