Python Tkinter开发中如何将百分比计算结果保留两位小数
解决方案
你只需调整calculate函数中给rate赋值的逻辑即可实现需求,修改方式如下:
修改核心代码
将原来calculate函数中rate.set((vaccint / popint) * 100)这一行,替换为你提到的格式化语法即可,自动完成四舍五入保留两位小数的效果。
修改后完整的calculate函数参考:
# 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()) # 保留两位小数的核心修改,{:.2f}会自动对结果做四舍五入处理 rate.set("{:.2f}".format((vaccint / popint) * 100)) # 如果后续还需要对百分比结果做数值计算,也可以用round方法 # rate.set(round((vaccint / popint) * 100, 2)) except ValueError: pass # Ignore for now # 可选新增:避免总人口输入为0时报错 except ZeroDivisionError: rate.set("0.00")
其他代码无需改动,addvacc函数和界面组件逻辑保持原有状态即可,修改后运行程序就能看到百分比结果自动保留两位小数。
程序GUI界面参考

内容的提问来源于stack exchange,提问作者Milodoc
相关产品推荐
相关产品推荐

