如何在Tkinter中创建动态标签颜色?

2024-04-29 06:49:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为暑期工作创建一个GUI BMI计算器。 我想实现一个功能,一旦你的BMI被计算出来,标签的颜色会根据你的BMI而改变。在

我现在的代码是:

self.AnswerlabelVariable = tkinter.StringVar() #Creates a variable used later for changing the label text
Answerlabel = tkinter.Label(self, text=u" ", textvariable=self.AnswerlabelVariable, anchor='w', fg="black",bg="light grey") #Creates a label
Answerlabel.grid(column=1,row=4, sticky='EW') #Defines where the label is and how it will move


...the calculation for the BMI happens...


if float(BMI2)<int(17): #Creates an 'if' statement
    self.MessagelabelVariable.set("You are underweight!") #Changes a label to display a new message.
    self.AnswerlabelVariable.set(fg='black', bg='blue') #Changes a labels colour (WIP WIP WIP)

当标签改变了它的文本,颜色没有改变,而是产生一个错误信息

^{pr2}$

有人能帮忙吗?在


Tags: thetextselffor颜色tkinter标签label
2条回答

我从未使用过StringVar类,但每当我想更改标签的颜色(或任何参数)时,我都会直接更改。在

Answerlabel['fg'] = 'black'

您需要使用标签的config()方法来修改其fg和{}属性,如下所示:

self.Answerlabel.config(fg='black', bg='blue') #Changes a labels colour

相关问题 更多 >