You can download this code by clicking the button below.
This code is now available for download.
Tkinter, random selection, button event handling
Technology Stack : Tkinter, random selection, button event handling
Code Type : The type of code
Code Difficulty : Intermediate
import tkinter as tk
import random
def create_random_button(root, text):
# Create a random button with random text and color
color = random.choice(['red', 'green', 'blue', 'yellow', 'purple'])
button = tk.Button(root, text=text, bg=color, command=lambda: change_button_color(root, color))
button.pack()
def change_button_color(root, color):
# Change the color of the button to a random color
new_color = random.choice(['red', 'green', 'blue', 'yellow', 'purple'])
for widget in root.winfo_children():
if isinstance(widget, tk.Button):
widget.config(bg=new_color)
# Create the main window
root = tk.Tk()
root.title("Random Button Color")
# Create a random button with a random initial text
create_random_button(root, "Click Me")
# Start the main loop
root.mainloop()