【问题标题】:I fail to insert the values to tkinter listbox我无法将值插入 tkinter 列表框
【发布时间】:2019-07-21 09:45:47
【问题描述】:

我已经写了这段代码来实现打开文件时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'

【问题讨论】:

  • 你可以使用command=self.file2
  • .insert(self.emp2) 在按钮创建后执行,而不是在用户单击按钮后执行。你必须在file2()中使用.insert(self.emp2)

标签: python python-2.7 tkinter


【解决方案1】:

您遇到此错误是因为您的 .insert(self.emp2) 在按钮创建后执行,而不是在用户单击按钮后执行。而此时您还没有self.emp2 - 您稍后在file2() 中创建它。

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

编辑:您必须在 for 循环中使用插入并单独添加每个项目

            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)

【讨论】:

  • 你能帮我看看如何只实现某列的前 5 行吗?
  • 我应该将值附加到空列表中,然后从列表中插入,还是有任何方法不将值附加到空列表中?
  • 在答案中查看file2 中的代码 - 跳过注释行 - 它直接附加到列表框而不使用空列表。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多