我真的不知道这个问题怎么说,但我希望“h”或“j”或“k”输入显示它们各自的值
from pynput.keyboard import Key, Controller
import time
import random
keyboard = Controller()
wasd = ["w","a","s","d","j","h","k"]
for x in range(1,11):
if wasd[random.randint(0,6)] == "w":
keyboard.press("w")
time.sleep(0.5)
keyboard.release("w")
elif wasd[random.randint(0,6)] == "a":
keyboard.press("a")
time.sleep(1)
keyboard.release("a")
elif wasd[random.randint(0,6)] == "s":
keyboard.press("s")
time.sleep(0.1)
keyboard.release("s")
elif wasd[random.randint(0,6)] == "d":
keyboard.press("d")
time.sleep(1)
keyboard.release("d")
elif wasd[random.randint(0,6)] == "h" or "j" or "k":
keyboard.press("h" or "j" or "k")
time.sleep(0.03)
keyboard.release("h" or "j" or "k")
这是代码,这是输出:shdhswhhhh
所以只要它是 h、j 或 k,它只输入 h
在您提供的代码中,以下一行是不正确的:
elif wasd[random.randint(0,6)] == "h" or "j" or "k":
这行代码始终为 True,因为“j”和“k”是非空字符串,在 Python 中被认为是 True
。因此,这种情况下的代码块每次都会执行,并且总是输入“h”。
要解决此问题,您可以将行更改为:
elif wasd[random.randint(0,6)] in ["h", "j", "k"]:
此代码将检查随机元素是否来自 wasd
。如果是,则执行此条件下的代码块,并键入相应的字符。
另外,keyboard.press("h" or "j" or "k") will always press "h"
.
所以你可以把它改成
keyboard.press(random.choice(["h", "j", "k"]))