Python Forum
HW on BarGraph Class - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: HW on BarGraph Class (/thread-30626.html)



HW on BarGraph Class - Grey_space - Oct-28-2020

Hi, I am currently working on a program that defines a class called DrawBar which basically turns a list into a bar graph. In it, I should have a method called get_color which whenever self.color equals 'random' all the bars should be different colors and when self.color is equal to something else (for example 'red') all the bars should be the color red. Now I tried running an if statement that says that when self.color is equal to random, self.color should be a random color chosen from a list. However, when I print my class and pass color as random it gives me a bar graph with all the bars being the same color. Does anyone have suggestions on what to fix or where my logic could be wrong?

import random
import sys
import tkinter
window = tkinter.Tk()
window.title("Tkinter Canvas")
canvas = tkinter.Canvas(window, width=500, height=500, background='white')
canvas.pack()

class BarGraph:
    
    def __init__(self,data,color = 'random'):
        self.color = color
        for i in data:
            if i == abs(i):
                self.data = data
            else:
                sys.exit()
        if len(data) != 0:
            self.data = data
        else:
            sys.exit()
            
    def get_color(self):
        if self.color == 'random':
            self.color = random.choice(['red', 'orange', 'yellow', 'green', 'blue', 'purple'])
            
        return self.color
            
    
    def __str__(self):
        return "'Bar Graph - Color:{} Data:{}'.".format(self.color,self.data)
 

    def draw_bar(self,canvas,x,y,width,height):
        x2 = x + width
        y2 = y
        x1 = x
        y1 = y - height
        canvas.create_rectangle(x1, y1, x2, y2,fill = self.get_color())
        
    def draw(self,canvas,total_width,total_height):
        
        x = 0
        y = total_height
        width = total_width / len(self.data)
        for i in self.data:
            self.get_color()
            height = (i/max(self.data)) * total_height
            self.draw_bar(canvas,x,y,width,height)
            x += width

      
bg = BarGraph([3,5,8,2,9,12,15,4],'random')
print(bg)
bg.draw(canvas,500,500)
bg.get_color()



RE: HW on BarGraph Class - deanhystad - Oct-28-2020

Look at get_color(). It does something that prevents you from ever having a graph with more than 1 color. With only 3 lines it should be easy to find.