这是代码
from tkinter import*
def final_calculation():
entryField.delete(0,'end')
Wood = entryWood.get()
Steal = entrySteal.get()
output_wood = (Wood *wood_c02)
output_steal = (Steal * steal_c02 )
final = (output_steal + output_wood *c02_coal)
entry.set(final)
steal_c02 = int (5.5)
wood_c02 = int (1.2)
c02_coal = int (0.94)
root = Tk()
root.configure(background="black")
root.title("C02 caculator")
root.resizable(1,0)
root.columnconfigure(0,weight=1)
root.columnconfigure(1,weight=1)
entry = StringVar()
entryField = Entry(root, textvariable=entry,background="white",foreground="black",justify=CENTER)
entryField.grid(row=0,column=0,columnspan=2,sticky=W+E)
entryField.columnconfigure(0,weight=1)
labelWood = Label(root, text="Amount of wood",background="black",foreground="grey90")
labelWood.grid(row=1,column=0, sticky=E)
labelSteal = Label(root, text="Amount of steal",background="black",foreground="grey90")
labelSteal.grid(row=2,column=0, sticky=E)
entryWood = Entry(root,background="grey80",foreground="black")
entryWood.grid(row=1,column=1,sticky=W)
entrySteal = Entry(root,background="grey80",foreground="black")
entrySteal.grid(row=2,column=1,sticky=W)
button = Button(root, text="caculate C02", command= final_calculation)
button.grid(row=3, columnspan=2)
root.mainloop()
按运行,一切正常。在计算出问题中可以重新解决的总和之前,即第二个输入被重复5次并显示为输出之前,任何帮助都将非常有帮助。
亲切问候:49.95
答案 0 :(得分:1)
您对数据类型感到困惑。让我们看一下代码。
在这里,您要将十进制数字转换为int
。整数是四舍五入的数字(例如0、1、2、3、4,...)。当您执行int(5.5)
时,基本上删除了小数点后的所有信息:
steal_c02 = int (5.5) # = 5
wood_c02 = int (1.2) # = 1
c02_coal = int (0.94) # = 0
从Entry小部件中获得的是字符串对象。尽管它们可能包含数字,但它们被视为文本,而不是数字。
例如
Wood = entryWood.get() # Wood = '10'
Steal = entrySteal.get() # Steal = '1.5'
output_wood = (Wood *wood_c02)
由于Wood = '10'
和wood_c02 = 1
,您正在将字符串与整数相乘。这行得通,但并没有达到您的期望。在python中执行'a'*5
时,您得到'aaaaa'
。因此,在这种情况下,Wood *wood_c02
是'10'*1
,即'10'
output_steal = (Steal * steal_c02 )
这里Steal = '1.5'
和steal_c02 = 5
相同:Steal * steal_c02
是'1.5'*5
,也就是'1.51.51.51.51.5'
final = (output_steal + output_wood *c02_coal)
这里output_steal = '1.51.51.51.51.5'
,output_wood = '10'
和c02_coal = 0
。 '10'*0 = ''
和'1.51.51.51.51.5' + '' = '1.51.51.51.51.5'
,您将其放在final
中。
您要使用数字而不是字符串进行计算,因此您应该将输入内容转换为数字(请记住,如果输入不能转换为数字,则此操作将失败)
Wood = float(entryWood.get())
Steal = float(entrySteal.get())
您还希望steal_c02
,wood_c02
和c02_coal
为十进制数字,因此请勿将它们转换为整数:
steal_c02 = 5.5
wood_c02 = 1.2
c02_coal = 0.94