Exemplo n.º 1
0
class create_csv():
    def __init__(self, root):
        self.f = Frame(root, height=500, width=500)
        self.f.pack()

        self.message_label = Label(self.f,
                                   text='Display the Empsal CSV:',
                                   font=('Roman', 24, 'bold'),
                                   fg='navy blue')
        self.confirm_button = Button(self.f,
                                     text='Display',
                                     font=('Arial', 14),
                                     bg='light green',
                                     fg='White',
                                     command=self.conv_to_csv,
                                     activeforeground='green')
        self.exit_button = Button(self.f,
                                  text='Exit',
                                  font=('Arial', 14),
                                  bg='pink',
                                  fg='White',
                                  command=root.destroy,
                                  activeforeground='red')

        self.message_label.grid(row=1, column=1)
        self.confirm_button.grid(row=3, column=0)
        self.exit_button.grid(row=3, column=2)

    def conv_to_csv(self):
        self.f = Frame(root, height=300, width=300)
        self.f.pack(fill=BOTH, expand=1)

        self.table = TableCanvas(self.f, read_only=True)
        self.table.importCSV('empsal.csv')
        self.table.show()
class create_csv:
    
    def __init__(self,root):
        self.f= Frame(root, height=350, width=500)
        self.f.pack() # Place the frame on root window
        
        #Creating label widgets
        self.message_label = Label(self.f,text='Conversion of stock Price Excel file to CSV ' , font=('Arial', 14))
        
        #Buttons
        self.confirm_button= Button(self.f,text='Load & Display', font=('Arial',14),bg='Orange', fg='Black', command=self.display_excel)
        self.exit_button=Button(self.f,text='Exit', font=('Arial',14),bg='Yellow', fg='Black',command=root.destroy)
        
        #Placing the widgets using grid manager
        
        self.message_label.grid(row=1,column=0)
        self.confirm_button.grid(row=2,column=0)
        self.exit_button.grid(row=2,column=2)
        
    def display_excel(self):
        try:
            stock_price_df=pd.read_excel('E:\project5\stock_price.xls', sheet_name='Stock')
            stock_price_df.to_csv('E:\project5\stock_price.csv', index=False)
            
            # Now display the csv in 'tkintertable' widget
            self.f= Frame(root,height=200 , width=300)
            self.f.pack(fill=BOTH, expand=1)
            self.table= TableCanvas(self.f , read_only=True)
            self.table.importCSV('E:\project5\stock_price.csv')
            #print(self.table.mode1.columnNames)# to print column names in IDLE shell
        except FileNotFoundError as e:
            print(e)
Exemplo n.º 3
0
class create_csv:

     def __init__(self, root):
          self.f = Frame(root, height=350, width=500)
          self.f.pack()    # Place the frame on root window

          # Creating label widgets
          self.message_label = Label(self.f,text='Display the Empsal CSV in TkinterTable',font=('Arial', 14))

          # Buttons
          self.confirm_button = Button(self.f,text='Display', font=('Arial', 14), bg='Orange',
                                 fg='Black', command=self.conv_to_csv)
          self.exit_button = Button(self.f,text='Exit', font=('Arial', 14), bg='Yellow',
                                 fg='Black', command=root.destroy)

          # Placing the widgets using grid manager
          self.message_label.grid(row=1, column=0)
          self.confirm_button.grid(row=2,column=0)
          self.exit_button.grid(row=2,column=2)

     def conv_to_csv(self):

         try:

             # Now display the CSV in 'tkintertable' widget
             self.f = Frame(root, height=200, width=300)
             self.f.pack(fill=BOTH,expand=1)
             self.table = TableCanvas(self.f, read_only=True)
             self.table.importCSV('empsal.csv')
             self.table.show()

         except FileNotFoundError as e:
             msg.showerror('Error in opening file', e.msg)
Exemplo n.º 4
0
class TestApp():
    def __init__(self,root):
        self.f=Frame(root,height=200,width=100)
        self.f.pack(fill=BOTH,expand=1)
        self.table=TableCanvas(self.f,read_only=True)
        self.table.importCSV('/media/amit/Work/GitHub/Machine Learning with Python/DataSets/empsal.csv')
        print(self.table.model.columnNames)
        self.table.show()
Exemplo n.º 5
0
class TestApp():
    def __init__(self, root):
        self.f = Frame(root, height=200, width=300) 
        self.f.pack(fill=BOTH,expand=1)
        
        self.table = TableCanvas(self.f, read_only=True)
        self.table.importCSV('exp_sal.csv')
        print (self.table.model.columnNames)
        self.table.show()
Exemplo n.º 6
0
 def __init__(self, parent=None):
     self.parent = parent
     Frame.__init__(self)
     self.main = self.master
     self.main.geometry('800x500+200+100')
     self.main.title('Test')
     f = Frame(self.main)
     f.pack(fill=BOTH, expand=1)
     table = TableCanvas(f)
     table.importCSV('2017_Traffic_Volume_Flow.csv')
     print(table.model.columnNames)
     #table.model.data[1]['a'] = 'XX'
     #table.model.setValueAt('YY',0,2)
     table.show()
     return
Exemplo n.º 7
0
def create_gui():
    root.title("XCOM Soldier Viewer")
    width = 1600
    height = 900
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    x = (screen_width / 2) - (width / 2)
    y = (screen_height / 2) - (height / 2)
    root.geometry("%dx%d+%d+%d" % (width, height, x, y))
    root.resizable(0, 0)

    tframe = Frame(root)
    tframe.pack(fill="both", expand=True)
    table = TableCanvas(tframe, editable=False)
    table.importCSV('soldiers.csv')
    table.show()
    table.update()
Exemplo n.º 8
0
def display(event=None):
    print("file", file_name)
    recreate()
    if (file_name):
        """recreate()
        typ=re.search(r'.csv',file_name)
        if(typ==None):"""
        table = TableCanvas(f1, read_only=True)
        #for csv and xls file------------------------------
        table.importCSV(file_name)
        #print (self.table.model.columnNames)
        table.show()
        """else:
            table = tktable.Table(root, rows=10, cols=4)
            table.pack(side="top", fill="both", expand=True)"""
    else:

        msgbx.showwarning("error", "No File is selected")
    def __init__(self, parent=None):
        self.parent = parent
        Frame.__init__(self)
        self.main = self.master
        self.main.geometry('890x500')
        self.main.title('Pedidos')
        f = Frame(self.main)
        f.pack(fill=BOTH, expand=1)
        table = TableCanvas(f, editable=False)
        table.importCSV('test.csv')
        #print (table.model.columnNames)
        #table.model.data[1]['a'] = 'XX'
        #table.model.setValueAt('YY',0,2)
        table.show()
        return


