问题描述
我正在尝试编写一个代码,当按下按钮时,该代码将用图像标签替换图像按钮.但是窗口没有更新,所以新图像不可见.有谁能够帮助我?如果有可能这样做.
Hi I'm trying to make a code that would replace an image button with an image label when the button is pressed. But the window isn't updating so the new image doesn't became visible. Can anybody help me? If it is even possible to do that way.
这是我正在尝试的代码:
There is the code I'm trying:
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()
当我将此代码添加到末尾时:
When I add this code to the end:
self.__window.update_idletasks()
time.sleep(1)
新图片会显示一秒钟,但我需要一直看到它并且仍然可以按其他按钮.
the new picture is shown for a one second but I need to see it all the time and still be able to press other buttons.
推荐答案
我修改了您的代码,因为您的代码设计非常奇怪,而且 IMO 不正确.这是修改后的版本:
I modified your code, as your code is very strangely designed, and incorrect IMO. This is the modified version:
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()
在这个新版本中,按下按钮,将改变其上的图像.基本上,在您的班级中,您需要保留对创建的小部件的引用.尤其是保持对 PhotoImage
的引用很重要,如果引用没有保留,垃圾收集器将删除图像,当 PhotoImage
的实例将超出 change_picture
.
In this new version, pressing the button, will change the image on it. Basically, in your class, you need to keep references to created widgets. Especially keeping a reference for PhotoImage
is important, as if the reference is not kept, garbage collector will remove the image, when instance of PhotoImage
will go out of scope in change_picture
.
这篇关于Python tkinter:用图像标签替换图像按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!