Displaying Cards in Python with tkinter [duplicate] - python

I am working on a python program that displays a series of images using Tkinter and ImageTk. I have not been able to display more than a single image. Below is a small complete program that reproduces the error. The program searches the current directly recursively for jpg files, and displays them as the uses presses Enter.
import Tkinter, ImageTk,os, re
def ls_rec(direc):
try:
ls = os.listdir(direc)
except Exception as e:
return
for f in os.listdir(direc):
fpath = os.path.join(direc, f)
if os.path.isfile(fpath):
yield fpath
elif os.path.isdir(fpath):
for f2 in iterate_dir(os.path.join(direc,f)):
yield f2
images = filter(lambda a:re.match('.*\\.jpg$',a),ls_rec(os.getcwd()))
assert(len(images)>10)
top = Tkinter.Tk()
image_label = Tkinter.Label(top)
Label_text = Tkinter.Label(top,text="Below is an image")
img = None
i = 0
def get_next_image(event = None):
global i, img
i+=1
img = ImageTk.PhotoImage(images[i])
label.config(image=img)
label.image = img
top.bind('<Enter>',get_next_image)
label.pack(side='bottom')
Label_text.pack(side='top')
get_next_image()
top.mainloop()
The program fails with the following traceback:
Traceback (most recent call last):
File "/usr/lib/python2.7/pdb.py", line 1314, in main
pdb._runscript(mainpyfile)
File "/usr/lib/python2.7/pdb.py", line 1233, in _runscript
self.run(statement)
File "/usr/lib/python2.7/bdb.py", line 387, in run
exec cmd in globals, locals
File "<string>", line 1, in <module>
File "/home/myuser/Projects/sample_images.py", line 1, in <module>
import Tkinter, ImageTk,os, re
File "/home/myuser/Projects/sample_images.py", line 32, in get_next_image
img = ImageTk.PhotoImage(some_image[1])
File "/usr/lib/python2.7/dist-packages/PIL/ImageTk.py", line 109, in __init__
mode = Image.getmodebase(mode)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 245, in getmodebase
return ImageMode.getmode(mode).basemode
File "/usr/lib/python2.7/dist-packages/PIL/ImageMode.py", line 50, in getmode
return _modes[mode]
KeyError: '/home/myuser/sampleimage.jpg'
Does anyone get the same behavior when running this code? What am I doing wrong?
EDIT: Using korylprince's solution, and a bit of cleaning, the following is a working version of the original code:
import os, re, Tkinter, ImageTk
def ls_rec(direc, filter_fun=lambda a:True):
for (dirname, dirnames, fnames) in os.walk(direc):
for fname in fnames:
if filter_fun(fname):
yield os.path.join(dirname,fname)
top = Tkinter.Tk()
image_label = Tkinter.Label(top)
text_label = Tkinter.Label(top,text="Below is an image")
images = ls_rec(os.getcwd(), lambda a:re.match('.*\\.jpg$',a))
imgL = []
def get_next_image(event = None):
fname = images.next()
print fname
fhandle = open(fname)
img = ImageTk.PhotoImage(file=fhandle)
fhandle.close()
imgL.append(img)
image_label.config(image=img)
top.bind('<Return>',get_next_image)
image_label.pack(side='bottom')
text_label.pack(side='top')
get_next_image()
top.mainloop()
Edit: top.bind('<Enter>'...) actually bound the event of the mouse entering the frame, rather than user pressing Enter key. The correct line is top.bind('<Return>',...).

ImageTk.PhotoImage is not really documented properly.
You should try something like this:
#outside of functions
images = list()
#inside function
global images
with open(images[i]) as f:
img = ImageTk.PhotoImage(file=f)
images.append(img)
The reason for putting the image in the list is so that python will have a reference to it. Otherwise the garbage collector will delete the image object eventually.

Related

Trying to trying to select images from a database and insert them into a Treeview

