【问题标题】:How to change button colour in python [closed]如何在python中更改按钮颜色[关闭]
【发布时间】:2020-12-09 14:41:10
【问题描述】:

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

【问题讨论】:

  • 您使用的是什么 GUI 框架?有很多,每个人的答案都不一样。最好还显示您是如何创建按钮的。

标签: python button


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-20
    • 2023-01-15
    • 2018-01-12
    • 2015-08-16
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2014-11-05
    相关资源
    最近更新 更多