You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter输出无内容求助:计算结果无法显示在标签中

问题解决:Tkinter输出标签无法显示计算结果

问题说明

程序实现磅转公斤功能,按钮可正常获取输入数值、计算出Num变量,但结果无法在输出标签中显示,程序无报错。

错误定位

问题出在clicked函数的这一行:

output_str.set = (Num)
  • set是StringVar的方法,必须用set()调用,不能直接赋值
  • Num是浮点数,StringVar的set方法要求传入字符串类型参数

修正后的完整代码

import tkinter as tk

def clicked():
    num = entry_int.get()
    Num = num * 0.45
    # 正确调用set方法,同时将数值转为字符串
    output_str.set(str(Num))

window = tk.Tk()
window.title("Pounds to kilos")
window.geometry('350x200')

title = tk.Label(window, text="Pounds to Kg", font="helvectica")
title.place(x=115)

entry_int = tk.IntVar()
txt = tk.Entry(window, width=15, textvariable=entry_int)
txt.place(x=129, y=30)

output_str = tk.StringVar()
output = tk.Label(window, fg="blue", textvariable=output_str, font="helvectic")
output.place(x=126, y=50)

btn = tk.Button(window, text="Calculate", fg="red", command=clicked)
btn.place(x=240, y=26)

window.mainloop()

可选优化

  • 给结果添加格式,比如保留两位小数:output_str.set(f"{Num:.2f} kg")
  • 增加异常处理,避免输入非整数时崩溃:
def clicked():
    try:
        num = entry_int.get()
        Num = num * 0.45
        output_str.set(f"{Num:.2f} kg")
    except tk.TclError:
        output_str.set("请输入整数")

内容的提问来源于stack exchange,提问作者Gregory Rodgers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 13:42:08