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

标签 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')

最佳答案

其实你还有一个制表符和空格的使用不一致的问题,我解决了,但也许其他人解决不了。

首先,你应该用小写字母命名你的文件/模块(按照惯例,你应该遵循它!)。然后,在 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_listmodule People 的不存在属性,它是某些函​​数的局部变量,据我所见。

如果你想用来自另一个 Toplevel B 的输入填充一个 Listbox 这是一些 Toplevel A 的属性,你应该将 Toplevel 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 实例。如果您想使用多个窗口,只需使用 Toplevels,就像我提到的那样。

总的来说,你的结构不太好。您应该从创建简单的好应用程序开始,然后在掌握了基本概念后转向大型应用程序。

关于linux - 使用来自另一个类的条目将项目添加到列表框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29291704/

相关文章:

javascript - 开源 Linux Acrobat Javascript 编辑器

java - 如何从 Web 表单获取数据?

javascript - 如何使用 javascript 或 jquery 检查输入类型日期是否为空

linux - 是否已编译 X11 c 程序,出现 undefined reference 错误,需要哪些库?

linux - 如何使用 NASM Assembly 忽略输入中的换行符?

javascript - JS 根据 Dropdown 用户输入显示内容

python - SQLite 数据库上的 Fetchall() 返回 unicode 字符串 [Python 2.7]

python - if/elif 语句的多个条件

python - lambda 的字符串表示

linux - 查找不在列表中的文件