比较两个字符串变量,如果它们相同则做某事

Compare Two String Variables, Do Something If They Are The Same

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

只需要通过 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 是一个字符串,而 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")