暂停python tkinter脚本

2024-03-28 17:54:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

但是,这会使程序崩溃,并且不会取消暂停。在

出什么问题了,我该怎么解决?在


Tags: 用户self脚本eventtrue游戏timebind
1条回答
网友
1楼 · 发布于 2024-03-28 17:54:32

while创建一个循环,使GUI循环对任何内容(包括KeyPress绑定)无响应。在pause方法中只调用time.sleep(9999999)也会做同样的事情。我不确定程序的其余部分是如何组织的,但是您应该研究一下^{}方法,以找到一种添加启动和停止功能的简单方法。下面是一个简单的例子:

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()

相关问题 更多 >