Пример #1
0
 def load(self):
     """
 Функция выводит на экран модальное окно открытия файла и записывает обработанные данные файла в переменную базы данных.
 Параметры: нет
 Возращаемые значения: нет
 Автор: Рудицкий М.
 """
     dlg = fd.Open(self.root, filetypes=[('Файл базы данных', '*.txt')])
     path = dlg.show()
     if path:
         self.db = mydb.load(path)
         if self.db is False:
             mb.showerror("Ошибка", "Произошла ошибка при чтении файла!")
         else:
             self.print_records(self.db)
Пример #2
0
    def onOpen(self):
        ftypes = [('XML Files', '*.xml')]
        dlg = filedialog.Open(self, filetypes=ftypes)
        fl = dlg.show()

        # destroying old frame & creating new - incase of a new file
        self.txt.destroy()
        self.txt = Text(self)
        self.txt.pack(fill=BOTH, expand=1)

        self.txt.insert(END, "File - " + fl + "\n\n")

        if fl != '':
            text = self.readFile(fl)
            self.txt.insert(END, text)
Пример #3
0
    def tangkapCitraSatuan(self):
        ftypes = [('Portable Network Graphics', '*.png'), ('JPEG', '*.jpg')]
        dlg = filedialog.Open(self, filetypes=ftypes)
        fl = dlg.show()

        if fl != '':
            self.img = Image.open(fl)
            f = ImageTk.PhotoImage(self.img)

            jumlahWBC, hasilResize = prosesCitra(f)

            self.dataJumlahWBC = self.dataJumlahWBC + jumlahWBC  # Penambahan untuk update data
            label = Label(self, height="480", width="640", image=hasilResize
                          )  # img nanti di resize dulu dari hasil TensorBox
            label.image = hasilResize
            label.pack(side="left", expand="no")
Пример #4
0
def open_file(event):
    ftypes = [('Commas Separated Variable', '*csv')]
    dlg = filedialog.Open(root, filetypes=ftypes)
    file_name = dlg.show()
    if file_name != "":
        global catalogue
        global sources
        global numeric_cols
        catalogue, sources, numeric_cols = loadCustom(file_name)
        update_cols_list()
        plot_coord_btn.configure(state="disabled")
        plot_intensity_hist_btn.configure(state="disabled")
        plot_intensity_scat_btn.configure(state="disabled")
        plot_coord_btn.unbind("<Button-1>")
        plot_intensity_hist_btn.unbind("<Button-1>")
        plot_intensity_scat_btn.unbind("<Button-1>")
    def LoadFile(self, ev):
        fn = tkFileDialog.Open(self.root).show(initialdir = path)
        if fn == '':
            return

        self.bands = np.empty((size[0], size[1], n_bands))
        with zf.ZipFile(fn, 'r') as zp:
            zp.extractall(path)

        self.mask = cv2.imread(path + 'landsat8/valdata/' + 'QB.tif')[:, :, 0]
        for band in range(n_bands):
            self.bands[:, :, band] = cv2.imread(path + 'landsat8/valdata/'+ f'B{band + 1}.tif')[:, :, 0]

        self.unmarked_image = ImageTk.PhotoImage(Image.fromarray(self.mask).resize((500, 500)))
        self.band.config(text="Mask")
        self.leftImFrame.create_image(25, 5, anchor=NW, image=self.unmarked_image)
Пример #6
0
    def onOpenFileDialog(self):
        """
           Grabs file and processes text/data in it.
        """
        ftypes = [('Text files', '*.txt'), ('Binary Files', '*.bin')]
        filedialogue = tkfiledialog.Open(self.parent, filetypes=ftypes)
        file = filedialogue.show()

        if file != '':
            _filename, file_extension = os.path.splitext(file)
            print("#" * 79)
            print(file)
            if file_extension == ".txt":
                self.process_huffman(file)
            elif file_extension == ".bin":
                self.reconstruct_coded_string(file)
Пример #7
0
    def load_data(self, title):
        """
        loads_coords from csv.
        """
        print("loading file")
        #if there is no passed variable, open dialog to select
        file_types = [('Microsoft Excel', '*.csv'), ('All files', '*')]
        dlg = filedialog.Open(filetypes=file_types)
        file = dlg.show()
        print(file)

        #if file is selected, read the data
        if file != '':
            data = pd.read_csv(file)
            print(data)
            return data
