Pygame安装异常求助:命令行可用但PyCharm无法导入
Hey there, let's work through this Pygame issue step by step—sounds like a classic environment mismatch problem, which is super common when switching between command line and IDEs like PyCharm. Here's how to sort it out:
1. Fix the PyCharm Module Not Found Error
The root cause here is that the Python interpreter PyCharm is using for your project doesn't have Pygame installed, while the one your command line uses (py) does. Let's align them:
First, confirm which Python version your command line is using:
Open Command Prompt and run:py --versionNote down the version number (e.g.,
Python 3.10.12).Next, switch PyCharm's project interpreter to match this version:
- Open PyCharm, go to
File > Settings(orFile > Preferenceson Mac). - Navigate to
Project: [Your Project Name] > Python Interpreter. - Click the gear icon in the top-right corner, select
Add. - Choose
System Interpreter, then find the Python executable that matches the version you noted earlier. On Windows, this is usually in a path likeC:\Users\YourUsername\AppData\Local\Programs\Python\Python310\python.exe. - Click
OKto set this as your project's interpreter.
- Open PyCharm, go to
Test it out:
Create a new Python file in your PyCharm project with this code:import pygame print(pygame.__version__) pygame.init() pygame.display.set_mode((400, 300)) pygame.quit()Run the file—if it prints the Pygame version without errors, you're good to go!
2. Fix the Desktop Lib/Include Folders Issue
Those folders on your desktop mean Pygame was installed to the wrong location (likely because you used a --target flag in your pip command or selected the desktop as the install path by accident). Here's how to clean this up:
- Delete the
LibandIncludefolders from your desktop (double-check they're only Pygame-related first—if you're unsure, you can skip this step and just reinstall correctly). - Reinstall Pygame to the correct location using Command Prompt:
This will install Pygame directly into thepy -m pip install pygame --upgradesite-packagesdirectory of the Python interpreter yourpycommand uses, which is where PyCharm will look once you've switched the interpreter.
Extra Troubleshooting Tip
If you're still having issues, run this command in Command Prompt to confirm where Pygame is installed:
py -m pip show pygame
Look for the Location field—this is the path to Pygame's installation directory. In PyCharm's interpreter settings, you can check that this path is listed under the interpreter's Packages tab (search for pygame to verify it's present).
内容的提问来源于stack exchange,提问作者Michael Sibille

