python - Tkinter 实时动画
问题描述
我将如何实现我绘制的第一个点不是 (0,0),(由 确定line1, = ax1.plot([0], [0]
),而是在函数func_A
的第一次迭代中计算的点update_plot()
。
import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
import matplotlib.pyplot as plt
from matplotlib import style
import matplotlib
matplotlib.use("Agg")
root = tk.Tk()
root.title("Graph")
#root.geometry("800x400")
# progress label, pause and resume buttons
frame = tk.Frame(root)
frame.pack(fill="x", side=tk.TOP)
progress = tk.Label(frame)
progress.pack(side="left")
is_paused = tk.BooleanVar() # variable to hold the pause/resume state
tk.Button(frame, text="Pause", command=lambda: is_paused.set(True)).pack(side="right")
tk.Button(frame, text="Resume", command=lambda: is_paused.set(False)).pack(side="right")
# the plot
fig = plt.figure(figsize=(10, 5), dpi=100)
canvas = FigureCanvasTkAgg(fig, master=root)
toolbar = NavigationToolbar2Tk(canvas, root)
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
plt.grid("both")
style.use("ggplot")
a = 1
ax1 = plt.subplot(111)
line1, = ax1.plot([0], [0])
def func_A(a, x):
import numpy
data_x = numpy.arange(0, x)
data_y = a * numpy.sin(data_x/5)
return data_x, data_y
# function to update ploat
def update_plot(k=0):
if not is_paused.get():
progress["text"] = f"iteration: {k}"
data_x, data_y = func_A(a, k)
#print("iteration", k)
#print("data_x", data_x)
#print("data_y", data_y)
line1.set_xdata(data_x)
line1.set_ydata(data_y)
ax1.set_ylim([-1, 1])
ax1.set_xlim([0, 100])
plt.grid("both")
canvas.draw()
canvas.flush_events()
k += 1
if k <= 100:
# update plot again after 10ms. You can change the delay to whatever you want
root.after(10, update_plot, k)
update_plot() # start updating plot
root.mainloop()
解决方案
推荐阅读
- gradle - 哪些依赖项被添加到使用“项目库依赖项”的 Gradle 项目中,这是可配置的吗?
- javascript - 如何避免在动态生成的 HTML 元素上使用 onClick (vanilla js)
- javascript - 检测按下了哪个按钮 sdk paypal
- android - 为 android 配置 Flutter“sign_in_with_apple”时出现问题
- python - 您可以使用 ffmpeg 流实时插入文件中的文本吗?
- visual-studio-code - 是否有任何键盘快捷键可以切换(或选择)给定的启动目标?
- unity3d - 将统一游戏构建到 android
- xslt - XSLT 如果存在则创建新标签,否则更新标签(如果存在)
- r - 带组的 R 二进制整数优化
- laravel - 你如何使用新鲜缓存运行 laravel php artisan serve