#app=TestApp()
#app.mainloop()
Exemplo n.º 10
0
class label_GUI:
    def __init__(self, root, video_path, csv_path, labels_csv, mode):

        self.video_path = video_path
        self.fps = cv2.VideoCapture(video_path).get(cv2.CAP_PROP_FPS)
        self.csv_path = csv_path

        self.mode = mode

        if self.mode == 'single':
            self.labels = get_labels_single(labels_csv)
            self.CLASSES = self.labels.labels()
            self.CLASSES_DICT = self.labels.label_dict()
        if self.mode == 'duo':
            verb_csv, noun_csv = labels_csv
            self.labels = get_labels_duo(verb_csv, noun_csv)
            self.NOUNS = self.labels.nouns()
            self.NOUNS_DICT = self.labels.noun_dict()
            self.VERBS = self.labels.verbs()
            self.VERBS_DICT = self.labels.verb_dict()

        self.window = root
        self.canvas = Canvas(self.window, width=1850, height=1000)
        self.canvas.pack()

        self.current_state = 0  #this is either 0 (not labeling), 1 (mid label (i.e defined start)), 2 labeled waiting for confirmation
        self.console_output = []
        self.current_index = 0
        self.start_frame = None
        self.end_frame = None

        #pay attention to all keypresses
        self.window.bind("<Key>", self.key_pressed)

        #decode the video here (and check if its already been decoded)
        self.image_folder = decode_video(self.video_path)

        #==================== create all the widgets =========================:

        #label selection
        if self.mode == 'single':
            self.label = Label(self.window,
                               text='Select Label:',
                               font=("Courier", 15))
            self.label.place(x=1150, y=150)

            self.class_drop = StringVar(self.window)
            self.class_drop.set(self.CLASSES[0])
            self.w_classes = OptionMenu(*(self.window, self.class_drop) +
                                        tuple(self.CLASSES))
            self.w_classes.place(x=1400, y=150)

        if self.mode == 'duo':
            self.label = Label(self.window,
                               text='Select Label:',
                               font=("Courier", 15))
            self.label.place(x=1150, y=150)

            self.noun_drop = StringVar(self.window)
            self.noun_drop.set(self.NOUNS[0])
            self.w_noun = OptionMenu(*(self.window, self.noun_drop) +
                                     tuple(self.NOUNS))
            self.w_noun.place(x=1550, y=150)

            self.verb_drop = StringVar(self.window)
            self.verb_drop.set(self.VERBS[0])
            self.w_verb = OptionMenu(*(self.window, self.verb_drop) +
                                     tuple(self.VERBS))
            self.w_verb.place(x=1400, y=150)

        #play buttons:
        self.prev_button = Button(self.window,
                                  text="Prev",
                                  height=100,
                                  width=100,
                                  command=self.prev)
        self.next_button = Button(self.window,
                                  text="Next",
                                  height=100,
                                  width=100,
                                  command=self.nxt)
        self.pause_button = Button(self.window,
                                   text="Stop",
                                   height=50,
                                   width=100,
                                   command=self.pause_video)
        self.play_button = Button(self.window,
                                  text="Play",
                                  height=50,
                                  width=100,
                                  command=partial(self.play_video, speed=1))
        self.play_button2 = Button(self.window,
                                   text="x2",
                                   height=50,
                                   width=100,
                                   command=partial(self.play_video, speed=2))
        self.play_button4 = Button(self.window,
                                   text="x4",
                                   height=50,
                                   width=100,
                                   command=partial(self.play_video, speed=4))
        self.play_button8 = Button(self.window,
                                   text="x8",
                                   height=50,
                                   width=100,
                                   command=partial(self.play_video, speed=8))
        self.speed = 1

        self.prev_button.place(bordermode=OUTSIDE,
                               height=100,
                               width=100,
                               x=45,
                               y=300)
        self.next_button.place(bordermode=OUTSIDE,
                               height=100,
                               width=100,
                               x=1050,
                               y=300)
        self.pause_button.place(bordermode=OUTSIDE,
                                height=50,
                                width=100,
                                x=400,
                                y=600)
        self.play_button.place(bordermode=OUTSIDE,
                               height=50,
                               width=100,
                               x=550,
                               y=600)
        self.play_button2.place(bordermode=OUTSIDE,
                                height=50,
                                width=100,
                                x=650,
                                y=600)
        self.play_button4.place(bordermode=OUTSIDE,
                                height=50,
                                width=100,
                                x=750,
                                y=600)
        self.play_button8.place(bordermode=OUTSIDE,
                                height=50,
                                width=100,
                                x=850,
                                y=600)

        self.pause = False  #boolean, if true, video is in paused (still image state) if faluse, it is playing.
        self.currently_playing = False

        #frame input textbox and button for submitting it.
        self.textBox = Text(self.window, height=1, width=10)
        self.textBox.place(x=150, y=600)
        self.buttonCommit = Button(self.window,
                                   height=1,
                                   width=10,
                                   text="Jump to frame",
                                   command=lambda: self.retrieve_input())
        self.buttonCommit.place(x=250, y=600)

        #display frame numbers
        self.frame_no = Label(self.window,
                              text='Current Frame: {}'.format(
                                  self.current_index),
                              font=("Courier", 15))
        self.start_no = Label(self.window,
                              text='Start Frame: {}'.format(self.start_frame),
                              font=("Courier", 15))
        self.end_no = Label(self.window,
                            text='End Frame: {}'.format(self.end_frame),
                            font=("Courier", 15))
        self.frame_no.place(x=150, y=45)
        self.start_no.place(x=1150, y=70)
        self.end_no.place(x=1500, y=70)

        #display image with current index.

        self.image = get_image(
            self.image_folder,
            self.current_index)  #retun the current image from
        self.max_index = len(os.listdir(self.image_folder)) - 1
        self.img = ImageTk.PhotoImage(self.image.resize((896, 504)))
        self.img_panel = Label(self.window, image=self.img)
        self.img_panel.image = self.img
        self.img_panel.place(x=150, y=75)

        #add a slider to navigate frames
        self.slider = Scale(self.window,
                            from_=0,
                            to=self.max_index,
                            orient=HORIZONTAL)
        self.slider.set(0)
        self.slider.place(width=900, x=150, y=700)

        self.slider_button = Button(self.window,
                                    text='Jump',
                                    command=self.goto_slider)
        self.slider_button.place(x=1075, y=715)

        #console output.
        self.console_listbox = Listbox(self.window)
        for item in self.console_output:
            self.console_listbox.insert(END, item)
        self.console_listbox.place(height=200, width=600, x=1200, y=700)

        #table output
        self.label_data = self.read_csv()

        self.write(
            'Welcome to my simple video label GUI. Please read the Github for user instructions'
        )

        self.window.mainloop()

    def read_csv(self):
        #reads csv and displays table using tkintertable
        self.tframe = Frame(self.window)
        self.tframe.place(x=1200, y=350, width=600)
        self.table = TableCanvas(self.tframe)
        self.table.importCSV(self.csv_path)
        self.table.show()

    def write(self, message):
        #function that is used instead of regular print statement to display messages within the GUI output box

        if len(self.console_output
               ) < 10:  #only collect last 10 lines of output.
            self.console_output.append(message)
        else:
            self.console_output = self.console_output[1:]
            self.console_output.append(message)

        self.update_all()
        return self.console_output

    def prev(self):
        #move to next image
        if self.current_index == 0:
            self.update_all()
        else:
            self.current_index -= 1
            self.update_all()

    def nxt(self):
        #move to previous image
        if self.current_index == self.max_index:
            self.update_all()
        else:
            self.current_index += 1
            self.update_all()

    def play_video(self, speed):
        #function that runs when play buttons are pressed.
        self.speed = speed

        def play():
            delay = int((1 / (self.speed * self.fps)) * 1000)
            if self.pause:  #if currently paused and button is pressed, we want to play
                self.window.after_cancel(self.after_id)
                self.pause = False
                self.currently_playing = False

            else:
                self.currently_playing = True
                self.current_index += 1
                start = time.time()
                self.update_image()
                finish = int(1000 * (time.time() - start))
                delay = max(
                    1, (delay - finish)
                )  #this factors in the time to retrieve and display an image into the fps calculations.
                self.after_id = self.window.after(delay, play)

        play()

    def pause_video(self):
        if self.currently_playing:
            self.pause = True
        else:
            self.pause = False

    def retrieve_input(self):
        input_val = self.textBox.get("1.0", END)
        try:
            input_val = int(input_val)
        except:
            self.write('please input an intiger')
            self.window.mainloop()
            input_val = 0
        if input_val < 0 or input_val > int(self.max_index):
            self.write('please enter a value between 0 and {}'.format(
                self.max_index))
            self.window.mainloop()
        else:
            self.current_index = input_val
            self.write('jumped to frame {}'.format(self.current_index))
            self.window.mainloop()

    def goto_slider(self):
        self.current_index = self.slider.get(
        )  #set current index to slider value.
        self.update_all()

    #code for using keyboard shortcuts.
    def key_pressed(self, event):
        if event.keysym == 'Right':
            self.nxt()
        if event.keysym == 'Left':
            self.prev()
        if event.keysym == 'space':
            if self.current_state == 0:
                self.start_frame = self.current_index
                self.write(
                    'selected a start frame, press space to select end frame or esc to cancel selection'
                )
                self.end_frame = None
                self.current_state = 1  #change state to 1.
            elif self.current_state == 1:
                self.end_frame = self.current_index
                self.write(
                    'Selected an end frame, press space to change end frame, return to submit the label or esc to cancel selection'
                )
                self.current_state = 2
            elif self.current_state == 2:
                self.end_frame = self.current_index
            self.update_all()
        if event.keysym == 'Return':
            if self.current_state == 2:  #only care is someone is in state 2.
                self.make_label()
                self.current_state = 0
                self.start_frame = None
                self.end_frame = None
            else:
                self.write(
                    'You must make a start and end frame selection before submitting the label'
                )
            self.update_all()
        if event.keysym == 'Escape':
            #if escape is hit, delete all frame selections and return to state 0, ready for a new input sequence.
            self.start_frame = None  #delete frame selection
            self.end_frame = None
            self.current_state = 0  #set current state back to 0.
            self.write('cancled frame selection')
            self.update_all()

    def make_label(self):
        video_name = os.path.basename(self.video_path)[:-4]

        if self.mode == 'single':
            _class = self.class_drop.get()

            with open(self.csv_path, 'a', newline='') as csvfile:
                linewriter = csv.writer(csvfile, delimiter=',')
                linewriter.writerow([
                    video_name, self.start_frame, self.end_frame, _class,
                    self.CLASSES.index(_class)
                ])

            self.write(
                'added action {} between frames {} and {} to csv file'.format(
                    _class, self.start_frame, self.end_frame))

        if self.mode == 'duo':
            verb = self.verb_drop.get()
            noun = self.noun_drop.get()

            #still need to implement checks here, e.g make sure end frame is after begining, that they are not the same frame etc...
            with open(self.csv_path, 'a', newline='') as csvfile:
                linewriter = csv.writer(csvfile, delimiter=',')
                linewriter.writerow([
                    video_name, self.start_frame, self.end_frame, verb,
                    self.VERBS.index(verb), noun,
                    self.NOUNS.index(noun)
                ])

            self.write(
                'added label to csv file, action {} {} between frames {} and {}'
                .format(verb, noun, self.start_frame, self.end_frame))

        self.read_csv()

    def update_image(self):
        """
		Same as update_all except only updates the image and the current frame - quicker to execute as doenst update csv table
		"""
        pil_img = get_image(self.image_folder, self.current_index)
        img = ImageTk.PhotoImage(pil_img.resize((896, 504)))  #size is 896x504
        self.img_panel.configure(image=img)
        self.img_panel.image = img

        self.frame_no['text'] = "Current Fame: {}".format(self.current_index)
        self.slider.set(self.current_index)

    def update_all(self):
        '''
		the main function that updates everything, run efter nearly every function
		'''

        pil_img = get_image(self.image_folder, self.current_index)
        img = ImageTk.PhotoImage(pil_img.resize((896, 504)))
        self.img_panel.configure(image=img)
        self.img_panel.image = img

        self.slider.set(self.current_index)
        self.table.show()

        self.frame_no['text'] = "Current Fame: {}".format(self.current_index)
        self.start_no['text'] = "Start Frame: {}".format(self.start_frame)
        self.end_no['text'] = "End Frame: {}".format(self.end_frame)

        self.console_listbox.delete(0, 'end')
        for item in self.console_output:
            self.console_listbox.insert(END, item)
