我不能使用标签传递变量

I cant pass variables using labels

当我在我的代码中偶然发现这个问题时,我开始编写 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,但是代码让它认为我正在传递一些不存在的名为 amount 的参数。

请帮忙。

您需要传递的唯一位置参数是 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 class 的接口解析参数来创建它的一个实例,使用给定参数的配置。

tkinter 标签 class 知道可以找到的参数 here

因此,将您的标签与可用参数进行比较,您会注意到 amountyears 不是其中的一部分。 tkinter 的 Label class 期望的唯一位置参数是 master,后跟关键字参数 **optionsRead this.

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

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

如果有什么不清楚的地方,请告诉我。