问题描述
我想使用 grid()
显示文件夹中的图像.但是当我尝试使用以下代码时,我得到了单个图像迭代的输出.
I want to display the images in the folder using grid()
. But when I tried with the following code, I got the output with single image iterated.
我的代码:
def messageWindow():
win = Toplevel()
path = 'C:UsersHPDesktopdataset'
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()
当我运行这段代码时,5分钟后会弹出一个子窗口,它会显示一个像这样的图像;
When I run this code, after 5 minutes a child window will popup, and it will display a single image like this;
但是如何获取数据集中的所有图像呢?欢迎任何建议.感谢您的支持!
But how to get all the images in the dataset? Any suggestions are welcome. Tkanks for your support!
推荐答案
正如我在评论中所说,您在网格的每一行和每一列中都放置了相同的图像.以下是如何使用内置 divmod()
函数迭代计算每一行的行和列,基于 COLUMNS
的数量,您希望根据 image_count的当前值在每一行中显示代码>:
As I said in a comment, you're putting the same image in every row and column of the grid. Here's how to avoid that using the built-in divmod()
function to iteratively compute the row and column for each one, based on the number of COLUMNS
you want to display in each row based on the current value of image_count
:
def messageWindow():
win = Toplevel()
path = r'C:UsersHPDesktopdataset'
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...
这篇关于如何使用 tkinter 使用网格功能显示不同的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!