使用 Tkinter 时 while 循环不起作用 [英] While loop not working while using Tkinter
问题描述
我有一个 BASH 脚本正在运行,它打开一个程序 (tshark),该程序将一堆值写入日志文件.然后脚本计算唯一值并将过去 3 分钟的(计数)唯一值写入日志文件 (count3m.log) 它还打开一个 python 脚本.python 用于显示一个窗口,其中包含来自 count3m.log 的值.由于 count3m.log 中的值每 30 秒更改一次,我想继续从 count3m 中寻找新值.我用下面的代码试过了.它只执行一次循环.我做错了什么?
I have a BASH script running that opens a program (tshark) which writes a bunch of values to a logfile. The script then counts the unique values and writes the (count of the) uniques values from the last 3 minutes to a logfile (count3m.log) It also opens a python script. The python is there to show a window with the values from count3m.log. As the value in count3m.log changes every 30 seconds I want to keep looking for a new value from count3m. I tried it with the code below. It only executes the loop once. What am I doing wrong?
#!/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()
推荐答案
参考这个 答案
mainloop 实际上只不过是一个大致如下所示的无限循环(这些不是方法的实际名称,名称仅用于说明这一点):
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
所以,你的循环中有一个无限循环.
So, you have an infinite loop inside your loop.
为了更新您的标签,您需要将一个事件附加到您的根目录.另外,设置标签的 textvariable = a StringVar.然后,更新事件中的StringVar,它会改变标签.
In order to update your label, you'll need to attach an event to your root. Also, set your label's textvariable = a StringVar. Then, update the StringVar in the event, and it will change the label.
像这样
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()
这应该给你基本的想法.相关堆栈溢出问题:
That should give you the basic idea. Relate stack overflow questions:
Python:当函数在后台运行时,是否可以创建一个具有动态字符串的 tkinter 标签?
这篇关于使用 Tkinter 时 while 循环不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!