我用Python编程, 但我想用tkinter制作我的文本编辑器
所以我看了一个教程,但它没有用。 这是代码
from tkinter import *
from tkinter import filedialog
filename = None
def newFile():
global filename
filename = "Untitled"
text.delete(0.0, END)
def saveFile():
global filename
t = text.get(0.0, END)
f = open(filename, 'w')
f.write(t)
f.close()
def saveAs():
f = asksaveasfile(mode='w', defaultextension='.txt')
t = text.get(0.0, END)
try:
f.write(t.rstrip())
except:
showerror(title="Oops!", message="Error had been finded. Please try it again")
def openFile():
f = askopenfile(mode='f')
t = f.read
text.delete(0.0, END)
text.insert(0.0, t)
root = Tk()
root.title("STE v.alpha")
root.minsize(width=400, height=400)
root.maxsize(width=400, height=400)
text = Text(root, width=400, height=400)
text.pack()
menubar = Menu(root)
filemenu = Menu(menubar)
filename.add_command(label="New", add_comand=newFile)
filename.add_command(label="Open", add_comand=openFile)
filename.add_command(label="Save As...", add_comand=saveAs)
filemenu.addsperator()
filemenu.add_command(label="Quit", command=root.quit)
menubar.add_cascade(filemenu)
root.config(menu=menubar)
root.mainloop()
但错误是
Traceback (most recent call last):
File "C:/Users/superjoy/Desktop/programming/print/memojang.py", line 42, in <module>
filename.add_command(label="New", add_comand=newFile)
AttributeError: 'NoneType' object has no attribute 'add_command'
我该如何解决这个问题? add_command也改变了什么?
答案 0 :(得分:1)
您正在创建filemenu
:
filemenu = Menu(menubar)
然后在您发布的代码顶部使用设置为filename
的{{1}},这就是为什么它被报告为None
类型的原因:
NoneType
尝试将这些filename.add_command(label="New", add_comand=newFile)
filename.add_command(label="Open", add_comand=openFile)
条目重命名为filename
。
从文档中,filemenu
也没有采用名为add_command
的参数,但确实需要一个名为add_comand
答案 1 :(得分:-1)
太多错别字&amp;错误。我设法以某种方式修复它们......
1c1
< from tkinter import *
---
> from tkinter import *
2a3
> from tkinter.filedialog import asksaveasfile, askopenfile
5a7
>
10a13
>
17a21
>
24c28,29
< showerror(title="Oops!", message="Error had been finded. Please try it again")
---
> showerror(title="Oops!", message="Error had been finded. Please try "
> "it again")
26,30c31,36
< def openFile():
< f = askopenfile(mode='f')
< t = f.read
< text.delete(0.0, END)
< text.insert(0.0, t)
---
>
> def openFile():
> f = askopenfile(mode='f')
> t = f.read
> text.delete(0.0, END)
> text.insert(0.0, t)
42,45c48,51
< filename.add_command(label="New", add_comand=newFile)
< filename.add_command(label="Open", add_comand=openFile)
< filename.add_command(label="Save As...", add_comand=saveAs)
< filemenu.addsperator()
---
> filemenu.add_command(label="New", command=newFile)
> filemenu.add_command(label="Open", command=openFile)
> filemenu.add_command(label="Save As...", command=saveAs)
> filemenu.add_separator()
47c53
< menubar.add_cascade(filemenu)
---
> menubar.add_cascade(label="File", menu=filemenu)