0

This is for a school project, so i kind off want to understand what I am doing.

I want to add a photo, for example the photo with the name 'teletubbies.jpg' as the background. I have no clue how to do this and how this works, been searching for hours now and dying to find an answer :$

This is the bit of code that i have now:

from tkinter import *

from tkinter.messagebox import showinfo

def clicked():
    bericht = 'Test for stackflow!',
    showinfo(title='popup', message=bericht)

def clicked1():
    bericht = 'Test for stackflow'
    showinfo(title='popup', message=bericht)

root = Tk()

label = Label(master=root,
              text='This is a test for stackflow',
              background='black',
              foreground='white',
              height = 2
              )
label.pack()

button2 = Button(master=root, text='Klik hier voor het beheerportaal', command=clicked, fg='red')
button2.pack(side=BOTTOM,pady=10)

button1 = Button(master=root, text='Klik hier voor het klantportaal', command=clicked1)
button1.pack(side=TOP,pady=10)

entry = Entry(master=root)
entry.pack(padx=10, pady = 10)

root.configure(background='black')
root.mainloop()

1 Answers1

1

If you have a .gif or .pgm/ppm file you could use the Tkinter PhotoImage class to load your image and put it as a background to your label:

backgroundImage = PhotoImage(file = <yourFilePath>)
label = Label(master=root,
              image = backgroundImage,
              text='This is a test for stackflow',
              height = 2
              )
label.place(x=0, y=0, relwidth=1, relheight=1)

This will put your image as background in your label.

For the other image formats you can use the Python Image Library.

toti08
  • 2,448
  • 5
  • 24
  • 36
  • I've tried doing this, but when i try to open a .gif file it gives the error: _tkinter.TclError: couldn't recognize data in image file "teletubbies.gif" Since i believe that, when the file is in the same directory as the image, i do not have to specify the path to the image file and just the name is enough – Niels Fonken Oct 15 '18 at 11:39
  • Yes, you're correct, you shouldn't specify the full path, but the error suggests your image is not readable. Are you sure the image is a `gif`? Do you have another image to try with? – toti08 Oct 15 '18 at 11:43
  • Sounds like its the actual file and not the path. Might be some help here https://stackoverflow.com/questions/15718663/tkinter-image-not-showing-or-giving-an-error – Jake Oct 15 '18 at 11:48
  • 1
    You are a hero, thank you so much. I think that the image which i was trying wasn't a .gif file even tho the extension said so, a bit weird :P. Again thank you! – Niels Fonken Oct 15 '18 at 11:50