0

I'm trying to have an image in a window in tkinter in a class but i cant get it to work, without the image lines it shows an empty window but when I execute the code with the lines for the image, I get an error saying: 'Img_window' object has no attribute 'tk'.

How can I change the code to show the image?

Here is the code:

from tkinter import *
from PIL import Image, ImageTk

class Img_window:
    def __init__(self):

        self.window = Tk()
        self.window.title("Image")
    
        image_open = Image.open("welcome.jpg")
        welcome_img = ImageTk.PhotoImage(image_open)

        image_label = Label(self, image = welcome_img)
        image_label.grid(row=1,columnspan=3)
    
        self.window.mainloop()

img_window = Img_window()
martineau
  • 112,593
  • 23
  • 157
  • 280
Dan S.
  • 1
  • Exactly what "lines" are you talking about? I think your question might be a duplicate of [Why does Tkinter image not show up if created in a function?](https://stackoverflow.com/questions/16424091/why-does-tkinter-image-not-show-up-if-created-in-a-function) – martineau Dec 14 '21 at 21:11
  • Typo. You have `Label(self, ...)` where you need `Label(self.window, ...)`. – Tim Roberts Dec 14 '21 at 21:16
  • You can't use a non-widget as the parent of a widget. `self` isn't a widget. – Bryan Oakley Dec 14 '21 at 22:01
  • If it is a child window, use `Toplevel()` instead of `Tk()`. – acw1668 Dec 15 '21 at 00:46

1 Answers1

0
import tkinter as tk   #Added this
from tkinter import *

from PIL import Image, ImageTk



class Img_window:
    def __init__(self):
        window = Tk() #Fixed
        window.title("Image") #Fixed
            
        image_open = Image.open("welcome.jpg")
        welcome_img = ImageTk.PhotoImage(image_open)

        image_label = Label(image = welcome_img) #fixed
        image_label.grid(row=1,columnspan=3)
            
        window.mainloop()

Img_window()

Your problem was beeing using self where you shouldn't and not importing tkinter as tk

    image_label = Label(self, image = welcome_img)


    self.window = Tk()
    self.window.title("Image")
Lixt
  • 13
  • 5