最近我一直试图通过一种实践方法来学习Python(我觉得它更有趣,虽然效率不高)。
在这个特定的代码中,我试图制作一个程序来批量生成证书。 试图解决这个问题一直在破解我的想法,代码不断覆盖旧图片并再次保存它们,而不是从基础变量中获取干净的图片。
我尝试将base = Image.open("generico/Certificado.png")
移到criacao(nome)
函数中,但后来我被告知“base”尚未定义。
draw = ImageDraw.Draw(base)
NameError: name 'base' is not defined
非常感谢帮助!
import zlib, datetime
from PIL import Image, ImageFont, ImageDraw
curso = input("Course: ")
inicio = input("Date of start (DD/MM): ")
fim = input("Date ended (formato DD/MM/AAAA): ")
horas = input ("Total hours spent: ")
professor = input("Professor: ")
quantos = int(input("Number of students: "))
contador = int(0)
base = Image.open("generico/Certificado.png")
font = ImageFont.truetype("arial.ttf", 50)
draw = ImageDraw.Draw(base)
def criacao(nome):
nome_arquivo = str(datetime.date.today()) + " " + nome[0].upper() + nome[1:len(nome)].lower() + " " + curso
draw.text((750,1065), nome.upper(), font=font, fill=(0,0,0,0))
draw.text((750,1414), curso.upper(), font=font, fill=(0,0,0,0))
draw.text((1220,1625), inicio, font=font, fill=(0,0,0,0))
draw.text((1500,1625), fim, font=font, fill=(0,0,0,0))
draw.text((1540,1750), horas + ".", font=font, fill=(0,0,0,0))
draw.text((1740,2130), str(datetime.date.today()), font=font, fill=(0,0,0,0))
draw.text((1550,2680), professor, font=font, fill=(0,0,0,0))
base.save("Criado/" + nome_arquivo + ".png")
while contador < quantos:
criacao(input("Student's name: "))
contador += 1
答案 0 :(得分:1)
我怀疑除了定义draw = ImageDraw.Draw(base)
的行之外,您还需要移动base
行。您当前的错误与该行无法看到base
有关,而且它似乎是您操纵图像数据的手段,所以它是有道理的。
试试这个:
font = ImageFont.truetype("arial.ttf", 50)
def criacao(nome):
base = Image.open("generico/Certificado.png") # move this line from above
draw = ImageDraw.Draw(base) # this one too
nome_arquivo = str(datetime.date.today()) + " " + nome[0].upper() + nome[1:len(nome)].lower() + " " + curso
draw.text((750,1065), nome.upper(), font=font, fill=(0,0,0,0))
draw.text((750,1414), curso.upper(), font=font, fill=(0,0,0,0))
draw.text((1220,1625), inicio, font=font, fill=(0,0,0,0))
draw.text((1500,1625), fim, font=font, fill=(0,0,0,0))
draw.text((1540,1750), horas + ".", font=font, fill=(0,0,0,0))
draw.text((1740,2130), str(datetime.date.today()), font=font, fill=(0,0,0,0))
draw.text((1550,2680), professor, font=font, fill=(0,0,0,0))
base.save("Criado/" + nome_arquivo + ".png")