2010-04-30 185 views
27

我正在用Tkinter編寫幻燈片程序,但我不知道如何將背景顏色更改爲黑色而不是標準淺灰色。如何才能做到這一點?Python中Tk的背景顏色

import os, sys 
import Tkinter 
import Image, ImageTk 
import time 

root = Tkinter.Tk() 
w, h = root.winfo_screenwidth(), root.winfo_screenheight() 
root.overrideredirect(1) 
root.geometry("%dx%d+0+0" % (w, h)) 
root.focus_set() 
root.bind("<Escape>", lambda e: e.widget.quit()) 
image = Image.open(image_path+f) 
tkpi = ImageTk.PhotoImage(image)   
label_image = Tkinter.Label(root, image=tkpi) 
label_image.place(x=0,y=0,width=w,height=h) 
root.mainloop(0) 
+0

的背景是什麼?一個小部件?使用'背景'關鍵字。更多信息:http://www.pythonware.com/library/tkinter/introduction/widget-styling.htm – 2010-04-30 13:52:43

+0

許多Tk窗口小部件都有bg屬性,它允許指定它們的背景顏色。 – sastanin 2010-04-30 13:57:47

+0

嗯,我對Tk非常陌生,所以我不確定小部件究竟是什麼,但是label_image.configure(background ='black')取得了訣竅。在這種情況下,label_image是一個小部件,還是僅僅是root? – olofom 2010-04-30 18:26:42

回答

58
root.configure(background='black') 

或者更一般

<widget>.configure(background='black') 
+0

非常感謝!在這種情況下, label_image.configure(background ='black') 是獲得黑色背景所需要的! – olofom 2010-04-30 18:25:32

+0

只能使用預定義的顏色,如「黑色」或「白色」或十六進制代碼? – 2017-10-04 16:43:14

+0

據我所知,[任何顏色](http://effbot.org/tkinterbook/tkinter-widget-styling.htm)都可以。這是[一個簡單的例子](https://gist.github.com/thecjharries/8a4ecf94d2b43564d9b87815a3d1de55)。 – 2018-02-11 11:30:21

17

我知道這是有點老問題,但:

root["bg"] = "black" 

也會做你想要什麼,它涉及較少的打字。

0
widget['bg'] = '#000000' 

widget['background'] = '#000000' 

也將工作作爲十六進制值的顏色也是可以接受的。

0

config是另一種選擇:

widget1.config(bg='black') 
widget2.config(bg='#000000') 

或:

widget1.config(background='black') 
widget2.config(background='#000000')