使用来自其他类的条目将项添加到列表框

时间:2015-03-27 01:13:19

标签: linux forms python-2.7 oop tkinter

我创建了两个类,一个在People.py(将是父类),其中包含一个列表框,可以通过打开文件并逐行向列表框添加内容来填充。

另一个类位于Names.py(我希望它是子类),其中包含名字,姓氏和标题的组合框,应该(一旦问题/问题得到解答就会实现) )进入主窗口中列为People的列表。我正在尝试使用OOP模型。现在,它不完全是OOP,但我稍后会重构代码。

我之前尝试发布此代码,但由于缩进问题,人们无法运行它,所以我提供了这些类的链接。在Dropbox Name ClassPeople Class:

注意:我在Linux环境中运行它,因此如果使用Windows(或其他操作系统),您可能必须修改People类中的文件选择行。

f = os.path.expanduser('~/Desktop')

1 个答案:

答案 0 :(得分:3)

实际上,你仍然有inconsistent use of tabs and spaces的问题,我解决了,但也许其他人无法解决它。

首先,你应该用较小的案例命名你的文件/模块(按照惯例,你应该遵循它!)。然后,在Names.py中你正在from Tkinter import *然后from Tkinter import Tk,这没有任何意义:第一个你已经导入了Tk

您的问题如下:

  

People.people_list.insert(Tk.END,FirstName.get())AttributeError:

     

'module'对象没有属性'people_list'

事实上,您正在尝试访问名为People模块 people_list的不存在属性,该属性是某些函数的局部变量,而不是我曾经使用的属性看到。

如果你想用另一个Toplevel Listbox的输入来填充某个Toplevel A属性的B,你应该传递Toplevel {{1可能在构建期间{}}到A

这里有一个例子:

B

我还注意到你为每个窗口使用了from tkinter import * # python 3 class Other(Toplevel): """Note that the constructor of this class receives a parent called 'master' and a reference to another Toplevel called 'other'""" def __init__(self, master, other): Toplevel.__init__(self, master) self.other = other # other Toplevel self.lab = Label(self, text="Insert your name: ") self.lab.grid(row=0, column=0) self.entry = Entry(self) self.entry.grid(row=0, column=1) # When you click the button you call 'self.add' self.adder = Button(self, text='Add to Listbox', command=self.add) self.adder.grid(row=1, column=1) def add(self): """Using a reference to the other window 'other', I can access its attribute 'listbox' and insert a new item!""" self.other.listbox.insert("end", self.entry.get()) class Main(Toplevel): """Window with a Listbox""" def __init__(self, master): Toplevel.__init__(self, master) self.people = Label(self, text='People') self.people.grid(row=0) self.listbox = Listbox(self) self.listbox.grid(row=1) if __name__ == "__main__": root = Tk() root.withdraw() # hides Tk window main = Main(root) Other(root, main) # passing a reference of 'main' root.mainloop() 的2个实例,这很糟糕。对于每个应用程序,您应该只使用Tk的一个实例。如果您想使用多个窗口,请按照我提到的那样使用Tk

一般来说,你的结构不太好。你应该从创建简单的好应用程序开始,然后在掌握基本概念后传递给大型应用程序。