[Tutor] (no subject)

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 11 Apr 2001 02:09:30 -0700 (PDT)


On Tue, 10 Apr 2001, Glen Bunting wrote:

> Below is a simple script I wrote to download a file, time how long it takes
> to download and display the bandwidth usage in Tkinter.  It works initially.
> But the while loop does not work.  After the initial run, the program just
> hangs there and I cannot even exit out of the Tkinter that pops up.  What am
> I doing wrong?


When we hit the mainloop() command, Tkinter takes control, and doesn't
exit the mainloop() function until we shut down the gui by closing all
windows (or calling quit()).  It's meant to be the last command in a
program, so that's what's causing the while loop to "hang".

It looks like you want to update your display every once in a while: try
using the after() method: it tells Tkinter to call a function "after" a
certain period of time.  For example:

###
from Tkinter import *
root = Tk()

def addLabelContinuously():
    Label(root, text='hola').pack()
    root.after(1000, addLabelContinuously)

addLabelContinuously()
mainloop()
###

is a funny little program that, after every second, pack()s in a new label
into our main window.  Not very useful, but it illustrates how to use
after() a little bit.




I hope you don't mind, but I wanted to try converting your code with OOP.  
As a result, I've mutilated your code somewhat beyond recognition.  


###
from Tkinter import *
import os, urllib, time

class GUI(Frame):
    def __init__(self, root):
        Frame.__init__(self, root)
        self.speedvar = StringVar()
        self.updateSpeedvar()
        Label(self, text='Kilobytes/sec:').pack()
        Label(self, textvariable=self.speedvar).pack()
        Button(self, text='QUIT', command=self.quit,
               bg='red', fg='white').pack()

    def updateSpeedvar(self):
        first = time.time()
        urllib.urlretrieve('http://www.esynch.com/mw_test.dat', 'test')
        second = time.time()
        speed1 = second - first
        print speed1
        speed = round(speed1, 1)
        self.speedvar.set(speed)
        self.after(500, self.updateSpeedvar)

if __name__ == '__main__':
    root = Tk()
    gui = GUI(root)
    gui.pack()
    mainloop()
###