Container Stack¶
Unless an item is a root item, all items need to belong to a valid container. An item’s parent is deduced through the following process:
If item is a root, no parent needed; finished.
Check before keyword, if used skip to 5 using parent of “before” item.
Check parent keyword, if used skip to 5.
Check container stack, if used skip to 5.
Check if parent is compatible.
Check if parent accepts.
If runtime, add item using runtime methods; finished.
If startup, add item using startup methods; finished.
Container items can be manually pushed onto the container stack using
push_container_stack
and popped off using
pop_container_stack
.
This process is automated when using Containers & Context Managers. Below is a simple example demonstrating manual stack operations:
import dearpygui.dearpygui as dpg
dpg.create_context()
dpg.push_container_stack(dpg.add_window(label="Tutorial"))
dpg.push_container_stack(dpg.add_menu_bar())
dpg.push_container_stack(dpg.add_menu(label="Themes"))
dpg.add_menu_item(label="Dark")
dpg.add_menu_item(label="Light")
dpg.pop_container_stack()
# remove menu_bar from container stack
dpg.pop_container_stack()
# remove window from container stack
dpg.pop_container_stack()
dpg.create_viewport(title='Custom Title', width=800, height=600)
dpg.setup_dearpygui()
dpg.show_viewport()
dpg.start_dearpygui()
dpg.destroy_context()
Explicit Parental Assignment¶
Parents can be explicitly assigned using the parent keyword. This is most often used for adding new items at runtime. The above example can be shown again below using explicit parent assignment:
import dearpygui.dearpygui as dpg
dpg.create_context()
dpg.add_window(label="Tutorial", tag="window")
dpg.add_menu_bar(parent="window", tag="menu_bar")
dpg.add_menu(label="Themes", parent="menu_bar", tag="themes")
dpg.add_menu_item(label="Dark", parent="themes")
dpg.add_menu_item(label="Light", parent="themes")
dpg.create_viewport(title='Custom Title', width=800, height=600)
dpg.setup_dearpygui()
dpg.show_viewport()
dpg.start_dearpygui()
dpg.destroy_context()
Context Managers¶
Context managers can be used to simplify the above example. All the context managers can be found in the Containers & Context Managers but a simple example can be found below:
import dearpygui.dearpygui as dpg
dpg.create_context()
with dpg.window(label="Tutorial"):
with dpg.menu_bar():
with dpg.menu(label="Themes"):
dpg.add_menu_item(label="Dark")
dpg.add_menu_item(label="Light")
dpg.add_menu_item(label="Classic")
dpg.create_viewport(title='Custom Title', width=800, height=600)
dpg.setup_dearpygui()
dpg.show_viewport()
dpg.start_dearpygui()
dpg.destroy_context()
Benefits 1. Automatically push container to container stack. 2. Automatically pop container off container stack. 3. More structured, readable code.