在Python中编辑非全局名称

时间:2013-11-03 04:30:28

标签: python function graphics global

在Python版本中:2.7.5, 我安装了Zelle的图形,我不知道该怎么做,因为我试图在具有不同功能的函数中编辑非全局名称。 这是我的代码示例。

from graphics import *
import time
keyPad=GraphWin("Key Pad",300,400)
def Game():
    Buttons()
    testFor_keyPad_press()
def Buttons():
    button1=Rectangle(Point(1,1),Point(100,100))
    button1.setFill('gold')
    button.draw(keyPad)
def testFor_keyPad_press():
    userInput=keyPad.getMouse()
    userInputX=str(userInput.getX())
    userInputY=str(userInput.getY())
    if(userInputX<101 and userInputY<100):
        button1.setFill('grey')
        keyPad.update()
        time.sleep(0.5)
        button1.setFill('gold')
        keyPad.update()
Game()

我认为这应该有用,但它给我一个错误,说全局名称'button1'没有定义...所以有没有办法在用户定义的函数“Buttons()”中编辑button1?或者那是不可能的?如果有办法做到这一点,请告诉我......所有帮助都是

1 个答案:

答案 0 :(得分:0)

def Buttons():
    global button1
    button1=Rectangle(Point(1,1),Point(100,100))
    button1.setFill('gold')
    button.draw(keyPad)

会使它在函数外部可访问......但实际上你应该将逻辑封装在类