我怎样才能使按钮按下时再次运行。 即我进入" BIG"并单击按钮 - >返回答案,然后我改变" BIG"到" SMALL"然后再次单击,但没有任何反应,但我希望它再次搜索并再次返回结果。
from tkinter import *
def part_search():
Finder = ()
scrollbar = Scrollbar(mGui)
scrollbar.pack(side=RIGHT, fill=Y)
listbox = Listbox(mGui)
listbox.pack(fill=BOTH, expand=1)
listbox.configure(justify=CENTER, bg="orange", font="Times 16")
mtext = ment.get()
mlabel2 = Label(mGui, text=mtext)
mlabel2.pack()
msearch = open(r"D:\Users\gblmac\Desktop\Python programs\Parts List\Parts.txt")
for line in msearch:
if mtext in line:
listbox.insert(END, str(line))
listbox.config(yscrollcommand=scrollbar.set, height=30, width=0, justify=LEFT)
scrollbar.config(command=listbox.yview)
msearch.close()
return
mGui = Tk()
mGui.configure(bg="orange")
ment = StringVar()
mGui.geometry ("1000x500+200+300")
mGui.title ("Parts Finder")
mlabel1 = Label(mGui, text="Type in search term", font="Times 20", bg="orange")
mlabel1.pack()
mentry = Entry(textvariable=ment, font="Times 20", width = 50, bg="orange")
mentry.pack()
mentry.focus()
mlabel3 = Label(mGui, text="Now click GO", font="Times 20", bg="orange")
mlabel3.pack()
mbutton = Button(mGui, text ="Go", font="Times 20", command = part_search, bg="grey")
mbutton.pack()
答案 0 :(得分:1)
嗯,你在创建元素时遇到了一些问题 我将首先提供固定代码,然后解释:
from tkinter import *
def part_search():
# The sole purpose of this function is to update elements, not creating them.
mtext = ment.get()
print(mtext)
mlabel2.config(text=mtext)
msearch = open(r"Parts.txt")
print('again')
for line in msearch:
if mtext in line:
listbox.insert(END, str(line))
listbox.config(yscrollcommand=scrollbar.set,width=0, justify=LEFT)
scrollbar.config(command=listbox.yview)
msearch.close()
return
# This code is your original code for creating the first elements
mGui = Tk()
mGui.configure(bg="orange")
ment = StringVar()
mGui.geometry ("1000x500+200+300")
mGui.title ("Parts Finder")
mlabel1 = Label(mGui, text="Type in search term", font="Times 20", bg="orange")
mlabel1.pack()
mentry = Entry(textvariable=ment, font="Times 20", width = 50, bg="orange")
mentry.pack()
mentry.focus()
mlabel3 = Label(mGui, text="Now click GO", font="Times 20", bg="orange")
mlabel3.pack()
mbutton = Button(mGui, text ="Go", font="Times 20", command = part_search, bg="grey")
mbutton.pack()
# here is the moved code from the function
Finder = ()
scrollbar = Scrollbar(mGui)
scrollbar.pack(side=RIGHT, fill=Y)
listbox = Listbox(mGui)
listbox.pack(fill=BOTH, expand=1)
listbox.configure(justify=CENTER, bg="orange", font="Times 16")
mlabel2 = Label(mGui)
mlabel2.pack()
while True:
# ball.draw()
mGui.update_idletasks()
mGui.update()
发生了什么事?
在代码中,在part_search
函数内,您已创建元素并在UI中显示它们。然后,每次调用,您再次创建这些元素并将它们堆叠在您的布局中。他们刚刚消失了,在你的列表框下方
另一件事是你已经设置了一个完整的高度列表框,它将你的标签推到了窗口的底部。
您应该使用Tk
布局方案(堆叠,格栅等)。请参阅官方文档here
如何避免此类错误?
您应该将创建UI的代码和为其提供信息的代码分开,并对用户操作做出反应。在YouTube中快速搜索和基本教程应该可以帮助您入门。一次解决一个问题要容易得多,并且有许多关于UI设计的模式和知识,即使对于只为POC创建UI的后端开发人员和研究人员,它也非常有用。
祝你好运!