我正在制作一个程序,用于打印图像中像素的颜色值,并引用chenlian's answer to a question here来读取RGB值。我将程序的这一部分隔离到一个不同的文件中进行测试。
pic = "H://fourpxtest.png"
from tkinter import *
def getRGB(image, x, y):
value = image.get(x, y)
return tuple(map(int, value.split(" ")))
getRGB(pic, 1, 1)
就是我现在所拥有的一切。运行它返回
Traceback (most recent call last):
File "H:/tzrtst.py", line 6, in <module>
getRGB(pic, 1, 1)
File "H:/tzrtst.py", line 4, in getRGB
value = image.get(x, y)
AttributeError: 'str' object has no attribute 'get'
image
应该是什么?我已经尝试将image
替换为pic
变量,并将pic
替换为image
,但这没有任何区别。图像可以像我一样的文件路径吗?
答案 0 :(得分:1)
图片必须是PhotoImage的实例,而不是文件名http://effbot.org/tkinterbook/photoimage.htm
import sys
if sys.version_info[0] < 3:
import Tkinter as tk ## Python 2.x
else:
import tkinter as tk ## Python 3.x
grape_gif='''\
R0lGODlhIAAgALMAAAAAAAAAgHCAkC6LV76+vvXeswD/ANzc3DLNMubm+v/6zS9PT6Ai8P8A////
/////yH5BAEAAAkALAAAAAAgACAAAAS00MlJq7046803AF3ofAYYfh8GIEvpoUZcmtOKAO5rLMva
0rYVKqX5IEq3XDAZo1GGiOhw5rtJc09cVGo7orYwYtYo3d4+DBxJWuSCAQ30+vNTGcxnOIARj3eT
YhJDQ3woDGl7foNiKBV7aYeEkHEignKFkk4ciYaImJqbkZ+PjZUjaJOElKanqJyRrJyZgSKkokOs
NYa2q7mcirC5I5FofsK6hcHHgsSgx4a9yzXK0rrV19gRADs=
'''
def getRGB(image, x, y):
value = image.get(x, y)
return value
master=tk.Tk()
master.geometry("300x500")
## uses data= instead of file= because the picture
## is data within this program
photo=tk.PhotoImage(data=grape_gif)
print getRGB(photo, 10, 10)