如何在python tkinter中四舍五入到2位小数

2024-06-25 06:25:39 发布

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

我正在制作一个计算百分比的小程序,但我找不到将结果四舍五入到2位小数的方法

  • 有一个用于输入数字的字段
  • 还有另一个字段用于输入第二个数字(或通过单击按钮增加)
  • 有一个字段显示百分比

我相信我需要在函数中使用类似"{:.2f}"的东西,但我不知道具体在哪里

这是我代码的一部分,我想我必须把命令:

# Defining a function that takes any arguments and calulcates the proportion of the population and the vaccinated
def calculate(*args):
    try:
        popint = float(pop.get())
        vaccint = float(vacc.get())
        rate.set((vaccint / popint) * 100)
    except ValueError:
        pass  # Ignore for now

# Defining a function that increases by 1 the number of vaccinated
def addvacc(*args):
    try:
        vaccadd = int(vacc.get())
        vacc.set(vaccadd + 1)
        calculate()
    except ValueError:
        pass # Ignore for now

# Creating a window with title
root = Tk()

一切都已创建(按钮、标签等),并且可以正常工作

Image

我已经附加了程序的GUI。多谢各位


Tags: andofthe程序getthatdeffunction