im trying to learn Python and doing some test apps.
Right now im creating a type of image viewer for viewing external images. But have some problems.
I've successfully worked out on how to view the image. But i need to view it as a function, so the image can be updated.
This is what i use for just viewing the image:
from io import BytesIO
import urllib
import urllib.request
import tkinter as tk
from PIL import Image, ImageTk
imagelinks = []
***** Here is a crawler that provides image urls from a webpage into the above list ***
root = tk.Tk()
listvalue = 1
url = (imagelinks[listvalue])
with urllib.request.urlopen(url) as u:
raw_data = u.read()
im = Image.open(BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
label = tk.Label(image=image)
label.pack()
root.mainloop()
Everything works well, the image 1 from the list shows up properly.
The problem im having is that i want to add a prev and next button which increment the value of listvalue-=1 and +=1 but simply doing that wont work since it wont update the image in the tkinter window.
Also tried with the Tkinter's update() in my buttons function, but didn't help much either.
Anyone got some input on how to get it to work?
Update:
Tried to put it in a function like this. It is resizing the windows to the proper size, but wont show the image.
from io import BytesIO
import urllib
import urllib.request
import tkinter as tk
from PIL import Image, ImageTk
root = tk.Tk()
link='http://img.khelnama.com/sites/default/files/previewimage/features/2013/Aug/IMG- Reliance_logo(1).jpg'
def showimg(currentimg):
url = currentimg
with urllib.request.urlopen(url) as u:
raw_data = u.read()
im = Image.open(BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
label = tk.Label(image=image)
label.pack()
showimg(link)
root.mainloop()
You will need to put your code that retrieves and displays the image in a definition, and pass the list item that it is meant to use as a parameter. That way on a button press, you can increment or decrement the index, and call your own update function you made.
Edit:
Try this then
label = tk.Label()
label.pack()
def showimg(currentimg, label):
url = currentimg
with urllib.request.urlopen(url) as u:
raw_data = u.read()
im = Image.open(BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
label.config(image = image)
showimg(link, label)
Related
So i am using python 3 and got confused why the image doesnt show up in text widget after excuted the following code:
from tkinter import *
import fitz
root=Tk()
filenew=fitz.open(r'C:\Users\azoka\Desktop\Python\b.pdf')
text_1=Text(root,width=100,height=100,bg='gray').pack(side=LEFT,expand=FALSE)
def Show():
pix =filenew.getPagePixmap(0) # 0 is page number
pix1=fitz.Pixmap(pix,0)
img =pix1.getImageData("ppm")
timg=PhotoImage(data=img)
frame=[]
frame.append(timg)
text_1.image_create(END,image=timg)
Shower=Button(win1,text='show',bg='navy',fg='light cyan',width=5,height=1,command=Show)
Shower.place(x=1000,y=360)
root.mainloop()
The image just dont show up after clicked the button but it doesnt show any code error,I am new to python
and cant figure out. I want my img be shown without altering the Show()function.
-Appreciate for helpful answers!-
I tried to use the from previous code but not works
I made some fix with last version today, see fix bellow with simplifications
from tkinter import *
from PIL import Image, ImageTk
import fitz
root = Tk()
file = "yourfile.pdf"
doc = fitz.open(file)
page = doc.load_page(0) # loads page number 'pno' of the document (0-based)
pix = page.get_pixmap()
mode = "RGBA" if pix.alpha else "RGB"
img = Image.frombytes(mode, [pix.width, pix.height], pix.samples)
frame_image = ImageTk.PhotoImage(img)
label = Label(root, bg='gray')
label.pack(side=LEFT)
label.config(image=frame_image)
label.image = frame_image
root.mainloop()
requirements to use "PyMuPDF-1.21.1"
pip install --upgrade pymupdf
see more: https://pymupdf.readthedocs.io/
from tkinter import *
from PIL import Image, ImageTk
import glob, os
root = Tk()
root.geometry("800x600")
# Function to display image
def displayImg(img):
image = Image.open(img)
photo = ImageTk.PhotoImage(image)
newPhoto_label = Label(image=photo)
newPhoto_label.pack()
# gta_images = []
os.chdir("gta")
for file in glob.glob("*.jpg"):
# gta_images.append(str(file))
displayImg(file)
print(file)
# print(gta_images)
root.mainloop()
I am trying to load images from a folder called "gta" and then display those game logos on my app. Program has no error but I think its a logical error. I am new to Python I don't know maybe there is some scoping logic problem in my displayImg funcion.
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.
For more.
from tkinter import *
from PIL import Image, ImageTk
import glob, os
root = Tk()
root.geometry("800x600")
photos = []
def displayImg(img):
image = Image.open(img)
photo = ImageTk.PhotoImage(image)
photos.append(photo)#keep references!
newPhoto_label = Label(image=photo)
newPhoto_label.pack()
for file in glob.glob("*.jpg"):
displayImg(file)
print(file)
root.mainloop()
Not sure if it will work but try using the path of the gta folder you are getting the images from, instead of its name simply - replace the name with the path.
I am trying to use the image from this webpage and display it in a Tkinter label. However, whenever I try it the label is created, but the image is blank. It works when I use a url that ends in .jpg (http://i.imgur.com/CC8zIPr.jpg for example). Is there a way to make the first link work correctly? This is the relevant part of my code:
url = "http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=414495&type=card"
u = urlopen(url)
raw_data = u.read()
im = Image.open(io.BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
label = tk.Label(image=image)
label.image = image
label.pack()
My goal is to display an JPG image from an URL using tkinter python.
This is the stackoverflow link that I used as a reference. But when I try to run the code, I have received a bunch of error such as:
KeyError: b'R0l.......
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
Does anyone have the solution to this?
This is the code:
import tkinter as tk
from PIL import Image, ImageTk
from urllib.request import urlopen
import base64
root = tk.Tk()
URL = "http://www.universeofsymbolism.com/images/ram-spirit-animal.jpg"
u = urlopen(URL)
raw_data = u.read()
u.close()
b64_data = base64.encodestring(raw_data)
photo = ImageTk.PhotoImage(b64_data)
label = tk.Label(image=photo)
label.image = photo
label.pack()
root.mainloop()
The first error is not specifying the data parameter within ImageTk.PhotoImage(data=b64_data). However, I'm unsure why PhotoImage is unable to read base64 data.
A workaround would be to use BytesIO from the io module. You can pass in the raw data you read from the image into a BytesIO, open it in Image and then pass that into PhotoImage.
I found the code for opening the image from here.
import tkinter as tk
from PIL import Image, ImageTk
from urllib2 import urlopen
from io import BytesIO
root = tk.Tk()
URL = "http://www.universeofsymbolism.com/images/ram-spirit-animal.jpg"
u = urlopen(URL)
raw_data = u.read()
u.close()
im = Image.open(BytesIO(raw_data))
photo = ImageTk.PhotoImage(im)
label = tk.Label(image=photo)
label.image = photo
label.pack()
root.mainloop()
If anybody has a better answer as to why the encoding fails, it would be a more appropriate answer to this question.
Very similar but easier than Hobbes' answer, you can directly use the data parameter in the ImageTk.PhotoImage constructor:
import tkinter as tk
from PIL import Image, ImageTk
from urllib.request import urlopen
root = tk.Tk()
URL = "http://www.universeofsymbolism.com/images/ram-spirit-animal.jpg"
u = urlopen(URL)
raw_data = u.read()
u.close()
photo = ImageTk.PhotoImage(data=raw_data) # <-----
label = tk.Label(image=photo)
label.image = photo
label.pack()
root.mainloop()
This question already has answers here:
Tkinter Label does not show Image
(3 answers)
Closed 7 years ago.
I'm trying to create an image, but it's not working and I'm not sure what I'm doing wrong. All I get when I click the button that should display the image is the white canvas, without the image. How do I get it to display?
def show_original(self):
from os.path import exists
from PIL import Image, ImageTk
if not os.path.exists(self.wdg_orig_file_name_.get()):
tkMessageBox.showinfo('Load','File does not exist:' + self.wdg_orig_file_name_.get())
return
self.orig_image_=Image.open(str_orig_file_name)
canvas = self.gui_.ca(500,500,bg='white')
im_TK = ImageTk.PhotoImage(self.orig_image_)
canvas.create_image(250,250,image=im_TK)
canvas.pack()
pass
self.wdg_orig_file_name_.get() in the main loop is:
self.wdg_orig_file_name_ = self.gui_.en(text='boat.png')
The global str_orig_file_name is assigned in pick_file():
def pick_file(self):
'''Opens a file dialog and sets its result to the filename entry'''
global str_orig_file_name
str_orig_file_name = tkFileDialog.askopenfilename()
if str_orig_file_name:
self.wdg_orig_file_name_.delete(0, END)
self.wdg_orig_file_name_.insert(0, str_orig_file_name)
#We got a new image to process. Forget the previous results.
self.orig_image_ = None
self.preview_image_ = None
Have you tried easygui?
#!/usr/bin/python
from easygui import *
image = "img.jpg"
msg = "Do you like this picture?"
choices = ["Yes","No","No opinion"]
reply=buttonbox(msg,image=image,choices=choices)
Very easy.
http://www.ferg.org/easygui/tutorial.html
I'm sorry. I though the OP was looking for a way to display an image and now I see the image is supposed to be on the button. Well I tried this and it works just fine with .gif and .png. However .jpg gives an error: "_tkinter.TclError: couldn't recognize data in image file "img.jpg"".
#!/usr/bin/python
from Tkinter import *
root=Tk()
b=Button(root,justify = LEFT)
photo=PhotoImage(file="img.png")
b.config(image=photo,width="100",height="100")
b.pack(side=LEFT)
root.mainloop()