使用 Tkinter 时循环不起作用

While loop not working while using Tkinter

我有一个 BASH 脚本 运行 打开一个程序 (tshark),它将一堆值写入日志文件。然后脚本计算唯一值并将最近 3 分钟的(计数)唯一值写入日志文件 (count3m.log) 它还会打开一个 python 脚本。 python 用于显示 window 和 count3m.log 中的值。由于 count3m.log 中的值每 30 秒更改一次,我想继续从 count3m 中寻找新值。我用下面的代码试了一下。它只执行一次循环。我做错了什么?

#!/usr/bin/env python

import sys
import re
import time
from Tkinter import *

while True:  

    root = Tk()
    count3m = open('count3m.log','r')
    countStart = open('countStart.log','r')


    minutes = Label(root, text="Uniq signals < 3m ago:")
    minutes.grid(row=0, column=0)

    minutes = Label(root, text=count3m.read())
    minutes.grid(row=1, column=0)
    count3m.close

    minutes = Label(root, text="Uniq signals since start:")
    minutes.grid(row=0, column=1)

    minutes = Label(root, text=countStart.read())
    minutes.grid(row=1, column=1)
    countStart.close
    time.sleep(5)
    print "test"
    root.mainloop()

引用此 answer

mainloop is really nothing more than an infinite loop that looks roughly like this (those aren't the actual names of the methods, the names merely serve to illustrate the point):

while True:
    event=wait_for_event()
    event.process()
    if main_window_has_been_destroyed(): 
        break

所以,你的循环中有一个无限循环。

为了更新您的标签,您需要将一个事件附加到您的根。此外,设置标签的 textvariable = a StringVar。然后,更新事件中的StringVar,它会改变标签。

像这样

text  = StringVar()
label = Label(root, textvariable=text)
label.pack()

def update_label():
  text.set("new stuff")
  #update again
  root.after(SOME_TIME, update_label)

#the first update
root.after(SOME_TIME, update_label)
root.mainloop()

这应该给你基本的想法。相关堆栈溢出问题:

Making python/tkinter label widget update?

Python: Is it possible to create an tkinter label which has a dynamic string when a function is running in background?