试图在TKinter中加载图像,但是在空白处应该有什么主意?

时间:2019-03-17 16:30:13

标签: python image tkinter scrollbar python-imaging-library

我只能在底部得到一张照片,但是在垂直塔中应该有10张照片,有什么想法吗?还想知道tkinter scrollbar命令是否可以在其中包含图像,如果没有其他方法可以为标签添加滚动条呢?

def show_data(self):
    print('------------------------------------------------------------------------')
    print('data OK')
    for i in range(10):
        self.image = Image.open(self.data[i][7] + '.jpg')
        self.photo = ImageTk.PhotoImage(self.image)
        #result0 = Label(self.frame, text=self.data[i][0])
        #result0.grid(row=i+3, column=1, sticky=W)
        #result1 = Label(self.frame, text=self.data[i][1])
        #result1.grid(row=i+3, column=2, sticky=W)
        #result2 = Label(self.frame, text=self.data[i][2])
        #result2.grid(row=i+3, column=3, sticky=W)
        #result3 = Label(self.frame, text=self.data[i][3])
        #result3.grid(row=i+3, column=4, sticky=W)
        #result4 = Label(self.frame, text=self.data[i][4])
        #result4.grid(row=i+3, column=5, sticky=W)
        #result5 = Label(self.frame, text=self.data[i][5])
        #result5.grid(row=i+3, column=6, sticky=W)
        #result6 = Label(self.frame, text=self.data[i][6])
        #result6.grid(row=i+3, column=7, sticky=W)
        result7 = Label(self.frame, image=self.photo)
        result7.grid(row=i + 3, column=8, sticky=W)

1 个答案:

答案 0 :(得分:0)

为了防止标签中使用的图像被破坏,您需要保留对图像的引用:

def show_data(self):
    print('------------------------------------------------------------------------')
    print('data OK')
    for i in range(10):
        photo = ImageTk.PhotoImage(file=self.data[i][7]+'.jpg')
        result7 = Label(self.frame, image=photo)
        result7.image = photo # keep a reference of the image
        result7.grid(row=i + 3, column=8, sticky=W)

要在框架内具有用于标签的滚动条,最常见的方法是将框架放入画布中,然后创建一个滚动条以滚动画布的视图区域:

# create a canvas and put it as the left side of window
canvas = Canvas(self.master, width=200, height=600) # assume self.master is Tk()
canvas.pack(side='left')
# create an vertical scrollbar and put it at the right side of window
scrollbar = Scrollbar(self.master, orient='vertical', command=canvas.yview)
scrollbar.pack(side='right', fill='y')
# configure the scrollbar to scroll the canvas in vertical direction
canvas.configure(yscrollcommand=scrollbar.set)
# create the frame as child of canvas to hold the labels
self.frame = Frame(canvas)
canvas.create_window((0,0), window=self.frame, anchor='nw')
# make sure to update the scrolling region if the frame is resized
self.frame.bind('<Configure>', lambda e: canvas.configure(scrollregion=canvas.bbox('all')))