Question

I have a label object, that I am going to be changing the background colour of, and I would like to have a way to check what the background colour is at a given time. For example:

root=Tk()
label=ttk.Label(root, text="Hello there", background="#000000", foreground="#ffffff")
label.pack()
root.mainloop()

Saying oldfg=label.cget("foreground") and then calling oldfg gives the rather ambiguous <color object at 0x04078168> . Is there a way to get a hexidecimal or rgb representation of the colour, or can I use that in some way?

EDIT: In the title I say foreground, in the code i say background, the same thing applies to both.

Was it helpful?

Solution

I think you you have answered your own question to prove the point:

import Tkinter as tk


def swapsies():
    oldfg = label.cget("foreground")
    oldbg = label.cget("background")
    label.config(background=oldfg, foreground=oldbg)
    print "Foreground: {0} Background: {1}".format(oldfg, oldbg)


root = tk.Tk()
label = tk.Label(root, text="Hello there", background="#000000", foreground="#ffffff")
label.pack(side=tk.LEFT)
mega_button = tk.Button(root, text="GO!", command=swapsies)
mega_button.pack(side=tk.LEFT)

root.mainloop()

Has the output off, and clicking the button swaps the colours:

"Foreground: #ffffff Background: #000000"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top