首页 > 解决方案 > 单击按钮后更改按钮的颜色 - tkinter

问题描述

我对使用 tkinter 的按钮有疑问。我创建了一个按钮,但如果单击它,我希望它改变它的颜色。例如,如果按钮是红色的,它会变成蓝色,然后保持蓝色。我知道我可以使用一个条件,如果单击按钮,我会使用它button.configure()来更改他的颜色,但我不知道这个条件是什么样的。抱歉,如果这是一个简单的问题,我试图自己找到它,但没有奏效。

标签: pythontkinterbutton

解决方案


一种简单的方法是检查当前颜色是什么,然后在必要时更改颜色。

import tkinter as tk

root = tk.Tk()

def do_stuff():
    if button.cget('bg') == 'tomato':   # Check current color
        button.config(bg='powder blue', activebackground='powder blue')
    # Do other stuff if you want

button = tk.Button(root, text='Change color', command=do_stuff, 
                   bg='tomato', activebackground='tomato')
button.pack(padx=50, pady=20)

root.mainloop()

推荐阅读