Python matplotlib如何在一个窗口画多张图,界面一次只显示一张图,但可以使用forward to next view按钮切换
时间: 2024-05-05 10:15:05 浏览: 244
可以使用matplotlib的Figure和Subplot来实现在一个窗口画多张图,并使用NavigationToolbar2TkAgg类中的“forward”和“backward”按钮来切换视图。具体实现步骤如下:
1. 导入matplotlib和Tkinter库
```python
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2TkAgg)
import tkinter as tk
from tkinter import ttk
```
2. 创建Tkinter窗口和matplotlib Figure对象
```python
root = tk.Tk()
root.wm_title("多图窗口")
fig = plt.Figure(figsize=(5, 4), dpi=100)
```
3. 创建Subplot对象,并绘制图形
```python
ax1 = fig.add_subplot(221)
ax1.plot([1, 2, 3], [2, 4, 6])
ax1.set_title("图1")
ax2 = fig.add_subplot(222)
ax2.plot([1, 2, 3], [3, 6, 9])
ax2.set_title("图2")
ax3 = fig.add_subplot(223)
ax3.plot([1, 2, 3], [4, 8, 12])
ax3.set_title("图3")
ax4 = fig.add_subplot(224)
ax4.plot([1, 2, 3], [5, 10, 15])
ax4.set_title("图4")
```
4. 创建FigureCanvasTkAgg对象,并将其添加到Tkinter窗口中
```python
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
```
5. 创建NavigationToolbar2TkAgg对象,并将其添加到Tkinter窗口中
```python
toolbar = NavigationToolbar2TkAgg(canvas, root)
toolbar.update()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
```
6. 创建切换视图的按钮,并绑定到NavigationToolbar2TkAgg对象的“forward”和“backward”方法上
```python
def forward():
toolbar.forward()
def backward():
toolbar.back()
button_forward = ttk.Button(root, text="Forward", command=forward)
button_forward.pack(side=tk.LEFT)
button_backward = ttk.Button(root, text="Backward", command=backward)
button_backward.pack(side=tk.LEFT)
```
7. 运行Tkinter mainloop()方法,显示窗口和图形
```python
tk.mainloop()
```
完整代码如下:
```python
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2TkAgg)
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.wm_title("多图窗口")
fig = plt.Figure(figsize=(5, 4), dpi=100)
ax1 = fig.add_subplot(221)
ax1.plot([1, 2, 3], [2, 4, 6])
ax1.set_title("图1")
ax2 = fig.add_subplot(222)
ax2.plot([1, 2, 3], [3, 6, 9])
ax2.set_title("图2")
ax3 = fig.add_subplot(223)
ax3.plot([1, 2, 3], [4, 8, 12])
ax3.set_title("图3")
ax4 = fig.add_subplot(224)
ax4.plot([1, 2, 3], [5, 10, 15])
ax4.set_title("图4")
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
toolbar = NavigationToolbar2TkAgg(canvas, root)
toolbar.update()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
def forward():
toolbar.forward()
def backward():
toolbar.back()
button_forward = ttk.Button(root, text="Forward", command=forward)
button_forward.pack(side=tk.LEFT)
button_backward = ttk.Button(root, text="Backward", command=backward)
button_backward.pack(side=tk.LEFT)
tk.mainloop()
```
阅读全文