[英]Pyglet: variables in on_draw
我的代码使用on_draw()
显示一些图形,它使用全局变量作为这些图形的参数。
我想知道如何将局部变量从main()
函数发送到on_draw()
。 可能吗?
我不熟悉Pyglet,但我会尽力解答。
如果要使用main()
全局变量,请使用global
关键字在on_draw()
声明变量。
例如在全局空间(任何功能之外)。
x = 5
在您的on_draw()
:
global x
#whenever you refer to x from now on, you will be referring to the x from main
#do something with x
x = 10
现在,如果您再次进入main()
:
global x
print(x)
> 10
为了补充李·托马斯(Lee Thomas)的答案,下面是一个完整的代码段,该代码段实际上可以根据代码中任意位置的变量值执行操作:
import pyglet
x = 0 #declaring a global variable
window = pyglet.window.Window()#fullscreen=True
one_image = pyglet.image.load("one.png")
two_image = pyglet.image.load("two.png")
x = 10 #assigning the variable with a different value
one = pyglet.sprite.Sprite(one_image)
two = pyglet.sprite.Sprite(two_image)
print "x in main, ", x
@window.event
def on_draw():
global x #making the compiler understand that the x is a global one and not local
one.x = 0
one.y = 0
one.draw()
two.x = 365
two.y = 305
two.draw()
print "x in on_draw, ", x
pyglet.app.run()
希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.