如何在不按下按钮的情况下更新此代码的标签?
import tkinter
from tkinter import *
main=Tk()
main.attributes("-fullscreen", False)
lo=open("/xxx/xx/x.l" , "r")
l=lo.read()
lo.close()
info=Label(main, text="Watch Log of COW")
log=Label(main, text=l)
log.config(text=l)
info.pack()
log.pack()
main.mainloop()
您需要定期监视文件的更新,并在文件更改时更新标签。使用文件上次修改时间来检查文件更改,使用.after(...)
定期检查它,如下所示:
import os
from tkinter import *
root = Tk()
Label(text='Watch Log of COW').pack()
log = Label(text='abc')
log.pack()
last_mtime = None
cow = '/xxx/x.l'
def monitor_file_change():
global last_mtime
mtime = os.path.getmtime(cow)
if last_mtime is None or mtime > last_mtime:
with open(cow) as f:
log['text'] = f.read()
last_mtime = mtime
root.after(1000, monitor_file_change)
monitor_file_change()
root.mainloop()
没有你在我的系统上使用的文件我无法提供完美的解决方案,但也许l
不是一个字符串?你有没有尝试过:
import tkinter
from tkinter import *
main=Tk()
main.attributes("-fullscreen", False)
lo=open("/xxx/xx/x.l" , "r")
l=lo.read()
lo.close()
info=Label(main, text="Watch Log of COW")
log=Label(main, text=str(l))
log.config(text=str(l))
info.pack()
log.pack()
main.mainloop()
在哪里尝试使用str(l)
将其显式转换为字符串?如果提供了完整的错误回溯,将会很有帮助。也许错误在于打开你的文件?你有没有尝试过:
with open("/xxx/xx/x.l" , "r") as lo:
l=lo.read()
或者错误是使用.config()
而不是.configure()
(这是我一直使用的,我不知道它们之间的区别)
你的问题太广泛了,我们无法真正提供帮助