为什么照片放得慢?

2024-05-22 00:45:55 发布

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

操作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操作需要很长时间。有没有更快的方法?在


Tags: 对象inimportimgforputtkinteras
3条回答

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

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参数接受一个空格分隔的颜色值字符串,这些值要么命名为(official list),要么是一个8位颜色十六进制代码。字符串表示每像素要重复的颜色数组,其中具有多个颜色的行包含在大括号中,列仅以空格分隔。行必须具有相同数量的列/颜色。在

^{pr2}$

如果使用包含空格的命名颜色,它必须用大括号括起来。即‘{道奇蓝}’

下面是几个示例来说明上述操作,其中需要一个长字符串:

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

enter image description here

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

enter image description here

使用边界框:

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

尝试构造一个二维颜色数组,并使用该数组作为参数调用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))

相关问题 更多 >