我在 tkinter 中使用 matplotlib。我想將 matplotlib 狀態作為函式更新為新狀態,我該如何解決?
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
window = tk.Tk()
def change():
ss = np.random.randint(100)
ss1 = np.random.randint(100)
ss2 = np.random.randint(100)
x = ['Col A', 'Col B', 'Col C']
y = [ss,ss1,ss2]
fig = plt.figure(figsize=(4, 5))
plt.bar(x=x, height=y)
plt.xticks(x, rotation=90)
canvas = FigureCanvasTkAgg(fig, master=window)
canvas.draw()
btn = tk.Label(window, text='A simple plot')
btn.grid(row=0, column=0, padx=20, pady=10)
x = ['Col A', 'Col B', 'Col C']
y = [50, 20, 80]
fig = plt.figure(figsize=(4, 5))
plt.bar(x=x, height=y)
plt.xticks(x, rotation=90)
canvas = FigureCanvasTkAgg(fig, master=window)
canvas.draw()
canvas.get_tk_widget().grid(row=1, column=0, ipadx=40, ipady=20)
toolbarFrame = tk.Frame(master=window)
toolbarFrame.grid(row=2,column=0)
toolbar = NavigationToolbar2Tk(canvas, toolbarFrame)
button = tk.Button(text='change',command = change)
button.grid(row= 3,column =0)
window.mainloop()
output 執行這段代碼時,當按鈕被按下時,圖形螢屏不發生變化,當程式結束時,圖形被執行。
uj5u.com熱心網友回復:
您不需要創建新圖形,只需更新當前圖形:
def change():
ss = np.random.randint(100)
ss1 = np.random.randint(100)
ss2 = np.random.randint(100)
x = ['Col A', 'Col B', 'Col C']
y = [ss,ss1,ss2]
plt.clf() # clear current figure
plt.bar(x=x, height=y) # plot the graph
plt.xticks(x, rotation=90)
canvas.draw() # refresh plot
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/374591.html
標籤:Python matplotlib 特金特 阴谋 传统知识
上一篇:防止餅圖中的標簽重疊PythonMatplotlib
下一篇:用改變的軸繪制FITS影像