class EDS:
    '''INSTANTIATION'''
    def __init__(self, root):
        # initialize the application
        self.root = root
        self.root.title("EDS Data Analysis Tool")
        self.root.geometry("1050x550")


        '''CONSTANTS'''
        # header constants from the csv files
        #self.manual_cols_list = ['Temperature(C)', 'Humidity(%)', 'GPOA(W/M2)', 'OCV_Before(V)', 'OCV_After(V)', 'SCC_Before(A)', 'SCC_After(A)', 'EDS_PWR_Before(W)', 'EDS_PWR_After(W)', 'EDS_PR_Before', 'EDS_PR_After', 'EDS_SR_Before', 'EDS_SR_After']
        #self.noon_cols_list = ['Temperature(C)', 'Humidity(%)', 'GPOA(W/M2)', 'OCV(V)', 'SCC(A)', 'Power(W)', 'PR', 'SR']
        self.testing_cols_list = ['Temperature(C)', 'Humidity(%)', 'GPOA(W/M2)', 'Voc_Before(V)', 'Voc_After(V)',
                                 'Isc_Before(A)', 'Isc_After(A)', 'Pout_Before(W)', 'Pout_After(W)', 
                                 'PR_Before', 'PR_After', 'SR_Before', 'SR_After']
        
        # global variables
        self.mode = ''
        self.output_loc = ''
        self.window = 1

        '''LABELS'''
        # labels for the program title
        self.title_label = Label(root, text="EDS DATA ANALYSIS TOOL", font=("Helvetica", 20))
        self.title_label.grid(row=0, column=3, padx=10,pady=15, sticky=W)
        self.bu_label = Label(root, text="BOSTON UNIVERSITY", font=("Arial", 14))
        self.bu_label.grid(row=1, column=3, padx=10,sticky=W)

        # instructions label
        self.ins_label = Label(root, text="How To Use:",font=("Arial", 13))
        self.ins_label.grid(row=2, column=3,padx=10, pady=120, sticky=N+W)
        self.ins_label1 = Label(root, text=" 1. Select the CSV File To Analyze",font=("Arial", 11))
        self.ins_label1.grid(row=2, column=3, padx=10, pady=150, sticky=W+N)
        self.ins_label2 = Label(root, text=" 2. Select Output File Location",font=("Arial", 11))
        self.ins_label2.grid(row=2, column=3, padx=10, pady=180, sticky=W+N)
        self.ins_label3 = Label(root, text=" 3. Click Table Button",font=("Arial", 11))
        self.ins_label3.grid(row=2, column=3, padx=10, pady=210, sticky=W+N)
        self.ins_label4 = Label(root, text=" 4. Plot Metrics",font=("Arial", 11))
        self.ins_label4.grid(row=2, column=3, padx=10, pady=240, sticky=W+N)

        # labels for showing testing/manual/noon mode
        self.eds_label = Label(root, text="Eds Data", borderwidth=1.4, relief="solid", width=18, height=3)
        self.eds_label.grid(row=1, column=1)

        #self.manual_label = Label(root, text="Manual Data", borderwidth=1.4, relief="solid", width=18, height=3)
        #self.manual_label.grid(row=1, column=1)
        #self.noon_label = Label(root, text="Noon Data", borderwidth=1.4, relief="solid", width=18, height=3)
        #self.noon_label.grid(row=1, column=2, padx=18)

        # label for error message
        self.error_label = Label(root, text="", fg='red',font=("Arial", 15))
        self.error_label.grid(row=2, column=3,padx=10,pady=177,sticky=S+W)

        # label to get average day input
        self.avg_label = Label(root, text="Average Days: ",font=("Arial", 14))
        self.avg_label.grid(row=2, column=3, padx=10, pady=21, sticky=W+N)

        '''BUTTONS'''
        # button to get the path of the data csv file
        self.file_btn = Button(root, text="Find CSV File", command= self.find_file, borderwidth=2, relief="raised")
        self.file_btn.grid(row=0,column=0, padx=20, pady=20, sticky=W)

        # button to display soiling rate values
        self.sr_btn = Button(root, text="Get Soiling Rate", command= self.show_sr)
        self.sr_btn.grid(row=2, column=0, columnspan=3, pady=135, sticky=S)

        # create label for getting output path
        self.out_btn = Button(root, text="Select Output Location", command= self.select_output, borderwidth=2, relief="raised")
        self.out_btn.grid(row=2, column=0, padx=20, pady=98,sticky=S+W)

        # create button to update the table
        self.table_btn = Button(root, text="Get Table", command= self.get_table, font=("Arial", 14),borderwidth=1.4, relief="solid", width=15, height=3)
        self.table_btn.grid(row=2, column=3, padx=10, pady=60, sticky=N+W)

        # create button to plot the table
        self.plot_btn = Button(root, text="Plot Table", command= self.plot_table, font=("Arial", 14),borderwidth=1.4, relief="solid", width=15, height=3)
        self.plot_btn.grid(row=2, column=3, padx=200, pady=60, sticky=N)

        '''ENTRY FIELDS'''
        # entry field to display path for data csv file
        self.file_entry = Entry(root, width=55)
        self.file_entry.grid(row=0, column=1, columnspan=2, padx=2, sticky=W)

        # entry field for the output path
        self.out_entry = Entry(root, width=55)
        self.out_entry.grid(row=2, column=1, columnspan=2, padx=5,pady=100, sticky=S+W)

        # entry field for average day input
        self.avg_entry = Entry(root, width= 35)
        self.avg_entry.grid(row=2, column=3,padx=150, pady=25, sticky=N+W)

        '''RADIO BUTTON'''
        # create radio button for selecting which plot
        self.plot_mode = StringVar()
        self.plot_mode.set("Power")
        self.radio_btn1 = Radiobutton(root, text="Isc", variable=self.plot_mode, value="Isc")
        self.radio_btn1.grid(row=2, column=3, sticky=N+W, pady=150, padx=260)
        self.radio_btn2 = Radiobutton(root, text="Power", variable=self.plot_mode, value="Power")
        self.radio_btn2.grid(row=2, column=3, sticky=N+W, pady=180, padx=260)
        self.radio_btn3 = Radiobutton(root, text="PR", variable=self.plot_mode, value="PR")
        self.radio_btn3.grid(row=2, column=3, sticky=N+W, pady=210, padx=260)
        self.radio_btn4 = Radiobutton(root, text="SR", variable=self.plot_mode, value="SR")
        self.radio_btn4.grid(row=2, column=3, sticky=N+W, pady=240, padx=260)

        '''FRAME'''
        # create frame for the table
        self.tframe = Frame(root)
        self.tframe.grid(row=2, column=0, columnspan=3, padx=10, pady=20, sticky=N)

        '''TABLE CANVAS'''
        # insert the csv table
        self.table = TableCanvas(self.tframe)
        self.table.thefont = ('Arial',10)
        self.table.show()

    '''Button Functions'''
    # function to get csv file path
    def find_file(self):
        # clear the entry field
        self.file_entry.delete(0, END)
        # clear the color for the testing modes
        self.clear_mode_buttons()
        # clear errors
        self.error_label.config(text="")
        # get the path for the csv file
        self.root.filename = filedialog.askopenfilename(initialdir=".", title="Select A CSV File", 
                                                        filetypes=(("CSV Files", "*.csv"),("All Files", "*.*")))
        # insert the path to the entry field
        self.file_entry.insert(0, root.filename)
        # based on path, figure out which mode
        self.mode = root.filename.split("/")[-1]
        if self.mode == 'eds_data.csv':
            self.eds_label.config(bg="green")

    
    
    # show the soiling rates in new window
    def show_sr(self):
        # new window for soiling rate data
        self.sr_window = Toplevel()
        self.sr_window.geometry("300x400")
        self.sr_title = Label(self.sr_window, text="Soiling Rate Values:", font=("Arial", 15)).pack()
        if self.mode == 'eds_data.csv':
            data = self.calc_soiling_rate(self.mode)
            # error check the calculation
            if data == "error":
                #display error in the new window
                self.error_msg = Label(self.sr_window, text="Please enter a valid avg day entry for analysis", fg = 'red').pack()
            else:
                # prepare the label message
                eds1 = "EDS1 Soiling Rate: " + str(data['EDS1_PRE']) + "%(PRE), " + str(data['EDS1_POST']) + "%(POST)"
                eds2 = "EDS2 Soiling Rate: " + str(data['EDS2_PRE']) + "%(PRE), " + str(data['EDS2_POST']) + "%(POST)"
                eds3 = "EDS3 Soiling Rate: " + str(data['EDS3_PRE']) + "%(PRE), " + str(data['EDS3_POST']) + "%(POST)"
                eds4 = "EDS4 Soiling Rate: " + str(data['EDS4_PRE']) + "%(PRE), " + str(data['EDS4_POST']) + "%(POST)"
                eds5 = "EDS5 Soiling Rate: " + str(data['EDS5_PRE']) + "%(PRE), " + str(data['EDS5_POST']) + "%(POST)"
                ctrl1 = "CTRL1 Soiling Rate: " + str(data['CTRL1_PRE']) + "%(PRE), " + str(data['CTRL1_POST']) + "%(POST)"
                ctrl2 = "CTRL2 Soiling Rate: " + str(data['CTRL2_PRE']) + "%(PRE), " + str(data['CTRL2_POST']) + "%(POST)"
                message = eds1 + '\n' + eds2 + '\n' + eds3 + '\n' + eds4 + '\n' + eds5 + '\n' + ctrl1 + '\n' + ctrl2
                # display the message
                sr_contents = Label(self.sr_window, text=message).pack()
        else:
            #display error in the new window
            self.error_msg = Label(self.sr_window, text="Please Select Valid CSV File For Analysis", fg = 'red').pack()
    
    # function to specify output path
    def select_output(self):
        # clear  entry fields
        self.out_entry.delete(0, END)
        # clear errors
        self.error_label.config(text="")
        # use filedialog to select output location
        self.out_dir = filedialog.askdirectory(initialdir=".",title="Select A Folder To Store Output")
        # insert to entry field
        self.out_entry.insert(0, self.out_dir)
        # store in location
        self.output_loc = self.out_dir
   
    # function to update the table
    def get_table(self):
        # clear errors
        self.error_label.config(text="")
        # get the average day number
        self.window = self.avg_entry.get()
        # error check the window variable
        avg_check = self.avg_entry_check(self.window)
        if avg_check:
            # check which mode selected
            if self.mode == 'eds_data.csv':
                man_df = get_avg_eds_data(self.root.filename, self.testing_cols_list, int(self.window))
                output = self.output_loc+"/eds_sorted.csv"
                x = man_df.to_csv(output)
                # upload csv to the table
                self.table.importCSV(output)
          
            else:
                self.error_label.config(text="Select Valid CSV File For Analysis!")
    
    # plot the table
    def plot_table(self):
        # clear errors
        self.error_label.config(text="")
        # check which mode selected
        if self.mode == 'eds_data.csv':
            # get the file to find the soiling rate
            output = self.output_loc+"/eds_sorted.csv"
            df = self.load_sorted(output)
            # get desired columns names to plot
            cols = ['Isc_Before(A)', 'Isc_After(A)', 'Pout_Before(W)', 'Pout_After(W)', 'PR_Before', 'PR_After', 
                    'SR_Before', 'SR_After']
            # get the desired column data from the table
            data = {
                'Isc_Before(A)':[],
                'Isc_After(A)':[],
                'Pout_Before(W)':[],
                'Pout_After(W)':[],
                'PR_Before': [],
                'PR_After': [],
                'SR_Before': [],
                'SR_After': []
            }
            for x in cols:
                for y in df[x]:
                    data[x].append(y)
            # get the dates for x axis
            dates = ()
            for x in df['Date']:
                x = x.replace("/2020", "")
                dates = dates + (x,)
            # plot the data (x,y)
            plt.figure(figsize=(12, 6))
            if self.plot_mode.get() == 'Isc':
                # plot a scatter plot
                plt.scatter(range(len(data['Isc_Before(A)'])),data['Isc_Before(A)'], label="Pre EDS")
                plt.scatter(range(len(data['Isc_After(A)'])),data['Isc_After(A)'], label="Post EDS")
                # add the plot title
                plt.title("Isc(A)")
                # add the legend
                plt.legend(loc='upper right')
                # add axis limits
                x1,x2,y1,y2 = plt.axis()
                plt.axis([x1, x2, 0, 10])
                plt.xticks(np.arange(0, x2, 1), dates, fontsize=8, rotation=80)
            elif self.plot_mode.get() == 'Power':
                # plot a scatter plot
                plt.scatter(range(len(data['Pout_Before(W)'])), data['Pout_Before(W)'], label="Pre EDS")
                plt.scatter(range(len(data['Pout_After(W)'])), data['Pout_After(W)'], label = "Post EDS")
                # add the plot title
                plt.title("Power(W)")
                # add the legend
                plt.legend(loc='upper right')
                # add axis limits
                x1,x2,y1,y2 = plt.axis()
                plt.axis([x1, x2, 0, 50])
                plt.xticks(np.arange(0, x2, 1), dates, fontsize=8, rotation=80)
            elif self.plot_mode.get() == 'PR':
                # plot a scatter plot
                plt.scatter(range(len(data['PR_Before'])),data['PR_Before'], label="Pre EDS")
                plt.scatter(range(len(data['PR_After'])),data['PR_After'], label="Post EDS")
                # add the plot title
                plt.title("PR")
                # add the legend
                plt.legend(loc='upper right')
                # add axis limits
                x1,x2,y1,y2 = plt.axis()
                plt.axis([x1, x2, -1, 100])
                plt.xticks(np.arange(0, x2, 1), dates, fontsize=8, rotation=80)
            elif self.plot_mode.get() == 'SR':
                # plot a scatter plot
                plt.scatter(range(len(data['SR_Before'])),data['SR_Before'], label="Pre EDS")
                plt.scatter(range(len(data['SR_After'])),data['SR_After'], label="Post EDS")
                # add the plot title
                plt.title("SR")
                # add the legend
                plt.legend(loc='upper right')
                # add axis limits
                x1,x2,y1,y2 = plt.axis()
                plt.axis([x1, x2, -1, 100])
                plt.xticks(np.arange(0, x2, 1), dates, fontsize=8, rotation=80)
            #show the plot
            plt.show()
       
        else:
            self.error_label.config(text="Select Valid CSV File For Analysis")

    '''Non Button Functions'''
    # function to clear the mode buttons
    def clear_mode_buttons(self):
        self.eds_label.config(bg="white")
        #self.manual_label.config(bg="white")
        #self.noon_label.config(bg="white")
    
    # load sorted data as pandas dataframe
    def load_sorted(self,name):
        # file location for the csv file
        file = name
        # return pandas dataframe of the csv file
        df = pd.read_csv(file)
        # remove all NaN entries
        df.drop(df.filter(regex="Unname"),axis=1, inplace=True)
        return df
    
    # function to calculate the soiling rate of the table's data
    def calc_soiling_rate(self, mode):
        # check which mode of operation
        if self.mode == 'eds_data.csv':
            # get the file to find the soiling rate
            output = self.output_loc+"/eds_sorted.csv"
            df = self.load_sorted(output)
            labels = ['EDS1_PRE', 'EDS2_PRE', 'EDS3_PRE', 'EDS4_PRE', 'EDS5_PRE', 'CTRL1_PRE', 'CTRL2_PRE',
                      'EDS1_POST','EDS2_POST','EDS3_POST','EDS4_POST','EDS5_POST','CTRL1_POST','CTRL2_POST']
            # declare soiling ratio dictionary
            soiling_ratios = {
                'EDS1_PRE':[],
                'EDS2_PRE':[],
                'EDS3_PRE':[],
                'EDS4_PRE':[],
                'EDS5_PRE':[],
                'CTRL1_PRE':[],
                'CTRL2_PRE':[],
                'EDS1_POST':[],
                'EDS2_POST':[],
                'EDS3_POST':[],
                'EDS4_POST':[],
                'EDS5_POST':[],
                'CTRL1_POST':[],
                'CTRL2_POST':[],
            }
            # get the soiling ratio values
            data_SR = df[['EDS/CTRL(#)', 'SR_Before','SR_After']]
            data_SR.set_index('EDS/CTRL(#)', inplace=True)
            

            EDS1 = data_SR.loc[['EDS1']]
            EDS2 = data_SR.loc[['EDS2']]
            EDS3 = data_SR.loc[['EDS3']]
            EDS4 = data_SR.loc[['EDS4']]
            EDS5 = data_SR.loc[['EDS5']]
            CTRL1 = data_SR.loc[['CTRL1']]
            CTRL2 = data_SR.loc[['CTRL2']]

            #SR Before
            EDS1_Pre = EDS1[['SR_Before']].values.flatten()
            soiling_ratios['EDS1_PRE'].extend(EDS1_Pre)

            EDS2_Pre = EDS2[['SR_Before']].values.flatten()
            soiling_ratios['EDS2_PRE'].extend(EDS2_Pre)

            EDS3_Pre = EDS3[['SR_Before']].values.flatten()
            soiling_ratios['EDS3_PRE'].extend(EDS3_Pre)

            EDS4_Pre = EDS4[['SR_Before']].values.flatten()
            soiling_ratios['EDS4_PRE'].extend(EDS4_Pre)

            EDS5_Pre = EDS5[['SR_Before']].values.flatten()
            soiling_ratios['EDS5_PRE'].extend(EDS5_Pre)

            CTRL1_Pre = CTRL1[['SR_Before']].values.flatten()
            soiling_ratios['CTRL1_PRE'].extend(CTRL1_Pre)

            CTRL2_Pre = CTRL2[['SR_Before']].values.flatten()
            soiling_ratios['CTRL2_PRE'].extend(CTRL2_Pre)

            #Sr After
            EDS1_Post = EDS1[['SR_After']].values.flatten()
            soiling_ratios['EDS1_POST'].extend(EDS1_Post)

            EDS2_Post = EDS2[['SR_After']].values.flatten()
            soiling_ratios['EDS2_POST'].extend(EDS2_Post)

            EDS3_Post = EDS3[['SR_After']].values.flatten()
            soiling_ratios['EDS3_POST'].extend(EDS3_Post)

            EDS4_Post = EDS4[['SR_After']].values.flatten()
            soiling_ratios['EDS4_POST'].extend(EDS4_Post)

            EDS5_Post = EDS5[['SR_After']].values.flatten()
            soiling_ratios['EDS5_POST'].extend(EDS5_Post)

            CTRL1_Post = CTRL1[['SR_After']].values.flatten()
            soiling_ratios['CTRL1_POST'].extend(CTRL1_Post)

            CTRL2_Post = CTRL2[['SR_After']].values.flatten()
            soiling_ratios['CTRL2_POST'].extend(CTRL2_Post)

            # declare soiling rate dictionary
            soiling_rates = {
                'EDS1_PRE':0,
                'EDS2_PRE':0,
                'EDS3_PRE':0,
                'EDS4_PRE':0,
                'EDS5_PRE':0,
                'CTRL1_PRE':0,
                'CTRL2_PRE':0,
                'EDS1_POST':0,
                'EDS2_POST':0,
                'EDS3_POST':0,
                'EDS4_POST':0,
                'EDS5_POST':0,
                'CTRL1_POST':0,
                'CTRL2_POST':0,
            }
            # error check the data to make sure it can compute soiling rate
            if len(soiling_ratios['EDS1_PRE'])==0:
                return "error"
            elif len(soiling_ratios['EDS1_PRE'])==1:
                return "error"
            # calculate the soiling rate values
            for y in labels:
                soiling_rates[y] = stats.theilslopes(soiling_ratios[y], range(len(soiling_ratios[y])), 0.90)[0].round(2)
            # return the dictionary
            return soiling_rates
        elif self.mode == 'testing_data.csv':
            # update the soiling rate value
            self.sr_label.config(text= "Soiling Rate: N/A (This mode does not measure SR)")
        else:
            # return error
            self.error_label.config(text="Select Valid CSV File For Analysis")
    
    # error check the average day entry field
    def avg_entry_check(self, window):
        if self.window == '':
            self.error_label.config(text="Please fill in the average days entry field")
            return False
        elif self.window.isalpha():
            self.error_label.config(text="Please input a valid number in the average days entry field")
            return False
        elif int(self.window) <= 0:
            self.error_label.config(text="Please input a valid number in the average days entry field")
            return False
        else:
            return True
