Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
HW on BarGraph Class
#1
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()
Larz60+ write Oct-28-2020, 08:10 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.

added for you this time. Please use on future posts.
Reply
#2
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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020