简体   繁体   English

Pyglet:on_draw中的变量

[英]Pyglet: variables in on_draw

My code uses on_draw() to display some figures, it uses global variables as the parameters of those figures. 我的代码使用on_draw()显示一些图形,它使用全局变量作为这些图形的参数。

I would like to know how to send local variables from the main() function to on_draw() . 我想知道如何将局部变量从main()函数发送到on_draw() Is it possible? 可能吗?

I'm not familiar with Pyglet, but I'll try and answer. 我不熟悉Pyglet,但我会尽力解答。

If you want to use global variables from main() , declare the variables from within the on_draw() with the global keyword. 如果要使用main()全局变量,请使用global关键字在on_draw()声明变量。

For example in the global space (outside of any functions). 例如在全局空间(任何功能之外)。

x = 5

In your on_draw() : 在您的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: 现在,如果您再次进入main()

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: 为了补充李·托马斯(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()    

Once I run the code, I get the output 运行代码后,我得到输出 如这里

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM