[Python] 纯文本查看 复制代码
import random
from openpyxl import Workbook
from openpyxl.utils import get_column_letter
import tkinter as tk
from tkinter import messagebox
from tkinter import ttk
import os,sys
# 生成加法运算题目
def generate_addition_problems(count=10, s=10, z=2):
problems = []
for _ in range(count):
if z == 2:
a = random.randint(1, s)
b = random.randint(1, s)
answer=a+b
problems.append((f"{a} + {b} = ",answer))
elif z == 3:
a = random.randint(1, s)
b = random.randint(1, s)
c = random.randint(1, s)
answer=a+b+c
problems.append((f"{a} + {b} + {c} = ",answer))
return problems
# 生成减法运算题目
def generate_subtraction_problems(count=10, s=10, z=2):
problems = []
for _ in range(count):
if z == 2:
a = random.randint(1, s)
b = random.randint(1, a) # 确保减法不出现负数
answer=a-b
problems.append((f"{a} - {b} = ",answer))
elif z == 3:
a = random.randint(1, s)
b = random.randint(1, a)
c = random.randint(1, s)
if b + c > a:
b, c = c, b
answer=a-b-c
problems.append((f"{a} - {b} - {c} = ",answer))
return problems
# 生成加减混合运算题目
def generate_mixed_problems(count=10, s=10, z=2):
problems = []
for _ in range(count):
if z == 2:
a = random.randint(1, s)
b = random.randint(1, s)
if random.choice(['+', '-']) == '+':
answer = a + b
problems.append((f"{a} + {b} = ", answer))
else:
if a < b:
a, b = b, a # 确保减法不出现负数
answer = a - b
problems.append((f"{a} - {b} = ", answer))
elif z == 3:
a = random.randint(1, s)
b = random.randint(1, s)
c = random.randint(1, s)
operators = random.choices(['+', '-'], k=2)
if operators[0] == '-' and b > a:
a, b = b, a
if operators[1] == '-' and c > (a - b if operators[0] == '-' else a + b):
b, c = c, b
if operators[0] == '+':
temp_result = a + b
else:
temp_result = a - b
if operators[1] == '+':
answer = temp_result + c
else:
answer = temp_result - c
problem = f'{a}{operators[0]} {b} {operators[1]} {c} ='
problems.append((problem, answer))
return problems
# 将题目写入sheet表
def write_problems_to_sheet(sheet, problems,answers=False):
row = 1
col = 1
for i, (problem,answer)in enumerate(problems, start=1):
# 写入题目编号
sheet[f"{get_column_letter(col)}{row}"] = f"{i}."
# 写入题目和分隔线
sheet[f"{get_column_letter(col + 1)}{row}"] = problem
if answers==False:
sheet[f"{get_column_letter(col + 2)}{row}"] = "( )"
else:
sheet[f"{get_column_letter(col + 2)}{row}"] = f"( {answer} )"
row += 1
# 每50行换一列
if row > 50:
row = 1
col += 3 # 每题占用3列
# 创建Excel文件并添加三个sheet表
def create_excel_file(filename, addition_problems, subtraction_problems, mixed_problems,answers):
wb = Workbook()
# 加法运算
ws1 = wb.active
ws1.title = "加法运算"
write_problems_to_sheet(ws1, addition_problems,answers)
# 减法运算
ws2 = wb.create_sheet(title="减法运算")
write_problems_to_sheet(ws2, subtraction_problems,answers)
# 加减混合运算
ws3 = wb.create_sheet(title="加减混合运算")
write_problems_to_sheet(ws3, mixed_problems,answers)
# 保存文件
wb.save(filename)
# 主函数
def main():
def entry():
try:
s = int(entry_max_value.get())
x = int(entry_num_problems.get())
z = int(entry_num_operands.get())
addition_problems = generate_addition_problems(x, s, z)
subtraction_problems = generate_subtraction_problems(x, s, z)
mixed_problems = generate_mixed_problems(x, s, z)
current_dir=os.path.dirname(sys.executable)
print(current_dir)
filename_problems=os.path.join(current_dir,'题目.xlsx')
filename_answers=os.path.join(current_dir,'答案.xlsx')
create_excel_file(filename_problems, addition_problems, subtraction_problems, mixed_problems,answers=False)
create_excel_file(filename_answers, addition_problems, subtraction_problems, mixed_problems,answers=True)
output_text.insert(tk.END,f"题目文件与答案文件已生成,保存位置\n{current_dir}")
except Exception as e:
output_text.insert(tk.END,f'发生错误{str(e)}\n')
print(e)
finally:
output_text.see(tk.END)
# 创建主窗口
root = tk.Tk()
root.title('运算题目生成器')
dir=os.path.dirname(os.path.abspath(__file__))
ico_path=os.path.join(dir,'jisuan2.ico')
root.iconbitmap(ico_path)
root.geometry("550x450")
# 设置主窗口背景颜色为白色
root.config(bg='white')
font = ("Arial", 14)
# 输入框
tk.Label(root, text='输入题目最大值:',font=font,bg='white').grid(row=0, column=0,padx=10,pady=20,sticky='e')
entry_max_value = tk.Entry(root,font=font,width=10,bd=2,bg='lightyellow',fg='blue',relief='sunken')
entry_max_value.grid(row=0, column=1,padx=10,pady=20)
tk.Label(root, text='输入生成的题数:',font=font,bg='white').grid(row=1, column=0,padx=10,pady=20,sticky='e')
entry_num_problems = tk.Entry(root,font=font,width=10,bd=2,bg='lightyellow',fg='blue',relief='sunken')
entry_num_problems.grid(row=1, column=1,padx=10,pady=20)
tk.Label(root, text='可选择几则运算:',font=font,bg='white').grid(row=2, column=0,padx=10,pady=20,sticky='e')
entry_num_operands=ttk.Combobox(root,values=[2,3],font=font,width=8,style='TCombobox')
entry_num_operands.grid(row=2, column=1,padx=10,pady=20)
entry_num_operands.current(0)
# 按钮
button = tk.Button(root, text= '''生成题目''',
command=entry,font=font,width=10,bd=5,fg='black',padx=10,pady=10,)
# button.place(x=350,y=60)
button.grid(row=3,columnspan=2,padx=0,pady=0)
#输出显示
output_text=tk.Text(root,font=font,height=5,width=35,bd=2,relief='sunken',bg='lightyellow')
output_text.grid(row=4,columnspan=2,padx=10,pady=20)
# 让所有列具有相同的扩展权重,从而在窗口大小调整时居中对齐
root.grid_columnconfigure(0, weight=1)
root.grid_columnconfigure(1, weight=1)
# 让所有行具有相同的扩展权重,从而在窗口大小调整时居中对齐
# root.grid_rowconfigure(0, weight=1)
# root.grid_rowconfigure(1, weight=1)
# root.grid_rowconfigure(2, weight=1)
# root.grid_rowconfigure(3, weight=1)
root.mainloop()
if __name__ == "__main__":
main()
马上暑假了,得给娃娃找点事情做。做了一个加减练习的题库。