Python3 tkinter设置图像大小

时间:2017-07-07 18:07:49

标签: python python-3.x tkinter python-imaging-library

我到处寻找一种设置图像大小的方法。图像设置为网址。我在网站上发现了其他问题,但没有一个有效。

import urllib.request, base64

u = urllib.request.urlopen(currentWeatherIconURL)
raw_data = u.read()
u.close()

b64_data = base64.encodestring(raw_data)
image = PhotoImage(data=b64_data)

label = Label(image=image, bg="White")
label.pack()

这是创建图像的代码,我如何设置图像的大小

4 个答案:

答案 0 :(得分:1)

正如其他几位人士所说,在将图像附加到tkinter标签之前,您应该使用PIL调整图像大小:

from tkinter import Tk, Label
from PIL import Image, ImageTk

root = Tk()

img = ImageTk.PhotoImage(Image.open('img-path.png').resize(pixels_x, pixels_y)) # the one-liner I used in my app
label = Label(root, image=img, ...)
label.image = img # this feels redundant but the image didn't show up without it in my app
label.pack()

root.mainloop()

答案 1 :(得分:0)

如果可以接受简单的缩放,您可以添加这一行:

image = PhotoImage(data=b64_data)
image = image.subsample(4, 4) # divide by 4
# image = image.zoom(2, 2)    # zoom x 2
label = Label(image=image, bg="White")

否则你应该使用提供更准确工具的PIL lib。

答案 2 :(得分:0)

调整大小的新语法:

  

resize((pixels_x,pixels_y))

所以代码可以像这样:

from tkinter import Tk, Label
from PIL import Image, ImageTk

root = Tk()

file = '/home/master/Work/Tensorflow/Project06 - LSC_CVPPP/Data/00 - Backgrounds_org/A1/plant001.png'

image = Image.open(file)

zoom = 1.8

#multiple image size by zoom
pixels_x, pixels_y = tuple([int(zoom * x)  for x in image.size])

img = ImageTk.PhotoImage(image.resize((pixels_x, pixels_y))) 
label = Label(root, image=img)
label.image = img
label.pack()

root.mainloop()

基于尼尔森的答案

答案 3 :(得分:0)

try:
    # Relative Path
    img = Image.open(File)
    width, height = img.size
    print(width)
    print(height)

    img = img.resize((round(680/height*width) , round(680)))

    # Saved in the same relative location
    # img.save("resized_picture.jpg")

    img = ImageTk.PhotoImage(img)
    print(img.height()) 
    print(img.width())
except IOError:
    pass