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

如何在Python与Tkinter中拼接变量名与循环变量?

问题解决:循环拼接变量名调用对象方法报错

错误原因

你当前代码里的temp_var只是拼接出来的字符串(比如"self.date_label_call_0"),并不是指向self上实际存在的标签对象。字符串类型没有config方法,所以会抛出AttributeError: 'str' object has no attribute 'config'错误。

解决方案

方法1:使用getattr()函数获取对象属性

getattr()可以通过字符串形式的属性名,直接获取对象上对应的属性。修改代码如下:

def get_or_refresh_call_list(self, event=None): 
            
    #get dates
    call_dates_webElements = self.get_elements(self.call_dates)
        
    for i in range(len(call_dates_webElements)):
        # 用i+1得到1开头的变量名,匹配你的预期
        temp_var = getattr(self, f'date_label_call_{i+1}')
        temp_var.config(text=call_dates_webElements[i].text)

getattr(self, '属性名')等价于直接写self.属性名,这样就能拿到实际的标签对象,正常调用config方法。

方法2:提前将标签存入列表(更推荐)

如果可以提前把所有需要操作的标签整理到一个列表里,代码会更清晰易维护:

# 初始化时把标签存入列表
self.date_label_calls = [
    self.date_label_call_1,
    self.date_label_call_2,
    self.date_label_call_3
    # 按顺序添加所有标签
]

def get_or_refresh_call_list(self, event=None): 
            
    #get dates
    call_dates_webElements = self.get_elements(self.call_dates)
        
    for i in range(len(call_dates_webElements)):
        self.date_label_calls[i].config(text=call_dates_webElements[i].text)

这种方式避免了字符串拼接,代码可读性和稳定性更好。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 22:15:36