我的目标是创建一个随机的国家/地区生成器,然后将显示所选择的国家/地区的标志。但是,如果图像文件大于标签的预定大小,则仅显示图像的一部分。有没有办法调整图像大小以适合标签?(我看到的所有其他类似问题均已回答,提到了PIL或Image模块。我对它们都进行了测试,并且都提出了此错误:
追溯(最近一次调用):文件“ C:\ python \ country.py”,导入PIL中的第6行ImportError:没有名为“ PIL”的模块
这是我的代码,如果有帮助的话:
import tkinter
from tkinter import *
import random
flags = ['England','Wales','Scotland','Northern Ireland','Republic of Ireland']
def newcountry():
country = random.choice(flags)
flagLabel.config(text=country)
if country == "England":
flagpicture.config(image=England)
elif country == "Wales":
flagpicture.config(image=Wales)
elif country == "Scotland":
flagpicture.config(image=Scotland)
elif country == "Northern Ireland":
flagpicture.config(image=NorthernIreland)
else:
flagpicture.config(image=Ireland)
root = tkinter.Tk()
root.title("Country Generator")
England = tkinter.PhotoImage(file="england.gif")
Wales = tkinter.PhotoImage(file="wales.gif")
Scotland = tkinter.PhotoImage(file="scotland.gif")
NorthernIreland = tkinter.PhotoImage(file="northern ireland.gif")
Ireland = tkinter.PhotoImage(file="republic of ireland.gif")
blackscreen = tkinter.PhotoImage(file="black screen.gif")
flagLabel = tkinter.Label(root, text="",font=('Helvetica',40))
flagLabel.pack()
flagpicture = tkinter.Label(root,image=blackscreen,height=150,width=150)
flagpicture.pack()
newflagButton = tkinter.Button(text="Next Country",command=newcountry)
newflagButton.pack()
除了仅显示图像的一部分之外,该代码还可以正常工作。有没有办法在代码本身中调整图像的大小?(我正在使用Python 3.5.1)
如果您尚未安装PIL,则首先需要安装
pip install pillow
安装后,您现在可以从PIL导入:
from PIL import Image, ImageTk
Tk的PhotoImage只能显示.gif,而PIL的ImageTk可以让我们在tkinter中显示各种图像格式,而PIL的Image类提供了resize
一种可用于调整图像大小的方法。
我将您的代码精简了一些。
您可以调整图像的大小,然后仅配置标签,标签将扩展为图像的大小。如果为标签指定了特定的高度和宽度,请说出height=1
和width=1
,然后将图像的大小调整为500x500,然后配置小部件。由于您已明确设置这些属性,因此它仍将显示1x1标签。
在下面的代码中,修改字典,在遍历字典时修改字典是不可行的。dict.items()返回dict的副本。
有多种方法可以做到这一点,尽管我在这里很方便。
链接到超出高度/宽度限制的图像-kitty.gif
from tkinter import *
import random
from PIL import Image, ImageTk
WIDTH, HEIGHT = 150, 150
flags = {
'England': 'england.gif',
'Wales': 'wales.gif',
'Kitty': 'kitty.gif'
}
def batch_resize():
for k, v in flags.items():
v = Image.open(v).resize((WIDTH, HEIGHT), Image.ANTIALIAS)
flags[k] = ImageTk.PhotoImage(v)
def newcountry():
country = random.choice(list(flags.keys()))
image = flags[country]
flagLabel['text'] = country
flagpicture.config(image=image)
if __name__ == '__main__':
root = Tk()
root.configure(bg='black')
batch_resize()
flagLabel = Label(root, text="", bg='black', fg='cyan', font=('Helvetica',40))
flagLabel.pack()
flagpicture = Label(root)
flagpicture.pack()
newflagButton = Button(root, text="Next Country", command=newcountry)
newflagButton.pack()
root.mainloop()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句