[英]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.