我正在尝试循环文件夹中的随机图像。到目前为止,我可以循环图像,但每次我尝试使用random.choice时,我都会出错。下面是我的代码没有随机导入
import tkinter as tk
import glob
root = tk.Tk()
from PIL import ImageTk, Image
root.geometry('600x600')
pics = glob.glob("./imgs/*.png")
photos = [random.choice(tk.PhotoImage(file=x)) for x in pics]
label = tk.Label(root)
label.photos = photos
label.counter = 0
def changeimage():
label['image'] = label.photos[label.counter%len(label.photos)]
label.after(8000, changeimage)
label.counter += 1
label.pack(padx=10, pady=10)
changeimage()
root.mainloop()
错误
Traceback (most recent call last):
File "/Users/ad/Documents/Python/Project_tkinter/test1.py", line 148, in <module>
photos = [random.choice(tk.PhotoImage(file=x)) for x in pics]
File "/Users/ad/Documents/Python/Project_tkinter/test1.py", line 148, in <listcomp>
photos = [random.choice(tk.PhotoImage(file=x)) for x in pics]
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/random.py", line 288, in choice
i = self._randbelow(len(seq))
TypeError: object of type 'PhotoImage' has no len()
您必须首先创建照片列表,然后选择单个照片
list_of_photos = [tk.PhotoImage(file=x) for x in pics]
single_photo = random.choice(list_of_photos)
但是如果你想循环这个列表,那么你需要random.shuffle()
来改变列表上的顺序,使文件按随机顺序排列。
list_of_photos = [tk.PhotoImage(file=x) for x in pics]
random.shuffle(list_of_photos)
random.shuffle()
更改原始列表,不返回新列表。