如何调整图像大小以适应标签大小? (蟒蛇)

时间:2016-04-30 19:40:24

标签: python image tkinter

我的目标是创建一个随机的国家/地区生成器,并将显示所选国家/地区的标志。但是,如果图像文件大于标签的预定大小,则仅显示部分图像。有没有办法调整图像大小以适应标签? (我所看到的所有其他问题都得到了解答,提到了PIL或Image模块。我对它们进行了测试,他们都提出了这个错误:

追踪(最近一次通话):   文件" C:\ python \ country.py",第6行,in     进口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()

除了仅显示图像的一部分外,代码完美无缺。有没有办法在代码本身内调整图像大小?(我使用的是Python 3.5.1)

2 个答案:

答案 0 :(得分:1)

如果您没有安装PIL,首先需要安装

pip install pillow

安装完成后,您现在可以从PIL导入:

from PIL import Image, ImageTk

Tk的PhotoImage只能显示.gif,而PIL的ImageTk会让我们在tkinter中显示各种图像格式,而PIL的Image类有一个resize方法可以用来调整图像大小。

我把你的代码修剪了一些。

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

在下面的代码中,修改了dict,在迭代时修改dict是不可行的。 dict.items()返回dict的副本。

有各种各样的方法可以做到这一点,我只是说这里的字典很方便。

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()

答案 1 :(得分:1)

我们不是随机选择一个国家来显示其国旗,而是循环浏览按键排序的国旗字典。与将不可避免地重复标记的随机选择不同,此方案以字母顺序遍历各个国家。同时,我们根据根窗口的宽度和高度乘以比例因子,将所有图像调整为固定的像素大小。下面是代码:

import  tkinter as tk
from PIL import Image, ImageTk

class   Flags:

    def __init__(self, flags):
        self.flags = flags
        self.keyList = sorted(self.flags.keys()) # sorted(flags)
        self.length = len(self.keyList)
        self.index = 0

    def resize(self, xy, scale):
        xy = [int(x * y) for (x, y) in zip(xy, scale)]
        for k, v in self.flags.items():
            v = Image.open(r'C:/Users/user/Downloads/' + v)
            v = v.resize((xy[0], xy[1]), Image.ANTIALIAS)
            self.flags[k] = ImageTk.PhotoImage(v)

    def newCountry(self, lbl_flag, lbl_pic):
        country = self.keyList[self.index]
        lbl_flag["text"] = country
        img = self.flags[country]
        lbl_pic.config(image = img)
        self.index = (self.index + 1) % self.length # loop around the flags dictionary

def rootSize(root):
    # Find the size of the root window
    root.update_idletasks()
    width = int(root.winfo_width() * 1.5)      #   200 * m
    height = int(root.winfo_height() * 1.0)    #   200 * m
    return width, height

def centerWsize(root, wh):
    root.title("Grids layout manager")
    width, height = wh
    # Find the (x,y) to position it in the center of the screen
    x = int((root.winfo_screenwidth() / 2) - width/2)
    y = int((root.winfo_screenheight() / 2) - height/2)
    root.geometry("{}x{}+{}+{}".format(width, height, x, y))

if __name__ == "__main__":

    flags = {
        "Republic of China": "taiwan_flag.png",
        "United States of America": "america_flag.gif",
        "America": "america_flag.png",
    }

    root = tk.Tk()
    wh = rootSize(root)
    centerWsize(root, wh)
    frame = tk.Frame(root, borderwidth=5, relief=tk.GROOVE)
    frame.grid(column=0, row=0, rowspan=3)
    flag = Flags(flags)
    zoom = (0.7, 0.6)   # Resizing all the flags to a fixed size of wh * zoom
    flag.resize(wh, zoom)
    lbl_flag = tk.Label(frame, text = "Country name here", bg = 'white', fg = 'magenta', font = ('Helvetica', 12), width = 30)
    lbl_flag.grid(column = 0, row = 0)
    pic_flag = tk.Label(frame, text = "Country flag will display here")
    pic_flag.grid(column = 0, row = 1)
    btn_flag = tk.Button(frame, text = "Click for next Country Flag",
                         bg = "white", fg = "green", command = lambda : flag.newCountry(lbl_flag, pic_flag))
    btn_flag.grid(column = 0, row = 2)

    root.mainloop()