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))
Related
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!
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.
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:
Hello!
I a trying to make a subprocess.call() to change the current drive to the C: But it gives me a WindowsError saying that the access is denied. This is the full Error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1541, in __call__
return self.func(*args)
File "C:\Snake\snake.py", line 18, in open_file
call("C:")
File "C:\Python27\lib\subprocess.py", line 168, in call
return Popen(*popenargs, **kwargs).wait()
File "C:\Python27\lib\subprocess.py", line 390, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 640, in _execute_child
startupinfo)
WindowsError: [Error 5] Access is denied
This is my code:
from tkinter import *
from tkinter import filedialog
from subprocess import *
import shutil
root = Tk()
root.title("Snake converter")
def open_file():
filename = filedialog.askopenfilename(filetypes = (("Snake files", "*.sim"),("Python Files", "*.py"),("All files", "*.*")))
filenametmp = filename + ".tmp"
print filename + " is being compiled. Please wait..."
tf = open(filenametmp, "a")
f = open(filename, "r")
filecontents = f.read()
tf.write("from simincmodule import *" + "\n")
tf.write(filecontents)
call("C:")
call("cd C:\Snake\info\Scripts")
f.close()
tf.close()
print "Done compiling " + filename + ". Find the file under /dist/[filename]/[filename].exe"
openbutton = Button(root, text = "Open", width = 10, command = open_file)
openbutton.pack()
root.mainloop()
Any help that is given, even a suggestion, will be appreciated.
Thanks in advance!
Code:
import tkinter
window = tkinter.Tk()
c = tkinter.Canvas(window, height=400, width=600, bg='green')
mid_x = 600 / 2
mid_y = 400 / 2
window.geometry("600x400")
window.title("window")
def ship_control(event):
pass
c.bind_all('<KeyPress-a>', ship_control)
def start():
global ship
rock_speed = 10
ship = c.create_oval(mid_x, mid_y, mid_x + 20, mid_y + 20, fill='red', outline='orange')
button_start = tkinter.Button(window, text='play', command=start)
button_start.pack()
c.pack()
Error:
>>>
>>> Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\Python 3.5\lib\idlelib\run.py", line 121, in main
seq, request = rpc.request_queue.get(block=True, timeout=0.05)
File "C:\Program Files\Python 3.5\lib\queue.py", line 172, in get
raise Empty
queue.Empty
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: '??'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Program Files\Python 3.5\lib\tkinter\__init__.py", line 1534, in __call__
args = self.subst(*args)
File "C:\Program Files\Python 3.5\lib\tkinter\__init__.py", line 1252, in _substitute
e.num = getint_event(b)
File "C:\Program Files\Python 3.5\lib\tkinter\__init__.py", line 1231, in getint_event
return int(s)
SystemError: result with error in PyObject_Call
How to reproduce:
Open the program, press play then press a.
I have no idea what could be wrong altough I have tried searching on google.
I tried adding prints but they don't get executed.
Does anyone know why I get the error?
The problem was that I was using 3.5 instead of 3.4. Switching versions worked.