问题描述
我试图在按下一个键时循环打印,并在按下另一个键时停止打印.
Im trying to loop a print when a key is pressed and stop when another key is pressed.
我也不想退出该程序,它必须继续侦听密钥.
Also I dont want to exit the program, it must continue listening for a key.
问题:但是我得到的是一个无限循环,因为当循环为True时,它无法监听另一个键!
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()
编辑
我确实解释了错误的一部分,我想在按下某个特定键 WAS 时进行循环.
I did explained wrong one part, I wanted to do a loop when a certain key WAS pressed.
推荐答案
您不能在 on_press
(或任何长期运行的函数)中运行/>因为它阻止了
Listener
.您必须在单独的 thread
中运行它.
You can't run
while True
(or any long-running function) inside on_press
because it blocks Listener
. You have to run it in separated thread
.
您需要
on_press
来创建和启动 thread
.
然后 on_release
停止 thread
.
它需要全局变量.IE.为此运行
.
You need
on_press
to create and start thread
.
And on_release
to stop thread
.
It needs global variable. ie. running
for this.
我仅使用
datetime
来查看它是否显示新行.
I use
datetime
only to see if it displays new line or not.
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()
这篇关于循环播放,直到按下键并重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!