0

我正在尝试制作一个计数器,所以如果我输入“再见”,它就会开始计算自从我说再见以来已经过了多长时间,但问题是我无法输入任何内容来停止计数器,我不知道如何拥有当你输入一些东西来阻止它时,它会告诉你一些东西。这是我的计数器代码,但我尝试输入一些内容,但它并没有停止:

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
4

3 回答 3

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。

于 2013-06-29T02:52:06.860 回答
0

我知道的唯一方法是使用 pygame。它会设置一个正常的 pygame 循环,除了它只有 1 x 1,所以你可以看到背景窗口,当你输入一个字母时,它会退出 pygame 循环。

于 2013-06-29T15:53:17.903 回答
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
        ......
        ......
于 2014-02-06T16:47:18.263 回答