當試圖訪問從Python的外部文本文件,我和當試圖簡單地查看該文件的內容,嘗試添加到該文件時遇到了幾個問題,一個變量名保存的文本文件。涉及的程序的一部分需要一個用戶名,並在該用戶名下創建一個文本文件,如果它尚不存在的話。當使用Create()
功能,我遇到以下TypeError
:如何訪問下
Exception in Tkinter callback
Traceback (most recent call last):
File "D:\Python 3.3.2\A Level Computer Science\stackoverflowsolution.py", line 48, in View
with open(userfile, 'r') as u:
FileNotFoundError: [Errno 2] No such file or directory: 'name.txt'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\Python 3.3.2\Python files\lib\tkinter\__init__.py", line 1475, in __call__
return self.func(*args)
File "D:\Python 3.3.2\A Level Computer Science\stackoverflowsolution.py", line 91, in Add
u.write(addText.get())
TypeError: get() missing 1 required positional argument: 'index1'
這是遇到的錯誤代碼:
from tkinter import *
import os
def Login():
global nameEL
global rootA
rootA = Tk()
rootA.title('Login')
intruction = Label(rootA, text='Please Login\n')
intruction.grid(sticky=E)
nameL = Label(rootA, text='Username: ')
nameL.grid(row=1, sticky=W)
nameEL = Entry(rootA)
nameEL.grid(row=1, column=1)
loginB = Button(rootA, text='Login', command=LoggedIn)
loginB.grid(columnspan=2, sticky=W)
rootA.mainloop()
def LoggedIn():
global userfile
roots1 = Tk()
roots1.title('Logged in successfully')
roots1.geometry('300x300')
userfile = nameEL.get() + '.txt'
View1 = Button(roots1, text='View', command=View)
View1.grid(columnspan=10, sticky=W)
View1.pack(fill = 'x')
Create1 = Button(roots1, text='Create', command=Create)
Create1.grid(columnspan=10, sticky=W)
Create1.pack(fill = 'x')
def View():
global userfile
try:
with open(userfile, 'r') as u:
print(u.read())
except FileNotFoundError:
r = Tk()
r.title('View')
r.geometry('300x50')
rlbl = Label(r, text='\n[!] Theres nothing to see here [!]')
rlbl.pack()
r.mainloop()
LoggedIn()
except ValueError:
r = Tk()
r.title('View')
r.geometry('300x50')
rlbl.pack()
r.mainloop()
LoggedIn()
def Create():
global addText
global rootC
rootC = Tk()
rootC.title('Lets add some information')
instruction = Label(rootC, text='Please enter the information you would like to add\n')
instruction.grid(row=0, column=0, sticky=W)
newText = Label(rootC, text='info: ')
newText.grid(row=1, column=0)
addText = Text(rootC)
addText.grid(row=2, column=0)
addButton = Button(rootC, text='Add', command=Add)
addButton.grid(columnspan=2, sticky=W)
addButton.grid(row=3, column=0)
def Add():
global userfile
with open(userfile, 'a') as u:
u.write(addText.get())
u.write('\n')
rootC.destroy()
LoggedIn()
Login()
爲什麼你相信你可以從文件中讀取以追加方式打開? –
'NameError:name'Login'is not defined'from the last line is not a good start。然後,從'userfile = open(nameEL.get()+'.txt','a')'行'nameEr':'nameEL'未被定義。您的示例代碼不可執行。 – martineau