首页 > 解决方案 > 中断 python 输入的问题 (Mac)

问题描述

我试图允许用户输入多个答案,但只能在分配的时间内。问题是我让它运行但程序不会中断输入。如果用户在时间结束后输入答案,程序只会停止用户输入。有任何想法吗?我想在 python 中做的甚至可能吗?

我尝试过使用线程和信号模块,但是它们都会导致相同的问题。

使用信号:

    import signal

    def handler(signum, frame):
        raise Exception

    def answer_loop():
        score = 0
        while True:
            answer = input("Please input your answer")

    signal.signal(signal.SIGALRM, handler)
    signal.alarm(5)
    try:
        answer_loop()
    except Exception:
        print("end")

    signal.alarm(0)

使用线程:

    from threading import Timer

    def end():
        print("Time is up")

    def answer_loop():
        score = 0
        while True:
            answer = input("Please input your answer")

    time_limit =  5
    t = Timer(time_limit, end)
    t.start()
    answer_loop()
    t.cancel()

标签: macospython-multithreadingpython-3.7

解决方案


您的问题是内置input没有超时参数,并且,AFAIK,线程不能被其他线程终止。我建议您使用带有事件的 GUI 来精细控制用户交互。这是一个简单的 tkinter 示例。

import tkinter as tk

root = tk.Tk()
label = tk.Label(root, text='answer')
entry = tk.Entry(root)
label.pack()
entry.pack()

def timesup():
    ans = entry.get()
    entry.destroy()
    label['text'] = f"Time is up.  You answered {ans}"

root.after(5000, timesup)

root.mainloop()


推荐阅读