简体   繁体   中英

How to get a value for “foreground” in tkinter/ttk python?

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM