2013-05-19 30 views
1

我有一個標籤對象,我將要改變背景顏色,我想有一種方法來檢查背景顏色在給定時間是什麼。例如:如何獲得tkinter/ttk python中「前景」的值?

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

oldfg=label.cget("foreground"),然後調用oldfg給出了比較模糊的 <color object at 0x04078168> 。有沒有辦法獲得顏色的十六進制或rgb表示,或者我可以以某種方式使用它?

編輯:在標題中我說前景,在我說的背景代碼中,同樣的事情適用於兩者。

回答

2

我想你,你已經回答了你自己的問題來證明這一點:

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

有輸出關閉,並單擊按鈕交換的顏色:

"Foreground: #ffffff Background: #000000" 
+1

哦。 Woops。所以只要打印(oldbg)會做到這一點?該死的。謝謝你指出我的白癡! – rjmcf

+0

舉起!根本不愚蠢!我不知道你可以做那個label.cget東西,我經常使用tk半。感謝那個人,只是想我會製作一個小小的演示腳本來向你證明!我並不需要改變標籤的顏色和東西,但我真的可以看到它是如何有用的! – Noelkd

+0

好吧,也許現在看起來並不像現在這樣明顯,但令我沮喪的是,我確實在那裏得到了答案......然後謝謝你。 – rjmcf