Of course! This is a great project that combines file handling, API interaction, and a graphical user interface (GUI).
Here is a complete Python script that accomplishes your goal. I've chosen to use the built-in tkinter library for the GUI because it doesn't require any extra installation.
First, let's break down the plan:
- File Handling: The script will be designed to read
.txt files by default as they are much simpler and more reliable for this task. I will also include the logic to handle .docx files, but this will require an extra library. Each term in the file should be on a new line.
- Randomness: We'll make a request to the
random.org JSON-RPC API to get truly random numbers. These numbers will be the indices for the terms we select from our list.
- GUI: We'll use
tkinter to create a simple window with a button to select a file, a button to draw the terms, and a text area to display the results.
Step 1: Prerequisites
You'll need to install a couple of Python libraries.
requests: For making the API call to random.org.
python-docx: (Optional) Only if you absolutely need to use .docx files.
You can install them using pip:
pip install requests
pip install python-docx
random.org API Key:
For any serious use, random.org requires an API key.
- Go to the random.org API page and get a free key.
- You will need to paste this key into the script where indicated.
Step 2: The Script
Save the following code as a Python file (e.g., term_picker.py).
import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext
import requests
import os
import sys
# Optional: required for reading .docx files
try:
import docx
except ImportError:
docx = None # Flag that the library is not available
# --- CONFIGURATION ---
# IMPORTANT: Replace this with your own random.org API key
# Get one for free here: https://api.random.org/api-keys
RANDOM_ORG_API_KEY = "YOUR_API_KEY_HERE"
RANDOM_ORG_API_URL = "https://api.random.org/json-rpc/2/invoke"
NUM_TERMS_TO_DRAW = 5
# --- CORE LOGIC ---
def get_terms_from_file(filepath):
"""Reads terms from a file, one term per line."""
if not os.path.exists(filepath):
raise FileNotFoundError("The specified file does not exist.")
terms = []
try:
if filepath.lower().endswith('.txt'):
with open(filepath, 'r', encoding='utf-8') as f:
terms = [line.strip() for line in f if line.strip()]
elif filepath.lower().endswith('.docx'):
if docx is None:
raise ImportError("The 'python-docx' library is required to read .docx files.\n"
"Please install it using: pip install python-docx")
document = docx.Document(filepath)
terms = [p.text.strip() for p in document.paragraphs if p.text.strip()]
else:
raise ValueError("Unsupported file type. Please use .txt or .docx")
except Exception as e:
# Re-raise with a more user-friendly message
raise type(e)(f"Error reading file '{os.path.basename(filepath)}': {e}").with_traceback(sys.exc_info()[2])
return terms
def get_random_indices_from_api(num_indices, max_index):
"""Fetches a list of random indices from random.org."""
if RANDOM_ORG_API_KEY == "YOUR_API_KEY_HERE":
raise ValueError("Please replace 'YOUR_API_KEY_HERE' with a real random.org API key.")
payload = {
"jsonrpc": "2.0",
"method": "generateIntegers",
"params": {
"apiKey": RANDOM_ORG_API_KEY,
"n": num_indices,
"min": 0,
"max": max_index,
"replacement": False # Ensures we get unique numbers
},
"id": 42 # A unique identifier for the request
}
try:
response = requests.post(RANDOM_ORG_API_URL, json=payload, timeout=10)
response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
data = response.json()
if "error" in data:
error_msg = data['error']['message']
raise ConnectionError(f"random.org API error: {error_msg}")
return data['result']['random']['data']
except requests.exceptions.RequestException as e:
raise ConnectionError(f"Network error connecting to random.org: {e}")
# --- GUI APPLICATION ---
class TermPickerApp:
def __init__(self, root):
self.root = root
self.root.title("True Random Term Picker")
self.root.geometry("500x400")
self.filepath = None
self.terms = []
# --- Widgets ---
top_frame = tk.Frame(root, padx=10, pady=10)
top_frame.pack(fill=tk.X)
self.file_btn = tk.Button(top_frame, text="1. Select File...", command=self.select_file)
self.file_btn.pack(side=tk.LEFT, padx=(0, 10))
self.file_label = tk.Label(top_frame, text="No file selected.", fg="grey")
self.file_label.pack(side=tk.LEFT, fill=tk.X, expand=True)
self.draw_btn = tk.Button(root, text="2. Draw 5 Random Terms", font=("Helvetica", 12, "bold"), command=self.draw_terms, state=tk.DISABLED)
self.draw_btn.pack(pady=10, padx=10, fill=tk.X)
results_frame = tk.Frame(root, padx=10, pady=10)
results_frame.pack(fill=tk.BOTH, expand=True)
results_frame.grid_rowconfigure(0, weight=1)
results_frame.grid_columnconfigure(0, weight=1)
self.results_text = scrolledtext.ScrolledText(results_frame, wrap=tk.WORD, height=10, font=("Courier New", 11))
self.results_text.grid(row=0, column=0, sticky="nsew") # Use grid to make it expandable
self.results_text.insert(tk.END, "Results will be displayed here...")
self.results_text.config(state=tk.DISABLED)
def select_file(self):
"""Opens a file dialog and loads terms from the selected file."""
# Define supported file types
filetypes = [('Text files', '*.txt')]
if docx:
filetypes.append(('Word Documents', '*.docx'))
filetypes.append(('All files', '*.*'))
filepath = filedialog.askopenfilename(filetypes=filetypes)
if not filepath:
return
self.filepath = filepath
try:
self.terms = get_terms_from_file(self.filepath)
self.file_label.config(text=f"{os.path.basename(self.filepath)} ({len(self.terms)} terms)", fg="black")
if len(self.terms) >= NUM_TERMS_TO_DRAW:
self.draw_btn.config(state=tk.NORMAL)
else:
self.draw_btn.config(state=tk.DISABLED)
messagebox.showerror("Not Enough Terms",
f"The file must contain at least {NUM_TERMS_TO_DRAW} non-empty lines.")
except (ValueError, FileNotFoundError, ImportError, Exception) as e:
messagebox.showerror("Error Reading File", str(e))
self.filepath = None
self.terms = []
self.file_label.config(text="No file selected.", fg="grey")
self.draw_btn.config(state=tk.DISABLED)
def draw_terms(self):
"""The main action: gets random indices and displays the corresponding terms."""
self.results_text.config(state=tk.NORMAL)
self.results_text.delete('1.0', tk.END)
self.results_text.insert(tk.END, "Fetching true random numbers from random.org...")
self.root.update_idletasks() # Force GUI update
try:
max_index = len(self.terms) - 1
random_indices = get_random_indices_from_api(NUM_TERMS_TO_DRAW, max_index)
# Display results
self.results_text.delete('1.0', tk.END)
self.results_text.insert(tk.END, "--- Your 5 Truly Random Terms ---\n\n")
for i, index in enumerate(random_indices):
self.results_text.insert(tk.END, f"{i+1}. {self.terms[index]}\n")
except (ValueError, ConnectionError) as e:
messagebox.showerror("Error", str(e))
self.results_text.delete('1.0', tk.END)
self.results_text.insert(tk.END, "An error occurred. Please try again.")
finally:
self.results_text.config(state=tk.DISABLED)
if __name__ == "__main__":
root = tk.Tk()
app = TermPickerApp(root)
root.mainloop()
Step 3: How to Use It
-
Prepare Your File: Create a .txt file (e.g., my_terms.txt). Place each term you want to draw from on a new line.
Example my_terms.txt:
Quantum Entanglement
General Relativity
Photosynthesis
The Industrial Revolution
String Theory
Natural Selection
Machine Learning
Black Hole
-
Edit the Script: Open the term_picker.py file and replace "YOUR_API_KEY_HERE" with the actual API key you got from random.org.
-
Run the Script:
python term_picker.py
-
Use the GUI:
- A window will appear.
- Click the "1. Select File..." button and choose your
my_terms.txt (or .docx) file. The label will update to show the file name and the number of terms found.
- The "2. Draw 5 Random Terms" button will become active. Click it.
- The script will contact
random.org, get five unique random numbers, and display the corresponding terms from your file in the text box below.