这是我的第一段Python编程代码。我试图在点击按钮时更改图像。我有两个按钮:开始对话和停止对话。
当页面加载时,没有图像。当点击开始按钮时,将显示ABC图像。当点击停止按钮时,应该显示xyz图像。
我的问题是,当我点击开始时,相应的图像出现了,但是当我点击停止时,新图像出现了,但是以前的图像没有消失。两张图片一个接一个地显示。
我的代码如下:
root = Tk()
prompt = StringVar()
root.title("AVATAR")
label = Label(root, fg="dark green")
label.pack()
frame = Frame(root,background='red')
frame.pack()
函数定义
def Image1():
image = Image.open("C:\Python27\Agent.gif")
photo = ImageTk.PhotoImage(image)
canvas = Canvas(height=200,width=200)
canvas.image = photo # <--- keep reference of your image
canvas.create_image(0,0,anchor='nw',image=photo)
canvas.pack()
def Image2():
image = Image.open("C:\Python27\Hydrangeas.gif")
photo = ImageTk.PhotoImage(image)
canvas = Canvas(height=200,width=200)
canvas.image = photo # <--- keep reference of your image
canvas.create_image(0,0,anchor='nw',image=photo)
canvas.pack()
#Invoking through button
TextWindow = Label(frame,anchor = tk.NW, justify = tk.LEFT, bg= 'white', fg = 'blue', textvariable = prompt, width = 75, height=20)
TextWindow.pack(side = TOP)
conversationbutton = Button(frame, text='Start Conversation',width=25,fg="green",command = Image1)
conversationbutton.pack(side = RIGHT)
stopbutton = Button(frame, text='Stop',width=25,fg="red",command = Image2)
stopbutton.pack(side = RIGHT)
root.mainloop()