我正在尝试制作幻灯片并将所有图像路径存储在 1 个文本文件中,以使主代码更干净, 这是主要代码:
import tkinter as tk
from itertools import cycle
from PIL import ImageTk, Image
images = open('list.txt', 'r').read()
print(images)
photos = cycle(ImageTk.PhotoImage(Image.open(image)) for image in images)
def slideShow():
img = next(photos)
displayCanvas.config(image=img)
root.after(1200, slideShow)
root = tk.Tk()
root.overrideredirect(True)
width = root.winfo_screenwidth()
height = root.winfo_screenwidth()
root.geometry('%dx%d' % (1600, 900))
displayCanvas = tk.Label(root)
displayCanvas.pack()
root.after(1000, lambda: slideShow())
root.mainloop()
这是列表文件的下载,以防它需要重新格式化或其他东西:https://drive.google.com/open?id=17PzCCf6DK9L-8q4ZxVe7bPD1kFlIuZts
我目前在尝试运行代码时收到此错误FileNotFoundError: [Errno 2] No such file or directory: '['
我尝试以不同的方式格式化它,没有任何效果,只是第一个字符是什么,然后"没有这样的文件或目录">
只需替换
images = open('list.txt', 'r').read()
print(images)
跟
images =[]
with open('list.txt', 'r') as f:
lines = f.read().strip('[]')
images = [i.strip("" ") for i in lines.split(',')]
您的文本文件的格式不同。我所做的只是剥离[]
的文本文件,然后用,
分隔符拆分它们,然后删除尾随的空格和"
。
希望这对你:)有所帮助
open('list.txt', 'r').read()
这会将整个文件读取为单个字符串,而不注意该字符串的实际外观。
cycle(ImageTk.PhotoImage(Image.open(image)) for image in images)
这会尝试将images
的每个元素用于Image.open
调用。由于images
是单个字符串(由前一行生成(,因此其元素是该字符串的各个字符(作为 1 个字符的字符串(。因此,'['
是其中的第一个。
似乎您希望将列表的字符串表示形式写入文件,然后通过读取文件自动获取实际的相应列表。这行不通。您需要实际解释文件内容以构建列表。
您不小心创建了JSON
文件,您可以使用模块json
将其转换回 Python 的列表
import json
images = json.loads(open('list.txt').read())
print(images[0])
您正在对文件调用.read()
,这会将所有内容加载到字符串中。
然后,您逐个字符地循环字符串,尝试将字符作为图像打开
如果你的每一行都有名字,那么你想要这个
with open('list.txt', 'r') as f:
images = f.readlines()
print(images)
photos = cycle(ImageTk.PhotoImage(Image.open(image.rstrip())) for image in images)
如果您的文件格式有任何不同,则需要先将其解析为图像文件名列表
1.
import json
with open('../resources/list.txt') as list_file:
list_res = json.load(list_file)
阿拉伯数字。
from ast import literal_eval
with open('../resources/list.txt') as list_file:
list_res = literal_eval(list_file.read())