【问题标题】:Python Tkinter puzzling resultPython Tkinter 令人费解的结果
【发布时间】:2015-04-21 22:57:38
【问题描述】:

我是 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()

给出例如:

【问题讨论】:

  • 这看起来很复杂。到目前为止你做了哪些调试?
  • 您的代码出错。你怎么可能让它画一条水平线?
  • 为什么要以 8 个为一组进行 k 循环?这是否意味着您将图像填充为 8 像素部分?
  • 我会尝试重构以满足pep8this one 之类的检查器,以便代码更清晰,更易于阅读。
  • @BryanOakley 对我来说运行正常 - 你遇到了什么错误?

标签: python tkinter


【解决方案1】:

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

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()

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

我怀疑这就是你所希望的。


要减少image.puts 的数量,请注意数据格式为(对于 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?)并给出一个相似的图像。您的图像是条纹的,因为它将每个像素颜色解释为线条颜色,因为您没有为每条线条添加 '{''}'

【讨论】:

  • 是的,这就是我想要的视觉效果,只是我试图用尽可能少的 put 来加速它。当我将画布尺寸增加到 800x600 时,它会变得很明显。
  • @AntoniGualVia 我明白了;我添加了一个更有效(但仍然相当易读)的示例。请注意,如果您有特定目标(例如,最小化 puts),将其包含在您的问题中会非常有帮助。
  • 我想你已经回答了我的问题!所以需要花括号来分隔每一行的数据!另一个问题:我在哪里可以找到 put 格式的规范?我是通过反复试验来做到的.....
  • @AntoniGualVia Tkinter 基于 Tcl/Tk,因此您可以查看例如tcl.tk/man/tcl8.4/TkCmd/photo.htm#M30。这个网站也很方便:tkinter.unpythonic.net/wiki/PhotoImage
  • 我的 Mandelbrot 小演示运行速度惊人。我在一个合适的线程中发布了代码,stackoverflow.com/a/29800526/1955444
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-10
  • 1970-01-01
  • 1970-01-01
  • 2010-10-01
  • 1970-01-01
  • 2018-01-09
  • 2012-10-31
相关资源
最近更新 更多