问题描述
我是pyglet和python的新手,我想创建一个画线的函数。 这是我的代码:
import pyglet
from pyglet import shapes
title = "Tic Tac Toe"
window = pyglet.window.Window(600,600,title)
batch = pyglet.graphics.Batch()
def drawBoard(batch=None):
line = shapes.Line(600,300,width=2,color=(0,230,0),batch=batch)
line.opacity = 250
drawBoard(batch=batch)
@window.event
def on_draw():
window.clear()
batch.draw()
pyglet.app.run()
当我将函数内的代码移出函数时,它会根据需要创建该行,但是当我将其放入函数时,代码只会创建一个空白背景。
解决方法
形状 line
是 drawBoard
函数中的局部变量。 batch
仅存储指向形状的弱指针。因此 line
在函数终止时被销毁。
一个选项是存储行 global
命名空间:
def drawBoard(batch=None):
global line
line = shapes.Line(600,300,600,width=2,color=(0,230,0),batch=batch)
line.opacity = 250
如果你想画更多的sahpes,我建议在列表中管理形状:
import pyglet
from pyglet import shapes
title = "Tic Tac Toe"
window = pyglet.window.Window(600,title)
batch = pyglet.graphics.Batch()
def drawBoard(shape_list,batch=None):
for i in range(100,100):
linex = shapes.Line(i,i,batch=batch)
linex.opacity = 250
shape_list.append(linex)
liney = shapes.Line(0,batch=batch)
liney.opacity = 250
shape_list.append(liney)
shape_list = []
drawBoard(shape_list,batch=batch)
@window.event
def on_draw():
window.clear()
batch.draw()
pyglet.app.run()