Python DearPyGui 项目实践

32 篇文章 1 订阅
31 篇文章 10 订阅

源码下载地址

创建主框架

这里以一个名为 dear_demo 的项目为例,并在项目下创建几个文件夹:applicationdatautils,和两个文件:config.inimain.py,现在的项目结构应该是这样的:

\dear_demo          # 项目文件夹
d----- application  # 项目的应用文件夹
d----- data         # 项目的数据文件夹
d----- utils        # 项目的工具文件夹
-a---- config.ini   # 项目的配置文件
-a---- main.py      # 项目的启动方法
-a---- requirements.txt

然后在 requirements.txt 文件中添加一行:

dearpygui

再通过 pip install -r requirements.txt 安装来自动 DearPyGUI

项目主窗口

我们在使用 DearPyGUI 时候会发现,启动时打开的页面是一个随机颜色的背板,因此,我们需要为项目创建一个主页,在 DearPyGUI 中的主页叫 primary_window 即主窗口,在 main.py 文件中,我们添加一下代码:

from dearpygui.core import *
from dearpygui.simple import *

with window('Main Window'):
    pass

if __name__ == "__main__":
    set_main_window_size(width=900, height=732)
    set_main_window_title('Dear Demo (Alpha Version)')
    start_dearpygui(primary_window='Main Window')

然后启动 main.py 文件,可以看到一个最简单的主窗口:

在这里插入图片描述
但是这样的主窗口好像不太好看,我们可以为它加上一张图片,在 utils 目录下创建一个 callback.py 文件,再创建一个 resources 文件夹,把图片文件重命名为 cover_image_pro.png 并存放到 resources 文件夹下,这时的项目结构如下:

\dear_demo          # 项目文件夹
d----- application  # 项目的应用文件夹
d----- data         # 项目的数据文件夹
d----- utils        # 项目的工具文件夹
d---------- resources
-a------------- cover_image_pro.png
-a--------- callback.py
-a---- config.ini   # 项目的配置文件
-a---- main.py      # 项目的启动方法
-a---- requirements.txt

然后在 callback.py 文件中编辑以下代码,添加一个 set_resize_callback 事件的监听回调函数:

from dearpygui.core import *

def on_set_primary_window_resize(sender, data):
    delete_item('Main Window Cover', children_only=True)
    add_drawing(
        name='Main Window Cover Image',
        width=get_main_window_size()[0],
        height=get_main_window_size()[1] - 100,
        parent='Main Window Cover'
    )
    draw_image(
        drawing='Main Window Cover Image',
        file='utils/resources/cover_image_pro.png',
        pmin=[get_main_window_size()[0] - 325, get_main_window_size()[1] - 100 - 282],
        pmax=[get_main_window_size()[0] - 50, get_main_window_size()[1] - 100],
        uv_min=[0, 0],
        uv_max=[1, 1]
    )

main.py 文件中也同步进行一些修改:

from dearpygui.core import *
from dearpygui.simple import *
from utils.callback import on_set_primary_window_resize  # 添加的代码

with window('Main Window'):
    with group('Main Window Cover', horizontal=True):  # 添加的代码
        pass                                           # 添加的代码

if __name__ == "__main__":
    set_main_window_size(width=900, height=732)
    set_main_window_title('Dear Demo (Alpha Version)')
    set_resize_callback(on_set_primary_window_resize, handler='Main Window')  # 添加的代码
    start_dearpygui(primary_window='Main Window')

这样,无论我们如何放大缩小页面,图片始终位于屏幕右下角:

在这里插入图片描述

项目主菜单

然后我们再加上一个 “Themes” 和 “Help” 菜单,这些都是 DearPyGUI 自带的方便功能,我们可以把它们整到一起去,方便我们调试用。在 utils 目录下创建一个 widgets.py 文件,创建完成后,项目结构如下:

