You need to enable JavaScript to run this app. Tkinter开发文本编辑器时出现TypeError: 'Button' object is not callable如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter开发文本编辑器时出现TypeError: 'Button' object is not callable如何解决?

报错根因

你在创建打开文件按钮时,将按钮实例的变量名设为了open,直接覆盖了Python原生内置的open()文件读取函数。当open_file回调函数执行到读取文件的f = open(file_location,'r')代码行时,此时代码识别到的open是你实例化的Button对象,而非可调用的文件操作函数,因此抛出'Button' object is not callable报错。

修复方法

仅需修改按钮的变量名,避开Python内置关键字/函数名即可,示例修改后的完整代码如下:

from tkinter import *
from tkinter import filedialog

root = Tk()

root.title("Microsoft Word")

def open_file():
    file_location = ''
    file_location = filedialog.askopenfilename()
    f = open(file_location,'r')
    x = f.read()
    f.close()
    print(x)

heading = Label(text = 'Microsoft Word', font='Helvetica 40 bold')
heading.grid(row = 0,column = 0)

text = Text()
text.grid(row = 1,column = 0)

# 修改变量名 避免覆盖内置open函数
open_btn = Button(text = 'Open',command = open_file)
open_btn.grid(row = 2,column = 0)

save = Button(text = 'Save')
save.grid(row = 3,column = 0)

root.mainloop()
额外注意事项
  • 日常编码中不要使用open、str、int、list这类Python内置类型/函数名作为自定义变量名,避免出现类似的覆盖冲突问题。
  • 文件操作建议使用with上下文管理器写法,无需手动调用close()方法,可避免文件漏关的问题,示例写法:
with open(file_location,'r', encoding='utf-8') as f:
    x = f.read()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 16:45:04