-1
from Tkinter import Tk, PhotoImage, Label
def start_up():
    app = Tk()
    app.title("Tower")
    app.geometry('600x900')
    photo = PhotoImage("Python.png")
    label = Label(app, image = photo)
    label.pack()
    app.mainloop()
start_up()

I'm currently struggling with tkinter 2.7. I cannot display the image I want, therefore please take a look at my code and help me fix it. Thanks.

rwp
  • 1,456
  • 2
  • 9
  • 21
jaxk
  • 11
  • 3
  • Apologies, I voted to close for a minute there but on second look I don't think your problem has the same cause as https://stackoverflow.com/questions/27430648/python-tkinter-2-7-issue-with-image. – Kevin Apr 06 '18 at 18:46
  • You have to `pack()` the label _before_ you call `mainloop()`. – Aran-Fey Apr 06 '18 at 18:49
  • I applied the change but it's still a white screen. – jaxk Apr 06 '18 at 18:52

1 Answers1

1
from Tkinter import 

This is a syntax error. When using the from syntax, you need to list the names you want imported. (or an asterisk to import everything, but that's not good practice since it pollutes your namespace unnecessarily)

from Tkinter import Tk, PhotoImage, Label

 

label = Label(app, image = photo)
app.mainloop()
label.pack()

You're supposed to pack() your widgets before you call mainloop. Change this to:

label = Label(app, image = photo)
label.pack()
app.mainloop()

 

photo = PhotoImage("Python.png")

You're supposed to use the file keyword argument if you want to pass a filename to PhotoImage. Additionally, PhotoImage doesn't know how to open pngs. Try a format such as gif or pgm.

photo = PhotoImage(file="Python.gif")

Alternatively, install the third party library Pillow, and use its ImageTk.PhotoImage class, which supports a wide variety of image formats, including png.

from PIL import Image, ImageTk
img = Image.open("python.png")
photo = ImageTk.PhotoImage(img)
label = Label(app, image = photo)

End result:

from Tkinter import Tk, PhotoImage, Label
def start_up():
    app = Tk()
    app.title("Tower")
    app.geometry('600x900')
    photo = PhotoImage(file="Python.gif")
    label = Label(app, image = photo)
    label.pack()
    app.mainloop()
start_up()
Kevin
  • 69,817
  • 12
  • 97
  • 139
  • **_tkinter.TclError: couldn't open "Python.gif": no such file or directory** I converted the png to gif and ran the code but the error message showed up. I tried fixing it by dragging the gif into the same directory but it didn't do anything. – jaxk Apr 06 '18 at 20:41
  • @jaxk The image has to be placed in the [current working directory](https://en.wikipedia.org/wiki/Working_directory). Alternatively, use an absolute path like `r'C:\Users\whatever\Python.gif'`. Or make the path [relative to the python script](https://stackoverflow.com/questions/50499/how-do-i-get-the-path-and-name-of-the-file-that-is-currently-executing). – Aran-Fey Apr 06 '18 at 22:31