PyQt5中round()函数计算结果未在GUI的QLabel组件显示问题
问题根因与修复方案
核心问题和PyQt的QLabel控件无关,是你对round()函数的特性理解有误:
round()是有返回值的纯函数,不会修改传入的原始变量,仅会返回四舍五入后的新数值。你当前代码只调用了round(activeRate, 3)但没有把结果赋值回activeRate变量,后续传给控件展示的还是未取整的原始值。
修复方法
方案1:接收round的返回值
将round调用的结果赋值回activeRate变量即可:
def rate(self, activeCount): activeRate = (activeCount/64)/1.5 # function of activeRate here activeRate = round(activeRate, 3) self.incRate.setText(f' {activeRate}/min')
方案2:直接在字符串格式化时指定精度
不需要单独调用round(),在f-string中直接指定保留3位小数即可实现相同展示效果:
def rate(self, activeCount): activeRate = (activeCount/64)/1.5 # function of activeRate here self.incRate.setText(f' {activeRate:.3f}/min')
内容的提问来源于stack exchange,提问作者pipettejockey
相关产品推荐
相关产品推荐

