2017-07-14 605 views
-1

我正在制作一个计算器程序,而且我正在尝试将用户的输入变成一个字符串。我能够根据他们按下的按钮创建一个列表。所以如果他们按5,字符串将是'5',如果他们之后按8,它将是'58'等。因此,每次人按下按钮时,我已将该数字添加到列表中,所以在最后一个例子中,列表将是['5','8']。我试图把它们串成一个串,'58',但我有问题。列表中的字符串没有正确添加到空字符串

from Tkinter import * 


root=Tk() 
root.geometry('300x500') 
root.configure(bg="gray") 
root.title("Calculator") 

typed_num=[] 

def button_command(number): 
    typed_num.append(str(number)) 

    string_num='' 
    for val in typed_num: 
     string_num+=typed_num 
    print string_num 


startx=20 
starty=60 

one_button=Button(root, text="1", command=lambda:button_command(1), highlightbackground='gray').place(x=startx, y=starty) 
two_button=Button(root, text="2", command=lambda:button_command(2), highlightbackground='gray').place(x=startx+60, y=starty) 
three_button=Button(root, text="3", command=lambda:button_command(3), highlightbackground='gray').place(x=startx+120, y=starty) 
four_button=Button(root, text="4", command=lambda:button_command(4), highlightbackground='gray').place(x=startx, y=starty+60) 
five_button=Button(root, text="5", command=lambda:button_command(5), highlightbackground='gray').place(x=startx+60, y=starty+60) 
six_button=Button(root, text="6", command=lambda:button_command(6), highlightbackground='gray').place(x=startx+120, y=starty+60) 
seven_button=Button(root, text="7", command=lambda:button_command(7), highlightbackground='gray').place(x=startx, y=starty+120) 
eight_button=Button(root, text="8", command=lambda:button_command(8), highlightbackground='gray').place(x=startx+60, y=starty+120) 
nine_button=Button(root, text="9", command=lambda:button_command(9), highlightbackground='gray').place(x=startx+120, y=starty+120) 
zero_button=Button(root, text="0", command=lambda:button_command(0), highlightbackground='gray').place(x=startx+60, y=starty+180) 


root.mainloop() 

任何和所有的帮助,非常感谢!返回的错误是:TypeError:无法连接'str'和'list'对象

+1

变化'string_num + = typed_num'到'string_num + = val' – eyllanesc

回答

1

您正在尝试此连接:string_num+=typed_num。如果要将项目添加到列表,例如typed_num.append(string_num),可以使用append。您尝试将一个列表添加到一个字符串中,但是您可以将一个字符串添加到列表中。 “+”也可以使用,但反过来

1

该问题是因为你想添加一个字符串的列表,该操作是不可能的,我认为你想要做的是连接他们你必须改变:

string_num+=typed_num 

string_num+=val 

一个简单的方法来连接字符串列表的加入,这个它的变化:

string_num='' 
for val in typed_num: 
    string_num+=typed_num 
print string_num 

到:

print "".join(typed_num)