Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何调整图像大小以适应标签大小?(python)_Python_Image_Tkinter - Fatal编程技术网

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

如何调整图像大小以适应标签大小?(python),python,image,tkinter,Python,Image,Tkinter,我的目标是创建一个随机国家生成器,将显示所选国家的国旗。然而,如果图像文件大于标签的预定大小,则仅显示图像的一部分。是否有方法调整图像大小以适应标签?(我看到的所有其他类似问题都得到了回答,提到了PIL或图像模块。我对它们都进行了测试,它们都出现了这个错误: 回溯(最近一次呼叫最后一次): 文件“C:\python\country.py”,第6行,在 进口PIL 导入错误:没有名为“PIL”的模块。 这是我的代码,如果有帮助: import tkinter from tkinter import

我的目标是创建一个随机国家生成器,将显示所选国家的国旗。然而,如果图像文件大于标签的预定大小,则仅显示图像的一部分。是否有方法调整图像大小以适应标签?(我看到的所有其他类似问题都得到了回答,提到了PIL或图像模块。我对它们都进行了测试,它们都出现了这个错误:

回溯(最近一次呼叫最后一次): 文件“C:\python\country.py”,第6行,在 进口PIL 导入错误:没有名为“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类有一个调整图像大小的
方法

我把你的代码删减了一些

您可以调整图像的大小,然后只配置标签,标签将扩展为图像的大小。如果您为标签指定了特定的高度和宽度,例如
height=1
width=1
,然后将图像的大小调整为500x500,然后配置小部件。由于您设置了显式地删除属性

在下面的代码中,修改dict时,在迭代dict时修改它是不正确的。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()

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

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