python - 单击按钮后更改按钮的颜色 - tkinter
问题描述
我对使用 tkinter 的按钮有疑问。我创建了一个按钮,但如果单击它,我希望它改变它的颜色。例如,如果按钮是红色的,它会变成蓝色,然后保持蓝色。我知道我可以使用一个条件,如果单击按钮,我会使用它button.configure()
来更改他的颜色,但我不知道这个条件是什么样的。抱歉,如果这是一个简单的问题,我试图自己找到它,但没有奏效。
解决方案
一种简单的方法是检查当前颜色是什么,然后在必要时更改颜色。
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()
推荐阅读
- php - 如何在谷歌地方获得星级评分
- javascript - Three.js - 在缩放时保持对象静态
- windows - 带有 Windows 身份验证的 WCF 服务不会拒绝不受信任的用户
- c# - 如何在自己的代码中模仿(单参数)重载解析规则?
- asp.net - 在 cshtml 中使用 cshtml.cs 中的 List
- json - 如何从 JSON API 解析和存储前一天
- php - 我的布尔代码无法通知错误的用户名和密码
- python - 他们如何在 Django 项目的 python 控制台中运行这些命令?
- c++ - 查找点属于哪个三角形的优化技巧
- node.js - 使用模块“crypto”对十六进制数据进行 NodeJS DES ECB 加密