Tkinter Button Color Changer

  • Share this:

Code introduction


This function creates a Tkinter window with a button. Each time the button is clicked, the background color of the button changes randomly.


Technology Stack : Tkinter

Code Type : Tkinter GUI Function

Code Difficulty : Intermediate


                
                    
import tkinter as tk
import random

def generate_random_color():
    return "#{:06x}".format(random.randint(0, 0xFFFFFF))

def random_button_colorization(root):
    def change_button_color():
        color = generate_random_color()
        button.config(bg=color)
    
    button = tk.Button(root, text="Change Color", command=change_button_color)
    button.pack(pady=20)
    root.mainloop()                
              
Tags: