TypeError:'instancemethod'对象在python中是unsubscriptable

时间:2014-11-01 19:14:35

标签: python xbmc

我正在处理我的python脚本以获取按钮列表。我的代码有问题。当我按下键盘的向下箭头按钮时,出现错误:TypeError: 'instancemethod' object is unsubscriptable

错误是跳到这一行:

for channel in channels[page_no*7:page_no*7+7]:

以下是完整代码:

#get actioncodes from keyboard.xml
ACTION_MOVE_LEFT = 1
ACTION_MOVE_RIGHT = 2
ACTION_MOVE_UP = 3
ACTION_MOVE_DOWN = 4
CHANNELS_PER_PAGE = 7

class MyClass(xbmcgui.WindowXML):

     def __new__(cls):
         return super(MyClass, cls).__new__(cls, 'script-tvguide-mainmenu.xml', ADDON.getAddonInfo('path'))


     def __init__(self):
         self._timel = []
         self.thread = None
         self.buttonList=[]
         self.last_page = False


     def All_Channels(self):
         yellow_flag = True
         global __killthread__
         self.getControl(4202).setLabel("0%")
         try:
            # DOWNLOAD THE XML SOURCE HERE
            url = ADDON.getSetting('allchannel.url')
            data = ''
            response = urllib2.urlopen(url)
            meta = response.info()
            file_size = int(meta.getheaders("Content-Length")[0])
            file_size_dl = 0
            block_size = 2048
            while True and not __killthread__:
                mbuffer = response.read(block_size)
                if not mbuffer:
                   break
                   file_size_dl += len(mbuffer)
                   data += mbuffer
                   state = int(file_size_dl * 10.0 / file_size)
                   self.getControl(4202).setLabel(str(state) + '%')
                else:
                    if __killthread__:
                        raise AbortDownload('downloading')
                del response

                # CREATE DATABASE
                profilePath = xbmc.translatePath(os.path.join('special://userdata/addon_data/script.tvguide', 'source.db'))
                if os.path.exists(profilePath):
                    os.remove(profilePath)
                con = database.connect(profilePath)
                cur = con.cursor()
                cur.execute('CREATE TABLE programs(channel TEXT, title TEXT, start_date TIMESTAMP, stop_date TIMESTAMP, description TEXT)')
                con.commit()

                # Get the loaded data
                total_count = data.count('programme')/2
                tv_elem = ElementTree.parse(StringIO.StringIO(data)).getroot()
                cur = con.cursor()
                count = 1
                channels = OrderedDict()

                for channel in tv_elem.findall('channel'):
                    channel_name = channel.find('display-name').text
                    for program in channel.findall('programme'):
                        if __killthread__:
                            raise AbortDownload('filling')
                        title = program.find('title').text
                        start_time = program.get("start")
                        stop_time = program.get("stop")
                        cur.execute("INSERT INTO programs(channel, title, start_date, stop_date)" + " VALUES(?, ?, ?, ?)", [channel_name, title, start_time, stop_time])
                        status = 10 + int(float(count)/float(total_count) * 90.0)
                        self.getControl(4202).setLabel(str(status) + '%')
                        xbmc.sleep(10)
                        count += 1
                    con.commit()
                print 'Channels have been successfully stored into the database!'
                self.getControl(4202).setLabel('100%')
                xbmc.sleep(3000)

                # Set the date and time row
                current_time = time.time() # now (in seconds)
                half_hour = current_time + 60*30  # now + 30 minutes
                one_hour = current_time + 60*60  # now + 60 minutes

                for t in [current_time,half_hour,one_hour]:
                    if (0 <= datetime.datetime.now().minute <= 29):
                        self.getControl(4204).setLabel(time.strftime("%I").lstrip('0') + ':00' + time.strftime("%p"))
                        self.getControl(4205).setLabel(time.strftime("%I").lstrip('0') + ':30' + time.strftime("%p"))
                        self.getControl(4206).setLabel(time.strftime("%I" + ":00%p",time.localtime(t)).lstrip("0"))
                    else:
                        self.getControl(4204).setLabel(time.strftime("%I").lstrip('0') + ':30' + time.strftime("%p"))
                        self.getControl(4205).setLabel(time.strftime("%I" + ":00%p",time.localtime(t)).lstrip("0"))
                        self.getControl(4206).setLabel(time.strftime("%I" + ":30%p",time.localtime(t)).lstrip("0"))


                #Pull the data from the database
                channelList = list()
                database_path = xbmc.translatePath(os.path.join('special://userdata/addon_data/script.tvguide', 'source.db'))

                if os.path.exists(database_path):
                    #get the channels list
                    cur.execute('SELECT channel FROM programs WHERE channel GROUP BY channel')

                    for row in cur:
                        channels = row[0].encode('ascii')
                        channelList.append(channels)
                    # set the channels text
                    for index in range(0, CHANNELS_PER_PAGE):
                        channel = channelList[index]
                        channel_index = index

                        if channel is not None:
                            pass
                            #self.getControl(4207 + index).setLabel(channel)
                            #self.button.setLabel(channel, 'font14', '0xFFFFFFFF', '0xFFFF3300', '0xFF000000')

                        #get the programs list
                        cur.execute('SELECT channel, title, start_date, stop_date FROM programs WHERE channel=?', [channel])
                        programList = list()
                        programs = cur.fetchall()
                        start_pos = 368    # indent for first program

                        for row in programs:
                            program = row[1].encode('ascii'), str(row[2]), str(row[3])
                            title = row[1].encode('ascii')
                            program_start_date = str(row[2])
                            program_end_date = str(row[3])

                            #convert the date formats into minutes
                            minutes_start = self.parseDateTimeToMinutesSinceEpoch(program_start_date)
                            minutes_end = self.parseDateTimeToMinutesSinceEpoch(program_end_date)
                            minutes_length = minutes_end - minutes_start

                            program_length = minutes_length
                            program_notification = program
                            programs_top_backup = 0
                            programs_top = 315
                            program_height = 34.5
                            program_gap = 2.5
                            position_start = start_pos
                            position_top = programs_top + channel_index * (program_height + program_gap)


                            if 10 <= program_length < 60:
                               program_width = 342.5
                            elif 60 <= program_length < 90:
                               program_width = 690
                            elif 90 <= program_length < 105:
                               program_width = 1050
                            elif 105 <= program_length < 120:
                               program_width = 1400
                            elif 120 <= program_length < 150:
                               program_width = 1750
                            elif 150 <= program_length < 180:
                                program_width = 2100
                            elif 180 <= program_length < 210:
                               program_width = 2450
                            elif 210 <= program_length < 240:
                               program_width = 2800
                            elif 240 <= program_length < 270:
                               program_width = 3150
                            elif 270 <= program_length < 300:
                                program_width = 3500
                            elif 300 <= program_length < 330:
                               program_width = 3850
                            elif 330 <= program_length < 360:
                               program_width = 4200
                            elif 360 <= program_length < 390:
                               program_width = 3250
                            elif 390 <= program_length < 420:
                               program_width = 4550
                            elif 420 <= program_length < 450:
                               program_width = 4900
                            elif 450 <= program_length < 480:
                               program_width = 5250

                            start_pos += program_width + 2 * program_gap

                            if program_width > 1:
                                if yellow_flag:
                                    if program_notification:
                                        button_nofocus = 'changelang_yellow.png'
                                        button_focus = 'channels_bar1.png'
                                    else:
                                        button_nofocus = 'changelang_yellow.png'
                                        button_focus = 'channels_bar1.png'
                                    yellow_flag = False
                                    text_color = '0xFF000000'

                                else:
                                    if program_notification:
                                        button_nofocus = 'channels_bar1.png'
                                        button_focus = 'channels_yellow.png'
                                    else:
                                        button_nofocus = 'channels_bar1.png'
                                        button_focus = 'channels_yellow.png'
                                    text_color = '0xFFFFFFFF'

                                if program_width < 1:
                                    program_title = ''
                                else:
                                    program_title = '[B]' + title + '[/B]'


