簡體   English   中英

類型錯誤:__init__() 需要 1 到 2 個位置參數,但給出了 3 個。 嘗試為我的 BMI 計算器構建 GUI

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM