首页 > 解决方案 > 如何在具有功能的tkinter中显示多张图片?

问题描述

我想在我的 gui 应用程序中显示许多图片。但是根据这里我需要保存这些图片作为我班级的参考。但我很困惑我应该如何处理很多图片?

这不会在打开的窗口上显示任何图像

from tkinter import *
import tkinter
import os 

from PIL import Image, ImageTk

CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) + "/"
class GUI():

    def __init__(self,file_list):
        self.file_list = file_list
        self.root=Tk()
        self.canvas = Canvas(self.root, width=480, height=800)
        self.canvas.pack()

    def image_opener(self, filename):
        opened_image = Image.open(CURRENT_DIR + "images/gui/" + filename)
        photo_image = ImageTk.PhotoImage(opened_image)
        return photo_image

    def show_image1(self):
        img = self.image_opener(files["img1"])
        self.canvas.create_image(0, 0, image=img, anchor = NW, state = NORMAL)

    def show_image2(self):  
        img = self.image_opener(files["img2"])
        self.canvas.create_image(0, 0, image=img, anchor = NW, state = NORMAL)

    def show_screens(self):
        self.show_image1()
        self.show_image2()
        self.root.mainloop()



files = {
    "img1":"image1.png",
    "img2":"image2.png",
    "img3":"image3.png",
    "img4":"image4.png"
        }

gui = GUI(files)
gui.show_screens()

当我把它改成这个时,它会在窗口中显示图片,但是有没有什么优雅的方法可以处理很多图片(可能是 75 张左右)?

from tkinter import *
import tkinter
import os 

from PIL import Image, ImageTk

CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) + "/"
class GUI():

    def __init__(self,file_list):
        self.file_list = file_list
        self.root=Tk()
        self.canvas = Canvas(self.root, width=480, height=800)
        self.canvas.pack()
        self.opened_image1 = Image.open(CURRENT_DIR + "images/gui/image1")
        self.photo_image1 = ImageTk.PhotoImage(self.opened_image1)

        self.opened_image2 = Image.open(CURRENT_DIR + "images/gui/image2")
        self.photo_image2 = ImageTk.PhotoImage(self.opened_image2)


    def show_image1(self):
        self.canvas.create_image(0, 0, image=self.photo_image1, anchor = NW, state = NORMAL)

    def show_image2(self):  
        self.canvas.create_image(0, 0, image=self.photo_image2, anchor = NW, state = NORMAL)

    def show_screens(self):
        self.show_image1()
        self.show_image2()
        self.root.mainloop()

files = {
    "img1":"image1.png",
    "img2":"image2.png",
    "img3":"image3.png",
    "img4":"image4.png"
        }

gui = GUI(files)
gui.show_screens()

标签: python-3.xtkinter

解决方案


推荐阅读