Giter Site home page Giter Site logo

dearpygui-examples's Introduction

dearpygui-examples's People

Contributors

dependabot[bot] avatar dkluis avatar hoffstadt avatar jendakolda avatar pcothren avatar vascoferreira25 avatar xircon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dearpygui-examples's Issues

Process finished with exit code -1073741819 (0xC0000005)

import dearpygui.dearpygui as dpg

class MyCustomLogger:

def __init__(self):

    self.log_level = 0
    self._auto_scroll = True
    self.filter_id = None
    self.window_id = dpg.add_window(label="mvLogger", pos=(200, 200), width=500, height=500)
    self.count = 0
    self.flush_count = 1000
    self.level_options = {"Trace": 0, "Debug": 1, "Info": 2,  "Warning": 3, "Error": 4, "Critical": 5}

    with dpg.group(horizontal=True, parent=self.window_id):
        dpg.add_checkbox(label="Auto-scroll", default_value=True,
                         callback=lambda sender: self.auto_scroll(dpg.get_value(sender)))
        dpg.add_button(label="Clear", callback=lambda: dpg.delete_item(self.filter_id, children_only=True))
    dpg.add_input_text(label="Filter", callback=lambda sender: dpg.set_value(self.filter_id, dpg.get_value(sender)),
                       parent=self.window_id)
    dpg.add_radio_button(list(self.level_options.keys()), parent=self.window_id,
                         callback=lambda sender: self.set_level(self.level_options[dpg.get_value(sender)]))
    dpg.add_same_line(parent=self.window_id)
    self.child_id = dpg.add_child(parent=self.window_id, autosize_x=True, autosize_y=True)
    self.filter_id = dpg.add_filter_set(parent=self.child_id)

    with dpg.theme() as self.trace_theme:
        dpg.add_theme_color(dpg.mvThemeCol_Text, (0, 255, 0, 255))

    with dpg.theme() as self.debug_theme:
        dpg.add_theme_color(dpg.mvThemeCol_Text, (64, 128, 255, 255))

    with dpg.theme() as self.info_theme:
        dpg.add_theme_color(dpg.mvThemeCol_Text, (255, 255, 255, 255))

    with dpg.theme() as self.warning_theme:
        dpg.add_theme_color(dpg.mvThemeCol_Text, (255, 255, 0, 255))

    with dpg.theme() as self.error_theme:
        dpg.add_theme_color(dpg.mvThemeCol_Text, (255, 0, 0, 255))

    with dpg.theme() as self.critical_theme:
        dpg.add_theme_color(dpg.mvThemeCol_Text, (255, 0, 0, 255))

def auto_scroll(self, value):
    self._auto_scroll = value

def _log(self, message, level):

    if level < self.log_level:
        return

    self.count += 1

    if self.count > self.flush_count:
        self.clear_log()

    theme = self.info_theme

    if level == 0:
        message = "[TRACE]\t\t" + message
        theme = self.trace_theme
    elif level == 1:
        message = "[DEBUG]\t\t" + message
        theme = self.debug_theme
    elif level == 2:
        message = "[INFO]\t\t" + message
    elif level == 3:
        message = "[WARNING]\t\t" + message
        theme = self.warning_theme
    elif level == 4:
        message = "[ERROR]\t\t" + message
        theme = self.error_theme
    elif level == 5:
        message = "[CRITICAL]\t\t" + message
        theme = self.critical_theme

    new_log = dpg.add_text(message, parent=self.filter_id, filter_key=message)
    dpg.set_item_theme(new_log, theme)
    if self._auto_scroll:
        scroll_max = dpg.get_y_scroll_max(self.child_id)
        dpg.set_y_scroll(self.child_id, -1.0)

def log(self, message):
    self._log(message, 0)

def log_debug(self, message):
    self._log(message, 1)

def log_info(self, message):
    self._log(message, 2)

def log_warning(self, message):
    self._log(message, 3)

def log_error(self, message):
    self._log(message, 4)

def log_critical(self, message):
    self._log(message, 5)

def clear_log(self):
    dpg.delete_item(self.filter_id, children_only=True)
    self.count = 0

def set_level(self, level):
    self.log_level = level

def log_things(sender, app_data, user_data):
user_data.log("We can log to a trace level.")
user_data.log_debug("We can log to a debug level.")
user_data.log_info("We can log to an info level.")
user_data.log_warning("We can log to a warning level.")
user_data.log_error("We can log to a error level.")
user_data.log_critical("We can log to a critical level.")

with dpg.window():
logger = MyCustomLogger()
logger.log("This is my logger. Just like an onion it has many levels.")
dpg.add_button(label="Log to logger", callback=log_things, user_data=logger)

