簡體   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