atrefeu
atrefeu

Reputation: 168

Creating a background made of rectangles with tkinter?

I've been trying to create a program that would draw me a random picture made of filled rectangles, with tkinter. I had in mind to test it with a collection of grey nuances, for this purpose I made a list with 13 hexadecimal strings that would be randomly call during the drawing, on the tkinter canvas.

I've tried to make a 2d array with two - badly designed - loops and for each pixel creating a rectangle. Problem is that I get, after a fairly long time, a black screen, made of several black rectangles I guess. Maybe my variable that carries the picked color isnt of the right type for tkinter in the color='...' thing.

I put right here the code to make it understable, sorry for my english ;)

root=Tk()

colorlist = ['#000000', '#111111', '#222222', '#333333', '#444444', '#555555', '#666666', '#777777', '#888888', '#999999', '#bfbfbf', '#dedede', '#ffffff']

canevas = Canvas(root, width=1920, height=1080)
canevas.pack()

for i in range(1920):
    for j in range(1080):
        ind = randint(0, 12)
        ccolor = colorlist[ind]
        canevas.create_rectangle(i, j, i+1, j+1, fill=ccolor)

root.mainloop()

Upvotes: 1

Views: 746

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385830

Rectangles have an outline which is black by default. If you are trying to create a one-pixel rectangle, you need to set the width of the outline to zero with the width option. Otherwise, all you'll see in a one-pixel rectangle is the one-pixel outline.

canevas.create_rectangle(i, j, i+1, j+1, fill=ccolor, width=0)

By the way, instead of computing an index into your colors, you can use random.choice.

import random
...
ccolor = random.choice(colorlist)
canevas.create_rectangle(i, j, i+1, j+1, fill=ccolor, width=0)

Upvotes: 2

Related Questions