简体   繁体   中英

Highlighting a clicked line in an unfocused Tkinter text widget

I'd like to keep focus on the entry text widget, which will pass whatever's entered into a separate display text widget. I have that part working.

I can't figure out how to make it so that when someone clicks on the display text widget the line clicked is highlighted (or the line changes background color) but focus is returned to the entry widget. I also need to store a reference to that line so that i can manipulate it with other Widgets.

Here's some sample code so you can see how I have it so far. I have a lot more widgets and code in GUI right now but I only posted the relevant code to my issue:

from Tkinter import *

class GUI:
    def __init__(self,root):
        Window = Frame(root)
        self.OutWidget = Text(Window, state='disabled')
        self.InWidget = Text(Window,bg='black',bd=3,fg='white',exportselection=0,height=1,wrap=WORD,insertofftime=0,insertbackground="white")
        self.OutWidget.pack()
        self.InWidget.pack()
        Window.pack()
        self.InWidget.focus_set()
        self.OutWidget.bind("<Button 1>",self.Select)
        self.InWidget.bind("<Return>", self.Post)

    def Post(self,event):
        text = self.InWidget.get(1.0,2.0)
        self.InWidget.delete(1.0,2.0)
        self.OutWidget['state'] = ['normal']
        self.OutWidget.insert('end',text)
        self.OutWidget['state'] = ['disabled']
        return ("break")

    def Select(self,event):
        #highlight the CURRENT line
        #store a reference to the line
        #return focus to InWidget
        self.InWidget.focus()
        return ("break")

if __name__ == '__main__':
    root = Tk()
    App = GUI(root)
    root.mainloop()

You can get the index of the start of the line where you clicked by using something like this:

line_start = self.OutWidget.index("@%s,%s linestart" % (event.x, event.y))

You can add highlighting by applying a tag to that line with something like this:

line_end = self.OutWidget.index("%s lineend" % line_start)
self.OutWidget.tag_remove("highlight", 1.0, "end")
self.OutWidget.tag_add("highlight", line_start, line_end)

You can set the color for the item with the "highlight" tag with something like this:

self.OutWidget.tag_configure("highlight", background="bisque")

You can move the focus back to the other window with something like this:

self.InWidget.focus_set()

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