我正在构建一个程序,其中我有一个实时图形使用使用matplotlib。我使用tkinter制作2个按钮:“graph it”打开一个新窗口来绘制图,“clear”关闭窗口。问题是,当我第一次用“clear”按钮关闭窗口时,我不能用“graph it”按钮重新显示图形。相反,它给了我这个错误:
"UserWarning: Animation was deleted without rendering anything. This is most likely
not intended. To prevent deletion, assign the Animation to a variable, e.g. `anim`, that exists until you output the Animation using `plt.show()` or `anim.save()`.
下面是我的代码:
import datetime as dt
import random
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from tkinter import *
#import tmp102
# Create figure for plotting
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
xs = []
ys2 = []
ys = []
# Initialize communication with TMP102
#tmp102.init()
# This function is called periodically from FuncAnimation
def animate(i,xs, ys, ys2):
# Read temperature (Celsius) from TMP102
#temp_c = round(tmp102.read_temp(), 2)
num_random = random.randint(0,100)
num_random2 = random.randint(0,100)
# Add x and y to lists
xs.append(dt.datetime.now().strftime('%H:%M:%S.%f'))
ys.append(num_random)
ys2.append(num_random2)
# Limit x and y lists to 20 items
xs = xs[-15:]
ys = ys[-15:]
ys2 = ys2[-15:]
# Draw x and y lists
ax.clear()
ax.plot(xs, ys, ys2)
# Format plot
plt.xticks(rotation=45, ha='right')
plt.subplots_adjust(bottom=0.30)
plt.title('TMP102 Temperature over Time')
plt.ylabel('Temperature (deg C)')
# Set up plot to call animate() function periodically
def graph():
ani = animation.FuncAnimation(fig, animate, fargs=(xs, ys, ys2), interval=1000)
plt.show()
def clear():
plt.close()
root = Tk()
root.title('matplot with tkinter test')
root.geometry("400x200")
my_button = Button(root, text="Graph it", command=graph)
my_button.pack()
clear_button = Button(root, text="Clear", command=clear)
clear_button.pack()
root.mainloop()
我希望按钮能够显示和关闭的实时图形的任何时候按下按钮
1条答案
按热度按时间vsaztqbk1#
运行
plt.close()
时,实际上是删除了之前创建的图形fig
,因此必须重新创建该图形。或者,你可以使用
plt.close()
以外的其他命令,这样你就不会删除你的图形。你可以使用plt.clf()
来清除它,而不是同时删除窗口。