I am trying to select images from a database with other info and insert them into a Treeview, and this Treevire has to be shown in a notebook,
I have tried the following code:
from PIL import ImageTk, Image
from io import BytesIO
from tkinter import filedialog
from tkinter.filedialog import askopenfile
import sqlite3
class Cardealer():
def __init__(self):
self.root = root
# calling dashboad_checks so its showing the treeview on the root notebook
self.dashboard_checks()
def dashboard_checks(self):
self.con = sqlite3.connect('car dealership.db')
self.cursorObj = self.con.cursor()
self.buying_checks_row = self.cursorObj.execute(
'SELECT checkpic, buyername, carmake, checknum, checkvalue, checkdate FROM cars_selling_checksonly')
self.buying_checks_output = self.cursorObj.fetchall()
self.checkslist_buying_img = []
for record in self.buying_checks_output:
checks_buying_img = ImageTk.PhotoImage(date=record[0])
self.Dashboardcheck_buying_tree.insert("",
END,image=checks_buying_img,values=record[1:])
self.checkslist_buying_img.append(checks_buying_img)
self.con.commit()
def selling_filedialogscheckonepic(self):
global filename, img, images
f_types = [("png", "*.png"), ("jpg", "*.jpg"), ("Allfile", "*.*")]
filename = filedialog.askopenfilename(filetypes=f_types)
img = Image.open(filename)
img = img.resize((700, 270), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
self.selling_checkimagelabel.place(x=20, y=60)
self.selling_check_fob = open(filename, 'rb')
self.selling_check_fob = self.selling_check_fob.read()
self.selling_check_fob = (self.selling_check_fob)
I got the following error:
Traceback (most recent call last):
File "C:\Users\user\Desktop\thecardealer(new version)\main.py", line 3271, in <module>
x = Cardealer()
File "C:\Users\user\Desktop\thecardealer(new version)\main.py", line 70, in __init__
self.dashboard_checks()
File "C:\Users\user\Desktop\thecardealer(new version)\main.py", line 106, in dashboard_checks
checks_buying_img = ImageTk.PhotoImage(date=record[0])
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\PIL\ImageTk.py", line 108, in __init__
mode = Image.getmodebase(mode)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\PIL\Image.py", line 294, in getmodebase
return ImageMode.getmode(mode).basemode
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\PIL\ImageMode.py", line 74, in getmode
return _modes[mode]
KeyError: None
Exception ignored in: <function PhotoImage.__del__ at 0x000001FC7DA30E50>
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\PIL\ImageTk.py", line 118, in __del__
name = self.__photo.name
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
Process finished with exit code 1
I would appreciate any help as I am a new programmer and still learning.

how to resolve the ArgumentError: argument 2: <class 'TypeError'>: wrong type in tkinter askopenfile

I want to make a tkinter gui to convert pdf page into image. I tried this:
root = Tk()
def open_file():
global file
file = askopenfile(mode ='rb', filetypes =[('pdf files', '*.pdf')])
print('Selected:', file)
def pdftoimage():
pdf = wi(filename=file, resolution=300)
pdfimage = pdf.convert("jpeg")
i=1
for img in pdfimage.sequence:
page = wi(image=img)
page.save(filename="file.jpg")
i +=1
label1 = Label(root,text="Select the ")
button1 = Button(root, text="Select File",command=open_file)
button1.place(x=10,y=10)
button2 = Button(root,text="Convert pdf into image",command=pdftoimage)
button2.place(x=10,y=40)
button3 = Button(root,text="Exit",command=root.destroy)
button3.place(x=40,y=70)
root.mainloop()
but it gives the following error:
Traceback (most recent call last):
File "D:\Anaconda\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "<ipython-input-4-be9660d3a6d2>", line 33, in pdftoimage
pdf = wi(filename=file, resolution=300)
File "D:\Anaconda\lib\site-packages\wand\image.py", line 9062, in __init__
self.read(filename=filename)
File "D:\Anaconda\lib\site-packages\wand\image.py", line 9654, in read
r = library.MagickReadImage(self.wand, filename)
ctypes.ArgumentError: argument 2: <class 'TypeError'>: wrong type
As far as i can understand, this is because of the type of file in askopenfile is _io.BufferedReader but wand takes class str type. If i am right about that then how to make wand to access the file from askopenfile function?

Converting Video File(s) to GIF

I want make a converter based on python 3.8
I'm using imageoi API 2.6.1
Here's some of my codes what i think i did it wrong
from tkinter import *
from tkinter import filedialog
import imageio
import os
root = Tk()
ftypes = [('All Files', "*.*"), ('Webm', "*.webm")]
ttl = "Select Files(s)"
dir1 = 'D:/My Pictures/9gag'
root.fileName = filedialog.askopenfilenames(filetypes=ftypes, initialdir=dir1, title=ttl)
lst = list(root.fileName)
def path_leaf(path):
return path.strip('/').strip('\\').split('/')[-1].split('\\')[-1]
print([path_leaf(path) for path in lst])
lst2 = [path_leaf(path) for path in lst]
print(lst)
def gifMaker(inputPath, targetFormat):
outputPath = os.path.splitext(inputPath)[0] + targetFormat
print(f'converting {inputPath} \n to {outputPath}')
reader = imageio.get_reader(inputPath)
fps = reader.get_meta_data()['fps']
writer = imageio.get_writer(outputPath, fps=fps)
for frames in reader:
writer.append_data(frames)
print(f'Frame {frames}')
print('Done!')
writer.close()
for ad in lst2:
gifMaker(ad, '.gif')
And the error are shown like this
Traceback (most recent call last):
File "D:/My Pictures/GIF/GIF.py", line 41, in <module>
gifMaker(ad, '.gif')
File "D:/My Pictures/GIF/GIF.py", line 28, in gifMaker
reader = imageio.get_reader(inputPath)
File "C:\Python\Anaconda3\lib\site-packages\imageio\core\functions.py", line 173, in get_reader
request = Request(uri, "r" + mode, **kwargs)
File "C:\Python\Anaconda3\lib\site-packages\imageio\core\request.py", line 126, in __init__
self._parse_uri(uri)
File "C:\Python\Anaconda3\lib\site-packages\imageio\core\request.py", line 278, in _parse_uri
raise FileNotFoundError("No such file: '%s'" % fn)
FileNotFoundError: No such file: 'D:\My Pictures\GIF\a6VOVL2_460sv.mp4'
So, what am i missing or fault? I don't understand why the error is showing "file is not found". Can someone explain to me in detail, how these lines of error occurred?
There are several possibilities
Maybe you misstyped the path/filename.
Maybe the space in the path is causing trouble.

tcl error when removing/adding pictures to folder in a slide show, python, tkinter, itertools, cycle

I am having some trouble with an small slide show script that I am trying to make. The script runs just fine when the folder of files is not altered, but if i add a picture to the folder I get an tcl error stating that the file cannot be opened or is missing. I am really struggeling to see the issue here and I am hoping that some of you can?
the function where adding a picture to the folder without having to restart it is the main function, so that the slides just change automatically. It will be a slide show of graphs running in our office as an information screen.
See the code and error underneath. Any help is much appritiated!
Code
from itertools import cycle
import os
try:
import Tkinter as tk
except ImportError:
class App(tk.Tk):
def __init__(self,x, y, delay):
print "init running"
tk.Tk.__init__(self)
self.geometry('+{}+{}'.format(x, y))
self.delay = delay
self.image_files = []
self.new_image = []
for path, subdirs, files in os.walk('C:\kitfinder2\pictures'):
for filename in files:
f = filename
self.image_files.append(f)
self.new_image.append(f)
self.pictures = cycle((tk.PhotoImage(file=image), image)
for image in self.image_files)
self.picture_display = tk.Label(self)
self.picture_display.pack()
def UpdateImages(self):
self.new_image = []
for path, subdirs, files in os.walk('C:\kitfinder2\pictures'):
for filename in files:
f = filename
self.new_image.append(f)
if len(self.image_files) != len(self.new_image):
print "Difference!"
self.image_files = []
for path, subdirs, files in os.walk('C:\kitfinder2\pictures'):
for filename in files:
f = filename
self.image_files.append(f)
self.pictures = cycle((tk.PhotoImage(file=image), image)
for image in self.image_files)
print "image updated!:" + str(self.image_files)
self.show_slides()
def show_slides(self):
print self.image_files
'''cycle through the images and show them'''
img_object, img_name = next(self.pictures)
self.picture_display.config(image=img_object)
self.title(img_name)
self.after(self.delay, self.UpdateImages)
def run(self):
self.mainloop()
delay = 3500
x = 100
y = 50
app = App( x, y, delay)
app.UpdateImages()
app.run()
Error message
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
return self.func(*args)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 533, in callit
func(*args)
File "start_stopp.py", line 56, in UpdateImages
self.show_slides()
File "start_stopp.py", line 60, in show_slides
img_object, img_name = next(self.pictures)
File "start_stopp.py", line 53, in <genexpr>
for image in self.image_files)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 3326, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 3282, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
TclError: couldn't open "2.gif": no such file or directory
You're only appending the basename and then trying to open it. e.g. 2.gif. Unfortunately, 2.gif isn't in the current directory -- it's (somewhere) in 'C:\kitfinder2\pictures'
You probably want something like:
self.image_files.append(os.path.join(path, filename))
rather than simply:
self.image_files.append(f)
Brother you can use:
photo = PhotoImage(file = "path_of_file")
you can put litter r before "path_of_file" to override putting douple \
photo = PhotoImage(file=r'F:\Python Programs\Tkinter\2.png')

