You can download this code by clicking the button below.
This code is now available for download.
The code defines a function named `random_color` that generates a random hexadecimal color code. Another function `create_random_button` creates a button with a background color set to a randomly generated color. When the button is clicked, the `change_button_color` function is called to change the button's background color to a new random color.
Technology Stack : Python, tkinter
Code Type : Function
Code Difficulty : Intermediate
import tkinter as tk
import random
def random_color():
"""
Generates a random color in hexadecimal format.
"""
return "#{:06x}".format(random.randint(0, 0xFFFFFF))
def create_random_button(root):
"""
Creates a button with a random color in the tkinter root window.
"""
color = random_color()
button = tk.Button(root, text="Click Me", bg=color, command=lambda: change_button_color(root, color))
button.pack(pady=20)
def change_button_color(root, color):
"""
Changes the color of the button to a new random color.
"""
new_color = random_color()
root.config(bg=new_color)
def main():
root = tk.Tk()
root.title("Random Color Button")
create_random_button(root)
root.mainloop()
if __name__ == "__main__":
main()