我怎样才能让按键第一次做一件事,第二次做不同的事情?

How can I have a keypress do one thing the first time, and a different thing the second time?

所以我将这个脚本放在一起,它允许我在按下 "w" 键时发送 osc(打开声音控制)消息。 (我需要这个 运行 在我的电脑后台,所以任何关于如何提高它效率的建议都将不胜感激!:D)

我遇到的问题是,我希望它在我第二次点击 "w" 时发送不同的消息。 (这就是 client.send_message 出现的地方。)你会看到我开始写这个,但无济于事大声笑。

简而言之,当我第一次点击 "w" 时,它运行良好。 (执行 client.send_message("/TABS", "Mixer"))。现在,当我第二次点击它时,我希望它执行 client.send_message("/TABS", "Instruments") 我该怎么做呢?

代码:

import argparse
import pynput

from pythonosc import udp_client
from pynput.keyboard import Key, Listener
from pynput import keyboard
import keyboard

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--ip", default="192.168.1.140",
        help="The ip of the OSC server")
    parser.add_argument("--port", type=int, default=8420,
        help="The port the OSC server is listening on")
    args = parser.parse_args()

    client = udp_client.SimpleUDPClient(args.ip, args.port)

    def on_press(key):
        if keyboard.is_pressed('w'):
            client.send_message("/TABS", "Mixer")
        else:
            client.send_message("/TABS", "Instruments")


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

既然你想来回循环这两个操作,你可以使用itertools.cycle来完成。

首先,您需要定义两个小函数来执行您的两个操作。在这种情况下,我发送 client 作为函数的参数。

def do_mixer(client_arg):
    client_arg.send_message("/TABS", "Mixer")

def do_instruments(client_arg):
    client_arg.send_message("/TABS", "Instruments")

然后,您可以创建一个 cycle 对象以在每次按下 "w":

时在两个函数之间无限切换
import argparse
import pynput

from pythonosc import udp_client
from pynput.keyboard import Key, Listener
from pynput import keyboard
import keyboard

# Additional import
from itertools import cycle

# New funcs
def do_mixer(client_arg):
    client_arg.send_message("/TABS", "Mixer")

def do_instruments(client_arg):
    client_arg.send_message("/TABS", "Instruments")

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--ip", default="192.168.1.140",
        help="The ip of the OSC server")
    parser.add_argument("--port", type=int, default=8420,
        help="The port the OSC server is listening on")
    args = parser.parse_args()

    client = udp_client.SimpleUDPClient(args.ip, args.port)

    # Function cycler
    func_cycler = cycle((do_mixer, do_instruments))

    def on_press(key):
        if keyboard.is_pressed('w'):
            # With each press of "w", call the function that is next in line
            # The cycle object will iterate the collection given to it infinitely
            # In this case, it will be: do_mixer, do_instruments, do_mixer, ...
            next(func_cycler)(client)

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