python - 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))
解决方案
这是比较简单的做法。
但是,我不明白您为什么在激活自动滚动功能之前执行搜索。您需要做的就是循环浏览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
小部件中搜索词的多个结果。
推荐阅读
- unicode - 如何在 Zig 中打印 UTF-16 字符串?
- javascript - React hook useEffect 首先返回空数组
- ios - 为什么我会收到涉及 `_kFIRLoggerInstanceID` 的错误?
- dictionary - 为什么“Map”类的“get”方法可以发送不相关的键而不会出现编译错误?
- jquery - 404 未在发布路线上找到
- c# - 将基于 Kerberos 的 WindowsIdentity 转换为 Base64 字符串
- sql-server - Pandas read_sql changing large number IDs when reading
- typescript - 即使输入了函数,我在导入的函数上也遇到了 no-unsafe-call 和 no-unsafe-assignment eslint 错误
- java - 尝试在 javafx 中使用 imageViews 创建滚动背景效果
- postgresql - 防止 Docker 容器在主进程死亡时退出