OpenGL.TKのメモ

部品なのでこれだけでは動かないが、tkinterとの接続方法について。
OpenGL.Tk.RawOpenglを使うのがミソで、OpenGL.Tk.Openglはマウス操作等が最初から組み込まれた便利Widgetなのだった。
RawOpenglのコード量は少ないので、直接tkinter.Widgetを継承しようかと思ったのだが
コンストラクタの引数がよくわからんかったのでとりあえずこの形にした。
参考になるのは、

C:/Python32/Lib/site-packages/OpenGL/Tk/__init__.py
#!/usr/bin/python
# coding: utf-8

import sys
import tkinter as tk
import OpenGL.Tk as togl


class MyGL(togl.RawOpengl):
    def __init__(self, parent, engine, *args, **kw):
        super(MyGL, self).__init__(args, **kw)
        self.engine=engine
        self.bind('<Map>', self.onDraw)
        self.bind('<Expose>', self.onDraw)
        self.bind('<Configure>', self.onResize)
        self.initialised=False
        self.bind('<ButtonPress-1>', lambda e: self.engine.onLeftDown(e.x, e.y) and self.onDraw())
        self.bind('<ButtonRelease-1>', lambda e: self.engine.onLeftUp(e.x, e.y) and self.onDraw())
        self.bind('<B1-Motion>', lambda e: self.engine.onMotion(e.x, e.y) and self.onDraw())
        self.bind('<ButtonPress-2>', lambda e: self.engine.onMiddleDown(e.x, e.y) and self.onDraw())
        self.bind('<ButtonRelease-2>', lambda e: self.engine.onMiddleUp(e.x, e.y) and self.onDraw())
        self.bind('<B2-Motion>', lambda e: self.engine.onMotion(e.x, e.y) and self.onDraw())
        self.bind('<ButtonPress-3>', lambda e: self.engine.onRightDown(e.x, e.y) and self.onDraw())
        self.bind('<ButtonRelease-3>', lambda e: self.engine.onRightUp(e.x, e.y) and self.onDraw())
        self.bind('<B3-Motion>', lambda e: self.engine.onMotion(e.x, e.y) and self.onDraw())
        self.bind('<MouseWheel>', lambda e: self.engine.onWheel(-e.delta) and self.onDraw())
        self.bind('<Key>', self.onKeyDown)

    def setup(self):
        pass

    def onDraw(self, *dummy):
        self.tk.call(self._w, 'makecurrent')
        self.update_idletasks()
        if not self.initialised:
            self.setup()
            self.initialised = 1
        self.engine.draw()
        self.tk.call(self._w, 'swapbuffers')

    def onResize(self, event):
        self.engine.onResize(event.width, event.height)
        self.onDraw()

    def onKeyDown(self, event):
        key=event.keycode
        if key==27:
            # Escape
            sys.exit()
        if key==81:
            # q
            sys.exit()
        else:
            print("keycode: %d" % key)


def run(engine):
    frame=MyGL(None, engine, width=600, height=600, double=1, depth=1)
    frame.pack(expand=tk.YES, fill=tk.BOTH)
    frame.focus_set()
    frame.mainloop()