2016-04-30 88 views
0

我的目标是创建一个随机的国家发电机,并挑选国家的国旗会出现。但是,如果图像文件大于标签的预定大小,则只显示部分图像。有没有调整图像大小以适应标签的方法? (这样,其他所有问题,我所看到的已经回答了,提PIL或图片模块我测试了他们两个,他们都想出了这个错误:如何调整图像大小以适应标签大小? (蟒蛇)

回溯(最近通话最后一个): 文件“C:\蟒蛇\ country.py”,第6行,在 进口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)

回答

1

如果您尚未安装PIL,首先你需要安装

pip install pillow 

一旦安装,你现在可以从PIL导入:

from PIL import Image, ImageTk 

Tk的的光象只能显示.gif注意的,而PIL的ImageTk将让我们在Tkinter的显示各种图像格式和PIL的图像类有resize方法,我们可以用它来调整图像大小。

我修剪了一些代码。

您可以调整图像大小,然后只配置标签,标签将展开为图像大小。如果您为标签指定了特定的高度和宽度,则可以说height=1width=1,并将图像调整为500x500,然后配置该小部件。它会显示一个1x1标签,因为你已经明确地设置了这些属性。

在下面的代码中,修改字典,修改字典而不是修改字典,而迭代它。 dict.items()返回字典的副本。

有很多种方法可以做到这一点,我只是在这里使用了一个字典。

Link to an image that's over the height/width limit - 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()