首页 > 解决方案 > 如何在 tkinter 画布的某些区域嵌入 matplotlib 图?

问题描述

您好,我正在尝试将 matplotlib 图嵌入到画布的特定区域,并且在尝试使工具栏正常工作时遇到了一些问题。这是我到目前为止所拥有的:

import matplotlib
import matplotlib.pyplot as plt
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
import tkinter as tk

def on_closing():
    root.quit()
    root.destroy()

root = tk.Tk()
root.protocol("WM_DELETE_WINDOW", on_closing)

canvas = tk.Canvas(root, width = 500, height=400, highlightthickness=0)
canvas.pack()
# create Frame
x0, y0, x1, y1 = (10, 10, 490, 390)
frame = tk.Frame(canvas, width=x1-x0, height=y1-y0)
window = canvas.create_window(x0, y0, anchor="nw",
window=frame, width=x1-x0, height=y1-y0)
# Create matplotlib graph
figure, ax = plt.subplots()
ax.plot([1,2,3,4,5,6,7,8],[5,6,1,3,8,9,3,5])
ax.set(xlabel='something', ylabel='something',
       title='something')
ax.grid()

canvas_matplotlib = FigureCanvasTkAgg(figure, frame)
canvas_matplotlib.draw()
canvas_matplotlib.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

toolbar = NavigationToolbar2Tk(canvas_matplotlib, frame)
toolbar.update()
canvas_matplotlib._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
root.mainloop()

我不明白为什么工具栏不会出现。

编辑:

我想要的是绘图和工具栏完全占据定义的画布区域。

标签: pythonmatplotlibtkintercanvas

解决方案


推荐阅读