1

Hello i have problem with set background image i want set image in another window in tkinter (python) look at def matus()

can someone help me idk now anymore..

this is function for another window...

def matus():
matus = Tk()
matus.title("Nice WIndow")
matus.geometry("400x400")
canvas=Canvas(matus, width = 400, height = 400)

image=ImageTk.PhotoImage(Image.open("fotky/images.jpg"))

canvas.create_image(0,0,anchor=NW,image=image)

canvas.pack()
Bryan Oakley
  • 341,422
  • 46
  • 489
  • 636
Cunoo
  • 21
  • 4
  • 1
    `Tk()` should be used only to create main window. For other windows use `Toplevev()`. – furas Dec 01 '19 at 21:35
  • 2
    There is bug in `PhotoImage` which remove image from memory when it is created in function and not assigned to global variable - see `Note` in doc [PhotoImage](http://effbot.org/tkinterbook/photoimage.htm) – furas Dec 01 '19 at 21:41
  • Please fix the indentation of the code in your question. Also, why do you think this code isn't working? What does it do, and how is that different than what you expect? – Bryan Oakley Dec 02 '19 at 20:42
  • Read [Why are multiple instances of Tk discouraged?](https://stackoverflow.com/questions/48045401/why-are-multiple-instances-of-tk-discouraged) and [Why does Tkinter image not show up if created in a function?](https://stackoverflow.com/a/16424553/7414759) – stovfl Dec 02 '19 at 21:34

1 Answers1

0

There is bug in PhotoImage which removes image from memory when it is assigned to local variable in function. See Note in doc PhotoImage

You have to assign it to global variable

def matus():
    global image

    image = ImageTk.PhotoImage(Image.open("image.jpg"))

or to variable in some class

def matus():
    matus = tk.Toplevel()

    image = ImageTk.PhotoImage(Image.open("image.jpg"))
    matus.image = image

import tkinter as tk
from PIL import ImageTk, Image

# --- functions ---

def matus():

    matus = tk.Toplevel()

    image = Image.open("image.jpg")
    w, h = image.size

    photo = ImageTk.PhotoImage(image)
    matus.photo = photo  # solution for bug in `PhotoImage`

    canvas = tk.Canvas(matus, width=w, height=h)
    canvas.pack()

    canvas.create_image(0, 0, anchor='nw', image=photo)

# --- main ---

root = tk.Tk()

button = tk.Button(root, text='IMAGE', command=matus)
button.pack()

root.mainloop()
furas
  • 119,752
  • 10
  • 94
  • 135
  • still doesnt work look this is my code (search for matus..)https://gist.github.com/Cunoo/3e5779af4b3ea4e419ab74cfcb3ccc37 – Cunoo Dec 01 '19 at 23:26