【问题标题】:Tkinter - How to change the color of a label's background if the users input is satisfied using gridTkinter - 如果使用网格满足用户输入,如何更改标签背景的颜色
【发布时间】:2020-05-02 16:30:37
【问题描述】:

我的目标是更改标签的颜色以匹配框架的颜色,使它们看起来漂亮而时尚。这是我的第一个编程项目,非常感谢您的帮助。谢谢。

import tkinter as tk


class Main:
    def __init__(self):
        self.root = tk.Tk()
        self.root.geometry("250x300-1200-400")

        # input field stored
        self.input_a = tk.StringVar()

        # label
        label = tk.Label(self.root, text="Enter Value")
        label.grid(row=0, column=0)

        # input field
        input_color_changer = tk.Entry(self.root, textvariable=self.input_a)
        input_color_changer.grid(row=0, column=1)

        button = tk.Button(self.root, text="Run", command=self.color_changer)
        button.grid(row=1, column=1)


        self.root.mainloop()


    def color_changer(self):
        input_b = self.input_a.get()

        if input_b == "r":
            self.root["bg"] = "red"
            self.label["bg"] = "red" # <--- code in question
        if input_b == "y":
            self.root["bg"] = "yellow"
        if input_b == "g":
            self.root["bg"] = "green"



Main()

【问题讨论】:

  • 好的,你有你的目标。那么告诉我们您的问题是什么?
  • 这表示您使用self.label["bg"] = "red",但没有将label 定义为类属性。尝试将label = tk.Label() 更改为self.label = tk.Label()
  • 您对框架提出了同样的问题。为什么你需要问两次这个问题?更改标签的背景与更改标签的背景相同。

标签: python button tkinter colors label


【解决方案1】:

您需要将label 定义为类属性。现在它只是init 方法中的一个变量。

为此,请添加 self. 前缀。

这里是您的代码更新了一点,从 Tk() 继承并使用标签的类属性。

import tkinter as tk


class Main(tk.Tk):
    def __init__(self):
        super().__init__()
        self.geometry("250x300-1200-400")
        self.input_a = tk.StringVar()
        self.label = tk.Label(self, text="Enter Value")
        self.label.grid(row=0, column=0)
        tk.Entry(self, textvariable=self.input_a).grid(row=0, column=1)
        tk.Button(self, text="Run", command=self.color_changer).grid(row=1, column=1)

    def color_changer(self):
        input_b = self.input_a.get()
        print(input_b)
        if input_b == "r":
            self["bg"] = "red"
            self.label["bg"] = "red"
        if input_b == "y":
            self["bg"] = "yellow"
        if input_b == "g":
            self["bg"] = "green"


if __name__ == '__main__':
    Main().mainloop()

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-07
    • 2020-02-10
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多