'File not found' while importing gif for Tkinter.Label - python

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:

Related

Unable to use JPEG images in tkinter

My code:
from tkinter import *
mah_root = Tk()
mah_root.geometry("900x900")
photo = PhotoImage(file="2.jpeg")
varun_label = Label(image=photo)
varun_label.pack()
mah_root.mainloop()
Error:
Traceback (most recent call last):
File "/Users/dm19/Desktop/GUI/tut5.py", line 7, in <module>
photo = PhotoImage(file="2.jpeg")
File "/Users/dm19/opt/anaconda3/lib/python3.9/tkinter/__init__.py", line 4064, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "/Users/dm19/opt/anaconda3/lib/python3.9/tkinter/__init__.py", line 4009, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "2.jpeg"

Python error - Traceback (most recent call last)

I entered this code. I entered the example alike in the book where I could study Python.
from turtle import Screen, Turtle
import random
screen=Screen()
image1="C:\\rabbit.gif"
image2="C:\\turtle.gif"
screen.addshape(image1)
screen.addshape(image2)
t1=turtle.Turtle()
t1.shape(image1)
t1.pensize(5)
t1.penup()
t1.goto(-300, 0)
t2=turtle.Turtle()
t2.shape(image2)
t2.pensize(5)
t2.penup()
t2.goto(-300, -200)
t1.pendown()
t2.pendown()
t1.speed(1)
t2.speed(1)
for i in range(100):
d1=random.randint(1, 60)
t1.forward(d1)
d2=random.randint(1, 60)
t2.forward(d2)
I entered the code correctly, but there was an error.
Here is the code of the error.
Traceback (most recent call last):
File "D:/대학/파이썬프로그래밍기초/파이썬_과제(2018)/fd.py", line 7, in <module>
screen.addshape(image1)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 1134, in register_shape
shape = Shape("image", self._image(name))
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 478, in _image
return TK.PhotoImage(file=filename, master=self.cv)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 4093, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 4038, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "C:\rabbit.gif"
I tried to find a way to correct the error, but I couldn't find it. I wonder where this code is wrong.

ImageTk.Photoimage not working as expected

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))

No idea what's causing this error "AttributeError: '_io.TextIOWrapper' object has no attribute 'tk'"

The code keeps throwing the AttributeError: '_io.TextIOWrapper' object has no attribute 'tk' and I can't figure out what's causing it, I looked at other posts and nothing has helped me to get an idea of what's going on.
Below is the code that's causing it.
def showhwk(lesson, popup):
lesson = lesson.replace("/","")
popup.withdraw()
show = Tk()
show.title("Homework marks for "+lesson)
show.geometry("+{}+{}".format(positionRight, positionDown))
try:
with open(lesson+".csv", "r") as show:
csvlist = list(csv.reader(show))
for label in range (len(csvlist)):
Label(show, text = "hello").grid(row = label)
except FileNotFoundError:
show.title("Error!")
error = Label(show, text = "Homework file was not found")
error.grid(row = 0)
def goback3(show):
popup.deiconify()
show.withdraw()
returnbut = Button(show, text = "Return", bg = "#79838e", command = lambda: goback3(show)).grid(row = 40, sticky = W+E)
This is the full error:
Traceback (most recent call last):
File "C:\Users\Olek\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "D:\Desktop\Folders\Python\Coursework\coursework code main.py", line 242, in <lambda>
show = Button(popup, text = "Show homework marks", bg = "green", command = lambda: showhwk(lesson, popup))
File "D:\Desktop\Folders\Python\Coursework\coursework code main.py", line 278, in showhwk
Label(show, text = "hello").grid(row = label)
File "C:\Users\Olek\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 3143, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Users\Olek\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 2561, in __init__
BaseWidget._setup(self, master, cnf)
File "C:\Users\Olek\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 2530, in _setup
self.tk = master.tk
AttributeError: '_io.TextIOWrapper' object has no attribute 'tk'
You first define show like this:
show = Tk()
Later, you redefine show to be an open file handle with this statement:
with open(lesson+".csv", "r") as show:
Then, you try to use show as the master for a widget here:
Label(show, text = "hello").grid(row = label)
Because show is no longer a widget, it can't be used as the master for another widget. And that is why you get a tkinter error.

Creating multiple variables / strings within loops in Python

I'm trying to create a program that, well, looks something like this:
self.b1 = Checkbutton(self, variable=self.b1v, text="1.")
self.b1.grid()
self.b2v = IntVar()
self.b2 = Checkbutton(self, variable=self.b2v, text="2.")
self.b2.grid()
self.b3v = IntVar()
self.b3 = Checkbutton(self, variable=self.b3v, text="3.")
self.b3.grid()
self.b4v = IntVar()
Well, kinda like that, just... 30+ times. There has GOT to be a better way to do this. However, I have no idea how to do this in a loop. I imagine it would look something like this:
while i <= 32:
n = "self.b" + str(i) + "v = IntVar() \n"
n += "self.b" + str(i) + " = Checkbutton(self, variable=self.b" + str(i) + "v) \n"
n += "self.b" + str(i) + ".grid()\n"
exec(n)
...Or something like that... But that throws an error:
Traceback (most recent call last):
File "/Users/jonahswersey/Documents/toggle flags.py", line 126, in <module>
app = Application()
File "/Users/jonahswersey/Documents/toggle flags.py", line 93, in __init__
self.createWidgets()
File "/Users/jonahswersey/Documents/toggle flags.py", line 117, in createWidgets
exec(m)
File "<string>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 2337, in __init__
Widget.__init__(self, master, 'checkbutton', cnf, kw)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1923, in __init__
BaseWidget._setup(self, master, cnf)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1903, in _setup
if cnf.has_key('name'):
AttributeError: IntVar instance has no attribute 'has_key'
...whereas just manually entering them doesn't. Anyone have any advice for me?
Something like this?
num_buttons = 3
self.b_vars = [IntVar() for i in range(num_buttons)]
self.b = [CheckButton(self, variable=self.b_vars[i], text="%d." % (i + 1)) for i in range(num_buttons)]
for button in self.b:
button.grid()
You're looking for setattr().

Categories

Resources