python3.2 tkinter display an image from a URL - python-3.x

I'm trying to use tkinter on python 3.2 to display an image from the Internet.
I'm getting TypeError: 'HTTPResponse' object is not callable.I know that this means I'm referencing a variable or function incorrectly.
I have read urllib "module object is not callable" but I'm still not sure how to fix this problem. Your help is appreciated.
import tkinter as tk
from urllib.request import urlopen
from PIL import ImageTk, Image
#http://docs.activestate.com/activepython/3.1/diveintopython3/html/porting-code- to-python-3-with-2to3.html
import io
img_file = urlopen('https://www.google.com/images/srpr/logo4w.png')
im = io.FileIO(img_file())<<<<<<<<<<<<<this line is throwing the error
resized_image = Image.open(im)
im.show()
root = tk.Tk()
img = ImageTk.PhotoImage(resized_image)
panel = tk.Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()

You can create a StringIO object instead:
from StringIO import StringIO
...
im = StringIO(img_file.read())
It behaves like a file, but it's not a file.

Related

How to resize image using Pillow and tkinter

I am trying to display photos from NASA API but I only get the piece of this photo.
I tried to change the geometry of the window app but I still have the same problem.
Also, I tried to resize the image but I am getting errors.
import requests
from pprint import PrettyPrinter
import json
import datetime
from tkinter import *
from PIL import Image, ImageTk
from urllib.request import urlopen
root = Tk()
root.geometry("800x500")
root.title("Nasa photo of a day")
pp = PrettyPrinter()
api_key = 'PRIVATE KEY'
today_date = datetime.date.today()
URL_APOD = "https://api.nasa.gov/planetary/apod"
date = today_date
params = {
'api_key': api_key,
'date': date,
'hd': 'True'
}
response_image = requests.get(URL_APOD, params=params)
json_data = json.loads(response_image.text)
image_url = json_data['hdurl']
print(image_url)
imageUrl = image_url
u = urlopen(imageUrl)
raw_data = u.read()
u.close()
nasa_img = ImageTk.PhotoImage(data=raw_data)
my_label1 = Label(image=nasa_img)
my_label1.pack()
root.mainloop()
This is how it looks like
And this is how is should looks like
You can pass the result of urlopen(...) to PIL.Image() to fetch the image and then resize the image as below:
with urlopen(imageUrl) as fd:
# fetch the image from URL and resize it to desired size
image = Image.open(fd).resize((500,500))
nasa_img = ImageTk.PhotoImage(image)
my_label1 = Label(image=nasa_img)
my_label1.pack()

Looping an OpenCV image inside a Tkinter label - using an esp32-cam

It's a loop understanding problem, I'm new to Tkinter and I don't know how the images are updated
°°°PROBLEM°°°
It is about making a program that captures images of the esp32-cam module and can visualize and use them with the urllib and Opencv libraries, in addition to displaying the images in Tkinter to make a user interface
The image updates correctly but scrolls down as shown in the images
I would like you to help me with the problem and how to anchor it where I want, use the function .place (x = 0, y = 0) in and out of the loop but the image was not updating
°°°IMAGES°°°
starting the program, the image is centered in the Tkinter window, that's fine.
first capture
when the image is refreshed at 500 milliseconds, the image is scrolled down "infinitely", as shown in the following image:
second capture
#Python v3.8.4
import tkinter as *
from PIL import Image, ImageTk
import cv2
import numpy as np
import urllib.request
url='http://192.168.0.24/picture'
delay = 1000
imgtk = [None]
def loopCapture():
imgResponse = urllib.request.urlopen (url)
imgNp =np.array(bytearray(imgResponse.read()),dtype=np.uint8)
image = cv2.imdecode (imgNp, -1)
b,g,r = cv2.split(image)
img = cv2.merge((r,g,b))
im = Image.fromarray(img)
imgtk[0] = ImageTk.PhotoImage(image = im)
capture = Label(root, image = imgtk[0]).pack()
root.after(delay, loopCapture)
root = Tk()
root.geometry("1200x700")
loopCapture()
root.mainloop()
I just needed to learn more about the tkinter library, but if anyone comes across the same question, here is the code:
capture when running the program.
from PIL import Image, ImageTk
import urllib.request
import tkinter as tk
import numpy as np
import cv2
# esp32-cam url
urlCam ='http://192.168.0.24/picture'
panel = None
root = None
def loopCamera():
imgResponse = urllib.request.urlopen (urlCam)
imgNp = np.array(bytearray(imgResponse.read()),dtype=np.uint8)
image = cv2.imdecode (imgNp, -1)
b,g,r = cv2.split(image)
img = cv2.merge((r,g,b))
im = Image.fromarray(img)
imgtk = ImageTk.PhotoImage(image = im)
panel.configure(image = imgtk)
panel.image = imgtk
panel.after(5, loopCamera)
root = tk.Tk()
root.title('car-vision')
root.geometry('1000x600')
panel = tk.Label(root)
panel.pack()
loopCamera()
root.mainloop()

Problems to display Web Scraping values in Tkinter

