gpt4 book ai didi

python - 在文本小部件中搜索单词/字母 (tkinter)

转载 作者:行者123 更新时间:2023-12-01 05:25:11 24 4
gpt4 key购买 nike

如何添加在文本小部件中搜索文本的搜索功能?* 根据用户输入进行搜索

def openFile():
global text
artiststxt = tkinter.Tk()
artiststxt.title('Artists')
artiststxt.geometry('300x360')
artiststxt.minsize(300,360)
artiststxt.maxsize(500,360)
file = open('Artists.txt','r', encoding='utf-8')
lines = file.read()
scrollbar = Scrollbar(artiststxt, jump = 1)
text = Text(artiststxt, yscrollcommand = scrollbar.set)
scrollbar.configure(command=text.yview)
text.insert(INSERT, lines)
text.config(font=('Fixedsys', 15), fg = 'darkblue', bg = 'lightgray')
menu = tkinter.Menu(artiststxt,tearoff=0)
menu.add_command(label='Save', command = saveFile)
artiststxt.config(menu=menu)
scrollbar.pack(side=RIGHT, fill=BOTH)
text.pack()

编辑:好的,我找到了如何用这个搜索文本:

def get(event):
global searchent
text.tag_remove('found', '1.0', END)
s = searchent.get()
if s:
idx = '1.0'
while 1:
idx = text.search(s, idx, nocase=1, stopindex=END)
if not idx: break
lastidx = '%s+%dc' % (idx, len(s))
text.tag_add('found', idx, lastidx)
idx = lastidx
text.tag_config('found', foreground='red')
searchent.focus_set()

现在,假设搜索的文本位于更下方。如何使滚动条向下移动到搜索到的文本?

最佳答案

好吧,我明白了。花了一些时间,但非常值得。

首先我们在窗口中创建一个输入框,并将其与回车键绑定(bind)并放置一个 .get 事件

searchent.bind("<Return>", get)

当按下回车键时,我们进入 def get(event):

def get(event):
global searchent
text.tag_remove('found', '1.0', END)
s = searchent.get() # Grabs the text from the entry box
if s:
idx = '1.0'
while 1:
idx = text.search(s, idx, nocase=1, stopindex=END)
if not idx: break
lastidx = '%s+%dc' % (idx, len(s))
text.tag_add('found', idx, lastidx)
idx = lastidx
text.see(idx) # Once found, the scrollbar automatically scrolls to the text
text.tag_config('found', foreground='red')
searchent.focus_set()

关于python - 在文本小部件中搜索单词/字母 (tkinter),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21507157/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com