单击按钮更改图像

时间:2016-09-14 03:56:59

标签: python python-2.7 tkinter

这是我的第一个python编程代码。我想点击一个按钮来改变图像。我有2个按钮, Start Conversation & 停止对话

当表单加载时,没有图像。单击开始按钮时,将显示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()

1 个答案:

答案 0 :(得分:3)

最重要的问题是在创建新图像之前不要清除画布。使用以下命令启动(按钮)功能:

value

然而,你的画布也是如此;你一直在创造它。更好地分割画布的创建和设置图像:

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*