Tkinter GUI using images from site - python

I am able to get the image to display in the GUI with Tkinter however I can not get this part of the code to work as I am trying to keep it all either under one .py file because it is easier for me to keep everything in one singular window.
The error I am getting is:
Traceback (most recent call last):
File "C:/Users/Holcomb Family/PycharmProjects/webscrapeTKINTER/venv/main4.py", line 32, in <module>
run = MainWin(root)
pil_img = Image.open(my_picture)
AttributeError: type object 'Image' has no attribute 'open'
My code:
import io
from PIL import Image, ImageTk
from tkinter import *
from urllib.request import urlopen
root = tk.Tk()
root.title("New Window")
class MainWin:
def __init__(self, master):
self.master = master
url1 = "https://img.finalfantasyxiv.com/lds/pc/global/images/itemicon/"
url2 = "da/dad2c1875e87e7a7f1d02fce24f0bd0351cdda11.png?n5.45"
pic_url = url1 + url2
my_page = urlopen(pic_url)
my_picture = io.BytesIO(my_page.read())
pil_img = Image.open(my_picture)
tk_img = ImageTk.PhotoImage(pil_img)
self.label = tk.Label(root, image=tk_img)
self.label.pack(padx=5, pady=5)
root = Tk()
run = MainWin(root)
root.mainloop()

Related

How to display a photo on a Tkinter App from a URL using canvas

import io
import base64
try:
# Python2
import Tkinter as tk
from urllib2 import urlopen
except ImportError:
# Python3
import tkinter as tk
from urllib.request import urlopen
def display_poster(image_url, x, y):
# image_url = "http://i46.tinypic.com/r9oh0j.gif"
image_byt = urlopen(image_url).read()
image_b64 = base64.encodebytes(image_byt)
photo = tk.PhotoImage(data=image_b64)
# create a white canvas
cv = tk.Canvas(bg='white')
cv.pack(side='top', fill='both', expand='yes')
# put the image on the canvas with
# create_image(xpos, ypos, image, anchor)
cv.create_image(x, y, image=photo, anchor='nw')
def btn_clicked():
display_poster("http://i46.tinypic.com/r9oh0j.gif", 630, 350)
I have tried the base64 package solution but its not working.
It would be nice if someone could help me out with the pakages i need to import and the function to display the image using Canvas.
use this snippets, its work fine :
import tkinter as tk
import urllib.request
#import base64
import io
from PIL import ImageTk, Image
root = tk.Tk()
root.title("Weather")
link = "http://i46.tinypic.com/r9oh0j.gif"
class WebImage:
def __init__(self, url):
with urllib.request.urlopen(url) as u:
raw_data = u.read()
#self.image = tk.PhotoImage(data=base64.encodebytes(raw_data))
image = Image.open(io.BytesIO(raw_data))
self.image = ImageTk.PhotoImage(image)
def get(self):
return self.image
img = WebImage(link).get()
imagelab = tk.Label(root, image=img)
imagelab.grid(row=0, column=0)
root.mainloop()
Output:

Tkinter image doesn't exist

