【发布时间】:2021-10-08 17:40:31
【问题描述】:
我想在 Python 上做一些简单的程序。 该程序计算您的正常体重。你写你的年龄和身高。 问题是计算后我无法为“标签”设置新的计算值 我该怎么做?
这是程序代码
from tkinter import *
def clicked(): #button click
p = int(age.get()) #try ti get value of your age from Entry
b = int(height.get()) #try to get value of your height from Entry
mas = int(50 + 0.75*(p - 150) + (b - 20) / 4) #it is calculation
lbl3.setvar(mas) # here is a problem (i think)
window = Tk()
window.title('Ваш здоровый вес')
window.geometry('200x200')
lblage = Label(window, text='Ваш возраст') # Label for Age
lblage.grid(column=0, row=1)
age = Entry(window, width=5) # Entry for Age
age.grid(column=1, row=1)
lblheight = Label(window, text='Ваш рост') #Label for height
lblheight.grid(column=0, row=2)
height = Entry(window, width=5) # Entry for height
height.grid(column=1, row=2)
button1 = Button(window, text='Получить значение', fg='green', command=clicked) #Button
button1.grid(column=0, row=5)
lbl2 = Label(window, text='Ваш здоровый вес')
lbl2.grid(column=0, row=6)
lbl3 = Label(window) #here have to be our calculation
lbl3.grid(column=1, row=6)
window.mainloop()
程序看起来
错误是
" Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Maxim03\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "C:\Users\Maxim03\PycharmProjects\practice1\weight.py", line 7, in clicked
lbl3.setvar(mas)
File "C:\Users\Maxim03\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 709, in setvar
self.tk.setvar(name, value)
TypeError: must be str, bytes or Tcl_Obj, not int"
我认为问题出在这里:
def clicked():
p = int(age.get())
b = int(height.get())
mas = int(50 + 0.75*(p - 150) + (b - 20) / 4)
lbl3.setvar(mas)
【问题讨论】:
-
从例外情况来看, .setvar 需要一个字符串,而不是一个整数,这是有道理的,因为您似乎正在更新标签。
lbl3.setvar(str(mas))也许? -
setvar据我所知,这不是设置标签文本的常用方法。我相信lbl3.config(text=str(mas))应该可以工作。
标签: python user-interface tkinter