如何使用 Matplotlib 提供的 FigureCanvasTkAgg 类将整个绘图对象嵌入到 Tkinter GUI 中。
时间: 2024-03-17 18:41:24 浏览: 461
使用 `FigureCanvasTkAgg` 类将整个 Matplotlib 绘图对象嵌入到 Tkinter GUI 中,可以按照以下步骤进行:
1. 导入 Matplotlib 和 Tkinter 库:
```python
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
```
2. 创建 Matplotlib 绘图对象:
```python
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
```
3. 创建 Tkinter 窗口和画布:
```python
root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=300)
canvas.pack()
```
4. 将 Matplotlib 绘图对象嵌入到 Tkinter 画布中:
```python
canvas_widget = FigureCanvasTkAgg(fig, canvas)
canvas_widget.draw()
canvas_widget.get_tk_widget().pack()
```
5. 运行 Tkinter 主循环:
```python
root.mainloop()
```
完整代码示例:
```python
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
# 创建 Matplotlib 绘图对象
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
# 创建 Tkinter 窗口和画布
root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=300)
canvas.pack()
# 将 Matplotlib 绘图对象嵌入到 Tkinter 画布中
canvas_widget = FigureCanvasTkAgg(fig, canvas)
canvas_widget.draw()
canvas_widget.get_tk_widget().pack()
# 运行 Tkinter 主循环
root.mainloop()
```
这样就可以将整个 Matplotlib 绘图对象嵌入到 Tkinter GUI 中了。
阅读全文