【问题标题】:Change Color Text with If-Else statements in Python在 Python 中使用 If-Else 语句更改颜色文本
【发布时间】:2013-11-07 23:15:31
【问题描述】:

所以基本上,这是我的代码:

#Imports Tk gui syntax
from Tkinter import *

#Creates App class
class App(Tk):

    #Initiates class
    def __init__(self):

        #Initiates Tk
        Tk.__init__(self)

        #Creates title of app
        self.title("BMI Calculator")

        #adds extra line for a cleaner gui
        self.fillerLine = Label(self, text = "")
        self.fillerLine.grid(row=0, column=0)

        #asks user for height
        self.hgtOutput = Label(self, text = "What is your height (in inches)? :")
        self.hgtOutput.grid(row=1, column=0)

        #user inputs height in inches using a slider
        self.hgtInput = Scale(self, from_=0, to=96, orient=HORIZONTAL, length=450)
        self.hgtInput.pack()
        self.hgtInput.grid(row=1, column=1)

        #button asking user to confirm height
        self.btnConfirmHGT = Button(self, text = "Confirm Your Hegiht", command = self.confirmHGT)
        self.btnConfirmHGT.grid(row=3, column=0)

        #prints the height the user input in feet and inches
        self.printHGT = Label(self, text = "\n\n")
        self.printHGT.grid(row=3, column=1)

        #extra line for cleaner gui
        self.fillerLine = Label(self, text = "-------------------------------------------------------------------------------------")
        self.fillerLine.grid(row=4, column=0, columnspan=2)

        #asks user for weight in pounds
        self.wghtOutput = Label(self, text = "What is your weight (in pounds)? :")
        self.wghtOutput.grid(row=5, column=0)

        #user inputs weight using a slider
        self.wghtInput = Scale(self, from_=0, to=400, orient=HORIZONTAL, length=450)
        self.wghtInput.pack()
        self.wghtInput.grid(row=5, column=1)

        #button to start calculations
        self.btnCalc = Button(self, text = "Calculate", command = self.calculate)
        self.btnCalc.grid(row=6, columnspan=2)

        #extra line for cleaner gui
        self.fillerLine = Label(self, text = "---------------------------------------------")
        self.fillerLine.grid(row=7, column=0, columnspan=2)

        #prints users BMI
        self.tellBMI = Label(self, text = "")
        self.tellBMI.grid(row=8, column=0, columnspan=2)

        #prints what category the user is in, underweight, normal, overweight, obese
        self.catBMI = Label(self, text = "")
        self.catBMI.grid(row=9, column=0, columnspan=2)

        #extra line for cleaner gui
        self.fillerLine = Label(self, text = "---------------------------------------------")
        self.fillerLine.grid(row=10, column=0, columnspan=2)

        self.mainloop()

    #function to make sure the user put in the correct height
    def confirmHGT(self):
        feet = (self.hgtInput.get())/12
        inches = (self.hgtInput.get())%12
        #print the height the user input
        self.printHGT["text"] = "\nYou're height is : %s ft. & %s in. \n" % (feet, inches)

    #function that calculates BMI and places it within a category
    def calculate(self):
        #Formula calculating BMI using the height and weight given by the user
        BMI = ((self.wghtInput.get()/float(self.hgtInput.get() ** 2))*703)
        #Prints users BMI
        self.tellBMI["text"] = "You're BMI is:\n %2.1f\n" % (BMI)
        #
        if BMI < 18.5:
            self.catBMI["text"] = "Grab a cheeseburger! You are underweight."
        elif BMI >= 18.5 and BMI <= 24.9:
             self.catBMI["text"] = "Congratulations! You are normal!"
        elif BMI >= 25.0 and BMI <= 29.9:
             self.catBMI["text"] = "Maybe eat some salad! You are overweight."
        elif BMI >= 30.0:
             self.catBMI["text"] = "Hit the treadmills! You are obese."
        else:
             pass

#creates an instance of the App() class
def main():
    a = App()

#runs main() function
if __name__ == "__main__":
  main()

对于我想做的事情,代码运行得非常好,我只是想做出一些小的改进来学习。我想做的是,如果 BMI 属于体重过轻的类别,请给出“吃一个芝士汉堡!你体重过轻”。声明黄色背景。如果在正常类别中,请给出“恭喜!您是正常的!”声明绿色背景。如果在超重类别中,则为黄色背景,而在肥胖类别中则为红色背景。在按下计算按钮之前保持正常背景。

我试过了,

tag_add()
tag_config()

但我似乎无法弄清楚,也不知道下一步该去哪里!

【问题讨论】:

    标签: python tkinter tk


    【解决方案1】:

    好吧,当你更改文本属性时,只需设置background 属性:

    if BMI < 18.5:
        self.catBMI["text"] = "Grab a cheeseburger! You are underweight."
        self.catBMI["background"] = "yellow"
    elif BMI >= 18.5 and BMI <= 24.9:
        self.catBMI["text"] = "Congratulations! You are normal!"
        self.catBMI["background"] = "green"
    elif BMI >= 25.0 and BMI <= 29.9:
        self.catBMI["text"] = "Maybe eat some salad! You are overweight."
        self.catBMI["background"] = "orange"
    elif BMI >= 30.0:
        self.catBMI["text"] = "Hit the treadmills! You are obese."
        self.catBMI["background"] = "red"
    else:
        pass
    

    顺便说一句。我认为您不应该在__init__ 方法中调用self.mainloop。这样做会阻止它离开那个方法,这似乎是不对的。而是在初始化应用后调用mainloop

    def main():
        a = App()
        a.mainloop()
    

    进一步说明,您的 if/else 结构进行了不必要的检查。如果您首先检查BMI &lt; 18.5 是否不是,那么BMI &gt;= 18.5 自动为真。因此,您可以省略 elifs 的所有第一次检查,因为它们自动为真,因为以前的情况不正确。同样,else 块永远不会执行。所以这一切都是这样的:

    if BMI < 18.5:
        self.catBMI["text"] = "Grab a cheeseburger! You are underweight."
        self.catBMI["background"] = "yellow"
    elif BMI <= 24.9:
        self.catBMI["text"] = "Congratulations! You are normal!"
        self.catBMI["background"] = "green"
    elif BMI <= 29.9:
        self.catBMI["text"] = "Maybe eat some salad! You are overweight."
        self.catBMI["background"] = "orange"
    else:
        self.catBMI["text"] = "Hit the treadmills! You are obese."
        self.catBMI["background"] = "red"
    

    【讨论】:

      猜你喜欢
      • 2014-03-18
      • 2015-12-07
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多