【发布时间】:2019-01-25 14:54:58
【问题描述】:
我希望比较 Python 中的两个字符串变量,如果它们相同,则打印 same。不幸的是,我无法让它工作,same 永远不会被打印出来。我的一个字符串只是一个简单的变量,而另一个是来自 ImageGrab 模块的 RGB 输出。
代码如下:
from PIL import ImageGrab
import threading
cc = "(255, 255, 255)"
def getcol():
global pxcolor
threading.Timer(0.5, getcol).start()
pixel=ImageGrab.grab((960,540,961,541)).load()
for y in range(0,1,1):
for x in range(0,1,1):
pxcolor=pixel[x,y]
print(pxcolor)
if pxcolor == cc:
print("same")
getcol()
我尝试过使用pxcolor = pxcolor.strip(),但这返回了这个错误:
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Users\mikur\Python\Python37-32\lib\threading.py", line 917, in _bootstrap_inner
self.run()
File "C:\Users\mikur\Python\Python37-32\lib\threading.py", line 1158, in run
self.function(*self.args, **self.kwargs)
File "C:\Users\mikur\Desktop\tye.py", line 14, in getcol
pxcolor = pxcolor.strip()
AttributeError: 'tuple' object has no attribute 'strip'
【问题讨论】:
-
我不熟悉这个库,但是你确定 pxcolor 是一个字符串吗?你能检查一下
type(pxcolor)吗?看起来它可能是一个元组。 -
pxcolor 是一个 tuple (错误信息很清楚)。您的比较永远不会评估为 True。尝试
cc = (255, 255, 255)(将其声明为 tuple,not string)。或者(跛脚)其他方式:if str(pxcolor) == cc: -
是的,对于新手的错误,我们深表歉意。
标签: python string variables python-imaging-library rgb