Skip to main content
 首页 » 编程设计

python之向 tkinter 小部件添加标签会更改整个布局

2025年02月15日8kevingrace

我正在做一个python文本编辑器,现在忙于find功能。 然后,当找到用户输入的最后一次出现时,它会再次跳回开头,并在窗口底部显示文本“从顶部找到第 1 次出现,已到达文件末尾”。

但是显示这个也会改变所有其他项目的位置,如您所见here .现在,我想从将文本添加到对话框底部后得到的布局开始。这是我的相关代码:

find_window = Toplevel() 
find_window.geometry('338x70') 
find_window.title('Find') 
 
Label(find_window, text='Enter text to find:').grid(row=0, column=0, sticky=W) 
 
find_text = Entry(find_window, highlightcolor='blue', highlightbackground='blue', highlightthickness=1) 
find_nextbutton = Button(find_window, text='Find Next', command=find_next) 
find_allbutton = Button(find_window, text='Find All') 
 
find_text.grid(row=0, column=1, sticky=W) 
find_nextbutton.grid(row=0, column=2, sticky=W) 
find_allbutton.grid(row=1, column=2, sticky=W) 

当找到最后一次出现时,我会这样做:

file_end = Label(find_window, text='Found 1st occurance from the top, end of file has been reached.') 
file_end.grid(row=2, columnspan=4, sticky=W) 

请您参考如下方法:

最简单的解决方案不是将窗口强制设置为特定大小,而是始终将那个标签放在那里。将宽度设置得足够大以包含消息的全文。当您准备好显示值时,使用 configure 方法显示文本。

这是一个基于您的代码的完整示例:

from tkinter import * 
 
root = Tk() 
text = Text(root) 
text.pack(fill="both", expand=True) 
with open(__file__, "r") as f: 
    text.insert("end", f.read())                 
 
def find_next(): 
    file_end.configure(text='Found 1st occurance from the top, end of file has been reached.') 
 
find_window = Toplevel() 
#find_window.geometry('338x70') 
find_window.title('Find') 
 
Label(find_window, text='Enter text to find:').grid(row=0, column=0, sticky=W) 
 
find_text = Entry(find_window, highlightcolor='blue', highlightbackground='blue', highlightthickness=1) 
find_nextbutton = Button(find_window, text='Find Next', command=find_next) 
find_allbutton = Button(find_window, text='Find All') 
file_end = Label(find_window, width=50) 
 
find_text.grid(row=0, column=1, sticky=W) 
find_nextbutton.grid(row=0, column=2, sticky=W) 
find_allbutton.grid(row=1, column=2, sticky=W) 
file_end.grid(row=2, columnspan=4, sticky="w") 
 
find_window.lift(root) 
root.mainloop()