如何实现按下并释放空格键时自动截图并按序保存?
Fixing Your Auto-Screenshot Script with Spacebar Trigger
Hey there! Since you're new to Python (welcome aboard!), let's walk through fixing your screenshot script to meet your needs—no more overwriting files, and proper spacebar-triggered captures when you release the key.
First, let's spot the issues in your original code:
- You’re using
keyboard.add_hotkey()but haven’t linked it to an actual screenshot function (right now it does nothing when you press space) - Your save path uses a single backslash
\, which Python interprets as an escape character (this will cause errors) - You’re saving every screenshot to the same
image.jpgfile, so each new capture overwrites the last one
Here’s the corrected, fully working script:
First, make sure you have the required libraries installed. Open your terminal and run:
pip install pillow keyboard
Then use this code:
import os from PIL import ImageGrab import keyboard # Initialize a counter to track screenshot numbers screenshot_counter = 1 # Define your save folder (use raw string to avoid escape character issues) save_folder = r"C:\Users\robbie\Desktop\prints" # Create the folder if it doesn't exist (prevents save errors) os.makedirs(save_folder, exist_ok=True) def take_and_save_screenshot(): global screenshot_counter # Capture the entire screen ss = ImageGrab.grab() # Create a unique filename with the counter save_path = os.path.join(save_folder, f"Image{screenshot_counter}.jpg") # Save the screenshot ss.save(save_path) # Print a confirmation (optional, helps you know it worked) print(f"Saved screenshot to {save_path}") # Increment the counter for the next screenshot screenshot_counter += 1 # Bind the spacebar to trigger the function WHEN YOU RELEASE THE KEY keyboard.add_hotkey('space', take_and_save_screenshot, trigger_on_release=True) # Keep the program running so it listens for the spacebar print("Ready to take screenshots! Press spacebar to capture, press Ctrl+C to exit.") keyboard.wait()
Let’s break down what this does:
- Raw string path: The
rbefore the folder path tells Python to treat backslashes as literal characters, so no more escape errors. - Folder creation:
os.makedirs(..., exist_ok=True)makes sure your save folder exists—if it doesn’t, it creates it automatically. - Unique filenames: We use a global counter that increments every time you take a screenshot, so you get
Image1.jpg,Image2.jpg, etc., no overwrites. - Release-triggered capture: The
trigger_on_release=Trueparameter makes the script run when you let go of the spacebar, just like you wanted. - Persistent listening:
keyboard.wait()keeps the program running until you press Ctrl+C to stop it.
Just run this script, and every time you press and release the spacebar, it’ll save a new numbered screenshot to your specified folder. Enjoy!
内容的提问来源于stack exchange,提问作者rimenta
相关产品推荐
相关产品推荐

