簡體   English   中英

如何在Tkinter中動態更改按鈕的顏色?

[英]How can I dynamically change the color of a button in Tkinter?

如何在Tkinter中動態更改按鈕的背景顏色?

它僅在初始化按鈕時起作用:

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

我已經試過了:

   self.colorB.bg = "#234"

但這不起作用..謝謝

使用配置方法

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

對於我一生,僅使用configure方法就無法使其正常工作。 最終可行的方法是將所需的顏色(在我的情況下為按鈕)設置為StringVar()(直接設置為get()),然后也使用按鈕上的配置。

我為我最需要的用例編寫了一個非常普通的示例(其中有很多按鈕,我需要引用它們(在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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM