Highlighting a clicked line in an unfocused Tkinter text widget

耗尽温柔 提交于 2020-01-04 17:46:12

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/8422942/highlighting-a-clicked-line-in-an-unfocused-tkinter-text-widget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!