Tkinter:从按钮处理程序访问画布 [英] Tkinter: Access canvas from button handler

查看:23
本文介绍了Tkinter:从按钮处理程序访问画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I update the canvas from a function called by a button? Here's my code:

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)),两者都没有效果.我做错了什么?

Pressing the "Display Label" button does nothing. I've tried designating the canvas global in the method, or passing the canvas in as an argument (using command = lambda (displayLabel(canvas)), both to no effect. What am I doing wrong?

更新:我现在意识到我的问题是这个重复,但@shalitmaan 的回答以另一种没有的方式帮助了我.

UPDATE: I now realize my question is a duplicate of this one, but @shalitmaan's answer helped me in ways the other one didn't.

推荐答案

当您将 PhotoImage 或其他 Image 对象添加到 Tkinter 小部件时,您必须保留自己对图像对象的引用.如果不这样做,图像将不会始终显示.这基本上就是我想说的:

When you add a PhotoImage or other Image object to a Tkinter widget, you must keep your own reference to the image object. If you don’t, the image won’t always show up. Here is essentially what I'm trying to say:

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

我是从这里了解到的.

另外你需要去掉括号()

b3 = Button(tk, text="Display Label", width=30, command= displayLabel) #no parenthesis

否则它会被直接调用,甚至无需按下按钮.您可能直到现在才注意到它,因为 Tk 只是使图像空白,您现在可以从链接中了解到.

otherwise it will be called directly without even the button press. You might not have noticed it up until now since Tk was just making the image blank as you may understand now from the link.

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

Also if you want to send some arguments to displayLabel you need to use lambda. For eg:

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

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

In your asked question,you were missing the colon :

这篇关于Tkinter:从按钮处理程序访问画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