Python中的类/属性

时间:2017-04-04 13:39:49

标签: python python-3.x class object attributes

我目前正在开展一项任务,声明我必须使用Tkinter构建一个GUI,它将从文本文件加载字符串并在文本框中显示它们。说明还指出必须使用类。 作为编程新手,我不确定这一切是如何运作的。我当前的文本文件如下所示:

(项目标识#,数量,项目,位置,颜色)

(23871243,20,Remote,California,White)

(94938443,10,Socks,Canada,Black)

根据要求,每一行必须是一个单独的对象 属性,例如数量,位置等。 我对GUI组件很好,但是我遇到的主要问题是告诉Python文本文件中的每一行都是一个单独的对象,具有某些属性。

“OpenFile”功能可能是问题所在。截至目前,它返回一个字符串列表,但我希望它返回一个具有5个属性的对象(如上所列,在文本文件中)。 任何帮助将不胜感激。

from tkinter import *
from tkinter import ttk
from tkinter import font
from tkinter.filedialog import askopenfile


class Manager:

def __init__(self, root):
    #The frame for the GUI itself
    mainframe = ttk.Frame(root, relief=SUNKEN, padding="3 10 12 12")
    mainframe.grid(column=0, row=0, columnspan=10, rowspan=10, sticky="NW")

    button_load= ttk.Button(mainframe, text="Load",command=self.OpenFile)
    button_load.grid(row=35, column=17, sticky = "NE", padx=5, pady=10)
    global text_identity
    text_identity = Text(mainframe, width = 15, height = 2)
    text_identity.grid(column=8, row=5, sticky=(N,W))

def OpenFile(self):
    listing=[]
    name = askopenfile(mode='r',initialdir="D:/Documents",
                   filetypes =(("Text File", "*.txt"),("All Files","*.*")),
                   title = "Choose a file.")

    with name as rd:
    global items

    items=rd.readlines()
    one=[x.strip('\n') for x in items]
return one

class Items:
    identity=''
    num=''
    name = ''
    location = ''
    other = ''

def __init__(self,identity,num,name,location,other):
self.identity = identity
self.num = num
self.name = name
self.location = location
self.other = other

def main():
    root = Tk()
    Manager(root)
    root.title("Data Management")
    root.mainloop()

if __name__ == main():
    main()

1 个答案:

答案 0 :(得分:0)

首先,您应该创建一个名为 item_descriptions.csv 的文件,并使用以下文字填写:

item_id,quantity,item,location,color
23871243,20,Remote,California,White
94938443,10,Socks,Canada,Black

任何 CSV 文件的第一行都需要有一行可在Python中使用的标识符。为什么?因为以下程序依赖于字段名称来自动生成命名元组:

#! /usr/bin/env python3
import collections
import csv
import pathlib
import tkinter.filedialog
import tkinter.messagebox
import tkinter.scrolledtext
import tkinter.ttk


# Make the constants easy to refer to in the rest of the program.
from tkinter.constants import *


class Manager(tkinter.ttk.Frame):

    """Manager(master=None, **kw) -> Manager instance"""

    @classmethod
    def main(cls):
        """Create a root window for the Manager and display the widget."""
        tkinter.NoDefaultRoot()
        root = tkinter.Tk()
        root.title('Manager')
        root.minsize(680, 420)
        frame = cls(root)
        frame.grid(sticky=NSEW)
        root.grid_columnconfigure(0, weight=1)
        root.grid_rowconfigure(0, weight=1)
        root.mainloop()

    def __init__(self, master=None, **kw):
        """Initialize the Manager instance and its attributes."""
        super().__init__(master, **kw)
        self.initial_dir = pathlib.Path.home()
        self.scrolled_text = tkinter.scrolledtext.ScrolledText(self)
        self.load_button = tkinter.ttk.Button(self)
        self.size_grip = tkinter.ttk.Sizegrip(self)
        self.setup_widgets()
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(0, weight=1)

    def setup_widgets(self):
        """ Change options on the widgets so they work properly."""
        self.scrolled_text.configure(state=DISABLED, wrap=WORD)
        self.load_button.configure(text='Load', command=self.find_csv_file)
        # Place widgets where they belong in the frame.
        self.scrolled_text.grid(row=0, column=0, columnspan=2, sticky=NSEW)
        self.load_button.grid(row=1, column=0, sticky=EW)
        self.size_grip.grid(row=1, column=1, sticky=SE)

    def find_csv_file(self):
        """Begin the process of loading a CSV file for display."""
        source = tkinter.filedialog.askopenfilename(
            parent=self,
            title='Where is the file you want to open?',
            multiple=False,
            defaultextension='.csv',
            filetypes=(('Spreadsheet', '.csv'), ('All Files', '*')),
            initialdir=self.initial_dir
        )
        if source:
            self.initial_dir = pathlib.Path(source).parent
            self.show_records(self.load_records(source))

    def load_records(self, source):
        """Open the requested file and try to yield out its records."""
        with open(source, newline='') as file:
            reader = csv.DictReader(file)
            try:
                Record = collections.namedtuple('Record', reader.fieldnames)
            except Exception as error:
                tkinter.messagebox.showerror(
                    'Exception',
                    f'{type(error).__name__}: {error}',
                    master=self
                )
            else:
                self.scrolled_text.configure(state=NORMAL)
                self.scrolled_text.delete(0.0, END)
                yield from (Record(**row) for row in reader)

    def show_records(self, iterable):
        """Display each record when able without locking up the GUI."""
        try:
            record = next(iterable)
        except StopIteration:
            self.scrolled_text.configure(state=DISABLED)
        else:
            self.scrolled_text.insert(END, f'{record}\n')
            self.after_idle(self.show_records, iterable)


if __name__ == '__main__':
    Manager.main()

如果您需要有关计划的进一步帮助,可能需要提出其他问题以获得更多答案。