My intention was to use pyGTK’s main loop to create a function that blocks while it waits for the user’s input. The problem I’ve encountered is best explained in code:
#! /usr/bin/python
import gtk
def test():
retval = True
def cb(widget):
retval = False
gtk.main_quit()
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
button = gtk.Button("Test")
button.connect("clicked", cb)
button.show()
window.add(button)
window.show()
gtk.main()
return retval
if __name__ == "__main__":
print test() # prints True when the button is clicked
It seems that the exact order of instructions (change value of retval, then exit main loop) isn’t being followed here.
Is there any way around this, or is this just bad design on my part?
What is happening is that when python sees
foo = baras the first reference tofooin a function it assumes that it is a local variable. In python3k you can get around this by using thenonlocalkeyword. For 2.x you can wrap your retval in a list so that you aren’t directly assigning to it.not really an elegant solution, hence the addition of nonlocal in 3.x (PEP)