Tkinter:从按钮手访问画布

2024-04-20 10:38:40 发布

您现在位置:Python中文网/ 问答频道 /正文

如何从按钮调用的函数更新画布?我的代码是:

from Tkinter import *
import ImageTk

tk = Tk()
canvas = Canvas(tk, bg="white", width=300, height=200)
canvas.grid()

def displayLabel():
    photoimage = ImageTk.PhotoImage(file="Logo.png")
    canvas.create_image(0,0, image=photoimage, anchor = NW)

b3 = Button(tk, text="Display Label", width=30, command= displayLabel())
b3.grid(row=1)

tk.mainloop()

按“显示标签”按钮不起任何作用。我尝试在方法中指定画布全局,或者将画布作为参数传入(使用command = lambda (displayLabel(canvas))),但都没有效果。我做错什么了?在

更新:我现在意识到我的问题是一个duplicate of this one,但是@shalitmaan的回答在某种程度上帮助了我,而另一个却没有


Tags: 函数代码imageimport画布width按钮command
1条回答
网友
1楼 · 发布于 2024-04-20 10:38:40

PhotoImage或其他图像对象添加到Tkinter小部件时,必须保留对该图像对象的引用。如果你不这样做,图像就不会一直出现。 我想说的是:

def displayLabel():
    photoimage = ImageTk.PhotoImage(file="lena.png")
    canvas.create_image(0,0, image=photoimage, anchor = NW)
    canvas.image=photoimage #keep the reference!

我是从here学来的。在

同时您需要删除括号()

^{pr2}$

否则它将被直接调用,甚至不按按钮。您可能直到现在才注意到,因为Tk只是使图像变为空白,您现在可以从链接中了解到这一点。在

另外如果您想向displayLabel发送一些参数,则需要使用lambda。例如:

b3 = Button(tk, text="Display Label", width=30, command= lambda:displayLabel(args))

在您的问题中,您缺少冒号:

相关问题 更多 >