[英]How to use tkinter FigureCanvasTkAgg
Hello I use FigureCanvasTkAgg to use matplotlib in tkinter.您好,我使用 FigureCanvasTkAgg 在 tkinter 中使用 matplotlib。 I wrote a code so that when the button is pressed, the two graphs change.我编写了一个代码,以便当按下按钮时,两个图形会发生变化。
import numpy as np
import tkinter as tk
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]
plt.clf() # clear current figure
plt.bar(x=x, height=y) # plot the graph
plt.xticks(x, rotation=90)
canvas.draw() # refresh plot
def change2():
s1s = np.random.randint(100)
s1s1 = np.random.randint(100)
s1s2 = np.random.randint(100)
x2 = ['Col A', 'Col B', 'Col C']
y2 = [s1s,s1s1,s1s2]
plt.clf() # clear current figure
plt.bar(x=x2, height=y2) # plot the graph
plt.xticks(x2, rotation=90)
canvas1.draw() # refresh plot
btn = tk.Button(window, text='click',command =lambda:[change(),change2()])
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)
x2 = ['Col A', 'Col B', 'Col C']
y2 = [70, 40, 30]
fig2 = plt.figure(figsize=(4, 5))
plt.bar(x=x2, height=y2)
plt.xticks(x2, rotation=90)
canvas = FigureCanvasTkAgg(fig, master=window)
canvas.draw()
canvas.get_tk_widget().grid(row=1, column=0, ipadx=40, ipady=20)
canvas1 = FigureCanvasTkAgg(fig2, master=window)
canvas1.draw()
canvas1.get_tk_widget().grid(row=2, column=0, ipadx=40, ipady=20)
window.mainloop()
output But when I run the code, only the last appended change2() is executed. output但是当我运行代码时,只执行最后附加的change2()。 Can you set up a solution?你能设置一个解决方案吗?
One of the way is to assign an unique ID to the two figures:一种方法是为这两个数字分配一个唯一的 ID:
...
fig = plt.figure(1, figsize=(4,5)) # figure with ID 1
...
fig2 = plt.figure(2, figsize=(4,5)) # figure with ID 2
...
Then select the figure you want to update inside change()
and change2()
:然后 select 您要在change()
和change2()
中更新的图形:
def change():
...
plt.figure(1) # select figure 1
plt.clf()
...
def change2():
...
plt.figure(2) # select figure 2
plt.clf()
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.