【问题标题】:How Do I Loop An Input In Python?如何在 Python 中循环输入?
【发布时间】:2015-08-26 15:02:48
【问题描述】:

我一直在搜索和搜索如何弄清楚如何使输入或某些内容进入 while 循环。如, input() 命令不会停止我的秒表。我尝试过 tkinter、pygame 和其他几种方法,但它们都不起作用。如果有人可以帮助我,如果可能的话,我更喜欢小而简单的东西。具体来说,我想学习做什么,基本上是允许,当按下任何键时,它会立即停止(最好不按回车键)。谢谢,马鞍猪!

这是我目前所拥有的,没有任何东西可以激活停止:

    #Setup (Variables and stuff)
        hours = 0
        minutes = 0
        seconds = 0
        import time



    #Main Part of Code
    print("Welcome to PyWatch, a stopwatch coded in Python!")
    print("Press any key to start the stopwatch.")
    print("Then, press any key to stop it!")
    start = input("")

    while hours < 48:
        seconds = seconds + 1
        time.sleep(1)
        print(hours, "hours,", minutes, "minutes,", seconds, "seconds")



    #If Statements for getting seconds/minutes/hours
    if (seconds == 60):
        minutes = minutes + 1
        seconds = seconds - 60

    if (minutes == 60):
        hours =hours + 1
        minutes = minutes - 60

【问题讨论】:

标签: python loops input


【解决方案1】:

线程是你想要的。

创建第二个线程等待输入,而您的第一个线程处理您的秒表代码。看:

 import threading, sys

 def halt():
     raw_input()

 threading.Thread(target=halt).start()


 while hours < 48 and threading.active_count() > 1:
     seconds = seconds + 1
     time.sleep(1)

     # copy and past what you had before

请允许我详细说明发生了什么:到目前为止,您编写的所有代码都是单线程的。这意味着一次只执行一行代码,只有一个执行线程。因此,您的脚本不能进行多任务处理,它不能同时等待输入和打印时间。

所以当这条线被评估时

threading.Thread(target=halt).start()

主线程创建第二个执行线程。同时,主线程继续运行并进入while循环。目标参数是线程的入口点,它是起点。它类似于主线程的if __name__ == "__main__:"。就像主线程在到达if __name__ == "__main__:" 的末尾时终止一样,我们的第二个线程将在到达halt() 的末尾时终止。

threading.active_count 函数告诉您当前有多少线程正在执行中。

【讨论】:

  • 我仍然对它的去向以及线程的具体操作有点困惑,因为我刚刚学习 Python。另外,如果您不介意,您能否向我解释一下代码的哪一部分在做什么(出于学习目的)?谢谢,马鞍猪!
  • 我不确定线程​​对于那些努力理解编程基础的人来说是一个好的答案。线程是一个有点高级的话题。
【解决方案2】:

你不能在 Python 中做到这一点。您正在请求键盘事件。键盘事件随 GUI 一起提供。这个帖子几乎解释了一切:QKeyPress event in PyQt

或者为您的操作系统使用一个外部应用程序,该应用程序可以将输出附加到您的 Python 程序循环读取的文件中。当检测到某个事件时,您可以执行一些操作。对于 Linux,此步骤说明:https://superuser.com/questions/248517/show-keys-pressed-in-linux

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多