【发布时间】:2021-09-20 12:37:08
【问题描述】:
我正在编写一个计算百分比的小程序,但我找不到将结果四舍五入到小数点后两位的方法。
- 有一个输入数字的字段
- 还有另一个字段用于输入第二个数字(或通过单击按钮增加)
- 有一个字段显示百分比
我认为我需要在函数中使用"{:.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()
一切都已创建(按钮、标签等),并且可以正常工作。
我已经附上了程序的 GUI。谢谢。
【问题讨论】:
-
请考虑分享您的所有代码
-
使用
rate.set("{:.2f}".format((vaccint / popint) * 100))。 -
成功了!谢谢亨利!
-
如果你有 Python 3.6+ 并且想使用
f strings(这是首选):rate.set(f'{(vaccint / popint) * 100: .2f}')
标签: python python-3.x tkinter