Exemplo n.º 12
0
class hostGUI:
    def __init__(self):
        '''
        The host's FTP client instance
        '''
        self.client = HostClient()
        self.fileDownloadClient = HostClient()
        '''
        Boolean for whether we're searching or not. defines the info to load into the table
        '''
        self.searching = False
        '''
        Assemble the GUI
        '''

        self.top = Tk()
        self.top.title("GV-Napster Host")
        self.top.protocol("WM_DELETE_WINDOW", self.onClose)
        #self.top.geometry("700x1200")

        self.fontStyle = tkFont.Font(root=self.top,
                                     family="Helvetica",
                                     size=20)

        self.font = tkFont.Font(family="Helvetica", size=12)

        self.top.option_add("*Font", self.font)

        self.connectionLabelFrame = LabelFrame(self.top, text="Connection")
        self.connectionLabelFrame.pack(fill="both", expand="yes")
        self.searchLabelFrame = LabelFrame(self.top, text="Search")
        self.searchLabelFrame.pack(fill="both", expand="yes")
        self.FTPLabelFrame = LabelFrame(self.top, text="FTP")
        self.FTPLabelFrame.pack(fill="both", expand="yes")

        self.connectionInputs = Frame(self.connectionLabelFrame)

        self.serverHostnameLabel = Label(self.connectionInputs,
                                         text="Server Hostname:")
        self.serverHostnameLabel.grid(row=0, column=0)
        self.serverHostnameText = Entry(self.connectionInputs)
        self.serverHostnameText.grid(row=0, column=1)

        self.usernameLabel = Label(self.connectionInputs, text="Username:"******"Port:")
        self.portLabel.grid(row=0, column=3)
        self.portText = Entry(self.connectionInputs)
        self.portText.grid(row=0, column=4)

        self.hostnameLabel = Label(self.connectionInputs, text="Hostname:")
        self.hostnameLabel.grid(row=1, column=3)
        self.hostnameText = Entry(self.connectionInputs)
        self.hostnameText.grid(row=1, column=4)

        self.speedFrame = Frame(self.connectionLabelFrame)
        self.connSpeedLabel = Label(self.speedFrame, text="Speed:")
        self.connSpeedLabel.pack(side=LEFT)
        self.connSpeedSelection = StringVar(self.top)
        self.speedChoices = {'Ethernet', "TL1", "TL2"}
        self.speedMenu = OptionMenu(self.speedFrame, self.connSpeedSelection,
                                    *self.speedChoices)
        self.speedMenu.pack(side=RIGHT)

        self.connectButton = Button(self.connectionLabelFrame,
                                    text="Connect",
                                    command=self.connect)

        self.searchKeywordFrame = Frame(self.searchLabelFrame)
        self.keywordLabel = Label(self.searchKeywordFrame, text="Keyword:")
        self.keywordLabel.grid(row=0, column=0)
        self.keywordText = Entry(self.searchKeywordFrame)
        self.keywordText.grid(row=0, column=1)
        self.searchButton = Button(self.searchKeywordFrame,
                                   text="Search",
                                   command=self.search)
        self.searchButton.grid(row=0, column=2)
        self.resetSearchButton = Button(self.searchKeywordFrame,
                                        text="Reset",
                                        command=self.resetSearch)
        self.resetSearchButton.grid(row=0, column=3)
        self.updateFileIndexButton = Button(self.searchKeywordFrame,
                                            text="Update File Index",
                                            command=self.updateFileIndex)
        self.updateFileIndexButton.grid(row=0, column=4)

        # working on a table, just a placeholder
        self.searchFrame = Frame(self.searchLabelFrame)
        self.searchTable = TableCanvas(self.searchFrame, width=800)
        self.searchTable.importCSV("files.csv")
        #self.searchTable = Text(self.searchLabelFrame, height=7)

        #removed because server now starts on GUI init
        #self.runServerFrame = Frame(self.FTPLabelFrame)
        #self.runServerButton = Button(self.runServerFrame, text="Start Server", bg="lawn green")
        #self.runServerButton.pack()

        self.getFileFrame = Frame(self.FTPLabelFrame)
        self.fileNameLabel = Label(self.getFileFrame, text="Filename:")
        self.fileNameLabel.grid(row=0, column=0)
        self.fileNameText = Entry(self.getFileFrame)
        self.fileNameText.grid(row=0, column=1)
        self.fileLocationLabel = Label(self.getFileFrame, text="Location:")
        self.fileLocationLabel.grid(row=0, column=2)
        self.fileLocationText = Entry(self.getFileFrame)
        self.fileLocationText.grid(row=0, column=3)
        self.filePortLabel = Label(self.getFileFrame, text="Port:")
        self.filePortLabel.grid(row=0, column=4)
        self.filePortText = Entry(self.getFileFrame)
        self.filePortText.grid(row=0, column=5)
        self.getFileButton = Button(self.getFileFrame,
                                    text="Download File",
                                    command=self.downloadFile)
        self.getFileButton.grid(row=0, column=6)

        self.addFileFrame = Frame(self.FTPLabelFrame)
        self.addFileNameLabel = Label(self.addFileFrame, text="Filename:")
        self.addFileNameLabel.grid(row=0, column=0)
        self.addFileNameText = Entry(self.addFileFrame)
        self.addFileNameText.grid(row=0, column=1)
        self.addFileDescLabel = Label(self.addFileFrame, text="Description:")
        self.addFileDescLabel.grid(row=0, column=2)
        self.addFileDescText = Entry(self.addFileFrame)
        self.addFileDescText.grid(row=0, column=3)
        self.addFileLocationLabel = Label(self.addFileFrame, text="Location:")
        self.addFileLocationLabel.grid(row=0, column=4)
        self.addFileLocationText = Entry(self.addFileFrame)
        self.addFileLocationText.grid(row=0, column=5)
        self.addFilePortLabel = Label(self.addFileFrame, text="Port:")
        self.addFilePortLabel.grid(row=0, column=6)
        self.addFilePortText = Entry(self.addFileFrame)
        self.addFilePortText.grid(row=0, column=7)
        self.speedLabel = Label(self.addFileFrame, text="Speed:")
        self.speedLabel.grid(row=0, column=8)
        self.speedSelection = StringVar(self.top)
        self.speedChoices = {'Ethernet', "TL1", "TL2"}
        self.speedMenu = OptionMenu(self.addFileFrame, self.speedSelection,
                                    *self.speedChoices)
        self.speedMenu.grid(row=0, column=9)
        self.addFileButton = Button(self.addFileFrame, text="Add File")
        self.addFileButton.grid(row=0, column=10)
        '''
        pack all frames in proper order (top to bottom)
        '''
        self.connectionInputs.pack()
        self.speedFrame.pack(side=TOP)
        self.connectButton.pack(side=BOTTOM)
        self.searchFrame.pack()
        self.searchTable.show()
        self.searchKeywordFrame.pack()
        #self.searchTable.pack()
        #self.runServerFrame.pack()
        self.getFileFrame.pack()
        self.addFileFrame.pack()

    def connect(self):
        serverHostname = self.serverHostnameText.get()
        port = self.portText.get()
        username = self.userNameText.get()
        hostname = self.hostnameText.get()
        #speed = self.speedMenu.get()
        self.centralServerPort = port
        self.centralServerURL = serverHostname
        print("Connecting to " + serverHostname + ":" + port + " as " +
              username + " from " + hostname + " at speed <later>...")
        connectionResult = self.client.connect(serverHostname, port, username)
        if (connectionResult == 1):
            messagebox.showerror(title="Server Connection",
                                 message="Connection Refused")
            return
        if (connectionResult == 2):
            messagebox.showerror(title="Server Authentication",
                                 message="Authentication Failed")
        else:
            print("Connected...")
            self.updateFileIndex()

    def downloadFile(self):
        filename = self.fileNameText.get()
        location = self.fileLocationText.get()
        port = self.filePortText.get()
        print("Downloading " + filename + " from " + location)
        self.fileDownloadClient.downloadFile(filename, location, port)

    def addFile(self):
        filename = self.addFileNameText.get()
        description = self.addFileDescText.get()
        location = self.addFileLocationText.get()
        port = self.addFilePortText.get()
        speed = self.speedSelection
        fileParams = [filename, description, location, port, speed]
        fileParams = ",".join(params)
        fullCentralServerURL = self.centralServerURL + ":" + self.centralServerPort
        response = req.request(method='SITE',
                               url=fullCentralServerURL,
                               params=fileParams)

    def search(self):
        print("Searching for keyword in current file index...")
        self.searching = True

        # perform search
        keyword = self.keywordText.get()
        if (keyword == ""):
            return

        self.searchFileIndex(keyword)

        #show results in table
        self.searchTable.importCSV("searchResults.csv")
        self.searchTable.redraw()

    def searchFileIndex(self, keyword):
        self.resetSearchIndex()
        matches = []
        i = 0
        with open('files.csv') as csvfile:
            readCSV = csv.reader(csvfile, delimiter=',')
            for row in readCSV:
                #print(row) # print the array at that row
                #print(row[0]) # print filename of that row
                #print(row[0],row[1],row[2],) # print filename, description, and path of row
                if (keyword in row[0]):
                    matches.append(row)
                    i = i + 1
        print("Number of Files Matching Keyword: " + str(i))

        with open('searchResults.csv', 'w') as searchResults:
            row = ['FILENAME', 'DESCRIPTION', 'LOCATION', 'PORT', 'SPEED']
            writer = csv.writer(searchResults)
            writer.writerow(row)
            for row in matches:
                print(row)
                #row = row[0] + "," + row[1] + "," + row[2] + "\n"
                writer.writerow(row)

    def resetSearch(self):
        self.searching = False
        self.resetSearchIndex()
        self.searchTable.importCSV("files.csv")
        self.searchTable.redraw()

    def runFTPCommand(self):
        print("Run FTP Command stand-in")

    def updateFileIndex(self):
        print("Updating file index...")
        #print("SEARCHING: " + str(self.searching))
        self.client.fetchFileIndex()
        if (self.searching == False):
            self.searchTable.importCSV("files.csv")
            self.searchTable.redraw()

        print("File index updated...")

    def resetFileIndex(self):
        with open('files.csv', 'w') as files:
            row = ['FILENAME', 'DESCRIPTION', 'LOCATION', 'PORT', 'SPEED']
            writer = csv.writer(files)

            writer.writerow(row)
            writer.writerow(['   '])

    def resetSearchIndex(self):
        with open('searchResults.csv', 'w') as searchResults:
            row = ['FILENAME', 'DESCRIPTION', 'LOCATION', 'PORT', 'SPEED']
            writer = csv.writer(searchResults)

            writer.writerow(row)
            writer.writerow(['   '])

    def onClose(self):
        print("Resetting file index...")
        self.resetFileIndex()
        print("Resetting search results...")
        self.resetSearchIndex()
        print("Quitting...")
        self.top.destroy()
        sys.exit(0)
