use*_*070 5 python tkinter python-2.7
这是我的第一个Python 编程代码。我试图通过单击按钮来更改图像。我有 2 个按钮,Start Conversation& Stop 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()
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)
最重要的问题是在创建新图像之前没有清除画布。通过以下方式启动您的(按钮)功能:
canvas.delete("all")
Run Code Online (Sandbox Code Playgroud)
然而,这同样适用于你的画布;你继续创造它。更好地拆分画布的创建和设置图像:
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()
Run Code Online (Sandbox Code Playgroud)
这也可以防止按下按钮时窗口出现有些奇怪的扩展。要使代码适合python3,请替换from Tkinter import*为from tkinter import*