这是我的第一个 Python 编程代码。我试图通过单击按钮来更改图像。我有 2 个按钮,开始对话 & 停止对话。
当表单加载时没有图像。单击开始 按钮时,将显示 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()
最佳答案
最重要的问题是在创建新图像之前您没有清除 Canvas 。开始你的(按钮)功能:
canvas.delete("all")
然而,这同样适用于您的 Canvas ;你一直在创造它。最好拆分 Canvas 的创建和设置图像:
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*
关于python - 单击按钮更改图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39482273/