2017-04-04 1 views
2

현재 Tkinter를 사용하여 GUI를 작성해야하며 텍스트 파일의 문자열을로드하고 텍스트 상자에 표시해야한다는 과제가 있습니다. 지침에는 또한 수업을 활용해야한다고 명시되어 있습니다. 프로그래밍에 익숙하지 않아이 모든 것이 어떻게 작동하는지 잘 모르겠습니다. 나의 현재 텍스트 파일은 다음과 같습니다Python의 클래스/속성

(항목 식별 번호, 수량, 품목, 위치, 컬러)

(23871243, 20, 원격, 캘리포니아, 화이트)

(94938443, 10 , 양말, 캐나다, 블랙)은 요구 사항에 따라

, 각 라인은 등 나는, 그러나 주요 문제 GUI 구성 요소 괜찮아 수량, 위치, 같은 속성과 개별 객체 여야합니다 나는 파이썬에게 각 행이 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

각 행의 유형이 '항목' – WhatsThePoint

답변

0

첫째, 당신은 item_descriptions.csv라는 이름의 파일을 만들고 다음 텍스트를 작성해야합니다 :

어떤 CSV 파일의 첫 번째 행하도록
item_id,quantity,item,location,color 
23871243,20,Remote,California,White 
94938443,10,Socks,Canada,Black 

해야합니다 파이썬 내에서 사용될 수있는 일련의 식별자. 왜? 다음 프로그램이 자동으로 명명 된 튜플 생성하는 필드 이름에 의존하기 때문에 : 당신은 당신의 프로그램에 더 도움이 필요하면

#! /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() 

을, 당신은 더 많은 답을 또 다른 질문을해야 할 수도 있습니다.