点击按钮更换图片

5

这是我的第一段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()

你好 user6829070,你有注意到答案吗?请提一下。 - Jacob Vlijm
1个回答

3

最重要的问题是在创建新图像之前没有清除画布。在您的(按钮)函数中开始使用以下代码:

canvas.delete("all")

然而,对于你的画布也是如此;你需要不断地创建它。最好将画布的创建和图像的设置分开处理:
from Tkinter import *

root = Tk()
prompt = StringVar()
root.title("AVATAR")
label = Label(root, fg="dark green")
label.pack()

frame = Frame(root,background='red')
frame.pack()

# Function definition

# first create the canvas
canvas = Canvas(height=200,width=200)
canvas.pack()

def Image1():
    canvas.delete("all")
    image1 = PhotoImage(file = "C:\Python27\Agent.gif")
    canvas.create_image(0,0,anchor='nw',image=image1)
    canvas.image = image1

def Image2():
    canvas.delete("all")
    image1 = PhotoImage(file = "C:\Python27\Hydrangeas.gif")
    canvas.create_image(0,0,anchor='nw',image=image1)
    canvas.image = image1

#Invoking through button
TextWindow = Label(frame,anchor = NW, justify = 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()

这还可以防止在按钮被按下时窗口的某种奇怪扩展。 为了使代码适用于 Python3,请将 from Tkinter import* 替换为 from tkinter import*


非常感谢。在使用 canvas.delete("all") 之后,现在它的工作非常完美。再次感谢 :) - user6829070
当然,Jacob。我按照上述步骤接受了它,再次感谢。 - user6829070

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接