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

Tkinter运行报错AttributeError: 'str' object has no attribute 'items'如何解决?

报错原因

Tkinter所有控件的构造函数规则为:第一个参数是父容器对象,之后所有的属性配置参数必须以关键字参数形式传入,或者传入一个包含配置键值对的字典。
你代码中else分支创建badLabel时,直接将字符串"Bad!"作为第二个位置参数传入Label构造函数,Tkinter内部会默认将这个位置参数识别为配置字典,尝试调用其items()方法遍历配置项,字符串对象没有items属性,因此触发该报错。

修复方法

对齐正确的goodLabel写法,给传入的文本加上text关键字声明即可。另外你提供的原始代码缺失主循环启动逻辑,同时可以补充旧提示清理逻辑,避免多次点击后提示重叠,修正后的完整代码如下:

from tkinter import *

root = Tk()

e = Entry(root)
e.grid(row=0, column=0)

def buttonclick():
    # 清空上一次的提示内容
    for widget in root.grid_slaves(row=3, column=0):
        widget.destroy()
    if e.get() == "12345":
        goodLabel = Label(root, text="Good!")
        goodLabel.grid(row=3, column=0)
    else:
        # 补充缺失的text关键字参数
        badLabel = Label(root, text="Bad!")
        badLabel.grid(row=3, column=0)

button = Button(root, text="Submit", command=buttonclick)
button.grid(row=2, column=0)

root.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 08:54:03