2017-04-04 56 views
2

我目前正在處理一項任務,指出我必須使用Tkinter構建GUI,它將從文本文件加載字符串並將它們顯示在文本框中。說明還指出,必須利用課程。作爲編程新手,我不確定這是如何實現的。我現在的文本文件看起來像這樣:Python中的類/屬性

(項目標識#,數量,項目,位置,顏色)

(23871243,20,遠程,加利福尼亞州,白)

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

根據要求,每條線必須是一個單獨的對象,具有 屬性,如數量,位置等 我很好,與GUI組件,但主要問題我正在告訴Python,每一行都在t中他的文本文件是一個單獨的對象,具有某些屬性。

'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() 
+0

閱讀並解析文件後,只需使用新收到的信息調用Item項即可。 – MooingRawr

+0

你將不得不指定每行是'Item'類型 – WhatsThePoint

回答

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

,你可能需要問另一個問題更多的答案。