Exemplo n.º 13
0
class GUI:
    def __init__(self):
        self.__window = Tk()
        self.__window.title("Supernormal GUI")
        self.__window.geometry('1600x900')

        os.chdir('..')
        # 读取数据
        self.__data = dict()
        self.locals = ["杭州", "上海", "北京", "广州", "深圳", '武汉', '宁波',
                       "苏州", '南京', '长沙', '成都', '重庆', '昆明', '西安',
                       '哈尔滨', '长春', '大连', '全部']
        self.__image_worldcloud = [[], []]
        self.__image_graphics = [[], []]
        self.load_data('全部')

        # two Frame,one for operation,another for show image and data
        frame_operation = Frame(self.__window, width=400, height=900, bd=1, relief="sunken", bg='white')
        frame_operation.pack(side=LEFT, fill=BOTH)
        frame_show = Frame(self.__window, width=1200, height=900, bd=1, relief="sunken", bg='gray')
        frame_show.pack(side=LEFT, fill=BOTH, expand=1)
        # 固定框架大小
        frame_operation.grid_propagate(0)

        # operating Button
        button_updata = Button(frame_operation, text='更新', height=4, width=20, bd=20,
                               font=('534E658769774F53', 20), command=self.updata)
        button_wordcloud = Button(frame_operation, text='词云', height=4, width=20, bd=20,
                                  font=('534E658769774F53', 20), command=self.wordcloud)
        button_graphics = Button(frame_operation, text='数据分析图表', height=4, width=20, bd=20,
                                 font=('534E658769774F53', 20), command=self.show_graphics)
        button_commendation = Button(frame_operation, text='推荐', height=4, width=20, bd=20,
                                     font=('534E658769774F53', 20), command=self.commendation)
        button_welfare = Button(frame_operation, text='福利', height=4, width=20, bd=20,
                                font=('534E658769774F53', 20), command=self.show_welfare)
        button_updata.grid(row=0, column=0, sticky=W+E+S+N)
        button_updata.grid_propagate(0)
        button_wordcloud.grid(row=1, column=0, sticky=W+E+S+N)
        button_wordcloud.grid_propagate(0)
        button_graphics.grid(row=2, column=0, sticky=W+E+S+N)
        button_graphics.grid_propagate(0)
        button_commendation.grid(row=3, column=0, sticky=W+E+S+N)
        button_commendation.grid_propagate(0)
        button_welfare.grid(row=4, column=0, sticky=W+E+S+N)
        button_welfare.grid_propagate(0)

        # show data
        frame_table = Frame(frame_show, relief="sunken", bg='white')
        frame_data = Frame(frame_show, relief="sunken", bg='white')
        frame_data.pack()
        frame_table.pack(fill=BOTH, expand=1)
        self.__combobox_show = ttk.Combobox(frame_data)
        self.__combobox_show['value'] = self.locals[:-1]
        self.__combobox_show.current(0)
        self.__combobox_show.pack(side=LEFT, fill=BOTH, expand=1)
        button_show = Button(frame_data, text='show', command=self.show_data)
        button_show.pack(side=LEFT, fill=BOTH, expand=1)
        table = Frame(frame_table)
        table.pack(fill=BOTH, expand=1)
        self.show_table = TableCanvas(table)
        self.show_data()
        mainloop()

    def load_data(self, local):
        # 加载数据
        if local == '全部':
            for local in self.locals[:-1]:
                self.__data[local] = pd.read_csv("commendation\\clear_data\\{}.csv".format(local),
                                                 encoding='gbk')

            self.__image_worldcloud = [[], []]
            self.__image_graphics = [[], []]
            for local in self.locals:
                self.__image_worldcloud[0].append(
                    ImageTk.PhotoImage(Image.open('view\\wordcloud\\工作领域词云图\\{}.png'
                                                  .format(local)).resize((800, 550))))
                if local != '全部':
                    self.__image_graphics[0].append(
                        ImageTk.PhotoImage(Image.open('view\\graphics\\networks\\{}.png'
                                                      .format(local)).resize((800, 550))))
            # welfare
            for local in self.locals:
                self.__image_worldcloud[1].append(
                    ImageTk.PhotoImage(Image.open('view\\wordcloud\\福利词云图\\{}福利.png'
                                                  .format(local)).resize((800, 550))))
                if local != '全部':
                    self.__image_graphics[1].append(
                        ImageTk.PhotoImage(Image.open('view\\graphics\\histogram\\{}.png'
                                                      .format(local)).resize((800, 550))))
        else:
            self.__data[local] = pd.read_csv("commendation\\clear_data\\{}.csv".format(local), encoding='gbk')
            index = self.locals.index(local)
            self.__image_worldcloud[0][index] = ImageTk.PhotoImage(Image.open('view\\wordcloud\\工作领域词云图\\{}.png'
                                                                              .format(local)).resize((800, 550)))
            self.__image_worldcloud[1][index] = ImageTk.PhotoImage(Image.open('view\\wordcloud\\福利词云图\\{}福利.png'
                                                                              .format(local)).resize((800, 550)))
            self.__image_graphics[0][index] = ImageTk.PhotoImage(Image.open('view\\graphics\\networks\\{}.png'
                                                                              .format(local)).resize((800, 550)))
            self.__image_graphics[1][index] = ImageTk.PhotoImage(Image.open('view\\graphics\\histogram\\{}.png'
                                                                              .format(local)).resize((800, 550)))

    def show_data(self):
        # 在显示框显示数据
        data = self.__combobox_show.get()
        self.show_table.importCSV("commendation\\clear_data\\{}.csv".format(data))
        self.show_table.show()

    def updata(self):
        # 更新数据
        # 生成窗口
        def updata_data():
            local = combobox_updata.get()
            # print(local)
            if local == '全部':
                # 爬起数据
                data.get_data(self.locals[:-1])
                # 数据处理
                value.data_clear(self.locals[:-1])
                fc.main(self.locals[:-1])
                # 重新加载数据
                self.load_data('全部')
            else:
                data.get_data([local])
                value.data_clear([local])
                fc.main([local])
                self.load_data(local)

            finish_updata = messagebox.askokcancel("提示!", '更新完毕!\nok退出!\ncancel继续更新!')
            if finish_updata:
                window_updata.destroy()

        window_updata = Toplevel(self.__window)
        window_updata.geometry('300x200')
        window_updata.title('updata')
        # 更新地区

        combobox_updata = ttk.Combobox(window_updata)
        combobox_updata['value'] = self.locals
        combobox_updata.current(0)
        combobox_updata.pack(padx=5, pady=10)
        button_updata = Button(window_updata, text='更新', font='534E658769774F53', command=updata_data)
        button_updata.pack()
        text_process = Text(window_updata)
        text_process.pack()
        text_process.insert(END,
                            "启动更新后,界面锁定!\n请不要随便退出!\nupdating...")

    def wordcloud(self):
        # 显示图片
        image = self.__image_worldcloud[0][0]
        title = '杭州'
        condition = 0

        # 显示词云
        window_wordcloud = Toplevel(self.__window)
        window_wordcloud.geometry('800x600')
        window_wordcloud.title('wordcloud')

        # 两个容器,放操作键和显示画面
        frame_operator = Frame(window_wordcloud, relief="sunken", bg='white')
        frame_show = Frame(window_wordcloud, relief="sunken", bg='white')
        frame_show.pack(fill=BOTH, expand=1)
        frame_operator.pack()

        # 画面显示
        image_label = Label(frame_show, image=image, anchor=CENTER)
        image_label.pack()

        def show_img_True():
            # welfare
            global condition
            global image
            # print('ok')
            image = self.__image_worldcloud[1][0]
            condition = 1
            image_label.configure(image=image)

        def show_img_False():
            # workarea
            global condition
            global image
            # print('ok')
            image = self.__image_worldcloud[0][0]
            condition = 0
            image_label.configure(image=image)

        def change_image1():
            # print('ok')
            # 上一张
            global condition
            global image
            index = self.__image_worldcloud[condition].index(image) - 1
            image = self.__image_worldcloud[condition][index]
            image_label.configure(image=image)
            label.configure(text=self.locals[index])

        def change_image0():
            # print('ok')
            # 下一张
            global condition
            global image
            index = (self.__image_worldcloud[condition].index(image) + 1) % 17
            image = self.__image_worldcloud[condition][index]
            image_label.configure(image=image)
            label.configure(text=self.locals[index])

        # 操作按钮
        welfare_wordcloud_button = Button(frame_operator, text='工作领域', command=show_img_False)
        workarea_wordcloud_button = Button(frame_operator, text='福利', command=show_img_True)
        last_wordcloud_button = Button(frame_operator,
                                       text="上一张",
                                       command=change_image1)
        next_wordcloud_button = Button(frame_operator,
                                       text="下一张",
                                       command=change_image0)
        label = Label(frame_operator, text=title)
        label.pack(side=LEFT)
        welfare_wordcloud_button.pack(side=LEFT)
        workarea_wordcloud_button.pack(side=LEFT)
        last_wordcloud_button.pack(side=LEFT)
        next_wordcloud_button.pack(side=LEFT)

    def show_welfare(self):
        # 生成窗口
        window_welfare = Toplevel(self.__window)
        window_welfare.geometry('800x600')
        window_welfare.title('welfare')

        # 滚动条
        scrollbar = Scrollbar(window_welfare, orient=HORIZONTAL)
        scrollbar.pack(side=BOTTOM, fill=X)
        text_welfare = Text(window_welfare, xscrollcommand=scrollbar.set,
                            wrap=NONE)
        text_welfare.pack(expand=YES, fill=BOTH)
        scrollbar.config(command=text_welfare.xview)

        with open('commendation\\classify_welfare.txt', 'r') as f:
            for line in f:
                text_welfare.insert(END, line)
                text_welfare.insert(END, '\n')
            f.close()
        text_welfare['state'] = DISABLED

    def show_graphics(self):
        # 显示图片
        image = self.__image_graphics[0][0]
        title = '杭州'
        condition = 0

        # 显示图表
        window_graphics = Toplevel(self.__window)
        window_graphics.geometry('800x600')
        window_graphics.title('graphics')

        # 两个容器,放操作键和显示画面
        frame_operator = Frame(window_graphics, relief="sunken", bg='white')
        frame_show = Frame(window_graphics, relief="sunken", bg='white')
        frame_show.pack(fill=BOTH, expand=1)
        frame_operator.pack()

        # 画面显示
        image_label = Label(frame_show, image=image, anchor=CENTER)
        image_label.pack()

        def show_img_True():
            # welfare
            global condition
            global image
            # print('ok')
            image = self.__image_graphics[1][0]
            condition = 1
            image_label.configure(image=image)

        def show_img_False():
            # workarea
            global condition
            global image
            # print('ok')
            image = self.__image_graphics[0][0]
            condition = 0
            image_label.configure(image=image)

        def change_image1():
            # print('ok')
            # 上一张
            global condition
            global image
            index = self.__image_graphics[condition].index(image) - 1
            image = self.__image_graphics[condition][index]
            image_label.configure(image=image)
            label.configure(text=self.locals[index])

        def change_image0():
            # print('ok')
            # 下一张
            global condition
            global image
            index = (self.__image_graphics[condition].index(image) + 1) % 16
            image = self.__image_graphics[condition][index]
            image_label.configure(image=image)
            label.configure(text=self.locals[index])

        # 操作按钮
        welfare_graphics_button = Button(frame_operator, text='networks', command=show_img_False)
        workarea_graphics_button = Button(frame_operator, text='histogram', command=show_img_True)
        last_graphics_button = Button(frame_operator,
                                       text="上一张",
                                       command=change_image1)
        next_graphics_button = Button(frame_operator,
                                       text="下一张",
                                       command=change_image0)
        label = Label(frame_operator, text=title)
        label.pack(side=LEFT)
        welfare_graphics_button.pack(side=LEFT)
        workarea_graphics_button.pack(side=LEFT)
        last_graphics_button.pack(side=LEFT)
        next_graphics_button.pack(side=LEFT)


    def commendation(self):
        # 生成窗口
        window_commendation = Toplevel(self.__window)
        window_commendation.geometry('420x200')
        window_commendation.title('commendation')

        label_location = Label(window_commendation, text='工作位置:')
        label_location.grid(row=0, column=0)
        combobox_location = ttk.Combobox(window_commendation)
        combobox_location['value'] = self.locals
        combobox_location.current(0)
        combobox_location.grid(row=0, column=1, sticky=W)

        label_work = Label(window_commendation, text='工作:')
        label_work.grid(row=1, column=0)
        entry_work = Entry(window_commendation)
        entry_work.grid(row=1, column=1,sticky=W)

        label_company = Label(window_commendation, text='公司:')
        label_company.grid(row=2, column=0)
        entry_company = Entry(window_commendation)
        entry_company.grid(row=2, column=1,sticky=W)

        label_area_company = Label(window_commendation, text='公司性质:')
        label_area_company.grid(row=3, column=0)
        combobox_area_company = ttk.Combobox(window_commendation,state="readonly")
        combobox_area_company['value'] = ['创业公司', '非营利组织', '国企', '合资', '民营公司', '上市公司',
                                          '事业单位', '外企代表处', '外资(非欧美)', '外资(欧美)', '政府机关',"<空白>"]
        combobox_area_company.grid(row=3, column=1,sticky=W)

        label_area_company_work = Label(window_commendation, text='公司领域:')
        label_area_company_work.grid(row=4, column=0)
        combobox_area_company_work = ttk.Combobox(window_commendation,state="readonly")
        combobox_area_company_work_value = []
        # 读取公司领域数据
        with open('commendation\\notes.txt', 'r', encoding='utf-8') as f:
            for line in f:
                combobox_area_company_work_value.append(line.replace("\n","").split(" "))
            f.close()

        combobox_area_company_work['value'] = [x[0] for x in combobox_area_company_work_value]
        combobox_area_company_work.grid(row=4, column=1,sticky=W)
        combobox_area_company_work_ = ttk.Combobox(window_commendation,values=["<空白>"],state="readonly")
        combobox_area_company_work_.grid(row=4,column=2,sticky=W)
        # 当选择第一个框中元素,第二个框的元素改变
        def change(index):
            values = combobox_area_company_work_value[combobox_area_company_work.current()] + ["<空白>"]
            combobox_area_company_work_.config(values=values[1:])
            combobox_area_company_work_.current(0)
        combobox_area_company_work.bind("<<ComboboxSelected>>", change)

        label_welfare = Label(window_commendation, text='福利:')
        label_welfare.grid(row=5, column=0)
        entry_welfare = Entry(window_commendation)
        entry_welfare.grid(row=5, column=1,sticky=W)

        # 推荐
        def commendation():
            global data
            # 确定推荐范围
            if combobox_location.get() == "全部":
                data = pd.concat(self.__data.values())
                data = data.reset_index(drop=True)
                self.__combobox_show.set(combobox_location.get())
            else:
                data = self.__data[combobox_location.get()]
                self.__combobox_show.set(combobox_location.get())
            # 推荐工作
            if entry_work.get() != "":
                work = entry_work.get()
                work = '|'.join(jieba.lcut(work, cut_all=True, HMM=True))
                data = data[data['岗位'].str.contains(work)]

            # 推荐公司
            if entry_company.get() != "":
                company = entry_company.get()
                data = data[data['公司'].str.contains(company)]

            #公司性质
            if combobox_area_company.get() != '<空白>':
                data = data[data['公司性质'].str.contains(combobox_area_company.get(),na=False)]

            # 公司领域
            if combobox_area_company_work_ != '<空白>':
                data = data[data['工作领域'].str.contains(combobox_area_company_work_.get(),na=False)]
            # 福利
            if entry_welfare != '':
                data = data[data['福利'].str.contains(entry_welfare.get(),na=False)]
            # 输出
            data = data.sort_values(by='平均薪资',ascending=False,kind='heapsort')
            data.to_csv("commendation\\commendation_data.csv",encoding='gbk',index=False)
            self.show_table.importCSV('commendation\\commendation_data.csv')
            self.show_table.show()
            window_commendation.destroy()

        button_commendation = Button(window_commendation, text='OK', height=2, width=10, fg='red', font='534E658769774F53', command=commendation)
        button_commendation.grid(row=6,column=2,sticky=E)