Displaying images with Tkinter

I am working on a python program that displays a series of images using Tkinter and ImageTk. I have not been able to display more than a single image. Below is a small complete program that reproduces the error. The program searches the current directly recursively for jpg files, and displays them as the uses presses Enter.
import Tkinter, ImageTk,os, re
def ls_rec(direc):
try:
ls = os.listdir(direc)
except Exception as e:
return
for f in os.listdir(direc):
fpath = os.path.join(direc, f)
if os.path.isfile(fpath):
yield fpath
elif os.path.isdir(fpath):
for f2 in iterate_dir(os.path.join(direc,f)):
yield f2
images = filter(lambda a:re.match('.*\\.jpg$',a),ls_rec(os.getcwd()))
assert(len(images)>10)
top = Tkinter.Tk()
image_label = Tkinter.Label(top)
Label_text = Tkinter.Label(top,text="Below is an image")
img = None
i = 0
def get_next_image(event = None):
global i, img
i+=1
img = ImageTk.PhotoImage(images[i])
label.config(image=img)
label.image = img
top.bind('<Enter>',get_next_image)
label.pack(side='bottom')
Label_text.pack(side='top')
get_next_image()
top.mainloop()
The program fails with the following traceback:
Traceback (most recent call last):
File "/usr/lib/python2.7/pdb.py", line 1314, in main
pdb._runscript(mainpyfile)
File "/usr/lib/python2.7/pdb.py", line 1233, in _runscript
self.run(statement)
File "/usr/lib/python2.7/bdb.py", line 387, in run
exec cmd in globals, locals
File "<string>", line 1, in <module>
File "/home/myuser/Projects/sample_images.py", line 1, in <module>
import Tkinter, ImageTk,os, re
File "/home/myuser/Projects/sample_images.py", line 32, in get_next_image
img = ImageTk.PhotoImage(some_image[1])
File "/usr/lib/python2.7/dist-packages/PIL/ImageTk.py", line 109, in __init__
mode = Image.getmodebase(mode)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 245, in getmodebase
return ImageMode.getmode(mode).basemode
File "/usr/lib/python2.7/dist-packages/PIL/ImageMode.py", line 50, in getmode
return _modes[mode]
KeyError: '/home/myuser/sampleimage.jpg'
Does anyone get the same behavior when running this code? What am I doing wrong?
EDIT: Using korylprince's solution, and a bit of cleaning, the following is a working version of the original code:
import os, re, Tkinter, ImageTk
def ls_rec(direc, filter_fun=lambda a:True):
for (dirname, dirnames, fnames) in os.walk(direc):
for fname in fnames:
if filter_fun(fname):
yield os.path.join(dirname,fname)
top = Tkinter.Tk()
image_label = Tkinter.Label(top)
text_label = Tkinter.Label(top,text="Below is an image")
images = ls_rec(os.getcwd(), lambda a:re.match('.*\\.jpg$',a))
imgL = []
def get_next_image(event = None):
fname = images.next()
print fname
fhandle = open(fname)
img = ImageTk.PhotoImage(file=fhandle)
fhandle.close()
imgL.append(img)
image_label.config(image=img)
top.bind('<Return>',get_next_image)
image_label.pack(side='bottom')
text_label.pack(side='top')
get_next_image()
top.mainloop()
Edit: top.bind('<Enter>'...) actually bound the event of the mouse entering the frame, rather than user pressing Enter key. The correct line is top.bind('<Return>',...).
ImageTk.PhotoImage is not really documented properly.
You should try something like this:
#outside of functions
images = list()
#inside function
global images
with open(images[i]) as f:
img = ImageTk.PhotoImage(file=f)
images.append(img)
The reason for putting the image in the list is so that python will have a reference to it. Otherwise the garbage collector will delete the image object eventually.

Categories