2016-04-30 91 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() 
相關問題