使用来自另一个 class 的条目将项目添加到列表框

Adding items to a Listbox using Entries from another class

我创建了两个 classes,一个在 People.py(将是 parent class)中,其中包含一个列表框,可以通过只需打开一个文件并将内容逐行添加到列表框即可。

另一个class在Names.py中(我希望它是childclass),其中包含名字、姓氏和组合的条目应该(将在 question/problem 被回答后实施)进入主 window 列表的标题框,其中 class 是 People。我正在尝试使用 OOP 模型。现在,它还不是完全 OOP,但我稍后会重构代码。

我之前曾尝试发布此代码,但由于缩进问题,人们遇到了 运行 问题,因此我提供了 class 的链接。在 Dropbox 中 Name Class and People Class:

注意:我运行这是在Linux环境中,所以如果使用Windows(或另一个OS)。

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

其实你还有一个inconsistent use of tabs and spaces的问题,我已经解决了,可能其他人解决不了。

首先,您应该用小写字母命名您的 files/modules(按照惯例,您应该遵循它!)。然后,在 Names.py 你正在做 from Tkinter import * 然后 from Tkinter import Tk,这没有任何意义:第一个你已经在导入 Tk.

您的问题如下:

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

'module' object has no attribute 'people_list'

实际上,您正在尝试访问名为 people_list 模块 People 的一个不存在的属性,它是某些函​​数的局部变量,据我所见。

如果你想用来自另一个 Toplevel B 的输入填充 Listbox,它是某个 Toplevel A 的 属性,你应该传递一个引用顶层 AB,可能在其构建期间。

这里有一个例子:

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()

我还注意到您为每个 windows 使用了 2 个 Tk 实例,这很糟糕。您应该为每个应用程序只使用一个 Tk 实例。如果你想使用多个 windows,只需使用 Toplevels,正如我提到的。

总的来说,你的结构不是很好。您应该从创建简单的好应用程序开始,一旦掌握了基本概念,然后再过渡到大型应用程序。