OSError: cannot open resource

OSError: cannot open resource

import tkinter as tk  
from tkinter import ttk,font  
from PIL import Image,ImageDraw,ImageFont

root = tk.Tk()

def func_image():  
    image = Image.open(r'E:\side_300.png')  
    font_type_1 = ImageFont.truetype(str(combo.get()),18)
    draw = ImageDraw.Draw(image)  
    draw.text((50,50),text='Hello',fill='red',font=font_type_1)  
    image.show()  

fonts=list(font.families())  
fonts.sort()  
combo = ttk.Combobox(root,value=fonts)    
combo.pack()  

btn = ttk.Button(root,text='Click Me',command=func_image)  
btn.pack()

root.mainloop()

输出

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Mevada\AppData\Local\Programs\Python\Python37\lib\tkinter__init__.py", line 1702, in __call__return self.func(*args)
File "test.py", line 9, in func_image
font_type_1 = ImageFont.truetype(str(combo.get()),18)
File "C:\Users\Mevada\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageFont.py", line 280, in truetype return FreeTypeFont(font, size, index, encoding, layout_engine)
File "C:\Users\Mevada\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageFont.py", line 145, in __init__layout_engine=layout_engine)
OSError: cannot open resource

谢谢...

ImageFont.truetype 要求您给它一个文件名。您没有给它一个文件名,而是给它一个字体系列的名称。 Tkinter 的 font.families() 没有 return 文件名。

PIL 好像font 找不到

在您的计算机中找到您的字体文件。在 windows 中,它总是在 C:\WINDOWS\Fonts 目录中。 select 一个并像这样修改你的第 9 行:

font_type_1 = ImageFont.truetype("bahnschrift.ttf",18)

bahnschrift.ttf 只是我电脑上的一个示例,我不确定它是否存在于你的电脑上。

它不起作用,因为您必须在此处插入字体文件名作为第一个参数:ImageFont.truetype(str(combo.get()),18)

如果您尝试 arial,您就会成功(当然,如果您的计算机上安装了 Arial)。哦,那个函数是区分大小写的,所以你必须用小写来写,因为文件名实际上是 arial.ttf(顺便说一下,你可以删除扩展名).

因此,您的组合框不起作用,因为当您选择名为 Courier New 的字体时,PIL 将找不到它,因为它的文件名是 cour.ttf。不幸的是,您不能在 ImageFont 上使用来自 tkinter 的字体列表,在这种情况下我没有适合您的解决方法。

正如我所说,这可能有效,但你必须放弃你的组合框:ImageFont.truetype('arial',18)

在我开始之前,还有一个重要的注意事项:如果您正在处理 OS 而不是 Windows,则必须键入字体文件的完整路径。

import tkinter as tk  
from tkinter import ttk
from PIL import Image,ImageDraw,ImageFont
import matplotlib.font_manager as fm

root = tk.Tk()

def func_image():  
    image = Image.open(r'E:\side_300.png')  
    font_type_1 = ImageFont.truetype(fm.findfont(fm.FontProperties(family=combo.get())),18)
    draw = ImageDraw.Draw(image)  
    draw.text((50,50),text='Hello',fill='red',font=font_type_1)  
    image.show()  

fonts = list(set([f.name for f in fm.fontManager.ttflist]))
fonts.sort()

combo = ttk.Combobox(root,value=fonts)    
combo.pack()  

btn = ttk.Button(root,text='Click Me',command=func_image)  
btn.pack()

root.mainloop()