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

Python tkinter报错:'int'对象无'cget'属性 求解决

解决Tkinter中AttributeError: 'int' object has no attribute 'cget'错误

错误原因

核心问题出在path_text变量的定义上:canvas.create_text()方法返回的是一个整数ID(用于标识画布上的文本元素),而非Tkinter的Widget对象。所以当你调用path_text.cget("text")或path_text.config(text=path)时,本质是在给整数调用Widget的方法,自然会抛出AttributeError。

解决方法

方法1:使用Canvas的元素操作方法(推荐,贴合现有代码结构)

直接通过Canvas对象来操作文本元素的属性,修改以下两个函数:

def select_path():
    path = filedialog.askdirectory()
    # 用canvas.itemconfig替代path_text.config
    canvas.itemconfig(path_text, text=path)

def download_video():
    get_link = url_entry.get()
    # 用canvas.itemcget替代path_text.cget
    user_path = canvas.itemcget(path_text, "text")
    screen.title("Lädt herunter...")
    mp4_video= YouTube(get_link).streams.get_highest_resolution().download()
    clip = VideoFileClip(mp4_video)
    clip.close()

    shutil.move(mp4_video, user_path)
    screen.title("Download abgeschlossen!")

方法2:改用Label组件替代画布文本

如果更习惯使用标准Widget的config和cget方法,可以创建一个Label组件,再嵌入到画布中:

  1. 替换原来的path_text = canvas.create_text(...)代码:
# 创建Label组件,注意bg要匹配画布背景色以保证视觉统一
path_text = Label(screen, text="Wähle einen Speicherort", font=("Agency FB", 16), fg="white", bg="#你的画布背景色")
# 将Label嵌入画布指定位置
canvas.create_window(250, 330, window=path_text)
  1. 此时原来的select_path和download_video函数中的代码无需修改,可正常使用path_text.config()和path_text.cget()。

额外优化建议

  • 代码中重复导入了from tkinter import *,可删除其中一行,避免冗余。
  • 使用moviepy的VideoFileClip后,会自动处理文件关闭,clip.close()可以省略。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 07:15:36