本文介绍了Tkinter Canvas:函数运行而不会被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始在Python中使用Canvas对象.我创建了以下简单工作:目的是使蓝色三角形双击时变为黄色.相反,它从一开始就是黄色.我在做什么错了?

I am starting out using Canvas objects in Python.I've created the following simple job: the intention is that a blue triangle which, when double clicked, turns yellow.Instead, it is yellow right from the start. What am I doing wrong?

from Tkinter import *

def Yellow():
    canv.itemconfigure(obj,fill='yellow')

root=Tk()
canv=Canvas(root,width=200,height=200)
obj=canv.create_polygon(100,100,120,120,120,80,fill='blue')
canv.tag_bind(obj,'<Double-1>',Yellow())
canv.pack()
root.mainloop()

推荐答案

在代码行中

canv.tag_bind(obj,'<Double-1>',Yellow())

表达式Yellow()调用名为Yellow的函数.为了简单地引用一个函数(例如将其绑定到一个事件)而不是调用它,您应该只编写Yellow.因此,您的代码应改为

The expression Yellow() calls the function called Yellow. In order to simply refer to a function (say to bind it to an event) instead of calling it, you should just write Yellow. So your code should instead read

canv.tag_bind(obj,'<Double-1>',Yellow)

这篇关于Tkinter Canvas:函数运行而不会被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 22:25