I am trying to display an image inside a Tkinter window through Web Scraping displaying a message from a certain point on the website that says in Portuguese "Capella Ganhou" or "Procyon Ganhou".
I tried to look in different forums for a solution but I couldn't find any that fixes the error in my situation. I also tested with print to make sure the string exists and is returning its value and also encapsulated it into a variable.
The source code and the error are below .
from tkinter import *
import urllib.request
from bs4 import BeautifulSoup
from IPython.display import Image, display
from PIL import Image, ImageTk
import io
def capella_tg():
resultado_tg = StringVar()
resultado_tg.set(soup.find_all("font")[5].string)
label_resultado_tg = Label(root, textvariable=resultado_tg).pack()
def procyon_tg():
resultado_tg = StringVar()
resultado_tg.set(soup.find_all("font")[4].string[3:])
label_resultado_tg = Label(root, textvariable=resultado_tg).pack()
def img_capella():
raw_data = urllib.request.urlopen("https://i.imgur.com/AHLqtt0.jpg").read()
im = Image.open(io.BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
label1 = Label(root, image=image).pack()
def img_procyon():
raw_data = urllib.request.urlopen("https://i.imgur.com/TQyCnfD.jpg").read()
im = Image.open(io.BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
label1 = Label(root, image=image).pack()
root = Tk()
with urllib.request.urlopen("http://www.cabaleasy.com") as url: page = url.read()
soup = BeautifulSoup(page, "html.parser")
#print(soup.find_all("font")[5].string)
try:
capella_tg()
except:
procyon_tg()
if capella_tg():
img_capella()
elif procyon_tg():
img_procyon()
root.mainloop()
-------ERROR---------
Traceback (most recent call last):
File "C:/Users/LucasDEV/PycharmProjects/LucasDEV/WEB_SCRAPPING/TESTES.py", line 49, in <module>
elif procyon_tg():
File "C:/Users/LucasDEV/PycharmProjects/LucasDEV/WEB_SCRAPPING/TESTES.py", line 17, in procyon_tg
resultado_tg.set(soup.find_all("font")[4].string[3:])
TypeError: 'NoneType' object is not subscriptable
#Dipen Shah That is why I used the try/except structure for. But it's not working and I'm getting the same error. I also tried this way:
def capella_tg():
resultado_tg = StringVar()
try:
resultado_tg.set(soup.find_all("font")[5].string)
label_resultado_tg = Label(root, textvariable=resultado_tg).pack()
except:
pass
i tested just using text and it works:
import urllib.request
from bs4 import BeautifulSoup
with urllib.request.urlopen("http://www.cabaleasy.com") as url: page = url.read()
soup = BeautifulSoup(page, "html.parser")
try:
print(soup.find_all("font")[5].string)
#At this moment, it will not be showing, cuz the status changes every hour
except:
print(soup.find_all("font")[4].string[3:])

Tkinter Button with icon: `_tkinter.TclError: image doesn't exist`

In a script, that I am writing I need a button with a little trash bin as an icon on it. I use the code shown below:
# Python 3.7.1
import tkinter as tk
master = tk.Tk()
photo = tk.PhotoImage(file="bin.png")
icon_button = tk.Button(master, image=photo)
icon_button.pack()
The following error occurs:
_tkinter.TclError: image "pyimage1. doesn't exist
Since I specified bin.png as the image file, I cannot really understand how pyimage1 is specified in the error.
After some debugging, I realized, that the PhotoImage returns the string pyimage1, and therefore gives "pyimage1" as a parameter to the Button, but I still don't know how to fix my issue.
The problem is that Relative path won't be accepted, i.e. if you have your bin.png in C:\ then you should do as-
tk.PhotoImage(file='C:\\bin.png')
Now, if you still want to use relative paths then the following will do-
import tkinter as tk
import os
Win = tk.Tk()
Img = tk.PhotoImage(file=os.path.abspath('bin.png')
tk.Button(Win, image=Img).pack()
Win.mainloop()
Or use this-
import sys, os
def get_path(file):
if not hasattr(sys, ''):
file = os.path.join(os.path.dirname(__file__), file)
return file
else:
file = os.path.join(sys.prefix, file)
return file
It simply just gets the full path of a file.
Now, use the function-
...file=get_path('bin.png'))

Python 3.6 - AttributeError: module 'tkinter' has no attribute 'filedialog'

My function was working perfectly fine few minutes ago. Did not modify the code, just installed PyAudio. I get the error as per subject. It doesn't matter if run it from command line or IDE, same error. Any ideas?
def DataFinder():
#imports and initialize
import pandas as pd
import tkinter as tk
finder = tk.Tk()
finder.withdraw()
__dataFlag = False
#ask user to select a file
__path = tk.filedialog.askopenfilename()
#check the extension to handle reader
#for csv files
if __path.endswith('.csv')==True:
df = pd.read_csv(__path,header=0)
return df
__dataFlag = True
#and for excel files
elif __path.endswith('.xls')==True:
df = pd.read_excel(__path,header=0)
return df
__dataFlag = True
#if a file is not a supported type display message and quit
else:
__dataFlag = False
#check if there is a data to be returned
if __dataFlag==True:
return df
else:
print('The file format is not supported in this version.')
Explicitly import of filedialog can solve the problem.
So, you just need to add this line to your codes:
import tkinter.filedialog
You can find more information at Why tkinter module raises attribute error when run via command line but not when run via IDLE?
the following code didn't work for me:
import tkinter as tk
import tkinter.filedialog
But the following did work:
import tkinter
import tkinter.filedialog
and also this:
import tkinter.filedialog
import tkinter as tk
Hope this helps
Note
As mentioned by Vaidøtas I., you can't import filedialog from tkinter. Because you did not import the original tkinter but an aliased version tk.

Resources