# 如何在 PyCharm 中正确安装和配置 Python 环境(零基础详细教程)
你问的“没有找到 Python interpreter”是非常常见的新手问题,下面我会一步步带你完成 **环境安装 → PyCharm 配置 → 项目运行** 的全过程。
---
## 🌟 第一步:下载并安装 Python
### ✅ 1. 下载 Python 官方安装包
打开浏览器,访问:
> [https://www.python.org/downloads/](https://www.python.org/downloads/)
点击大按钮:**Download Python 3.x.x**(推荐版本:`3.9` 或 `3.10`)
📌 提示:下载时会自动识别你的系统(Windows / macOS)
---
### ✅ 2. 安装 Python(以 Windows 为例)
双击下载好的 `.exe` 文件,注意勾选:
> ✅ **Add Python to PATH**
然后点击 “Install Now”
等待安装完成 ✔️
---
## 🌟 第二步:下载并安装 PyCharm
### ✅ 1. 下载 PyCharm Community(免费版)
访问官网:
> [https://www.jetbrains.com/pycharm/download/](https://www.jetbrains.com/pycharm/download/)
选择:
- **Community(社区版)** ← 免费!适合学生使用
- 操作系统对应版本(Windows / macOS)
---
### ✅ 2. 安装 PyCharm
双击安装包,一路“下一步”,默认设置即可。
安装完成后启动 PyCharm。
---
## 🌟 第三步:创建新项目,并设置 Python 解释器
### ✅ 1. 打开 PyCharm 后 → 点击 "New Project"
你会看到一个界面,其中有几个关键选项:
| 项目 | 建议设置 |
|------|--------|
| Location | 自定义路径,如 `C:\my_projects\CBS_Animation` |
| Interpreter | 点击右边小图标,选择系统已安装的 Python |
---
### ✅ 2. 设置 Python Interpreter(重点!)
#### 🔹 如果你是第一次用:
- PyCharm 可能提示:“No interpreter configured”
- 别担心,我们手动添加!
👉 点击下拉菜单旁的小齿轮 ⚙️ → 选择 **Add...**
弹出窗口中选择:
> **System Interpreter**
然后浏览到你刚才安装的 Python 路径,通常是:
```
C:\Users\你的用户名\AppData\Local\Programs\Python\Python39\python.exe
```
✅ 找到后点击 OK。
📌 成功标志:PyCharm 显示类似
> `Python 3.9 (python.exe)`
这就说明解释器配置成功了!
---
## 🌟 第四步:创建项目文件并粘贴代码
### ✅ 1. 创建文件夹结构
在 PyCharm 左侧项目栏中右键点击项目名 → New → Directory
- 名字输入:`utils`
然后再右键 `utils` → New → Python File
- 名字输入:`path_planning`
再在主目录新建一个文件:
- 名字输入:`main`
最终结构:
```
CBS_Animation_Project/
├── main.py
└── utils/
└── path_planning.py
```
---
### ✅ 2. 把我给的代码复制进去
#### ➤ 打开 `utils/path_planning.py`,粘贴以下内容:
```python
from typing import List, Tuple
Point = Tuple[int, int]
def a_star(start: Point, goal: Point, grid_size: int) -> List[Point]:
def heuristic(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
open_set = [(0, start)]
came_from = {}
g_score = {start: 0}
import heapq
while open_set:
_, current = heapq.heappop(open_set)
if current == goal:
path = []
while current in came_from:
path.append(current)
current = came_from[current]
path.append(start)
return path[::-1]
x, y = current
neighbors = [(x+dx, y+dy) for dx, dy in [(0,1),(1,0),(0,-1),(-1,0)]]
for nx, ny in neighbors:
if 0 <= nx < grid_size and 0 <= ny < grid_size:
neighbor = (nx, ny)
tentative_g = g_score[current] + 1
if neighbor not in g_score or tentative_g < g_score[neighbor]:
came_from[neighbor] = current
g_score[neighbor] = tentative_g
f_score = tentative_g + heuristic(neighbor, goal)
heapq.heappush(open_set, (f_score, neighbor))
return []
def cbs_single_conflict(path1: List[Point], path2: List[Point]) -> Tuple[List[Point], List[Point]]:
min_len = min(len(path1), len(path2))
for t in range(min_len):
if path1[t] == path2[t]:
return path1, path2[:t] + [path2[t]] + path2[t:]
return path1, path2
def smooth_path(path: List[Point], num_points: int = 50) -> tuple:
import numpy as np
from scipy.interpolate import splev, splprep
if len(path) < 2:
return np.array([path[0][0]]), np.array([path[0][1]])
x = np.array([p[0] for p in path])
y = np.array([p[1] for p in path])
k = min(3, len(path) - 1)
tck, u = splprep([x, y], s=0, k=k)
u_new = np.linspace(0, 1, num_points)
sx, sy = splev(u_new, tck)
return sx, sy
```
#### ➤ 打开 `main.py`,粘贴以下内容:
```python
import matplotlib
matplotlib.use('TkAgg') # 防止图形不显示
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from utils.path_planning import a_star, cbs_single_conflict, smooth_path
GRID_SIZE = 5
# 起点与终点
start1, goal1 = (0, 0), (4, 4)
start2, goal2 = (4, 0), (0, 4)
# 规划路径
path1_raw = a_star(start1, goal1, GRID_SIZE)
path2_raw = a_star(start2, goal2, GRID_SIZE)
path1_cbs, path2_cbs = cbs_single_conflict(path1_raw, path2_raw)
sx1, sy1 = smooth_path(path1_cbs)
sx2, sy2 = smooth_path(path2_cbs)
# 动画绘制
fig, axes = plt.subplots(1, 3, figsize=(18, 6))
titles = ['Raw Paths (Collision)', 'CBS Paths', 'CBS + Smooth']
for ax in axes:
ax.set_xlim(-0.5, GRID_SIZE - 0.5)
ax.set_ylim(-0.5, GRID_SIZE - 0.5)
ax.grid(True)
ax.set_xticks(np.arange(GRID_SIZE))
ax.set_yticks(np.arange(GRID_SIZE))
ax.set_aspect('equal')
def animate(frame):
for ax in axes:
while ax.lines:
ax.lines.pop()
while ax.collections:
ax.collections.pop()
paths_data = [
(path1_raw, path2_raw, False),
(path1_cbs, path2_cbs, False),
((sx1, sy1, len(path1_cbs)), (sx2, sy2, len(path2_cbs)), True)
]
colors = ['blue', 'red']
for ax, (paths, is_smooth) in zip(axes, paths_data):
for idx, p in enumerate(paths):
if not is_smooth:
path = p
if frame < len(path):
x, y = path[frame]
ax.plot(x, y, 'o', color=colors[idx], markersize=10)
sub_path = path[:frame+1]
ax.plot([p[0] for p in sub_path], [p[1] for p in sub_path],
'-', color=colors[idx], alpha=0.7)
else:
sx, sy, raw_len = p
ratio = min(frame / raw_len, 1.0) if raw_len > 0 else 0
cur_idx = int(ratio * len(sx))
if cur_idx >= len(sx): cur_idx = -1
ax.plot(sx[cur_idx], sy[cur_idx], 'o', color=colors[idx], markersize=10)
ax.plot(sx[:cur_idx+1], sy[:cur_idx+1], '-', color=colors[idx], alpha=0.7)
fig.suptitle(f"Time Step: {frame}", fontsize=16)
return []
ani = FuncAnimation(fig, animate, frames=range(15),
interval=600, repeat=True, blit=False)
plt.tight_layout()
plt.show()
```
---
## 🌟 第五步:安装依赖库(非常重要!)
### ✅ 在 PyCharm 底部打开 Terminal(终端)
输入命令:
```bash
pip install numpy matplotlib scipy
```
按回车执行。
📌 等待安装完成(出现 `Successfully installed ...` 就好了)
---
## 🌟 第六步:运行程序!
右键点击 `main.py` → 选择 **Run 'main'**
🎉 如果一切顺利,几秒后会弹出一个包含三幅图的窗口,动画开始播放!
---
## ❗常见问题解决
| 问题 | 解决方法 |
|------|----------|
| `ModuleNotFoundError` | 检查是否运行了 `pip install numpy matplotlib scipy` |
| 图形一闪而逝 | 确保不是在控制台直接粘贴运行,要用右键 Run |
| 提示 No Python Interpreter | 回到第三步,重新检查 Python 是否安装并被正确识别 |
---
## ✅ 总结:只需做这 6 步
1. ✅ 安装 Python(勾选 Add to PATH)
2. ✅ 安装 PyCharm(Community 版)
3. ✅ 创建项目并设置 Interpreter(指向 python.exe)
4. ✅ 创建 `main.py` 和 `utils/path_planning.py`
5. ✅ 在 Terminal 输入:`pip install numpy matplotlib scipy`
6. ✅ 右键运行 `main.py` → 看动画!
---
如果你按照这个流程操作还有问题,请告诉我:
- 你用的是什么电脑系统?(Windows / Mac)
- PyCharm 启动后看到什么画面?
- Terminal 输入 `python --version` 出现什么?
我可以继续帮你远程排查 💪