You need to enable JavaScript to run this app. Python Tkinter报错'NoneType' object has no attribute 'config'如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Python Tkinter报错'NoneType' object has no attribute 'config'如何解决

Tkinter代码商店程序报错修复方案

报错根因

  • Tkinter的布局方法(grid/pack/place)返回值为None,你将组件创建和布局逻辑写在同一行并赋值给变量,导致变量实际是None值,调用config方法时触发AttributeError
  • 代码存在拼写错误,部分位置将方法名config错写为cofig
  • 原有逻辑每次点击购买都会重复创建Label组件,同一位置叠加多个组件会导致性能和显示异常

修复步骤

步骤1:修改初始数量Label的定义,保留组件引用

将原来的数量Label创建和布局拆分为两行,保存Label对象供后续修改属性:

# **** Amount of Code ****
phy_global = 0
c_plus_global = 0
java_global = 0
scratch_global = 0

# 拆分组件创建与布局调用,保留Label对象引用
phy_amount_label = Label(middle_frame, text="/")
phy_amount_label.grid(row=1, column=2)

c_plus_amount_label = Label(middle_frame, text="/")
c_plus_amount_label.grid(row=2, column=2)

java_amount_label = Label(middle_frame, text="/")
java_amount_label.grid(row=3, column=2)

scratch_amount_label = Label(middle_frame, text="/")
scratch_amount_label.grid(row=4, column=2)

步骤2:重写buying函数,优化逻辑并修正错误

不需要每次购买都新建Label,直接修改已有Label的text属性即可,同时修正拼写错误:

def buying():
    code_to_buy = selected_code.get()
    if code_to_buy == "1":
        global phy_global
        phy_global += 1
        phy_amount_label.config(text=phy_global)
    elif code_to_buy == "2":
        global c_plus_global
        c_plus_global += 1
        c_plus_amount_label.config(text=c_plus_global)
    elif code_to_buy == "3":
        global java_global
        java_global += 1
        java_amount_label.config(text=java_global)
    elif code_to_buy == "4":
        global scratch_global
        scratch_global += 1
        scratch_amount_label.config(text=scratch_global)

可选优化

如果你的本地不存在图标文件c:/GUIs_Images/root_img.png,可以暂时注释掉图标相关的两行代码,避免启动报错。


内容的提问来源于stack exchange,提问作者Mr.Kuchenversum

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 05:45:07