歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python之OpenGL程序環境

Python之OpenGL程序環境

日期:2017/3/1 10:02:09   编辑:Linux編程

Python+OpenGL,想想都覺得很刺激~~

首先還是下載PyOpenGL包:http://pypi.python.org/pypi/PyOpenGL/3.0.2

在Windows下,安裝還是很簡單的,安裝程序會主動找到你的python目錄,所以可以直接下一步。

安裝好了後,就來寫一個腳本測試一下~

test.py

from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *

def Draw():
glClear(GL_COLOR_BUFFER_BIT)
glRotatef(0.5, 0, 1, 0)
glutWireTeapot(0.5)
glFlush()

glutInit()
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA)
glutInitWindowSize(400, 400)
glutCreateWindow("test")
glutDisplayFunc(Draw)
glutIdleFunc(Draw)
glutMainLoop()

可以看到,在python中同樣可以使用glut來創建窗口,語法遵從Python,但是大體上的結構還是和c語言的glut庫差不多。

在OpenGL編程學習實戰教程第2節.實現動畫這篇網站中 http://www.linuxidc.com/Linux/2013-02/78959.htm ,我用c語言,用OpenGL實現了一個顯示時鐘的程序。和上面的腳本一樣,那個程序也使用了glut庫,那是不是意味著用Python也能夠實現同樣的東西呢?

答案當然是!

於是,我抱著好奇的心態去嘗試了一下。最後居然成功了。。

有圖有真相:

在轉換的時候,有很多注意事項:

1.全局變量的處理。在Update函數和Draw函數中會用到h,m,s三個表示時間的全局變量。在Update函數中給他們更新值的時候需要用global關鍵字來聲明一下。

2.三角函數。記得import math,調用的時候也要用math.cos和math.sin。

3.變量的數據類型。因為Python中不需要事先聲明變量類型,所以有些值在賦值時需要注意,如果是浮點實數,但值需要暫時賦為一個整數時,需要在後面加上.0。如count=60.0

4.縮進的問題。在Python中代碼段是用縮進來標示的。在c語言的OpenGL中,我習慣性地把glBegin(XXX)後定點的語句縮進一下,但是這個在Python中是會出現問題的。

最後附上代碼:

from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import math
import time
h=0
m=0
s=0
def Draw():
PI=3.1415926
R=0.5
TR=R-0.05
glClear(GL_COLOR_BUFFER_BIT)
glLineWidth(5)
glBegin(GL_LINE_LOOP)
for i in range(100):
glVertex2f(R*math.cos(2*PI/100*i),R*math.sin(2*PI/100*i))
glEnd()
glLineWidth(2)
for i in range(100):
glBegin(GL_LINES)
glVertex2f(TR*math.sin(2*PI/12*i),TR*math.cos(2*PI/12*i))
glVertex2f(R*math.sin(2*PI/12*i),R*math.cos(2*PI/12*i))
glEnd()
glLineWidth(1)

h_Length=0.2
m_Length=0.3
s_Length=0.4
count=60.0
s_Angle=s/count
count*=60
m_Angle=(m*60+s)/count
count*=12
h_Angle=(h*60*60+m*60+s)/count
glLineWidth(1)
glBegin(GL_LINES)
glVertex2f(0.0,0.0)
glVertex2f(s_Length*math.sin(2*PI*s_Angle),s_Length*math.cos(2*PI*s_Angle))
glEnd()
glLineWidth(5)
glBegin(GL_LINES)
glVertex2f(0.0,0.0)
glVertex2f(h_Length*math.sin(2*PI*h_Angle),h_Length*math.cos(2*PI*h_Angle))
glEnd()
glLineWidth(3)
glBegin(GL_LINES)
glVertex2f(0.0,0.0)
glVertex2f(m_Length*math.sin(2*PI*m_Angle),m_Length*math.cos(2*PI*m_Angle))
glEnd()
glLineWidth(1)
glBegin(GL_POLYGON)
for i in range(100):
glVertex2f(0.03*math.cos(2*PI/100*i),0.03*math.sin(2*PI/100*i));
glEnd()
glFlush()
def Update():
global h,m,s
t=time.localtime(time.time())
h=int(time.strftime('%H',t))
m=int(time.strftime('%M',t))
s=int(time.strftime('%S',t))
glutPostRedisplay()
glutInit()
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA)
glutInitWindowSize(400, 400)
glutCreateWindow("My clock")
glutDisplayFunc(Draw)
glutIdleFunc(Update)
glutMainLoop()

Copyright © Linux教程網 All Rights Reserved