循环直到按下键并重复

loop until key is pressed and repeat

我正在尝试在按下一个键时循环打印并在按下另一个键时停止。

我也不想退出程序,它必须继续监听一个键。

问题:但是我得到的是一个无限循环,因为当循环为真时它无法收听另一个键!

from pynput import keyboard
    
def on_press(key):
    if key == keyboard.Key.f9:
        while True:
            print("loading")
    if key == keyboard.Key.f10:
        # Stop listener
        return False

# Collect events until released
with keyboard.Listener(on_press=on_press) as listener:
    listener.join()

Im using pynput, docs here

编辑

我确实解释错了一部分,我想在某个键WAS按下时循环。

你不能在 on_press
中 运行 while True (或任何 long-运行ning 函数) 因为它会阻塞 Listener。你必须 运行 它分开 thread.

您需要 on_press 来创建和启动 thread
并且 on_release 停止 thread.
它需要全局变量。 IE。 running为此。

我用datetime只是为了看是否显示换行。

from pynput import keyboard
import threading
import datetime

# --- functions ---

def loading():
    while running:
         print("loading", datetime.datetime.now()) #, end='\r')
    
def on_press(key):
    global running  # inform function to assign (`=`) to external/global `running` instead of creating local `running`

    if key == keyboard.Key.f9:
        running = True
        # create thread with function `loading`
        t = threading.Thread(target=loading)
        # start thread
        t.start()
        
    if key == keyboard.Key.f10:
        # stop listener
        return False

def on_release(key):
    global running  # inform function to assign (`=`) to external/global `running` instead of creating local `running`
    
    if key == keyboard.Key.f9:
        # to stop loop in thread
        running = False
        
#--- main ---

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

按下按键时的解决方案。 based on @furas code

from pynput import keyboard
import threading
import datetime, time

# --- functions ---

def loading():
    while running:
        print("loading", datetime.datetime.now()) #, end='\r')
        time.sleep(1)
    
def on_press(key):
    global running  # inform function to assign (`=`) to external/global `running` instead of creating local `running`

    if key == keyboard.Key.f9:
        running = True
        # create thread with function `loading`
        t = threading.Thread(target=loading)
        # start thread
        t.start()
        
    if key == keyboard.Key.f10:
        # to stop loop in thread
        running = False

    if key == keyboard.Key.f11:
        # stop listener
        return False
        
#--- main ---

with keyboard.Listener(on_press=on_press) as listener:
    listener.join()