Exemplo n.º 14
0
    def __init__(self, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
        _fgcolor = '#000000'  # X11 color: 'black'
        _compcolor = '#d9d9d9' # X11 color: 'gray85'
        _ana1color = '#d9d9d9' # X11 color: 'gray85'
        _ana2color = '#ececec' # Closest X11 color: 'gray92'
        font9 = "-family {Segoe UI} -size 14 -weight bold"
        font91 = "-family {Segoe UI} -size 8 -weight bold"

        top.geometry("600x450+406+135")
        top.title("New Toplevel")
        top.configure(background="#d9d9d9")
        top.configure(highlightbackground="#d9d9d9")
        top.configure(highlightcolor="black")

        self.Label1 = tk.Label(top)
        self.Label1.place(relx=0.0, rely=-0.022, height=831, width=1380)
        self.Label1.configure(activebackground="#f9f9f9")
        self.Label1.configure(activeforeground="#000000")
        self.Label1.configure(background="#0d0819")
        self.Label1.configure(disabledforeground="#a3a3a3")
        self.Label1.configure(font=font9)
        self.Label1.configure(foreground="#000000")
        self.Label1.configure(highlightbackground="#d9d9d9")
        self.Label1.configure(highlightcolor="black")
        photo_location = os.path.join(prog_location,"art.png")
        self._img0 = tk.PhotoImage(file=photo_location)
        self.Label1.configure(image=self._img0)
        #self.Label1.configure(text='''Label''')

        self.Label2 = tk.Label(top)
        self.Label2.place(relx=0.35, rely=0.689, height=71, width=304)
        self.Label2.configure(activebackground="#f9f9f9")
        self.Label2.configure(activeforeground="black")
        self.Label2.configure(background="#d9d9d9")
        self.Label2.configure(disabledforeground="#a3a3a3")
        self.Label2.configure(font=font9)
        self.Label2.configure(foreground="#000000")
        self.Label2.configure(highlightbackground="#d9d9d9")
        self.Label2.configure(highlightcolor="black")
        self.Label2.configure(text=z)


##
       # the_text_widget = tk.Text(top,height=4,width=50)
        #data=""
##        with open("sub.csv", "r") as f:
##                  data1 = f.read()
##                  data=data + data1[8:]
##                 # the_text_widget.insert("1.0", data)

       
        
##        with open("sub.csv") as inf:
##            rowr=csv.reader(inf,delimiter=',')
##            a=tabulate(rowr)

           
        self.tframe = tk.Frame(top)
       
        self.tframe.pack()
        
        
        table = TableCanvas(self.tframe,cellwidth=5000, width="1000",	
                 
               editable=False
              )
       
       
        
       

        table.show()
    
       
        
        
        table.redraw()
        
        table.importCSV("sub.csv")
Exemplo n.º 15
0
    inplace=True)

games_prediction = games_prediction[['Date', 'Visitor', 'Visitor Win%', 'Home', 'Home Win%']]

elos.to_csv('elos.csv', index=True)
games_prediction.to_csv('prediction.csv', index=False)


root = Tk()
root.title('NHL Elo Predictions')
root.geometry('800x600')
one = Label(root, text='NHL Elo Rankings', bg='blue', fg='white')
one.pack()
tframe = Frame(root)
tframe.pack()
table = TableCanvas(tframe, rowheaderwidth=0,
                    cellwidth=100, editable=False, width=325)
table.importCSV('elos.csv')
table.sortTable(columnName='Elo Rating', reverse=1)
colIndex = 1
table.show()
two = Label(root, text='Games Today', bg='blue', fg='white')
two.pack()
tframe2 = Frame(root)
tframe2.pack()
table2 = TableCanvas(tframe2, rowheaderwidth=0, editable=False, width=725)
table2.importCSV('prediction.csv')
table2.show()

root.mainloop()