Tkinter 画布绑定 '<Configure>'事件到项目 [英] Tkinter Canvas bind &#39;&lt;Configure&gt;&#39; event to item

查看:59
本文介绍了Tkinter 画布绑定 '<Configure>'事件到项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我错过了什么吗?我以为我已经做了类似下面例子的事情.但是我既没有找到像我希望的那样运行的脚本,也没有在网上找到一些东西.基本上我想将 Configure 事件绑定到一个项目.是不是可能像错误提示的那样?

资源:画布tag_bind

导入 tkinter 作为 tkdef do_something(事件=无):打印('东西')定义愚蠢的解决方法():如果 cnvs.coords(lbl) != lbl_coords:做点什么()cnvs.coords(lbl, *lbl_coords)cnvs.after(200,stupid_workaround)根 = tk.Tk()cnvs = tk.画布(根,highlightthickness=0)lbl = cnvs.create_text(0,0, text='这是一个例子', anchor='nw')lbl_coords = cnvs.coords(lbl)btn = tk.Button(root, text='change coords', command=lambda:cnvs.coords(lbl,10,10))btn.pack()愚蠢的解决方法()#cnvs.bind(lbl, '<Configure>', do_something) #没有报错#cnvs.tag_bind(lbl, '<Configure>', do_something) #抛出错误cnvs.pack()root.mainloop()

<块引用>

_tkinter.TclError:请求非法事件;只能使用按键、按钮、动作、进入、离开和虚拟事件

解决方案

就像错误所说的,你不能绑定到 事件,它根本不是一个选项.该事件仅对小部件有效,对画布上绘制的项目无效.

Am I missing something ? I thought I've done something like the example below. But neither I found a script of mine that act like I hoped, nor I have found something online. Basically I want to bind the Configure event to an item. Isnt it possible like the error suggest?

Resources : Canvas and tag_bind

import tkinter as tk

def do_something(event=None):
    print('something')
def stupid_workaround():
    if cnvs.coords(lbl) != lbl_coords:
        do_something()
        cnvs.coords(lbl, *lbl_coords)
    
    cnvs.after(200,stupid_workaround)

root = tk.Tk()
cnvs = tk. Canvas(root,highlightthickness=0)
lbl = cnvs.create_text(0,0, text='this is an exampel', anchor='nw')
lbl_coords = cnvs.coords(lbl)
btn = tk.Button(root, text='change coords', command=lambda:cnvs.coords(lbl,10,10))
btn.pack()
stupid_workaround()
#cnvs.bind(lbl, '<Configure>', do_something) #throws no error
#cnvs.tag_bind(lbl, '<Configure>', do_something) #throws error

cnvs.pack()
root.mainloop()

_tkinter.TclError: requested illegal events; only key, button, motion, enter, leave, and virtual events may be used

解决方案

Like the error says, you can't bind to the <Configure> event, it's simply not an option. That event is only valid for widgets, not items drawn on a canvas.

这篇关于Tkinter 画布绑定 '<Configure>'事件到项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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