\dear_demo          # 项目文件夹
d----- application  # 项目的应用文件夹
d----- data         # 项目的数据文件夹
d----- utils        # 项目的工具文件夹
d---------- resources
-a------------- cover_image_pro.png
-a--------- callback.py
-a--------- widgets.py
-a---- config.ini   # 项目的配置文件
-a---- main.py      # 项目的启动方法
-a---- requirements.txt

接下来我们在 widgets.py 文件中编写如下代码:

from dearpygui.core import *
from dearpygui.simple import *

def add_themes_and_help_menu(sender, data):
    with menu('Themes', parent=sender):
        add_menu_item("Dark", label='Dark (default)', callback=lambda sender, data: set_theme(sender), check=True)
        add_menu_item("Light", callback=lambda sender, data: set_theme(sender), check=True)
        add_menu_item("Classic", callback=lambda sender, data: set_theme(sender), check=True)
        add_menu_item("Dark 2", callback=lambda sender, data: set_theme(sender), check=True)
        add_menu_item("Grey", callback=lambda sender, data: set_theme(sender), check=True)
        add_menu_item("Dark Grey", callback=lambda sender, data: set_theme(sender), check=True)
        add_menu_item("Cherry", callback=lambda sender, data: set_theme(sender), check=True)
        add_menu_item("Purple", callback=lambda sender, data: set_theme(sender), check=True)
        add_menu_item("Gold", callback=lambda sender, data: set_theme(sender), check=True)
        add_menu_item("Red", callback=lambda sender, data: set_theme(sender), check=True)
    with menu('Help', parent=sender):
        add_menu_item('Show Logger', callback=show_logger)
        add_menu_item('Show About', callback=show_about)
        add_menu_item('Show Metrics', callback=show_metrics)
        add_menu_item('Show Documentation', callback=show_documentation)
        add_menu_item('Show Debug', callback=show_debug)
        add_menu_item('Show Style Editor', callback=show_style_editor)

然后在 main.py 文件中也同步添加一些代码:

from dearpygui.core import *
from dearpygui.simple import *
from utils.widgets import add_themes_and_help_menu                   # 添加的代码
from utils.callback import on_set_primary_window_resize

with window('Main Window'):
    with menu_bar('Main Menu Bar'):                                  # 添加的代码
        add_themes_and_help_menu(sender='Main Menu Bar', data=None)  # 添加的代码
    with group('Main Window Cover', horizontal=True):
        pass

if __name__ == "__main__":
    set_main_window_size(width=900, height=732)
    set_main_window_title('Dear Demo (Alpha Version)')
    set_resize_callback(on_set_primary_window_resize, handler='Main Window')
    start_dearpygui(primary_window='Main Window')

这样,我们就可以随意选择主题,快速打开 LoggerDebugStype Editor 等调试工具:

在这里插入图片描述

可拔插应用

我们可以用 可拔插 的方式在项目中快速添加一个应用,要实现这个功能,需要在 widgets.py 文件中添加一个自动寻找并添加应用到主菜单的方法:

import os  # 添加的代码
from dearpygui.core import *
from dearpygui.simple import *

def auto_add_application_to_menu(sender, data):  # 添加的方法
    application_dirs = []
    for file in os.listdir('application/'):
        application_dirs.append(file)
    application_menu = {}
    for application in application_dirs:
        exec(f'import application.{application}.views as {application}')
        exec(f'application_menu[{application}.app_menu_name]=[]')
    for application in application_dirs:
        exec(
            'application_menu[' + application + '.app_menu_name].append({"app":' + application + ',"name":' + application + '.app_menu_item_name})')
    for menu_k, menu_v in application_menu.items():
        with menu(f'{menu_k}##Main Menu', parent=sender):
            for _item in menu_v:
                add_menu_item(f'{_item["name"]}##Main Menu Item', callback=_item['app'].start_app)

def add_themes_and_help_menu(sender, data):
    # 省略代码

这个 auto_add_application_to_menu 方法会遍历 application/ 目录下的子目录,即可拔插应用的目录。然后再找到可拔插应用目录下的 views.py 文件,并根据 views.py 文件中的 app_menu_nameapp_menu_item_name 参数将当前应用上架到主窗口的菜单栏中。

