我无法使用标签传递变量

时间:2020-07-26 13:10:31

标签: python python-3.x tkinter label

当我在代码中偶然发现此问题时,我已经开始编写tkinter程序:

 elif (xtimes=="" or xtimes=="Optional") and (t!="" or t!="Optional"):
    amount
    years=0
    while years<t:
        principle=principle+((interest/100)*(principle))
        years+=1

    amount=principle
    finallabel=Label(root,text="Your Final Amount will be",amount,"at the end of",years,"years")
    finallabel.grid(row=13,column=0)

elif语句下,我已经计算了金额,并且想要使用标签显示答案,该标签给出了错误:“位置参数跟随关键字参数”

我认为我想像普通的python一样通过文本发送可变数量,但是代码使它认为我正在传递一些不存在的称为数量的参数。

请帮助。

1 个答案:

答案 0 :(得分:1)

您唯一需要传递的位置参数是Label(root)。 因此,如果您使用Label (text='my text', root),则会出现此错误。

这有效:

import tkinter as tk
root = tk.Tk()

lab = tk.Label(root, text='hi')
lab.pack()
root.mainloop()

这不是:

import tkinter as tk
root = tk.Tk()

lab = tk.Label(text='hi',root)
lab.pack()
root.mainloop()

更新后。.让我们在这里看代码的这一行:

finallabel=Label(root,text="Your Final Amount will be",amount,"at the end of",years,"years")

您在这里所做的是通过Label类的接口来解析参数,并使用给定参数的配置来创建它的实例。

tkinter Label类知道可以在here中找到的参数。

因此,将Label与可用参数进行比较,您会发现amountyears都不是其中的一部分。 tkinter的Label类期望的唯一Posistional自变量是master,后跟关键字自变量**optionsRead this

您试图做的是一个带有变量的字符串,有几种方法可以实现。我个人最喜欢的是f'string。 加上f'string,您的代码将如下所示:

finallabel=Label(root,text=f'Your Final Amount will be {amount},at the end of {years} years')

让我知道是否不清楚。