python tkinter“计算器”的意外输出

2024-10-04 05:25:43 发布

您现在位置:Python中文网/ 问答频道 /正文

这是代码

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

按run键,一切正常。在您计算问题中RedisSolutions解决的问题的总和之前,即第二个输入重复5次并显示为输出,任何帮助都会非常有用

问候:49.95


Tags: outputcolumnrootgridfinalrowblackbackground
1条回答
网友
1楼 · 发布于 2024-10-04 05:25:43

你被数据类型搞混了。让我们看看你的代码

在这里,您将十进制数转换为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

从条目小部件中获得的是字符串对象。虽然它们可能包含数字,但它们被视为文本,而不是数字。
比如说

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_c02wood_c02c02_coal为十进制数,因此不要将它们转换为整数:

steal_c02 = 5.5
wood_c02 = 1.2
c02_coal = 0.94

相关问题 更多 >