软件课题:Python实现打印100内数学试题软件及开发过程
一、需求管理:
1.实现语言:Python
2.打印纸张:A4
3.铺满整张纸
4.打包成exe
先看效果:
1.
2.电脑打印预览
3.打印到A4纸效果(晚上拍的,和手机像素有关,实际效果是清晰的)
二、实现过程
第一版:
效果:
代码:
from reportlab.lib.pagesizes import letter, A4
from reportlab.pdfgen import canvas
import random
# 设置A4纸尺寸
width, height = A4
# 定义页面边距(单位:毫米)
margin = 20
# 题目数量
num_questions = 50 # 示例中设置为50道题,可根据需要调整
def generate_question():
"""生成一道100以内的随机加减法题目"""
op = random.choice(['+', '-'])
if op == '+':
a = random.randint(0, 100)
b = random.randint(0, 100 - a) # 确保结果不超过100
else:
a = random.randint(0, 100)
b = random.randint(0, a) # 确保减法结果非负
return f"{a} {op} {b} = "
def draw_questions(c):
"""在canvas上绘制题目"""
question_width = (width - 2 * margin) / 2 # 每列宽度
question_height = 20 # 每题高度,可调整
y_position = height - margin - question_height * num_questions # 起始y坐标
for i in range(num_questions):
c.setFont("Helvetica", 12) # 设置字体和大小
question = generate_question()
c.drawString(margin, y_position, question)
y_position += question_height
def main():
c = canvas.Canvas("math_test.pdf", pagesize=A4)
draw_questions(c)
c.save()
print("PDF文件已生成。")
if __name__ == "__main__":
main()
第二版(最终版):
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas
import random
# 设置A4纸尺寸
width, height = A4
# 定义页面边距(单位:毫米)
margin = 20
# 题目数量(总题目数)
num_questions = 200 # 示例中设置为200道题,可根据需要调整
# 每列题目数估算,这里简化处理,实际情况可能需要更精确的计算以适应不同长度的题目
questions_per_column = num_questions // 4
if num_questions % 4 != 0:
questions_per_column += 1
# 计算每列宽度
column_width = (width - 3 * margin) / 4 # 减去3个间隔的边距
def generate_question():
"""生成一道100以内的随机加减法题目"""
op = random.choice(['+', '-'])
if op == '+':
a = random.randint(0, 100)
b = random.randint(0, 100 - a)
else:
a = random.randint(0, 100)
b = random.randint(0, a)
return f"{a} {op} {b} = "
def draw_questions(c):
"""在canvas上绘制题目到四列"""
question_height = 20 # 每题高度,可调整
column_positions = [margin + i * (column_width + margin) for i in range(4)] # 四列的位置
y_position = height - margin - question_height * questions_per_column # 起始y坐标
for col_pos in column_positions:
y_position = height - margin - question_height * questions_per_column # 重置y坐标
for q in range(questions_per_column):
question = generate_question()
c.setFont("Helvetica", 12) # 设置字体和大小
c.drawString(col_pos, y_position, question)
y_position += question_height # 移动到下一行
def main():
c = canvas.Canvas("math_test_4_columns.pdf", pagesize=A4)
draw_questions(c)
c.save()
print("PDF文件已生成,包含四列题目。")
if __name__ == "__main__":
main()
Python 版本:3.8
需要安装的Python插件及安装顺序:
chardet-5.2.0-py3-none-any.whl
reportlab-4.2.0-py3-none-any.whl
setuptools-69.5.1-py3-none-any.whl
altgraph-0.17.4-py2.py3-none-any.whl
pyinstaller_hooks_contrib-2024.6-py2.py3-none-any.whl
pefile-2023.2.7-py3-none-any.whl
pywin32_ctypes-0.2.2-py3-none-any.whl
pyinstaller-6.6.0-py3-none-win_amd64.whl
总结:
建议大家可以运行一下上面开发全部过程的代码,然后对比我上面的代码。找到出bug的地方,对比已经修复的地方。
揭开题目我敲的字母:
灰色就是编辑器提示的代码,可以按tab键直接生成,使用vscode安装fittencode插件。
(完)