我写了这段代码,控制台出错了,我尝试了几种无法解决的方法,请您解释一下我的错误在哪里。谢谢
import os
os.chdir(r"C:\Users\Umer Selmani\Desktop\prog.practice\MP1")
import csv
with open('FoodDB.csv','r') as FDB:
file = csv.reader(FDB)
for line in file:
print(line)
from tkinter import *
class Diet:
def __init__(self):
self.Left = Frame(root,width= 250,height=200,bg='salmon')
self.Left.pack(side=LEFT,pady=5)
self.labelrdL=Label(self.Left, text="Food Menu").grid(row=0)
self.listboxrdL=Listbox(self.Left,width=30).grid(row=1)
for q in file:
self.listboxrdL.insert(END,q)
self.buttonrdL=Button(self.Left, text="Continue",bg="red").grid(row=2)
root = Tk()
diet = Diet() # Create an instance of Diet.
root.mainloop()
在这里有错误,
Traceback (most recent call last):
File "C:/Users/Umer Selmani/.PyCharmEdu2018.2/config/scratches/scratch_3.py", line 26, in <module>
diet = Diet() # Create an instance of Diet.
File "C:/Users/Umer Selmani/.PyCharmEdu2018.2/config/scratches/scratch_3.py", line 21, in __init__
for q in file:
ValueError: I/O operation on closed file.
Process finished with exit code 1
答案 0 :(得分:1)
“打开状态”会自动关闭文件。因此,您会收到错误消息。
尝试使用with open('FoodDB.csv','r') as FDB:
代替FDB = open('FoodDB.csv','r')
完成操作后,别忘了手动关闭文件。
FDB.close()
完整解决方案应如下所示:
import os
os.chdir(r"C:\Users\Umer Selmani\Desktop\prog.practice\MP1")
import csv
FDB = open('FoodDB.csv','r')
file = csv.reader(FDB)
#for line in file:
#print(line)
from tkinter import *
class Diet:
def __init__(self):
self.Left = Frame(root,width= 250,height=200,bg='salmon')
self.Left.pack(side=LEFT,pady=5)
self.labelrdL=Label(self.Left, text="Food Menu").grid(row=0)
self.listboxrdL=Listbox(self.Left,width=30).grid(row=1)
for q in file:
self.listboxrdL.insert(END,q)
self.buttonrdL=Button(self.Left, text="Continue",bg="red").grid(row=2)
root = Tk()
diet = Diet() # Create an instance of Diet.
root.mainloop()
答案 1 :(得分:1)
您需要在此处进行一些操作。
您应遵循PEP8准则来命名变量。在文件开头定义所有导入。最后也是最重要的一点是,在更新列表框时,应使用with open
语句。请记住,with open
语句结束后,与open
并置的with
将自动关闭文件。
此外,这里self.listboxrdL = Listbox(self.Left,width=30).grid(row=1)
的这一行将阻止您将信息添加到列表框中。
通过执行以下操作,确保在新行上使用几何图形管理器以防止出现问题:
self.listboxrdL = Listbox(self.Left,width=30)
self.listboxrdL.grid(row=1)
代码:
import os
import csv
import tkinter as tk
os.chdir(r"C:\Users\Umer Selmani\Desktop\prog.practice\MP1")
class Diet:
def __init__(self):
self.left = tk.Frame(root, width=250, height=200, bg='salmon')
self.left.pack(side="left", pady=5)
tk.Label(self.left, text="Food Menu").grid(row=0)
self.listbox_rdl = tk.Listbox(self.left, width=30)
self.listbox_rdl.grid(row=1)
with open('FoodDB.csv', 'r') as fdb:
file = csv.reader(fdb)
for q in file:
self.listbox_rdl.insert("end", q)
tk.Button(self.left, text="Continue", bg="red").grid(row=2)
root = tk.Tk()
diet = Diet()
root.mainloop()