I have an image gallery made in Tkinter that lets you cycle through images. I am trying to set a path to a folder where the images can be stored. When there is no path set the code runs just fine because the images and script are saved in the same place (Pycharm). However, when a path is set this error is thrown raise ValueError(f"bad mode {repr(mode)}")
specifically on this line of code image = PIL.Image.open(mpath, image_list[current], 'r')
. Iv referenced other posts saying that there maybe an interference with the .open()
from the imported PIL module but cant seem to figure it out. Iv tried changing mode from r
to rb
but still get the same error. Any recommendations?
import PIL.Image
from PIL import ImageTk
import tkinter
import tkinter.messagebox
# path to image folder
mpath = "C:/Users/Me/Demo/DemoProject/Pics"
# List of images
image_list = ['2022-07-11_14-35-44.png', '2022-07-11_14-34-08.png']
current = 0
# Cycle through Image List
def move(delta):
global current, image_list, mpath
if not (0 <= current delta < len(image_list)):
tkinter.messagebox.showinfo('End', 'No more image.')
return
current = delta
image = PIL.Image.open(mpath, image_list[current], 'r')
photo = ImageTk.PhotoImage(image)
fileName = image_list[current]
print(fileName)
# Get values from image
def getvalues():
img = fileName
Dimage = PIL.Image.open(mpath, img, 'r')
data = ''
imgdata = iter(Dimage.getdata())
while (True):
pixels = [value for value in imgdata.__next__()[:3]
imgdata.__next__()[:3]
imgdata.__next__()[:3]]
# string of binary data
binstr = ''
for i in pixels[:8]:
if (i % 2 == 0):
binstr = '0'
else:
binstr = '1'
data = chr(int(binstr, 2))
if (pixels[-1] % 2 != 0):
return data
print(getvalues())
label['text'] = (str("Decoded Pic : ") getvalues())
label['image'] = photo
label.photo = photo
mRoot = tkinter.Tk()
label = tkinter.Label(mRoot, compound=tkinter.TOP)
label.pack()
frame = tkinter.Frame(mRoot)
frame.pack()
tkinter.Button(frame, text='Previous picture', command=lambda:
move(-1)).pack(side=tkinter.LEFT)
tkinter.Button(frame, text='Next picture', command=lambda: move( 1)).pack(side=tkinter.LEFT)
tkinter.Button(frame, text='Quit', command=mRoot.quit).pack(side=tkinter.LEFT)
move(0)
mRoot.mainloop()
CodePudding user response:
You are passing multiple params to Image
.
image = PIL.Image.open(mpath '/' image_list[current], 'r')
Concatenate the folder path and image name instead of passing them as separate params.
You can also do something like,
image = PIL.Image.open(os.path.join(mpath, image_list[current]), 'r')
Ofcourse, letting python handle paths is a much better idea.
CodePudding user response:
If you are using windows, you may need to escape your /'s in the given path or use r"directory/here/etc" to tell python it's a raw string and to ignore escape chars.