如何在python中仅使用Tk快速绘制位图?

2024-05-15 01:52:11 发布

您现在位置:Python中文网/ 问答频道 /正文

这是个问题。我想将一个特定的向量场可视化为位图。表示本身没问题,所以我已经准备好了一些RGB列表的矩阵,比如[255255115],但是我不知道如何在屏幕上绘制它。到目前为止,我制作了数千个彩色的1px矩形,但是这个速度太慢了。我相信有更好的方法来绘制位图。


Tags: 方法列表屏幕可视化绘制矩阵rgb速度
2条回答

第三次尝试-我发誓是最后一次…

我相信这是最快的纯传统的方式来做到这一点。在列表列表中生成10000个RGB值,创建一个Tkinter.PhotoImage,然后将像素值放入其中。

import Tkinter, random
class App:
    def __init__(self, t):
        self.i = Tkinter.PhotoImage(width=100,height=100)
        colors = [[random.randint(0,255) for i in range(0,3)] for j in range(0,10000)]
        row = 0; col = 0
        for color in colors:
           self.i.put('#%02x%02x%02x' % tuple(color),(row,col))
           col += 1
           if col == 100:
               row +=1; col = 0        
        c = Tkinter.Canvas(t, width=100, height=100); c.pack()
        c.create_image(0, 0, image = self.i, anchor=Tkinter.NW)

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

尝试1-使用create_rectangle方法

我写这个是为了测试。在2.67GHz的Intel Core 2 duo上,它将在0.6秒内画出约5000像素,包括生成随机RGB值的时间:

from Tkinter import *
import random

def RGBs(num):
 # random list of list RGBs
 return [[random.randint(0,255) for i in range(0,3)] for j in range(0,num)]

def rgb2Hex(rgb_tuple):
    return '#%02x%02x%02x' % tuple(rgb_tuple)

def drawGrid(w,colors):
 col = 0; row = 0
 colors = [rgb2Hex(color) for color in colors]
 for color in colors:
  w.create_rectangle(col, row, col+1, row+1, fill=color, outline=color)
  col+=1
  if col == 100:
   row += 1; col = 0

root = Tk()
w = Canvas(root)
w.grid()
colors = RGBs(5000)
drawGrid(w,colors)
root.mainloop()

尝试2-使用PIL

我知道你只说了TK,但是PIL让这变得简单快捷。

def rgb2Hex(rgb_tuple):
    return '#%02x%02x%02x' % tuple(rgb_tuple)

num = 10000 #10,000 pixels in 100,100 image
colors = [[random.randint(0,255) for i in range(0,3)] for j in range(0,num)]
colors = [rgb2Hex(color) for color in colors]
im = Image.fromstring('RGB',(100,100),"".join(colors))
tkpi = ImageTk.PhotoImage(im)
## add to a label or whatever...
label_image = Tkinter.Label(root, image=tkpi)

有一种更快的纯tkinter方法:

import Tkinter, random
import random

class App:
    def __init__(self, t):
        self.width = 320
        self.height = 200
        self.i = Tkinter.PhotoImage(width=self.width,height=self.height)
        rgb_colors = ([random.randint(0,255) for i in range(0,3)] for j in range(0,self.width*self.height))
        pixels=" ".join(("{"+" ".join(('#%02x%02x%02x' %
            tuple(next(rgb_colors)) for i in range(self.width)))+"}" for j in range(self.height)))
        self.i.put(pixels,(0,0,self.width-1,self.height-1))
        c = Tkinter.Canvas(t, width=self.width, height=self.height); c.pack()
        c.create_image(0, 0, image = self.i, anchor=Tkinter.NW)

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

您可以使用put()绘制一个包含一些颜色数据(字符串)的矩形,在本例中是整个图像。这样你就不需要很贵的回路了。

相关问题 更多 >

    热门问题