首页 > 解决方案 > 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()

标签: pythontkinterreal-time

解决方案


推荐阅读