PyGTK 主循环的阻塞行为
我的目的是使用 pyGTK 的主循环创建一个在等待用户输入时阻塞的函数。我遇到的问题最好用代码来解释:
#! /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
似乎没有遵循指令的确切顺序(更改retval
的值,然后退出主循环)这里。
有什么办法可以解决这个问题,还是这只是我的糟糕设计?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是对话模式。使用 gtk.Dialog。 Dialog.run() 完全阻止您需要的方式,并返回对话框的返回代码。
This is the dialog pattern. Use a gtk.Dialog. Dialog.run() blocks exactly how you need it to, and returns the dialog's return code.
发生的情况是,当 python 将 foo = bar 视为函数中对 foo 的第一个引用时,它假定它是局部变量。在 python3k 中,您可以使用
nonlocal
关键字。对于 2.x,您可以将 retval 包装在一个列表中,这样您就不会直接分配给它。这并不是一个真正优雅的解决方案,因此在 3.x 中添加了 nonlocal (PEP )
What is happening is that when python sees
foo = bar
as the first reference tofoo
in a function it assumes that it is a local variable. In python3k you can get around this by using thenonlocal
keyword. 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)