6

操作PhotoImage对象时:

import tkinter as tk

img = tk.PhotoImage(file="myFile.gif")
for x in range(0,1000):
  for y in range(0,1000):
    img.put("{red}", (x, y))

put操作需要很长时间。有没有更快的方法来做到这一点?

4

3 回答 3

7

使用边界框:

from Tkinter import *
root = Tk()
label = Label(root)
label.pack()
img = PhotoImage(width=300,height=300)
data = ("{red red red red blue blue blue blue}")
img.put(data, to=(20,20,280,280))
label.config(image=img)
root.mainloop()
于 2012-05-03T01:00:57.503 回答
4

只需使用命令的to可选参数put()就足够了,无需创建复杂的字符串:

import tkinter as tk
root = tk.Tk()

img = tk.PhotoImage(width=1000, height=1000)
data = 'red'
img.put(data, to=(0, 0, 1000, 1000))
label = tk.Label(root, image=img).pack()

root_window.mainloop()

进一步的观察

我在 PhotoImage 的文档中找不到太多内容,但该to参数比标准循环更有效地缩放数据。这里有一些我会觉得很有帮助的信息,这些信息似乎没有在网上得到很好的记录。

data参数接受一串以空格分隔的颜色值,这些颜色值要么命名为(官方列表),要么是一个 8 位颜色十六进制代码。该字符串表示每个像素要重复的颜色数组,其中具有多种颜色的行包含在花括号中,而列仅以空格分隔。行必须具有相同数量的列/颜色。

acceptable:
3 column 2 row: '{color color color} {color color color}'
1 column 2 row: 'color color', 'color {color}'
1 column 1 row: 'color', '{color}'

unacceptable:
{color color} {color}

如果使用包含空格的命名颜色,则必须用大括号括起来。IE。'{道奇蓝}'

这里有几个示例来说明上述操作,其中需要一个冗长的字符串:

img = tk.PhotoImage(width=80, height=80)
data = ('{{{}{}}} '.format('{dodger blue} ' * 20, '#ff0000 ' * 20) * 20 +
        '{{{}{}}} '.format('LightGoldenrod ' * 20, 'green ' * 20) * 20)
img.put(data, to=(0, 0, 80, 80))

在此处输入图像描述

data = ('{{{}{}}} '.format('{dodger blue} ' * 20, '#ff0000 ' * 10) * 20 +
        '{{{}{}}} '.format('LightGoldenrod ' * 20, 'green ' * 10) * 10)

在此处输入图像描述

于 2018-08-23T22:19:01.263 回答
2

尝试构造一个二维颜色数组并put使用该数组作为参数进行调用。

像这样:

import tkinter as tk

img = tk.PhotoImage(file="myFile.gif")
# "#%02x%02x%02x" % (255,0,0) means 'red'
line = '{' + ' '.join(["#%02x%02x%02x" % (255,0,0)] * 1000) + '}'
img.put(' '.join([line] * 1000))
于 2012-05-02T17:20:16.447 回答