Python 3.x 在Tkinter Python3中显示和隐藏PNG图像

Python 3.x 在Tkinter Python3中显示和隐藏PNG图像,python-3.x,tkinter,Python 3.x,Tkinter,喜欢这个话题,, 如何显示并隐藏.png图像?canvas和photoimage有什么区别呢?我写了一段代码,只需点击一个按钮就可以隐藏/显示图像。您可以根据需要对其进行编辑 注意:目前,我正在使用pack()和pack\u-forget(),如果您想使用网格或位置,必须使用grid\u-forget()或place\u-forget() 进口tkinter def hideBG(): global state if state == "Hidden": back

喜欢这个话题,,
如何显示并隐藏
.png
图像?canvas和photoimage有什么区别呢?

我写了一段代码,只需点击一个按钮就可以隐藏/显示图像。您可以根据需要对其进行编辑

注意:目前,我正在使用
pack()
pack\u-forget()
,如果您想使用网格或位置,必须使用
grid\u-forget()
place\u-forget()

进口tkinter

def hideBG():
    global state
    if state == "Hidden":
        background_label.pack()
        state = "Showing"

    elif state == "Showing":
        background_label.pack_forget()
        state = "Hidden"




window = tkinter.Tk()

background_image=tkinter.PhotoImage(file="BG.png")
background_label = tkinter.Label(window, image=background_image)

hideBttn = tkinter.Button(window, text="Hide Background", command=hideBG)
state = "Showing"

hideBttn.pack()
background_label.pack()

window.mainloop()
这将在标签和按钮中创建图像。按下按钮时,通过调用hideBG函数,按钮获取图像的当前“状态”(无论是隐藏还是显示),并将其更改为相反的状态


希望这有帮助

您试图显示的.png图像是什么?什么时候失败了?请在代码中编辑并添加错误等。