Creating a Tkinter Button with Random Background Color

  • Share this:

Code introduction


This function creates a tkinter button and sets a random background color for it.


Technology Stack : tkinter

Code Type : Function

Code Difficulty : Intermediate


                
                    
import tkinter as tk
import random

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

def create_button_with_random_color(root):
    color = random_color()
    button = tk.Button(root, text="Click Me!", bg=color)
    button.pack(pady=20)
    return button

# JSON Explanation                
              
Tags: