将事件附加到自身(画布)tkinter [英] Attaching event to self (canvas) tkinter

查看:53
本文介绍了将事件附加到自身(画布)tkinter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中创建了一个扩展tkinter画布的类.我试图将事件附加到此画布上以处理类中的单击.如果我将事件附加到类本身之外,它将起作用,但是在类内进行绑定时,单击事件仅发生一次,然后仅执行第一次单击就根本不做任何事情:

i have created a class in python that extends the tkinter canvas. I am trying to attach an event to this canvas to handle click's within the class. It functions if i attach the event outside of the class itself but when binding within the class the click event only occur's once and then proceeds not to do anything at all only performing the first click:

class myCanvas(Canvas):
    def callback(event):
        print('clicked at', event.x, event.y)

    def __init__(self, parent, **kwargs):
        Canvas.__init__(self, parent, **kwargs)
        self.bind("<Button-1>", self.callback())
        self.height = self.winfo_reqheight()
        self.width = self.winfo_reqwidth()

仅当我在类之外附加事件时,绑定事件函数才能正确运行.在寻找将事件附加到扩展画布的方法方面的任何帮助将不胜感激.

Binding the event functions correctly only if i attach the event outside of the class. Any help in finding a way to attach the event to the extended canvas would be appreciated.

推荐答案

问题出在这一行:

self.bind("<Button-1>", self.callback())

您需要将可调用的东西(换句话说,一个函数)连接到事件.该功能称为 self.callback .如果您调用函数( self.callback()),那么您将把 self.callback()返回值连接到点击事件,而不是函数本身.

You need to connect something callable (in other words, a function) to the event. The function is referenced as self.callback. If you call the function (self.callback()) then you're connecting the return value of self.callback() to the click event instead of the function itself.

这篇关于将事件附加到自身(画布)tkinter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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