【问题标题】:Python tkinter on matplotlib How update?python tkinter on matplotlib 如何更新?
【发布时间】:2022-01-08 16:31:45
【问题描述】:

我在 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()

输出 执行此代码时,按下按钮时,图形画面不变,程序结束时,图形被执行。

【问题讨论】:

    标签: python matplotlib tkinter plot tk


    【解决方案1】:

    您不需要创建新图形,只需更新当前图形:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-13
      • 2019-04-08
      • 1970-01-01
      • 2015-08-26
      • 2013-11-05
      • 1970-01-01
      • 2013-01-08
      • 2020-03-18
      相关资源
      最近更新 更多