Загрузка данных
#---------------------------------------------------ГЕНЕРАТОР ТЕСТА---------------------------------------------------
import tkinter as tk
from tkinter import filedialog, messagebox
import random
from docx import Document
INVISIBLE_MARKER = "\u200b"
class QuizGenerator:
def __init__(self, root):
self.root = root
self.root.title("Генератор тестов (скрытая маркировка)")
self.root.geometry("450x250")
self.all_questions = []
self.current_test = []
tk.Label(root, text="Генератор тестов (вопросы из таблиц)", font=("Arial", 12, "bold")).pack(pady=10)
self.btn_load = tk.Button(root, text="1. Загрузить документ (.docx)", command=self.load_file, width=35)
self.btn_load.pack(pady=5)
self.btn_generate = tk.Button(root, text="2. Сгенерировать тест (30 вопр.)", command=self.generate_test,
width=35, state=tk.DISABLED)
self.btn_generate.pack(pady=5)
self.btn_save = tk.Button(root, text="3. Сохранить в новый файл", command=self.save_test, width=35,
state=tk.DISABLED)
self.btn_save.pack(pady=5)
self.status_label = tk.Label(root, text="Ожидание загрузки...", fg="gray")
self.status_label.pack(pady=10)
def load_file(self):
file_path = filedialog.askopenfilename(filetypes=[("Word documents", "*.docx")])
if file_path:
try:
doc = Document(file_path)
self.all_questions = []
for table in doc.tables:
content = []
for row in table.rows:
for cell in row.cells:
text = cell.text.strip()
if text and text not in content:
content.append(text)
if content:
question = content[0]
options = content[1:]
if options:
options[0] = INVISIBLE_MARKER + options[0]
random.shuffle(options)
formatted_block = question + "\n"
for idx, option in enumerate(options):
letter = chr(97 + idx) # a, b, c...
formatted_block += f" {letter}) {option}\n"
self.all_questions.append(formatted_block)
if not self.all_questions:
messagebox.showwarning("Внимание", "В документе не найдено таблиц.")
else:
self.status_label.config(text=f"Найдено вопросов: {len(self.all_questions)}", fg="green")
self.btn_generate.config(state=tk.NORMAL)
except Exception as e:
messagebox.showerror("Ошибка", f"Не удалось прочитать файл: {e}")
def generate_test(self):
# Берем 30 случайных вопросов из общего списка
count = min(len(self.all_questions), 30)
self.current_test = random.sample(self.all_questions, count)
self.btn_save.config(state=tk.NORMAL)
messagebox.showinfo("Готово", f"Сгенерирован тест из {count} вопросов.")
def save_test(self):
save_path = filedialog.asksaveasfilename(defaultextension=".docx", filetypes=[("Word documents", "*.docx")])
if save_path:
try:
new_doc = Document()
new_doc.add_heading('Вариант теста', 0)
for i, q_block in enumerate(self.current_test, 1):
p = new_doc.add_paragraph()
run = p.add_run(f"Вопрос №{i}:")
run.bold = True
p.add_run(f"\n{q_block}")
new_doc.add_paragraph("-" * 30)
new_doc.save(save_path)
messagebox.showinfo("Успех", f"Файл сохранен: {save_path}")
except Exception as e:
messagebox.showerror("Ошибка", f"Ошибка сохранения: {e}")
if __name__ == "__main__":
root = tk.Tk()
app = QuizGenerator(root)
root.mainloop()