Skip to main content
 首页 » 编程设计

python之如何替换现有图像而不是添加其他图像

2025年01月19日9me-sa

这是我第一次来这里,我非常感谢对此的一些帮助。

所以我有一些代码可以运行 Tkinter 选项卡并显示 2 个按钮。如果单击第一个,则会出现一张猫的图片。

但是,如果您再次单击该按钮,相同的图片会再次出现在底部,成为 2。

如果我单击另一个名为 N/A 的按钮,则会出现不同的图片。但是,如果您再次单击该按钮,图片就会重复。

我想让它在按下每个按钮时替换图像,而不是复制图像。

这是我目前所拥有的。

from tkinter import * 
 
root = Tk() 
 
class HomeClass(object): 
    def __init__(self, master): 
        frame = Frame(master) 
        frame.pack() 
 
        self.WelcomeLabel = Label(root, text="Welcome to the game!", 
                                  bg="Black", fg="White") 
        self.WelcomeLabel.pack(fill=X) 
 
        self.FirstButton = Button(root, text="Start", bg="RED", fg="White", 
                                 command=self.FirstClick) 
        self.FirstButton.pack(side=LEFT, fill=X) 
 
        self.SecondButton = Button(root, text="N/A", bg="Blue", fg="White", 
                                   command=self.SecondClick) 
        self.SecondButton.pack(side=LEFT, fill=X) 
 
    def FirstClick(self): 
        FirstPhoto = PhotoImage(file="keyboardcat.gif") 
        FiLabel = Label(root, image=FirstPhoto) 
        FiLabel.img = FirstPhoto 
        FiLabel.pack() 
 
 
    def SecondClick(self): 
        FirstPhoto = PhotoImage(file="donald.gif") 
        FiLabel = Label(root, image=FirstPhoto) 
        FiLabel.img = FirstPhoto 
        FiLabel.pack() 
 
 
k = HomeClass(root) 
root.mainloop() 

请您参考如下方法:

这是因为每次单击按钮时,都会调用 FirstClick 方法,该方法会创建 PhotoImage 类的新实例。我认为存储 FirstPhoto 并在每个 FirstClick 方法调用中检查它是否已经有值(value)会更好。

class HomeClass(object): 
    def __init__(self, master): 
        frame = Frame(master) 
        frame.pack() 
 
        self.WelcomeLabel = Label(root, text="Welcome to the game!", 
                              bg="Black", fg="White") 
        self.WelcomeLabel.pack(fill=X) 
 
        self.FirstButton = Button(root, text="Start", bg="RED", fg="White", 
                             command=self.FirstClick) 
        self.FirstButton.pack(side=LEFT, fill=X) 
 
        self.SecondButton = Button(root, text="N/A", bg="Blue", fg="White", 
                               command=self.SecondClick) 
        self.SecondButton.pack(side=LEFT, fill=X) 
 
        self.FirstPhoto = None 
 
    def FirstClick(self): 
        if self.FirstPhoto is None: 
            self.FirstPhoto = PhotoImage(file="ksiazka.png") 
            self.FiLabel = Label(root, image=self.FirstPhoto) 
            self.FiLabel.img = self.FirstPhoto 
            self.FiLabel.pack()