Skip to main content

ImGui Bundle: easily create ImGui applications in Python and C++. Batteries included!

Project description

abc

ImGui Bundle: easily create ImGui applications in Python and C++. Batteries included!

sources doc manual

Introduction

About ImGui Bundle

ImGui Bundle is a bundle for Dear ImGui, including various powerful libraries from its ecosystem. It enables to easily create ImGui applications in C++ and Python, under Windows, macOS, and Linux. It is aimed at application developers, researchers, and beginner developers who want to quickly get started.

Interactive manual & demo in one click!

Click on the animated demonstration below to launch the fully interactive demonstration.

ImGui Bundle interactive demo
ImGui Bundle interactive demo

This demonstration is also an interactive manual, similar to the online ImGui Manual

Batteries included

ImGui Bundle includes the following libraries:

A big thank you to their authors for their awesome work!

Easily port your code between python and C++

The python bindings closely mirror the original C++ API, with fully typed bindings. The original code documentation is meticulously kept inside the python stubs. See for example the documentation for imgui , implot, and hello imgui

Thanks to this, code completion in your favorite python IDE works like a charm, and porting code between Python and C++ becomes easy.

Build and install instructions

Install for Python

Install from pypi

pip install imgui-bundle
pip install opencv-contrib-python 
  • in order to run the immvision module, install opencv-python or opencv-contrib-python

Note: under windows, you might need to install msvc redist.

Install from source:

git clone https://github.com/pthom/imgui_bundle.git
cd imgui_bundle
git submodule update --init --recursive 
pip install -v . 
pip install opencv-contrib-python
  • Since there are lots of submodules, this might take a few minutes

  • The build process might take up to 5 minutes

Run the python demo

Simply run imgui_bundle_demo.

The source for the demos can be found inside bindings/imgui_bundle/demos_python.

Consider imgui_bundle_demo as an always available manual for ImGui Bundle with lots of examples and related code source.

Install for C++

Integrate ImGui Bundle in your own project in 5 minutes

The easiest way to use ImGui Bundle in an external project is to use the example provided in example_integration. This folder includes everything you need to set up your own project with ImGui Bundle.

Build ImGui Bundle from source

If you choose to clone this repo, follow these instructions:

git clone https://github.com/pthom/imgui_bundle.git
cd imgui_bundle
git submodule update --init --recursive 
mkdir build
cd build
cmake .. -DIMMVISION_FETCH_OPENCV=ON 
make -j
  • Since there are lots of submodules, this might take a few minutes

  • The flag -DIMMVISION_FETCH_OPENCV=ON is optional. If set, a minimal version of OpenCV will be downloaded a compiled at this stage (this might require a few minutes)

The immvision module will only be built if OpenCV can be found. Otherwise, it will be ignored, and no error will be emitted.

If you have an existing OpenCV install, set its path via:

cmake .. -DOpenCV_DIR=/.../path/to/OpenCVConfig.cmake

Run the C++ demo

If you built ImGui Bundle from source, Simply run build/bin/demo_imgui_bundle.

The source for the demos can be found inside bindings/imgui_bundle/demos_cpp.

Consider demo_imgui_bundle as a manual with lots of examples and related code source. It is always available online

Usage instructions

Dear ImGui - Immediate GUI

Dear ImGui is an implementation of the Immediate Gui paradigm.

Consult the ImGui Manual

Dear ImGui comes with a complete demo. It demonstrates all the widgets, together with an example code on how to use them.

ImGui Manual is an easy way to consult this demo, and to see the corresponding code. The demo code is in C++, but read on for "Code advices" on how to translate from C++ to python.

Example

An example is often worth a thousand words, the following code:

C++

// Display a text
ImGui::Text("Counter = %i", app_state.counter);
ImGui::SameLine(); // by default ImGui starts a new line at each widget

// The following line displays a button
if (ImGui::Button("increment counter"))
    // And returns true if it was clicked: you can *immediately* handle the click
    app_state.counter += 1;

// Input a text: in C++, InputText returns a bool and modifies the text directly
bool changed = ImGui::InputText("Your name?", &app_state.name);
ImGui::Text("Hello %s!", app_state.name.c_str());

Python

# Display a text
imgui.text(f"Counter = {app_state.counter}")
imgui.same_line()  # by default ImGui starts a new line at each widget

# The following line displays a button
if imgui.button("increment counter"):
    # And returns true if it was clicked: you can *immediately* handle the click
    app_state.counter += 1

# Input a text: in python, input_text returns a tuple(modified, new_value)
changed, app_state.name = imgui.input_text("Your name?", app_state.name)
imgui.text(f"Hello {app_state.name}!")

Displays this:

immediate gui example

Hello ImGui - Starter pack

ImGui Bundle includes Hello ImGui, which is itself based on ImGui. "Hello ImGui" can be compared to a starter pack that enables to easily write cross-platform Gui apps for Windows, macOS, Linux, iOS, and emscripten.

API

See the "Hello ImGui" API doc. Also consult the doc on how to build DPI aware applications.

Features

  • Full multiplatform support: Windows, Linux, OSX, iOS, Emscripten, Android (poorly supported). See demo video

  • Power Save mode: reduce FPS when application is idle (see RunnerParams.fpsIdle)

  • DPI aware applications (widget placement, window size, font loading and scaling)

  • Theme tweaking (see demo video, and API )

  • Window geometry utilities: autosize, restore window position, full screen, etc. (see WindowGeometry)

  • Multiplatform assets embedding

  • Switch between Glfw or Sdl backend (see RunnerParams.backendType)

The usage of Hello ImGui is optional. You can also build an imgui application from scratch, in C++ or in python (see python example)

HelloImGui is fully configurable by POD (plain old data) structures. See their description

ImmApp - Immediate App

ImGui Bundle includes a library named ImmApp (which stands for Immediate App). ImmApp is a thin extension of HelloImGui that enables to easily initialize the ImGuiBundle addons that require additional setup at startup

API

C++ API

Python bindings

How to start an application with addons

Some libraries included by ImGui Bundle require an initialization at startup. ImmApp makes this easy via AddOnParams.

The example program below demonstrates how to run an application which will use implot (which requires a context to be created at startup), and imgui_md (which requires additional fonts to be loaded at startup).

C++

#include "immapp/immapp.h"
#include "imgui_md_wrapper/imgui_md_wrapper.h"
#include "implot/implot.h"
#include "demo_utils/api_demos.h"
#include <vector>
#include <cmath>


int main(int, char**)
{
    // This call is specific to the ImGui Bundle interactive manual. In a standard application, you could write:
    //         HelloImGui::SetAssetsFolder("my_assets"); // (By default, HelloImGui will search inside "assets")
    ChdirBesideAssetsFolder();

    constexpr double pi = 3.1415926535897932384626433;
    std::vector<double> x, y1, y2;
    for (double _x = 0; _x < 4 * pi; _x += 0.01)
    {
        x.push_back(_x);
        y1.push_back(std::cos(_x));
        y2.push_back(std::sin(_x));
    }

    auto gui = [x,y1,y2]()
    {
        ImGuiMd::Render("# This is the plot of _cosinus_ and *sinus*");  // Markdown
        if (ImPlot::BeginPlot("Plot"))
        {
            ImPlot::PlotLine("y1", x.data(), y1.data(), x.size());
            ImPlot::PlotLine("y2", x.data(), y2.data(), x.size());
            ImPlot::EndPlot();
        }
    };

    HelloImGui::SimpleRunnerParams runnerParams { .guiFunction = gui, .windowSize = {600, 400} };
    ImmApp::AddOnsParams addons { .withImplot = true, .withMarkdown = true };
    ImmApp::Run(runnerParams, addons);

    return 0;
}

Python:

import numpy as np
from imgui_bundle import implot, imgui_md, immapp
from imgui_bundle.demos_python import demo_utils


def main():
    # This call is specific to the ImGui Bundle interactive manual. In a standard application, you could write:
    #         hello_imgui.set_assets_folder("my_assets"); # (By default, HelloImGui will search inside "assets")
    demo_utils.set_hello_imgui_demo_assets_folder()

    x = np.arange(0, np.pi * 4, 0.01)
    y1 = np.cos(x)
    y2 = np.sin(x)

    def gui():
        imgui_md.render("# This is the plot of _cosinus_ and *sinus*")  # Markdown
        if implot.begin_plot("Plot"):
            implot.plot_line("y1", x, y1)
            implot.plot_line("y2", x, y2)
            implot.end_plot()

    immapp.run(gui, with_implot=True, with_markdown=True, window_size=(600, 400))


if __name__ == "__main__":
    main()

Using ImGui Bundle with jupyter notebook

ImmApp adds support for integration inside jupyter notebook: the application will be run in an external window, and a screenshot will be placed on the notebook after execution.

This requires a window server, and will not run on google collab.

Below is a screenshot, that you can test by running jupyter notebook inside bindings/imgui_bundle/demos_python/notebooks

immapp notebook example

40 seconds demo video on Youtube

API:

immapp/immapp_notebook.py

C++ / Python porting advices

General advices

ImGui is a C++ library that was ported to Python. In order to work with it, you will often refer to its manual, which shows example code in C++.

