Python Pyglet:on_draw中的变量

Python Pyglet:on_draw中的变量,python,pyglet,Python,Pyglet,我的代码使用on_draw()来显示一些图形,它使用全局变量作为这些图形的参数 我想知道如何将本地变量从main()函数发送到on_draw()。 有可能吗?我对Pyglet不熟悉,但我会尽力回答 如果要使用main()中的全局变量,请使用global关键字从\u draw()上的中声明变量 例如,在全局空间中(在任何函数之外) 在绘图()上的中: 现在,如果您再次使用main(): global x print(x) > 10 为了补充Lee Thomas的答案,下面是一个完整的代码

我的代码使用
on_draw()
来显示一些图形,它使用全局变量作为这些图形的参数

我想知道如何将本地变量从
main()
函数发送到
on_draw()

有可能吗?

我对Pyglet不熟悉,但我会尽力回答

如果要使用
main()
中的全局变量,请使用
global
关键字从\u draw()上的
中声明变量

例如,在全局空间中(在任何函数之外)

在绘图()上的
中:

现在,如果您再次使用
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()    
一旦我运行代码,我就会得到输出


希望这对不起作用的人有所帮助。如果我这样做,一个错误表明变量x不存在。@jl.da抱歉,我的意思是首先在全局空间中定义x。所以在main()之外。然后,每当您想在任何函数(包括main)类型中引用全局x时,请首先
global x
global x
print(x)

> 10
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()