var*_*lla 4 python grid label tkinter
我想使用显示文件夹中的图像grid()。但是,当我尝试使用以下代码时,得到的输出带有单张图像。
我的代码:
def messageWindow():
win = Toplevel()
path = 'C:\Users\HP\Desktop\dataset'
for r in range(7):
for c in range(10):
for infile in glob.glob(os.path.join(path,'*.jpg')):
im = Image.open(infile)
resized = im.resize((100, 100),Image.ANTIALIAS)
tkimage = ImageTk.PhotoImage(resized)
myvar=Label(win,image = tkimage)
myvar.image = tkimage
myvar.grid(row=r,column=c)
root = Tk()
button = Button(app, text='Images in DataSet',command = messageWindow)
button.pack(padx = 1, pady = 1,anchor='ne')
button.place( x = 850, y = 60)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
当我运行此代码时,5分钟后将弹出一个子窗口,它将显示一个图像。

但是如何获取数据集中的所有图像?欢迎任何建议。谢谢您的支持!
正如我在评论中说的那样,您将在网格的每一行和每一列中放置相同的图像。这是如何避免使用内置divmod()函数基于COLUMNS要基于当前值在每一行中显示的数量来迭代计算每一行的行和列的方法image_count:
def messageWindow():
win = Toplevel()
path = r'C:\Users\HP\Desktop\dataset'
COLUMNS = 10
image_count = 0
for infile in glob.glob(os.path.join(path, '*.jpg')):
image_count += 1
r, c = divmod(image_count-1, COLUMNS)
im = Image.open(infile)
resized = im.resize((100, 100), Image.ANTIALIAS)
tkimage = ImageTk.PhotoImage(resized)
myvar = Label(win, image=tkimage)
myvar.image = tkimage
myvar.grid(row=r, column=c)
win.mainloop() # Not sure if you need this, too, or not...
Run Code Online (Sandbox Code Playgroud)