用滚动条在Tkinter中显示多个图像

2024-04-24 05:28:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我想设计一个小部件,在一列中显示多个固定大小(300x300)的图像。为此,我创建了一个大小为300x800的文本小部件,然后在其中添加了图像标签。我在下面的示例中添加了4个图像。由于堆叠图像的总垂直尺寸更大,它正在扩展文本小部件的大小,甚至不适合屏幕。我希望所有的图像都留在文本小部件内,而不展开它,并添加一个滚动条到文本小部件,这样我就可以滚动并看到所有的图像。在下面的代码中,我可以添加滚动条,但它不起作用。在

from Tkinter import *
import ttk
from PIL import *
from PIL import Image
import os
root = Tk();

text = Text(root, width = 300, height=300)
text.grid(row=0, column=0)
text.grid_propagate(False)


class ImageLabel:
    def __init__(self, master, img_file):        
        label = Label(master)
        label.img = PhotoImage(file=img_file)
        label.config(image=label.img)
        label.pack(side="bottom")

## Adding images to text widget
width = 300
src = "./"
my_item_id = 770353540339
count = 0;
file_name = str(my_item_id)+'_'+str(count)+'.jpeg';
full_file_name = os.path.join(src, file_name)

imagelabels = []
while os.path.isfile(full_file_name):
    im = Image.open(full_file_name)
    height = width*im.size[1]/im.size[0]
    im.thumbnail((width, height), Image.ANTIALIAS)
    im.save(str(count),'gif')
    imagelabels.append(ImageLabel(text, str(count)))
    count = count+1;
    file_name = str(my_item_id)+'_'+str(count)+'.jpeg';
    full_file_name = os.path.join(src, file_name)
    print(count)

## Adding scrollbar
scrollbar = Scrollbar(root, orient=VERTICAL, command=text.yview)
scrollbar.grid(row=0,column=1, sticky='ns')
text.config(yscrollcommand=scrollbar.set)

root.mainloop()

Tags: textname图像文本importimgos部件
1条回答
网友
1楼 · 发布于 2024-04-24 05:28:25

如果使用文本小部件来包含图像,则必须使用image_create或{}方法,而不是使用pack将图像放入小部件中。您还需要在每个图像后面插入一个换行符以使它们垂直堆叠。在

相关问题 更多 >