In order to translate from C++ to Python:

  1. Change the function names and parameters' names from CamelCase to snake_case

  2. Change the way the output are handled.

    1. in C++ ImGui::RadioButton modifies its second parameter (which is passed by address) and returns true if the user clicked the radio button.

    2. In python, the (possibly modified) value is transmitted via the return: imgui.radio_button returns a Tuple[bool, str] which contains (user_clicked, new_value).

  3. if porting some code that uses static variables, use the @immapp.static decorator. In this case, this decorator simply adds a variable value at the function scope. It is preserved between calls. Normally, this variable should be accessed via demo_radio_button.value, however the first line of the function adds a synonym named static for more clarity. Do not overuse them! Static variable suffer from almost the same shortcomings as global variables, so you should prefer to modify an application state.

Example:

C++

void DemoRadioButton()
{
    static int value = 0;
    ImGui::RadioButton("radio a", &value, 0); ImGui::SameLine();
    ImGui::RadioButton("radio b", &value, 1); ImGui::SameLine();
    ImGui::RadioButton("radio c", &value, 2);
}

Python

@immapp.static(value=0)
def demo_radio_button():
    static = demo_radio_button
    clicked, static.value = imgui.radio_button("radio a", static.value, 0)
    imgui.same_line()
    clicked, static.value = imgui.radio_button("radio b", static.value, 1)
    imgui.same_line()
    clicked, static.value = imgui.radio_button("radio c", static.value, 2)

Enums and TextInput

In the example below, two differences are important:

InputText functions:

imgui.input_text (Python) is equivalent to ImGui::InputText (C++)

  • In C++, it uses two parameters for the text: the text pointer, and its length.

  • In Python, you can simply pass a string, and get back its modified value in the returned tuple.

Enums handling:

  • ImGuiInputTextFlags_ (C++) corresponds to imgui.InputTextFlags_ (python) and it is an enum (note the trailing underscore).

  • ImGuiInputTextFlags (C++) corresponds to imgui.InputTextFlags (python) and it is an int (note: no trailing underscore)

You will find many similar enums.

The dichotomy between int and enums, enables you to write flags that are a combinations of values from the enum (see example below).

Example

C++

void DemoInputTextUpperCase()
{
    static char text[64] = "";
    ImGuiInputTextFlags flags = (
        ImGuiInputTextFlags_CharsUppercase
        | ImGuiInputTextFlags_CharsNoBlank
    );
    /*bool changed = */ ImGui::InputText("Upper case, no spaces", text, 64, flags);
}

Python

@immapp.static(text="")
def demo_input_text_decimal() -> None:
    static = demo_input_text_decimal
    flags:imgui.InputTextFlags = (
            imgui.InputTextFlags_.chars_uppercase.value
          | imgui.InputTextFlags_.chars_no_blank.value
        )
    changed, static.text = imgui.input_text("Upper case, no spaces", static.text, flags)

Note: in C++, by using imgui_stdlib.h, it is also possible to write:

#include "imgui/misc/cpp/imgui_stdlib.h"

void DemoInputTextUpperCase_StdString()
{
    static std::string text;
    ImGuiInputTextFlags flags = (
        ImGuiInputTextFlags_CharsUppercase
        | ImGuiInputTextFlags_CharsNoBlank
    );
    /*bool changed = */ ImGui::InputText("Upper case, no spaces", &text, flags);
}

Advanced glfw callbacks

When using the glfw backend, you can set advanced callbacks on all glfw events.

Below is an example that triggers a callback whenever the window size is changed:

import imgui_bundle
import glfw   # always import glfw *after* imgui_bundle!!!


# define a callback
def my_window_size_callback(window: glfw._GLFWwindow, w: int, h: int):
    print(f"Window size changed to {w}x{h}")


# Get the glfw window used by hello imgui
window = imgui_bundle.glfw_window_hello_imgui()
glfw.set_window_size_callback(window, my_window_size_callback)

It is important to import glfw after imgui_bundle, since - upon import - imgui_bundle informs glfw that it shall use its own version of the glfw dynamic library.

Closing words

Who is this project for

As mentioned in the intro,

ImGui Bundle is a bundle for Dear ImGui, including various powerful libraries from its ecosystem. It enables to easily create ImGui applications in C++ and Python, under Windows, macOS, and Linux. It is aimed at application developers, researchers, and beginner developers who want to quickly get started.

ImGui Bundle aims to make applications prototyping fast and easy, in a multiplatform / multi-tooling context. The intent is to reduce the time between an idea and a first GUI prototype down to almost zero.

It is well adapted for

  • developers and researchers who want to switch easily between and research and development environment by facilitating the port of research artifacts

  • beginners and developers who want to quickly develop an application without learning a GUI framework

Who is this project not for

You should prefer a more complete framework (such as Qt for example) if your intent is to build a fully fledged application, with support for internationalization, advanced styling, etc.

