English 中文(简体)
造成错误的全局变量
原标题:Global variable causing an error
  • 时间:2012-05-23 14:41:36
  •  标签:
  • python

因此,我试图将变量“核对”宣布为全球变量,因为我得到了以下问题:

  File "C:Python27ProjectsAutomatic Installerautoinstall.py", line 11, in installFunc
    if checks[0] == 1:
NameError: global name  checks  is not defined

这里的代码, 我试图在程序的主体和安装功能中添加全局检查。 我是否应该添加另一个位置/ 其它方式来表示检查应该包含程序的信息?

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: \it01files")
    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]
最佳回答

我认为这是因为 checks 是在主环( 已张贴代码的最后一行) 之后设置的。 函数 < code> hostageFunc 通过按钮按键从主环调调用, 但检查尚未定义 。

在这种情况下,使用全球数据并不是一个好主意。你也许应该做一些事情,比如:

def installFunc(checks):
    ...

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

或者,更好的是,把这些都包起来 在一个班级... 这样你就可以做到:

self.b=Button(..., command=self.installFunc)
问题回答

用 Global = =. 来替换第一个全球检查( 全球一级的检查), 并适当初始化它。 使用 Global 只在函数/ 方法中真正相关。 参考 Python docs : 全球声明是当前整个代码块中的一项声明。 这意味着列出的标识符将被解释为是全球性的。 如果没有全球变量, 将无法指定为全球变量, 尽管自由变量可能指全球变量而不被宣布为全球。 您可能想要读取这个信息 - 有许多相关的信息 : https:// stackoverflow. com/ questions 423379/ use- global- vables- in- a- in- in- in- com- other- than- the- that- create- the- the- semet > > 函数中全球变量。

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

您必须在拨打应用程序的主循环前先初始化检查 。

首先, " 强势 " Python不是 PHP

您需要使用关键词global,如果仅当您在函数范围内重新指定全局变量时,您需要使用关键词global

顶层 global check 上层完全没有意义,更重要的是, < strong> 根本没有定义该变量的 。

您的 global check attack 没有意义, 因为您没有为该变量指定任何内容, 事实上您甚至没有修改它 。

在Python的外在变量中,外在范围的可见度为本地范围,当然,除非你试图指定某种可被解释为重新定义本地范围内的变量。

您的代码问题在于您仅在退出主环后定义 < code> 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()




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签