2025년 3월 19일 수요일

Python Lottery Number Generator with GUI - Code & Explanation

 





import tkinter as tk
import random

def generate_numbers():
    """Generates 6 unique lottery numbers between 1 and 45."""
    numbers = random.sample(range(1, 46), 6)  # Select 6 unique numbers from 1 to 45
    numbers.sort()  # Sort the numbers in ascending order
    result_label.config(text=f"Lottery Numbers: {', '.join(map(str, numbers))}")

# --- Main Window Setup ---
window = tk.Tk()
window.title("Lottery Number Generator")
window.geometry("300x150")

# --- Widgets ---
instruction_label = tk.Label(window, text="Click the button to generate lottery numbers:")
instruction_label.pack(pady=10)

generate_button = tk.Button(window, text="Generate Numbers", command=generate_numbers)
generate_button.pack()

result_label = tk.Label(window, text="")
result_label.pack(pady=10)

# --- Start the GUI ---
window.mainloop()

-

How to Run:

  1. Save the Code: Save the code as a .py file (e.g., lottery_generator.py).
  2. Run: Open a command prompt or terminal on Windows and navigate to the directory where you saved the file. Then, run the script using python lottery_generator.py.

Code Explanation:

  1. Importing Libraries:


import tkinter as tk
import random
-
  • tkinter: This is Python's standard GUI library. It provides the tools to create windows, buttons, and labels. We import it as tk for convenience.
  • random: This module provides functions for generating random numbers.
   2. generate_numbers() Function:



def generate_numbers():
    """Generates 6 unique lottery numbers between 1 and 45."""
    numbers = random.sample(range(1, 46), 6)  # Select 6 unique numbers from 1 to 45
    numbers.sort()  # Sort the numbers in ascending order
    result_label.config(text=f"Lottery Numbers: {', '.join(map(str, numbers))}")

-
  • random.sample(range(1, 46), 6): This is the core of the lottery number generation.
    • range(1, 46): Creates a sequence of numbers from 1 to 45 (inclusive).
    • random.sample(..., 6): Randomly selects 6 unique numbers from the sequence. This ensures that you don't get duplicate numbers.
  • numbers.sort(): Sorts the generated numbers in ascending order for better readability.
  • result_label.config(text=f"Lottery Numbers: {', '.join(map(str, numbers))}"): Updates the result_label with the generated lottery numbers.
    • map(str, numbers): Converts each number in the numbers list to a string.
    • ', '.join(...): Joins the string representations of the numbers with a comma and a space in between.
    • f"Lottery Numbers: ...": Uses an f-string to create a formatted string that includes the lottery numbers.
    • result_label.config(text=...): Updates the text of the result_label widget.
3.  Main Window Setup:


window = tk.Tk()
window.title("Lottery Number Generator")
window.geometry("300x150")
- Creating Widgets:
  • instruction_label = tk.Label(window, text="Click the button to generate lottery numbers:"): Creates a label that provides instructions to the user.
  • generate_button = tk.Button(window, text="Generate Numbers", command=generate_numbers): Creates a button that says "Generate Numbers". The command=generate_numbers part tells the button to call the generate_numbers() function when it's clicked.
  • result_label = tk.Label(window, text=""): Creates a label that will display the generated lottery numbers. It's initially empty.
Arranging Widgets:
  • instruction_label.pack(pady=10): Places the instruction label in the window using the pack layout manager. pady=10 adds 10 pixels of padding above and below the label.
  • generate_button.pack(): Places the generate button in the window.
  • result_label.pack(pady=10): Places the result label in the window.
Starting the GUI:

window.mainloop()

-

How it Works:

The code creates a window with a label, a button, and another label. When the user clicks the "Generate Numbers" button, the generate_numbers() function is called. This function generates 6 unique random numbers between 1 and 45, sorts them, and then displays them in the result_label. The mainloop() function keeps the window open and waiting for user input.

댓글 없음:

댓글 쓰기

Recommended Posts

Resolving: "error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools"" in AUTOMATIC1111

  Resolving: "error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools"" in AUTOM...