2013-04-30 39 views
-1

我想實現一個原始字典來查找我們在實驗室中使用的縮略詞。這本字典的格式爲:Python字典在tkinter與非GUI中添加/刪除項目

{'REN': 'plasma renin', 'PROP': 'procollagen III', 'IMETAB': 'intermediary metabolites, pyruvate, lactate, beta-OH-butyrate'...} 

試圖添加/刪除項目,但只與GUI格式時,我可以做無論是在圖形用戶界面和其它格式的詞典搜索項目,卻得到一個錯誤。 這裏有問題的代碼兩個片段:

此代碼的工作

elif inp == 'add': 
     abbr_in = input('acronym: ') 
     text_in = input('expanded text: ') 
     acronyms[abbr_in] = text_in 
     with open('acronym_dict.py','w')as outfile: 
      outfile.write(str(acronyms)) 
      outfile.close() 

elif inp == 'delete': 
     name = input("Enter acronym to delete: ").upper() 
     r =dict(acronyms) 

      del r[name]     

      with open('acronym_dict.py','w')as outfile: 
       outfile.write(str(r)) 
       outfile.close() 

和GUI代碼不起作用:

def add_acronym(): 
add_del_acronym.get() 
add_del_acronym.upper() 
abbr_in = addordel_acronym 
add_expansion.get() 
text_in = add_expansion 
acronyms[abbr_in] = text_in 
# write amended dictionary 
with open('acronym_dict.py','w')as outfile: 
    outfile.write(str(acronyms)) 
    outfile.close() 
def remove_acronym(): 
    name = addordel_acronym.get().upper() 
    name.upper() 
    r =dict(acronyms) 
    del r[name] 
    # write amended dictionary 
    with open('acronym_dict.py','w')as outfile: 
     outfile.write(str(r)) 
     outfile.close() 

,我得到的錯誤是:

TypeError: get() missing 1 required positional argument: 'self' 

請有人來我的協助。不明白該怎麼做。 謝謝

+0

你縮進你的榜樣搞砸了,根本不可能知道你的代碼的真正本質。 – 2013-04-30 10:50:16

回答

0

你給出的錯誤信息與tkinter無關。當你得到一個錯誤,指出消息:

TypeError: get() missing 1 required positional argument: 'self' 

...那麼就意味着你在呼喚像something.get()功能,但你定義的東西作爲def something(self)。所以,追蹤哪個函數調用拋出這個錯誤來找到你的問題。我的猜測是,你有一些變量,你認爲是一個字典,但實際上是一個類的實例。

根據對該問題的原始版本的評論,看起來您錯誤地使用了tkinter StringVar類。你顯然這樣做是:

variable = tkinter.StringVar 

這將導致你到類分配variable而不是類的一個實例variable。該類定義了一個名爲get的方法,該方法正在調用,但它需要self參數,它告訴該類您引用的是哪個實例。既然你不是指一個實例,self是未定義的,因此你會得到你報告的錯誤。

要解決你的問題,你必須創建的StringVar一個實例,像這樣:

variable = tkinter.StringVar() 
+0

謝謝。會追捕。 – user1478335 2013-04-30 11:33:33

+0

我看不到它。是否有任何'快速'的方法來找到這樣的錯誤。無法想象單元測試或文檔測試。有什麼建議麼?我應該發佈整個代碼嗎? – user1478335 2013-04-30 13:23:27

+0

@ user1478335:「快速」方法是查看錯誤的全文,它應該告訴您導致問題的行號。 – 2013-04-30 13:51:18