【问题标题】:Change the color of button after it is clicked on - tkinter单击按钮后更改按钮的颜色 - tkinter
【发布时间】:2021-02-10 16:53:50
【问题描述】:

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

【问题讨论】:

  • 您可以在按钮的command 选项的回调中使用.configure() 简单地更改按钮颜色。

标签: python tkinter button


【解决方案1】:

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

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

【讨论】:

  • 我明白了,谢谢。如果我想在执行代码后更改其颜色,则可以使用此功能,但是您知道如何针对这种情况更改此代码:如果我单击一个按钮,则更改其颜色,如果我不单击就可以了,保持初始颜色?如果单击按钮,我不知道如何编写该条件
  • 嗯...,我想我不明白你想要发生什么。如果您单击按钮,它会改变颜色,如果您不单击它,则会保留原始颜色。我在这里想念什么吗?
猜你喜欢
  • 2021-07-31
  • 1970-01-01
  • 1970-01-01
  • 2021-03-18
  • 2018-08-01
  • 2015-06-04
  • 1970-01-01
  • 1970-01-01
  • 2015-01-26
相关资源
最近更新 更多