how to display different images using grid function using tkinter?(如何使用 tkinter 使用网格功能显示不同的图像?)
问题描述
我想使用 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 使用网格功能显示不同的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 tkinter 使用网格功能显示不同的图像?
基础教程推荐
- 尝试制作WhatsApp机器人 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
