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

7 投票
2 回答
13011 浏览
提问于 2025-04-15 15:08

这里有个问题。我想把一个特定的向量场显示成位图。关于这个显示方式我已经没问题了,因为我已经有了一些RGB颜色列表的矩阵,比如[255,255,115]。但是我不知道怎么把它画到屏幕上。到目前为止,我是用成千上万的1像素的彩色小方块来画,但这样做太慢了。我相信还有更好的方法来绘制位图。

2 个回答

6

这里有一个更快的纯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()来绘制一个带有颜色数据(字符串)的矩形,在这个例子中就是整个图像。这样你就不需要使用循环了,因为循环会消耗很多资源。

14

尝试 3 - 我发誓这是最后一次...

我认为这是用TK做这件事最快的方法。它会生成一个包含10,000个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方法

我写这个是为了测试。在我的Intel Core 2 duo,2.67 GHz的电脑上,它大约需要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)

撰写回答