2015-02-06 164 views
0

我迷失在这里。我定义了一个名为yenTrucks的变量。后来我在函数中调用它。由于我打算改变它,因此我在函数的开头将它定义为全局。还有一个if语句确保yenTrucks存在。不知何故,“如果”认为日元囤积存在并执行该声明。同时声明失败,错误不存在。在函数中取得全局变量

def KamyonSec(): 
    global Trucks 

    yenTrucks = deepcopy(Trucks) 

    kamyonTL = Toplevel() 
    label1 = Label(kamyonTL, text="Kamyon Tercihlerini Değiştirmek", height=0, width=100) 
    orj = Listbox(kamyonTL, width=100,height=5) 
    secim = Listbox(kamyonTL, width=40,height=5) 


    for truck in Trucks: 
     orj.insert(END, truck["brand"]) 

    def relist(): 

     for i in xrange(10): 
      secim.delete(0) 

     for truck in yenTrucks: 
      secim.insert(END, truck["brand"]) 

    def ekle_cikar(): 
     global yenTrucks 

     a = str(orj.selection_get()) 
     math = 0 
     for truck in Trucks: 
      if truck["brand"] == a: 
       if yenTrucks: 
        for yeniT in yenTrucks: 
         if yeniT["brand"] == a: 

          match = 1 
          break 


       if match == 0 : 
        yenTrucks.append(truck) 

     if match == 1 : yenTrucks.remove(a) 
     relist() 

输出是:

Exception in Tkinter callback 
Traceback (most recent call last): 
    File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __call__ 
    return self.func(*args) 
    File "/home/mbp/workspace/SOYKAN_Final/main.py", line 962, in ekle_cikar 
    if yenTrucks: 
NameError: global name 'yenTrucks' is not defined 

回答

0

使用if yenTrucks:是不一样的检查,如果存在yenTrucks,它检查是否yenTrucks有一个非零值。如果您使用if yenTrucks:yenTrucks不存在,您仍然会收到NameError,正如您所经历的。

要检查变量的存在,你可以使用:

if 'yenTrucks' in globals(): 

更多的一些信息,请参阅this问题。