【问题标题】:How to change the text color using tkinter.Label如何使用 tkinter.Label 更改文本颜色
【发布时间】:2021-01-25 03:07:56
【问题描述】:

我正在尝试构建我的第一个 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()

非常感谢:-)

【问题讨论】:

  • tk.Label(...) 中添加fg='red'
  • 在 tk.label 中尝试 bg='#fff' 或 fg='f00'

标签: python-3.x tkinter


【解决方案1】:

请注意,background='' 会将标签返回为其默认颜色。我通过打印label.cget('background') 的结果发现了这一点,其中 label 是 tkinter 标签。

【讨论】:

  • 不适用于 Linux (Kubuntu 20.04)
【解决方案2】:

您可以在tk.label 中使用bg='#fff'fg='f00'

【讨论】:

    【解决方案3】:

    您可以使用可选参数 bgfg(请注意,您可能需要在 MacOS 系统上使用不同的选项,如 highlightbackground,如 In this answer 所述) - 我认为这是 @ 的一个已知问题在 MacOS 上为 987654326@。

    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()
    

    我添加这个作为答案的唯一原因是因为last answer 我在 SO 上为某人写了一个类似的问题,仅仅因为他们使用的是 Mac 而没有工作。如果你在 Windows 机器上,你没问题。

    【讨论】:

    • @JackGriffin 我不确定这意味着什么。 #f00 将始终代表红色,无论其主机操作系统如何。
    • @PS Solanki:你是对的。我误解了你的代码。我的错。将删除该评论。
    猜你喜欢
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    • 2018-03-03
    相关资源
    最近更新 更多