Skip to content

Commit 420791b

Browse files
authored
Create Random-Joke-Generator.py
1 parent 3c5ace3 commit 420791b

1 file changed

Lines changed: 194 additions & 0 deletions

File tree

Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
import sys
2+
import os
3+
import threading
4+
import tkinter as tk
5+
from tkinter import ttk, messagebox, filedialog
6+
import sv_ttk
7+
import random
8+
9+
# =========================
10+
# Helpers
11+
# =========================
12+
def resource_path(file_name):
13+
base_path = getattr(sys, "_MEIPASS", os.path.dirname(os.path.abspath(__file__)))
14+
return os.path.join(base_path, file_name)
15+
16+
def set_status(msg):
17+
status_var.set(msg)
18+
root.update_idletasks()
19+
20+
# =========================
21+
# App Setup
22+
# =========================
23+
root = tk.Tk()
24+
root.title("Random Joke Generator")
25+
root.geometry("600x500")
26+
root.minsize(600, 500)
27+
sv_ttk.set_theme("light")
28+
29+
# =========================
30+
# Globals
31+
# =========================
32+
dark_mode_var = tk.BooleanVar(value=False)
33+
joke_result_var = tk.StringVar(value="")
34+
joke_history = [] # List of tuples: (joke_type, joke)
35+
36+
# =========================
37+
# Theme Toggle
38+
# =========================
39+
def toggle_theme():
40+
bg = "#2E2E2E" if dark_mode_var.get() else "#FFFFFF"
41+
fg = "white" if dark_mode_var.get() else "black"
42+
root.configure(bg=bg)
43+
for w in ["TFrame", "TLabel", "TLabelframe", "TLabelframe.Label", "TCheckbutton"]:
44+
style.configure(w, background=bg, foreground=fg)
45+
46+
# =========================
47+
# Joke Data & Generation
48+
# =========================
49+
JOKES = {
50+
"Classic": [
51+
"Why did the scarecrow win an award? Because he was outstanding in his field!",
52+
"Why don’t scientists trust atoms? Because they make up everything!",
53+
"I told my computer I needed a break, and it said 'No problem – I'll go to sleep.'"
54+
],
55+
"Dad Jokes": [
56+
"I would avoid the sushi if I was you. It’s a little fishy.",
57+
"Why did the math book look sad? Because it had too many problems.",
58+
"I only know 25 letters of the alphabet… I don’t know y."
59+
],
60+
"Programming": [
61+
"Why do programmers prefer dark mode? Because light attracts bugs.",
62+
"There are 10 types of people in the world: those who understand binary and those who don’t.",
63+
"Why did the developer go broke? Because he used up all his cache."
64+
]
65+
}
66+
67+
def generate_joke(joke_type):
68+
jokes = JOKES.get(joke_type, sum(JOKES.values(), []))
69+
return random.choice(jokes)
70+
71+
# =========================
72+
# Joke Generation & History
73+
# =========================
74+
def create_joke():
75+
joke_type = joke_type_var.get()
76+
if not joke_type:
77+
messagebox.showwarning("Select Type", "Please select a joke type.")
78+
return
79+
80+
set_status("Generating joke...")
81+
threading.Thread(target=_generate_joke_thread, args=(joke_type,), daemon=True).start()
82+
83+
def _generate_joke_thread(joke_type):
84+
joke = generate_joke(joke_type)
85+
joke_result_var.set(joke)
86+
add_to_history(joke_type, joke)
87+
set_status("Joke generated!")
88+
89+
def add_to_history(joke_type, joke):
90+
joke_history.append((joke_type, joke))
91+
preview = joke[:80] + "..." if len(joke) > 80 else joke
92+
history_list.insert(tk.END, f"[{joke_type}] {preview}")
93+
94+
def export_history_txt():
95+
if not joke_history:
96+
messagebox.showinfo("Empty History", "No jokes to export.")
97+
return
98+
99+
file_path = filedialog.asksaveasfilename(
100+
defaultextension=".txt",
101+
filetypes=[("Text Files", "*.txt")],
102+
title="Export Joke History"
103+
)
104+
if not file_path:
105+
return
106+
107+
try:
108+
with open(file_path, "w", encoding="utf-8") as f:
109+
f.write("Random Joke Generator History\n")
110+
f.write("=" * 50 + "\n\n")
111+
for i, (jtype, joke) in enumerate(joke_history, 1):
112+
f.write(f"{i}. Type: {jtype}\n")
113+
f.write(f" Joke: {joke}\n\n")
114+
set_status("Joke history exported")
115+
messagebox.showinfo("Export Successful", "Joke history saved successfully.")
116+
except Exception as e:
117+
messagebox.showerror("Export Failed", str(e))
118+
119+
def view_selected_joke(event=None):
120+
selection = history_list.curselection()
121+
if not selection:
122+
messagebox.showinfo("No Selection", "Please select a joke from history.")
123+
return
124+
index = selection[0]
125+
_, joke = joke_history[index]
126+
127+
joke_window = tk.Toplevel(root)
128+
joke_window.title("Full Joke")
129+
joke_window.geometry("500x200")
130+
131+
# Make it modal
132+
joke_window.transient(root) # Keep above main window
133+
joke_window.grab_set() # Block interaction with main window
134+
135+
tk.Label(joke_window, text=joke, wraplength=480, font=("Segoe UI", 14)).pack(expand=True, fill="both", padx=10, pady=10)
136+
137+
# =========================
138+
# Styles
139+
# =========================
140+
style = ttk.Style()
141+
style.theme_use("clam")
142+
style.configure("Action.TButton", font=("Segoe UI", 11, "bold"), padding=8)
143+
144+
# =========================
145+
# Status Bar
146+
# =========================
147+
status_var = tk.StringVar(value="Ready")
148+
ttk.Label(root, textvariable=status_var, anchor="w").pack(side=tk.BOTTOM, fill="x")
149+
150+
# =========================
151+
# UI Layout
152+
# =========================
153+
main = ttk.Frame(root, padding=20)
154+
main.pack(expand=True, fill="both")
155+
main.columnconfigure(0, weight=1)
156+
157+
ttk.Label(main, text="Random Joke Generator", font=("Segoe UI", 22, "bold")).grid(row=0, column=0, sticky="ew", pady=(0,10))
158+
159+
# Joke Type Selection
160+
joke_type_var = tk.StringVar()
161+
ttk.Label(main, text="Select Joke Type:", font=("Segoe UI", 12)).grid(row=1, column=0, sticky="w")
162+
ttk.Combobox(main, textvariable=joke_type_var, values=list(JOKES.keys()), font=("Segoe UI", 12)).grid(row=2, column=0, sticky="ew", pady=2)
163+
164+
# Joke Result
165+
ttk.Label(main, text="Generated Joke:", font=("Segoe UI", 12)).grid(row=3, column=0, sticky="w")
166+
joke_result_label = ttk.Label(main, textvariable=joke_result_var, wraplength=550, font=("Segoe UI", 14))
167+
joke_result_label.grid(row=4, column=0, sticky="w", pady=5)
168+
169+
# Controls
170+
controls = ttk.Frame(main)
171+
controls.grid(row=5, column=0, sticky="ew", pady=8)
172+
controls.columnconfigure((0,1), weight=1)
173+
174+
ttk.Button(controls, text="😂 Generate Joke", command=create_joke, style="Action.TButton").grid(row=0, column=0, padx=4, sticky="ew")
175+
ttk.Button(controls, text="📤 Export History", command=export_history_txt, style="Action.TButton").grid(row=0, column=1, padx=4, sticky="ew")
176+
177+
# Joke History Vault
178+
vault = ttk.LabelFrame(main, text="Joke History Vault", padding=10)
179+
vault.grid(row=6, column=0, sticky="nsew", pady=10)
180+
main.rowconfigure(6, weight=1)
181+
182+
history_list = tk.Listbox(vault, font=("Segoe UI", 10), height=7)
183+
history_list.pack(fill="both", expand=True)
184+
history_list.bind("<Double-Button-1>", view_selected_joke)
185+
186+
# Options
187+
options_frame = ttk.Frame(main)
188+
options_frame.grid(row=7, column=0, sticky="w", pady=6)
189+
ttk.Checkbutton(options_frame, text="Dark Mode", variable=dark_mode_var, command=toggle_theme).pack(side="left", padx=(0,10))
190+
191+
# =========================
192+
# Run App
193+
# =========================
194+
root.mainloop()

0 commit comments

Comments
 (0)