为了让 Canvas 使用鼠标画出基本图形元素(线段、椭圆、矩形、弧形),本文介绍一种统一的接口。
from tkinter import Canvas
class Meta(Canvas):
'''Graphic elements are composed of line(segment), rectangle, ellipse, and arc.
'''
def __init__(self, master=None, cnf={}, **kw):
'''The base class of all graphics frames.
:param master: a widget of tkinter or tkinter.ttk.
'''
super().__init__(master, cnf, **kw)
def layout(self, row=0, column=0):
'''Layout graphic elements with Grid'''
# Layout canvas space
self.grid(row=row, column=column, sticky='nwes')
def draw_graph(self, graph_type, direction, color='blue', width=1, tags=None, **kwargs):
'''Draw basic graphic elements.
:param direction: Specifies the orientation of the graphic element.
Union[int, float] -> (x_0,y_0,x_,y_1), (x_0, y_0) refers to the starting point of
the reference brush (i.e., the left mouse button is pressed), and (x_1, y_1) refers to
the end position of the reference brush (i.e., release the left mouse button).
:param graph_type: Types of graphic elements.
(str) 'rectangle', 'oval', 'line', 'arc'(That is, segment).
Note that 'line' can no longer pass in the parameter 'fill'.
:param color: The color of the graphic element.
:param width: The width of the graphic element.(That is, center fill)
:param tags: The tags of the graphic element.
It cannot be a pure number (such as 1 or '1' or '1 2 3'), it can be a list, a tuple,
or a string separated by a space(is converted to String tupers separated by a blank space).
The collection or dictionary is converted to a string.
Example:
['line', 'graph'], ('test', 'g'), 'line',
' line kind '(The blanks at both ends are automatically removed), and so on.
:param style: Style of the arc in {'arc', 'chord', or 'pieslice'}.
:return: Unique identifier solely for graphic elements.
'''
com_kw = {'width': width, 'tags': tags}
kw = {**com_kw, 'outline': color}
line_kw = {**com_kw, 'fill': color}
if graph_type == 'line':
kwargs.update(line_kw)
else:
kwargs.update(kw)
if graph_type in ('rectangle', 'oval', 'line', 'arc'):
func = eval(f"self.create_{graph_type}")
graph_id = func(direction, **kwargs)
[self.addtag_withtag(tag, graph_id)
for tag in ('graph', graph_type)]
else:
graph_id = None
return graph_id
if __name__ == "__main__":
from tkinter import Tk
root = Tk()
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
self = Meta(root)
kw = {
'color': 'purple',
'dash': 2,
'width': 2,
'tags': 'test '
}
name = 'oval'
color = 'purple'
width = 2
self.draw_graph('line', [20, 20, 100, 200], **kw)
self.draw_graph('oval', [50, 80, 100, 200], fill='red', **kw)
self.draw_graph('rectangle', [170, 80, 220, 200], fill='yellow', **kw)
self.draw_graph('arc', [180, 100, 250, 260],
fill='lightblue', style='chord', **kw)
self.layout(row=0, column=0)
print(self.gettags(1))
print(self.find_withtag('graph'))
root.mainloop()
可以测试该接口,显示图片:
Meta 测试下面便可以对创建的图形进行操作。
画出不同颜色的矩形框
root = Tk()
self = Meta(root, background='lightgray')
graph_type = 'rectangle'
start, end = 20, 50
colors = 'red', 'blue', 'black', 'white', 'green'
for k, color in enumerate(colors):
direction = start+10*k, start+10*k, end+10*k, end+10*k
self.draw_graph(graph_type, direction, 'lightblue', fill=color)
start += 80
end += 80
for k, color in enumerate(colors):
direction = start+30*k, start, end+30*k, end
self.draw_graph(graph_type, direction, 'lightblue', fill=color)
self.grid()
root.mainloop()
带文本的图形
class Param:
def __init__(self):
self.param = {}
def __get__(self, obj, objtype):
return self.param[obj]
def __set__(self, obj, value):
self.param[obj] = value
class Selector(Meta):
colors = 'red', 'blue', 'black', 'purple', 'green', 'skyblue', 'yellow', 'white'
shapes = 'rectangle', 'oval', 'line', 'oval_point', 'rectangle_point'
def __init__(self, master=None, graph_type=None, color=None, cnf={}, **kw):
'''The base class of all graphics frames.
:param master: a widget of tkinter or tkinter.ttk.
'''
super().__init__(master, cnf, **kw)
self.start, self.end = 15, 50
self.create_color()
self.create_shape()
SelectBind(self)
def create_color(self):
'''Set the color selector'''
self.create_text((self.start, self.start),
text='color', font='Times 15', anchor='w')
self.start += 10
for k, color in enumerate(Selector.colors):
t = 7+30*(k+1)
direction = self.start+t, self.start-20, self.end+t, self.end-20
self.draw_graph('rectangle', direction,
'yellow', tags=color, fill=color)
self.dtag('rectangle')
def create_shape(self):
'''Set the shape selector'''
self.create_text((self.start-10, self.start+30),
text='shape', font='Times 15', anchor='w')
for k, shape in enumerate(Selector.shapes):
t = 7+30*(k+1)
direction = self.start+t, self.start+20, self.end+t, self.end+20
width = 10 if shape == 'line' else 1
fill = 'blue' if 'point' in shape else 'white'
self.draw_graph(shape.split(
'_')[0], direction, 'blue', width=width, tags=shape, fill=fill)
class SelectBind:
# 初始化参数
color = Param()
graph_type = Param()
def __init__(self, selector, graph_type=None, color=None):
'''The base class of all graphics frames.
:param selector: a instance of Selector.
'''
self.color = color
self.graph_type = graph_type
[self.color_bind(selector, color) for color in selector.colors]
[self.graph_type_bind(selector, graph_type)
for graph_type in selector.shapes]
selector.dtag('all')
def set_color(self, new_color):
self.color = new_color
print(self.color, self.graph_type)
def set_graph_type(self, new_graph_type):
self.graph_type = new_graph_type
print(self.color, self.graph_type)
def color_bind(self, canvas, color):
canvas.tag_bind(color, '<1>', lambda e: self.set_color(color))
def graph_type_bind(self, canvas, graph_type):
canvas.tag_bind(graph_type, '<1>',
lambda e: self.set_graph_type(graph_type))
if __name__ == "__main__":
from tkinter import Tk
root = Tk()
selector = Selector(root, background='lightgreen')
selector.grid()
root.mainloop()
测试结果:
图形选择器此代码完成了使用鼠标选择图形的颜色以及形状的工作。
网友评论