import tkinter as tk
class Shape:
def __init__(self,
canvas,
shape_type,
x,y,width,height,command=None):
self.canvas = canvas
self.shape_type = shape_type
self.x = x
self.y = y
self.width = width
self.height = height
self.shape = None
self.command = command
def draw(self):
if self.shape_type=='circle':
self.shape=self.canvas.create_oval(self.x,self.y,self.x+self.width,self.y+self.height,fill='pink')
elif self.shape_type == 'rectangle':
self.shape = self.canvas.create_rectangle(self.x,self.y,self.x+self.width,self.y+self.height,fill='blue')
self.canvas.tag_bind(self.shape,'<Button-1>',self.on_click)
def on_click(self,event):
if self.shape_type=='circle':
condition=self.x<=event.x<self.x+self.width and self.y<event.y<self.y+self.height
if condition and self.command:
self.command()
elif self.shape_type=='rectangle':
condition = self.x <= event.x < self.x + self.width and self.y < event.y < self.y + self.height
if condition and self.command:
self.command()
class MyClass:
def __init__(self):
self.root=tk.Tk()
self.root.geometry("800x600")
self.canvas=tk.Canvas(self.root,width=600,height=400)
self.canvas.place(x=0,y=0)
self.c = Shape(self.canvas,'circle',20,20,80,80,self.fun)
self.c.draw()
self.r = Shape(self.canvas,'rectangle',100,100,150,150)
self.r.draw()
def fun(self):
print('hello world')
a=MyClass()
a.root.mainloop()
tkinter之canvas学习
于 2023-07-10 20:57:53 首次发布