Пример #8
0
def onLoad():

    global sig
    global rate

    ftypes = [('WAV files', '*.wav'), ('All files', '*')]
    dlg = filedialog.Open(filetypes=ftypes)
    fl = dlg.show()

    if fl != '':
        print(fl)
        (rate, sig) = wave.read(fl)
        sig = sig[:5 * rate]
        plot(lowerframe, sig)
        e20.delete(0, END)
        e20.insert(0, len(sig))
Пример #9
0
 def onOpen(self):
     """打开文件"""
     ftypes = [('all files', '.*'), ('text files', '.txt'),
               ('ann files', '.ann')]
     dlg = tkFileDialog.Open(self, filetypes=ftypes)
     fl = dlg.show()
     if fl != '':
         self.text.delete("1.0", END)
         text = self.readFile(fl)
         self.text.insert(END, text)
         self.setNameLabel("File: " + fl)
         self.autoLoadNewFile(self.fileName, "1.0")
         # self.setDisplay()
         # self.initAnnotate()
         self.text.mark_set(INSERT, "1.0")
         self.setCursorLabel(self.text.index(INSERT))
Пример #10
0
 def onOpen(self):
     ftypes = [('all files', '.*'), ('text files', '.txt'), ('ann files', '.ann')]
     dlg = tkFileDialog.Open(self, filetypes = ftypes)
     # file_opt = options =  {}
     # options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]
     # dlg = tkFileDialog.askopenfilename(**options)
     fl = dlg.show()
     if fl != '':
         self.text.delete("1.0",END)
         text = self.readFile(fl)
         self.text.insert(END, text)
         self.setNameLabel("File: " + fl)
         self.setDisplay()
         # self.initAnnotate()
         self.text.mark_set(INSERT, "1.0")
         self.setCursorLabel(self.text.index(INSERT))
Пример #11
0
 def open_bd(self):
     """
     Входные данные: данный метод вызывается из конструктора класса, входных параметров нет
     Выходные данные: объект базы данных.
     Данный метод пытается открыть файл с базой данных. В случае, если файл не удалось открыть, пользователю
     предлагается выбрать файл с жесткого диска.
     """
     try:
         open(cfg.bd_path, 'rb')
     except FileNotFoundError:
         fn = filedialog.Open(root, filetypes=[('*.dat files', 'shl.dat')
                                               ]).show()
         if fn != '':
             base = shl.open(fn.remove('.dat'))
             return base
     finally:
         return shl.open(cfg.bd_path_2)
Пример #12
0
 def onOpen(self):
     '''打开文件 并将内容显示到文本框内'''
     self.recoEntity = ''
     # 每次重新打开一个文件标注 清除预标注列表
     self.pre_ent_list = []
     self.text.config(state=NORMAL)
     ftypes = [('all files', '.*'), ('text files', '.txt'),
               ('ann files', '.ann')]  # 这里配置显示文件格式
     dlg = tkFileDialog.Open(self, filetypes=ftypes)
     f1 = dlg.show()
     if f1 != '':
         self.text.delete("1.0", END)
         text = self.readFile(f1)
         print(f1)
         self.text.insert("1.0", text)
         self.setTitle(" " + f1)
         self.text.mark_set(INSERT, "1.0")
         self.no = 0
     self.clearTable()  # 清空表格内容
     self.entity_list = []  # 清空实体内容
     # clear tag
     self.text.tag_delete(self, 'TagEntity')
     self.text.tag_delete(self, 'RecEntity')
     self.text.tag_delete(self, 'dpEntity')
     self.text.tag_delete(self, 'highlight')
     self.text.config(state=DISABLED)  # set text state disable
     if self.recommendFlag2 == "ON":
         ann_file = './model/test_label/' + os.path.split(
             f1)[1][:-3] + 'ann'
         if os.path.exists(ann_file):
             data = open(ann_file, 'r', encoding='utf-8')
             lines = data.readlines()
             for line in lines:
                 line = line.strip().split('\t')
                 tmp = line[1].strip().split()
                 dict = {
                     'ENTITY': line[2],
                     'POS':
                     (int(tmp[1]), int(tmp[2]), int(tmp[3]), int(tmp[4])),
                     'CATEGORY': tmp[0],
                     'STATUS': 'certain'
                 }
                 self.pre_ent_list.append(dict)
         else:
             tkinter.messagebox.showerror('错误', '预标注的文件不存在!')
     self.setDisplayCorolor()  # 首先 先显示预标注实体
Пример #13
0
    def on_open_bg(self):

        global bg_loaded, image_bg_path

        ftypes = [('JPG files', '*.jpg'), ('PNG files', '*.png'),
                  ('All files', '*')]
        dlg = filedialog.Open(self, title="Select image file",
                              filetypes=ftypes)

        image_bg_path = dlg.show()
        # make sure user loaded something
        if len(image_bg_path) > 0:
            bg_loaded = True
            messagebox.showinfo("Success",
                                "Background image loaded successfully")
            # initialize again to access background menu
            self.initialize()
Пример #14
0
    def open_file(self, lastsess=None):
        def readFile(filename):
            f = open(filename, "r")
            text = f.read()
            return text

        if lastsess:
            self.pack_widgets()
            return

        ftypes = [('Text files', '*.txt'), ('All files', '*')]
        dlg = filedialog.Open(self, filetypes=ftypes)
        fl = dlg.show()

        if fl != '':
            docname = fl.split("/")[-1].split(".")[0]
            self.pack_widgets()
Пример #15
0
    def on_open_fg(self):

        global fg_loaded, image_fg_path

        ftypes = [('JPG files', '*.jpg'), ('PNG files', '*.png'),
                  ('All files', '*')]
        dlg = filedialog.Open(self, title="Select image file",
                              filetypes=ftypes)

        image_fg_path = dlg.show()
        # make sure user loaded something
        if len(image_fg_path) > 0:
            fg_loaded = True
            messagebox.showinfo("Success!", "Foreground image loaded\
 successfully! You can now use use image segmentation with Grabcut!")
            # initialize again to access grabcut
            self.initialize()
Пример #16
0
def change_profile_icon(root: Any, _locals: dict):
    """
    Изменение аватарки
    """

    dlg = filedialog.Open(filetypes=[('PNG file',
                                      '*.png'), ('JPG file', '*.jpg')])
    file_path = dlg.show()  # Получаем выбранный файл
    try:
        icon = root.Image.open(file_path)
        icon.save(root.Images.dp + 'profile_icon.png', 'png')
        root.Images.IMG_PROFILE_ICON = root.open_img(
            root.Images.dp + 'profile_icon.png', (46, 46), proportions=False)
        root.Images.IMG_PROFILE_ICON_SMALL = root.open_img(
            root.Images.dp + 'profile_icon.png', (35, 35), proportions=False)
        root.home_view(need_resize=False, _locals=_locals)
    except Exception:
        pass
Пример #17
0
 def __init__(self, title="Open File", initial_dir=_os.path.curdir, filetypes=None, multiple=False):
     """
     :Parameters:
         `title` : str
             The Dialog Window name. Defaults to "Open File".
         `initial_dir` : str
             The directory to start in.
         `filetypes` : list of tuple
             An optional list of tuples containing (name, extension) to filter by.
             If none are given, all files will be shown and selectable.
             For example: `[("PNG", ".png"), ("24-bit Bitmap", ".bmp")]`
         `multiple` : bool
             True if multiple files can be selected. Defaults to False.
     """
     from tkinter import filedialog
     self._dialog = filedialog.Open(title=title,
                                    initialdir=initial_dir,
                                    filetypes=filetypes or (),
                                    multiple=multiple)
Пример #18
0
def LoadFile(ev):
    fn = filedialog.Open(root, filetypes=[('*.txt files', '.txt')]).show()
    if fn == '':
        return
    index = 0
    global lb

    file = open(fn, 'r')
    b = len(file.readlines())
    file.close()
    file = open(fn, 'r')
    while index != b:
        lb.append(file.readline())
        index += 1

    for i in lb:
        listbox.insert(END, i)
    lb = [line.rstrip() for line in lb]
    print(lb)
Пример #19
0
 def place_main_img(self, file='', flag=0):
     global filename
     if file == '':
         ftypes = [('Изображения', '*.png'), ('Изображения', '*.jpg'),
                   ('Все файлы', '*')]
         dlg = fd.Open(self, filetypes=ftypes)
         filename = dlg.show()
     if filename != '':
         pil_im = Image.open(filename)
         main_canv = tk.Canvas(self.master,
                               width=pil_im.size[0],
                               height=pil_im.size[1])
         imgs.image = ImageTk.PhotoImage(pil_im)
         main_canv.place(x=pil_im.size[0] * 0.5, y=pil_im.size[1] * 0.5)
         main_canv.create_image(-pil_im.size[0] + pil_im.size[0] * 1.5,
                                -pil_im.size[1] + pil_im.size[1] * 1.5,
                                image=imgs.image)
         if not flag:
             self.center_window(pil_im.size[0] * 2, pil_im.size[1] * 2)
