tkinter 使用鼠标选择图形的颜色以及形状

为了让 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()

测试结果:

图形选择器

此代码完成了使用鼠标选择图形的颜色以及形状的工作。

更多精彩 API 请参考:TensorAtom(develop 分支)。

可以调用:

from graph.test import test_Meta, test_Drawing

分别来测试类:MetaDrawing,其中 Drawing 实现鼠标左键画图的功能:

鼠标左键画图

上图展示了使用鼠标左键画图的操作,在右边选择画笔的颜色与形状,在左边使用鼠标左键画图。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,607评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,239评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,960评论 0 355
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,750评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,764评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,604评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,347评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,253评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,702评论 1 315
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,893评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,015评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,734评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,352评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,934评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,052评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,216评论 3 371
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,969评论 2 355

推荐阅读更多精彩内容