It does not show the images

0

I'm practicing with Python 2 and Tkinter, the problem is that when I try to add an image it does not appear.

The code is this:

image= tk.PhotoImage("1473185883EMBW_07.gif")
image=image.subsample(1,1)
label=tk.Label(image=image)
label.place(x=0,y=0,relwidth=1.0,relheight=1.0)
label.pack(padx=10,pady=10)

but when I execute it I do not get any error but the image does not appear, a very small white dot appears:

    
asked by elotaca 16.05.2018 в 00:14
source

1 answer

1

Although it is not very well documented, the first initializer argument of the class tkinter.PhotoImage (apart from self ) is name , which by default is None and that is common to the rest of the widgets. Basically it allows defining a name that identifies the instance and that is necessary for Tk (so Tkinter always defines one automatically if it is not provided) although with almost no utility in Tkinter itself. You can confirm this by doing print(image.name) just below the instance of PhotoImage (which will print your route).

To avoid having the route taken as a value of the argument name use the keyword file :

image= tk.PhotoImage(file="1473185883EMBW_07.gif")

PhotoImage also accepts GIF images encoded in base64 (strings), in this case the argument data is used:

image = tk.PhotoImage(data=string_base64)

You should keep a reference to the image at all times , this is relevant if this code is in a function or method e image is a local variable, look at this question and my answer related to this:

Add buttons with images dynamically in Python Tkinter

You should always pass to each widget your father if he has it, it is essential when applying pack / grid / place because you can end up creating the widgets in the wrong container for example:

import Tkinter as tk


root = tk.Tk()
image= tk.PhotoImage(file="1473185883EMBW_07.gif")
label=tk.Label(root, image=image)
label.pack(padx=10, pady=10)
root.mainloop()

Finally two observations (I do not know if they are the result of you trying things out): it does not make much sense that you use two geometry managers on the same widget, in the end you will only apply the last one ( pack in your case). On the other hand, the use of the method subsample with (1, 1) as arguments is limited to copying the image, since there is no scaling factor whatsoever.

    
answered by 16.05.2018 в 01:44