My code uses on_draw()
to display some figures, it uses global variables as the parameters of those figures.
I would like to know how to send local variables from the main()
function to on_draw()
. Is it possible?
I'm not familiar with Pyglet, but I'll try and answer.
If you want to use global variables from main()
, declare the variables from within the on_draw()
with the global
keyword.
For example in the global space (outside of any functions).
x = 5
In your 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
Now if you're in your main()
again:
global x
print(x)
> 10
To add to Lee Thomas's answer, here is a complete snippet that can actually perform actions based on the value of the variable anywhere in the code:
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()
Once I run the code, I get the output
Hope this helps
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.