Home > OS >  Correct display of image with canvas tkinter window in Python
Correct display of image with canvas tkinter window in Python

Time:12-13

A part of the input image is cut off when displaying via canvas.create_image in a tkinter window

I have tried to change the "side" parameters and the width / height values in the canvas.create_image object.

here is my code and input image:

import tkinter as tk
from tkinter import *
from tkinter.filedialog import askopenfilename
import os
from PIL import ImageTk, Image


def show_values():
    print(slider1.get())


window = tk.Tk()

filename = askopenfilename()  # show an "Open" dialog box and return the path to the selected file
print(filename)

slider1 = Scale(window, from_=0, to=42, orient='vertical')
slider1.pack(side=LEFT)

canvas = Canvas(window)
canvas.pack()
img = ImageTk.PhotoImage(Image.open(filename))
imageWidth = img.width()
imageHeight = img.height()

canvas.create_image(imageWidth   1, imageHeight   1, image=img)
canvas.pack(side=RIGHT)

Button(window, text='Process Image', command=show_values).pack(side=BOTTOM)

window.mainloop()

input image

CodePudding user response:

The root of the problem is that, by default, images are placed on a canvas with the center of the image at the coordinates given. You're giving coordinates based on the image width and height, and that is where the center is going.

For example, the image in the question is 297x170. You're using those as the coordinates for the image, which means that the center of the image will be at 297x170. The canvas is roughly 300x200. Since the center of the image is at x=297, it's going to extend beyond the right and bottom edges of the canvas.

It's not clear where you want the image to appear, but a simple fix to illustrate how anchor affects placement is to put the image at 0,0 and set the anchor to "nw" (northwest). That will show the entire image. If you want the image centered in the canvas, the solution just involves a little math to compute the coordinates of the center of the canvas.

CodePudding user response:

An answer would be to not use Canvas whatsoever and instead use a frame and label to display the image. Here is a working example:

import tkinter as tk
from tkinter import *
from tkinter.filedialog import askopenfilename
import os
from PIL import ImageTk, Image


def show_values():
    print(slider1.get())


window = tk.Tk()

filename = askopenfilename()  # show an "Open" dialog box and return the path to the selected file
print(filename)
filename3, file_extension = os.path.splitext(filename)

slider1 = Scale(window, from_=0, to=42, orient='vertical')
slider1.pack(side=LEFT)


frame = Frame(window, width=600, height=400)
frame.pack()


img = ImageTk.PhotoImage(Image.open(filename))
imageWidth = img.width()
imageHeight = img.height()

label = Label(frame, image = img)
label.pack(side=RIGHT)

Button(window, text='Process Image', command=show_values).pack(side=BOTTOM)

window.mainloop()
  • Related