why does my window doesn't work for on_draw?

♀尐吖头ヾ 提交于 2020-07-22 06:31:38

问题


I was watching a video about pyglet and I tried to create a triangle:

import pyglet
from pyglet.gl import *

class mywindow(pyglet.window.Window):
    def __init__(self, *args,**kwargs):
        super().__init__(*args,**kwargs)
        self.set_minimum_size(300,300)
        
window = mywindow(300,300,"deneme", True)

def on_draw():
    glBegin(GL_TRIANGLE)
    glColor3b(255,0,0)
    glVertex2f(-1,0)
    glColor3b(0,255,0)
    glVertex2f(1,0)
    glColor3b(0,0,255)
    glVertex2f(0,1)

window.on_draw()
pyglet.app.run()

    

when I run this code; I get this error:

AttributeError: 'mywindow' object has no attribute 'on_draw'

Any idea how to solve this?


回答1:


on_draw has to be a method of the class mywindow rather than a function. Don't invoke on_draw yourself, because it is called automatically, when the window is needed to be updated.
At the begin of on_draw you've to clear the display by (see Windowing).
A OpenGL immediate mode glBegin/glEnd sequence has to be ended by glEnd. The primitive type is GL_TRIANGLES rather than GL_TRIANGLE. If you want to specify the colors in range [0, 255], the you've to use glColor3ub (unsigned byte) rather then glColor3b (signed byte).
You have to set the viewport rectangle of the resizable window by glViewport in the on_resize event.

See the example:

import pyglet
from pyglet.gl import *

class mywindow(pyglet.window.Window):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.set_minimum_size(300,300)

    def on_draw(self):

        self.clear()

        glBegin(GL_TRIANGLES)
        glColor3ub(255, 0, 0)
        glVertex2f(-1, 0)
        glColor3ub(0, 255, 0)
        glVertex2f(1, 0)
        glColor3ub(0, 0, 255)
        glVertex2f(0, 1)
        glEnd()

    def on_resize(self, width, height):
        glViewport(0, 0, width, height)

window = mywindow(300,300,"deneme", True)
pyglet.app.run()



回答2:


In [1]: from pyglet.gl import *
   ...:
   ...: window = pyglet.window.Window()
   ...:
   ...: vlist = pyglet.graphics.vertex_list(3, ('v2f', [0,0, 400,50, 200,300]))
   ...:
   ...: @window.event
   ...: def on_draw():
   ...:     glClear(pyglet.gl.GL_COLOR_BUFFER_BIT)
   ...:     glColor3f(1,0,0)
   ...:     vlist.draw(GL_TRIANGLES)
   ...:
   ...: pyglet.app.run()

Output:



来源:https://stackoverflow.com/questions/62875646/why-does-my-window-doesnt-work-for-on-draw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!