This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed last year.
I'm trying to load an image into tkinter, to use as a background image. The image is a GIF (originally JPG, but I heard that tkinter doesn't support that format) with the same dimensions as the window. Anyway, when I ran my code, it ran, but the tkinter window was empty! Here's my code for the window:
class Window(Tk):
def __init__(self):
super().__init__()
self.geometry("700x600")
self.resizable(False, False)
def background_img(self, img_path):
background_img = PhotoImage(file=img_path)
background_img_label = Label(self, image=background_img)
background_img_label.place(x=0, y=0)
window = Window()
img_path = "background.gif"
window.background_img(img_path)
window.mainloop()
Can you please tell me what I'm doing wrong? Thanks in advance.
As TDG said, the names background_img (function) and background_img (tkinter.PhotoImage) override each other. You should rename one.
Related
This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 11 months ago.
I want to set my Canvas background as gif. Here's what I'm currently trying to do:
def convertPage():
for i in mw.winfo_children():
i.destroy()
drop_file = Canvas(mw, width=270, height=270)
drop_file.place(x=25, y=25)
image = ImageTk.PhotoImage(file="media/ukral.gif")
drop_file.create_image(10, 10, image=image, anchor=NW)
Button(mw, text='KEYWORD IMAGE', command=fileDialog, font=('Inter', 24), fg='#3EC96D', bg='black').place(width=250, height=60, relx=0.1875, rely=0.628)
Button(mw, text='BACK', command=mainPage, font=fnt_sml, fg='#3EC96D', bg='black').place(width=250, height=60, relx=0.1875, rely=0.806)
There are no errors returned in the console, but gif doesn't work, the background of Canvas is white. BTW, I'm doing it from Mac, so maybe this could be the issue.
Update: finally found the solution here:
Play an Animated GIF in python with tkinter
Have you tried to look online?
I found this link, it might be helpful
In short, the answer could be adding the right format kwarg
This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 4 years ago.
I am trying to display an image in a window. I tried it two methods, using classes and single snippet.
I am confused why this is showing correct output:
from Tkinter import *
from PIL import ImageTk, Image
root = Tk()
picture="path/image.jpg"
image = Image.open(picture).resize((350, 350), Image.ANTIALIAS)
print(image)
pic = ImageTk.PhotoImage(image)
panel = Label(root, image = pic)
panel.grid(sticky="news")
root.mainloop()
but not the below one?
from Tkinter import *
from PIL import ImageTk, Image
class DisplayImage():
def __init__(self, root):
self.root = root
def stoneImg(self, picture="path/default_image.png"):
image = Image.open(picture).resize((350, 350), Image.ANTIALIAS)
pic = ImageTk.PhotoImage(image)
panel = Label(self.root, image=pic)
panel.grid(sticky="news")
if __name__ == '__main__':
root = Tk()
DisplayImage(root).stoneImg()
root.mainloop()
The difference is that in your second example, the picture was referred to only by a local variable, which went away at the end of the function. Garbage collection works a bit weirdly in Tkinter, since all of the GUI-related objects exist in the embedded Tcl interpreter, outside of Python's control.
The simple solution is to add a line like panel.image = pic, so that a reference to the image exists for as long as the widget itself does.
This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 4 years ago.
I am trying to display an image in a window...seems simple enough right? Well I have a big bug!
I have this exact same code in one file:
import Tkinter
root = Tkinter.Tk()
canvas = Tkinter.Canvas(root)
canvas.grid(row = 0, column = 0)
photo = Tkinter.PhotoImage(file = '/Users/Richy/Desktop/1.gif')
image1 = canvas.create_image(0,0, image=photo)
root.mainloop()
It works.
I have this in part of a bigger file:
def officialPictureWindow(self):
t = Toplevel(self)
t.wm_title("Official Image")
self.__canvas3 = Canvas(t)
self.__canvas3.grid(row = 0, column = 0)
photo = PhotoImage(file = '/Users/Richy/Desktop/1.gif')
image1 = self.__canvas3.create_image(0,0, image=photo)
It doesn't work!
That function is called when someone presses a button on a menubar I have. All the other menubar buttons I have operate properly and show their windows. There's no images in the others though.
This gives no no error. Just a blank screen. Does anyone know why?
You need to keep an additional reference to photo so it doesn't get prematurely garbage collected at the end of the function. An Introduction to Tkinter explains further:
Note: When a PhotoImage object is garbage-collected by Python (e.g. when you return from a function which stored an image in a local variable), the image is cleared even if it’s being displayed by a Tkinter widget.
To avoid this, the program must keep an extra reference to the image object. A simple way to do this is to assign the image to a widget attribute, like this:
label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()
In your case, you could attach the image to your self variable, or maybe the canvas. It doesn't really matter, as long as it is assigned to something.
self.image = photo
#or:
self.__canvas3.image = photo
This question already has answers here:
Image resize under PhotoImage
(5 answers)
Closed 6 years ago.
I have an image that I display and I would like to resize (enlarge, actually) that image. Here's my code, using other SO questions, but I get no result - my image still has the same size. Resizing the button also does not change the image size.
I've tried the answers from this SO question: Image resize under PhotoImage but they won't work.
from Tkinter import *
root = Tk()
root.withdraw()
def cleanUp():
root.destroy()
def openWebsite():
print 'Will try to implement opening the website here.'
window = Toplevel(root)
window.protocol('WM_DELETE_WINDOW', cleanUp)
photo = PhotoImage(file="Header.pgm")
photo.zoom(2)
button = Button(window, image=photo, command=openWebsite)
button.pack()
root.mainloop()
PhotoImage.zoom() returns a new image, it does not modify the original image. Try rebinding photo like this:
photo = photo.zoom(2)
From the help:
zoom(self, x, y='') method of Tkinter.PhotoImage instance
Return a new PhotoImage with the same image as this widget
but zoom it with X and Y.
This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 7 years ago.
I'm using TkInter to write a GUI that will contain an image and a few buttons in a panel next to the image.
I started by writing a script that would allow me to visualize an image, and it works just fine:
#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
import Tkinter
from PIL import Image, ImageTk
window = Tkinter.Tk()
window.title("Test GUI")
window.geometry("640x478")
window.configure(background='grey')
window.grid()
img = ImageTk.PhotoImage(Image.open('./test.jpg'))
canvas = Tkinter.Canvas(window, width=640, height=478, bg='white')
canvas.create_image(0,0,anchor='nw',image=img)
canvas.grid(column=0,row=0)
window.mainloop()
I then tried to rewrite the above code as a class, to implement some event-handling functions. However, the same exact code written in the class initialization function will not visualize the image.
#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
import Tkinter
from PIL import Image, ImageTk
class showImageGUI(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
# the grid layout manager is a simple grid
# where you put your widgets
self.grid()
img = ImageTk.PhotoImage(Image.open('./test.jpg'))
canvas = Tkinter.Canvas(self, width=640, height=478, bg='white')
canvas.create_image(0,0,anchor='nw',image=img)
canvas.grid(column=0,row=0)
if __name__ == "__main__":
app = showImageGUI(None)
app.title('Test GUI')
# event-driven programming: the program will
# loop forever doing nothing but wait for events
# and only react when it receives an event
app.mainloop()
The only difference between the two is:
In the script implementation I assign the parent of the canvas widget to be the whole window.
In the class implementation I assign the parent of the canvas widget to be the self variable for the whole app.
Can someone please explain me why is this breaking the code / how to solve it?
There's a bug in Tkinter that causes images to disappear if there is no external reference to them, even though they should be bound into the Canvas widget somehow. I'm probably not explaining this well, because I've never taken the trouble to really research what is going on. I believe it is explained somewhere on effbot.org.
In any event, change the line
img = ImageTk.PhotoImage(Image.open('./test.jpg'))
to
img = self.img = ImageTk.PhotoImage(Image.open('./test.jpg'))
and I think it will work for you. It works for me.