Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 tkinter set image size

I have looked everywhere to find a way to set the size of an image. The image is set to a url. I have found other questions on the site but none of them have worked.

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

That is the code that creates the image, how would I set the size of the image

like image 642
SeanOMik Avatar asked Jul 07 '17 18:07

SeanOMik


3 Answers

As mentioned by several others, you should use PIL to resize your image before attaching it to a tkinter label:

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()
like image 172
Nelson Avatar answered Nov 18 '22 16:11

Nelson


New syntax of resize:

resize((pixels_x, pixels_y))

So the code can be comething like this:

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

root = Tk()

file = '/home/master/Work/Tensorflow/Project/Data/images/p001.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()

based on Nelson answer

like image 24
ChaosPredictor Avatar answered Nov 18 '22 15:11

ChaosPredictor


You can add this one line if a simple zoom is acceptable :

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

Otherwise you should use the PIL lib which provide more accurate tools.

like image 5
PRMoureu Avatar answered Nov 18 '22 15:11

PRMoureu