首页 > 解决方案 > 如何在python中更改按钮颜色

问题描述

我想用 tkinter 创建一个按钮,当你点击它时它会改变颜色。我知道我可以通过删除按钮来做到这一点,但是否还有其他可能性。

标签: pythonbutton

解决方案


好吧,有很多选择。您可以使用许多 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()

推荐阅读