In the last post we saw how to toggle our tab on and off. But when we turned it off, our deleted our widget instance. The next time we turned our tab back on, we had to create a new instance of the widget.
Sometimes it is better to keep the widget in existence. Then we can open a new tab that uses our existing widget instance. This will maintain the state of our widget, so that we can pick up where we left off.
In the demo outline from the last post, we create a few constant names:
WIDGET_NAME
VISIBLE
We stored them in the log frame's contentsDict and used them to check whether our tab was available (open) or not:
# Now you see it
if log.contentsDict.get(VISIBLE, False):
log.deleteTab(TABNAME)
# Now you don't
log.contentsDict[VISIBLE] = False
log.contentsDict[WIDGET_NAME] = None
log.contentsDict[WIDGET_NAME] stores the widget instance.
To maintain our widget instance while our tab is closed, we need to omit the line
log.contentsDict[WIDGET_NAME] = None
We also need to track whether the widget instance has already been loaded so that we if it has we can just reuse it but if not we can create it. This constant is named LOADED. We also store it in contentsDict. Here is the changed code:
log = c.frame.log
TABNAME = 'Pyplot'
VISIBLE = f'{TABNAME}-visible'
LOADED = f'{TABNAME}-loaded'
WIDGET_NAME = f'{TABNAME}-widget'
# If our tab is visible, remove it
# but keep our widget
if log.contentsDict.get(VISIBLE, False):
log.deleteTab(TABNAME)
log.contentsDict[VISIBLE] = False
font = c.config.getColor('font-family')
else:
# Show our tab, reusing our widget if already loaded
if log.contentsDict.get(LOADED, False):
log.createTab(TABNAME,
widget = log.contentsDict[WIDGET_NAME],
createText = False)
log.contentsDict[VISIBLE] = True
log.selectTab(TABNAME)
else:
# Create our tab for the first time
w = PlotWindow()
log.createTab(TABNAME, widget = w, createText = False)
log.selectTab(TABNAME)
log.contentsDict[LOADED] = True
log.contentsDict[VISIBLE] = True
log.contentsDict[WIDGET_NAME] = w
Next time we will pass g and c so that we can interact with Leo itself. We will also show how to change some behavior or state depending on whether our tab is visible or not. This is a kind of parlor trick, yet can be useful.