我希望比较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'
答案 0 :(得分:3)
只需通过str()将pxcolor转换为字符串即可进行比较
from PIL import ImageGrab
import threading
cc = "(45, 42, 46)"
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=str(pixel[x,y])
print(pxcolor)
if pxcolor == cc:
print("same")
getcol()
根据Kevin的建议,在一开始将cc变量设为元组
from PIL import ImageGrab
import threading
cc = (45, 42, 46)
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()
答案 1 :(得分:0)
cc是一个str,而pxcolor是一个元组
您需要将cc更改为元组,或将pxcolor更改为字符串,然后检查==
语句:
要字符串化的元组
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 str(pxcolor) == cc:
print("same")
要元组的字符串
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)
elements = cc[1:-1].split(",")
tuple_cc = [ int(x) for x in elements ]
mytuple = tuple(tuple_cc)
if pxcolor == mytuple:
print("same")