Tkinter Button Color Changer

  • Share this:

Code introduction


This function creates a tkinter window with a button. Each time the button is clicked, its background color is changed randomly.


Technology Stack : tkinter

Code Type : Function

Code Difficulty : Intermediate


                
                    
import tkinter as tk
import random

def random_button_color():
    def change_color():
        color = random.choice(['red', 'green', 'blue', 'yellow', 'purple'])
        button.config(bg=color)
    
    root = tk.Tk()
    button = tk.Button(root, text="Change Color", command=change_color)
    button.pack(pady=20)
    root.mainloop()                
              
Tags: