import tkinter as tk
import json
import random
# File to store flashcards
FLASHCARDS_FILE = "flashcards.json"
class FlashcardApp:
def __init__(self, root):
self.root = root
self.root.title("Flashcard App")
self.root.geometry("400x300")
self.flashcards = self.load_flashcards()
self.current_flashcard = {}
# UI Elements
self.label = tk.Label(root, text="Press 'Next' to start!", font=("Arial", 14), wraplength=350)
self.label.pack(pady=20)
self.flip_button = tk.Button(root, text="Flip", command=self.flip_card)
self.flip_button.pack()
self.next_button = tk.Button(root, text="Next", command=self.next_card)
self.next_button.pack()
self.add_button = tk.Button(root, text="Add Flashcard", command=self.add_flashcard)
self.add_button.pack()
def load_flashcards(self):
try:
with open(FLASHCARDS_FILE, "r") as file:
return json.load(file)
except FileNotFoundError:
return []
def save_flashcards(self):
with open(FLASHCARDS_FILE, "w") as file:
json.dump(self.flashcards, file)
def next_card(self):
if not self.flashcards:
self.label.config(text="No flashcards available. Add some!")
else:
self.current_flashcard = random.choice(self.flashcards)
self.label.config(text=f"Q: {self.current_flashcard['question']}")
def flip_card(self):
if self.current_flashcard:
self.label.config(text=f"A: {self.current_flashcard['answer']}")
def add_flashcard(self):
add_window = tk.Toplevel(self.root)
add_window.title("Add Flashcard")
add_window.geometry("300x200")
tk.Label(add_window, text="Question:").pack()
question_entry = tk.Entry(add_window, width=40)
question_entry.pack()
tk.Label(add_window, text="Answer:").pack()
answer_entry = tk.Entry(add_window, width=40)
answer_entry.pack()
def save_new_flashcard():
question = question_entry.get()
answer = answer_entry.get()
if question and answer:
self.flashcards.append({"question": question, "answer": answer})
self.save_flashcards()
add_window.destroy()
save_button = tk.Button(add_window, text="Save", command=save_new_flashcard)
save_button.pack()
# Run the app
root = tk.Tk()
app = FlashcardApp(root)
root.mainloop()
No comments:
Post a Comment