我正在尝试制作一个打印“ hi”的程序,直到用户释放键为止。即使在释放密钥后,我当前的代码仍然可以运行。我很确定这是因为键盘侦听器在另一个线程上,但是我不知道如何在该线程上运行。
from pynput.mouse import Button, Controller
from pynput import keyboard
running = True
def on_release(key):
running = False
listener = keyboard.Listener(
on_release=on_release)
listener.start()
while running:
print("hi")
将其放在类中会产生相同的结果
class Clicker():
def __init__(self):
self.running = True
self.listener = keyboard.Listener(on_release=self.on_release)
self.listener.start()
def on_release(self):
self.running = False
print("Stopped")
def run(self):
while(self.running):
print("hi")
答案 0 :(得分:0)
由于running
被定义为全局变量,因此除非您使用on_release()
关键字,否则方法global
将无法对其进行修改。从官方文档中可以找到的最佳参考是here。
全局变量未已修改:
global_variable = 1
def change_global_variable_wrong():
global_variable = 2 # This statement declares a new local variable
# called `global_variable` and assigns the
# value `2` to it.
change_global_variable_wrong()
print(global_variable) # prints 1
全局变量 已修改:
global_variable = 1
def change_global_variable_correct():
global global_variable
global_variable = 2
change_global_variable_correct()
print(global_variable) # prints 2
代码所需的相关更改将遵循以下内容:
def on_release(key):
global running
running = False