I am converting a pdf to a bunch of images and displaying it to a tkinter window, but after the pdf conversion I get this error from Tkinter:
Traceback (most recent call last):
File "C:\Users\karee\PycharmProjects\Workspace\pdf_viewer.py", line 25, in <module>
pdf.image_create(END, image=p)
File "C:\Users\karee\AppData\Local\Programs\Python\Python39-32\lib\tkinter\__init__.py", line 3728, in image_create
return self.tk.call(
_tkinter.TclError: image "<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=1700x2200 at 0x5386C10>" doesn't exist
Here is my code:
from tkinter import *
from PIL import Image, ImageTk
from PyPDF2 import PdfFileWriter, PdfFileReader
import pdf2image
root = Tk()
pdf1 = 'pdf_path.pdf'
pil_images = []
inputpdf = PdfFileReader(open(pdf1, "rb"))
pdf_frame = Frame(root).pack(fill=BOTH,expand=1)
scrol_y = Scrollbar(pdf_frame, orient=VERTICAL)
pdf = Text(pdf_frame, yscrollcommand=scrol_y.set, bg="grey")
scrol_y.pack(side=RIGHT, fill=Y)
scrol_y.config(command=pdf.yview)
maxPages = inputpdf.numPages
for page in range(1, maxPages, 100):
pil_images.append(pdf2image.convert_from_path(pdf1, dpi=200, first_page=page,
last_page=min(page + 100 - 1, maxPages), fmt='jpg',
thread_count=1, userpw=None,
use_cropbox=False, strict=False, poppler_path="poppler-21.03.0/Library/bin"))
for photo in pil_images:
for p in photo:
pdf.image_create(END, image=p)
pdf.insert(END, '\n\n')
mainloop()
When I debugged this program, there were PIL images so I'm not sure what's causing these errors. Any help would be greatly appreciated!

Cannot import tkFont

I want to import tkFont but it's not working
from tkinter import *
import tkFont
class BuckysButtons:
def __init__(self,master):
frame = Frame(master)
frame.pack()
helv36 = tkFont.Font(family="Helvetica",size=36,weight="bold")
self.printButton = Button(frame,font=helv36, text ="Print
Message",command = self.printMessage,compound ='top')
self.printButton.pack(side =LEFT)
self.quitButton = Button(frame, text ="quit", command = frame.quit)
self.quitButton.pack(side=LEFT)
def printMessage(self):
print("It worked!")
root = Tk()
b = BuckysButtons(root)
root.mainloop()
i'm getting following error:
Traceback (most recent call last):
File "exercise.py", line 2, in <module>
import tkFont
ModuleNotFoundError: No module named 'tkFont'
It's possible you are trying to run Python 2 code under Python 3, which did some library reorganisation.
If you replace your current import with import tkinter.font as TkFont that should suffice to move you forward.

NameError: name 'tk' is not defined in the object class

I have constructed an application, the source starts like this:
from tkinter import Text
from tkinter import Label
from AESEncDec import *
from MD5Hashing import *
from RSAEncDec import *
color = 'lightblue' #color our background
class Application(Frame):
def __init__(self, root=None):
Frame.__init__(self, root)
self.frame_width = 700
self.frame_height = 400
But last piece of it cannot execute:
#create object TK class
the_window = Tk(className = " Cryptographic")
#create object Application
app = Application(the_window)
#run our Application
app.mainloop()
And it gives the NameError:
Traceback (most recent call last):
File "/home/artur/Documents/MScProject/MSc Project/Task #179276/main_program.py", line 169, in
the_window = Tk(className = " Cryptographic")
NameError: name 'Tk' is not defined
How should I define it properly in this case?
You miss an import statement : from tkinter import Tk
The best way to avoid conflict, is to import the whole module, eventually with an alias to make it short (but don't forget to add tk. everywhere you've called a tkinter widget):
import tkinter as tk
from AESEncDec import *
from MD5Hashing import *
from RSAEncDec import *
color = 'lightblue' #color our background
class Application(tk.Frame):
def __init__(self, root=None):
tk.Frame.__init__(self, root)
self.frame_width = 700
self.frame_height = 400
#create object TK class
the_window = tk.Tk(className = " Cryptographic")
#create object Application
app = Application(the_window)
#run our Application
app.mainloop()

How to make image pop up on a window Tkinter python3

Hey I'm following a tutorial, https://www.youtube.com/watch?v=a1Y5e-aGPQ4 , and I can't get it to work properly. I'm trying to add an image when you press on a menu button:
from tkinter import *
from PIL import *
class Window(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.master = master
self.init_Window()
def init_Window(self):
self.master.title("GUI")
self.pack(fill =BOTH, expand=1)
#quitButton = Button(self, text = "Quit", command = self.client_exit)
#quitButton.place(x=0,y=0)
menu = Menu(self.master)
self.master.config(menu=menu)
file=Menu(menu)
file.add_command(label='Save',command= self.client_exit)
file.add_command(label='Exit',command= self.client_exit)
menu.add_cascade(label='File',menu=file)
edit = Menu(menu)
edit.add_command(label='Show Image', command=self.showImg)
edit.add_command(label='Show Text', command=self.showTxt)
menu.add_cascade(label='Edit',menu=edit)
def showImg(self):
load = Image.open('Pic.png')
render = ImageTk.PhotoImage(load)
img = Label(self, image=render)
img.image = render
img.place(x=0,y=0)
def showTxt(self):
text = Label(self,text='Hey')
text.pack
def client_exit(self):
exit()
root = Tk()
root.geometry("400x300")
app = Window(root)
root.mainloop()
I have tried asking around school, StackOverflow, and YouTube for about 3 days now, and nothing has solved my problem, if you need any more info about it please ask. I am getting the error code:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.5/tkinter/__init__.py", line 1558, in __call__
return self.func(*args)
File "/root/Desktop/Python Programs/Tkinter.py", line 35, in showImg
load = Image.open('pic.png')
AttributeError: type object 'Image' has no attribute 'open'
You use import * so you don't know if you use tkinter.Image or PIL.Image . And this is why you shouldn't use import *
Try
from PIL import Image, ImageTk
Images are a bit tricky to get right, some tips: Keep the image object global, to avoid garbage collection, avoid Attribute Error (by reading the docs).
In this example I don t use PIL and I load a gif image
#!/usr/bin/python
#-*-coding:utf-8 -*
#Python 3
#must have a valid gif file "im.gif" in the same foldeer
from tkinter import *
Window=Tk()
ListePhoto=list()
ListePhoto.append(PhotoImage(file="im.gif"))
def Try():
Window.title('image')
Window.geometry('+0+0')
Window.configure(bg='white')
DisplayImage()
def DisplayImage():
label_frame=LabelFrame(Window, relief='ridge', borderwidth=12, text="AnImage",
font='Arial 16 bold',bg='lightblue',fg='black')
ListeBouttons=list()#Liste Vide pour les Radiobutton(s)
RadioButton = Radiobutton(label_frame,text="notext",image=ListePhoto[0], indicatoron=0)
RadioButton.grid(row=1,column=1)
label_frame.pack(side="left")
if __name__ == '__main__':
Try()

Categories

Resources