Python Tkinter令人费解的结果

时间:2015-04-21 13:44:28

标签: python tkinter

我是Python的新手,试图用随机像素填充画布。有人能告诉我为什么它会做横条纹吗?

import tkinter
from random  import randint
from binascii import  hexlify
class App:
    def __init__(self, t):
        x=200
        y=200
        xy=x*y
        b=b'#000000 '
        s=bytearray(b*xy)
        c = tkinter.Canvas(t, width=x, height=y);
        self.i = tkinter.PhotoImage(width=x,height=y)
        for k in range (0,8*xy,8):
          s[k+1:k+7]=hexlify(bytes([randint(0,255) for i in range(3)]))
        print (s[:100])      
        pixels=s.decode("ascii")                                        
        self.i.put(pixels,(0,0,x,y))
        print (len(s),xy*8)
        c.create_image(0, 0, image = self.i, anchor=tkinter.NW)
        c.pack()

t = tkinter.Tk()
a = App(t)    
t.mainloop()

例如:

Window full of colourful stripes

1 个答案:

答案 0 :(得分:3)

我建议你做一些更简单的事情,例如:

class App:

    def __init__(self, t, w=200, h=200):
        self.image = tkinter.PhotoImage(width=w, height=h)  # create empty image
        for x in range(w):  # iterate over width
            for y in range(h):  # and height
                rgb = [randint(0, 255) for _ in range(3)]  # generate one pixel
                self.image.put("#{:02x}{:02x}{:02x}".format(*rgb), (y, x))  # add pixel
        c = tkinter.Canvas(t, width=w, height=h);
        c.create_image(0, 0, image=self.image, anchor=tkinter.NW)
        c.pack()

这更容易理解,并且给了我:

Windowful of fuzzy colours

我怀疑这是你所希望的。


要减少image.put的数量,请注意数据的格式是(对于2x2黑色图像):

'{#000000 #000000} {#000000 #000000}'

因此您可以使用:

self.image = tkinter.PhotoImage(width=w, height=h)
lines = []
for _ in range(h):
    line = []
    for _ in range(w):
        rgb = [randint(0, 255) for _ in range(3)]
        line.append("#{:02x}{:02x}{:02x}".format(*rgb))
    lines.append('{{{}}}'.format(' '.join(line)))
self.image.put(' '.join(lines))

只有一个image.put(请参阅例如Why is Photoimage put slow?)并提供类似图像。您的图片有条纹,因为它将每个像素颜色解释为线条颜色,因为您没有为每一行添加'{''}'