UserWarning: Animation was deleted without rendering anything

Hi all,
I am trying to add a animation plot to an tkinter App, and it is running well for the first call. But it’s broken in the second call ( close the plot then recall it again via a tkinter button) with:
Warning (from warnings module):
File “C:\Users\eliu\AppData\Local\Programs\Python\Python311\Lib\site-packages\matplotlib\animation.py”, line 892
warnings.warn(
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().

Here’s my code:

import customtkinter as ctk
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation

gSize = "400x240"   
root = ctk.CTk()
root.geometry(gSize) 
root.title("Plot View")

ctk.set_appearance_mode("System")
ctk.set_default_color_theme("blue")

plt.style.use('dark_background')

fig, ax = plt.subplots()
x = np.array(["C1", "C2", "C3", "C4"])
y = np.array([3.1, 8.2, 1.5, 10.3])
clrs = ['lightblue', 'blue', 'purple', 'red']

i=0

def update(frame):
    global x, y,i
    ax.clear()
    i=i+1
    print(i)
    if (i%2 == 1):
        y[0]=y[0]+1
        clrs[0]='green'
    else:
        y[0]=y[0]-1
        clrs[0]='lightblue'

    plt.grid(True, color = "grey", linewidth = "0.3", linestyle = "-", axis='y')
    plt.bar(x,y,width = 0.1, color = clrs)
    plt.xticks(rotation=45, fontsize=13)

    
def viewPlot():
    animation = FuncAnimation(fig, update, frames=40, interval=1000)
    plt.show()

snlBtn = ctk.CTkButton(root, text="View Plot", command=viewPlot)
snlBtn.grid(row=0, column=0, padx=120, pady=20)

root.mainloop()

Does anyone have an idea? Thanks in advance.
– Eric

Could we see a complete stack trace for the warning?

Does anything else wrong happen besides seeing that warning?

Hi Karl,
That’s all the information I got. No plot popping up after first call.