如何将Tkinter应用放入一个类中

1 投票
1 回答
707 浏览
提问于 2025-04-19 19:08

我一直在尝试弄明白如何使用类,但每个人用的方式都不一样,这让我感到很困惑。

我想把两张图片放进一个类里,但我不知道该怎么做。还有一个问题是,我想把想要删除的东西放到一个列表里,这样就可以一次性发送给函数去删除这些图片,而不是一个一个地处理。

如果有人能帮我解释一下怎么做这些事情,或者给我举个例子(我最喜欢通过例子学习,但之前的例子让我感到困惑,因为它们和我的情况不太一样)。

import sys
from tkinter import *
from PIL import Image, ImageTk

SWH = Tk()
SWH.geometry("1024x950+130+0")
SWH.title("ServiceWhiz.")
#_#GlobalFunction#_
#ClearAllWidgets
def removewidgets(A, B):
    A.destroy()
    B.destroy()
    return;
#_#LoadingPage#_

class SWLoad:
    def __init__(self, master):


load = Image.open("Logo.png")
render = ImageTk.PhotoImage(load)
img = Label(SWH,image=render)
img.image = render  
img.place(x=458,y=250)

load = Image.open("PoweredByServiceWhiz.png")
render = ImageTk.PhotoImage(load)
img1 = Label(SWH,image=render)
img1.image = render  
img1.place(x=362,y=612.5)

img.after(3000, lambda: removewidgets(img, img1) )

1 个回答

2

我猜你是想把你的Tkinter应用放在一个类里面,对吧?而且这个应用需要显示两张图片,之后再把这两张图片都去掉?

如果我理解没错,这段代码应该能帮到你。我在注释里解释了每一部分的作用。

import sys
from tkinter import *
from PIL import Image, ImageTk

# Create the Class. Everything goes in the class,
# and passing variables is very easy because self is passed around
class SWLoad():
    # __init__ runs when the class is called
    def __init__(self):
        # Create window
        SWH = Tk()
        SWH.geometry("1024x950+130+0")
        SWH.title("ServiceWhiz.")

        # Initialize a list for the images
        self.img_list = []

        # Load the first image
        load = Image.open("Logo.png")
        render = ImageTk.PhotoImage(load)
        # Add the label to the list of images.
        # To access this label you can use self.img_list[0]
        self.img_list.append(Label(SWH, image=render))
        self.img_list[0].image = render  
        self.img_list[0].place(x=458,y=250)

        # Load the second image
        load = Image.open("PoweredByServiceWhiz.png")
        render = ImageTk.PhotoImage(load)
        # Add the label to the list of images.
        # To access this label you can use self.img_list[1]
        self.img_list.append(Label(SWH, image=render))
        self.img_list[1].image = render  
        self.img_list[1].place(x=362,y=612.5)

        # Fire the command that removes the images after 3 seconds
        SWH.after(3000, self.removewidgets)
        # Initialize the main loop
        SWH.mainloop()

    # Here, the function that removes the images is made
    # Note that it only needs self, which is passed automatically
    def removewidgets(self):
        # For every widget in the self.img_list, destroy the widget
        for widget in self.img_list:
            widget.destroy()

# Run the app Class
SWLoad()

撰写回答