What is difference between label.configure(image=value) and label.image=value? - python

from tkinter import *
from tkinter.filedialog import *
wd = Tk()
def func_open():
fname = askopenfilename(parent=wd, filetypes=( ("gifs","*.gif"), ("alls","*.*") ))
photo1 = PhotoImage( file = fname )
pLabel.configure( image = photo1 )
pLabel.image=photo1
temp = PhotoImage()
pLabel = Label(wd, image = temp )
pLabel.pack(expand=1)
mainMenu = Menu(wd)
wd.config(menu=mainMenu)
fileMenu = Menu(mainMenu)
mainMenu.add_cascade(label="File", menu=fileMenu)
fileMenu.add_command(label="Open",command=func_open)
wd.mainloop()
2 lines of code above,
pLabel.configure( image = photo1 )
pLabel.image=photo1
if i remove one of these, func_open() can't print image file.
To me, it seems like both line says same thing,
as pLabel.configure( image = photo1 ) put image through argument photo1
and pLabel.image=photo1 is directly put photo1 to pLabel's image.
I tried search that .configure() method but i couldn't get any understandable imformation.

Widgets have internal configuration options that control its appearance and behavior. When you call the configure method, you are giving one of those options a value. Thus, pLabel.configure( image = photo1 ) sets the image option to the value of the photo1 variable.
When you do pLabel.image=photo1, you are creating a new instance variable on the pLabel python object named image and setting it to the value of the photo1 variable. The underlying tkinter widget has no knowledge of this attribute, and isn't affected by this attribute.
This is a common idiom for saving a reference to the image. The use of the word image is completely arbitrary, using pLabel.xyzzy=photo1 or pLabel.save_this=photo1 would solve the exact same problem.
For more information see Why does Tkinter image not show up if created in a function?

Related

Yet Another tkinter Image Garbage Collection Issue - RESOLVED: wrong parameter type [duplicate]

I have a label with an image, and a button which should update the label / delete the image in the label, so I can put a new image into the same label via label.config.
I tryed to use something like that: whenever you click on the button the it should remove the image with label.config(image = None) but it doesnt work, if I load new images into the label the old ones are still there:
# here is the label initialized
global brand_preview
brand_preview = Label(root, image = None)
brand_preview.place(x = 10, y = 60)
# thats the button which have to clear the label image
self.top_brand = Button(root, text = "clear", bg = "snow3", command=clear_label_image)
self.top_brand.place(x = 550, y = 60)
# thats how I load a photoimage into the label
photoimg_brand = ImageTk.PhotoImage(im_thumb)
brand_preview.image = photoimg_brand
brand_preview.config(image = photoimg_brand)
# Thats how the button works
def clear_label_image():
brand_preview.config(image = None)
brand_preview.image = None
All I want now that if we I click the Button the brand_preview loses the image / the image gets deleted
EDIT:
The main issue is solved, but that only works if the button only has to delete the image. If I want to delete and add a new one it doesnt work
def clear_label_image():
brand_preview.config(image = "")
photoimg_brand = ImageTk.PhotoImage(im_thumb)
brand_preview.image = photoimg_brand
brand_preview.config(image = photoimg_brand)
You're very close - the image parameter just needs an empty string rather than None.
def clear_label_image():
brand_preview.config(image='')
After some Googling, I found this solution
def clear_label_image():
#brand_preview.config(image = None)
brand_preview.image.blank()
brand_preview.image = None
This definitely clears the image from the button. I haven't tried changing to a new image.
I just copied it from the Web, and it worked. I created the image with
photoimg_brand = tk.PhotoImage(file='/usr/share/httpd/icons/world1.gif')
I did this with python 2.7, and my only import was import Tkinter as tk
If you are using label to show the image then you can do this:
label.pack_forget()
label should be global

Tkinter image not showing

I made this piece of code:
from tkinter import *
from PIL import ImageTk, Image
import sys
import getnew
class startUp:
def __init__(self, master):
master.title("Tag checker")
master.resizable(False, False)
img1 = ImageTk.PhotoImage(Image.open("images/ss.png"))
cercaImg = Label(master, image = img1)
cercaImg.bind("<Button-1>",clicka)
cercaImg.grid(row=0,column=0)
img2 = ImageTk.PhotoImage(Image.open("images/opz.png"))
opzioniImg = Label(master, image = img2)
opzioniImg.grid(row=0,column=1)
img3 = ImageTk.PhotoImage(Image.open("images/exit.png"))
esciImg = Label(master, image = img3)
esciImg.bind("<Button-1>",(master.destroy and quit))
esciImg.grid(row=0,column=2)
def clicka(event):
print('ciaooo')
x = getnew.getSchools()
print(x[0][0],x[0][1],x[0][2])
root = Tk()
st = startUp(root)
root.mainloop()
The point is to have 3 images that, when clicked, execute a function, but he images don't show up. They do appear as size and 'clickable' zone and they execute the function, but the image as it is doesn't show up.
What am I doing wrong here ?
From tkinter docs on PhotoImage:
You must keep a reference to the image object in your Python program, either by storing it in a global variable, or by attaching it to another object.
The reason to do so is :
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.
Hence for your program:
img1 = ImageTk.PhotoImage(Image.open("images/ss.png"))
cercaImg = Label(master, image = img1)
cercaImg.image = img1 # Keep a reference
Similarly for the other images as well.

Python- tkinter: Opening One Another image in another window?

