在 Tkinter 中动态更改小部件背景颜色 [英] Dynamically change widget background color in Tkinter

查看:56
本文介绍了在 Tkinter 中动态更改小部件背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 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.).

我的第一个想法是使用一个全局变量,例如,我将其设置为 red",并将所有小部件 background 选项与全局变量相关联.然后,在按下按钮时,我会将全局变量更改为 green"(这样所有小部件的背景都会发生变化)但没有任何反应.

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.

我的理解是.mainloop() 类型的更新 窗口.当我的变量更改不重新启动我的应用程序时,如何让小部件更改背景颜色?

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?

推荐答案

从我的第一印象来看,我认为这应该是你要找的,作为一个简单的例子

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

这篇关于在 Tkinter 中动态更改小部件背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