dpg.start_dearpygui()

Run the above code and report an error:

F:\workspace\ENVS\TOOLS-ENV\Scripts\python.exe F:/workspace/projects/python-project/tools/can_tool/logger.py

Process finished with exit code -1073741819 (0xC0000005)

Repo Structure

  • re-organize repo with file structure with categories ( OOP wrapping examples, core examples, app examples, ect)

  • be sure to update the .ignore file with any new files

Can't get my head around git

Done a lot of work, completely changed, here is the code:

#!/usr/bin/env python
"""
Author: Steve Fisher (xircon)
Licence: MIT
A simple python script using DearPyGui and Sqlite3.
Creates a database and table in the same directory as the script.
Uses one form to do add, delete, find and edit records.
"""
import sqlite3
from dearpygui import core, simple
from dearpygui.core import *
from dearpygui.simple import *
import pandas as pd

# Create the database if it does not exist:
try:
    con = sqlite3.connect('addresses.db')
    cursor = con.cursor()
    print("Database created and Successfully Connected to SQLite")

except sqlite3.Error as error:
    print("File exists", error)

finally:
    if con:
        con.close()
        print("The SQLite connection is closed")

# Create the table:
try:
    con = sqlite3.connect('addresses.db')
    sqlite_create_table_query = '''CREATE TABLE address_data (
                                id INTEGER PRIMARY KEY,
                                fname TEXT,
                                sname TEXT,
                                add1 TEXT,
                                add2 TEXT,
                                city TEXT,
                                pcode TEXT,
                                tel TEXT);'''

    cursor = con.cursor()
    print("Successfully Connected to SQLite")
    cursor.execute(sqlite_create_table_query)
    con.commit()
    print("SQLite table created")

    cursor.close()

except sqlite3.Error as error:
    print("Table exists", error)

finally:
    if (con):
        con.close()
        print("sqlite connection is closed")


wid=800
hgt=600
core.set_main_window_size(wid, hgt)

core.add_additional_font("/usr/share/fonts/adobe-source-code-pro/SourceCodePro-Bold.otf", 25, "")


def save_callback(sender, data):

    # Store Data to variables:
    tFN = core.get_value("##fname").strip()
    tSN = core.get_value("##sname").strip()
    tA1 = core.get_value("##add1").strip()
    tA2 = core.get_value("##add2").strip()
    tCI = core.get_value("##city").strip()
    tPC = core.get_value("##pcode").strip()
    tTE = core.get_value("##tel").strip()


    # Write to table:
    con = sqlite3.connect('addresses.db')
    cursor = con.cursor()
    sqlite_insert_query = """INSERT INTO address_data
                          ( fname, sname, add1, add2, city, pcode, tel) 
                          VALUES (?, ?, ?, ?, ?, ?, ?);"""
    cursor.execute(sqlite_insert_query, (tFN, tSN, tA1, tA2, tCI, tPC, tTE))
    con.commit()
    con.close()
    clear_callback(1,1) # With dummy sender and data values. 
    table_update()
    
# Clears the Data input fields     
def clear_callback(sender, data):
    
    # Clear previous input data:
    tFN = core.set_value("##fname", "")
    tSN = core.set_value("##sname", "")
    tA1 = core.set_value("##add1",  "")
    tA2 = core.set_value("##add2",  "")
    tCI = core.set_value("##city",  "")
    tPC = core.set_value("##pcode", "")    
    tTE = core.set_value("##tel",  "")

# Finds a record based on first name and/or surname:    
def find_callback(sender, data):
    # Read first & surname: 
    tFN = core.get_value("##fname")
    tSN = core.get_value("##sname")
     
    # Connect to database:
    con = sqlite3.connect('addresses.db')
    cursor = con.cursor()

    # Find if first name and surname supplied:
    if tFN != "" and tSN != "":
       sqlite_insert_query = """SELECT * from address_data where fname LIKE ? and sname LIKE ? COLLATE NOCASE"""
       cursor.execute(sqlite_insert_query, (tFN, tSN))

    # Find if first name only supplied:
    if tFN != "" and tSN == "":
       con.set_trace_callback(print)
       sqlite_insert_query = """SELECT * from address_data where fname LIKE ? COLLATE NOCASE"""
       cursor.execute(sqlite_insert_query, (tFN,))

    # Find if only surname supplied:   
    if tFN == "" and tSN != "":
       sqlite_insert_query = """SELECT * from address_data where sname LIKE ? COLLATE NOCASE"""
       cursor.execute(sqlite_insert_query, (tSN,))

    # Return first matching record from query:       
    record = cursor.fetchone()

    # If record not found, exit, else populate fields
    if record is None:
        return
    else:
        core.set_value("##fname", record[1])
        core.set_value("##sname", record[2])
        core.set_value("##add1",  record[3])
        core.set_value("##add2",  record[4])
        core.set_value("##city",  record[5])
        core.set_value("##pcode", record[6])
        core.set_value("##tel",   record[7])
    # Close database connection:
    con.commit()
    con.close()

