【问题标题】:How to check if key is pressed while other code is running如何在其他代码运行时检查是否按下了键
【发布时间】:2022-07-15 18:11:54
【问题描述】:

在下面的代码中,退出循环的唯一方法是按住 q 并在最后一个输入上按 enter。但是有没有办法在任何其他代码运行时检查是否按下了某个键?

import keyboard, time
while True:
   if keyboard.is_pressed('q'):
      break
   str1 = input('Type your first name: ')
   time.sleep(5)
   str2 = input('Type your last name: ')

【问题讨论】:

  • 为什么不检查str1"q"然后是break
  • @DSteman 这只是一些随机的模板代码来显示正在发生的事情。我想要其他有意义的代码,但是如果用户想退出,他们可以随时按住 q。
  • 不是和ctrl+c一样吗?您只需要另一个密钥
  • @DSteman 是也不是。我不想让它完全退出代码,我只想结束while循环。

标签: python


【解决方案1】:

我想你想要这样的东西:

import keyboard, time
from threading import Thread

def execute_questions():
    while True:
        str1 = input('Type your first name: ')
        str2 = input('Type your last name: ')



t =Thread(target=execute_questions)
t.daemon = True 
t.start()

while True:
    if keyboard.is_pressed('q'):
        #stops the thread
        print('\nprogram finish')
        break

【讨论】:

    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    • 2014-08-31
    • 2012-11-12
    • 1970-01-01
    • 2015-04-22
    相关资源
    最近更新 更多