Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么Photoimage放得慢?_Python_Tkinter - Fatal编程技术网

Python 为什么Photoimage放得慢?

Python 为什么Photoimage放得慢?,python,tkinter,Python,Tkinter,操作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操作需要很长时间。有更快的方法吗?尝试构建一个二维颜色数组,并使用该数组作为参数调用put 像这样: import tkinter as tk img = tk.Pho

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

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

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()
命令的
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
参数接受一个以空格分隔的颜色值字符串,这些值可以是命名的(),也可以是一个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}
如果使用包含空格的命名颜色,则必须将其用大括号括起来。例如{道奇蓝}

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

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


我想说的是,可能不仅仅是
put()
调用很慢,而且您正在执行嵌套for循环(1000^2),这非常慢。但是@soulcheck为您提供了正确的答案。意识到这个答案很古老,但您能否解释一下如何使用
“{red red red blue blue}”
作为数据输入来创建颜色列?解决了这个问题,谢谢!如果其他人遇到这个问题,有一个类似的问题,可以很好地解释。@JetBlue:很遗憾,你的链接已经失效了:(@PhoemueX这里有一个我喜欢这个答案。为我省去了很多麻烦。我确实觉得重复有点混乱,因为我想更新图像中的每个像素。我制作了一个演示,演示了如何使用
put
to=
逐像素更新图像。
data = ('{{{}{}}} '.format('{dodger blue} ' * 20, '#ff0000 ' * 10) * 20 +
        '{{{}{}}} '.format('LightGoldenrod ' * 20, 'green ' * 10) * 10)