Sam Hooke

NiceGUI: tkinter error when updating pyplot

TL;DR: if you get the error can't delete Tcl command when updating a pyplot within NiceGUI, add close=False to ui.pyplot().

Problem §

NiceGUI provides a simple example of a static plot with pyplot.

I wanted to be able to update the plot, so taking that static example, I split it out into two steps:

  1. Create the plot as my_plot.
  2. Update my_plot by populating it with data.
# Create plot
with ui.pyplot(
        figsize=(3, 2),
    ) as my_plot:

# Update plot
with my_plot:
    x = np.linspace(0.0, 5.0)
    y = np.cos(2 * np.pi * x) * np.exp(-x)
    plt.plot(x, y, '-')


However, this gave a long Python traceback with the final error line of:

_tkinter.TclError: can't delete Tcl command

Solution §

The solution is to add close=False inside the call to ui.pyplot()1.

# Create plot
with ui.pyplot(
        figsize=(3, 2),
    ) as my_plot:

This is actually documented in the static example linked above, in the usage of the optional close argument, but is very easy to miss. See the following quote (emphasis added):

close: whether the figure should be closed after exiting the context; set to False if you want to update it later (default: True)

See all notes.

← Previous Note: The Important Files: Part 8
Next Note: NiceGUI: Bind visibility to arbitrary value →