同时,我们可以为这些可拔插应用提供一个通用的 on_close 回调,在 callback.py 文件中添加一个 on_close_callback 方法,用于用户关闭应用时的回调:

from dearpygui.core import *

def on_close_callback(sender, data):  # 添加的方法
    delete_item(sender)

def on_set_primary_window_resize(sender, data):
    # 省略代码

然后我们还要把 auto_add_application_to_menu 方法添加到 main.py 文件中:

from dearpygui.core import *
from dearpygui.simple import *
from utils.widgets import add_themes_and_help_menu, auto_add_application_to_menu  # 修改的代码
from utils.callback import on_set_primary_window_resize

with window('Main Window'):
    with menu_bar('Main Menu Bar'):
        auto_add_application_to_menu(sender='Main Menu Bar', data=None)  # 添加的代码
        add_themes_and_help_menu(sender='Main Menu Bar', data=None)
    with group('Main Window Cover', horizontal=True):
        pass

if __name__ == "__main__":
    # 省略代码

添加一个应用

我们以一个 “MD5加密工具” 为例,首先在在 application 目录下创建一个 encrypt_md5 文件夹,并在 encrypt_md5 文件夹下创建几个文件,views.pycallback.py、和 handle.py 三个文件,创建后项目结构如下:

\dear_demo          # 项目文件夹
d----- application  # 项目的应用文件夹
d---------- encrypt_md5
-a------------- views.py
-a------------- callback.py
-a------------- handle.py
d----- data         # 项目的数据文件夹
d----- utils        # 项目的工具文件夹
d---------- resources
-a------------- cover_image_pro.png
-a--------- callback.py
-a--------- widgets.py
-a---- config.ini   # 项目的配置文件
-a---- main.py      # 项目的启动方法
-a---- requirements.txt

然后我们先编辑 views.py 文件,在每一个应用的 views.py 文件中,必须要有 app_menu_nameapp_menu_item_nameapp_name 参数,还要有一个 start_app 方法,例如:

from dearpygui.simple import *
from utils.callback import on_close_callback
from .callback import *

app_menu_name = 'Tools'
app_menu_item_name = 'Encrypt MD5 Tools'
app_name = 'Encrypt MD5 Tools'

def start_app(sender, data):
    if not is_item_shown(app_name):
        add_app_window()

def add_app_window():
    with window(app_name, width=360, height=260, on_close=on_close_callback):
        add_input_text(f'Plaintext##{app_name}', default_value='Unencrypted Text', multiline=True)
        add_button(f'MD5 Encryption##{app_name}', callback=md5_encryption_callback,
                   callback_data=f'Plaintext##{app_name}')
        add_input_text(f'Upper 32##{app_name}')
        add_input_text(f'Lower 32##{app_name}')
        add_input_text(f'Upper 16##{app_name}')
        add_input_text(f'Lower 16##{app_name}')

接下来再编辑 callback.py 文件,我们在 callback.py 文件里要编写一个 md5_encryption_callback 方法,该方法对应 views.py 文件中的 “MD5 Encryption” 按钮:

import hashlib
from dearpygui.core import *

def md5_encryption_callback(sender, data):
    plaintext = get_value(data)
    m = hashlib.md5()
    m.update(plaintext.encode('utf-8'))
    app_name = sender.split("##")[1]
    set_value(f'Upper 32##{app_name}', m.hexdigest().upper())
    set_value(f'Lower 32##{app_name}', m.hexdigest().lower())
    set_value(f'Upper 16##{app_name}', m.hexdigest()[8:-8].upper())
    set_value(f'Lower 16##{app_name}', m.hexdigest()[8:-8].lower())

最后,我们直接就可以启动项目,会发现, “MD5加密工具” 自动的被找到 auto_add_application_to_menu 方法找到,并上架到主窗口的菜单栏:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

何小有

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值