python - 如何处理用户创建的小部件?
问题描述
我正在使用一个简单的函数,它在画布上创建矩形(用户指定的大小)。
def create_some_rectangle(self):
self.canvas.create_rectangle(master, x0, y0, x1, y1, fill='somecolor')
# user specify x0 y0 x1 y1
但是我想为将来的寻址添加一些东西(通过单击鼠标突出显示特定的小部件)。如果有 1 个矩形会很简单,但是用户会创建很多矩形,所以我需要一些特别的东西来分别突出显示每个小部件。
- 用户在小部件上单击鼠标左键
- 小部件亮点
- 用户单击画布(突出显示的小部件除外)并突出显示过期
我怎么能意识到这一点?是否有一些方法可以用于此\任何有用的想法?
解决方案
每个方法都create_XXX
给出id
创建的对象
id = canvas.create_rectangle(...)
您可以将其保留在列表中,以便在需要时访问所有对象。
要更改对象的选项,您可以使用它id
canvas.itemconfig(id, fill='blue')
您可以绑定到单击左键( )Canvas
时将执行的函数<Button-1>
canvas.bind('<Button-1>', on_click)
这个函数会得到event
鼠标位置event.x
,event.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()
文件:帆布
推荐阅读
- python - python如何通过右键单击Windows访问文件
- mysql - MySQL 多个 JOINS 在同一个单元格上
- css - 为什么使用 Bootstrap 4 在顶行和导航栏之间有一个空格?
- javascript - 如何将 React Hooks 与 video.js 一起使用?
- objective-c - Clang 将 #import 语句误解为文件,而不是框架
- python - 如何在文本字段中创建有效的 HTML 标签
- javafx - JavaFX中时间轴的场景更改问题
- javascript - 为什么我的 JavaScript 代码算术方程出现 NaN 错误
- javascript - 父子组件之间的 2 路事件绑定不起作用
- c++ - 在头文件和 cpp 文件中都包含一个库