Skip to main content
 首页 » 编程设计

Python tkinter : Replacing an image button with an image label

2024年10月25日9artech

您好,我正在尝试制作一个代码,在按下按钮时用图像标签替换图像按钮。但是窗口没有更新,所以新图像不可见。有谁能够帮助我?如果甚至可以这样做的话。

这是我正在尝试的代码:

from tkinter import * 
import time 
 
gifdir = "./" 
class Game: 
   def __init__(self): 
      self.__window = Tk() 
 
 
 
      igm = PhotoImage(file=gifdir+"empty.gif") 
 
      Button(self.__window, image=igm, command= self.change_picture)\ 
      .grid(row=1, column=2, sticky=E) 
 
      def change_picture(): 
        igm = PhotoImage(file=gifdir+"new.gif") 
        Label(self.__window, image=igm,)\ 
        .grid(row=1, column=2, sticky=E) 
 
       self.__window.mainloop() 
 
def main(): 
    Game() 
 
 
main() 

当我将此代码添加到末尾时:

   self.__window.update_idletasks() 
   time.sleep(1) 

新图片只显示一秒钟,但我需要一直看到它并且仍然能够按其他按钮。

请您参考如下方法:

我修改了你的代码,因为你的代码设计得很奇怪,并且不正确的 IMO。这是修改后的版本:

from tkinter import * 
 
import time 
 
class Game: 
    def __init__(self): 
        self.__window = Tk() 
 
        self.gifdir = "./" 
 
        self.igm = PhotoImage(file=self.gifdir+"empty.gif") 
 
        self.btn = Button(self.__window, image=self.igm, command = self.change_picture) 
        self.btn.grid(row=1, column=2, sticky=E) 
 
        self.__window.mainloop()                 
 
    def change_picture(self): 
        self.igm = PhotoImage(file=self.gifdir+"new.gif") 
        self.btn.configure(image = self.igm)               
 
 
def main(): 
    Game() 
 
 
main() 

在这个新版本中,按下按钮,将改变上面的图像。基本上,在您的类(class)中,您需要保留对创建的小部件的引用。特别是保留对 PhotoImage 的引用很重要,因为如果不保留引用,垃圾收集器将删除图像,当 PhotoImage 的实例超出 的范围时>更改图片。