2017-02-21 52 views
-1

我知道這個問題很多,但我似乎無法讓我的代碼工作。python TKinter'int'/'str'對象沒有屬性'追加'

作爲一個預測,我試圖建立一個簡單的計算器。但我有點卡住了。這是我的代碼。

import Tkinter as tk 
import tkMessageBox 

top = tk.Tk() 

def helloCallBack(x): 
    counter = 0  
    counter.append(x) 
    tkMessageBox.showinfo("result", counter) 

one = tk.Button (top, text = "1", command = lambda: helloCallBack(1)) 
two = tk.Button (top, text = "2", command = lambda: helloCallBack(2)) 
three = tk.Button (top, text = "3", command = lambda: helloCallBack(3)) 
four = tk.Button (top, text = "4", command = lambda: helloCallBack(4)) 
five = tk.Button (top, text = "5", command = lambda: helloCallBack(5)) 
six = tk.Button (top, text = "6", command = lambda: helloCallBack(6)) 
seven = tk.Button (top, text = "7", command = lambda: helloCallBack(7)) 
eight = tk.Button (top, text = "8", command = lambda: helloCallBack(8)) 
nine = tk.Button (top, text = "9", command = lambda: helloCallBack(9)) 
zero = tk.Button (top, text = "9", command = lambda: helloCallBack(0)) 

one.pack() 
two.pack() 
three.pack() 
four.pack() 
five.pack() 
six.pack() 
seven.pack() 
eight.pack() 
nine.pack() 
zero.pack() 

top.mainloop() 

我目前得到「詮釋」對象有沒有屬性「追加」

這意味着你不能使用數字附加命令?

如果是的話如何才能做到這一點,如果我按下其中一個按鈕,它將該數字添加到櫃檯,所以如果你按下按鈕一,二,五,你會得到0125我也試過這樣做與

counter = "" 

,但只是給了同樣的錯誤,但以「海峽」對象有沒有屬性「追加」

我是新來的Python和任何幫助將不勝感激。

+0

'append'函數是列表。嘗試'counter + = x' – bunji

+0

Mb嘗試使用'counter = 0 counter + = str(x)'而不是.append。它應該工作,因爲我們預先定義了它的類型和連接字符串,而不是整數。 – Grynets

回答

1

這是否意味着您不能將append命令與數字一起使用?

是的,這正是它的意思。

如果又如何纔有可能使它所以如果我按下一個按鈕它補充說,數計數器,所以如果你按下按鈕,一,二,五,你會得到0125

你可以通過設置counter來解決這個問題。將其保留爲一個字符串,直到您需要它爲整數時爲止,此時您可以進行轉換。

雖然,字符串也沒有append方法。要追加到一個字符串,您可以使用+=,如:

counter += x 

雖然,要求x是一個字符串,太。簡單的解決方案是通過一個字符串而不是數字:

one = tk.Button (..., command = lambda: helloCallBack("1")) 
two = tk.Button (..., command = lambda: helloCallBack("2")) 
... 
+0

非常感謝這項工作。我還需要將計數器變量更改爲全局變量,並將其從函數中移出,否則它會一直保持重置爲數字,謝謝。 –

相關問題