You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

拆分TabControl后出现AttributeError: 'NoneType'无iloc属性问题求助

问题解决:AttributeError: 'NoneType' object has no attribute 'iloc'

问题根源

你在all_titles函数中使用global df试图共享DataFrame,但这个写法在类的__init__方法内部的嵌套函数中不生效。df实际是__init__里定义的局部变量,global声明会让它指向模块级的全局变量,而非你期望的那个DataFrame。当content函数访问df时,拿到的是__init__初始化的df = None,而非all_titles中赋值的DataFrame。

解决方案

把df改成Page1类的实例属性,用self.df统一访问,替换所有相关引用:

  1. 初始化实例属性:在__init__方法末尾,把df = None改为:
self.df = None
  1. 修改all_titles函数:去掉global df声明,所有df替换为self.df:
def all_titles():
    allnews = []
    new = []

    for place in ['name1', 'name2']:         
        results = get(place)
        allnews += results
        text_download.insert('end', f"search: {place}\nfound: {len(results)}\n")

        for place in ['name1']:
            for sublist in allnews:
                for item in sublist:
                    if "Name1" in item:
                        new += [sublist]

        for place in ['name2']:
            for sublist in allnews:
                for item in sublist:
                    if "Name2" in item:
                        new += [sublist]

    self.df = pd.DataFrame(new, columns=['date', 'time', 'place', 'title', 'news', 'link'])
    self.df = self.df.sort_values(by=['date', 'time', 'place', 'title'], ascending=[False, False, True, True])
    self.df = self.df.drop_duplicates(subset=['date', 'time', 'place', 'title'])
    self.df = self.df.reset_index(drop=True)

    listbox_title.delete('0', 'end')

    for index, row in self.df.iterrows():
        for place in ['name1']:
             if "Example" in row['news']:          
                 listbox_title.insert('end', row['news'])
  1. 修改content函数:将df替换为self.df,并增加self.df is not None的判断避免报错:
def content(event=None): 
    selection = listbox_title.curselection()
    print('selection:', selection)

    if selection and self.df is not None:
        item = self.df.iloc[selection[-1]]
        url = item['link']

        headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'
        }

        session = requests_cache.CachedSession('titles')
        response = session.get(url, headers=headers)
        soup = BeautifulSoup(response.content, 'html.parser')

        content_download = "\n".join(item.get_text() for item in soup.select("div.text.mbottom"))

        text_download.delete('1.0', 'end')
        text_download.insert('end', content_download)

原理说明

类的实例属性self.df在类的所有方法和嵌套函数中都能正确共享,不会出现作用域混淆的问题。原来的global写法在类内部会导致变量指向错误的作用域,这也是单文件能运行、拆分后失效的核心原因。

内容的提问来源于stack exchange,提问作者Evangelos Dellas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 04:55:03