Пример #20
0
def get_file(file_path=None):
    """
    This function opens a file selection, and loads up the video selected.
    """
    if file_path is None:
        #close the tkinter window that pops up
        root = Tk()
        root.withdraw()
        print("loading file")

        dlg = filedialog.Open()
        file_path = dlg.show()

    #extract the file format from extentsion
    file_format = file_path[file_path.find(".") + 1:]

    print(file_path)
    if file_path != '':
        return file_path, file_format
Пример #21
0
    def _browse(self):
        """Display the dialog to _browse for a file."""

        initial_file = self._variable.get()

        if initial_file:
            initial_dir = os.path.split(initial_file)[0]
            self.options['initialdir'] = initial_dir

        if self.mode == 'open':
            dlg = filedialog.Open(self.master, **self.options)
        else:
            dlg = filedialog.SaveAs(self.master, **self.options)

        new_file = dlg.show()

        if new_file:
            new_file = shorten(new_file)
            self.value = new_file
Пример #22
0
 def browseFile(self):
     filetypes = [("HTML Files", "*.htm *.html", "TEXT"),
                  ("PDF Files", "*.pdf", "TEXT"),
                  ("Windows Help Files", "*.chm"),
                  ("Text Files", "*.txt", "TEXT"), ("All Files", "*")]
     path = self.path.get()
     if path:
         dir, base = os.path.split(path)
     else:
         base = None
         if sys.platform[:3] == 'win':
             dir = os.path.join(os.path.dirname(sys.executable), 'Doc')
             if not os.path.isdir(dir):
                 dir = os.getcwd()
         else:
             dir = os.getcwd()
     opendialog = tkFileDialog.Open(parent=self, filetypes=filetypes)
     file = opendialog.show(initialdir=dir, initialfile=base)
     if file:
         self.path.set(file)
Пример #23
0
    def openButton(self):
        allowType = [('ERB', '*.ERB')]
        dlg = filedialog.Open(self, filetypes=allowType)
        file = dlg.show()
        if file != '' and self.core:
            #clear all
            self.originList.delete(0, 'end')
            self.translateList.delete(0, 'end')

            self.core.openFile(file)
            self.refreshList()

            #close window
            if self.editor:
                self.editor.closeWindow()
            if self.replaceWindow:
                self.replaceWindow.closeWindow()
            if self.autoTranslateWindow:
                self.autoTranslateWindow.closeWindow()
            self.core.stopTranslate()
Пример #24
0
    def open_file(self):

        try:
            file_types = [('Text files', '*.txt'), ('All files', '*')]
            dlg = filedialog.Open(filetypes=file_types)
            fl = dlg.show()

            if fl != '':
                # set file name
                self.set_file_name(self, fl)
                # read file
                data = read_file(self.parent.file_name)
                # set data
                self.set_dataset(data)
                # File loaded
                self.parent.output.insert(INSERT, 'File loaded... \n\n')
                self.file_loaded()
        except AttributeError:
            # File loaded
            self.parent.output.insert(INSERT, 'File not loaded... \n\n')
def LoadFile(ev):
    global selected_file, robot_adres, selected_file_no_dir

    if robot_adres == "0":
        print("select robot!")
        return

    fn = tkFileDialog.Open(root, filetypes=[('*.py files', '.py')]).show()
    if fn == '':
        return
    selected_file = fn

    s = fn.split("/")
    selected_file_no_dir = s[len(s) - 1]
    print(s[len(s) - 1])

    print(selected_file)
    root.title(selected_file)

    Stop(ev)
    send_selected_file()
Пример #26
0
    def openNewUploadFile(self):
        fileTypes = [("Text Documents", "*.txt")]
        dialog = filedialog.Open(master=self.root, filetypes=fileTypes)
        self.disableMenuBar()
        self.filePath = dialog.show()

        # check if file size is greater than 5 MB
        if self.filePath != "":
            self.fileStats = os.stat(self.filePath)
            print("size in bytes = ", self.fileStats.st_size)
            if self.fileStats.st_size > 5242880:
                GenericDialog(master=self.root,
                              title="Size Error!",
                              message="Max file size allowed: 5MB")
                self.enableMenuBar()
            else:
                # start uploading file
                self.initiateFileUpload(self.filePath)
                print("valid file size")
        else:
            self.enableMenuBar()
