vwait in Python?

Brian Kelley bkelley at wi.mit.edu
Fri Mar 29 10:21:45 EST 2002


Ken Guest wrote:
> On Thu, 2002-03-28 at 11:37, Ken Guest wrote:
> 
>>Anybody know if there's an equivalent to TCL's vwait keyword in Python?
> 
> 
> So is there no way, short of a 2 line while statement, to have code
> hang around until the value of some variable has been changed?

You can always create a function to do this (see below) and create a one 
liner.

> 
> I have tried using variations of the simple while statement, but they
> only result in the application hanging (going into an infinite loop
> no doubt).
> 
> 
> k.
> 

Here is an encapsulated vwait function.  I can't say I recommend this as 
I far prefer the observer pattern described before, but here you go :)

from Tkinter import *
import time

def vwait(root, var, timeout=0.1):
     """(master, var, timeout=0.1)->given a tk master and an observable
     variable
     i.e. var.get() returns a value
     wait for the variable to change.

     WARNING timeout defaults to subsecond precision, might not be
             available on all systems.

     WARNING vwait can only be called after the mainloop has been
             started. See test example below
     """
     start = var.get()
     while 1:
         root.update()
         time.sleep(timeout)
         if var.get() != start:
             break

if __name__ == "__main__":
     def go():
         """function that is called after mainloop is started.
         uses vwait to wait for a variable change"""
         var = IntVar()
         top = Toplevel()
         button = Checkbutton(top, text="Click ME", var=var)
         button.pack()
         label = Label(top, text="Vwait Starting")
         label.pack()
         # wait for var to change
         vwait(top, var)
         # once var is changed alter the label
         label.configure(text="Vwait done")


     root = Tk()
     button = Button(root, text="Start", command=go)
     button.pack()
     mainloop()






More information about the Python-list mailing list