执行 def 函数时 GUI 冻结。使用线程?
我制作了一个小程序,它有 2 个按钮,每个按钮都执行某些操作。这是代码的简化版本。
问题是它工作正常,只是按钮冻结并停留在单击位置,并且整个 GUI 冻结直到命令完成。 据我所知,在这种情况下最好使用线程,但我不知道如何在这个示例中实现它。
我使用 Glade 和 pygtk 作为 GUI。
def do1:
t = 2
#do something
time.sleep(t)
#do something
time.sleep(t)
def do2:
t = 3
#do something
time.sleep(t)
#do something
time.sleep(t)
class we:
wTree = None
def __init__( self ):
self.wTree = gtk.glade.XML( "ui.glade" )
dic = {
"on_buttonSone" : self.sone,
"on_buttonStwo" : self.stwo,
}
self.wTree.signal_autoconnect( dic )
gtk.main()
def sone(self, widget):
i = 0
while i < 3:
t = 1
#do something
i += 1
time.sleep(t)
self.wTree.get_widget("entryResult").set_text("Done.")
def stwo(self, widget):
start = time.clock()
array = ['A','B']
adict = {'A':do1,'B':do2}
for f in array:
adict[f]()
end = time.clock()
elapsed = end - start
gg = round(elapsed,2)
self.wTree.get_widget("entryResult").set_text(str(gg))
go=we()
I've made a small program which has 2 buttons and each does certain thing. Here's a simplified version of the code.
Thing is it works fine except that the button freezes and stays in a clicked position and whole GUI freezes until the command is completed.
As far as I know threads would be best to use in this situation, but I have no idea how to implement it in this example.
I use glade and pygtk for gui.
def do1:
t = 2
#do something
time.sleep(t)
#do something
time.sleep(t)
def do2:
t = 3
#do something
time.sleep(t)
#do something
time.sleep(t)
class we:
wTree = None
def __init__( self ):
self.wTree = gtk.glade.XML( "ui.glade" )
dic = {
"on_buttonSone" : self.sone,
"on_buttonStwo" : self.stwo,
}
self.wTree.signal_autoconnect( dic )
gtk.main()
def sone(self, widget):
i = 0
while i < 3:
t = 1
#do something
i += 1
time.sleep(t)
self.wTree.get_widget("entryResult").set_text("Done.")
def stwo(self, widget):
start = time.clock()
array = ['A','B']
adict = {'A':do1,'B':do2}
for f in array:
adict[f]()
end = time.clock()
elapsed = end - start
gg = round(elapsed,2)
self.wTree.get_widget("entryResult").set_text(str(gg))
go=we()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
pyGTK 的 FAQ 中有一整节专门讨论线程。
20.6 似乎是一个很好的最小示例。
pyGTK has a whole section of there FAQ devoted to threading.
20.6 seems like a good minimal example.