首页 > 解决方案 > Tkinter 搜索:需要搜索每个文本小部件

问题描述

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

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

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

问题

如何在所有 text_widgets 中单独搜索特定术语并获取它们的索引并使用它们的索引来滚动各自的文本框?

类似代码

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

标签: pythonpython-3.xtkinter

解决方案


这是比较简单的做法。

但是,我不明白您为什么在激活自动滚动功能之前执行搜索。您需要做的就是循环浏览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小部件中搜索词的多个结果。


推荐阅读