Generating Shapes from a Dictionary

Viewed 180

Good Evening All,

The idea is to create a series of colour blocks that sit on top of each other in a vertical column (See picture) by iterating through a dictionary. I can’t seem to get it right.

This is what I've attempted so far.

This is what I am aiming for. This is what I am able to create.

Any hints welcomed!

import tkinter

from collections import OrderedDict


def main():

    dict1 = OrderedDict()

    dict1['Block1'] = [70, 'red', '1st column']
    dict1['Block2'] = [200, 'green', '1st column']
    dict1['Block3'] = [420, 'blue', '1st column']


    canvas = make_canvas(200, 800, dict1['Block1'][2])


    for key in dict1.keys():
        canvas.create_rectangle(20, 40, 100, dict1[key][0], fill=dict1[key][1])  # Create a block for each key

    canvas.mainloop()



def make_canvas(width, height, title=None):
    objects = {}
    top = tkinter.Tk()
    top.minsize(width=width, height=height)
    if title:
        top.title(title)
    canvas = tkinter.Canvas(top, width=width + 1, height=height + 1)
    canvas.pack()
    canvas.xview_scroll(8, 'units')  # add this so (0, 0) works correctly
    canvas.yview_scroll(8, 'units')  # otherwise it's clipped off

    return canvas


if __name__ == '__main__':
    main()
1 Answers

The problem is that canvas is drawing different bars starting from the same position which overwrites the previous one.

You need start at the previous total and end at the total plus the length of the bar.

import tkinter

from collections import OrderedDict


def main():

    dict1 = OrderedDict()

    dict1['Block1'] = [70, 'red', '1st column']
    dict1['Block2'] = [200, 'green', '1st column']
    dict1['Block3'] = [420, 'blue', '1st column']


    canvas = make_canvas(200, 800, dict1['Block1'][2])

    total = 0
    for key in dict1.keys():
        canvas.create_rectangle(20, total, 100, total + dict1[key][0], fill=dict1[key][1])  # Create a block for each key
        total += dict1[key][0]

    canvas.mainloop()



def make_canvas(width, height, title=None):
    objects = {}
    top = tkinter.Tk()
    top.minsize(width=width, height=height)
    if title:
        top.title(title)
    canvas = tkinter.Canvas(top, width=width + 1, height=height + 1)
    canvas.pack()
    canvas.xview_scroll(8, 'units')  # add this so (0, 0) works correctly
    canvas.yview_scroll(8, 'units')  # otherwise it's clipped off

    return canvas


if __name__ == '__main__':
    main()

Result:

enter image description here

Related