在PIL(Python)中使用变量可能吗?

0 投票
1 回答
1639 浏览
提问于 2025-04-16 12:20

我正在用Python 3.1编程,并且使用了为这个版本更新的PIL库。现在我的程序需要从一个网页获取信息,我想把这些信息画到我已经有的图片上,所以我用一个变量来存储这些信息,这也是我需要帮助的地方。

下面是我程序的一部分(因为代码超过100行,所以我只展示了和问题相关的部分)

import webbrowser
import random
import urllib.request, urllib.parse, urllib.error
import re
import PIL
from PIL import Image, ImageFont, ImageDraw

arial16 = ImageFont.truetype ("arial.ttf", 16)

Z = (input ("What is the character name? "))

#The link which i get from my input info..
url = "http://"+X+".battle.net/wow/en/character/"+Y+"/"+Z+"/simple"

# Read the webpage
html = urllib.request.urlopen(url).read()

# Encoding
encoding = "utf-8"
html =html.decode (encoding)

# Find right class & choose background from it
cl = re.findall ('class="class">(.*)</a><span class="comma">,</span>', html) 

if "Death Knight" : im = Image.open ("DeathKnightBackground.png")
elif "Druid" : im = Image.open ("DruidBackground.png")
elif "Hunter" : im = Image.open ("HunterBackground.png")
elif "Mage" : im = Image.open ("MageBackground.png")
elif "Paladin" : im = Image.open ("PaladinBackground.png")
elif "Priest" : im = Image.open ("PriestBackground.png")
elif "Rogue" : im = Image.open ("RogueBackground.png")
elif "Shaman" : im = Image.open ("ShamanBackground.png")
elif "Warlock" : im = Image.open ("WarlockBackground.png")
elif "Warrior" : im = Image.open ("WarriorBackground.png")

# Find the Title
title = re.findall('<div class="title">(.*)</div>', html)

# If i want to print this i just do
print (("Your Charactername with it's title:")+Z, title)
print (("You are:"),cl)

# Then i want to use a variable to save my picture
S = input("Please enter a name to save your forumsignature: ")

# When i want to draw the text to the picture i tried to use (+Z, title) as in the print
# function - but since this didn't work i will just go with ((+Z, title)) which don't give me
# syntax error

draw = ImageDraw.Draw ( im )
draw.text ( (20,20), ((+ Z, title)), font=arial16, fill="white")

# As i said before, i'm using variable S for saving and tried this way.. but in all the ways i
# have tried, i always keep getting syntax errors 

im.save ((+S))

im.show ((+S))

所以,有人知道PIL是否能以这种方式处理变量吗?或者你知道其他方法可以在Python 3.1中把变量里的文本画到图片上吗?

非常期待大家的回复,我会继续尝试各种不同的方法来让这个工作,如果我找到可行的办法会在这里分享...

// Zabs

1 个回答

0

这是一个语法错误。加更多的括号只会创建一个新的数据结构。你可以试试:

text = Z + " " + title
draw.text ( (20,20), text, font=arial16, fill="white")

还有你的保存命令:

im.save(S)
im.show(S)

撰写回答