Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically change widget background color in Tkinter

Tags:

python

tkinter

I have a simple tkinter window. It consists of a small window, a timer, and a button to set timer. I don't want to go in details with the code.

I want to change the background of all the widgets in my window(buttons, label, Etc.).

My first thought is to use a global variable which I will set to "red" for example, and associate all the widgets background option with the global variable. Then, on button press I will change the global variable to "green" (so that the background of all widgets change) but nothing happens.

My understanding was the .mainloop() sort of updated the window. How can I have the widgets to change background color when my variable change without restarting my application?

like image 321
Morten Larsen Avatar asked Nov 27 '12 16:11

Morten Larsen


People also ask

How do you change the color of the background in tkinter?

There are two ways through which you can change the background color of window in Tkinter. They are: using configure(bg='') method of tkinter.Tk class. or. directly set the property bg of tkinter.Tk.

What do we use to change the background color of a widget?

ttk module is used for styling the tkinter widgets such as setting the background color, foreground color, activating the buttons, adding images to labels, justifying the height and width of widgets, etc. In order to add a background color in tkinter widgets, we can specify the background property in the widget.

How do you change the color of a tkinter label programmatically?

The attribute fg can be used to have the text in another colour and the attribute bg can be used to change the background colour of the label.

What is FG and BG in tkinter?

foreground − Foreground color for the widget. This can also be represented as fg. highlightbackground − Background color of the highlight region when the widget has focus. highlightcolor − Foreground color of the highlight region when the widget has focus.


1 Answers

from my first impression I think this should be what you're looking for, as a simple example

from Tkinter import *

root = Tk()
global colour
global colourselection 
global count 
colour = ""
colourselection= ['red', 'blue']
count = 1

def start(parent):
    Tk.after(parent, 1000, change)

def change():
    global colour 
    global colourselection
    global count 
    if (count < 2 ):
        colour = colourselection[count]
        button.configure(bg = colour)
        count + 1
    else:
        colour = colourselection[count]
        button.configure(bg = colour)
        count = 1 
    start(root)



button = Button(text = 'start', command = lambda: start(root))
button.pack()

root.mainloop()

I'm sure you can work out any issues, it's not been tested

like image 118
jbaldwin Avatar answered Oct 16 '22 13:10

jbaldwin