【发布时间】:2020-12-09 14:41:10
【问题描述】:
我想用 tkinter 创建一个按钮,当你点击它时它会改变颜色。我知道我可以通过删除按钮来做到这一点,但是否还有其他可能。
【问题讨论】:
-
您使用的是什么 GUI 框架?有很多,每个人的答案都不一样。最好还显示您是如何创建按钮的。
我想用 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()
【讨论】: