我想创建一个永远运行的程序,并且每隔10秒刷新一次信息。
我得到的最佳解决方案是:
while True:
Gui= GUI()
Gui.after(2000, lambda : Gui.destroy())
Gui.mainloop()
但是这导致了窗口关闭并产生了可怕的效果。 这是我的代码:我想在修改json文件时刷新页面,窗口不应该关闭。
from tkinter import *
import json
import time
def openfile():
data = []
d={}
return_listas = []
with open('test.json', 'r') as f:
for line in f:
data.append(json.loads(line))
for item in data:
d.update(item)
f.close()
return d
class GUI(Tk):
def __init__(self):
self.tk = Tk()
self.tk.wm_state('zoomed')
self.label = {}
self.topFrame = Frame(self.tk)
self.topFrame.pack(side=TOP,fill=Y)
self.task()
def task(self):
i = 0
list = openfile()
for ele in list:
if list[ele]=="true":
lb = Label(self.topFrame, text=ele+"\n", fg="green",font=("Helvetica", 24))
if list[ele]=="false":
lb = Label(self.topFrame, text=ele+"\n", fg="red",font=("Helvetica", 24))
lb.pack(fill=X)
self.label[ele] = lb
i += 1
UPDATE, 现在我有问题,我不能保持可刷新的信息,它要么叠加,要么根本不显示
答案 0 :(得分:1)
您不必每次都删除它,只需更新。这是你GUI
课程:
class GUI(Tk):
def __init__(self):
self.tk = Tk()
self.tk.wm_state('zoomed')
self.topFrame = Frame(self.tk)
self.topFrame.pack(side=TOP,fill=Y)
self.label = Label(self.topFrame, fg="green",font=("Helvetica", 24)) # This will be the label that is updated
self.label.pack(fill=X)
self.tk.after(1000, self.task) # in 1 second it will start the loop
def task(self):
list = openfile()
for ele in list:
if list[ele]=="true":
self.label.configure(text = ele+"\n", fg = 'green')
if list[ele]=="false":
self.label.configure(text = ele+"\n", fg = 'red')
self.tk.after(1000, self.task) # in 1 second it will go again
gui = GUI()
gui.mainloop()
答案 1 :(得分:0)
我所要做的就是删除旧标签
for ele in self.label:
self.label[ele].destroy()
self.label= {}