Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

python - Dynamically change widget background color in 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...