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()
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)
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()
第三次尝试-我发誓是最后一次…
我相信这是最快的纯传统的方式来做到这一点。在列表列表中生成10000个RGB值,创建一个Tkinter.PhotoImage,然后将像素值放入其中。
尝试1-使用create_rectangle方法
我写这个是为了测试。在2.67GHz的Intel Core 2 duo上,它将在0.6秒内画出约5000像素,包括生成随机RGB值的时间:
尝试2-使用PIL
我知道你只说了TK,但是PIL让这变得简单快捷。
有一种更快的纯tkinter方法:
您可以使用put()绘制一个包含一些颜色数据(字符串)的矩形,在本例中是整个图像。这样你就不需要很贵的回路了。
相关问题 更多 >
编程相关推荐