pyimgui / pyimgui Goto Github PK
View Code? Open in Web Editor NEWCython-based Python bindings for dear imgui
Home Page: https://pyimgui.readthedocs.io
License: BSD 3-Clause "New" or "Revised" License
Cython-based Python bindings for dear imgui
Home Page: https://pyimgui.readthedocs.io
License: BSD 3-Clause "New" or "Revised" License
After fixing the typos described in #70, I ran into the following error when running the SDL2 example (Windows 10, latest SDL2.dll):
Traceback (most recent call last):
File "C:/Users/admin/PycharmProjects/BotW-World-Editor/main.py", line 103, in <module>
main()
File "C:/Users/admin/PycharmProjects/BotW-World-Editor/main.py", line 12, in main
renderer = SDL2Renderer(window)
File "C:\Users\admin\PycharmProjects\botwenv\lib\site-packages\imgui\integrations\sdl2.py", line 17, in __init__
super(SDL2Renderer, self).__init__()
File "C:\Users\admin\PycharmProjects\botwenv\lib\site-packages\imgui\integrations\opengl.py", line 90, in __init__
super(ProgrammablePipelineRenderer, self).__init__()
File "C:\Users\admin\PycharmProjects\botwenv\lib\site-packages\imgui\integrations\opengl.py", line 18, in __init__
self._create_device_objects()
File "C:\Users\admin\PycharmProjects\botwenv\lib\site-packages\imgui\integrations\opengl.py", line 115, in _create_device_objects
last_array_buffer = gl.glGetIntegerv(gl.GL_ARRAY_BUFFER_BINDING)
File "C:\Users\admin\PycharmProjects\botwenv\lib\site-packages\OpenGL\latebind.py", line 41, in __call__
return self._finalCall( *args, **named )
File "C:\Users\admin\PycharmProjects\botwenv\lib\site-packages\OpenGL\wrapper.py", line 664, in wrapperCall
raise err
File "C:\Users\admin\PycharmProjects\botwenv\lib\site-packages\OpenGL\wrapper.py", line 657, in wrapperCall
result = wrappedOperation( *cArguments )
File "C:\Users\admin\PycharmProjects\botwenv\lib\site-packages\OpenGL\error.py", line 232, in glCheckError
baseOperation = baseOperation,
OpenGL.error.GLError: GLError(
err = 1280,
description = b'invalid enumerant',
baseOperation = glGetIntegerv,
pyArgs = (
GL_ARRAY_BUFFER_BINDING,
<object object at 0x000001E27D030110>,
),
cArgs = (
GL_ARRAY_BUFFER_BINDING,
<OpenGL.arrays.ctypesarrays.c_long_Array_1 object at 0x000001E27FA6C7C8>,
),
cArguments = (
GL_ARRAY_BUFFER_BINDING,
<OpenGL.arrays.ctypesarrays.c_long_Array_1 object at 0x000001E27FA6C7C8>,
)
)
Process finished with exit code 1
Classes in the impl
subpackage are currently very inconsistent and duplicate a lot of code. Also it is not clear how they shoud be used/created/extended. We should definitely improve this before the first release because they are the entry point to the pyimgui library.
Things to do:
impl
subpackageimpl
classes and decide how to handle extra dependencies for them (using extra_requires
?)doc/examples
impl
classes and also stabilise their APIimpl
classesHey,
I am trying to draw a diagram in pyimgui but I cannot find any document or wiki about the function like PlotLine in C++? is it exist or not?
Right now we use explicit markup in pxd file to track completion progress but we could see how many of symbols from imgui object file is already used. I think nm might be a good tool for this.
Only for pure Python code. We will deal with Cython sources later.
Discussion started in #18.
Hello,
This is not an issue, rather a way to acknowledge the quality of your package :-)
I have been working with pyimgui for several months.
As I work in the computer vision field, I needed a way to be able to display images from numpy and opencv (display & inspect images, have a way too start imgui simply, etc.). So I built some tools on top of pyimgui, and I have been using them since then.
In this context, pyimgui has proven to be extremely usable and reliable. Many thanks!
Then, I decided to try and make a pip package from those tools: would you mind having a look at it and telling me your honest opinion?
Here is a link to it : https://github.com/pthom/imgui_datascience
I have tested it with python 2 & 3, under linux, windows and osx.
Regards,
Pascal Thomet
PS : please bear in mind that this is my first experience with distributing a python package (which is quite a complex process, as I discovered). There might be some gotchas.
Follow up to #62.
These are deprecated and should be removed in next major release (i.e. 1.0.0
).
Problem
Unfortunately dear-imgui API uses inout arguments very often. Python does not allow for such calling convention. So it is very hard to wire together imgui windows and widgets in the same way like in C++.
General idea
We could introduce some abstract base class that could be used in place of existing inout argument handling:
import abc
class InOutABC(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def set(self, value):
pass
@abc.abstractmethod
def get(self):
pass
@classmethod
def __subclasshook__(cls, C):
if cls is InOutABC:
if (
any("set" in B.__dict__ for B in C.__mro__) and
any("get" in B.__dict__ for B in C.__mro__)
):
return True
return NotImplemented
Usage
Then user could create his own signal-like class that would handle his inout argument data and could be used in imgui function calls without inconvenient tuple unpacking and multiple variable assignments:
class InOutWire(object):
def __init__(self, value):
self._value = value
def set(self, value):
self._value = value
def get(self):
return self._value
Such InOutWire
could be used to easily glue together different widgets:
checked = InOutWire(False)
while True:
imgui_ctx.new_frame()
if imgui.checkbox("c1", checked)[0]:
print "c1.clicked", checked.get()
if imgui.checkbox("c2", checked)[0]:
print "c2.clicked", checked.get()
# ...
User could even create general objects to provide auto-generated inout arguments without the need to:
from collections import defaultdict
wires = defaultdict(lambda: Wire(False))
while True:
imgui_ctx.new_frame()
if imgui.checkbox("c1", wires['checked'])[0]:
print "c1.clicked", wires['checked'].get()
if imgui.checkbox("c2", wires['checked'])[0]:
print "c2.clicked", wires['checked'].get()
Implementation details
Having the abstract base class InOutABC
we can check if provided possible inout arguments have the compatible interface (set()
/get()
methods). We need to do that test in every function that will allow for such feature. Example implementation:
def checkbox(str label, state):
cdef cimgui.bool inout_mode = isinstance(state, InOutABC)
cdef cimgui.bool inout_state = state.get() if inout_mode else state
result = cimgui.Checkbox(_bytes(label), &inout_state)
if inout_mode:
state.set(inout_state)
return result, inout_state
Sadly this will require a lot of boilerplate and code changes. The ideal solution would be to have kind of decorator that can translate between ordinary/inout arguments. Inside of wrapped functions we could then always expect either InOutABC
-compatible objects or simple flat arguments.
The trouble is that right now we allow arguments that are "inout" in the C++ layer to be both positional and keyword. In such situation I don't know how do provide such decorator that would manipulate arguments without introspecting function signatures with inspect
. This would be easier if we would assume that inout arguments are always keyword-only. Good news is that Cython allows to have keyword-only arguments even on Python 2 and even without default values.
Example implementation and usage:
from functools import wraps
def allow_inout(kwarg_name, result_pos=1):
def wrapper(func):
@wraps(func)
def wrapped(*args, **kwargs):
kwarg = kwargs.get(kwarg_name, None)
inout_mode = isinstance(kwarg, InOutABC)
if inout_mode:
kwargs[kwarg_name]=kwarg.get()
result_tuple = func(*args, **kwargs)
if inout_mode:
kwarg.set(result_tuple[result_pos])
return result_tuple
return wrapped
return wrapper
@allow_inout('state')
def checkbox(str label, *, state):
cdef cimgui.bool inout_state = state
return cimgui.Checkbox(_bytes(label), &inout_state), inout_state
Further improvements
Common idiom in imgui is to always check result of widget call using if
to process user interaction. For every function that defines a widget and uses inout arguments we return a tuple. This means that some widgets will require result value indexing and some will not e.g:
if imgui.button("some button"):
print("user interaction")
if imgui.checkbox("some checkbox", False)[0]
print("user interaction")
This makes the API usage inconsistent. We could improve this by replacing simple return tuple with object that will take into account only the value during bool
test e.g:
class InteractionTuple(tuple):
def __bool__(self):
return bool(self[0])
The downside: changes user expectation on tuple truth value. Other way around is to inverse whole problem. We could replace every return value that means user interaction or widget visibility with an object that clearly describes what are expectations about "True value". Example:
class InteractionTuple(tuple):
def __bool__(self):
raise ValueError
@property
def clicked(self)
return bool(self[0])
class VisibilityTuple(tuple):
def __bool__(self):
raise ValueError
@property
def visible(self)
return bool(self[0])
@property
def expanded(self)
return bool(self[0])
# usage
if begin("my window").visible: # alternatively: .expanded
...
if imgui.checkbox("my checkbox").clicked:
...
Hey,
I'm trying to install the pre-release version here https://pypi.org/project/imgui/1.0.0a1/ to get is_mouse_clicked
. I first uninstalled the version I had in my virtualenv, and then:
pip install imgui==1.0.0a1
pip install --pre imgui
pip install --pre imgui==1.0.0a1
Any ideas?
//edit I'm on OSX El Capitan 10.11.4. I'm looking at the files, and it looks like there's just macosx_10_12
. When I download that macosx wheel and install I get:
$ pip install files/imgui-1.0.0a1-cp36-cp36m-macosx_10_12_x86_64.whl
imgui-1.0.0a1-cp36-cp36m-macosx_10_12_x86_64.whl is not a supported wheel on this platform.
But when I look at https://pypi.org/project/imgui/0.1.0/#files it has the same mac version.
Could you add the source .tar.gz
that 0.1.0
has to the pre-release? Maybe my pip installs via that?
Add nightly builds using
One of the classic example apps for GUI frameworks are todo apps. Let's write one in pyimgui! (Extends from #45 )
It'd be cool if we could write the todo app in a way that the user could choose which backend. Like:
> python doc/examples/todo_app.py
# runs with pygame by default
> python doc/examples/todo_app.py --backend=sdl2
# runs with pysdl2
In the wiki, there's this todo item: https://github.com/swistakm/pyimgui/wiki
Do we still need to do this? @swistakm can you elaborate on what work would be involved with that?
It would be nice to have animated visual examples for some interactive widgets (buttons, dropdowns etc.)
It should be easy to implement in our of-screen documentation renderer because Pillow allows for simple and easy creation of GIFs (see: https://pillow.readthedocs.io/en/latest/handbook/image-file-formats.html#gif).
I tried compiling in pypy and hit a bug which I reported to them -
https://bitbucket.org/pypy/pypy/issues/2626/invalid-conversion-from-const-char-to-char
This bug is a reminder to try compiling pyimgui with pypy again once the bug is fixed, and then add it to pyimgui properly
Project does not build on Cython==0.28.* probably due to some changes in typing:
$ pip install -e .
Obtaining file:///Users/swistakm/dev/pyimgui
Complete output from command python setup.py egg_info:
Error compiling Cython file:
------------------------------------------------------------
...
"""
cimgui.EndMenu()
def menu_item(
str name, str shortcut=None, cimgui.bool selected=None, enabled=True
^
------------------------------------------------------------
imgui/core.pyx:2029:54: Cannot assign None to bool
Compiling imgui/core.pyx because it depends on /Users/swistakm/.envs/pyimgui/lib/python2.7/site-packages/Cython/Includes/libcpp/__init__.pxd.
[1/1] Cythonizing imgui/core.pyx
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/Users/swistakm/dev/pyimgui/setup.py", line 146, in <module>
compiler_directives=compiler_directives, **cythonize_opts
File "/Users/swistakm/.envs/pyimgui/lib/python2.7/site-packages/Cython/Build/Dependencies.py", line 1026, in cythonize
cythonize_one(*args)
File "/Users/swistakm/.envs/pyimgui/lib/python2.7/site-packages/Cython/Build/Dependencies.py", line 1146, in cythonize_one
raise CompileError(None, pyx_file)
Cython.Compiler.Errors.CompileError: imgui/core.pyx
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /Users/swistakm/dev/pyimgui/
It fortunately still builds on previous releases (till 0.27.3). pyimgui is mostly distributed as a built wheel so the problem isn't that critical but it would be nice to fix it soon.
This is follow-up to #57
Hi,
As per the title, both the drag_float
and drag_int
controls don't appear to respect the min and max bounds set in code. Is this a known issue?
I'm using python3.6 with pyimgui 0.0.2 (installed from pip).
My pyimgui code looks like this:
imgui.begin("Test controls", True)
_, int_value = imgui.drag_int("drag int", int_value, min_value=0, max_value=10)
_, float_value = imgui.drag_float("drag float", float_value, min_value=0.0, max_value=10.0)
imgui.end()
And full example code is below:
# -*- coding: utf-8 -*-
from sdl2 import *
import ctypes
import OpenGL.GL as gl
import imgui
from imgui.integrations.sdl2 import SDL2Renderer
def main():
window, gl_context = impl_pysdl2_init()
renderer = SDL2Renderer(window)
running = True
event = SDL_Event()
int_value = 5
float_value = 5.3
while running:
while SDL_PollEvent(ctypes.byref(event)) != 0:
if event.type == SDL_QUIT:
running = False
break
renderer.process_event(event)
renderer.process_inputs()
imgui.new_frame()
imgui.begin("Test controls", True)
_, int_value = imgui.drag_int("drag int", int_value, min_value=0, max_value=10)
_, float_value = imgui.drag_float("drag float", float_value, min_value=0.0, max_value=10.0)
imgui.end()
gl.glClearColor(0.2, 0.2, 0.2, 0.2)
gl.glClear(gl.GL_COLOR_BUFFER_BIT)
imgui.render()
SDL_GL_SwapWindow(window)
renderer.shutdown()
SDL_GL_DeleteContext(gl_context)
SDL_DestroyWindow(window)
SDL_Quit()
def impl_pysdl2_init():
width, height = 1280, 720
window_name = "minimal ImGui/SDL2 example"
if SDL_Init(SDL_INIT_EVERYTHING) < 0:
print("Error: SDL could not initialize! SDL Error: " + SDL_GetError())
exit(1)
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1)
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24)
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8)
SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1)
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1)
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 16)
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG)
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4)
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1)
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE)
SDL_SetHint(SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK, b"1")
SDL_SetHint(SDL_HINT_VIDEO_HIGHDPI_DISABLED, b"1")
window = SDL_CreateWindow(window_name.encode('utf-8'),
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
width, height,
SDL_WINDOW_OPENGL|SDL_WINDOW_RESIZABLE)
if window is None:
print("Error: Window could not be created! SDL Error: " + SDL_GetError())
exit(1)
gl_context = SDL_GL_CreateContext(window)
if gl_context is None:
print("Error: Cannot create OpenGL Context! SDL Error: " + SDL_GetError())
exit(1)
SDL_GL_MakeCurrent(window, gl_context)
if SDL_GL_SetSwapInterval(1) < 0:
print("Warning: Unable to set VSync! SDL Error: " + SDL_GetError())
exit(1)
return window, gl_context
if __name__ == "__main__":
main()
Thanks,
Jeremy
This is now obsolete and tests are run with py.test
Issue found in #24.
As suggested by @ccanepa on Cocos2d mailing group:
while the example does a good job showing the wide offering, it exposes something that is entirely built on the other side of the bind. An additional, much simpler but non trivial example built in the python side would help to grasp how to compose the window.
Hi there!
I can't get the image_button to return true. If I change my code to use a "normal" button, everything works fine, but the image_button seems to be broken in pyimgui.
if (imgui.image_button(texture, width, height)):
# shows the image, but never prints "Yay"
print("Yay")
...
if (imgui.button("test")):
# Obviously no image, but prints "Yay" when clicked
print("Yay")
I don't think I'm doing something wrong. Can you confirm this issue?
Hi,
I just tried to run this on OSX yosemite, and it crashed almost immediately. LLDB traceback is below:
$ lldb python
(lldb) target create "python"
Current executable set to 'python' (x86_64).
(lldb) r
Process 33324 launched: '/Users/jeremy/anaconda/bin/python' (x86_64)
Python 3.5.2 |Anaconda 4.0.0 (x86_64)| (default, Jul 2 2016, 17:52:12)
[GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import imgui
>>> def do():
... imgui.begin("my window")
... imgui.end()
...
>>> do()
libc++abi.dylib: terminating with uncaught exception of type char const*
Process 33324 stopped
* thread #1: tid = 0xd6592b, 0x00007fff81be0286 libsystem_kernel.dylib`__pthread_kill + 10, queue = 'com.apple.main-thread', stop reason = signal SIGABRT
frame #0: 0x00007fff81be0286 libsystem_kernel.dylib`__pthread_kill + 10
libsystem_kernel.dylib`__pthread_kill:
-> 0x7fff81be0286 <+10>: jae 0x7fff81be0290 ; <+20>
0x7fff81be0288 <+12>: movq %rax, %rdi
0x7fff81be028b <+15>: jmp 0x7fff81bdbc53 ; cerror_nocancel
0x7fff81be0290 <+20>: retq
(lldb) bt
* thread #1: tid = 0xd6592b, 0x00007fff81be0286 libsystem_kernel.dylib`__pthread_kill + 10, queue = 'com.apple.main-thread', stop reason = signal SIGABRT
* frame #0: 0x00007fff81be0286 libsystem_kernel.dylib`__pthread_kill + 10
frame #1: 0x00007fff89ba49f9 libsystem_pthread.dylib`pthread_kill + 90
frame #2: 0x00007fff89d6b9a3 libsystem_c.dylib`abort + 129
frame #3: 0x00007fff82bafa21 libc++abi.dylib`abort_message + 257
frame #4: 0x00007fff82bd79d1 libc++abi.dylib`default_terminate_handler() + 267
frame #5: 0x00007fff85c817eb libobjc.A.dylib`_objc_terminate() + 124
frame #6: 0x00007fff82bd50a1 libc++abi.dylib`std::__terminate(void (*)()) + 8
frame #7: 0x00007fff82bd4b30 libc++abi.dylib`__cxa_throw + 121
frame #8: 0x0000000101b3abd9 core.cpython-35m-darwin.so`__py_assert(msg=<unavailable>) + 57 at py_imconfig.cpp:26
frame #9: 0x0000000101af86bd core.cpython-35m-darwin.so`ImGui::Begin(name="my window", p_open=0x0000000000000000, size_on_first_use=0x00007fff5bfff1f8, bg_alpha=-1, flags=0) + 93 at imgui.cpp:3780
frame #10: 0x0000000101af319b core.cpython-35m-darwin.so`ImGui::Begin(name=<unavailable>, p_open=<unavailable>, flags=<unavailable>) + 43 at imgui.cpp:3772
frame #11: 0x0000000101abea72 core.cpython-35m-darwin.so`__pyx_pw_5imgui_4core_19begin(_object*, _object*, _object*) [inlined] __pyx_pf_5imgui_4core_18begin(_object*, _object*, _object*, int) + 11 at core.cpp:14846
frame #12: 0x0000000101abea67 core.cpython-35m-darwin.so`__pyx_pw_5imgui_4core_19begin(__pyx_self=<unavailable>, __pyx_args=<unavailable>, __pyx_kwds=<unavailable>) + 423 at core.cpp:14797
frame #13: 0x000000010004fe5c libpython3.5m.dylib`PyCFunction_Call + 60
frame #14: 0x00000001000bd2df libpython3.5m.dylib`PyEval_EvalFrameEx + 22431
frame #15: 0x00000001000c192f libpython3.5m.dylib`fast_function + 207
frame #16: 0x00000001000bd434 libpython3.5m.dylib`PyEval_EvalFrameEx + 22772
frame #17: 0x00000001000c10c3 libpython3.5m.dylib`_PyEval_EvalCodeWithName + 1779
frame #18: 0x00000001000b7ac1 libpython3.5m.dylib`PyEval_EvalCode + 81
frame #19: 0x00000001000e642c libpython3.5m.dylib`PyRun_InteractiveOneObject + 588
frame #20: 0x00000001000e5d5e libpython3.5m.dylib`PyRun_InteractiveLoopFlags + 206
frame #21: 0x00000001000e5c5c libpython3.5m.dylib`PyRun_AnyFileExFlags + 60
frame #22: 0x00000001000fcd47 libpython3.5m.dylib`Py_Main + 3591
frame #23: 0x0000000100000dc7 python`main + 215
frame #24: 0x0000000100000ce4 python`start + 52
(lldb)
We use Markdown for the README and convert it dynamically during distribution of the package.
The problem is: locally we can build only sdist. Other packages are collected as semi-artifacts from Travis CI and AppVeyor. It means that we cannot expect yet that Markdown will be properly converted to rst during builds in these systems. If we upload all package wheels and sdist in bunch then the version metadata will be taken from first uploaded distribution. If it is a wheel built without pypandoc
the long description will not be rendered properly (see version 0.0.1). I have used to just re-upload package metadata for given version in other projects but this is not possible anymore (see pypi/warehouse#2170).
Right now we can upload rst-converted sdist first and only then upload the rest of distributions. Unfortunately, once we do a mistake there is only one solution: version bump and another upload. This of course isn't a long term solution as it leads to unjustified version inflation.
Here are my first ideas:
Makefile
target: If we ensure that sdist is uploaded before wheels we have solved the problem.pandoc
and pypandoc
are available on all build environments: this may be tricky, especially in Docker environment for manylinux1
builds on Travis.Vispy could be a good one to integrate with, especially since it can work in jupyter notebooks.
Hello,
I had a problem when running any variant of pip install integrations with zsh:
pip install imgui[pygame]
zsh: no matches found: imgui[pygame]
With good old bash is working fine. For zsh, you need to escape the brackets:
pip install imgui\[pygame\]
Was a bit tricky to find this, so I tough about sharing.
General idea is to:
make completion
)Pretty dirty but should work!
Note: If we store badge as badges/completion.svg
the url will be:
https://ci.appveyor.com/api/projects/swistakm/pyimgui/artifacts/badges/completion.svg?branch=master&job=Environment%3A%20PYTHON%3DC%3A%5CPython27%2C%20PYTHON_ARCH%3D32%2C%20MSVC_VERSION%3DVisual%20Studio%2010
This isn't actually a bug but it may look like one.
Some widgets get same "implicit" id and usually this is the value of widget's label parameter. For instance:
if imgui.button("OK"):
print("OK1")
if imgui.button("OK"):
print("OK2")
All above buttons will have same label "OK"
. Both buttons will look like clickable but only the first one will trigger on clicking. This would be a problem for common labels like yes/no/OK/cancel etc. but these usually are on different windows and windows have different IDs scopes. e.g. if we use following code:
imgui.begin("Win1")
if imgui.button("OK"):
print("W1-OK1")
if imgui.button("OK"):
print("W1-OK2")
imgui.end()
imgui.begin("Win1")
if imgui.button("OK"):
print("W2-OK1")
if imgui.button("OK"):
print("W2-OK2")
imgui.end()
We will see W1-OK1
and W2-OK1
in output but no W1-OK2
nor W2-OK2
. ImGui exposes following functions to maintain such ID scopes:
void PushID(const char* str_id)
void PushID(const char* str_id_begin, const char* str_id_end)
void PushID(const void* ptr_id)
void PushID(int int_id)
void PopID()
In order to solve such problems they need to be ported. We already have additional context managers for managing push/pop actions on fonts and styles so we could also create custom scope
or scoped
context manager that would make code more readable. We would then have two ways to interact with scopes:
if imgui.button("OK"):
print("OK outside scope")
imgui.push_id("my scope")
if imgui.button("OK"):
print("OK in scope")
imgui.pop_id()
# or ...
if imgui.button("OK"):
print("OK outside scope")
with imgui.scope("my scope"):
if imgui.button("OK"):
print("OK in scope")
Hi,
I was trying to compile pyimggui, but got the errors below.
OS: Ubuntu 17.04 64 bit.
Python: 2.7
$ make build
Bootstrapping project environment ...
git submodule update --init
Submodule 'imgui-cpp' (https://github.com/ocornut/imgui.git) registered for path 'imgui-cpp'
Cloning into '/mnt/data/home/stu/projects/external/pyimgui/imgui-cpp'...
Submodule path 'imgui-cpp': checked out 'adb85d800d70d3ddc4548f0e8f184eede4568034'
pip install -r doc/requirements-dev.txt
Requirement already satisfied: Cython in /mnt/data/home/stu/.virtualenvs/tmp-5b770036a307de45/lib/python2.7/site-packages (from -r doc/requirements-dev.txt (line 1))
Collecting PyOpenGL (from -r doc/requirements-dev.txt (line 2))
Downloading PyOpenGL-3.1.0.tar.gz (1.2MB)
100% |████████████████████████████████| 1.2MB 1.1MB/s
Collecting glfw (from -r doc/requirements-dev.txt (line 3))
Downloading glfw-1.4.0.tar.gz
Requirement already satisfied: wheel in /mnt/data/home/stu/.virtualenvs/tmp-5b770036a307de45/lib/python2.7/site-packages (from -r doc/requirements-dev.txt (line 4))
Collecting click (from -r doc/requirements-dev.txt (line 5))
Downloading click-6.7-py2.py3-none-any.whl (71kB)
100% |████████████████████████████████| 71kB 5.3MB/s
Building wheels for collected packages: PyOpenGL, glfw
Running setup.py bdist_wheel for PyOpenGL ... done
Stored in directory: /home/stu/.cache/pip/wheels/1c/17/50/f69d63e0a8169fb890f5a167817a73391be85d30e86fd29504
Running setup.py bdist_wheel for glfw ... done
Stored in directory: /home/stu/.cache/pip/wheels/8f/14/0a/b191d11fbbab2b5dc4fa090cf37540465f920af5fab87a1fb0
Successfully built PyOpenGL glfw
Installing collected packages: PyOpenGL, glfw, click
Successfully installed PyOpenGL-3.1.0 click-6.7 glfw-1.4.0
_CYTHONIZE_WITH_COVERAGE=1 python -m pip install -e . -v
Converted retries value: Retry(total=5, connect=None, read=None, redirect=None) -> Retry(total=Retry(total=5, connect=None, read=None, redirect=None), connect=None, read=None, redirect=None)
Converted retries value: Retry(total=5, connect=None, read=None, redirect=None) -> Retry(total=Retry(total=5, connect=None, read=None, redirect=None), connect=None, read=None, redirect=None)
Obtaining file:///mnt/data/home/stu/projects/external/pyimgui
Running setup.py (path:/mnt/data/home/stu/projects/external/pyimgui/setup.py) egg_info for package from file:///mnt/data/home/stu/projects/external/pyimgui
Running command python setup.py egg_info
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/mnt/data/home/stu/projects/external/pyimgui/setup.py", line 96, in <module>
], compiler_directives=cythonize_opts, gdb_debug=True),
File "/mnt/data/home/stu/.virtualenvs/tmp-5b770036a307de45/local/lib/python2.7/site-packages/Cython/Build/Dependencies.py", line 886, in cythonize
c_options = CompilationOptions(**options)
File "/mnt/data/home/stu/.virtualenvs/tmp-5b770036a307de45/local/lib/python2.7/site-packages/Cython/Compiler/Main.py", line 568, in __init__
raise ValueError(message)
ValueError: got unknown compiler directives: gdb_debug, build_inplace
Cleaning up...
Command "python setup.py egg_info" failed with error code 1 in /mnt/data/home/stu/projects/external/pyimgui/
The problem exists only on RTD online build of documentation (locally it builds as expected). This should be fixed before the first release because it breaks some links in "guide" section of documentation.
When I call imgui.get_draw_data()
it gives me a segfault. Am I using it wrong?
I modified doc/examples/pysdl2.py
to showcase what I was doing.
https://github.com/pconerly/pyimgui/blob/get_draw_data-gives-segfault/doc/examples/pysdl2.py
Hi, is there a way to custom-draw a region, like it is possible in the C++ imgui
? Likely not, because I don't see ImDrawList
exposed in the Python API, but is this planned?
I am working on #20 and #21 and I have realised that it would be nice to have some easy way to encode user interactions for illustration purposes in docs. Features that would be nice to have are:
Right now I have few ideas how to accomplish that:
Create some very simple language to encode interactions and use is as .. visual-example::
directive option. Like:
.. visual-example::
:auto_layout:
:height: 200
:animated: 5s 10fps
:interactions: move 0 0 | interpolate 1s | move 80 40 | click | wait 1s
current = 2
imgui.begin("Example: combo widget")
clicked, current = imgui.combo(
"combo", current, ["first", "second", "third"]
)
imgui.end()
This approach seems like the simplest to implement but also the hardest to use in docstrings and most expensive to maintain.
Include some annotations using special comments directly in the sample code. We could treat them as templates to include some special code in offscreen renderer. These comments would of course be removed from sample code in Sphinx. Something like this:
.. visual-example::
:auto_layout:
:height: 200
:animated: 5s 10fps
current = 2
imgui.begin("Example: combo widget")
clicked, current = imgui.combo(
"combo", current, ["first", "second", "third"]
)
#< click at 1s
imgui.end()
Imgui allows to get last item rect/position so this approach would be easier than hardcoding interaction positions. On the other hand the auto generated code that we would have to include would be a real mess. This also makes the example code harder to read for developers.
A hybrid (1+2) approach where we have simple interactions list (like in 1.) but allow to sprinkle the example code with specific labels in comments that allow to measure element position during example run. Like:
.. visual-example::
:auto_layout:
:height: 200
:animated: 5s 10fps
:interactions: move 0 0 | interpolate 1s | move "my-combo" | click | wait 1s
current = 2
imgui.begin("Example: combo widget")
clicked, current = imgui.combo(
"my-combo", current, ["first", "second", "third"]
)
#: my-combo
imgui.end()
Maybe it is not a good idea at all. Maybe there is already some "interaction" language that we could reuse. @supudo @Wiatrogon do you have any ideas?
I just tried to figure on my own how to load TTF fonts (documentation pending in #34), but I get an assertion error. What I do is the following:
font = imgui.get_io().fonts.add_font_from_file_ttf("fonts/DroidSans.ttf", 16)
...
while not glfw.window_should_close(self.window):
# draw stuff
imgui.push_font(font)
# draw text
imgui.pop_font()
The font seems to load successfully, i.e. the font
variable is a valid object, not None
. But then I get an error upon calling push_font
:
Traceback (most recent call last):
File "/Users/...[location].../igui.py", line 200, in <module>
app.main_loop()
File "/Users/...[location].../igui.py", line 76, in main_loop
self.draw()
File "/Users/...[location].../igui.py", line 86, in draw
self.draw_contents()
File "/Users...[location].../igui.py", line 152, in draw_contents
imgui.push_font(font)
File "imgui/core.pyx", line 4757, in imgui.core.push_font
imgui.core.ImGuiError: ImGui assertion error (font && font->IsLoaded()) at imgui-cpp/imgui.cpp:4529
Commenting out the push_font
and pop_font
calls makes everything work, but with the default raster font (which doesn't look great on a high-resolution display).
I also tried displaying the font atlas on screen -- the loaded font doesn't show in the atlas, only the default raster font
Any ideas will be greatly appreciated! I'm running macOS 10.12, tried the above code with both Python 2.7 and 3.6, both fail the same way.
Hello. I want to know if anyone can tell me how can I change the colors from the default theme to create a different skin?
Thank You.
This is simply to gain more users that could test the lib and give some initial feedback. Projects to research:
Pygame and cocos2d have the biggest user base so they are the first to research. Maybe we don't need anything more than SDL/SDL2/GLFW integration. Anyway it would be great to have some information about how to integrate pyimgui with these libraries and maybe create some examples for each one.
python-for-android looks interesting.
Originally made to enable Kivy apps on Android, it lets you run apps that use Cython and PySDL2. Libraries can provide recipes so that they can be built for Android.
pyimgui certainly has less cognitive overhead than Kivys declarative GUI so could be a welcome alternative.
Issue found thanks to #24. This affects text inputs from mapped core functions as well as text inpuths in C++ coded demo window. Issue is visible only in specific integrations and/or under specific versions of Python.
The root cause: invalid method of FPS measurement in all existing rendering integrations.
It seems it wasn't implemented in the version of imgui that is in this repo. Can we update that version and implement some of the new functions?
You know, I have started hating Github's announcing style on web search engines. If I had found your project before, I wouldn't wasted my time starting my own. Check here. Maybe you can integrate the SDL2 part to increase the completion of your project, or just check it out or whatever. If you are willing to keep being the PyImgui dev, I'm just dropping my version right know (no need for two of the same). Good work and good luck!
Looks like the newer version of Python isn't supported, which causes issues similar to what's described in #79.
Thanks!
When i try to run, i am getting this error, using the basic example of readthedocs
Traceback (most recent call last):
File "F:/Programming Projects/Python/twilio-app/main.py", line 3, in <module>
imgui.new_frame()
File "imgui\core.pyx", line 993, in imgui.core.new_frame
imgui.core.ImGuiError: ImGui assertion error (g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f) at imgui-cpp/imgui.cpp:2046
Process finished with exit code 1
Downloaded and installed trough pip install imgui[full].
PyCharm Community edition even trough python cmd i get the same error
Windows 7 SP1 x64
Python 3.6.2 virtualenv
Write a python implementation of ImGui::ShowDemoWindow
. This task was brought up in the broader ticket: #45
This would provide a good example for pyimgui users, and it would also provide a way for pyimgui users to check what is and isn't ported.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.