在 Tkinter 按钮命令上显示新图像

Display new image on Tkinter button command

使用 Tkinter,单击按钮时如何在图像之间切换。有了这段代码作为参考,我只能加载一张图片,但我不知道如何让它按照我需要的方式运行。

from Tkinter import *
import ttk
from PIL import ImageTk, Image

def showImage(*args):
        lbl['image'] = image_tk

root = Tk()   
c = ttk.Frame(root, padding=(5, 5, 12, 0))
c.grid(column=0, row=0, sticky=(N,W,E,S))
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0,weight=1)

fname = "A.jpg"
fname1 = "B.jpg"
image_tk = ImageTk.PhotoImage(Image.open(fname))

btn = ttk.Button(c, text="load image", command=showImage)
lbl1 = ttk.Label(c)
btn.grid(column=0, row=0, sticky=N, pady=5, padx=5)
lbl.grid(column=1, row=1, sticky=N, pady=5, padx=5)

root.mainloop()

我如何配置我的 ShowImage 功能或任何其他需要的修改才能在 fnamefname1 之间切换图像

要在单击按钮时更改图像,请使用按钮的 configure() 方法来更改命令参数并创建一个新的 ImageTk 对象来保存第二个图像的引用。

from Tkinter import *
import ttk
from PIL import ImageTk, Image    

def showImage():
        lbl1.configure(image=image_tk)
        btn.configure(text = "load image!", command=showImage1)

def showImage1(): 
        lbl1.configure(image=image_tk1)
        btn.configure(text = "load image!", command=showImage)     

root = Tk()    
c = ttk.Frame(root, padding=(5, 5, 12, 0))
c.grid(column=0, row=0, sticky=(N,W,E,S))
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0,weight=1)

fname = "a.jpg"
image_tk = ImageTk.PhotoImage(Image.open(fname))

fname1 = "b.jpg"
image_tk1 = ImageTk.PhotoImage(Image.open(fname1))  # new image object


btn = ttk.Button(c, text="load image", command=showImage)
lbl1 = ttk.Label(c)
btn.grid(column=0, row=0, sticky=N, pady=5, padx=5)
lbl1.grid(column=1, row=1, sticky=N, pady=5, padx=5)

root.mainloop()