python TKinter' int' /' str'对象没有属性'追加'

时间:2017-02-21 22:53:27

标签: python tkinter

我知道这个问题很多,但我似乎无法让我的代码工作。

作为一个预计,我试图建立一个简单的计算器。但我有点卡住了。这是我的代码。

 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()

我目前正在使用' int'对象没有属性'追加'

这是否意味着你不能将append命令与数字一起使用?

如果是这样的话怎么可能这样做如果我按下其中一个按钮就把这个数字加到柜台上,所以如果你按下按钮1,2,5,你会得到0125我也试过做这个用

counter = ""

但是这只是给出了相同的错误,但是' str'对象没有属性'追加'

我是python的新手,非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

  

这是否意味着您不能将append命令与数字一起使用?

是的,这正是它的含义。

  

如果是这样的话怎么可能这样做如果我按下其中一个按钮就把那个数字加到柜台上,所以如果你按下按钮1,2,5,你就会得到0125

您可以通过将counter设为字符串来解决此问题。将它保留为字符串,直到您需要它为整数为止,此时您可以进行转换。

但是,字符串也没有append方法。要附加到字符串,您可以使用+=,如:

counter += x

但是,这要求x也是一个字符串。对此的简单解决方案是传入字符串而不是数字:

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