Python使用tkinter对小数进行舍入



此代码段正常工作,但没有设置精度。输出在逗号后面有很多小数,我希望它设置为2。尝试了很多方法来设置它,但都没有成功。有什么想法吗?

非常感谢。

def getExponential():
x2 = entry2.get()
label2 = Label(window, text=float(x2)*float(x2))
canvas1.create_window(350, 100, window=label2)
button2 = Button(text='Get the Exponential', command=getExponential)
canvas1.create_window(240, 100, window=button2)

您需要format您的价值,请考虑以下示例:

sqrt2 = 2**0.5
print('{:.3f}'.format(sqrt2))

输出

1.414

在您的情况下,只需更换

label2 = Label(window, text=float(x2)*float(x2))

使用

label2 = Label(window, text='{:.2f}'.format(float(x2)*float(x2)))

如果你想了解更多关于.format用法的信息,请阅读文档中的格式字符串语法或格式规范迷你语言。

最新更新