Problem with open() function with tkinter in python

Viewed 27

I'm doing a python course and I'm learning to use tkinter here, and as part of the course they send me to make a text editor (a notepad), and I'm defining the functions of the menubar, but in the open one at the time of opening a file (obviously txt) gives me this error, could someone please help me, anyway... Thanks in advance.

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()

throws me this error

    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

It should be said that I used anaconda for the jupyter notebook but to write scripts I am now using VSCode.

1 Answers

You named your own function open, shadowing the definition of the built-in open with a global scope definition (global scope names are always found before built-in names, you only find the latter if the former doesn't exist). Don't name-shadow built-ins, it only leads to pain.

Change:

def open():

to some other name and change all the places that call it to match.

A list of the built-ins can be found in the docs here: https://docs.python.org/3/library/functions.html

Related