首页 > 解决方案 > 如何使用 tkinter.Label 更改文本颜色

问题描述

我正在尝试构建我的第一个 GUI 程序并想知道谁来更改标签文本颜色?例如,将其更改为“红色”

import tkinter as tk

root = tk.Tk()

label = tk.Label(root, text="what's my favorite video?", pady=10, padx=10, font=10,)
label.pack()
click_here = tk.Button(root, text="click here to find out", padx = 10, pady = 5)
click_here.pack()

root.mainloop()

非常感谢 :-)

标签: python-3.xtkinter

解决方案


您可以使用可选参数bgfg(请注意,您可能需要highlightbackground在 MacOS 系统上使用不同的选项,如本答案中所述) - 我认为这是 MacOS 上的一个已知问题tk.Button

import tkinter as tk

root = tk.Tk()

# bg is to change background, fg is to change foreground (technically the text color)
label = tk.Label(root, text="what's my favorite video?",
                 bg='#fff', fg='#f00', pady=10, padx=10, font=10) # You can use use color names instead of color codes.
label.pack()
click_here = tk.Button(root, text="click here to find out",
                       bg='#000', fg='#ff0', padx = 10, pady = 5)
click_here.pack()

root.mainloop()

我添加这个作为答案的唯一原因是因为我在一个类似的问题上为 SO 上的某个人写的最后一个答案只是因为他们使用的是 Mac 而不起作用。如果你在 Windows 机器上,你没问题。


推荐阅读