我正在尝试制作一个计数器,所以如果我输入“再见”它会开始计算自我说再见已经过了多长时间但问题是我不能输入任何东西来阻止计数器而我不知道当你输入一些东西来阻止它时,如何让它告诉你。这是我的计数器代码,但我尝试输入一些东西并且它不会停止:
import time
s = 0
m = 0
h = 0
while s<=60:
print h, 'Hours', m, 'Minutes', s, 'Seconds'
time.sleep(1)
s+=1
if s == 60:
m+=1
s = 0
elif m ==60:
h+=1
m = 0
s = 0
答案 0 :(得分:1)
考虑使用threading.Thread
:
import time
import threading
class MyTimer(threading.Thread):
def __init__(self):
self.h = 0
self.m = 0
self.s = 0
def count(self, t, stop_event):
while self.s <= 60:
print self.h, 'Hours', self.m, 'Minutes', self.s, 'Seconds'
time.sleep(1)
self.s += 1
if self.s == 60:
self.m += 1
self.s = 0
elif self.m == 60:
self.h += 1
self.m = 0
self.s = 0
elif stop_event.is_set():
print self.h, 'Hours', self.m, 'Minutes', self.s, 'Seconds'
break
class Asking(threading.Thread):
def asking(self, t, stop_event):
while not stop_event.is_set():
word = raw_input('enter a word:\n')
if word == 'bye':
timer_stop.set()
question_stop.set()
timer = MyTimer()
question = Asking()
question_stop = threading.Event()
timer_stop = threading.Event()
threading.Thread(target=question.asking, args=(1, question_stop)).start()
threading.Thread(target=timer.count, args=(2, timer_stop)).start()
以运行方式为例:
$ python stackoverflow.py
enter a word:
0 Hours 0 Minutes 0 Seconds
0 Hours 0 Minutes 1 Seconds
0 Hours 0 Minutes 2 Seconds
0 Hours 0 Minutes 3 Seconds
hi
enter a word:
0 Hours 0 Minutes 4 Seconds
0 Hours 0 Minutes 5 Seconds
0 Hours 0 Minutes 6 Seconds
bye
0 Hours 0 Minutes 7 Seconds
代码可能更整洁:p。我震惊了自己,我能够产生这个:D。
答案 1 :(得分:0)
我知道的唯一方法是使用pygame。它会设置一个普通的pygame循环,除了它只是1乘1,所以你可以看到背景窗口,当你输入一个字母时它会退出pygame循环。
答案 2 :(得分:0)
也许更好......
.....
.....
while self.s <= 60:
print self.h, 'Hours', self.m, 'Minutes', self.s, 'Seconds'
time.sleep(1)
self.s += 1
if self.s == 60:
self.m += 1
self.s = 0
if self.m == 60:
self.h += 1
self.m = 0
elif stop_event.is_set():
print self.h, 'Hours', self.m, 'Minutes', self.s, 'Seconds'
break
......
......