Python脚本:如何实现按F3启动持续按Enter,再按F3停止?
Toggle Enter Spamming with F3 (Start/Stop)
Hey there! I see you're looking to turn your one-time Enter press into a toggleable feature—press F3 to start spamming Enter, press it again to stop. Let's adjust your script to make that happen.
The core issue with your original code is that it only triggers the Enter press once per F3 press, since it's checking for the key being held in each loop iteration. We need a way to track a "running state" and flip that state with each F3 press. Here's the modified script:
import time import keyboard # Track whether we're actively spamming Enter is_spamming = False def toggle_spamming(): global is_spamming # Flip the state: start if stopped, stop if running is_spamming = not is_spamming print("Enter spamming started!" if is_spamming else "Enter spamming stopped!") # Register F3 as our toggle hotkey keyboard.add_hotkey('F3', toggle_spamming) print("Press F3 to start/stop Enter spamming. Press Ctrl+C to exit.") try: while True: if is_spamming: keyboard.press('enter') # Adjust this delay to control how fast Enter is pressed (lower = faster) time.sleep(0.1) # Tiny delay when not spamming to avoid eating too much CPU time.sleep(0.01) except KeyboardInterrupt: print("\nScript exited successfully.")
Quick breakdown of the changes:
- State Variable:
is_spammingacts as a switch—starts offFalse(not spamming), and flips every time F3 is pressed. - Toggle Function:
toggle_spamming()handles flipping the state and gives you a confirmation message so you know what's happening. - Hotkey Registration:
keyboard.add_hotkeylets us listen for F3 presses without having to constantly check the key state in the main loop. - Controlled Spamming: The
time.sleep(0.1)inside the spamming block prevents the script from sending Enter presses too quickly (you can tweak this value to make it faster or slower).
This setup keeps the script responsive—press F3 once to start the Enter spam, press it again to halt it immediately.
内容的提问来源于stack exchange,提问作者Equinox
相关产品推荐
相关产品推荐