def showepg(self, channels, page_no):
    self.last_page = False
    self.removeControls(self.buttonList)
    self.buttonList = []
    page_no = 0

    self.button = [[0 for x in xrange(20)] for x in xrange(20)]
    self.pdata = [[dict() for x in xrange(20)] for x in xrange(20)]

    row = 0
    for channel in channels[page_no*7:page_no*7+7]:
        #get the list of buttons in array
        print channel
        self.pdata[row][0]['url']   = channel['url']
        self.pdata[row][0]['cname'] = xbmcgui.ControlLabel(0, self.startPos + 17 + (row * row_height), 100, row_height,channel['callSign'])
        self.pdata[row][0]['cicon']  = channel['thumbnail'].replace('\\','')
        self.pdata[row][0]['cimage'] = xbmcgui.ControlImage(100, self.startPos + (row * row_height), logo_width, logo_width,self.pdata[row][0]['cicon'])
        self.buttonList.append(self.pdata[row][0]['cimage'])
        self.buttonList.append(self.pdata[row][0]['cname'])

        events = channel['events']
        col = 0
        coffset = 0
        for event in events:
            try:
                 self.pdata[row][col]['desc'] = '%s - %s\n%s' % (event['startTimeDisplay'], event['endTimeDisplay'], str(event['program']['description']))
             #except:
                 self.pdata[row][col]['desc'] = ""
                 self.pdata[row][col]['duration'] = str(event['duration'])
                 self.pdata[row][col]['eptitle'] = '%s - %s : %s' % (event['startTimeDisplay'], event['endTimeDisplay'], event['eptitle'])

                 cwidth = int((float(event['percentWidth']) / 100) * progs_width)
                 self.button[row][col] = xbmcgui.ControlButton(poffset + coffset, self.startPos + (row * row_height), cwidth, row_height, event['program']['title'])
                 self.buttonList.append(self.button[row][col])
                 coffset = coffset + cwidth
                 col = col + 1
             row =  row + 1

             if row == MAXIMUMROW:
                 break

     self.addControls(self.buttonList)

     if row == 0:
         self.current_page = 0
         self.showepg(channels, 0) # hack to display first page after last page - could be problem for empty epg
         return

     elif row < MAXIMUMROW:
         self.last_page = True

     maxrow = row
     for row in range(maxrow + 1):
         for col in range(20):
             if self.button[row][col] == 0:
                 break
             else:
                 if row < maxrow-1:
                     self.button[row][col].controlDown(self.button[row+1][0])
                 if row == maxrow-1:
                     if maxrow == MAXIMUMROW:
                         self.button[row][col].controlDown(self.button[row][col])
                 if col > 0:
                     self.button[row][col].controlLeft(self.button[row][col-1])
                     self.button[row][col-1].controlRight(self.button[row][col])
                 if row > 0:
                     self.button[row][col].controlUp(self.button[row-1][0])
                 if row == 0:
                     self.button[row][col].controlUp(self.button[row][col])


     self.topRow = True
     self.bottomRow = False
     control = self.button[0][0]
     self.setFocus(control)
     self.updateEpg(control)



def onAction(self, action):
    self.current_page = 0
    self.last_page = False
    if action == ACTION_MOVE_DOWN:
        if allchannels_enabled:
            if self.last_page:
                self.current_page = 0
            else:
                self.current_page += 1
            self.showepg(self.All_Channels, self.current_page)
            return

我不明白错误是什么意思。我在按下向下箭头按钮时尝试使用self.All_Channels定义频道以获取按钮控制。

有谁知道我为什么会收到错误以及如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

错误表示您在不支持它的内容上使用[],可以使用(例如)None[0]重现此内容。

现在,代码中的具体问题似乎是:

self.showepg(self.All_Channels, self.current_page)

这样做,是将函数 self.All_Channels传递给self.showepg函数。这就是为什么你在错误中看到instancemethod可能想要做的事情,就是在这里添加括号:

self.showepg(self.All_Channels(), self.current_page)