Пример #27
0
def start_open_file():
    global filename

    ftypes = [('WAV file', '*.wav'), ('All files', '*')]
    dlg = filedialog.Open(filetypes=ftypes)
    filename = dlg.show()

    def ask():
        ansver = messagebox.askyesno(
            'Warning',
            'This action will close the application. Are you really sure?')
        return ansver

    if filename == '':
        ansver = ask()
        if ansver:
            quit()
        else:
            start_open_file()

    return filename
 def onOpen(self):
     ftypes = [('Supported text files', '*.txt'), ('All files', '*')]
     dlg = filedialog.Open(self, initialdir=os.getcwd(), filetypes=ftypes)
     fl = dlg.show()
     self.last_opened = fl
     if fl != '':
         try:
             self.event = swiss.tournament
             self.event = self.event.load_tournament(self, fl)
             text = fl
             if self.event:
                 text = 'Successfully loaded ' + text
                 self.println(text)
                 self.addInfoTab()
                 self.checkOptions()
             else:
                 text = error(5) + text
             self.println(text)
         except:
             text = fl
             text = error(5) + text
             self.println(text)
    def __init__(self):
        tk.Tk.__init__(self)
        self.withdraw()  # To only show the dialogs
        self.wm_iconbitmap('../Data Files/myicon.ico')

        # Input questions file dialog
        fTypes = [('Excel files', '*.xlsx')]
        dlg = filedialog.Open(title="Choose the Input Questions File",
                              filetypes=fTypes,
                              initialdir=Path.home() / "Documents")
        questionsFile = dlg.show()
        if questionsFile == "":
            messagebox.showerror("Error", "Error => No Input file!!!")
            return

        # Output questions save as file dialog
        exportFile = filedialog.asksaveasfilename(
            title="Choose the Output File",
            filetypes=fTypes,
            initialdir=Path.home() / "Documents",
            initialfile="OutQuestions.xlsx")
        if exportFile == "":
            messagebox.showerror("Error", "Error => No Output file!!!")
            return

        # Dialog for Columns
        colDialog = simpledialog.askstring(
            title="Columns",
            prompt="Please input the column letters to be bolded",
            initialvalue="F,G")
        if colDialog == "":
            messagebox.showerror("Error", "Error => No Column Letters !!!")
            return

        # Run the program
        uLB = UniqueWordBolder(colDialog.split(','), questionsFile, exportFile)
        messagebox.showinfo(title="Program Complete!",
                            message="Questions have been bolded!")
Пример #30
0
    def open_file(self):
        """Opens dialog to select a file, reads data from file and plots the data"""
        ftypes = [('Text files', '*.txt'), ('All files', '*')]
        dlg = filedialog.Open(root, filetypes=ftypes)
        fl = dlg.show()
        if fl != '':
            # Open file for reading
            arch = open(fl, "r")
            datos_arch = arch.read()
            # Searches for every channel, delimited by L1, L2 and L3 tags.
            canal_1 = extraer_int_tag(datos_arch, 'L1')
            canal_2 = extraer_int_tag(datos_arch, 'L2')
            canal_3 = extraer_int_tag(datos_arch, 'L3')

            print("Amount of samples in channel 1: %s" % len(canal_1))
            print("Amount of samples on channel 2: %s" % len(canal_2))
            print("Amount of samples on channel 3: %s" % len(canal_3))
            message_string = "Amount of samples channel 1: {0} \n".format(
                len(canal_1))
            message_string += "Amount of samples channel 2: {0} \n".format(
                len(canal_2))
            message_string += "Amount of samples channel 3: {0} \n".format(
                len(canal_3))
            self.show_message(self.text_message, message_string)

            global g_canal_1, g_canal_2, g_canal_3
            #Keep a copy of the original values
            g_canal_1 = canal_1[:]  #Copy list by value not by reference
            g_canal_2 = canal_2[:]
            g_canal_3 = canal_3[:]

            self.window_var.set(1)  #Option rectangular window
            self.plot(self.tab1,
                      self.tab2,
                      canal_1,
                      canal_2,
                      canal_3,
                      win_var=1)