Seaky Lone
Seaky Lone

Reputation: 1031

How to set Label's bg color to no color (default color)?

I am wondering how to set a Label from colored to uncolored (or say to the default color).

For instance, I have a label l=Label(root,text='color',bg='red').

I have tried l.configure(bg=None) to make it uncolored, but it doesn't work. The color of the label stays the same.

Is there any function that does the trick?

Upvotes: 3

Views: 2414

Answers (2)

Derek
Derek

Reputation: 2234

If you want your background red to be transparent (no color) then this snippet will do it.

At least on Windows!

import tkinter as tk

parent = tk.Tk()

parent.attributes('-transparentcolor', 'red')

red = tk.Label(parent, text = '   color    \n    is    \n    transparent    ', bg = 'red')
red.pack()

parent.mainloop()

Upvotes: 0

Nae
Nae

Reputation: 15335

For windows(at least), simply set l['bg'] = 'SystemButtonFace'. Below examples should work independent of the platform.


Assuming by

I am wondering how to set a red Label to no color.

you mean to reset back to the default color. A simple way would be to create a new label, fetch its bg, remove it, then put that color to the actual label:

import tkinter as tk

def default_bg_color():
    global root, l
    _dummy_lbl = tk.Label(root)
    l['bg'] = _dummy_lbl['bg']
    _dummy_lbl.destroy()


root = tk.Tk()

l = tk.Label(root, text="This is the red label.", bg='red')

btn = tk.Button(root, text="Default color!", command=default_bg_color)

l.pack()
btn.pack()
root.mainloop()

Also, see below example that overwrites any widget's bg option to its default when the button is pressed:

import tkinter as tk


def default_bg_color(widget):

    _ = widget.__class__(widget.master)
    widget['bg'] = _['bg']
    _.destroy()


if __name__ == '__main__':

    root = tk.Tk()

    # tk.Label can be replaced with any widget that has bg option
    label = tk.Label(root, text="This is the red label.", bg='red')
    btn = tk.Button(root, text="Default color!")
    btn['command'] = lambda widget=label: default_bg_color(widget)

    label.pack()
    btn.pack()
    root.mainloop()

Upvotes: 2

Related Questions