Reputation: 312
I found this code:
from PIL import Image, ImageTk
import tkinter as tk
root = tk.Tk()
img = Image.open(r"Sample.jpg")
canvas = tk.Canvas(root, width=500, height=500)
canvas.pack()
tk_img = ImageTk.PhotoImage(img)
canvas.create_image(250, 250, image=tk_img)
root.mainloop()
It displays any picture in 500x500px resolution. I tried to change it and display it in its original size:
from PIL import Image, ImageTk
import tkinter as tk
root = tk.Tk()
img = Image.open(r"D:/1.jpg")
canvas = tk.Canvas(root, width=img.width, height=img.height)
canvas.pack()
tk_img = ImageTk.PhotoImage(img)
canvas.create_image(img.width/2, img.height/2, image=tk_img)
root.mainloop()
But something went wrong and the picture with a size of 604x604px shows in a window with a size of 602x602px, but the window size is correct. Take a look (full image). What am I doing wrong?
P.S. Sorry for bad English.
Upvotes: 1
Views: 1750
Reputation: 404
Well, no, your first example still cuts off by a few pixels. All top level windows will have padding around their absolute borders to prevent other elements from 'bleeding' into the borders and looking unprofessional.
You are still being given a canvas of 604 pixels by 604 pixels, but the root window itself is asserting its padding. I could not find any way of removing this top level padding, and it may very well appear differently in other operating systems. A work-around could be to request a canvas size that is slightly larger than the image you would like to display.
Another issue, if you're aiming for precision, would be the line...
canvas.create_image(img.width/2, img.height/2, image=tk_img)
Which could create off-by-one errors if your width or height is an odd number. You can anchor images to the north-west corner and place them at the co-ordinates (0, 0)
like such:
canvas.create_image(0, 0, anchor=tk.NW, image=tk_img)
Upvotes: 1