0

I would really appreciate some help..

What I am trying to to - in TKinter - to click on button, choose file, resize it and that file would display in canvas.

The problem occurs upon resizing. If I just update canvas it will work ok - the image just won't fit. So I've tried resize trick I read online (below). But the final image won't show. It does not produce any errors.. Just blank canvas

def select_file():
    filetypes = [('Image files', '*.jpg'), ('Image files', '*.png'), ('Image files', '*.jpeg')]
    filename = fd.askopenfilename(title='open a file', initialdir='/', filetypes=filetypes)

    canvas.delete("all")
    img_new = Image.open(filename)
    r_image = img_new.resize((200, 200))
    n_image = ImageTk.PhotoImage(r_image)
    canvas.create_image(100, 100, image=n_image)

the whole code below


from tkinter import *
from tkinter import messagebox
from tkinter import filedialog as fd
from PIL import Image, ImageTk

# Create a window
window = Tk()
window.title('Watermarking')
window.config(pady=50, padx=50)
window['bg'] = '#B3CFF2'

filename = ''

# ---- Functions ---- #

def select_file():
    filetypes = [('Image files', '*.jpg'), ('Image files', '*.png'), ('Image files', '*.jpeg')]
    global filename
    filename = fd.askopenfilename(title='open a file', initialdir='/', filetypes=filetypes)
    canvas.delete("all")
    img_new = Image.open(filename)
    r_image = img_new.resize((200, 200))
    n_image = ImageTk.PhotoImage(r_image)


# ----- UI ------ #
# Create Canvas
canvas = Canvas(height=200, width=200, bg='skyblue')
canvas.grid(column=1, row=0)
img = PhotoImage(file='computer-r.png')
print(f'This original{img}')
canvas.create_image(100, 100, image=img)

# Create Buttons
add_img = PhotoImage(file='assests/button_add-image.png')
# add_img_button = Button(text='Choose image', bg='#4B94F2', fg='#B3CFF2')
add_img_button = Button(image=add_img, borderwidth=0, bg='#B3CFF2', activebackground="#B3CFF2", command=select_file)
add_img_button.grid(column=0, row=0, pady=50)


window.mainloop()

I've tried changing position in canvas.create_image, change size on canvas (maybe it just got put somewhere else) - but nothing(

Nikita
  • 21
  • 1
  • 4

1 Answers1

0

Try to replace PhotoImage by ImageTk.PhotoImage. It is a bad habit to use * in imports.

Bad :

from tkinter import *
Button()

Good :

import tkinter as tk
tk.Button()
Phoenixo
  • 2,071
  • 1
  • 6
  • 13