画布中应该显示的图形没有出现
import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTk
import numpy as np
root = tk.Tk()
root.title("Graphique Matplotlib dans Tkinter")
root.geometry("750x500")
t = np.arange(0, 3, 0.01)
fig = plt.figure(figsize=(8, 8))
fig.add_subplot(111).plot(t, 2 * np.sin(2 * np.pi * t))
canvas = FigureCanvasTk(fig, master=root)
canvas.get_tk_widget().place(x=0,y=0)
button = tk.Button(root, text="Cliquez-moi !")
button.pack()
root.mainloop()
我在窗口中显示画布,一个按钮,但图形保持不可见,尽管当我编写 plt.show() 进行测试时它创建得很好。
我有这个,但无法更新工具栏,它不适用于单击按钮后创建的新图表
import random
import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
root = tk.Tk()
canvas = None
toolbar = None
def cplot():
global canvas, toolbar
if canvas:
plt.close()
canvas.get_tk_widget().pack_forget()
xCord = [random.randint(0, 10) for i in range(5)]
yCord = [random.randint(0, 10) for i in range(5)]
fig, ax = plt.subplots()
plt.plot(xCord, yCord)
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack()
if not toolbar:
toolbar = NavigationToolbar2Tk(canvas, root)
canvas.get_tk_widget().pack()
else:
toolbar.update()
bouton = tk.Button(root, text="Changer", command=cplot)
bouton.pack()
cplot()
root.mainloop()