在python3.6中,尝试在Tkinter中按下一个按钮后获取一个标签来更新和打印一个整数

2024-09-27 07:19:18 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我做了一个简单的体重指数计算器(非常简单),我试着让文本框有一个输入来改变底部的标签,上面写着最终的答案。问题是我无法让标签显示实际答案。你知道吗

我可以让程序在命令行中打印答案,但不能更新标签本身中文本的值。你知道吗

下面是我的代码。感谢所有帮助我的人:^)

from tkinter import *
import tkinter

root = Tk()
root.title("BMI Calculator")
root.geometry("300x200")

name = StringVar()
height = DoubleVar()
weight = DoubleVar()
bmi2= DoubleVar()


name.set("Default")
weight.set(20)
height.set(2)
bmi2.set(0)

def calculate():
    global name
    global height
    global weight
    global bmi2
    bmi1= (weight.get() /height.get())
    bmi2= (bmi1/height.get())
    fnlname = print(name.get())
    fnlbmi = print(bmi2)


e= Entry(root, textvariable=height)
e.pack()
e2= Entry(root, textvariable=weight)
e2.pack()
e3= Entry(root, textvariable=name)
e3.pack()
b=Button(root, text="Calculate", command=calculate).pack()
l=Label(root, text=bmi2).pack()
root.mainloop()

Tags: 答案namegettkinterroot标签globalpack
1条回答
网友
1楼 · 发布于 2024-09-27 07:19:18

你犯了两个错误:

  1. 您没有将bmi2变量正确分配给标签:

    l=Label(root, text=bmi2).pack()
    

    这将设置标签的文本,但不设置标签的变量。正确的定义是

    l=Label(root, textvariable=bmi2).pack()
    
  2. 从不更新bmi2变量。你写的

    bmi2= (bmi1/height.get())
    

    但它用一个浮点数取代了DoubleVar。你是在重新绑定而不是变异它。有一些帖子对此进行了更详细的解释,例如this one。你知道吗

    正确的代码是

    bmi2.set(bmi1/height.get())
    

相关问题 更多 >

    热门问题