使用PyOpenGL更改图形的颜色

yv5phkfx  于 2022-12-03  发布在  其他
关注(0)|答案(2)|浏览(154)

我用Python编写了一个基本的程序,使用的是OpenGL库......当有人按下“r”键时,图形会变成红色,当有人按下“g”键时,图形会变成绿色,当有人按下“b”键时,图形会变成蓝色。我不知道为什么颜色不会改变,但我知道程序知道当一个键被按下时,这是我的代码......

from OpenGL.GL import *
from OpenGL.GLUT import *
from math import pi 
from math import sin
from math import cos

def initGL(width, height):
   glClearColor(0.529, 0.529, 0.529, 0.0)
   glMatrixMode(GL_PROJECTION)

def dibujarCirculo():
  glClear(GL_COLOR_BUFFER_BIT)
  glColor3f(0.0, 0.0, 0.0)

  glBegin(GL_POLYGON)
  for i in range(400):
    x = 0.25*sin(i) #Cordenadas polares x = r*sin(t) donde r = radio/2  (Circunferencia centrada en el origen)
    y = 0.25*cos(i) #Cordenadas polares y = r*cos(t)
    glVertex2f(x, y)            
  glEnd()
  glFlush()

def keyPressed(*args):
  key = args[0]
  if key == "r":
    glColor3f(1.0, 0.0, 0.0)
    print "Presionaste",key
  elif key == "g":
    glColor3f(0.0, 1.0, 0.0)
    print "Presionaste g"
  elif key ==   "b":
    glColor3f(0.0, 0.0, 1.0)
    print "Presionaste b"           

def main():
  global window
  glutInit(sys.argv)
  glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB)
  glutInitWindowSize(500,500)
  glutInitWindowPosition(200,200)

  #creando la ventana
  window = glutCreateWindow("Taller uno")

  glutDisplayFunc(dibujarCirculo)
  glutIdleFunc(dibujarCirculo)
  glutKeyboardFunc(keyPressed)
  initGL(500,500)
  glutMainLoop()

if __name__ == "__main__":
  main()
w8f9ii69

w8f9ii691#

我怀疑是因为dibujarCirculo中的第二行将glColor3f重置为(0,0,0),所以您一直丢失在keyPressed中所做的更改。您是否尝试过在dibujarCirculo以外的其他地方初始化glColor3f?

xxls0lw8

xxls0lw82#

您可以这样做,全局存储当前形状颜色,并在检测到按键时更新该颜色

from OpenGL.GL import *
from OpenGL.GLUT import *
from math import pi 
from math import sin
from math import cos

import random

shapeColor = [0, 0, 0]

numAgents = 300

def initGL(width, height):
   glClearColor(0.529, 0.529, 0.529, 0.0)
   glMatrixMode(GL_PROJECTION)

def dibujarCirculo():
  glClear(GL_COLOR_BUFFER_BIT)
  glColor3f(shapeColor[0], shapeColor[1], shapeColor[2])

  glBegin(GL_POLYGON)
  for i in range(400):
    x = 0.25*sin(i) #Cordenadas polares x = r*sin(t) donde r = radio/2  (Circunferencia centrada en el origen)
    y = 0.25*cos(i) #Cordenadas polares y = r*cos(t)
    glVertex2f(x, y)            
  glEnd()
  glFlush()

def keyPressed(*args):
  key = args[0]
  global shapeColor
  if key == b'r':
    shapeColor = [1,0,0]
  elif key == b'g':
    shapeColor = [0,1,0]
  elif key == b'b':
    shapeColor = [0,0,1]        

def main():
  global window
  glutInit(sys.argv)
  glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB)
  glutInitWindowSize(500,500)
  glutInitWindowPosition(200,200)

  #creando la ventana
  window = glutCreateWindow("Taller uno")

  glutDisplayFunc(dibujarCirculo)
  glutIdleFunc(dibujarCirculo)
  glutKeyboardFunc(keyPressed)
  initGL(500,500)
  glutMainLoop()

if __name__ == "__main__":
  main()

相关问题