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

Python中Tkinter文本编辑器open()函数报错求助

Tkinter记事本打开文件报错问题解决

问题场景

用Tkinter开发记事本样式编辑器,点击菜单栏的「打开」功能选择TXT文件后触发报错,此前使用Anaconda的Jupyter Notebook,现在改用VSCode编写脚本。

报错信息

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\anaconda3\envs\spyder-cf\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "C:\Users\luisc\Desktop\CursoPython\Fase 4 - Temas avanzados\Tema 13 - Interfaces graficas con tkinter\editor.py", line 24, in open
    file = open(rute,'r')
TypeError: open() takes 0 positional arguments but 2 were given

问题分析

  1. 函数名冲突:自定义的open()函数覆盖了从io模块导入的open文件操作函数,导致执行open(rute,'r')时,实际调用的是自己写的无参数open函数,引发参数不匹配错误。
  2. 拼写与参数错误:代码中root.tittle是拼写错误(正确应为root.title),同时FileDialog.askopenfilename的参数filetype应为filetypes,否则会触发参数识别异常。

修复方案

  • 将自定义的打开文件函数改名(比如改为open_file),避免与内置open函数冲突;
  • 修正root.tittle的拼写错误为root.title;
  • 修正askopenfilename的参数名filetype为filetypes。

修复后的完整代码

from tkinter import *
from tkinter import filedialog as FileDialog
from io import open

rute = "" 

def new():
    global rute
    message.set("New File")
    rute = ""
    text.delete(1.0, "end")
    root.title(rute + " - MEditor")  # 修正拼写错误

def open_file():  # 改名避免与内置open冲突
    global rute
    message.set("Open File")
    rute = FileDialog.askopenfilename( 
        initialdir='.',
        filetypes=( ("Text Files", "*.txt"), ),  # 修正参数名filetype为filetypes
        title="Open a text file" )

    if rute != "":
        file = open(rute,'r')
        content = file.read()
        text.delete(1.0,'end')
        text.insert('insert', content)
        file.close()
        root.title(rute + " - MEditor")  # 修正拼写错误

def save():
    message.set("Save File")

def save_as():
    message.set("Save File As...")

root = Tk()
root.title("MEditor")

menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New",command=new)
filemenu.add_command(label="Open",command=open_file)  # 同步修改绑定的函数名
filemenu.add_command(label="Save",command=save)
filemenu.add_command(label="Save As",command=save_as)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(menu=filemenu, label="File")

text = Text(root)
text.pack(fill='both', expand=1)
text.config(bd=0, padx=6, pady=4, font=("Consolas",12))

message = StringVar()
message.set("Welcome to MEditor!")
monitor = Label(root, textvar=message, justify='left')
monitor.pack(side='left')

root.config(menu=menubar)

root.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 22:30:48