Also, ImGui Bundle makes no guarantee of ABI stability, and its API is opened to slight adaptations and breaking changes if they are found to make the overall usage better and/or safer.

Acknowledgments

ImGui Bundle would not be possible without the work of the authors of "Dear ImGui", and especially Omar Cornut.

It also includes a lot of other projects, and I’d like to thank their authors for their awesome work!

A particular mention for Evan Pezent (author of ImPlot), Cédric Guillemet (author of ImGuizmo), Balázs Jákó (author of ImGuiColorTextEdit), and Michał Cichoń (author of imgui-node-editor), and Dmitry Mekhontsev (author of imgui-md), Andy Borrel (author of imgui-tex-inspect, another image debugging tool, which I discovered long after having developed immvision).

This doc was built using Asciidoc.

Immvision was inspired by The Image Debugger, by Bill Baxter.

License

The MIT License (MIT)

Copyright (c) 2021-2023 Pascal Thomet

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Alternatives

pyimgui provides battle-tested comprehensive python bindings for ImGui. I worked with this project a lot, and contributed a bit to it. In the end, I had to develop a separate project, in order to be able to add auto-generated and auto-documented python modules.

Dear PyGui (repository) provides python bindings for ImGui with a lot of addons, and a more pythonesque API, which makes it perhaps more suited for Python only projects.

About the author

ImGui Bundle is developed by Pascal Thomet. I am reachable on my Github page. I sometimes blog. There is a playlist related to ImGui Bundle on YouTube.

I have a past in computer vision, and a lot of experience in the trenches between development and research teams; and I found ImGui to be a nice way to reduce the delay between a research prototype and its use in production code.

I also have an inclination for self documenting code, and the doc you are reading was a way to explore new ways to document projects.

How is ImGui Bundle developed

The development of the initial version of ImGui Bundle took about one year at full time.

The bindings are auto-generated thanks to an advanced parser, so that they are easy to keep up to date. I’ll give more information about the bindings generator a bit later in 2023.

Please be tolerant if you find issues! ImGui Bundle is developed for free, under a very permissive license, by one main author (and most of its API comes from external libraries).

If you need consulting about ImGui Bundle or about the bindings generator in the context of a commercial project, please contact me by email.

History

Three of my past projects gave me the idea to develop this library.

  • ImGui Manual, an interactive manual for Dear ImGui, which I developed in June 2020

  • implot demo which I developed in 2020.

  • imgui_datascience, a python package I developed in 2018 for image analysis and debugging. Its successor is immvision.

Developments for ImGui Bundle and its related automatic binding generator began in january 2022.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

imgui-bundle-0.8.2.tar.gz (55.8 MB view hashes)

Uploaded Source

Built Distributions

imgui_bundle-0.8.2-cp311-cp311-win_amd64.whl (65.8 MB view hashes)

Uploaded CPython 3.11 Windows x86-64

imgui_bundle-0.8.2-cp311-cp311-musllinux_1_1_x86_64.whl (47.4 MB view hashes)

Uploaded CPython 3.11 musllinux: musl 1.1+ x86-64

imgui_bundle-0.8.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (47.1 MB view hashes)

Uploaded CPython 3.11 manylinux: glibc 2.17+ x86-64

imgui_bundle-0.8.2-cp311-cp311-macosx_11_0_x86_64.whl (45.6 MB view hashes)

Uploaded CPython 3.11 macOS 11.0+ x86-64

imgui_bundle-0.8.2-cp310-cp310-win_amd64.whl (63.2 MB view hashes)

Uploaded CPython 3.10 Windows x86-64

imgui_bundle-0.8.2-cp310-cp310-musllinux_1_1_x86_64.whl (33.8 MB view hashes)

Uploaded CPython 3.10 musllinux: musl 1.1+ x86-64

imgui_bundle-0.8.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (33.1 MB view hashes)

Uploaded CPython 3.10 manylinux: glibc 2.17+ x86-64

imgui_bundle-0.8.2-cp310-cp310-macosx_11_0_x86_64.whl (32.0 MB view hashes)

Uploaded CPython 3.10 macOS 11.0+ x86-64

imgui_bundle-0.8.2-cp39-cp39-win_amd64.whl (60.6 MB view hashes)

Uploaded CPython 3.9 Windows x86-64

imgui_bundle-0.8.2-cp39-cp39-musllinux_1_1_x86_64.whl (20.1 MB view hashes)

Uploaded CPython 3.9 musllinux: musl 1.1+ x86-64

imgui_bundle-0.8.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (19.2 MB view hashes)

Uploaded CPython 3.9 manylinux: glibc 2.17+ x86-64

imgui_bundle-0.8.2-cp39-cp39-macosx_11_0_x86_64.whl (18.4 MB view hashes)

Uploaded CPython 3.9 macOS 11.0+ x86-64

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page