首页 > 解决方案 > 如何处理用户创建的小部件?

问题描述

我正在使用一个简单的函数,它在画布上创建矩形(用户指定的大小)。

def create_some_rectangle(self):
    self.canvas.create_rectangle(master, x0, y0, x1, y1, fill='somecolor')
    # user specify x0 y0 x1 y1

但是我想为将来的寻址添加一些东西(通过单击鼠标突出显示特定的小部件)。如果有 1 个矩形会很简单,但是用户会创建很多矩形,所以我需要一些特别的东西来分别突出显示每个小部件。

  1. 用户在小部件上单击鼠标左键
  2. 小部件亮点
  3. 用户单击画布(突出显示的小部件除外)并突出显示过期

我怎么能意识到这一点?是否有一些方法可以用于此\任何有用的想法?

标签: pythontkinter

解决方案


每个方法都create_XXX给出id创建的对象

id = canvas.create_rectangle(...)

您可以将其保留在列表中,以便在需要时访问所有对象。

要更改对象的选项,您可以使用它id

canvas.itemconfig(id, fill='blue')

您可以绑定到单击左键( )Canvas时将执行的函数<Button-1>

canvas.bind('<Button-1>', on_click)

这个函数会得到event鼠标位置event.xevent.y你可以用它在画布上找到对象

selected_id = canvas.find_overlapping(event.x, event.y, event.x+1, event.y+1)

现在您可以取消选择所有项目并仅选择单击的项目

for id_ in all_ids:
    canvas.itemconfig(id_, fill='red')

if selected_id:
    canvas.itemconfig(selected_id, fill='blue')

import tkinter as tk

# --- functions ---

def on_click(event):
    #print(event)

    selected_id = canvas.find_overlapping(event.x, event.y, event.x+1, event.y+1)
    print(selected_id)

    for id_ in all_ids:
        canvas.itemconfig(id_, fill='red')

    if selected_id:
        canvas.itemconfig(selected_id, fill='blue')

# --- main ---

root = tk.Tk()

canvas = tk.Canvas()
canvas.pack()

canvas.bind('<Button-1>', on_click)

all_ids = []

for x in range(10, 301, 60):
    id_ = canvas.create_rectangle((x, 10, x+50, 60), fill='red')
    all_ids.append(id_)

root.mainloop()

文件:帆布


推荐阅读