[Tutor] Centring an image on a label

Phil phillor9 at gmail.com
Tue May 7 00:41:00 EDT 2024


Spurred on by a recent question about displaying images, I have 
developed an image viewer that works except I haven't been able to 
centre the image when the image is less than the width or height of the 
frame.

I have label on a frame. The frame is set to 600 x 600. Images that are 
wider or higher than 600 are scaled to fit. The frame and label are 
defined as follows:

photo_frame = ttk.Frame(
     root, height=600, width=600, borderwidth=3, relief="sunken")
photo_frame.grid(row=0, column=0, padx=10, pady=10, sticky=tk.NSEW)

self.photo_label = ttk.Label(photo_frame)
self.photo_label.grid(row=0, column=0, padx=0, pady=0)#sticky=tk.NSEW)

root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
photo_frame.grid_propagate(False)

I have a test image that requires a padx of 63 to be centred and I'm 
trying to do that as follows:

self.photo_label.configure(padx=63)

Resetting the padding before the image is displayed has no effect and 
and neither does resetting the padding after the image is displayed.

photo = ImageTk.PhotoImage(image)
self.photo_label.config(image=photo)
self.photo_label.image = (photo)

It appears that the way that I'm trying to centre the image is not the 
correct method.

I had a play with the pack manager but that didn't seem to be the answer 
either.

Is it possible the centre the image without calculating the required 
padding?

Any suggestions will be greatly appreciated.

-- 
Regards,
Phil



More information about the Tutor mailing list