NiceGUI: tkinter error when updating pyplot
All notes in this series:
- NiceGUI: Always show main scrollbar
- NiceGUI: Show a confirmation popup
- NiceGUI: File upload and download
- FastAPI: Pretty print JSON
- NiceGUI with Click, Poetry, auto-reload and classes
- NiceGUI: tkinter error when updating pyplot
- NiceGUI: Bind visibility to arbitrary value
- NiceGUI: Change threshold for binding propagation warning
- NiceGUI with async classes
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:
- Create the plot as
my_plot. - Update
my_plotby populating it with data.
# Create plot
with ui.pyplot(
figsize=(3, 2),
) as my_plot:
pass
# 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, '-')
ui.update(my_plot)However, this gave a long Python traceback with the final error line of:
_tkinter.TclError: can't delete Tcl commandSolution §
The solution is to add close=False inside the call to ui.pyplot()1.
# Create plot
with ui.pyplot(
figsize=(3, 2),
close=False,
) as my_plot:
passThis 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)
Thanks to korenmolcho for this example of using pyplot and NiceGUI, and falkoschindler for these details on how to update a plot. ↩︎