python - AttributeError:“WindowsPath”对象没有 Discord.py 的“编码”属性
问题描述
我正在用 python 编写一个不和谐的机器人。这个机器人需要枕头和路径库。我有一个在图像上绘制的函数,但我总是遇到一个我无法解决的错误。根据我的调试器,该错误发生在这一行:
font = ImageFont.truetype(font_path, 15)
我总是收到这个错误:
AttributeError: 'WindowsPath' object has no attribute 'encode' with Discord.py
这是完整的代码:
class MaccaudCog(commands.cogs, name="Command !maccaud"):
def __init__(self, bot):
self.bot = bot
async def maccaud(self, ctx, *, sentence=None):
maccaud_sentence=['some sentences,some sentences']
def draw(sentence):
# Decode sentence sended if non latin-1 characters are present
sentence = sentence.encode('latin-1', 'replace').decode('latin-1')
# Set relative paths
mod_path = Path(__file__).parent
relative_path_1 = '../assets/maccaud/base_maccaud.jpg'
maccaud_base = (mod_path / relative_path_1).resolve()
relative_path_2 = '../assets/fonts/impact.ttf'
font_path = (mod_path / relative_path_2).resolve()
relative_path_3 = '../assets/maccaud/edited_maccaud.jpg'
maccaud_edited = (mod_path / relative_path_3).resolve()
# Draw on img
img = Image.open(maccaud_base)
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(font_path, 15)
W,H = img.size
w, h = draw.multiline_textsize(sentence)
width = (W-w)/2
height = (H-h)/1.25
draw.multiline_text((width,height), sentence, (255,255,255), font=font, align="center")
# Save and return file
img.save(maccaud_edited)
file = discord.File(maccaud_edited, filename="edited_maccaud.jpg")
return file
file = draw(sentence)
embed = discord.Embed(title="", description="", colour=discord.Color.green())
embed.set_image(url="attachment://edited_maccaud.jpg")
await self.client.send(file=file, embed=embed)
def setup(bot):
bot.add_cog(MaccaudCog(bot))
这是回溯:
Traceback (most recent call last):
File "D:\pythonProjects\cog_bot\new\cogs\maccaud.py", line 96, in draw
font = ImageFont.truetype(font_path, 15)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\PIL\ImageFont.py", line 655, in truetype
return freetype(font)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\PIL\ImageFont.py", line 652, in freetype
return FreeTypeFont(font, size, index, encoding, layout_engine)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\PIL\ImageFont.py", line 184, in __init__
font_bytes_path = font if isinstance(font, bytes) else font.encode()
AttributeError: 'WindowsPath' object has no attribute 'encode'
你有解决方案吗?
解决方案
尝试这个:
font = ImageFont.truetype(str(font_path), 15)
这将确保您font_path
是一个字符串
推荐阅读
- r - 如何在R中初始化随机矩阵,列中没有重复但行中允许重复
- python - .groupby 不在visualstudiocode本地工作,但在jupyterlab工作
- java - Hibernate 如何创建限制参数
- ios - 如何使用 Firebase 找到 iOS 代码崩溃的地方?(当您无法重现错误时)
- java - 我在 Intellij 中为 maven 创建了一个自定义原型,但想删除它
- stack - 如何确定 FreeBSD 正在运行的进程的堆大小、堆栈大小
- java - JDBC。替换列的所有行值
- reactjs - React-Native 获取 API 问题 #react-native
- java - Liquibase Windows MySQL - 找不到数据库驱动程序:com.mysql.cj.jdbc.Driver
- python - 为键中的每个斜线解包字典的节点