【问题标题】:While loop not working while using Tkinter使用 Tkinter 时循环不起作用
【发布时间】:2015-04-24 13:43:58
【问题描述】:

我有一个 BASH 脚本正在运行,它打开一个程序 (tshark),它将一堆值写入日志文件。该脚本然后计算唯一值并将最后 3 分钟的唯一值(计数)写入日志文件 (count3m.log) 它还打开一个 python 脚本。 python 在那里显示一个窗口,其中包含来自 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()

【问题讨论】:

  • 当您的代码到达root.mainloop() 时,它“基本上”会停止。 root.mainloop() 实例化 Tkinter,此时您的程序完全在等待事件发生,而不是继续运行代码。
  • 什么是root.mainloop()?我认为它可能会挂起你的循环(无限循环中的无限循环)。

标签: python bash tkinter tshark


【解决方案1】:

引用此answer

mainloop 实际上只不过是一个大致如下所示的无限循环(这些不是方法的实际名称,这些名称只是为了说明这一点):

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

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

为了更新您的标签,您需要将一个事件附加到您的根目录。另外,设置标签的 textvariable = 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?

【讨论】:

  • 花了一些时间研究其他主题,但最终让它发挥作用。感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-22
  • 2021-04-09
  • 1970-01-01
  • 1970-01-01
  • 2020-12-24
  • 1970-01-01
相关资源
最近更新 更多