Hello I am doing a job that I need (from a tkinter window containing an image) call another window that contains another imagem.I tried the following:
from tkinter import*
def abrir1():
b =Tk()
imagen = PhotoImage(file= "F2.png")
la = Label(b,image =imagen)
la.pack()
def abrir2():
b =Toplevel()
imagen = PhotoImage(file= "F2.png")
la = Label(b,image =imagen)
la.pack()
a = Tk()
canvas = Canvas(a, bg ="black",width = 512,height =512)
canvas.pack()
imagem = PhotoImage(file = "E2.png")
a1 = canvas.create_image(256,256,image = imagem)
btu1 = Button(a,text ="Abri1!",command = abrir1)
btu1.place(x = 150,y=400)
btu2 = Button(a,text ="Abri2!",command = abrir2)
btu2.place(x = 300,y=400)
But when I press the first button ( btu1 ) it returns the following error message:
_tkinter.TclError: image "pyimage2" doesn't exist
And when when I press the second button ( btu2 ) does not happen error but does not show the image, only the new window is created ;
I've tried several ways including placing * with canvas and without canvas* ;
You have two problems in your code.
The first problem is that you are creating two instances of Tk. A tkinter program needs to have exactly one instance.
The second problem is that the image you are creating is saved as a local variable. When the function returns, the variable is garbage collected. When a tkinter image is garbage collected the image data is discarded even though the widget still exists.
A very basic search of the internet yields this page: http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm

Displaying multiple images in Tkinter with scrollbar

I want to design a widget that displays multiple images of fixed size (300x300) stacked in a column. To do this, I created a text widget of size 300x800 and then added image labels inside it. I'm adding 4 images in the example below. Since the total vertical size of the stacked images are more, it's expanding the size of the text widget and it doesn't even fit the screen. I want all the images to stay inside the text widget without expanding it and add a scrollbar to the text widget so that I can scroll and see all the images. In the code below, I am able to add scrollbar but it doesn't work.
from Tkinter import *
import ttk
from PIL import *
from PIL import Image
import os
root = Tk();
text = Text(root, width = 300, height=300)
text.grid(row=0, column=0)
text.grid_propagate(False)
class ImageLabel:
def __init__(self, master, img_file):
label = Label(master)
label.img = PhotoImage(file=img_file)
label.config(image=label.img)
label.pack(side="bottom")
## Adding images to text widget
width = 300
src = "./"
my_item_id = 770353540339
count = 0;
file_name = str(my_item_id)+'_'+str(count)+'.jpeg';
full_file_name = os.path.join(src, file_name)
imagelabels = []
while os.path.isfile(full_file_name):
im = Image.open(full_file_name)
height = width*im.size[1]/im.size[0]
im.thumbnail((width, height), Image.ANTIALIAS)
im.save(str(count),'gif')
imagelabels.append(ImageLabel(text, str(count)))
count = count+1;
file_name = str(my_item_id)+'_'+str(count)+'.jpeg';
full_file_name = os.path.join(src, file_name)
print(count)
## Adding scrollbar
scrollbar = Scrollbar(root, orient=VERTICAL, command=text.yview)
scrollbar.grid(row=0,column=1, sticky='ns')
text.config(yscrollcommand=scrollbar.set)
root.mainloop()
If you are using a text widget to contain images, you must use the image_create or window_create method rather than using pack to place the image in the widget. You'll also need to insert a newline after each image to get them to stack vertically.

tkinter canvas image not displaying

I have a simple canvas being created in a function, and i would like an image displayed on the canvas.
def start(root):
startframe = tkinter.Frame(root)
canvas = tkinter.Canvas(startframe,width=1280,height=720)
startframe.pack()
canvas.pack()
one = tkinter.PhotoImage('images\one.gif')
canvas.create_image((0,0),image=one,anchor='nw')
when i run the code i get a blank 1280x720 window, no image.
i have looked at the following website: http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm but i do not understand how to apply their example to my situation (i dont know what to create a reference to or how to create a reference, if that is my problem). I have also looked at some stack overflow questions but they did not help either.
Escape backslashes in path string correctly. (or use r'raw string literal').
Prevent PhotoImage object being garbage collected.
specify the filename using file=... option.
def start(root):
startframe = tkinter.Frame(root)
canvas = tkinter.Canvas(startframe,width=1280,height=720)
startframe.pack()
canvas.pack()
# Escape / raw string literal
one = tkinter.PhotoImage(file=r'images\one.gif')
root.one = one # to prevent the image garbage collected.
canvas.create_image((0,0), image=one, anchor='nw')
UPDATE
The two statements one = ... and root.one = one can be merged into one statement:
root.one = one = tkinter.PhotoImage(r'images\one.gif')
How about canvas.update()? I was suffering a similar problem. I am using grid, so instead of .pack I needed to use .update.
I had the situation when image didn`t show up, when I call it in function, but otherwise everything was okay. That is my function
def ask_for_file():
f_types = [('PNG Images', '*.png')]
filename = askopenfilename(filetypes=f_types)
img = ImageTk.PhotoImage(file=filename)
canvas.config(height=img.height(), width=img.width())
canvas.create_image(0, 0, anchor=NW, image=img)
My solution was to add img = None as global variable and change it inside function. It worked
img = None
def ask_for_file():
global img
f_types = [('PNG Images', '*.png')]
filename = askopenfilename(filetypes=f_types)
img = ImageTk.PhotoImage(file=filename)
canvas.config(height=img.height(), width=img.width())
canvas.create_image(0, 0, anchor=NW, image=img)

Categories