You can download this code by clicking the button below.
This code is now available for download.
The code defines a function `create_random_button` that takes a Tkinter root window, button text, and command as arguments. This function generates a button with a random color and adds it to the root window.
Technology Stack : Tkinter, random number generation
Code Type : Function
Code Difficulty : Intermediate
import tkinter as tk
import random
def create_random_button(root, text, command):
# Create a random color for the button
random_color = f'#{random.randint(0, 0xFFFFFF):06x}'
# Create a button with the given text and a random color
button = tk.Button(root, text=text, bg=random_color, command=command)
button.pack(pady=20)
# Usage example
if __name__ == "__main__":
root = tk.Tk()
create_random_button(root, "Click Me", lambda: print("Button clicked!"))
root.mainloop()