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

向Entry组件输入值后仅返回0.0,求助!已尝试IntVar和StringVar

Tkinter Entry组件取值始终返回0.0的解决方法

你的代码有两个核心问题导致取值一直是0.0:

  • Entry变量赋值错误:创建Entry后直接调用.pack(),会把pack()的返回值(None)存在变量里,而不是Entry实例本身。
  • 变量未与Entry绑定:calculate函数里重新定义了DoubleVar,完全没和输入框关联,调用.get()自然只能拿到默认的0.0。

修正后的代码如下:

from tkinter import *

window = Tk()

# 先定义绑定变量
point_var = DoubleVar()
games_var = DoubleVar()

# 创建组件和布局分开执行,保留组件引用(这里取值用变量,也可以不用,但养成好习惯)
point_label = Label(window, text="Amount of Points")
point_label.pack()
point_entry = Entry(window, textvariable=point_var, bd=5)
point_entry.pack()

games_label = Label(window, text="Amount of games played")
games_label.pack()
games_entry = Entry(window, textvariable=games_var, bd=5)
games_entry.pack()

def calculate():
    # 直接通过绑定的变量获取输入值
    points = point_var.get()
    games = games_var.get()
    print(games, points)

Button(window, text="Submit", command=calculate).pack()

window.geometry("800x600")
window.title('Arena Point Calculator Chapter 4 Season 2')
window.mainloop()

关键修正点说明:

  1. 提前定义DoubleVar,并通过Entry的textvariable参数绑定到输入框,这样输入框的内容会同步到变量中。
  2. 把组件创建和布局(pack)分开写,避免变量被赋值为None。
  3. calculate函数直接使用之前定义的变量调用.get(),就能拿到输入框的真实值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 12:17:14