我有一个代码,我试图打印tkinter标签中的列表列表,但它不能以我想要的方式工作。当我运行下面的脚本时,它将在list.txt中搜索输入的文本,并在tkinter标签中打印它。输入更多文本时,先前搜索的文本应清除,新文本应根据list.txt文件中的搜索结果显示。但是前面的文本没有被清除。下面是部分代码:
import tkinter as tk
import re
from tkinter import Label
class App(tk.Tk):
def __init__(self):
super().__init__()
self.var = tk.StringVar()
self.var.trace("w", self.show_message)
self.entry = tk.Entry(self, textvariable=self.var)
self.label = tk.Label(self)
self.entry.pack()
self.label.pack()
def show_message(self, *args):
value = self.var.get()
scen = []
text = "{}".format(value) if value else scen.clear()
if text:
words = re.split('[ ]', text.lower())
with open('list.txt','r') as mfl:
scen.clear()
for line in mfl:
if all(word in line.lower() for word in words):
txt = re.split("[._ -]",line)
scen.append(txt[:-1])
for i in range(len(scen)):
exec('Label%d=Label(app,text="%s")\nLabel%d.pack()'%(i,scen[i],i))
if __name__ == "__main__":
app = App()
app.mainloop()
标准规则:
您应该在列表中保留标签,然后不必使用
exec()
来创建变量Label%d
,稍后您可以在添加新标签之前使用for
-loop来destroy()
所有标签相关问题 更多 >
编程相关推荐