dearpygui any code
- User
dearpygui any code
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
dearpygui any code
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, you've come to the right place! dearpygui is a fantastic Python GUI library that's fast and easy to use.
Here's a progression of dearpygui code examples, from the absolute basics to more interactive and common patterns.
First, ensure you have dearpygui installed:
pip install dearpygui
This is the simplest possible dearpygui application. It creates a window with some text.
import dearpygui.dearpygui as dpg
# 1. Create the DPG context
dpg.create_context()
# 2. Create the viewport (the actual OS window)
dpg.create_viewport(title='My First DPG App', width=700, height=300)
# 3. Setup DearPyGui (integrates with OS window)
dpg.setup_dearpygui()
# 4. Define your GUI elements within a window
with dpg.window(label="Main Window", tag="primary_window", autosize=True):
dpg.add_text("Hello, dearpygui!")
dpg.add_text("This is my first DPG application.")
dpg.add_separator()
dpg.add_text("You can move and resize this window.")
# 5. Show the viewport
dpg.show_viewport()
# 6. Start the DearPyGui main loop (this blocks until the window is closed)
dpg.start_dearpygui()
# 7. Destroy the context (cleanup)
dpg.destroy_context()
Let's make it interactive! When you click a button, it will change the text.
import dearpygui.dearpygui as dpg
dpg.create_context()
dpg.create_viewport(title='Button Example', width=500, height=200)
dpg.setup_dearpygui()
# Define a callback function for the button
def button_callback(sender, app_data, user_data):
# 'sender' is the tag of the widget that triggered the callback (e.g., 'my_button')
# 'app_data' usually contains widget-specific data (e.g., value of an input field)
# 'user_data' is custom data you can pass when registering the callback
print(f"Button '{sender}' pressed!")
# Update the text widget
dpg.set_value("status_text", "Button was clicked!")
with dpg.window(label="Interactive Window", tag="interactive_window", autosize=True):
dpg.add_text("Click the button below:")
dpg.add_button(label="Click Me!", tag="my_button", callback=button_callback)
dpg.add_text("Status: Idle", tag="status_text") # This text will be updated
dpg.show_viewport()
dpg.start_dearpygui()
dpg.destroy_context()
Get input from the user and display it.
import dearpygui.dearpygui as dpg
dpg.create_context()
dpg.create_viewport(title='Input Example', width=500, height=250)
dpg.setup_dearpygui()
def process_input_callback(sender, app_data, user_data):
# Get the current value from the input_text widget
input_text_value = dpg.get_value("user_input")
dpg.set_value("output_text", f"You entered: {input_text_value}")
print(f"Input processed: {input_text_value}")
with dpg.window(label="Input Demo", tag="input_window", autosize=True):
dpg.add_text("Enter something:")
dpg.add_input_text(label="Your Text", tag="user_input", hint="Type here...")
dpg.add_button(label="Submit", callback=process_input_callback)
dpg.add_separator()
dpg.add_text("Output will appear here.", tag="output_text")
dpg.show_viewport()
dpg.start_dearpygui()
dpg.destroy_context()
Organizing widgets for better visual appeal.
import dearpygui.dearpygui as dpg
dpg.create_context()
dpg.create_viewport(title='Layout Example', width=600, height=350)
dpg.setup_dearpygui()
def log_button_click(sender, app_data, user_data):
print(f"'{dpg.get_item_label(sender)}' clicked!")
with dpg.window(label="Layout Demo", tag="layout_window", width=550, height=300):
dpg.add_text("Horizontal Group:")
with dpg.group(horizontal=True):
dpg.add_button(label="Button 1", callback=log_button_click)
dpg.add_button(label="Button 2", callback=log_button_click)
dpg.add_button(label="Button 3", callback=log_button_click)
dpg.add_separator()
dpg.add_text("Using same_line():")
dpg.add_button(label="A", callback=log_button_click)
dpg.add_same_line() # Puts the next item on the same line
dpg.add_button(label="B", callback=log_button_click)
dpg.add_same_line()
dpg.add_button(label="C", callback=log_button_click)
dpg.add_separator()
dpg.add_text("Sliders and Checkboxes:")
dpg.add_slider_int(label="Int Slider", default_value=50, max_value=100)
dpg.add_slider_float(label="Float Slider", default_value=0.5, max_value=1.0, format="%.2f")
dpg.add_checkbox(label="Option 1", default_value=True)
dpg.add_checkbox(label="Option 2")
dpg.show_viewport()
dpg.start_dearpygui()
dpg.destroy_context()
A common need: selecting a file or directory.
import dearpygui.dearpygui as dpg
import os
dpg.create_context()
dpg.create_viewport(title='File Dialog Example', width=600, height=300)
dpg.setup_dearpygui()
def file_dialog_callback(sender, app_data):
# 'app_data' contains a dictionary with selected information
# 'file_path_name' for a single file/dir
# 'selections' for multiple files (dict of {filename: full_path})
print("File Dialog App Data: ", app_data)
if app_data['file_path_name']:
dpg.set_value("selected_path_text", f"Selected: {app_data['file_path_name']}")
elif app_data['selections']:
paths = "\n".join(app_data['selections'].values())
dpg.set_value("selected_path_text", f"Selected multiple:\n{paths}")
else:
dpg.set_value("selected_path_text", "No selection or dialog cancelled.")
# Create a file dialog
# You can define it once and show/hide it
with dpg.file_dialog(
directory_selector=False, # Set to True for directory selection
show=False,
callback=file_dialog_callback,
tag="file_dialog_tag",
width=700, height=400,
default_path=os.getcwd() # Start in current working directory
):
# Add allowed extensions if file_selector is True
dpg.add_file_extension(".py", color=(255, 0, 255, 255))
dpg.add_file_extension(".txt", color=(0, 255, 0, 255))
dpg.add_file_extension(".*", color=(0, 255, 255, 255), custom_text="[all]")
def open_file_dialog_btn_callback(sender, app_data, user_data):
dpg.show_item("file_dialog_tag") # Show the file dialog when button is clicked
with dpg.window(label="File Selector Demo", tag="file_selector_window", autosize=True):
dpg.add_text("Click to select a file or directory.")
dpg.add_button(label="Open File Dialog", callback=open_file_dialog_btn_callback)
dpg.add_text("No file selected.", tag="selected_path_text")
dpg.show_viewport()
dpg.start_dearpygui()
dpg.destroy_context()
numpy for data generation)dearpygui has excellent plotting capabilities.
import dearpygui.dearpygui as dpg
import numpy as np
# Install numpy if you don't have it: pip install numpy
dpg.create_context()
dpg.create_viewport(title='Plotting Example', width=800, height=600)
dpg.setup_dearpygui()
with dpg.window(label="Plot Demo", autosize=True):
# Generate some data
x_data = np.linspace(0, 2 * np.pi, 100)
y_data = np.sin(x_data)
y_data2 = np.cos(x_data)
# Create a plot
with dpg.plot(label="Sine and Cosine Waves", height=-1, width=-1): # -1 means fill remaining space
# Add a legend
dpg.add_plot_legend()
# Create X and Y axes
x_axis = dpg.add_plot_axis(dpg.mvXAxis, label="X-axis")
y_axis = dpg.add_plot_axis(dpg.mvYAxis, label="Y-axis")
# Add line series to the Y axis
# Note: data needs to be a list of lists or tuples (x_values, y_values)
dpg.add_line_series(list(x_data), list(y_data), label="Sine", parent=y_axis)
dpg.add_line_series(list(x_data), list(y_data2), label="Cosine", parent=y_axis, color=(255, 0, 0, 255)) # Red line
# (Optional) Set axis limits
dpg.set_axis_limits(x_axis, 0, 2 * np.pi)
dpg.set_axis_limits(y_axis, -1.1, 1.1)
dpg.show_viewport()
dpg.start_dearpygui()
dpg.destroy_context()
Displaying tabular data is easy with dpg.add_table.
import dearpygui.dearpygui as dpg
dpg.create_context()
dpg.create_viewport(title='Table Example', width=700, height=400)
dpg.setup_dearpygui()
with dpg.window(label="Table Demo", tag="table_window", autosize=True):
dpg.add_text("Simple Table:")
# Create a table container
with dpg.table(header_row=True, resizable=True, policy=dpg.mvTableRowsFit,
borders_outerH=True, borders_innerV=True, borders_innerH=True,
borders_outerV=True, row_background=True, tag="my_table"):
# Add columns
dpg.add_table_column(label="ID")
dpg.add_table_column(label="Name")
dpg.add_table_column(label="Age")
dpg.add_table_column(label="City")
# Add rows and cells
data = [
("001", "Alice", 30, "New York"),
("002", "Bob", 24, "London"),
("003", "Charlie", 35, "Paris"),
("004", "Diana", 28, "Tokyo")
]
for row_id, name, age, city in data:
with dpg.table_row():
dpg.add_text(row_id)
dpg.add_text(name)
dpg.add_text(age)
dpg.add_text(city)
dpg.add_separator()
dpg.add_text("Another row with a button:")
with dpg.table_row():
dpg.add_text("005")
dpg.add_text("Eve")
dpg.add_text(22)
dpg.add_button(label="View Profile", small=True, callback=lambda s, a, u: print("Eve's profile viewed!"))
dpg.show_viewport()
dpg.start_dearpygui()
dpg.destroy_context()
dearpygui:create_context, destroy_context): Always create and destroy the DearPyGui context. This manages all internal DPG resources.create_viewport, show_viewport, setup_dearpygui): The actual operating system window.dpg.add_...): Every GUI element (buttons, text, inputs, etc.) is a widget.tag="some_unique_id"): Every widget should ideally have a unique tag. This is how you reference them later to get/set values (dpg.get_value, dpg.set_value) or show/hide them.callback=my_function): Functions that are called when a widget is interacted with (e.g., button click, input change).with dpg.window(...):): Many widgets are added inside a parent container. Using with statements makes the hierarchy clear.dpg.start_dearpygui()): This function starts the GUI event loop, which listens for user input and renders the GUI. It blocks until the GUI is closed.This should give you a very strong start with dearpygui! Explore the official documentation for many more widgets and advanced features.