2010-04-30 189 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')