gpt4 book ai didi

python - 用一个按键暂停无限循环

转载 作者:行者123 更新时间:2023-12-04 05:41:04 31 4
gpt4 key购买 nike

我是 python 新手,我一直在尝试找到一种简单的方法来暂停正在运行的 while 循环,从而可以从暂停的位置重新启动它。我在谷歌上搜索了帮助和提示,但我发现的一切似乎都非常复杂。有没有一种简单的方法可以做到这一点?

我读过你可以使用 termios 和 tkinter。

我正在使用 ubuntu。

抱歉语言错误

谢谢!

最佳答案

这是一个在无限循环中运行的简单 tkinter 程序。按空格暂停/取消暂停,按 Esc 退出。

注意:以下是 Python 2.x,如果您使用的是 Python 3,请更改 Tkinter在第一行到 tkinter (小写 t)。

from Tkinter import *
import time

class MyLoop():
def __init__(self, root):
self.running = True
self.aboutToQuit = False
self.root = root
self.someVar = 0
self.root.bind("<space>", self.switch)
self.root.bind("<Escape>", self.exit)

while not self.aboutToQuit:
self.root.update() # always process new events

if self.running:
# do stuff
self.someVar += 1
print(self.someVar)
time.sleep(.1)

else: # If paused, don't do anything
time.sleep(.1)

def switch(self, event):
print(['Unpausing','Pausing'][self.running])
self.running = not(self.running)

def exit(self, event):
self.aboutToQuit = True
self.root.destroy()

if __name__ == "__main__":
root = Tk()
root.withdraw() # don't show the tkinter window
MyLoop(root)
root.mainloop()

这是一个可能的输出,我在退出之前手动暂停和取消暂停程序两次。
1
2
3
4
5
6
7
Pausing
Unpausing
8
9
10
11
12
13
14
15
16
Pausing
Unpausing
17
18
19
20
21
22
23
24
25

关于python - 用一个按键暂停无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11242176/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com