[英]Is there a way to print list of lists in tkinter label?
我有一个代码,我试图在其中打印 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()
标准规则:
"if you have many elements then keep them on list"
您应该将标签保留在列表中,然后您不必使用exec()
创建变量Label%d
,稍后您可以在添加新标签之前使用for
-loop 来destroy()
所有标签。
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()
# list for all labels
self.all_labels = []
def show_message(self, *args):
text = self.var.get()
scen = []
if text:
words = text.lower().split(' ')
with open('list.txt') 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])
# remove all labels
for item in self.all_labels:
item.destroy()
self.all_labels.clear() # remove references to old labels (as @acw1668 noticed in comment)
# add new labels
for item in scen:
l = tk.Label(self, text=item)
l.pack()
self.all_labels.append(l)
if __name__ == "__main__":
app = App()
app.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.