Random Color Changer with Tkinter

  • Share this:

Code introduction


This code creates a Tkinter window with a button and a label. When the button is clicked, the text color of the label changes randomly.


Technology Stack : Tkinter

Code Type : GUI Application

Code Difficulty : Intermediate


                
                    
import tkinter as tk
import random

def random_button_click():
    color = random.choice(['red', 'green', 'blue', 'yellow', 'purple'])
    label.config(fg=color)

def create_random_button(root):
    button = tk.Button(root, text="Click Me!", command=random_button_click)
    button.pack()

    label = tk.Label(root, text="Press the button to change color")
    label.pack()

# Create a root window
root = tk.Tk()

# Create a random button
create_random_button(root)

# Start the main loop
root.mainloop()                
              
Tags: