如何动态改变Tkinter中按钮的颜色?

0 投票
2 回答
12316 浏览
提问于 2025-04-16 05:55

我该如何在Tkinter中动态改变按钮的背景颜色呢?

这个方法只在我初始化按钮的时候有效:

self.colorB = tk.Button(self.itemFrame, text="", bg="#234", width=10, command=self.pickColor)

我试过这个:

   self.colorB.bg = "#234"

但是它不管用……谢谢!

2 个回答

0

我试了很多方法,就是没法光用configure这个方法让它工作。最后成功的办法是把我想要的颜色(在我的例子里是一个按钮的颜色)设置成一个StringVar()(直接用get()方法),然后再对按钮使用config。

我写了一个很通用的例子,适合我最常用的情况(就是有很多按钮,我需要引用它们,这个例子在Python 2和3中都测试过):

Python 3:

import tkinter as tk

Python 2:

import Tkinter as tk

代码

root = tk.Tk()
parent = tk.Frame(root)

buttonNames = ['numberOne','numberTwo','happyButton']
buttonDic = {}
buttonColors = {}

def change_color(name):
    buttonColors[name].set("red")
    buttonDic[name].config(background=buttonColors[name].get())

for name in buttonNames:
    buttonColors[name] = tk.StringVar()
    buttonColors[name].set("blue")
    buttonDic[name] = tk.Button(
            parent,
            text = name,
            width = 20,
            background = buttonColors[name].get(),
            command= lambda passName=name: change_color(passName)
            )

parent.grid(row=0,column=0)
for i,name in enumerate(buttonNames):
    buttonDic[name].grid(row=i,column=0)

root.mainloop()
6

使用配置方法

self.colorB.configure(bg = "#234")

撰写回答