我的目标是创建一个随机的国家生成器,被选中的国家的国旗将出现。然而,如果图像文件大于标签的预定大小,则仅显示图像的一部分。有没有办法调整图像大小以适应标签?(我看到的所有其他类似的问题都得到了回答,提到了PIL或图像模块。我测试了他们两个,他们都发现了这个错误:
回溯(最近一次呼叫): 文件“C:\python\国家.py“,第6行,英寸 进口PIL 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()
除了只显示图像的一部分之外,代码工作得非常好。有没有办法在代码中调整图像的大小?(我使用的是python3.5.1)
如果没有安装PIL,首先需要安装PIL
安装后,您现在可以从PIL导入:
^{pr2}$Tk的PhotoImage只能显示.gif,而PIL的ImageTk允许我们用tkinter显示各种图像格式,PIL的image类有一个
resize
方法来调整图像的大小。在我删减了你的代码。在
您可以调整图像大小,然后只需配置标签,标签将扩展为图像的大小。如果给标签指定了特定的高度和宽度,比如
height=1
和width=1
,然后将图像的大小调整为500x500,然后配置小部件。它仍然会显示1x1标签,因为您已经显式地设置了这些属性。在在下面的代码中,修改dict时,在遍历dict时修改dict是不正确的。dict.项目()返回dict的副本
有很多方法可以做到这一点,我只是觉得口述在这里很方便。在
Link to an image that's over the height / width limit-小猫.gif在
相关问题 更多 >
编程相关推荐