Randomly Generated Button Layout in Tkinter

  • Share this:

Code introduction


This function creates a Tkinter window and randomly generates 2 to 5 buttons. Each button, when clicked, will print out the corresponding button number.


Technology Stack : Tkinter

Code Type : Tkinter GUI layout

Code Difficulty : Intermediate


                
                    
import tkinter as tk
import random

def random_button_layout(root):
    # Create a list of button texts
    button_texts = ["Button 1", "Button 2", "Button 3", "Button 4", "Button 5"]
    
    # Randomly select the number of buttons to display
    num_buttons = random.randint(2, 5)
    
    # Create buttons randomly on the root window
    for i in range(num_buttons):
        button_text = random.choice(button_texts)
        button = tk.Button(root, text=button_text, command=lambda i=i: print(f"Button {i+1} clicked"))
        button.pack(fill='both', expand=True)
        
    # Configure the root window to be resizable
    root.resizable(True, True)

# Example usage
if __name__ == "__main__":
    root = tk.Tk()
    random_button_layout(root)
    root.mainloop()                
              
Tags: