Example #1
0
 def fileselect(self):
     #Create a set of variables to pass back to main program.
     global filePath1
     global filePath2 
     filePath1 = ""
     filePath2 = ""
     #self.master.withdraw()
     status_1 = 0
     status_2 = 0
     while filePath1 == "":
         if status_1 == 1:
             error_msg("Error","Please select a valid file.")
         filePath1 = tk.askopenfilename(title="Open First PDF (Old Drawing)")
         if platform == "win32":					   
             filePath1 = filePath1.replace("/","\\\\")
         status_1 = 1
     
     while filePath2 == "":
         if status_2 == 1:
             error_msg("Error","Please select a valid file.")
         filePath2 = tk.askopenfilename(title="Open Second PDF (New Drawing)")
         if platform == "win32":					   
             filePath2 = filePath2.replace("/","\\\\")
         status_2 = 1
     print ("Old Drawing: "+filePath1+"\n")  #Display first filepath
     print ("New Drawing: "+filePath2+"\n")  #Display second filepath
     #self.master.deiconify()
     v_status.set("Processing images...")
     v_status_f.set("Old Drawing:\n"+filePath1+"\n"+"New Drawing:\n"+filePath2)
     self.update_idletasks()
     maketmp(tempdir)
     process_images()
     self.master.destroy()
def callback(type):
    if type == 'transfer':
        transfer_callback()
    elif type == 'content':
        global content_input
        # return file full path
        fname = askopenfilename(title='Select content image',
                                filetypes=[('image', '*.jpg'),
                                           ('All Files', '*')])
        if fname == '':
            return
        content_input = fname
        print('content image path: ', content_input)
        paint.update_img('content', content_input)

    elif type == 'style':
        global style_input
        # return file full path
        fname = askopenfilename(title='Select style image')
        if fname == '':
            return
        style_input = fname
        print('style image path: ', style_input)
        paint.update_img('style', style_input)

    elif type == 'cancel':
        sys.exit()
Example #3
0
def main():
    # By default Tk shows an empty window, remove it
    tkinter.Tk().withdraw()

    input('Press enter to select the base file')
    baseFilePath = askopenfilename(title='Select the base file to read')
    print('Base file: ' + baseFilePath)

    input('Press enter to select the merge file')
    mergeFilePath = askopenfilename(title='Select the merge file to read')
    print('Merge file: ' + mergeFilePath)
    
    input('Press enter to select the save file')
    saveFilePath = asksaveasfilename()
    print('Save file: ' + saveFilePath)

    baseFile = csv.reader(open(baseFilePath, 'r', encoding='utf-8'))
    mergeFile = deque(csv.reader(open(mergeFilePath, 'r', encoding='utf-8')))
    saveFile = csv.writer(open(saveFilePath, 'w', encoding='utf-8'), delimiter=';', quoting=csv.QUOTE_NONE)

    mergeRow = mergeFile.popleft()
    for baseRow in baseFile:
        if mergeRow[0] == baseRow[0]:
            mergeCol = mergeRow[1]
            try:
                mergeRow = mergeFile.popleft()
            except:
                pass
        else:
            mergeCol = ''

        saveFile.writerow([baseRow[0], mergeCol, baseRow[1]])
Example #4
0
 def __init__(self, master, restore_project=False, **kw):
     Frame.__init__(self, master, **kw)
     
     #Load a project
     if restore_project:
         self.project = templify.Project.load(filedialog.askopenfilename())
     else:
         self.project = templify.Project(sample_file=filedialog.askopenfilename())
                 
     #Text
     self.text = Text(self)
     self.init_text()
     
     #Scrollbars
     self.vertical_scrollbar = ttk.Scrollbar(self)
     self.horizontal_scrollbar = ttk.Scrollbar(self)
     self.init_scrollbars()
     
     #Pop-up menu
     self.pop_up_menu = Menu(self)
     self.init_pop_up_menu()
     
     #Layout management        
     self.grid_conf()
     
     #Binding management
     self.master.bind('<Control-s>', lambda e:self.project.save())
     self.master.bind('<3>', lambda e: self.pop_up_menu.post(e.x_root, e.y_root))
Example #5
0
def getfile(var):
    if var == "ours":
        global ours, invname
        ours = filedialog.askopenfilename(filetypes=[("CSV files", "*.csv")], title="OUR CSV")
        invname.set(ours)
    elif var == "wh":
        global warehouse, bv, whname
        bv = filedialog.askopenfilename(filetypes=[("CSV files", "*.csv")], title="BELVEDERE CSV")
        whname.set(bv)
        warehouse = csv.reader(open(bv, "rt"))
Example #6
0
def getfile(var):
    if var == "ours":
        global inventory, ours, invname
        ours = filedialog.askopenfilename(filetypes=[("CSV files", "*.csv")], title="OUR CSV")
        invname.set(ours)
        inventory = csv.reader(open(ours, "rt"))
    elif var == "wh":
        global warehouse, wh, whname
        wh = filedialog.askopenfilename(filetypes=[("CSV files", "*.csv")], title="MAURI CSV")
        whname.set(wh)
        warehouse = csv.reader(open(wh, "rt"))
Example #7
0
 def loadWorkSpace(self):
     if self.workspace == None:
         self.workspace = ws.Workspace(self.root, widgets.StatusBar(self.root, self.images), self.images, gridX = 32, gridY = 32, width = 1920 * 3, height = 1080, option = con.WCC["LOAD"], 
                                       file = fd.askopenfilename(parent = self.root, defaultextension = ".blml", title = "Open", filetypes=[("rbr level file", ".blml"), ("All files", ".*")]))
         self.root.config(menu = widgets.MenuBar(self.root, self.workspace, self.images, self.newWorkSpace, self.loadWorkSpace))
     else:
         self.workspace.destroy()
         self.workspace = ws.Workspace(self.root, widgets.StatusBar(self.root, self.images), self.images, gridX = 32, gridY = 32, width = 1920 * 3, height = 1080, option = con.WCC["LOAD"], 
                                       file = fd.askopenfilename(parent = self.root, defaultextension = ".blml", title = "Open", filetypes=[("rbr level file", ".blml"), ("All files", ".*")]))
         self.root.config(menu = widgets.MenuBar(self.root, self.workspace, self.images, self.newWorkSpace, self.loadWorkSpace))
         
def open_file_log(event, child, login):
    flag = True
    while(flag):
        try:
            file_voice_log = fd.askopenfilename()
            file_voice_pass = fd.askopenfilename()
        except:
            print("Невозможно открыть выбрать файл")
        else:
            flag = False
            registr_login(event, child, file_voice_log, file_voice_pass, login)
Example #9
0
    def get_filename(self, init_dir, name, filetype):
        """
        This function sets the filename of the input csv file

        :param init_dir: Initial directory to look for input csv files
        :param name: Name of the selecting button
        :param filetype: File type allowed as the input
        """
        try:
            self.filename =  filedialog.askopenfilename(initialdir = init_dir,title = name,filetypes = (filetype,("csv files","*.csv")))
        except Exception as inst:
            self.pop_up(inst)
            self.filename =  filedialog.askopenfilename(initialdir = init_dir,title = name,filetypes = (filetype,("csv files","*.csv")))
def open_file_enter(event, child):
    flag = True
    while(flag):
        try:
            file_voice_log = fd.askopenfilename()
            file_voice_pass = fd.askopenfilename()
        except:
            print("Невозможно открыть выбрать файл")
        else:
            flag = False
            but_ok = tk.Button(child, text = 'ok')
            but_ok.pack()
            but_ok.bind("<Button-1>", lambda event:search_login(event, child, file_voice_log, file_voice_pass))
    def openDirSearchBox(data, canvas):
        if (data.mode == "mainProgram"):
            fileOpened = filedialog.askopenfilename()

            # Check if correct file type:
            while (not fileOpened.endswith(".gif") and (fileOpened != "")):
                tkinter.messagebox.showinfo("Warning", 
                        "Upload an IMAGE(.gif), please.")
                fileOpened = filedialog.askopenfilename()

            data.filename = fileOpened
            init(data, canvas)

        canvas.update()
Example #12
0
    def loadChoreography(self):

        if self.debug_FLAG:
            if self.db == 'salsa':
                tempf =self.debug_fastaccess
                tempf = list(tempf)
                tempf[0] = tempf[0].upper()
                tempf = ''.join(tempf)

                fname = "Data\\Salsa\\SVL\\" + tempf + "_DanceAnnotationTool.svl"

            elif self.db == 'calus':
                fname = "Data\\Calus\\DanceAnnotationTool.txt"
        else:
            if self.db == 'salsa':
                fname  = askopenfilename(initialdir='Data\\Salsa\\SVL', filetypes=(("svl file", "*.svl"), ("txt file", "*.txt"), ("All files", "*.*") ))
            elif self.db == 'calus':
                fname  = askopenfilename(initialdir='Data\\Calus', filetypes=(("txt file", "*.txt"), ("svl file", "*.svl"), ("All files", "*.*") ))



        dummy, fextension = os.path.splitext(fname)

        if fname:
            try:
                if fextension == '.svl':
                    params, self.annotationSecs, self.labels = readsvl.extractSvlAnnotRegionFile(fname)
                    self.entry_name_choreo.insert(0,"..." + fname[-30:])
                    self.choreoStatusSTR.set(str(len(self.labels)) + " labels")
                    self.choreoLoadedFlag = True
                    self.checkContinueEnable()
                elif fextension == '.txt':
                    self.annotationSecs, self.labels, self.annotationSecsB, self.labelsB = readtxt.parse(fname)
                    self.entry_name_choreo.insert(0,"..." + fname[-30:])
                    self.choreoStatusSTR.set(str(len(self.labels)) + " labels")
                    self.choreoLoadedFlag = True
                    self.checkContinueEnable()
                else:
                    showerror("Waring", "Parser does not exists for such a file, only svl or txt are supported")

            except Exception as e:
                self.choreoLoadedFlag = False
                self.checkContinueEnable()
                msg = "There was a problem in loading!\n'%s'" % e
                if messagebox.askyesno("Error", msg + "\n" + "Do you want to choose another file?"):
                    self.loadChoreography()
                else:
                    return
        return
Example #13
0
 def ask_load(filepath, filetypes=None):
     """ Pop-up to get path to a file """
     if filetypes is None:
         filename = filedialog.askopenfilename()
     else:
         # In case filetypes were not configured properly in the
         # arguments_list
         try:
             filename = filedialog.askopenfilename(filetypes=filetypes)
         except TclError as te1:
             filetypes = FileFullPaths.prep_filetypes(filetypes)
             filename = filedialog.askopenfilename(filetypes=filetypes)
         except TclError as te2:
             filename = filedialog.askopenfilename()
     if filename:
         filepath.set(filename)
Example #14
0
 def do_open(self):
     self.status.info()
     file_name = askopenfilename(filetypes=[("signal descriptor", ".py")],
                                 title="Open Signal File",
                                 parent= self.root)
     if file_name:
         module = self.load_signal_file(file_name)
Example #15
0
	def pick_gif( self ):
		gif = filedialog.askopenfilename( filetypes=[("GIF", "*.gif"), ], initialdir="." )
		if gif:
			self.gif_file = gif
			self.start_button.config( state=tkinter.NORMAL )
			self.test_button.config( state=tkinter.NORMAL )
			self.create_player_win()
Example #16
0
    def get_dir(self):
        '''Open a box to select
        the file.'''

        fname = askopenfilename()
        self.fpath.set(fname)
        return
Example #17
0
    def __init__(self, type='GUI', args='', wm=None):
        """Construct a new implosion."""
        super(Hyades, self).__init__()
        self.__ready__ = False

        # Get file to open based on type:
        if type is 'GUI':
            from tkinter.filedialog import askopenfilename
            FILEOPENOPTIONS = dict(defaultextension='.nc',
                           filetypes=[('Hyades netCDF','*.nc')],
                           multiple=False)
            filename = askopenfilename(**FILEOPENOPTIONS)
        elif type is 'File':
            filename = args
        elif type is 'CLI':
            # TODO: CLI args
            filename = input("HYADES file: ")
        else:
            raise ValueError('Type passed to Hyades constructor is invalid: ' + type)

        # Check that file exists, and that extension is correct:
        if not os.path.isfile(filename):
            raise FileNotFoundError('Could not find HYADES file: ' + filename)
        if not filename[-3:] == '.nc':
            raise FileNotFoundError('Invalid file type in HYADES: ' + filename)

        # Set a few instance variables:
        self.filename = filename
        self.runProgress = 0.
        self.__ready__ = True
def browseOutput():
    outputFilename = filedialog.askopenfilename()
    entry_outputFileName.delete(0, END)
    entry_outputFileName.insert(END, outputFilename)
    # text_log.insert(END, "i am browse output\n")
    global configOutputFilename
    configOutputFilename = entry_outputFileName.get()
Example #19
0
 def upload(self):
     uploadname = filedialog.askopenfilename()     #creates window to find file
     
     if uploadname != '':
         with open(uploadname, 'r') as fp:
             data, var_data = json.load(fp)
             
         for key, value in data.items():    
             if data[key] == None:
                 self.text_variable[key].set('None') #replace current StringVar with String 'None'
             elif key == 'g_robot_var':
                 self.g_robot_var.set(value)
             elif key == c.STL_FLAG:
                 self.stl_path = value
                 if self.stl_path:
                     self.text_variable[key].set(os.path.basename(os.path.normpath(self.stl_path)))
                 else:
                     self.text_variable[key].set(self.stl_path)
             elif key in self.text_variable.keys():
                 value = str(value)
                 value = value.replace('[','')
                 value = value.replace(']','')
                 self.text_variable[key].set(value)   #replace current StringVar values with data from JSON file
                 
         if var_data:
             for key, value in var_data.items():
                 self.var_saved[key] = value
def main() :
    """Code to read a file and assess its adherence to standards"""
    global fileDict
    
    fileDict = {}
    print("\nOpening a file—look for dialog box:")
    sys.stdout.flush()
    win = Tk() # root window for tkinter file dialog
    win.attributes('-topmost', True)
    win.withdraw() # hide root window
    win.lift() # move to front
    filename = filedialog.askopenfilename(parent=win) # get file name
    #            message="Pick a Python file to check") # label on dialog box
    win.destroy() # get rid of root window
    print("Opening file %s, assumed to be a Python file\n" % filename)
    analyzeFile(filename)

    if DEBUG_LEVEL > 0 :
        tokenParts = set(name for name in dir(tokenize) if name.isupper() 
                 and type(eval("tokenize." + name))==int) # tokenize constants
        tokenCodes = sorted([(eval("tokenize." + name),name) for 
                 name in tokenParts]) # codes corresponding to tokenParts
        print("\nTable of token codes")    
        for code, name in tokenCodes:
            print("%5d %s" % (code, name))
                                                         
    showTermination()
    return
Example #21
0
def confirm_name(info_lines, line_num, filetypes, title):
    """GUI asks user to choose a file/directory if the existing cannot be found"""

    # set initial variables, if filetypes is blank, then a directory is wanted
    path = info_lines[line_num - 1].rstrip('\r\n')
    directory = filetypes is None

    # if the path does not exist, prompt for a new one
    if not os.path.exists(path):
        if DEBUG:
            print("path " + str(path) + " does not exist")
        Tk().withdraw()
        if directory:
            path = askdirectory(title = title)
        else:
            path = askopenfilename(filetypes = filetypes, title = title)

        # throw SystemExit exception if the user does not choose a valid path
        if not os.path.exists(path):
            sys.exit() 

        # save the new path to the array if the user chooses a valid path
        else:
            if DEBUG:
                print(str(info_lines[line_num - 1]).rstrip('\r\n') +
                      " will be changed to " + str(path))
            info_lines[line_num - 1] = path + "\n"
    elif DEBUG:
        print(str(path) + " exists")

    return path
Example #22
0
def OpenFile():
    f= filedialog.askopenfilename()
    o=open(f,'r')
    t=o.read()
    text.delete(0.0,END)
    text.insert(0.0,t)
    o.close()
Example #23
0
 def open(self):
     filen = filedialog.askopenfilename(
             defaultextension=".js",
             initialfile="worldfile.js",
             initialdir="../",
             filetypes=(("Javascript files", "*.js"),
                        ("All files", "*")),
             title="Save")
     if filen != () and filen != "":
         with open(filen, "r") as fileo:
             header = fileo.readline()
             if header != "var worldfile = \n":
                 print("Not a proper worldfile")
                 return
             data = fileo.readline()
             self.roomset.load(json.loads(data))
         self.drawgrid(0,0)
         self.currentx = 0
         self.currenty = 0
         self.room = self.roomset.getroom(0,0)
         self.drawroom()
         self.objectlist.delete(0, tk.END)
         for i,x in enumerate(self.room.objects):
             if (x[0] >= 200):
                 self.objectlist.insert(
                     i, "Arbitrary {}: {}, {}".format(*x))
             else:
                 self.objectlist.insert(
                     i, "{}: {}, {}".format(Type[x[0]], x[1], x[2]))
Example #24
0
 def import_datashop_file(self):
     
     filename = filedialog.askopenfilename()
     
     with open(filename,"r") as filein:
         header_line = filein.readline()
         headers = header_line.split("\t")
     
     filelen = file_len(filename)       
     count =0
     
     with open(filename,"r") as filein:
         filein.readline() #skip header line
         while 1:
             line = filein.readline()
             if not line:
                 break
             
             rt.status.config(text="Status: Importing Datashop file... " + str(count) + " / " + str(filelen))
             rt.status.update_idletasks()
             
             count+=1
             
             values = line.split("\t")
             transaction = dict(zip(headers,values))
             
             skills = get_skills(transaction)
             
             #("problem_name","step_text","transaction_text","skill_names","outcome")
             rt.treeview.insert("","end",text= "Transaction", values=(transaction["Problem Name"],transaction["Step Name"],transaction["Transaction Id"],json.dumps(skills),transaction["Outcome"]))
     
     rt.status.config(text="Status: Idle")
     rt.status.update_idletasks()
     
     print("file " + filename)
    def openImage(self):
        #create file dialog to open image
        self.imgName = filedialog.askopenfilename()
        #open image
        self.openImage = Image.open(self.imgName)
        #get image file type
        self.imgType = str(self.openImage.format)

        #get image size
        self.imageWidth, self.imageHeight = self.openImage.size
        #if image proportions are too big, shrink them to max
        if self.imageWidth > self.screenWidth:
            self.imageWidth = self.screenWidth - 200
        if self.imageHeight > self.screenHeight:
            self.imageHeight = self.screenHeight - 200

        #create default image object for label (resize to take care of any image proportions exceeding maximum)
        self.defaultImage = self.openImage.resize((self.imageWidth, self.imageHeight), Image.ANTIALIAS)
        self.Image = ImageTk.PhotoImage(self.defaultImage)
        #create  image label
        self.imageLabel = ttk.Label(self.imageFrame, image = self.Image)
        self.imageLabel.grid(row = 0, column = 0)

        #set scalebars to default image size
        self.widthScale.set(self.imageWidth)
        self.heightScale.set(self.imageHeight)

        #set image present variable to on (1)
        self.imagePresent = 1
Example #26
0
   def auto(self, id):
      if (id == AutoSel.OPEN):
         gcodefile = filedialog.askopenfilename(parent=self, title="Open Gcode File")
         if (len(gcodefile) != 0):
            self.auto_val.set(gcodefile)
            self.display_max_line(gcodefile)
      elif (id == AutoSel.RUN):
         gcodefile = self.auto_val.get()
         if (gcodefile == ''):
            return
         if (not self.safety_check_ok()):
            return

         self.display_max_line(gcodefile)
         self.set_idle_state(ButtonState.BUSY)
         m = {}
         m['id'] = MechEvent.CMD_RUN
         m['file'] = gcodefile
         self.mechq.put(m)
         self.bp3d.clear_plot()
      else:
         gcodefile = self.auto_val.get()
         if (gcodefile == ''):
            return
         if (self.dog.get_state() & MechStateBit.VERIFY):
            self.dog.verify_cancel()
         else:
            self.display_max_line(gcodefile)
            self.set_idle_state(ButtonState.VERIFY)
            m = {}
            m['id'] = MechEvent.CMD_VERIFY
            m['file'] = gcodefile
            self.mechq.put(m)
            self.bp3d.clear_plot()
Example #27
0
 def loadFile(self):
     self.loadPath = filedialog.askopenfilename()
     self.textBox.delete(1.0, END)
     self.loadTxt = open(self.loadPath, "r")
     self.textBox.insert(1.0, str(self.loadTxt.read()).strip())
     self.loadTxt.close()
     return self.loadPath
Example #28
0
 def on_file_menuitem_clicked(self, itemid):
     if itemid == 'file_new':
         new = True
         if self.is_changed:
             new = openfile = messagebox.askokcancel( _('File changed'),
                 _('Changes not saved. Discard Changes?') )
         if new:
             self.previewer.remove_all()
             self.tree_editor.remove_all()
             self.properties_editor.hide_all()
             self.currentfile = None
             self.is_changed = False
             self.project_name.configure(text=_('<None>'))
     elif  itemid == 'file_open':
         openfile = True
         if self.is_changed:
             openfile = messagebox.askokcancel(_('File changed'),
                 _('Changes not saved. Open new file anyway?'))
         if openfile:
             options = { 'defaultextension': '.ui',
                 'filetypes':((_('pygubu ui'), '*.ui'), (_('All'), '*.*')) }
             fname = filedialog.askopenfilename(**options)
             if fname:
                 self.load_file(fname)
     elif  itemid == 'file_save':
         if self.currentfile:
             if self.is_changed:
                 self.do_save(self.currentfile)
         else:
             self.do_save_as()
     elif  itemid == 'file_saveas':
         self.do_save_as()
     elif  itemid == 'file_quit':
         self.quit()
Example #29
0
def open_project(nb,currentProjects):
    filename = filedialog.askopenfilename()
    if not filename == '' and not filename == () :
        if not '.closest' in filename:
            messagebox.showinfo(message='Wrong format for '+filename, icon = 'error' )
            return
        f = open(filename,'rb')
        try :
            projectDic = pickle.load(f)
        except pickle.UnpicklingError :
            messagebox.showinfo(message='Unable to exctract the project from '+filename+'\n\n (pickle error)', icon = 'error' )
            return
        f.close()
        if not type(projectDic) == dict :
            messagebox.showinfo(message='Unable to exctract the project from '+filename+'\n\n (dict error)', icon = 'error' )
            return
        #print(projectDic)
        newframe = mf.create_mainframe(nb,currentProjects,projectDic)
        #print(newframe)
        currentProjects[str(newframe)] = projectDic
        bS = builtSSS(projectDic)
        if bS == None :
            messagebox.showinfo(message='Unable to build the secret sharing scheme.', icon = 'error' )
        else :
            currentProjects[str(newframe)]['builtSSS'] = bS
            nb.add(newframe, text=projectDic['name'])
Example #30
0
def get_img(browse=True): #browse = false is for setting picture in certain cases.
    '''Obtains image filename from user, and creates an image object for later use.'''
    global previous, current;
    filename = "";
    
    if(browse): #If browse is true it allows the user to browse for a file.
        from tkinter import filedialog
        filename = filedialog.askopenfilename(filetypes =(("Image Files", "*.jpeg;*.jpg;*.png;*.bmp")
                                                            ,("Jpeg", "*.jpeg;*.jpg")
                                                            ,("Png", "*.png")
                                                            ,("Bitmap", "*.bmp")
                                                            ,("All files", "*.*") ))
    try:
        if(filename != ""):         #if a file is given, it setsh the photo to set.
            photo = ImageTk.PhotoImage(file = filename);
            previous = filename;    #filling previous with current.
            current = photo;
        elif(previous != ""):       #if file isnt given, but something is previously defined, sets to previous.
            photo = ImageTk.PhotoImage(file = previous);
            current = photo;
        #Called on init, and error cases.
        else:   #no filename/no previous -> sets to splash screen.
            previous = "data/Splash.png";
            photo = ImageTk.PhotoImage(file = previous);
            current = photo;
            print("No photo given.");
    except:
        print("Processing of image failed.");
Example #31
0
def abrirfichero():
    rutafichero = filedialog.askopenfilename(title="Abrir un fichero")
    print(rutafichero)
Example #32
0
 def csv_file_open(self, gs):
     """Open filedialog when Select CSV File button selected."""
     self.csv_file_path = filedialog.askopenfilename()
     gs.csv_path = self.csv_file_path
     self.csv_file_var.set(self.csv_file_path)
def browse_file():
    global filename
    filename = filedialog.askopenfilename()
Example #34
0
def open_file():
    filename = filedialog.askopenfilename(title='Select an image!')
    return filename
Example #35
0
def fileopen():
	global file_name
	file_name = fd.askopenfilename(filetypes=(("TXT files", "*.txt"),
                                        ("HTML files", "*.html;*.htm"),
                                                ("All files", "*.*") ))
import math
import matplotlib.pyplot as plt
#import tkinter as tk
from tkinter import filedialog

#tk.withdraw()
filename = filedialog.askopenfilename( filetypes=[('txt', '*.txt'), ('All Files', '*')])

f = open(filename, 'r')

ID=[]
PRN=[]
AZ=[]
EL=[]

ln = f.readline()
while ln:
    ln = f.readline()
    if not ln:
        break
    str = ln.split()
    id = str[2]
    prn = int(str[2][1:3])
    if (str[2][0] == 'R'):
        prn = prn+ 31
    elif (str[2][0] == 'E'):
        prn = prn+ 59
    elif (str[2][0] == 'C'):
        prn = prn+ 95
    az = float(str[3])/180*math.pi
Example #37
0
def get_path():
    if sys.argv[1:]:
        path = sys.argv[1]
    else:
        path = filedialog.askopenfilename(title='导入表格文件').replace('/', '\\')
    return path
def predict():
        filename = filedialog.askopenfilename(
            initialdir="C://")
        with open(filename) as datafile:
            data = json.load(datafile)
            api = (data['behavior']['processes'][1]['calls'][1]['api'])
            print(api)
        def result():
            Categories = ['trojan','backdoor','adware', 'spyware', 'virus', 'worms', 'downloader', 'dropper']
            def result(x):
                return x
            model = tf.keras.models.load_model('model.h5')
            prediction = model.predict(result([21]))
            cat = (Categories[int(prediction[0][0])])
            if cat == 'trojan':
                msg = "Trojan misleads users of its true intent"
                description = Label(window, font=('helvatic', 10, 'bold'),text=msg, fg="green")
                description.place(x=100, y=400)
                classification = Label(window, text=cat, font=('helvatic', 15, 'bold'), fg='green')
                classification.place(x=510, y=370)
            elif cat == 'backdoor':
                msg = "Backdoor is a technique in which a system security mechanism is bypassed undetectably toaccess a computer or its data"
                description = Label(window, text=msg, fg="green")
                description.place(x=100, y=400)
                classification = Label(window, text=cat, font=('helvatic', 15, 'bold'), fg='green')
                classification.place(x=510, y=370)
            elif cat == 'adware':
                msg = "Adware hides on your device and serves you advertisements"
                description = Label(window, text=msg, fg="green")
                description.place(x=100, y=400)
                classification = Label(window, text=cat, font=('helvatic', 15, 'bold'), fg='green')
                classification.place(x=510, y=370)
            elif cat == 'spyware':
                msg = "Spyware enables a user to obtain covert information about another’s computer activities bytransmitting data covertly from their hard drive"
                description = Label(window, text=msg, fg="green")
                description.place(x=100, y=400)
                classification = Label(window, text=cat, font=('helvatic', 15, 'bold'), fg='green')
                classification.place(x=510, y=370)
            elif cat == 'virus':
                msg = "Virus is designed to spread from host to host and has the ability to replicate itself"
                description = Label(window, text=msg, fg="green")
                description.place(x=100, y=400)
                classification = Label(window, text=cat, font=('helvatic', 15, 'bold'), fg='green')
                classification.place(x=510, y=370)
            elif cat == 'worms':
                msg = "Worms spreads copies of itself from computer to computer"
                description = Label(window, text=msg, fg="green")
                description.place(x=100, y=400)
                classification = Label(window, text=cat, font=('helvatic', 15, 'bold'), fg='green')
                classification.place(x=510, y=370)
            elif cat == 'downloader':
                msg = "Downloader share the primary functionality of downloading content"
                description = Label(window, text=msg, fg="green")
                description.place(x=100, y=400)
                classification = Label(window, text=cat, font=('helvatic', 15, 'bold'), fg='green')
                classification.place(x=510, y=370)
            elif cat == 'dropper':
                msg = "Dropper surreptitiously carries viruses, back doors and other malicious software so they canbe executed on the compromised machine"
                description = Label(window, text=msg, fg="green")
                description.place(x=100, y=400)
                classification = Label(window, text=cat, font=('helvatic', 15, 'bold'), fg='green')
                classification.place(x=510, y=370)
            else :
                msg = "Please! try again something went wrong"
                description = Label(window, text=msg, fg="green")
                description.place(x=100, y=400)
        result()
def report_parser():
    filename = filedialog.askopenfilename(initialdir="C://", multiple=True)

    parser(filename)
Example #40
0
## Make it so that the program creates a new entry for each header column
## User will be able to attain statistical data, such as: mean, median, mode, etc.
### They'll be able to choose what data they want to interact with

### Steps the user will go through
# Build the dataset
# Use tools to analyze numerical sets
## compatible columns will be added to a certain array to show the user they are compatible for that certain measure
## for instance, mode can be applied to strings.

import csv
import datetime
import os
from tkinter import filedialog

name = filedialog.askopenfilename()
currentDirectory = os.path.dirname(os.path.realpath(name))
nameProcessed = os.path.splitext(os.path.basename(name))[0]
time = datetime.datetime.now()


class recordClass(object):
    pass


file = open(name, newline='')
reader = csv.reader(file)
header = next(reader)
data = []

record = recordClass()
Example #41
0
"""
Created on Sat Oct  5 15:38:09 2019

@author: thugwithyoyo
"""
import numpy as np
import pandas as pd
from PeriEventTraceFuncLib import *
from collections import defaultdict
import os
import tkinter as tk
from tkinter.filedialog import askopenfilename

#RestoreFilePath = SavePath +'.dat'
root = tk.Tk()
RestoreFilePath = askopenfilename()
root.withdraw()

# Open workspace.
#exec(open('./RestoreShelvedWorkspaceScript.py').read())
try:

    exec(open('./RestoreShelvedWorkspaceScript.py').read())

except:

    print('Unshelving error.  Will attempt to continue...')

drive, path_and_file = os.path.splitdrive(RestoreFilePath)
path, file = os.path.split(path_and_file)
def openfile():
    Tk().withdraw()  # closes the default window and wait for the customised one to be opened
    file = askopenfilename()  # uses the default file opener
    filename = cv2.imread(file)  # passes the parameter obtained from python to OpenCv
    return filename
Example #43
0
import gather
import tkinter
from tkinter import filedialog
import codecs


def createDictionary(file_path):
    kakas = kakasi()
    kakas.setMode('J', 'H')
    conv = kakas.getConverter()
    word_list = gather.gather()
    print("> ", gather.search_word)
    hiragana = conv.do(gather.search_word)
    for word in word_list:
        print(word)
        word = hiragana + "\t" + word + "\t" + '名詞' + "\t"
        with codecs.open(str(file_path), 'a', encoding='utf-8') as dicfile:
            dicfile.write(word + '\n')


if '__main__' == __name__:
    root = tkinter.Tk()
    root.overrideredirect(1)
    root.withdraw()
    fileName = filedialog.askopenfilename(filetypes=(('IME Dictionary File',
                                                      '*.txt'), ('All files',
                                                                 '*.*')))
    print('Selected IME Dictionary File(*.txt): ' + fileName)
    while True:
        createDictionary(fileName)
Example #44
0
 def selectExcelfile():
     sfname = filedialog.askopenfilename(title='选择project文件',
                                         filetypes=[('project',
                                                     '*.project')])
     self.project_path_Ex.insert(INSERT, sfname)
Example #45
0
#-----------------------------------------------------------------------------

# import modules
import re
import os
import tkinter as tk
from tkinter import filedialog

#-----------------------------------------------------------------------
#--- DIRECTORY DIALOG
#-----------------------------------------------------------------------

ROOT = tk.Tk()
ROOT.withdraw()
ROOT.filename = filedialog.askopenfilename(filetypes=(("CSV Files", "*.csv"),
                                                      ("Text File", "*.txt"),
                                                      ("All Files", "*.*")),
                                           title="Choose a file.")

#-----------------------------------------------------------------------
#--- CLEANUP NAMES
#-----------------------------------------------------------------------

INPUT_PATH, INPUT_FILE_NAME = os.path.split(ROOT.filename)
INPUT_FILE_NAME, INPUT_FILE_EXTENSION = os.path.splitext(INPUT_FILE_NAME)
OUTPUT_FILEPATH = INPUT_PATH + '/' + INPUT_FILE_NAME + \
                "_recast" + INPUT_FILE_EXTENSION
EXCEPTIONS_FILEPATH = INPUT_PATH + os.sep + INPUT_FILE_NAME + \
                "_exceptions" + INPUT_FILE_EXTENSION

#-----------------------------------------------------------------------
#--- GLOBAL VARIABLES
#Importing cv2 
import cv2

# Importing tk to open and save our image file
from tkinter.filedialog import askopenfilename
filename = askopenfilename()

#creating the image variable
img =cv2.imread(filename)

# pretty straight forward from here used https://medium.com/python-in-plain-english/convert-a-photo-to-pencil-sketch-using-python-in-12-lines-of-code-4346426256d4
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
inverted_gray_image = 255 - gray_image
blurred_img = cv2.GaussianBlur(inverted_gray_image, (25,25),2) 
blurred_img_2ndlayer = cv2.blur(blurred_img, (5,5),1) 
inverted_blurred_img = 255 - blurred_img_2ndlayer
pencil_sketch_IMG = cv2.divide(gray_image, inverted_blurred_img, scale = 256.0)
#Show the original image
cv2.imshow('Original Image', img)
#Show the new image pencil sketch
cv2.imshow('Pencil Sketch', pencil_sketch_IMG)
#Display the window infinitely until any keypress
cv2.waitKey(0)
filename = 'pencil_sketchImage.jpg'
cv2.imwrite(filename, pencil_sketch_IMG)
Example #47
0
def browse():
    """ display the path of selected file """

    curr_directory = os.getcwd()
    file_path = filedialog.askopenfilename(initialdir = curr_directory, title = "Select file",filetypes = (("csv file","*.csv"),("all files","*.*")))
    path.set(file_path)
 def clickedSELECT(self):
     #self.CA = self.txt.get()
     #self.siteid = self.txt2.get()
     #self.deviceid = self.txt3.get()
     self.file_path = filedialog.askopenfilename()
Example #49
0
def getFileRaster():
    mainWindow.filename = filedialog.askopenfilename(initialdir="/")
    entryRaster.delete(0, END)
    entryRaster.insert(0, mainWindow.filename.replace("/", "\\"))
Example #50
0
        elif r2d2Rect.collidepoint(mx, my) and mb[0] == 1:  #R2D2
            tool = "r2d2.gif"
        elif hanRect.collidepoint(mx, my) and mb[0] == 1:  #Han Solo
            tool = "han.gif"
        elif yodaRect.collidepoint(mx, my) and mb[0] == 1:  #Yoda
            tool = "yoda.gif"
        if saveRect.collidepoint(mx, my) and mb[0] == 1:  # Save tool
            fileName = asksaveasfilename(
                parent=root, title="Save The Image As..."
            )  # gets the directory the image is to be saved to
            if fileName != "":
                image.save(screen.subsurface(canvasRect), fileName)
        elif loadRect.collidepoint(mx, my) and mb[0] == 1:
            screen.set_clip(canvasRect)  # Upload tool
            fileName = askopenfilename(
                parent=root, title="Open Image:"
            )  # gets which directory it needs to open the image from
            screen.blit(image.load(fileName), canvasRect)

    #*************************** DRAW TOOLS *********************************

    if tool == "pencil":
        screen.blit(timesFont.render("Click on the canvas to", True, black),
                    (25, 500))  #Writes in description rect
        screen.blit(timesFont.render("draw, and select the ", True, black),
                    (25, 520))
        screen.blit(
            timesFont.render("desired width on the menu!", True, black),
            (25, 540))
        draw.line(screen, c, (45, 210), (45, 440),
                  1)  #draws lines of various sizes for selection
Example #51
0
def getExcel():

    global df
    import_file_path = filedialog.askopenfilename()
    read_file = pd.read_excel(import_file_path)
    df = DataFrame(read_file, columns=['x', 'y'])
Example #52
0
def file():
    filename = filedialog.askopenfilename()
    filename = filedialog.asksaveasfilename()
    dirname = filedialog.askdirectory()
    #setting up a tkinter canvas with scrollbars
    frame = Frame(root, bd=2, relief=SUNKEN)
    frame.grid_rowconfigure(0, weight=1)
    frame.grid_columnconfigure(0, weight=1)
    xscroll = Scrollbar(frame, orient=HORIZONTAL)
    xscroll.grid(row=1, column=0, sticky=E+W)
    yscroll = Scrollbar(frame)
    yscroll.grid(row=0, column=1, sticky=N+S)
    canvas = Canvas(frame, bd=0, xscrollcommand=xscroll.set, yscrollcommand=yscroll.set)
    canvas.grid(row=0, column=0, sticky=N+S+E+W)
    xscroll.config(command=canvas.xview)
    yscroll.config(command=canvas.yview)
    frame.pack(fill=BOTH,expand=1)

    #adding the image
    File = askopenfilename(parent=root, initialdir="C:/Users/Dell/desktop/si/test.jpeg",title='test')
    img = ImageTk.PhotoImage(Image.open(File))
    canvas.create_image(0,0,image=img,anchor="nw")
    canvas.config(scrollregion=canvas.bbox(ALL))
    i=0,j=0,k=1;

    #function to be called when mouse is clicked
    def printcoords(event):
        #outputting x and y coords to console
        if(k==4):
            i=1
            j=0
        k++;
        arr[i][j++]
        print (event.x,event.y)
    #mouseclick event
Example #54
0
    BuildEventSocialApproach, BuildEventSocialEscape, BuildEventApproachContact,\
    BuildEventApproachRear, BuildEventGroup2, BuildEventGroup3, BuildEventGroup4,\
    BuildEventStop, BuildEventWaterPoint

from tkinter.filedialog import askopenfilename
from lmtanalysis.Util import getMinTMaxTAndFileNameInput

if __name__ == '__main__':

    print("Code launched.")
    '''
    compute behavioural traits for each individual for two mice (one for the tested strain and one control mouse)
    computation of individual and social traits.
    '''

    files = askopenfilename(title="Choose a set of file to process",
                            multiple=1)
    tmin, tmax, text_file = getMinTMaxTAndFileNameInput()
    '''
    min_dur = 10*oneSecond
    max_dur = min_dur + 10*oneMinute
    '''

    behaviouralEventOneMouse = [
        "Contact", "Group2", "Huddling", "Move isolated", "Move in contact",
        "Rearing", "Rear isolated", "Rear in contact", "Stop isolated",
        "WallJump"
    ]
    behaviouralEventTwoMice = [
        "Approach contact", "Approach rear", "Break contact", "Contact",
        "FollowZone Isolated", "Group2", "Oral-oral Contact",
        "Oral-genital Contact", "Side by side Contact",
 def RomSelect2():
     rom = filedialog.askopenfilename(filetypes=[("Rom Files", (".sfc", ".smc", ".bmbp")), ("All Files", "*")])
     romVar2.set(rom)
Example #56
0
from nilearn import plotting
from matplotlib import pyplot as plt
from nilearn.connectome import ConnectivityMeasure
from nilearn import datasets
import numpy
from tkinter.filedialog import askopenfilename

time_series = numpy.loadtxt(askopenfilename(),
                            skiprows=1,
                            usecols=(x for x in range(2, 118)))

print("time_series shape is " + str(numpy.shape(time_series)))
print(time_series[0])

atlas_coords = [(-38.65, -5.68, 50.94), (41.37, -8.21, 52.09),
                (-18.45, 34.81, 42.2), (21.9, 31.12, 43.82),
                (-16.56, 47.32, -13.31), (18.49, 48.1, -14.02),
                (-33.43, 32.73, 35.46), (37.59, 33.06, 34.04),
                (-30.65, 50.43, -9.62), (33.18, 52.59, -10.73),
                (-48.43, 12.73, 19.02), (50.2, 14.98, 21.41),
                (-45.58, 29.91, 13.99), (50.33, 30.16, 14.17),
                (-35.98, 30.71, -12.11), (41.22, 32.23, -11.91),
                (-47.16, -8.48, 13.95), (52.65, -6.25, 14.63),
                (-5.32, 4.85, 61.38), (8.62, 0.17, 61.85),
                (-8.06, 15.05, -11.46), (10.43, 15.91, -11.26),
                (-4.8, 49.17, 30.89), (9.1, 50.84, 30.22),
                (-5.17, 54.06, -7.4), (8.16, 51.67, -7.13),
                (-5.08, 37.07, -18.14), (8.35, 35.64, -18.04),
                (-35.13, 6.65, 3.44), (39.02, 6.25, 2.08),
                (-4.04, 35.4, 13.95), (8.46, 37.01, 15.84),
                (-5.48, -14.92, 41.57), (8.02, -8.83, 39.79),
def getCSV():
    global read_file

    import_file_path = filedialog.askopenfilename()
    read_file = pd.read_csv(import_file_path)
 def selectPath(self):
     path_ = askopenfilename()
     self.path.set(path_)
     self.path_entry.delete(0,'end')
     self.path_entry.insert(END,str(path_))
Example #59
0
    def loaddatafile(self):
        """
        Open the hyperspectral file.
        """
        self.hypfilename = filedialog.askopenfilename(
            initialdir=self.foldername1,
            title="Choose a hyperspectral data file",
            filetypes=(("Envi hdr files", "*.hdr"), ("all files", "*.*")))

        if self.hypfilename != '':
            self.foldername1 = os.path.split(self.hypfilename)[0]
            self.hypdata_map = None
            self.hypdata = None
            self.button_plotmono.configure(state=DISABLED)
            self.button_plotrgb.configure(state=DISABLED)
            self.button_plotnir.configure(state=DISABLED)
            self.button_plottrue.configure(state=DISABLED)

            # try to have .hdr extension, although this should not be compulsory. No error checking here.
            if not self.hypfilename.endswith(".hdr"):
                self.hypfilename += '.hdr'

            # open the files and assign handles
            self.hypdata = spectral.open_image(self.hypfilename)
            self.hypdata_map = self.hypdata.open_memmap()

            # come up with band names
            wl_hyp, wl_found = get_wavelength(self.hypfilename, self.hypdata)
            #  best possible result "number:wavelength"
            bandnames = [
                '%3d :%6.1f nm' % (i + 1, wli) for i, wli in enumerate(wl_hyp)
            ]
            if wl_found:
                self.printlog(
                    "loaddatafile(): Found wavelength information in file " +
                    self.hypfilename + ".\n")
            else:
                self.printlog(
                    "loaddatafile(): No wavelength information in file " +
                    self.hypfilename + ".\n")
                # try to use band name information
                if 'band names' in self.hypdata.metadata:
                    bn = self.hypdata.metadata['band names']
                    bandnames = [
                        '%3d:%s' % (i + 1, wli) for i, wli in enumerate(bn)
                    ]

            # fill the option menus with wavelengths
            self.option_red['menu'].delete(0, END)
            self.option_green['menu'].delete(0, END)
            self.option_blue['menu'].delete(0, END)
            self.option_mono['menu'].delete(0, END)
            for choice_num in bandnames:
                choice = str(choice_num)
                self.option_red['menu'].add_command(
                    label=choice,
                    command=lambda v=choice: self.redband_string.set(v))
                self.option_green['menu'].add_command(
                    label=choice,
                    command=lambda v=choice: self.greenband_string.set(v))
                self.option_blue['menu'].add_command(
                    label=choice,
                    command=lambda v=choice: self.blueband_string.set(v))
                self.option_mono['menu'].add_command(
                    label=choice,
                    command=lambda v=choice: self.monoband_string.set(v))

            # make reasonable preselections for r,g,b
            if 'default bands' in self.hypdata.metadata:
                if len(self.hypdata.metadata['default bands']) > 2:
                    i_r = int(self.hypdata.metadata['default bands'][0]) - 1
                    i_g = int(self.hypdata.metadata['default bands'][1]) - 1
                    i_b = int(self.hypdata.metadata['default bands'][2]) - 1
                    # avoid official printing band names, they usually contain long crappy strings
                    self.printlog(
                        "loaddatafile(): Found default bands (%i,%i,%i) for plotting.\n"
                        % (i_r, i_g, i_b))
                else:
                    i_m = int(self.hypdata.metadata['default bands'][0]) - 1
                    i_r = i_m
                    i_g = i_m
                    i_b = i_m
                    # avoid official printing band names, they usually contain long crappy strings
                    self.printlog(
                        "loaddatafile(): Found one default band (%i) for plotting.\n"
                        % i_m)

            elif wl_found:
                i_r = abs(wl_hyp - 680).argmin()  # red band
                i_g = abs(wl_hyp - 550).argmin()  # green
                i_b = abs(wl_hyp - 450).argmin()  # blue
            else:
                # just use the first one or three bands
                if self.hypdata_map.shape[2] > 2:
                    # we have at least 3 bands
                    i_r = 0
                    i_g = 1
                    i_b = 2
                else:
                    # monochromatic, use first band only
                    i_r = 0
                    i_g = 0
                    i_b = 0
            # set monochrome to red
            i_m = i_r

            # set the optionmenus to their respective values
            self.redband_string.set(bandnames[i_r])
            self.greenband_string.set(bandnames[i_g])
            self.blueband_string.set(bandnames[i_b])
            self.monoband_string.set(bandnames[i_m])

            # wrap it up. Make sure all options are active and ready
            self.option_red.configure(state=ACTIVE)
            self.option_green.configure(state=ACTIVE)
            self.option_blue.configure(state=ACTIVE)
            self.option_mono.configure(state=ACTIVE)
            self.button_plotmono.configure(state=ACTIVE)
            self.button_plotrgb.configure(state=ACTIVE)
            if wl_found:
                self.button_plotnir.configure(state=ACTIVE)
                self.button_plottrue.configure(state=ACTIVE)

        else:
            self.printlog("loaddatafile(): No file name given.\n")
Example #60
0
def file():
    global my_image
    root.filename = filedialog.askopenfilename(initialdir="c:", title="Select A File", filetypes=(("png files", "*.png"),("all files", "*.*")))
    my_label = Label(root, text=root.filename).pack()
    my_image = ImageTk.PhotoImage(Image.open(root.filename))
    my_image_label = Label(image=my_image).pack()