简体   繁体   中英

While loop not working while using Tkinter

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()

Referencing this 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

So, you have an infinite loop inside your loop.

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.

Something like this

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:

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM