2014-05-20 69 views
0

我在Tkinter中有一个游戏,其中我想实现一个暂停选项。我想bindp停止脚本。我尝试使用time.sleep,但我想暂停游戏,直到用户按u。我曾尝试过:不定期地暂停python tkinter脚本

def pause(self, event): 
    self.paused = True 
    while self.paused: 
     time.sleep(0.000001) 
def unpause(self, event): 
    self.paused = False 

但是,这会导致程序崩溃,并且不会暂停。

什么问题,我该如何解决?

+0

你从来没有给过任何'unpause'的机会 - 'self.paused'没有退出,所以它只是保持循环! – jonrsharpe

+0

unpause被绑定到'u'键,所以当用户点击'u'时,它将变量设置为false,打破循环。 – user2658538

+0

根据地质学家的回答,那不是真的 – jonrsharpe

回答

0

while创建一个循环,使GUI循环对任何事物都无响应 - 包括KeyPress绑定。在暂停方法中调用time.sleep(9999999)会做同样的事情。我不确定程序的其余部分是如何构建的,但您应该查看after()方法,以便添加启动和停止功能。这里有一个简单的例子:

class App(Frame): 
    def __init__(self, parent): 
     Frame.__init__(self, parent) 

     self.text = Text(self) 
     self.text.pack() 

     self._unpause(None) # start the method 

     self.bind_all('<p>', self._pause) 
     self.bind_all('<u>', self._unpause) 

    def _unpause(self, event): 
     '''this method is the running portion. after its 
     called, it continues to call itself with the after 
     method until it is cancelled''' 
     self.text.insert(END, 'hello ') 
     self.loop = self.after(100, self._unpause, None) 

    def _pause(self, event): 
     '''if the loop is running, use the after_cancel 
     method to end it''' 
     if self.loop is not None: 
      self.after_cancel(self.loop) 

root = Tk() 
App(root).pack() 
mainloop() 
+0

我试过了,尽管它仍然导致程序停顿并最终崩溃。 – user2658538

+0

这个确切的代码崩溃,或者当你实现它的一部分崩溃? – atlasologist

+0

这个确切的代码不会崩溃(在Windows中),也许它的实现 – Gogo