在PythonOpenGL中创建一个弹出菜单

2024-04-20 05:37:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在Python(v2.7)程序中使用GLUT创建一个右键单击弹出菜单。我还没有找到Python特定文档来做这件事,所以我使用C++文档,这几乎是类似的。在

以下是我所拥有的:

if __name__=="__main__":
    glutInit(sys.argv)
    #...more initialization code...
    createMenu()
    init()
    glutMainLoop()

以下是创建菜单的函数:

^{pr2}$

菜单显示正确,但当我单击某个项目时,会出现以下错误:

DEBUG:root:Menu pressed:
Traceback (most recent call last):
  File "_ctypes/callbacks.c", line 338, in 'converting callback result'
TypeError: an integer is required
Exception  in <function processMenuEvents at 0x1760b90> ignored

python opengl有不同的方法来实现这一点吗?我做错什么了?在

谢谢。在


Tags: namein文档程序ifmainmoresys
3条回答

不幸的是,PyOpenGL定义回调函数的方式要求返回类型为int,而不是void。下面是CreateMenu回调函数的更新版本,应该可以正常工作。在

def CreateMenu():
    menu = glutCreateMenu(processMenuEvents)  
    glutAddMenuEntry("One", 1)  
    glutAddMenuEntry("Two", 2)  
    glutAttachMenu(GLUT_RIGHT_BUTTON)
    # Add the following line to fix your code
    return 0

这个example帮助我确定了指定函数参数ctypes以解决相同问题的需求。在glutAddMenuEntry()上的pyopengl glut文档之后找到。指定了函数参数的Ctype数据类型here。在

此代码段显示了通过对象实例引用的f(int)->int函数的示例:

class Menu:
 def select_menu(self, choice):
    def _exit():
        import sys
        sys.exit(0)
    {
        1: _exit
    }[choice]()
    glutPostRedisplay()
    return 0

 def create_menu(self):
    #  - Right-click Menu     
    from ctypes import c_int
    import platform
    #platform specific imports:
    if (platform.system() == 'Windows'):
        #Windows
        from ctypes import WINFUNCTYPE
        CMPFUNCRAW = WINFUNCTYPE(c_int, c_int)
        # first is return type, then arg types.
    else:
        #Linux
        from ctypes import CFUNCTYPE
        CMPFUNCRAW = CFUNCTYPE(c_int, c_int)
        # first is return type, then arg types.

    myfunc = CMPFUNCRAW(self.select_menu)

    selection_menu = glutCreateMenu( myfunc )
    glutAddMenuEntry("Quit", 1);
    glutAttachMenu(GLUT_RIGHT_BUTTON);
    #                 -

在Python中通过ctypes指定回调函数的工作方式与预期的不太一样。您应该使用CFUNCTYPE创建回调函数,并将生成的变量用作glutCreateMenu的参数。在

您可以在这里找到有关ctypes和回调函数的详细信息:http://docs.python.org/release/2.5.2/lib/ctypes-callback-functions.html

相关问题 更多 >