Python 2.7 列表中的字符串未正确添加到空字符串
我正在制作一个计算器程序,我正在尝试将用户的输入转换成字符串。我能够根据他们按下的按钮创建一个列表。因此,如果他们按5,字符串将是“5”,如果他们在之后按8,字符串将是“58”,等等。因此,每次该人按下按钮,我都会将该数字添加到列表中,因此在最后一个示例中,列表将是['5','8']。我试着把它们串在一起,“58”,但我有问题Python 2.7 列表中的字符串未正确添加到空字符串,python-2.7,calculator,Python 2.7,Calculator,我正在制作一个计算器程序,我正在尝试将用户的输入转换成字符串。我能够根据他们按下的按钮创建一个列表。因此,如果他们按5,字符串将是“5”,如果他们在之后按8,字符串将是“58”,等等。因此,每次该人按下按钮,我都会将该数字添加到列表中,因此在最后一个示例中,列表将是['5','8']。我试着把它们串在一起,“58”,但我有问题 from Tkinter import * root=Tk() root.geometry('300x500') root.configure(bg="gray")
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'对象您正在尝试在此处连接:string_num+=typed_num。如果要向列表中添加诸如typed_num.appendstring_num之类的项,可以使用append。如果您试图向字符串中添加列表,则可以向列表中添加字符串。+也可以使用,但另一种方法是问题是因为您要添加带有字符串的列表,该操作是不可能的,我认为您要做的是为它们串联您必须更改:
string_num+=typed_num
到
连接字符串列表的一种简单方法是连接,为此它会更改:
string_num=''
for val in typed_num:
string_num+=typed_num
print string_num
致:
将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)