2015-02-06 166 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問題。