几天前,我开始学习 DearPyGui 框架,对速度和结果感到兴奋。然而,当我尝试实现图像的拖放功能时遇到了挑战。用法似乎很简单,因为方法
add_image
和 add_image_button
有 drag_callback
和 drop_callback
参数,但无论我尝试什么都不起作用。
我在官方文档中搜索了解决方案,但没有成功 - 关于拖放的文章不多。我还寻找了现成的解决方案,发现只有 this 似乎可以从应用程序外部拖放文本,但它不能解决我的问题,我需要在同一窗口内的元素之间拖放图像。
我正在 Windows 机器 和 Python 3.9.13 上使用最新的 DearPyGui 1.11.1。 图像已创建,但我无法触发
drag_callback
或 drop_callback
事件。对于测试,我将 callback=click_callback
参数添加到 add_image_button
函数并且它起作用了。看起来这个方法可行,只是我缺少一些东西。
下面是我的方法的简化变体 - 它自动创建图像来测试代码:
import dearpygui.dearpygui as dpg
def get_image(width, height, red, green, blue, alpha):
"""Generates simple image"""
return [red, green, blue, alpha] * width * height
def drag_callback(sender, app_data):
print(f"Starting drag from {sender}") # Never comes here
def drop_callback(sender, app_data):
print(f"Dropped from {sender}") # Never comes here
def create_image(image_data, width, height, image_tag, texture_tag):
with dpg.texture_registry():
texture_id = dpg.add_static_texture(width, height, image_data, tag=texture_tag)
# Add the image with drag and drop functionality
dpg.add_image_button(texture_id, tag=image_tag, payload_type="image_payload", drag_callback=drag_callback,
drop_callback=drop_callback)
if __name__ == '__main__':
dpg.create_context()
print(f"DPG version {dpg.get_dearpygui_version()}") # DPG version 1.11.1
# Create a window
with dpg.window(label="Image Drag-and-Drop", tag="DragDropWindow", width=800, height=600, no_close=True,
no_collapse=True):
width = 100
height = 100
img1 = get_image(width, height, 1, 0, 1, 1)
img2 = get_image(width, height, 0, 1, 0, 1)
# Create draggable images with unique tags for both group and texture
create_image(img1, width, height, "Image1", "ImageTexture1")
create_image(img2, width, height, "Image2", "ImageTexture2")
# Setup and show viewport
dpg.create_viewport(title="Main", width=800, height=600)
dpg.setup_dearpygui()
dpg.show_viewport()
dpg.start_dearpygui()
# Clean up
dpg.destroy_context()
经过长时间的互联网搜索终于找到了解决方案。
您必须添加以下两行:
def create_image(image_data, width, height, image_tag, texture_tag):
with dpg.texture_registry():
texture_id = dpg.add_static_texture(width, height, image_data, tag=texture_tag)
# Add the image with drag and drop functionality
dpg.add_image_button(texture_id, tag=image_tag, payload_type="image_payload", drag_callback=drag_callback, drop_callback=drop_callback)
# add this to enable drap&drop:
with dpg.drag_payload(parent=image_tag, drag_data="dragdata", payload_type="image_payload"):
dpg.add_text("popup drag")