2
votes

I need to resize my window(tkinter) according to the width and height of my background image. My code

from tkinter import *
from PIL import ImageTk
import cv2

image=cv2.imread("New_refImg.png")
width_1, height_1,channels = image.shape   

canvas = Canvas(width = width_1, height = height_1, bg = 'blue')
canvas.pack(expand = YES, fill = BOTH)

img = ImageTk.PhotoImage(file = "New_refImg.png")
canvas.create_image(10, 10, image = img, anchor = NW)

mainloop()

I'm using a simple method, I call the same image twice : image=cv2.imread("New_refImg.png") and img = ImageTk.PhotoImage(file = "New_refImg.png") but is there a way change this line img = ImageTk.PhotoImage(file = "New_refImg.png") to something like that img = ImageTk.PhotoImage(image) (image already has been called in the 3rd line of the code) Thank you

1

1 Answers

1
votes

I don't know about PIL, but I can show you how to do it in tkinter:

from tkinter import *

root = Tk() # Create Tk before you can create an image

img = PhotoImage(file='pilner.png')
w, h = img.width(), img.height()   

canvas = Canvas(root, width=w, height=h, bg='blue', highlightthickness=0)
canvas.pack(expand = YES, fill = BOTH)
canvas.create_image(0, 0, image=img, anchor=NW)

root.mainloop()

highlightthickness=0 rmoves the highlight border on the canvas. I'm positioning it at 0,0 so as to not show the bg.