Выделение объектов

from random import randrange as rnd, choice
from tkinter import *
import math
import time

root = Tk()
root.geometry('800x600')

canv = Canvas(root, bg = 'white')
canv.pack(fill = BOTH, expand = 10)

colors = ['brown','green','lightgreen','yellow','black','blue']

class ball():
	def __init__(self):
		x = self.x = rnd(50,700)
		y = self.y = rnd(50,550)
		r = self.r = rnd(10,30)
		self.color = choice(colors)
		self.pen_color = choice(colors)
		self.pen_color_original = self.pen_color
		self.select = 0
		self.width = 0
		self.id = canv.create_oval(x-r,y-r,x+r,y+r, fill = self.color, width = self.width, outline = self.pen_color)
		self.paint()
 
	def paint(self):
		x = self.x
		y = self.y
		r = self.r
		canv.coords(self.id,x-r,y-r,x+r,y+r)
		canv.itemconfig (self.id, fill = self.color, width = self.width, outline = self.pen_color)
	def kill(self):
		canv.delete(self.id)
		balls.remove(self)
		
def paint():
	for b in balls:
		b.paint()

def fill_random(event):
	global balls
	canv.delete(ALL)
	balls = []
	for z in range(12):
		balls += [ball()]

def move(event):
	if sel:
		canv.delete('mm2')
		canv.create_rectangle(sx,sy,event.x,event.y,tag = "mm2")


def select_on(event):
	global sel,sx,sy
	sel = 1
	sx = event.x
	sy = event.y
	
def select_off(event):
	global sel
	sel = 0
	sx2 = event.x
	sy2 = event.y
	canv.delete('mm2')
	#canv.create_rectangle(sx,sy,mx,my,tag = "mm2")
	for i in balls:
		if (sx > i.x > sx2 or sx2 > i.x > sx) and (sy > i.y > sy2 or sy2 > i.y > sy) or ((sx2-i.x)**2  + (sy2-i.y)**2 < i.r**2):
			i.pen_color = "#fe0000"
			i.width = 3
			i.paint()
			i.select = 1
		else:
			i.pen_color = i.pen_color_original
			i.paint()	
			i.select = 0
	
def delete_sel(event):
	for b in [b for b in balls if b.select]:
		b.kill()
	
sel = 0
fill_random(0) 
canv.bind('<Button-2>', fill_random)
root.bind('<Delete>', delete_sel)
canv.bind('<Button-1>', select_on)
canv.bind('<ButtonRelease-1>', select_off)
canv.bind('<Motion>', move)

mainloop()

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *