全局变量导致错误

时间:2012-05-23 14:41:37

标签: python

所以我试图将变量“checks”声明为全局变量,因为我遇到了以下问题:

  File "C:\Python27\Projects\Automatic Installer\autoinstall.py", line 11, in installFunc
    if checks[0] == 1:
NameError: global name 'checks' is not defined

这是我的代码,我试图将全局检查添加到程序的主体以及installFunc函数。是否有其他位置我应该添加它/其他一些方式来表明检查应该包含程序中的信息?

import urllib
import subprocess
from Tkinter import *

global checks

def installFunc():
    global checks
    subprocess.call("md c:\MGInstall", shell=True)
    subprocess.call (u"net use w: \\it01\files")
    if checks[0] == 1:
        subprocess.call(u"w:\\software\\snagitup.exe")
    if checks[1] == 1:
        subprocess.call(u"w:\\software\\camtasia.exe")
    if checks[2] == 1:
        urllib.urlretrieve(u"SUPERLONGURLLOLOLOL", u"c:\\MGinstall\\gotomeeting.exe")
        subprocess.call (u"c:\\MGinstall\\gotomeeting.exe")
    urllib.urlretrieve(u"http://ninite.com/.net-7zip-air-chrome-cutepdf-dropbox-essentials-firefox-flash-flashie-java-klitecodecs-quicktime-reader-safari-shockwave-silverlight-vlc/ninite.exe", u"c:\\MGinstall\\MGinstall.exe")
    subprocess.call (u"c:\\MGinstall\\MGinstall.exe")
    subprocess.call (u"w:\\printers\\installer\\printer.exe")

app = Tk()

w = Label(app, text="CompanyName IT Automatic Installer")
w.pack()

text = ["Snagit", "Camtasia", "GotoMeeting"]
variables = []
for name in text:
    variables.append(IntVar())
    Checkbutton(text=name, variable=variables[-1]).pack()

b = Button(text="OK", command=installFunc)
b.pack()

app.mainloop()
checks = [variable.get() for variable in variables]

4 个答案:

答案 0 :(得分:3)

我认为这是因为checks在主循环(发布代码的最后一行)之后设置。通过按下按钮从mainloop调用函数installFunc,但尚未定义检查。

无论如何,在这种情况下使用全局数据并不是一个好主意。你可能应该这样做:

def installFunc(checks):
    ...

checks = [variable.get() for variable in variables]
b = Button(text="OK", command=lambda : installFunc(checks))

或者,甚至更好,将所有这些包装在一个类中......你可以这样做:

self.b=Button(..., command=self.installFunc)

答案 1 :(得分:0)

将第一个'全局检查'(全局级别的检查)替换为'global = ...',并适当地初始化它。使用'global'仅在函数/方法中相关。根据Python文档:全局语句是一个声明,它包含整个当前代码块。这意味着列出的标识符将被解释为全局变量。没有全局变量就不可能分配给全局变量,尽管自由变量可以引用全局变量而不被声明为全局变量。您可能也想阅读此内容 - 有很多相关信息:Using global variables in a function other than the one that created them

答案 2 :(得分:0)

问题不是第一次'全球检查'。导致错误的原因是在初始化之前访问了检查。

您必须在调用应用程序的主循环之前初始化检查。

答案 3 :(得分:0)

首先, Python不是PHP

如果只是if,你需要在函数范围内分配全局变量,你需要使用关键字global

顶层的

global checks根本没有意义,更重要的是没有定义该变量。

global checks中的{p> installFunc()没有意义,因为您没有为该变量指定任何内容,实际上您甚至不修改它。

在Python中,外部作用域的变量在本地作用域中是可见的,除非您尝试分配某些内容,这将被解释为在本地作用域内重新定义该变量。

您的代码问题是您只在退出主循环后定义checks。正确的代码看起来像这样

import urllib
import subprocess
from Tkinter import *

#no global definition here...

def installFunc():
    #no global definition here...
    subprocess.call("md c:\MGInstall", shell=True)
    ...

...

#define checks before starting main loop
checks = [variable.get() for variable in variables]
app.mainloop()