我正在嘗試爲夏季作品創建GUI BMI計算器。 我想實現一個功能,一旦您計算出BMI,標籤的顏色會根據您的BMI而變化。如何在Tkinter中創建動態標籤顏色?
我當前的代碼如下:
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)
雖然標籤改變它的文字,顏色沒有改變,而是產生一個錯誤信息;
line 56, in OnCalculateButtonClick
self.AnswerlabelVariable.set(fg='black', bg='blue') #Changes a labels colour (WIP WIP WIP)
TypeError: set() got an unexpected keyword argument 'fg'
任何人都可以幫忙嗎?
我試過了。當我把它在代碼中,我得到了以下錯誤:self.AnswerlabelVariable.configure(FG = '黑',BG = '藍色')#Changes一個標籤顏色(WIP WIP WIP) AttributeError的: 'STRINGVAR' 對象有沒有屬性'configure' –
是的,你需要在'Answerlabel'標籤上調用'configure'。我會更新我的答案! 這是因爲AnswerlabelVariable不負責標籤看起來像是要修改的內容,它只包含它應該顯示的文本。所以,你需要'configure()'Label對象,而不是它的文本變量。 'AttributeError的: – Dartmouth
我嘗試新的,編輯的代碼時收到以下錯誤消息「_tkinter.tkapp」對象沒有屬性「AnswerLabel'' 還值得注意的,我試圖代碼爲'self.config.Answerlabel(FG =「黑」,BG =「藍」)'獲取錯誤'AttributeError的:「功能」對象有沒有屬性「MessageLabel'' 順便說一下,謝謝你們繼續幫助:) –