我无法将值插入tkinter列表框

2024-10-01 13:42:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我写这段代码是为了在我打开一个文件时将数据实现到Listbox,虽然有AttributeError,但我无法理解如何修复这个错误

from Tkinter import *
import tkFileDialog
import csv
from imdb import IMDb


class STproject:

    def __init__(self,app): #1

        self.mlb=LabelFrame(app, text='Movie Recommendation Engine')
        self.mlb.grid()
        self.lframe3=LabelFrame(self.mlb,text="Movies/Users",background='purple')
        self.lframe3.grid(row=0,column=1)
        self.framebutton=Frame(self.mlb,background='pink',height=50,width=50)
        self.framebutton.grid(row=0,column=0)

        self.buttonsnlabels()

    def buttonsnlabels(self):

        self.ratingbutton=Button(self.framebutton,text='Upload Rating',command=lambda :self.file2())
        self.ratingbutton.grid()
        self.lb1 = Listbox(self.lframe3)
        self.lb1.grid()
        self.lb1.insert(self.emp2) //self.emp2 its locally ?

    def file2(self):
        umovies=tkFileDialog.askopenfilename()
        f=open(umovies)
        self.emp2=[]
        self.csv_file2 = csv.reader(f)
        for line2 in self.csv_file2:
            self.emp2.append(line2[2])

root=Tk()
root.title()
application=STproject(root)
root.mainloop()

这里是完整的错误:

Traceback (most recent call last):
  File "C:/Users/Umer Selmani/Desktop/voluntarily/Voluntiraly.py", line 846, in <module>
    application=STproject(root)
  File "C:/Users/Umer Selmani/Desktop/voluntarily/Voluntiraly.py", line 814, in __init__
    self.a=self.emp2[1]
AttributeError: STproject instance has no attribute 'emp2'

Tags: csvtextimportselfdefrootusersgrid
1条回答
网友
1楼 · 发布于 2024-10-01 13:42:25

出现此错误是因为.insert(self.emp2)是在创建按钮之后执行的,而不是在用户单击按钮之后执行的。现在你还没有self.emp2,你可以稍后在file2()中创建它

必须在file2()中使用.insert(self.emp2)

编辑:您必须使用insert insidefor循环并分别添加每个项

            self.lb1.insert('end', line2[2])

如果以后不需要,可以跳过self.emp2

或者您必须使用*将列表中的项目放在分隔的行中

self.lb1.insert('end', *self.emp2)

代码

def buttonsnlabels(self):

        self.ratingbutton = Button(self.framebutton, text='Upload Rating', command=self.file2)
        self.ratingbutton.grid()

        self.lb1 = Listbox(self.lframe3)
        self.lb1.grid()


def file2(self):
        #self.emp2 = []

        umovies = tkFileDialog.askopenfilename()

        f = open(umovies)
        self.csv_file2 = csv.reader(f)

        for line2 in self.csv_file2:
            #self.emp2.append(line2[2])
            self.lb1.insert('end', line2[2])

        #self.lb1.insert('end', *self.emp2)

相关问题 更多 >