在未聚焦的 Tkinter 文本小部件中突出显示单击的行 [英] Highlighting a clicked line in an unfocused Tkinter text widget

查看:27
本文介绍了在未聚焦的 Tkinter 文本小部件中突出显示单击的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将重点放在输入文本小部件上,它会将输入的任何内容传递到单独的显示文本小部件中.我有那部分工作.

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.

这是一些示例代码,您可以了解我目前的情况.我现在在 GUI 中有更多的小部件和代码,但我只将相关代码发布到我的问题中:

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)

您可以使用highlight"标签为项目设置颜色,如下所示:

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

这篇关于在未聚焦的 Tkinter 文本小部件中突出显示单击的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