1

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?

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

4 Comments

thank you!! one small edit to your comment, the figure creation is actually fig = Figure.Figure().
@ohshitgorillas No, it should be fig = Figure() if you use my sample code.
Perhaps the difference is that I'm using Python 3.7.9, but fig = Figure() gave me an error whereas fig = Figure.Figure() succeeded. With fig = Figure() I got the error TypeError: 'module' object is not callable.
Oh, the difference was using import matplotlib.figure as Figure rather than from matplotlib.figure import Figure. For the latter, fig = Figure() works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.