pythontkintercustomtkinter

Why are there errors when I try to close a window in customtkinter?


I have a very simple data window that I am trying to show and offer an exit button:

import customtkinter as ctk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

# create the window using CTK
window = ctk.CTk()

# create the plot of random data
data = [1, 2, 3, 4, 5]
plt.plot(data)

# Add the plot to the window
canvas = FigureCanvasTkAgg(plt.gcf(), master=window)
canvas.draw()
canvas.get_tk_widget().pack(side='top', fill='both', expand=True)

exit_button = ctk.CTkButton(window, text='Exit', command=window.destroy)
exit_button.pack(side='bottom')  # add the exit button to the window

window.mainloop()

The problem is that after clicking Exit, while the window goes away, the terminal keeps running in the background with the following error:

invalid command name "2607166565512update"
    while executing
"2607166565512update"
    ("after" script)
invalid command name "2607167621640check_dpi_scaling"
    while executing
"2607167621640check_dpi_scaling"
    ("after" script)
invalid command name "2607249791944_click_animation"
    while executing
"2607249791944_click_animation"
    ("after" script)

What am I doing wrong and how can I get "Exit" to close the program completely?


Solution

  • It is a known issue of mixing tkinter and matplotlib.pyplot.plot(): cannot exit the application after closing the root window.

    Use matplotlib.figure.Figure instead:

    import customtkinter as ctk
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    
    # create the window using CTK
    window = ctk.CTk()
    
    fig = Figure()
    ax = fig.subplots()
    
    # create the plot of random data
    data = [1, 2, 3, 4, 5]
    ax.plot(data)
    
    # Add the plot to the window
    canvas = FigureCanvasTkAgg(fig, master=window)
    canvas.draw()
    canvas.get_tk_widget().pack(side='top', fill='both', expand=True)
    
    exit_button = ctk.CTkButton(window, text='Exit', command=window.destroy)
    exit_button.pack(side='bottom')  # add the exit button to the window
    
    window.mainloop()