【发布时间】:2022-10-23 17:51:19
【问题描述】:
早上好,
我想要达到的目标:
- 我想根据 GUI 提供的值以交互方式更改 matplotlib.animation 参数。
例子:
- 我准备了一个示例代码,如下所示,我试图根据用户通过使用 tkinter 创建的 spinBox 提供的值来更改动画的间隔参数。
问题:
- 为了能够更新其参数,我想将我的动画调用到旋转框调用的回调函数中。但如果我这样做,我会收到以下错误消息“用户警告:动画被删除而没有渲染任何东西。这很可能是无意的。为防止删除,请将动画分配给只要您需要动画就存在的变量。”
- 如果我将动画调用到主代码中,那么我将无法以交互方式更改其参数
问题:
- 如何以交互方式更改动画参数,即基于用户可以在 tkinter 小部件中设置的值?
谢谢
示例代码:
import tkinter as tk
from random import randint
import matplotlib as plt
import matplotlib.animation as animation
import matplotlib.backends.backend_tkagg as tkagg
#Creating an instance of the Tk class
win = tk.Tk()
#Creating an instance of the figure class
fig = plt.figure.Figure()
#Create a Canvas containing fig into win
aCanvas =tkagg.FigureCanvasTkAgg(fig, master=win)
#Making the canvas a tkinter widget
aFigureWidget=aCanvas.get_tk_widget()
#Showing the figure into win as if it was a normal tkinter widget
aFigureWidget.grid(row=0, column=0)
#Defining the animation
ax = fig.add_subplot(xlim=(0, 1), ylim=(0, 1))
(line,) = ax.plot([],[], '-')
CumulativeX, CumulativeY = [], []
# Providing the input data for the plot for each animation step
def update(i):
CumulativeX.append(randint(0, 10) / 10)
CumulativeY.append(randint(0, 10) / 10)
return line.set_data(CumulativeX, CumulativeY)
spinBoxValue=1000
#When the button is pushed, get the value
def button():
spinBoxValue=aSpinbox.get()
#Running the animation
ani=animation.FuncAnimation(fig, update, interval=spinBoxValue, repeat=True)
#Creating an instance of the Spinbox class
aSpinbox = tk.Spinbox(master=win,from_=0, to=1000, command=button)
#Placing the button
aSpinbox .grid(row=2, column=0)
#run the GUI
win.mainloop()
【问题讨论】:
-
您能否澄清您是否想在获得新输入时从头开始动画,或者按钮与动画是否有任何其他关系?
-
在我的完整代码中,我使用 tkinter 来提供一些输入。单击 tkinter 按钮后,我想 a) 完全清除上一个动画,b) 我想使用一些输入来计算将修改 line.set_data 的新列表(CumulativeX 和 CumulativeY 中的值,如果你愿意) 和 c) 剩余的输入必须改变 animate 函数本身的参数。
标签: python matplotlib tkinter animation callback