在Tkinter上,将其他文本框滚动到单击时包含在文本框1中的文本。没有标签绑定是否可能?

时间:2018-07-25 19:56:15

标签: python-3.x tkinter

说明:

我创建了3个文本框。第一个和第二个用文本填充。 第三是前两个文本框之间的比较。 我用tag_configure来显示差异。


问题:

我希望当我单击文本框1或2或3中的句子或文本的任何部分时,它应该将其他文本框滚动到该文本。

如何点击提取文字?


输出:

当我在文本框1上单击26时,它应将tb 2和3滚动到该特定文本(即:26)。

enter image description here


代码:

import diff_match_patch as dmp_module
import tkinter as tk

k1 = []
k2=[]
for i in range(100):
    k1.append(" This is the " + str(i) + " document\n")
    k2.append(" This is the " + str(i+5) + " doc\n")

diff = []    
for i in range(len(k1)):    
    dmp = dmp_module.diff_match_patch()
    diff.append(dmp.diff_main(k1[i], k2[i]))
    (dmp.diff_cleanupSemantic(diff))

root = tk.Tk()
journal2 = tk.Text(root, borderwidth=2, highlightthickness=0,  width = 45, height = 30)
journal2.insert("end","Textbox 1\n\n\n")
journal2.insert("end","\n".join(k1))
journal2.pack(side = 'left')

journal3 = tk.Text(root, borderwidth=2, highlightthickness=0,  width = 45, height = 30)
journal3.insert("end","Textbox 2\n\n\n")
journal3.insert("end","\n".join(k2))
journal3.pack(side = 'left')

journal1 = tk.Text(root, borderwidth=2, highlightthickness=0,  width = 45, height = 30)
journal1.insert("end","Textbox 3\n\n\n")
journal1.pack(side = 'left')

journal1.tag_config('insert', foreground="navy", font='Courier 10 bold')
journal1.tag_config('delete', foreground="red2", overstrike=True, )

def add_hyperlink2(section, tag2):
    journal1.insert("end",section,('delete', tag2))

def add_hyperlink3(section, tag2):
    journal1.insert("end",section,('insert', tag2))

def add_hyperlink4(section, tag2):
    journal1.insert("end",section, tag2)

for y in range(len(diff)):
    for q in range(len(diff[y])):
        if diff[y][q][0] == -1:
            add_hyperlink2(diff[y][q][1], diff[y][q][1])

        elif diff[y][q][0] == 1:
            add_hyperlink3(diff[y][q][1], diff[y][q][1])

        else:
            add_hyperlink4(diff[y][q][1], diff[y][q][1])

root.mainloop()

1 个答案:

答案 0 :(得分:1)

  

如何点击提取文字?

如果绑定到鼠标单击,则传递给回调的事件对象将具有单击发生位置的x / y坐标。您可以使用它来获取被单击的行的索引。如果您绑定到按钮的 release ,则文本小部件将更新插入光标,您可以使用它来了解单击了哪一行。

这是一个简单的例子:

import tkinter as tk

def on_click(event):
    index = text.index("@%s,%s" % (event.x, event.y))
    line, char = index.split(".")
    label1.configure(text="Click on line %s" % line)

def on_click_release(event):
    index = text.index("insert")
    line, char = index.split(".")
    label2.configure(text="Click Release on line %s" % line)

root = tk.Tk()

label1 = tk.Label(root, anchor="w")
label2 = tk.Label(root, anchor="w")
text = tk.Text(root)
label1.pack(side="top", fill="x")
label2.pack(side="top", fill="x")
text.pack(side="bottom", fill="both", expand=True)

for i in range(1, 20):
    text.insert("end", "line #%s\n" % i)

text.bind("<ButtonPress-1>", on_click)
text.bind("<ButtonRelease-1>", on_click_release)

root.mainloop()

运行上面的代码时,如果在一行上单击并按住鼠标按钮,则行号将使用x / y坐标显示在顶部。释放按钮时,行号将使用insert索引显示。