【发布时间】: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