python - 如何在python中更改按钮颜色
问题描述
我想用 tkinter 创建一个按钮,当你点击它时它会改变颜色。我知道我可以通过删除按钮来做到这一点,但是否还有其他可能性。
解决方案
好吧,有很多选择。您可以使用许多 GUI 库,例如 Kivy、Tkinter。但由于我不知道你在使用什么,我只是要在 Tkinter 中制作一个程序。
这是代码 -
# importing modules
from tkinter import *
import random
# making a window
root = Tk()
root.geometry("400x400")
# just for decoration or the Background Color
mainframe = Frame(root, bg="#121212", width=400, height=400)
mainframe.pack()
# the function changing color
def color_changing(buttonObject):
# randomizes the color in hexcode
r = lambda: random.randint(0, 255)
color = '#%02X%02X%02X' % (r(), r(), r())
# .config configures an Object in Tkinter
buttonObject.config(bg=color)
# making a button
button = Button(root, width=10, font=('Segoe UI', 32, "bold"), text="Click Me", command=lambda: color_changing(button))
# root in Button() is the place where the button has to be placed
# text, width, font, etc are all attributes
# command is a simple way to call a function
# placing it in a specific location
button.place(relx=0.5, rely=0.5, anchor=CENTER)
# making the window so it does not stop running till it is said to be
root.mainloop()
推荐阅读
- android - 如何实现 RecyclerView onClick 监听器和长按监听器方法
- python-3.x - 如何在用 pytest 测试的函数中替换对 random.randint() 的调用?
- python - Python 在反序列化 json 方面比 C++ 更快。为什么?Python 3 中的 json 库是用 C/C++ 还是其他低级语言编写的?
- xero-api - 检索 Accounts API 端点时 Xero API 401 未经授权
- python - 使用python从FASTA文件中获取标题行
- css - 为什么“选择:焦点{大纲:无}”不起作用?
- c++ - 有效地将两个整数 x 和 y 转换为浮点 xy
- mysql - 来自不同表的多个 SELECT 语句
- laravel - 重定向回不保存 auth()->user
- scala - 在 Chisel 中测试 RegisterFile