from tkinter import *
from glob import glob
import demoCheck
import random
import quitter
from PIL import ImageTk
gifdir = 'd:/Python/Jupyter/Programming Python/Chap 8 - GUI/pic/'
class buttonpics(Frame):
def __init__(self, parent=None, dir='./gifs/', **kwargs):
Frame.__init__(self, parent, **kwargs)
self.pack()
self.lbl = Label(self, text='None', bg='blue', fg='red')
self.lbl.pack(fill=BOTH)
self.btn = Button(self, text='Press me', bg='white', command=self.draw)
self.btn.pack()
self.quitter = quitter.Quitter(self)
self.quitter.pack(anchor=S)
self.files = glob(dir+'*.jpg')
self.images = [(file, ImageTk.PhotoImage(file=file))
for file in self.files]
def draw(self):
name, photo = random.choice(self.images)
self.btn.config(image=photo)
self.lbl.config(text=name)
buttonpics(dir=gifdir).mainloop()
The codes are trying to load jpg formatted pictures to Tkinter through Pillow's ImageTk module. However, the system generated the following error:
> Traceback (most recent call last): File
> "d:/Python/Jupyter/Programming Python/Chap 8 -
> GUI/buttonpics-func.py", line 31, in <module>
> buttonpics(dir=gifdir).mainloop() File "d:/Python/Jupyter/Programming Python/Chap 8 -
> GUI/buttonpics-func.py", line 22, in __init__
> self.images = [(file, ImageTk.PhotoImage(file=file)) File "d:/Python/Jupyter/Programming Python/Chap 8 -
> GUI/buttonpics-func.py", line 22, in <listcomp>
> self.images = [(file, ImageTk.PhotoImage(file=file)) File "C:\ProgramData\Anaconda3\lib\site-packages\PIL\ImageTk.py", line 89,
> in __init__
> image = _get_image_from_kw(kw) File "C:\ProgramData\Anaconda3\lib\site-packages\PIL\ImageTk.py", line 58,
> in _get_image_from_kw
> return Image.open(source) File "C:\ProgramData\Anaconda3\lib\site-packages\PIL\Image.py", line 2930,
> in open
> raise UnidentifiedImageError( PIL.UnidentifiedImageError: cannot identify image file 'd:/Python/Jupyter/Programming Python/Chap 8 -
> GUI/pic\\IMG_4147.jpg' Exception ignored in: <function
> PhotoImage.__del__ at 0x00000226CF6CFD30> Traceback (most recent call
> last): File
> "C:\ProgramData\Anaconda3\lib\site-packages\PIL\ImageTk.py", line 118,
> in __del__
> name = self.__photo.name AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
If the extension is changed to png, the program can be run smoothly. Does this result from a compatibility issue with jpg format or there are some other reasons? Thank you for the help!
Related
this is my code:
self.msg_entry = Entry(bottom_label, bg="#2C3E50", fg=TEXT_COLOR, font=FONT)
self.msg_entry.place(relwidth=0.74, relheight=0.06, rely=0.008, relx=0.011)
self.msg_entry.focus()
self.msg_entry.bind("<Return>", self._on_enter_pressed)
def _on_enter_pressed(self, event):
msg = self.msg_entry.get()
self._insert_message(msg, "You")
on hovering on on_enter_pressed function, it's showing function is not accessed and I'm getting the following error:
Traceback (most recent call last):
File "GUI.py", line 91, in <module>
app = ChatApplication()
File "GUI.py", line 15, in __init__
self._setup_main_window()
File "GUI.py", line 76, in _setup_main_window
self.msg_entry.bind("<Return>", self._on_enter_pressed)
AttributeError: 'ChatApplication' object has no attribute '_on_enter_pressed'
(I'm using tkinter in python to implement GUI.)
How can I solve this?
You have wrong indentations - _on_enter_pressed has to be outside __init__
def __init__(self):
# ... code ..
self.msg_entry = Entry(bottom_label, bg="#2C3E50", fg=TEXT_COLOR, font=FONT)
self.msg_entry.place(relwidth=0.74, relheight=0.06, rely=0.008, relx=0.011)
self.msg_entry.focus()
self.msg_entry.bind("<Return>", self._on_enter_pressed)
# outside `__init__`
def _on_enter_pressed(self, event):
msg = self.msg_entry.get()
self._insert_message(msg, "You")
I want to make the user open a file using askopenfile() and assign the image to a variable
code:
from tkinter import *
from tkinter import filedialog
from PIL import ImageTk, Image
root = Tk()
root.title("Forms")
def new_window():
root.filename = filedialog.askopenfilename(title="Select a file", filetypes=[("Png Files", "*.png")])
print(root.filename)
img = ImageTk.PhotoImage(open(root.filename))
btn = Button(text="Click here to open file .", command=new_window).pack()
root.mainloop()
But i get an error.
The output is:
C:\Users\Imtiaz\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/Imtiaz/PycharmProjects/pythonProject/mbox.py
C:/Users/Imtiaz/Pictures/Roblox/RobloxScreenShot20201102_204504924.png
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Imtiaz\pyver\py390\lib\tkinter\__init__.py", line 1885, in __call__
return self.func(*args)
File "C:\Users\Imtiaz\PycharmProjects\pythonProject\mbox.py", line 11, in new_window
img = ImageTk.PhotoImage(open(root.filename))
File "C:\Users\Imtiaz\PycharmProjects\pythonProject\venv\lib\site-packages\PIL\ImageTk.py", line 108, in __init__
mode = Image.getmodebase(mode)
File "C:\Users\Imtiaz\PycharmProjects\pythonProject\venv\lib\site-packages\PIL\Image.py", line 300, in getmodebase
return ImageMode.getmode(mode).basemode
File "C:\Users\Imtiaz\PycharmProjects\pythonProject\venv\lib\site-packages\PIL\ImageMode.py", line 64, in getmode
return _modes[mode]
KeyError: <_io.TextIOWrapper name='C:/Users/Imtiaz/Pictures/Roblox/RobloxScreenShot20201102_204504924.png' mode='r' encoding='cp1252'>
Answer: Thanks to acw1668 I got what the problem was.
error was in:
img = ImageTk.PhotoImage(open(root.filename))
it is supposed to be:
Either ImageTk.PhotoImage(file=root.filename) or ImageTk.PhotoImage(Image.open(root.filename))
I'm creating a bot to automate the label making process. i encountered this problem while trying to save (append) multiple images to a pdf. This issue only happens when I'm using a large no. of images and the program works fine if I'm using a few image.
I want to fix this program so that it can process unlimited no. of images and append it to a single pdf file.
from PIL import Image, ImageDraw, ImageFont
import textwrap
import pandas
import datetime
import numpy
import os
from tkinter import filedialog
from tqdm import tqdm_gui
datenow = datetime.datetime.now()
pdate = datenow.strftime("%d-%m-%y")
y = 0
excel = filedialog.askopenfilename(initialdir="/", title="Select A File", filetypes=(("Excel File", "*.xlsx"),("all files", "*.*")))
save_dir = filedialog.askdirectory()
imlist = []
df = pandas.read_excel(excel)
for data in (df.values):
name, no = data
x = 0
while x<no:
x = x+1
y = y+1
LH = len(name)
if LH < 32:
W = 70
Lng = 16
if LH > 32:
W = 53
Lng = 22
name = name.upper()
para = textwrap.wrap(name, width=Lng)
MAX_W, MAX_H = 800, 592
im = Image.open('TFC.jpg')
draw = ImageDraw.Draw(im)
font = ImageFont.truetype('OpenSans-ExtraBold.ttf', W)
current_h, pad = 155, -5
for line in para:
w, h = draw.textsize(line, font=font)
draw.text(((MAX_W - w) / 2, current_h), line, font=font)
current_h += h + pad
imlist.append(im)
im.save(f'{save_dir}/{pdate}{" TF "}{y}.pdf' , save_all=True, append_images=imlist)
os.startfile(save_dir)
The error which I'm getting:
"C:\Users\RAJA MONSINGH\PycharmProjects\Fuzzy\venv\Scripts\python.exe" "C:/Users/RAJA MONSINGH/PycharmProjects/Lable/lable3.py"
Traceback (most recent call last):
File "C:\Users\RAJA MONSINGH\AppData\Roaming\Python\Python38\site-packages\PIL\ImageDraw.py", line 465, in Draw
return im.getdraw(mode)
AttributeError: 'JpegImageFile' object has no attribute 'getdraw'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/RAJA MONSINGH/PycharmProjects/Lable/lable3.py", line 34, in <module>
draw = ImageDraw.Draw(im)
File "C:\Users\RAJA MONSINGH\AppData\Roaming\Python\Python38\site-packages\PIL\ImageDraw.py", line 467, in Draw
return ImageDraw(im, mode)
File "C:\Users\RAJA MONSINGH\AppData\Roaming\Python\Python38\site-packages\PIL\ImageDraw.py", line 59, in __init__
im.load()
File "C:\Users\RAJA MONSINGH\AppData\Roaming\Python\Python38\site-packages\PIL\ImageFile.py", line 233, in load
s = read(self.decodermaxblock)
File "C:\Users\RAJA MONSINGH\AppData\Roaming\Python\Python38\site-packages\PIL\JpegImagePlugin.py", line 394, in load_read
s = self.fp.read(read_bytes)
MemoryError
Process finished with exit code 1
Files needed to run the program:
https://drive.google.com/file/d/1rS-auW0MHmdjoPlNET71isL8AyEPPyGT/view?usp=sharing
I am trying to get Turtle-graphics to display a background image.
Here's my code:
import turtle
from turtle import *
from appJar import gui
...
turtle.setup(900,700) #windowsize
Ian = turtle.Turtle()
Ian.hideturtle()
Ian.screen.title("Arp Convertor")
Ian.screen.bgcolor("#4a4a54")
Ian.screen.bgpic('Backwslots2.gif')
Ian.speed(0)
Ian.penup() #dont draw
Ian.goto(-430,250) #where we'll start drawing
My image is the right size, exactly 900x700 in the current dir (same as my .py file). But the bgpic() line is giving me these errors.
> Exception in Tkinter callback Traceback (most recent call last):
> File
> "C:\Users\Ian\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py",
> line 1705, in __call__
> return self.func(*args) File "D:\Midipy\appJar\appjar.py", line 3574, in <lambda>
> return lambda *args: funcName(param) File "midipy.py", line 21, in openthefile
> convertthefile(btn) File "midipy.py", line 141, in convertthefile
> Ian.screen.bgpic('Backwslots2.gif') File "C:\Users\Ian\AppData\Local\Programs\Python\Python37-32\lib\turtle.py",
> line 1482, in bgpic
> self._setbgpic(self._bgpic, self._bgpics[picname]) File "C:\Users\Ian\AppData\Local\Programs\Python\Python37-32\lib\turtle.py",
> line 738, in _setbgpic
> self.cv.itemconfig(item, image=image)
I'm trying to import gif into a Tkinter.Label. I'm getting a file does not exist error. I have double checked the path and file name.
Below is the error message I get.
Traceback (most recent call last):
File "C:\Users\sachin\Desktop\Project California.py", line 39, in <module>
if __name__=='__main__': main()
File "C:\Users\sachin\Desktop\Project California.py", line 35, in main
feedback = Feedback(root)
File "C:\Users\sachin\Desktop\Project California.py", line 11, in __init__
self.logo = PhotoImage(file= "C:\\Users\\sachin\\Desktop\\signature.gif")
File "C:\Users\sachin\AppData\Local\Programs\Python\Python36
\lib\tkinter\__init__.py", line 3542, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "C:\Users\sachin\Desktop\signature.gif": no
such file or directory
Here is the code I used.
def __init__(self,master):
self.frame_header = ttk.Frame(master)
self.logo = PhotoImage(file= "C:\\Users\\sachin\\Desktop\\signature.gif")
ttk.Label(self.frame_header, image = self.logo)
I'm a noob in python programming. Apologies if the questions is too trivial.
I get the same error and I'm sure the path is right as well. In fact, it seems to find the file every other time it tries, with very similar code.
for r in range(0,5):
for c in range(1,4):
fn = file_name(c)
try:
photo = tk.PhotoImage(fn)
tk.Button(C, image = photo, width = "16", height = "16").grid(row = r,column = c)
except Exception as exception: