[英]PIL and tkinter error: TypeError: expected str, bytes or os.PathLike object, not list
I have this code, and the problem is I can't open the images.我有这个代码,问题是我无法打开图像。 I did a random election to open a random image.
我进行了随机选举以打开随机图像。 Thanks!
谢谢!
Code:代码:
import tkinter as tk
from tkinter import *
import random
from PIL import Image
window=Tk()
window.geometry('500x550')
window.resizable(False, False)
f=tk.Frame()
f.config(bg='blue', height='500', width='500')
f.pack()
cat=tk.Button(window, text='Cat')
cat.config()
cat.pack(fill=X)
dog=tk.Button(window, text='Dog')
dog.config()
dog.pack(fill=X)
images=['cat1.jpg', 'cat2.jpg', 'cat3.jpg', 'cube1.jpg', 'cube2.jpg', 'cube3.jpg']
imgimport = open(random.sample(images, 1))
img = PIL.Image.open(imgimport)
img.show()
random.sample()
returns a particular length list of items chosen from the sequence. random.sample()
返回从序列中选择的特定长度的项目列表。 So even random.sample(list, length=1)
returns a list, not the item.所以即使
random.sample(list, length=1)
返回一个列表,而不是项目。 You can use random.sample()[0]
as @Axe also said.正如@Axe 所说,您可以使用
random.sample()[0]
。
random.sample
is used to generate a list. random.sample
用于生成列表。 If you only want to get one,Why don't you just use random.choice(images)
,it will return a random string from list images
.如果你只想得到一个,为什么不直接使用
random.choice(images)
,它会从列表images
中返回一个随机字符串。
You used Image.open
in the end,so there is no necessary to use open
.你最后使用了
Image.open
,所以没有必要使用open
。
And your code in the last can be reduced to最后的代码可以简化为
images=['cat1.jpg', 'cat2.jpg', 'cat3.jpg', 'cube1.jpg', 'cube2.jpg', 'cube3.jpg']
img = Image.open(random.choice(images))
img.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.