将整数添加到字符串后在类中使用它时会出错

时间:2016-12-20 20:41:14

标签: python raspberry-pi3

import pigpio
import time
pi = pigpio.pi()
L1 = 2
L2 = 3
L3 = 4
L4 = 17
L5 = 27
L6 = 22
L7 = 10
R1 = 9
R2 = 18
R3 = 23
R4 = 24
R5 = 25
R6 = 8
R7 = 7
On = 255
Off = 0
sleepTime = 0.05
class ledControll:
    def pinClean(self):
        pi.set_PWM_dutycycle(L1 , Off)
        pi.set_PWM_dutycycle(L2 , Off)
        pi.set_PWM_dutycycle(L3 , Off)
        pi.set_PWM_dutycycle(L4 , Off)
        pi.set_PWM_dutycycle(L5 , Off)
        pi.set_PWM_dutycycle(L6 , Off)
        pi.set_PWM_dutycycle(L7 , Off)
        pi.set_PWM_dutycycle(R1 , Off)
        pi.set_PWM_dutycycle(R2 , Off)
        pi.set_PWM_dutycycle(R3 , Off)
        pi.set_PWM_dutycycle(R4 , Off)
        pi.set_PWM_dutycycle(R5 , Off)
        pi.set_PWM_dutycycle(R6 , Off)
        pi.set_PWM_dutycycle(R7 , Off)  
    def LEDOn(self , column , rows):
        pi.set_PWM_dutycycle(column , On)
        pi.set_PWM_dutycycle(rows , On)
    def LEDOff(self , column , row):
        pi.set_PWM_dutycycle(column , Off)
        pi.set_PWM_dutycycle(row , Off)
try:
    led = ledControll()
    while True:
        for i in range(1 , 7):
            row = "R" + str(i)
            led.LEDOn(L1 , row)
except KeyboardInterrupt:
    led.pinClean()
pi.stop()

这是我在python中的代码,当我运行这个时我收到此错误: struct.error:无法将参数转换为整数 我想将R1设置为R7,其中for为in.LEDOn(L1,R1至R7) 当我打印行时,它给我R1到R7 我是python中的新手

1 个答案:

答案 0 :(得分:2)

row = "R" + str(i)不会导致row引用名称以“R”开头的任何变量。当您需要执行led.LEDOn(L1, "R1")时,您实际上正在led.LEDOn(L1, R1)

您可能会想,“好的,那么如果给出一个包含其名称的字符串,我该如何获取变量呢?”问题How do I create a variable number of variables?中详细介绍了这一点,但简短的回答是:没有一堆只有数字不同的变量;改为使用字典或列表。

在您的具体情况下,您可能会执行类似

的操作
Rs = [9, 18, 23, 24, 25, 8, 7]

在文件的顶部,然后

for R in Rs:
    led.LEDOn(L1, R)

在你的功能中。

这样做的另一个好处是可以缩短pinClean方法:

def pinClean(self):
    for L in Ls:
        pi.set_PWM_dutycycle(L, Off)
    for R in Rs:
        pi.set_PWM_dutycycle(R, Off)

(...如果您还决定将L变量放入列表中)