为什么我的 bool 变量不会改变它的值

问题描述 投票:0回答:1

所以,我写的这段代码很难。它应该工作的方式是在

is_on
True
之间切换 bool
False
变量,当
is_on
True
时,它会继续打印一些文本。除了我第一次按下热键时它确实从
False
更改为
True
,但当我再次按下它时,它不会从
True
更改为
False

import time
from pynput import keyboard
from pynput.keyboard import Controller as controller

is_on = False
def for_canonical(input):
    return lambda key: input(listener.canonical(key))
def on_off(is_on):
    is_on = not is_on
    loop(is_on).start()
def loop(is_on):
    while is_on == True:
        print("some text")
        time.sleep(1)
        print("some text")
        time.sleep(1)
        print("some text")
        time.sleep(1)
        print("some text")
        time.sleep(1)
hotkey = keyboard.HotKey(keyboard.HotKey.parse("<alt>+n"), lambda: on_off(is_on).start())
listener = keyboard.Listener(
on_press=for_canonical(hotkey.press),
on_release=for_canonical(hotkey.release))
listener.start()

我花了很多时间重写代码,使用了很多不同的方法、运算符等,但我不知道为什么它不起作用。这是我写的最短、最干净的代码,我决定保留它。我真的需要一些帮助:(

python operator-keyword
1个回答
0
投票
  • 在 Python 中,
    funct
    参数按值传递,这意味着当您将
    is_on
    传递给
    on_off
    函数时,它会创建一个同名的
    new local
    变量。在函数内部修改此局部变量不会影响函数外部的
    original
    is_on
    变量。
  • 您可以在
    global
    函数中使用
    on_off
    关键字来指示您要修改
    global is_on variable
import time
from pynput import keyboard

is_on = False

def on_off():
    global is_on
    is_on = not is_on
    if is_on:
        loop()

def loop():
    while is_on:
        print("some text")
        time.sleep(1)

hotkey = keyboard.HotKey(keyboard.HotKey.parse("<alt>+n"), on_off)
listener = keyboard.Listener(on_press=hotkey.press, on_release=hotkey.release)
listener.start()

# Keep the program running
while True:
    pass

© www.soinside.com 2019 - 2024. All rights reserved.