# Save edited data:    
def edit_callback(sender, data):
    # Populate variables:
    tFN = core.get_value("##fname")
    tSN = core.get_value("##sname")
    tA1 = core.get_value("##add1")
    tA2 = core.get_value("##add2")
    tCI = core.get_value("##city")
    tPC = core.get_value("##pcode")
    tTE = core.get_value("##tel")

    # Connect to database
    con = sqlite3.connect('addresses.db')
    cursor = con.cursor()

    # Do a quick query to the record id and prove it exists:
    sqlite_insert_query = """SELECT * from address_data where fname LIKE ? and sname LIKE ?"""
    cursor.execute(sqlite_insert_query, (tFN, tSN))

    # Get first record from query:
    exist = cursor.fetchone()
    
    # If it doesn't exist do nothing, else update record based on id:
    if exist is None:
        return
    else:
        con.set_trace_callback(print)
        sql_update = """UPDATE address_data SET add1=?, add2=?, city=?, pcode=?, tel=? WHERE id=?"""
        cursor.execute(sql_update, (tA1, tA2, tCI, tPC, tTE, exist[0]))
        con.commit()
        con.close()
    clear_callback(1,1)

# Delete record based on first & suname:
def del_callback(sender, data):
    tFN = core.get_value("##fname")
    tSN = core.get_value("##sname")

    con = sqlite3.connect('addresses.db')
    cursor = con.cursor()

    sql_del_query = """DELETE from address_data where fname = ? AND sname = ?"""

    cursor.execute(sql_del_query, (tFN, tSN))

    con.commit()
    con.close()
    clear_callback(1,1)
    table_update()

#Update the table from a Pandas data frame
def table_update():

    # Connect to database:
    con = sqlite3.connect('addresses.db')
    cursor = con.cursor()

    # Setup the query string:
    sql_sel_query = """SELECT fname, sname, tel from address_data"""

    # TODO - work out how to reference the SQL query nativeley 
    # cursor.execute(sql_sel_query)
    # records = cursor.fetchall()
    # print(records)
    # [('Mickey', 'Mouse', '0111 111 1111'), ('aaaa', 'bbbb', 'gggg'), ('Elizabeth', 'Windsor', '01 234 56789')]

    # Use Pandas to access the SQL query data
    df = pd.read_sql_query(sql_sel_query,con)
    print(df.head()) # Debug

    # Create an index to find the number of records/columns:
    index = df.index
    nrows = len(index)
    ncols = len(df.columns)

    # Populate the table from the Pandas dataframe:
    tabledata = []
    for i in range(0, nrows):
        row = []
        for j in range(0, ncols):
            row.append(df.iat[i,j])
        tabledata.append(row)

    set_table_data("Table##widget", tabledata)

    # Close the database:
    con.close()


# Export the database to a CSV using Pandas:
def export_callback(sender, data):

    # Connect to Database: 
    con = sqlite3.connect('addresses.db')
    cursor = con.cursor()

    # Setup query:
    sql_sel_query = """SELECT * from address_data"""
    # Execute
    df = pd.read_sql(sql_sel_query, con)
    # Write to CSV:
    df.to_csv('export.csv')
    
    
with simple.window("Main Window"):
    # Create the text entry input boxes:
    core.add_text("")
    core.add_text("First Name:")
    core.add_same_line()
    core.add_input_text("##fname")
    core.add_same_line()
    core.add_text("?")

    core.add_text("Surname   :")
    core.add_same_line()
    core.add_input_text("##sname")
    core.add_same_line()
    core.add_text("?")    

    core.add_text("Address1  :")
    core.add_same_line()
    core.add_input_text("##add1")

    core.add_text("Address2  :")
    core.add_same_line()
    core.add_input_text("##add2")

    core.add_text("City      :")
    core.add_same_line()
    core.add_input_text("##city")

    core.add_text("Postcode  :")
    core.add_same_line()
    core.add_input_text("##pcode", uppercase=True)

    core.add_text("Phone No  :")
    core.add_same_line()
    core.add_input_text("##tel")

    # Create the buttons:
    # Row 1
    core.add_text("")
    core.add_button("Save", callback=save_callback, tip="Enter Data click Save")
    
    # Row 2
    core.add_button("Find", callback=find_callback, tip="Enter Firstname &/or Surname, click find")
    core.add_same_line()
    core.add_button("Save Edits", callback=edit_callback, tip="Save edited record")
    core.add_same_line()
    core.add_button("Clear", callback=clear_callback, tip="Clear fields")
    core.add_same_line()
    core.add_button("Delete", callback=del_callback, tip="Delete record")
    core.add_same_line()
    core.add_button("Export", callback=export_callback, tip="Export to CSV")

    
    add_table("Table##widget", ["First Name", "Surname", "Telephone Number"])
    table_update()

 
