[英]inheritance TypeError: __init__() takes from 1 to 2 positional arguments but 8 were given
[英]TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given. Trying to build a GUI for my BMI calculator
这是代码:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("BMI Calculator")
window_width = 300
window_height = 200
# get the screen dimension
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
# find the center point
center_x = int(screen_width/2 - window_width / 2)
center_y = int(screen_height/2 - window_height / 2)
# set the position of the window to the center of the screen
root.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')
root.iconbitmap('./tkinter.ico')
message = tk.Label(root, text="BMI Calculator")
message.pack()
height = tk.Label(root, text="Enter your height in metres.")
height.pack()
textbox = ttk.Entry(root, textvariable="height")
textbox.pack()
weight = tk.Label(root, text="Enter your weight in kilograms.")
weight.pack()
textbox1 = ttk.Entry(root, textvariable="weight")
textbox1.pack()
def callback():
height = float(textbox.get())
weight = float(textbox1.get())
bmi = (weight / (height * height))
printed_bmi = ttk.Label(root, bmi)
printed_bmi.pack()
button = ttk.Button(root, text="Calculate my BMI!", command=callback).pack()
root.mainloop()
错误是这样的:
我该如何解决? 我真的只是不明白这是什么意思。 我对 Python 很陌生——如果有人能指出我正确的方向,我将不胜感激。
你忘了提到text=
参数
这应该工作
printed_bmi = ttk.Label(root, text=bmi)
来自ttk
的源代码
可以看到__init__
函数只接受一个master
参数而不是self
def __init__(self, master=None, **kw):
错误消息中描述了该问题。 您正在向函数发送 3 个变量,这需要 2 ...
printed_bmi = ttk.Label(root, bmi)
当然,第一个是self 而不是 root,这是可以的,但是 bmi 是什么? 你可能是说 text = bmi 吗?
所以我建议将线路更改为
printed_bmi = ttk.Label(root, text=bmi)
您需要像其他答案所说的那样添加text=bmi
参数。
而且,最好在函数之外制作一个按钮,否则可以创建 1 个以上的标签。 然后您可以更改函数内的标签 -
printed_bmi = ttk.Label(root,text='')
def callback():
height = float(textbox.get())
weight = float(textbox1.get())
bmi = (weight / (height * height))
printed_bmi.config(text=bmi)
printed_bmi.pack()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.