比较两个字符串变量,如果它们是Sam

2024-09-28 21:56:00 发布

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

我希望比较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'

Tags: 字符串inpyimportselflineusersfile
2条回答

只需要通过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()

cc是str,pxcolor是tuple

您需要将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")

相关问题 更多 >