# Run the script:
core.start_dearpygui(primary_window="Main Window")

Example for putting modal window in center

I just found it usefull for other people they need an 0.8.x example for the login example

MainWindow_width = get_item_width(MainWindow_ID)
MainWindow_height = get_item_height(MainWindow_ID)
ModalWindow_width = get_item_width(ModalWindow_ID)
ModalWindow_height = get_item_height(ModalWindow_ID)

set_item_pos(ModalWindow_ID, [int((main_width/2 - ModalWindow_width/2)), int((main_height/2 - ModalWindow_height/2))])

camera_capture_with_opencv How to add threading

import dearpygui.dearpygui as dpg
import cv2
import numpy as np
import threading
import inspect
import ctypes

Start_Thread = None



def Async_raise(tid, exctype):
    tid = ctypes.c_long(tid)
    if not inspect.isclass(exctype):
        exctype = type(exctype)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")

def Stop_thread(thread):
    Async_raise(thread.ident, SystemExit)


dpg.create_context()
dpg.create_viewport(title='VideoCapture')


dpg.setup_dearpygui()
dpg.show_viewport()

width, height, channels, data= dpg.load_image("F:/Black_background.jpg")

def opencv_hread():

    vid = cv2.VideoCapture(0)
    
    ret, frame = vid.read()

    # image size or you can get this from image shape
    frame_width = vid.get(cv2.CAP_PROP_FRAME_WIDTH)
    frame_height = vid.get(cv2.CAP_PROP_FRAME_HEIGHT)
    video_fps = vid.get(cv2.CAP_PROP_FPS)
    print(frame_width)
    print(frame_height)
    print(video_fps)

    print("Frame Array:")
    print("Array is of type: ", type(frame))
    print("No. of dimensions: ", frame.ndim)
    print("Shape of array: ", frame.shape)
    print("Size of array: ", frame.size)
    print("Array stores elements of type: ", frame.dtype)

    data = np.flip(frame, 2)              #  because the camera data comes in as BGR and we need RGB
    data = data.ravel()                   #   flatten camera data to a 1 d stricture
    data = np.asfarray(data, dtype='f')  #    change data type to 32bit floats
    texture_data = np.true_divide(data, 255.0)  # normalize image data to prepare for GPU

    while dpg.is_dearpygui_running():

        ret, frame = vid.read()

        data = np.flip(frame, 2)
        data = data.ravel()
        data = np.asfarray(data, dtype='f')
        texture_data = np.true_divide(data, 255.0)

        dpg.set_value("texture_tag", texture_data)

        dpg.render_dearpygui_frame()



def threading_callback():
    global Start_Thread
    
    Start_Thread = threading.Thread(target=opencv_hread, daemon=True, name="opencv_hread_Start_Thread")
    Start_Thread.start()



def STOP_threading_callback():
    global Start_Thread
    if Start_Thread.isAlive():
        Stop_thread(Start_Thread)



with dpg.texture_registry(show=False):
    dpg.add_static_texture(width=640, height=480,default_value=data, tag="texture_tag")


with dpg.window(label="OpenCV VideoCapture"):

    with dpg.group(horizontal=True):
        dpg.add_image("texture_tag")
        dpg.add_button(label="Start", width=100, height=100,callback=threading_callback)
        dpg.add_button(label="Stop", width=100, height=100,callback=STOP_threading_callback)


dpg.show_metrics()

dpg.start_dearpygui()





dpg.destroy_context()

Start button
Stop button
threading.Thread

Unfortunately, there is something wrong with my writing
Need help
thank

Create issue topics and templates

  • "Example request" topic template
  • "Example Bug" template and topic
  • "Repo Issue" template and topic
  • "Discussion" topic and template
  • "Help" topic and template

Repeating line in render_callback.py example

Hi,

In lines 105 and 106 'render_callback.py' in folder 'special callbacks' , the line set_render_callback(render) is repeated. Deleting one of these two lines seems to work as well.

Example for node

please add example for node.
and one more question, can we change the shape of node? if yes, can you please write an example?
if not, how to make custom shaped node? i want to make simple logic gate simulation app where we can simulate logic like AND, OR and NOT

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.