简体   繁体   English

单击按钮后更改按钮的颜色 - tkinter

[英]Change the color of button after it is clicked on - tkinter

I have a question about buttons using tkinter.我对使用 tkinter 的按钮有疑问。 I created a button, but if it is clicked on I want it to change its color.我创建了一个按钮,但如果单击它,我希望它改变它的颜色。 For example, if the button is red, it turns to blue and it remains blue after that.例如,如果按钮是红色的,它会变成蓝色,然后保持蓝色。 I know that I can use a condition and if the button is clicked, I use button.configure() to change his color, but I do not know how this condition looks like.我知道我可以使用一个条件,如果单击按钮,我使用button.configure()来更改他的颜色,但我不知道这个条件是什么样的。 Sorry if it is an easy question, I was trying to find it by myself and it did not work.抱歉,如果这是一个简单的问题,我试图自己找到它,但没有奏效。

One easy way would be to check what the current color is, and then change color if necessary.一种简单的方法是检查当前颜色是什么,然后在必要时更改颜色。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM