繁体   English   中英

Python中的类/属性

[英]Classes/Attributes in Python

我目前正在做一个作业,该作业指出我必须使用Tkinter来构建GUI,该作业将从文本文件加载字符串并将其显示在文本框中。 这些说明还指出必须使用类。 作为编程新手,我不确定这一切如何实现。 我当前的文本文件如下所示:

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

(23871243,20,Remote,California,White)

(94938443,10,袜子,加拿大,黑色)

根据要求,每一行都必须是一个单独的对象,并具有诸如数量,位置等属性。我对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()

首先,您应该创建一个名为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()

如果您需要有关程序的进一步帮助,则可能需要询问另一个问题以获取更多答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM