繁体   English   中英

python 中的 open() function 与 tkinter 的问题

[英]Problem with open() function with tkinter in python

我正在学习 python 课程,我正在学习在这里使用 tkinter,作为课程的一部分,他们让我制作一个文本编辑器(记事本),我正在定义菜单栏的功能,但是在在打开文件时打开一个文件(显然是 txt)给我这个错误,有人可以帮助我,无论如何......提前谢谢。

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.tittle(rute + " - MEditor")

def open():
    global rute
    message.set("Open File")
    rute = FileDialog.askopenfilename( 
        initialdir='.',
        filetype=( ("Text Files", "*.txt"), ),
        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.tittle(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)
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()

向我抛出这个错误

    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

应该说我用anaconda做jupyter notebook,但是写脚本我现在用的是VSCode。

您将自己的 function open命名为 open ,使用全局 scope 定义隐藏内置open的定义(全局 scope 名称总是在前者不存在的情况下找到)。 不要命名阴影内置插件,它只会导致痛苦。

改变:

def open():

更改为其他名称并更改所有调用它的位置以匹配。

可以在此处的文档中找到内置列表: https://docs.python.org/3/library/functions.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM