使用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
功能或能够在fname
和fname1
答案 0 :(得分:1)
要更改按钮单击时的图像,请使用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()