I have a nicely working non-modal window (everything displays correctly, and buttons in the xaml are able to trigger Revit actions, etc).
The only minor problem is that if I click the pushbutton on the toolbar a second time, it opens a second instance of the same window. In other programming languages, I would implement a singleton (or similar) pattern, to track whether or not a window is open, and hold onto a reference to the open window, thereby ensuring a second window would not be created.
In the pyRevit documentation, there is a passing reference to leaving instances of non-modal windows in memory see here
I tried two approaches and neither seemed to work.
Approach 1:
__persistentengine__ = True
log = script.get_logger()
if '__window__' in globals():
log.warning("Window was found in globals at the start of the script")
window = globals()['__window__']
window.show()
else:
log.warning("Window was not found in globals at the start of the script")
window = script.load_ui(ux.MyWindow(), 'ui.xaml')
globals()['__window__'] = window
window.show()
if '__window__' in globals():
log.warning("Window was found in globals at the end of the script")
window = globals()['__window__']
window.show()
Result of approach 1… the script always results in the log showing this:
WARNING [DSO] Window was not found in globals at the start of the script
WARNING [DSO] Window was found in globals at the end of the script
Approach 2: Attach the window object to some other object dynamically
__persistentengine__ = True
if hasattr(EXEC_PARAMS.command_uibutton, 'window'):
window = EXEC_PARAMS.command_uibutton.window
window.show()
else:
window = EXEC_PARAMS.command_uibutton.load_ui(ux.MyWindow(), 'ui.xaml')
setattr(EXEC_PARAMS.command_uibutton, 'window', window)
window.show()
Result of approach 2…
AttributeError: 'RibbonButton' object has no attribute 'load_ui'
Other objects (like pyrevit.script) either have this error too or just don’t seem to persist between pushbutton clicks.
I tried finding examples of working solutions on github but came up blank. It would be greatly appreciated if someone could point out what I’m doing wrong or misunderstanding… Thanks!