函数中的全局变量

时间:2014-03-09 17:44:04

标签: python function variables global

我试图告诉一个函数使用place.forget()从屏幕上删除按钮lb但我收到一个错误,因为我已经将按钮lb定义为另一个函数中的全局变量,所以每次尝试回想起它并没有“看到”全球变量。我知道为什么它给我的错误我只是不确定如何纠正它,任何帮助将不胜感激。

def page4():
    master.title('Page 4')
    #draw
    c19.grid(pady=slpady)
    c19.grid(row=sly,column=slx1)
    c20.grid(row=sly,column=slx2)
    c21.grid(row=sly,column=slx3)
    c22.grid(row=sly,column=slx4)
    c23.grid(row=sly,column=slx5)
    c24.grid(row=sly,column=slx6)
    rec.grid(row=rec_y, column=rec_x,columnspan=3)
    clear_4.grid(row=clear_y, column=clear_x,columnspan=3)
    #hide
    c1.grid_remove()
    c2.grid_remove()
    c3.grid_remove()
    c4.grid_remove()
    c5.grid_remove()
    c6.grid_remove()
    c7.grid_remove()
    c8.grid_remove()
    c9.grid_remove()
    c10.grid_remove()
    c11.grid_remove()
    c12.grid_remove()
    c13.grid_remove()
    c14.grid_remove()
    c15.grid_remove()
    c16.grid_remove()
    c17.grid_remove()
    c18.grid_remove()
    new_show.grid_remove()
    save_show.grid_remove()
    load_show.grid_remove()
    pre_1.grid_remove()
    pre_2.grid_remove()
    pre_3.grid_remove()
    pre_4.grid_remove()
    clear_1.grid_remove()
    clear_2.grid_remove()
    clear_3.grid_remove()
    lb.place_forget()

#Presets
def presets():
    master.title('Presets')
    pre_1.grid(row=1,column=1,padx=ppadx, pady=ppady)
    pre_2.grid(row=1,column=2,padx=ppadx, pady=ppady)
    pre_3.grid(row=2,column=1,padx=ppadx, pady=ppady)
    pre_4.grid(row=2,column=2,padx=ppadx, pady=ppady)
    global lb
    lb=Button(master,width=20,height=5,text='LOCK',bg='burlywood1',command=lockscreen)
    lb.place(x=450,y=580)

我得到的错误是:

Exception in Tkinter callback Traceback (most recent call last):
    File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
        return self.func(*args)
    File "C:\Users\Josh Bailey\Desktop\pi_dmx\pi_dmx512py2.py", line 412, in page4
        lb.place_forget() NameError: global name 'lb' is not defined

2 个答案:

答案 0 :(得分:2)

在开始任何功能之前初始化lb。

答案 1 :(得分:0)

我通过移动全局lb和lb = Button(master,width = 20,height = 5,text =' LOCK',bg =' burlywood1'来解决它command = lockscreen)到我的代码的顶部,以便它没有任何功能,然后不得不重新安排我的其余代码,以便该按钮(锁定屏幕)调用的函数位于预设功能之上。谢谢你的帮助!