You can download this code by clicking the button below.
This code is now available for download.
The code defines a function named xxx that changes the background color of a tkinter canvas to a random color when a button is clicked.
Technology Stack : tkinter, random number generation
Code Type : Event handler
Code Difficulty : Intermediate
import tkinter as tk
import random
def generate_random_color():
"""
Generates a random color in hexadecimal format.
"""
return "#{:06x}".format(random.randint(0, 0xFFFFFF))
def xxx(event):
"""
This function changes the background color of a tkinter canvas to a random color
when a button is clicked.
"""
canvas.config(bg=generate_random_color())
# Create the main window
root = tk.Tk()
root.title("Random Color Generator")
# Create a canvas widget
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
# Create a button widget that will trigger the color change
button = tk.Button(root, text="Change Color", command=xxx)
button.pack()
# Start the tkinter event loop
root.mainloop()