Tkinter搜索:需要搜索每个文本小部件

时间:2018-07-18 15:14:52

标签: python python-3.x tkinter

我有一个函数,当用户单击按钮时,该函数会在框架中动态添加文本小部件。然后将不同的文本插入到每个文本小部件中。这些文本窗口小部件已存储在列表中,因为我想通过调用.see方法来滚动所有文本框。

我定义了一个函数,该函数将所有文本小部件自动滚动到使用text.search()方法获得的特定位置。

text.search()方法从文本小部件编号中返回搜索词的索引。 1帧,然后它自动滚动所有文本小部件。

问题

如何在所有text_widget中分别搜索特定术语并获取其索引并使用其索引滚动其各自的文本框?

相似代码

#Initializing an array at the top of your code:

widgets = []

#Next, add each text widget to the array:

for i in range(10):
    text1 = tk.Text(...)
    widgets.append(text1)

#Next, define a function that calls the see method on all of the widgets:

def autoscroll(pos):
    for widget in widgets:
        widget.see(pos)

#Finally, adjust your binding to call this new method:

pos_start = text1.search(anyword, '1.0', "end")
text1.tag_bind(tag, '<Button-1>', lambda e, index=pos_start: autoscroll(index))

1 个答案:

答案 0 :(得分:0)

这相对简单。

但是,我不明白为什么要在激活自动滚动功能之前执行搜索。您需要做的就是循环浏览list widgets并确定每当您要开始自动滚动时文本出现的位置,下面的脚本将执行我认为是期望的行为:

import tkinter as tk

class App:
    def __init__(self, root):
        self.root = root
        self.texts = [tk.Text(self.root) for i in range(3)]
        for i in self.texts:
            i.pack(side="left")
        tk.Button(self.root, text="Find 'foobar'", command=self.find).pack()

    def find(self):
        for i in self.texts:
            if i.search("foobar", "1.0", "end") != "":
                i.see(i.search("foobar", "1.0", "end"))

root = tk.Tk()
App(root)
root.mainloop()

但是,这并没有考虑到在同一Text小部件中甚至在多个Text小部件中搜索词的多个结果。