コード例 #1
1
class Loadbar:
    def __init__(self,size):
        self.loadbar = Tk()
        self.loadbar.wm_title('Loading')
        self.pgb = Progressbar(self.loadbar,orient='horizontal',length='500',maximum=int(size))
        self.pgb.pack()
        self.pgb.start()
    def start(self):
        self.loadbar.mainloop()
    def kill(self):
        self.loadbar.destroy()
コード例 #2
0
 def popupWindow(self):
     self.popup = Toplevel(self.root)
     self.popup.title("Progress window")
     self.popup.geometry("200x50")  
     self.popup.focus()
     self.counter = IntVar()
     self.counter.set(0)
     #label = Label(self.popup, textvariable = self.strVar)
     #label.pack(expand=True)
     pb = Progressbar(self.popup, mode="determinate", orient="horizontal", variable=self.counter, maximum=1000000)
     pb.start()
     pb.pack(expand=True)
     
     self.root.after(100, self.read_queue)
コード例 #3
0
class ProgressCheckButton(Frame, Observable):
    def __init__(self, parent, model, index, status_model):
        Frame.__init__(self, parent)
        Observable.__init__(self)
        self.model = model
        self.index = index
        self.status_model = status_model
        self.var = IntVar()
        self.var.set(model.get_checked())
        self.progress_var = IntVar()
        self.progress_status = ProgressStatus.undefined
        self.check_button = Checkbutton(self, text=model.get_label, variable=self.var, command=self._check_changed)
        self.progress_bar = Progressbar(self, orient='horizontal', mode='indeterminate', variable=self.progress_var)
        self.check_button.pack(side=LEFT, fill="both", expand=True)

        self.model.add_listener(self._model_changed)

    def _model_changed(self, new_status):
        model_state = self.model.get_checked()
        gui_state = self.var.get()
        if model_state is not gui_state:
            self.model.set_checked(gui_state)

    def refresh_check(self):
        if self.status_model.is_checked_force_reload():
            self.check_button.select()
        else:
            self.check_button.deselect()

    def is_checked(self):
        return self.var.get()

    def _progress_status_changed(self, new_status):
        self._refresh_progress()

    def _refresh_progress(self):
        status = self.status_model.get_status()
        if not status == self.progress_status:
            if status == ProgressStatus.in_progress:
                self.progress_bar.pack(side=RIGHT, fill="both", expand=True)
            else:
                self.progress_bar.pack_forget()

    def _check_changed(self):
        new_checked = self.var.get()
        if new_checked is not self.model.get_checked():
            self.model.set_checked(new_checked)
        if new_checked is not self.status_model.is_checked():
            self._notify(self.index, new_checked)
コード例 #4
0
class ProgressListBoxItem(Frame, Observable):
    def __init__(self, parent, model):
        Frame.__init__(self, parent)
        Observable.__init__(self)
        self._model = model

        # Create variables and initialise to zero
        self._checked_var = IntVar()
        self._progress_var = IntVar()
        self._checked_var.set(0)
        self._progress_var.set(0)
        self._current_gui_checked_state = CheckStatus.undefined
        self._current_gui_progress_state = ProgressStatus.undefined

        self.check_button = Checkbutton(self, text=model.get_label(), variable=self._checked_var, command=self._user_check_changed)
        self.progress_bar = Progressbar(self, orient='horizontal', mode='indeterminate', variable=self._progress_var)
        self.check_button.pack(side=LEFT, fill="both", expand=True)

        self._update()
        self._model.add_listener(self._model_changed)

    def _model_changed(self):
        self.update()

    def _update(self):
        # Update check status
        model_check_state = self._model.get_check_status()
        if model_check_state is not self._current_gui_checked_state:
            self._current_gui_checked_state = model_check_state
            # if self.status_model.is_checked_force_reload():
            if model_check_state:
                self.check_button.select()
            else:
                self.check_button.deselect()

        # Update progress status
        model_progress_state = self._model.get_progress_status
        if not model_progress_state == self._current_gui_progress_state:
            self._current_gui_progress_state = model_progress_state
            if model_progress_state == ProgressStatus.in_progress:
                self.progress_bar.pack(side=RIGHT, fill="both", expand=True)
            else:
                self.progress_bar.pack_forget()

    def _user_check_changed(self):
        new_checked = self._checked_var.get()
        if new_checked is not self._model.get_check_status():
            self._model.manual_set_checked(new_checked)
コード例 #5
0
ファイル: console.py プロジェクト: xialulee/WaveSyn
    def _make_cpu_mem_status(self):
        balloon = Scripting.root_node.gui.balloon

        def on_progbar_dbclick(app):
            with code_printer():
                Scripting.root_node.gadgets.launch(app)
        
        mem_progbar = Progressbar(self, orient="horizontal", length=60, maximum=100, variable=self.__membar)
        mem_progbar.pack(side='right', fill='y')
        mem_progbar.bind('<Double-Button-1>', lambda dumb: on_progbar_dbclick('wsmemmeter.pyw'))
        membar_tip = balloon.bind_widget(mem_progbar, balloonmsg='Total memory usage:')
        membar_tip.show_callback = lambda: f' {Scripting.root_node.interfaces.os.get_memory_usage()}%.'
        
        cpu_progbar = Progressbar(self, orient="horizontal", length=60, maximum=100, variable=self.__cpubar)
        cpu_progbar.pack(side='right', fill='y')
        cpu_progbar.bind('<Double-Button-1>', lambda dumb: on_progbar_dbclick('wscpumeter.pyw'))
        cpubar_tip = balloon.bind_widget(cpu_progbar, balloonmsg='Total CPU usage: ')        
        cpubar_tip.show_callback = lambda: f' {Scripting.root_node.interfaces.os.get_cpu_usage()}%.'
コード例 #6
0
ファイル: gui.py プロジェクト: Zettroke/VkMessageStat
class GUI:
    def __init__(self):
        self.root = Tk()
        self.root.title("VkMessageStat")
        self.root.iconbitmap(os.path.join(base_dir, "icon.ico"))
        self.root.geometry('661x617')
        Style().configure("Login.TLabel",
                          foreground="#777777",
                          font=("Arial", 12))
        Style().configure("Link.TLabel",
                          foreground="#039be5",
                          font=("Arial", 12))

        Style().configure("TFrame", bg="#ff0000")

        self.is_working = False

        self.login_status_label = Label(self.root,
                                        text="Проверка логина...",
                                        style="Login.TLabel")
        self.login_status_label.pack(side=TOP, pady=10)

        frame = Frame(self.root)
        lab = Label(frame, text="Автор", style="Link.TLabel", cursor='hand2')
        lab.bind('<Button-1>',
                 lambda x=None: webbrowser.open("https://vk.com/zettroke"))
        lab.pack(side=LEFT, padx=5)
        lab = Label(frame, text="GitHub", style="Link.TLabel", cursor='hand2')
        lab.bind('<Button-1>',
                 lambda x=None: webbrowser.open(
                     "https://github.com/Zettroke/VkMessageStat"))
        lab.pack(side=LEFT, padx=5)

        frame.place(x=0, y=0)

        self.login_button = Button(self.root,
                                   text='Войти',
                                   state=DISABLED,
                                   command=self.proceed_login)
        self.login_button.pack()
        self.root.after(50, self.login_check)

        self.is_logged_in = False
        self.access_token = ''
        self.root.bind("<Return>", self.bnd)

        self.current_progress = 0
        self.progress_value = DoubleVar()

        self.users = []

        self.root.mainloop()

    def bnd(self, event=None):
        self.t.configure(state=NORMAL)
        self.t.insert(END, 'enter\n')
        self.t.yview_moveto(1)
        self.t.configure(state=DISABLED)

    def login_check(self):
        try:
            need_token = True
            if os.path.exists('access_token'):
                access_token = open('access_token', 'r').read()
                r = requests.get(
                    "https://api.vk.com/method/users.get?v=5.78&access_token={access_token}"
                    .format(access_token=access_token))
                if 'response' in r.json().keys():
                    need_token = False
                    self.access_token = access_token

            if need_token:
                Style().configure("Login.TLabel", foreground="#f44336")
                self.login_status_label.configure(text="Неудалось войти")
                self.login_button.configure(state=NORMAL)
            else:
                self.logged_in()
        except Exception as e:
            traceback.print_exc(
                file=open("VkStatError.txt", "w", encoding='utf-8'))
            Style().configure("Login.TLabel", foreground="#f44336")
            self.login_status_label.configure(
                text='Произошла неизветстная ошибка при проверке логина.\n'
                'Отчет сохренен в фале VkStatError.txt\n'
                'Попробуйте снова')

    def proceed_login(self):
        self.login_button.configure(state=DISABLED)
        t = Toplevel(self.root)
        t.iconbitmap(os.path.join(base_dir, "icon.ico"))
        t.title("Login")
        Style().configure("Error.TLabel", foreground="#f44336")
        link_check = re.compile(
            'https:\/\/oauth\.vk\.com\/blank\.html#access_token=[a-z0-9]*&expires_in=[0-9]*&user_id=[0-9]*'
        )

        l = Label(t,
                  text="""
Сейчас откроеться ваш браузер. Вам будет нужно войти вконтакте и разрешить приложению читать ваши сообщения
Скопируйте и вставьте ссылку на страницу, на которую вас перенаправило, после входа Вконтакте.
Она будет вида https://oauth.vk.com/blank.html#access_token=....&expires_in=....&user_id=....
        """)
        l.pack()
        e = Entry(t, width=75)
        e.pack(pady=5, padx=10)

        err = Label(t, style="Error.TLabel")
        err.pack()

        def try_login_link():
            s = e.get()
            err.configure(text='')
            if not link_check.match(s):
                err.configure(
                    text="То что вы вставили не похоже на нужную ссылку.")
                return
            else:
                token = ''
                params = s.split('#')[1]
                pairs = params.split('&')
                for p in pairs:
                    k, v = p.split('=')
                    if k == 'access_token':
                        token = v
                r = requests.get(
                    "https://api.vk.com/method/users.get?v=5.78&access_token={access_token}"
                    .format(access_token=token))
                if 'response' in r.json():
                    self.access_token = token
                    t.destroy()
                    self.logged_in()
                else:
                    err.configure(
                        text="Токен некорректен. Попобуйте войти заново.")

        b = Button(t, text="Войти", command=try_login_link)
        b.pack(pady=5)

        def paste():
            e.insert(INSERT, self.root.clipboard_get())

        popup = Menu(t, tearoff=0)
        popup.add_command(label="Paste", command=paste)

        def do_popup(event):
            try:
                popup.tk_popup(event.x_root, event.y_root, 0)
            finally:
                popup.grab_release()

        e.bind("<Button-3>", do_popup)

        self.root.after(
            200, lambda: webbrowser.open(
                "https://zettroke.github.io/VkMessageStat/login_page"))

        def top_level_close():
            self.login_button.configure(state=NORMAL)
            t.destroy()

        t.protocol("WM_DELETE_WINDOW", top_level_close)

    def logged_in(self):
        Style().configure("Login.TLabel", foreground="#4caf50")
        open('access_token', 'w').write(self.access_token)
        r = requests.get(
            "https://api.vk.com/method/users.get?v=5.78&access_token={access_token}"
            .format(access_token=self.access_token))
        u = r.json()['response'][0]

        self.login_status_label.configure(
            text="Удалось войти как {} {}".format(u['first_name'],
                                                  u['last_name']))
        self.login_button.configure(state=DISABLED)

        r = requests.get(
            "https://api.vk.com/method/messages.getConversations?v=5.78&access_token={access_token}&count=100"
            .format(access_token=self.access_token))
        peer_list = []
        conv_list = r.json()['response']['items']
        for c in conv_list:
            peer = c['conversation']['peer']
            if peer['type'] == 'user':
                peer_list.append(str(peer['id']))

        r = requests.get(
            "https://api.vk.com/method/users.get?v=5.78&access_token={access_token}&user_ids={users_id}"
            .format(access_token=self.access_token,
                    users_id=','.join(peer_list)))
        self.users = r.json()['response']
        Frame(self.root).pack(pady=10)
        l = Label(self.root, text="Выбериет диалог:")
        l.pack()

        frame = Frame(self.root)
        scrollbar = Scrollbar(frame, orient=VERTICAL)
        self.listbox = Listbox(frame,
                               yscrollcommand=scrollbar.set,
                               font=("Arial", 14))
        scrollbar.config(command=self.listbox.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.listbox.pack(side=LEFT, fill=BOTH, expand=1)
        frame.pack()
        self.start_button = Button(self.root,
                                   text="Выбрать",
                                   command=self.listbox_select)
        self.start_button.pack(pady=10)

        for i in self.users:
            self.listbox.insert(END, i['first_name'] + ' ' + i['last_name'])
        self.listbox.bind("<Double-Button-1>", self.listbox_select)

        frame1 = Frame(self.root)
        frame1.pack()
        scrollbar1 = Scrollbar(frame1, orient=VERTICAL)
        self.t = Text(frame1,
                      takefocus=False,
                      yscrollcommand=scrollbar1.set,
                      height=13)
        scrollbar1.config(command=self.t.yview)
        scrollbar1.pack(side=RIGHT, fill=Y)
        self.t.pack(fill=X)
        self.t.configure(state=DISABLED)

        self.prog_bar = Progressbar(self.root,
                                    maximum=10000,
                                    mode='determinate',
                                    variable=self.progress_value)
        self.prog_bar.pack(fill=X)

    def listbox_select(self, event=None):
        if self.listbox.curselection() and not self.is_working:
            self.is_working = True
            user = self.users[self.listbox.curselection()[0]]
            self.start_button.configure(state=DISABLED)
            self.listbox.configure(state=DISABLED)

            self.start_stats(user['id'])

    def start_stats(self, user_id):

        self.t.configure(state=NORMAL)
        self.t.delete('1.0', END)
        self.t.configure(state=DISABLED)

        t = Thread(target=self.stat_wrapper,
                   args=(self.access_token, user_id,
                         ['vk_basic_stats.vk_base_stats']),
                   kwargs=dict(post_message_func=self.message,
                               post_progress_func=self.progress,
                               callback=self.stat_done),
                   daemon=True)
        t.start()

    def stat_wrapper(self, *args, **kwargs):

        try:
            stats.make_stats(*args, **kwargs)
        except Exception:
            t = Toplevel(self.root)
            l = Label(
                t,
                text=
                "Произошла непредвиденная ошибка. Программа будет закрыта.\n"
                "Вы можете отправить файл error.txt автору программы, что бы он её есправил.\n"
                "Извините за причененные неудобства")
            l.pack()
            time.sleep(5)
            self.root.destroy()
            traceback.print_exc()
            exit(-1)

    def stat_done(self):
        self.start_button.configure(state=NORMAL)
        self.listbox.configure(state=NORMAL)
        self.is_working = False
        webbrowser.open("file:///" + os.path.join(os.path.abspath(os.getcwd()),
                                                  'result', 'result.html'))

    def progress(self, frac):
        self.progress_value.set(frac * 10000)

    def message(self, msg):
        def f(msg):
            self.t.configure(state=NORMAL)
            self.t.insert(END, msg)
            self.t.configure(state=DISABLED)

        self.root.after(10, f, msg)
コード例 #7
0
def mangrovehealthchange(root, zoneshp, mangrovehealthshp):
    writepath = './FormatedShapefiles/Mangroves/m_health_FUTURE.shp'
    w = shapefile.Writer(writepath)

    totalshapes = len(mangrovehealthshp.shapes())
    i = 0
    # Copy over the existing fields
    fields = mangrovehealthshp.fields
    for name in fields:
        if type(name) == "tuple":
            continue
        else:
            args = name
            w.field(*args)

    progresswindow = tk.Toplevel(root)
    progresswindow.geometry("+400+350")
    progresslabel = tk.Label(progresswindow,
                             text='Progresso do Cálculo',
                             font=('Arial', 24))
    progresslabel.pack(pady=10)
    progress = Progressbar(progresswindow,
                           orient='horizontal',
                           length=1000,
                           mode='determinate')
    progress.pack(pady=10)

    for mangroveshaperec in mangrovehealthshp.iterShapeRecords():
        i += 1
        if i % 100 == 0:
            progressvalue = i / totalshapes * 100
            print('Progress: ', progressvalue, '%')
            progress['value'] = progressvalue
            root.update_idletasks()

        mangroveboundary = mangroveshaperec.shape
        mangroveboundary = shapely.geometry.shape(mangroveboundary)
        health = mangroveshaperec.record['mangroveHe']

        for zoneshaperec in zoneshp.iterShapeRecords():
            zoneboundary = zoneshaperec.shape
            zoneboundary = shapely.geometry.shape(zoneboundary)
            if mangroveboundary.intersects(zoneboundary):
                zonestatus = zoneshaperec.record['Zone_TypeN']
                if zonestatus == 0:
                    health = health + 1
                elif zonestatus == 1:
                    if health < 3:
                        health = health + 1
                    elif health > 4:
                        health = health - 1
                    else:
                        health = health
                else:
                    health = health - 1

                if health > 6:
                    health = 6
                elif health < 0:
                    health = 0
                break

        mangroveshaperec.record['mangroveHe'] = health
        w.record(*mangroveshaperec.record)
        w.shape(mangroveshaperec.shape)

    # Close and save the altered shapefile
    w.close()
    progresswindow.destroy()
    return shapefile.Reader(writepath)

    for shaperec in self.zone_default.iterShapeRecords():
        boundary = shaperec.shape  # get a boundary polygon
        if shapely.geometry.Point(
            (geox, geoy)).within(shapely.geometry.shape(
                boundary)):  # make a point and see if it's in the polygon
            #Pull data from shapefile
            name = shaperec.record[
                1]  # get the second field of the corresponding record
            population = shaperec.record['POP']
            zonetype = shaperec.record['Zone_Type']
            emp = shaperec.record['Emp']
            agri = shaperec.record['Agri']
            print("The point is in", name)

            #Calculate area of zone
            geom = shapely.geometry.polygon.Polygon(boundary.points)
            geom_area = shapely.ops.transform(
                partial(pyproj.transform, pyproj.Proj(init='EPSG:4326'),
                        pyproj.Proj(init='epsg:3857')),
                shapely.geometry.shape(geom))
            area = geom_area.area

            #Calculate area of mangrove loss in zone
            area_of_loss = 0
            for shaperec in self.shape_mangroveloss.iterShapeRecords():
                m_boundary = shaperec.shape  # get a boundary polygon
                m_boundary_shape = shapely.geometry.shape(m_boundary)
                if m_boundary_shape.intersects(
                        shapely.geometry.shape(boundary)):
                    m_geom = shapely.geometry.polygon.Polygon(
                        m_boundary.points)
                    m_geom_area = shapely.ops.transform(
                        partial(pyproj.transform,
                                pyproj.Proj(init='EPSG:4326'),
                                pyproj.Proj(init='epsg:3857')),
                        shapely.geometry.shape(m_geom))
                    area_of_loss = area_of_loss + m_geom_area.area
コード例 #8
0
class App(object):

    screen_background = "#EAEAAE"
    screen_resizable = (False,False)
    screen_title = "File Transfer GUI"

    __address = None
    __path = None
    __mode = FileTransfer.CLIENT


    def __init__(self):
        
        # Obtém a largura da tela do dispositivo do usuário
        self.__window = Tk()
        width = self.__window.winfo_screenwidth()
        default_width = 600
        self.__window.destroy()

        # Define o tamanho da janela do programa
        if width >= default_width:
            self.screen_geometry = [default_width,int(0.16666666666666666666666666666667*default_width)]
        else:
            self.screen_geometry = [width,int(0.16666666666666666666666666666667*width)]

        # Ajusta o tamanho de fonte, largura e outros com base na resolução da janela do programa
        self.button_font = ("Arial",int(15/default_width*self.screen_geometry[0]))
        self.button_width = int(10/default_width*self.screen_geometry[0])
        self.entry_font = ("Arial",int(20/default_width*self.screen_geometry[0]))
        self.filename_size = int(20/default_width*self.screen_geometry[0])
        self.label_font = ("Arial",int(15/default_width*self.screen_geometry[0]))
        self.__sep = int(5/default_width*self.screen_geometry[0])

        # Cria um objeto para realizar a transferência
        self.fileTransfer = FileTransfer()

        # Cria a janela
        self.buildWindow()

        # Cria parte para inserir o endereço e tipo da transferência
        self.buildInterfaceToCreateConnection()
    
        self.__window.mainloop()


    def buildWindow(self,title=screen_title):
        """
        Método para criar a janela do programa.
        """

        # Cria janela e realiza algumas configurações
        self.__window = Tk()
        self.__window.title(title)
        self.__window.resizable(*self.screen_resizable)
        self.__window.geometry("{}x{}".format(*self.screen_geometry))
        self.__window.protocol("WM_DELETE_WINDOW",self.close)
        self.__window["bg"] = self.screen_background

        # Cria estilos dos botões do programa
        self.__style = Style()
        self.__style.configure("SELECTED.TButton",background=self.screen_background,foreground="red",font=self.button_font,width=self.button_width)
        self.__style.configure("TButton",background=self.screen_background,foreground="black",font=self.button_font,width=self.button_width)


    def buildInterfaceToCreateConnection(self):
        """
        Método para criar uma interface para o usuário 
        inserir o endereço e tipo de transferência.
        """

        def clearEntry(entry):
            """
            Função para limpar o título das Entrys.
            """
            if entry.hasTitle and entry.get() == entry.title:
                entry.delete(0,"end")
                entry.hasTitle = False

        # Cria um frame para colocar as Entrys de IP e PORT NUMBER
        entrysFrame = Frame(self.__window,bg=self.screen_background)
        entrysFrame.pack(side="left",padx=self.__sep)

        # Cria uma entry para inserir o IP 
        self.__ip_entry = Entry(entrysFrame,font=self.entry_font)
        self.__ip_entry.title = "IP: "
        self.__ip_entry.insert(0,self.__ip_entry.title)
        self.__ip_entry.hasTitle = True
        self.__ip_entry.bind("<Button-1>",lambda event: clearEntry(self.__ip_entry))
        self.__ip_entry.pack(padx=self.__sep)

        # Cria uma entry para inserir o PORT NUMBER
        self.__port_entry = Entry(entrysFrame,font=self.entry_font)
        self.__port_entry.title = "PORT: "
        self.__port_entry.insert(0,self.__port_entry.title)
        self.__port_entry.hasTitle = True
        self.__port_entry.bind("<Button-1>",lambda event: clearEntry(self.__port_entry))
        self.__port_entry.pack(padx=self.__sep,pady=self.__sep)

        # Cria um frame para os botões
        buttonsFrame = Frame(self.__window,bg=self.screen_background)
        buttonsFrame.pack(side="left",padx=self.__sep)

        #Cria um frame somente para botões de seleção de modo de transferência
        modeButtonsFrame = Frame(buttonsFrame,bg=self.screen_background)
        modeButtonsFrame.pack(side="top",pady=self.__sep*2)

        # Cria um botão para selecionar o modo Client (Download). Por padrão, ele já é selecionado.
        self.clientButton = Button(modeButtonsFrame,text="Client",style="SELECTED.TButton")
        self.clientButton.config(command=lambda: self.setMode("client",True))
        self.clientButton.pack(side="left",padx=self.__sep)

        # Cria um botão para selecionar o modo Host (Upload)
        self.hostButton = Button(modeButtonsFrame,text="Host",style="TButton")
        self.hostButton.config(command=lambda: self.setMode("host",True))
        self.hostButton.pack(side="left",padx=self.__sep)

        # Cria um botão para prosseguir
        self.continueButton = Button(buttonsFrame,text="Continue",width=(self.button_width*2)-3+self.__sep,style="TButton")
        self.continueButton.config(command=self.buildInterfaceToSelectPathOrFilename)
        self.continueButton.pack(side="top",pady=self.__sep)


    def buildInterfaceToSelectPathOrFilename(self):
        """
        Método para criar uma interface onde o usuário possa
        escolher o arquivo que será enviado ou o diretório onde
        o arquivo baixado será salvo.
        """

        def clearEntry(entry):
            """
            Função para limpar o título das Entrys.
            """
            if entry.hasTitle and entry.get() == entry.title:
                entry.delete(0,"end")
                entry.hasTitle = False
            elif self.__path:
                entry.delete(0,"end")
                self.__path_entry.insert(0,self.__path)

        def setPath():
            """
            Função para definir o caminho do arquivo ou da pasta.
            """
            path = functionToGetDirectory()
            if not path or path == self.__path_entry.title:
                return
            self.__path_entry.delete(0,"end")
            self.__path_entry.insert(0,path)
            self.__path = path


        # Recebe o IP e o PORT NUMBER dentro das entrys
        ip = self.__ip_entry.get()
        port = self.__port_entry.get()

        # Se o PORT NUMBER não for numérico ou o usuário não 
        # tiver inserido um IP ou PORT NUMBER, não será possível prosseguir.
        if port.isnumeric():
            port = int(port)
        else: return
        if (not ip or ip == self.__ip_entry.title) or (not port or port == self.__port_entry.title): return 
        

        self.__address = (ip,port)

        # Destrói a janela antiga para criar uma nova
        self.__window.destroy()
        self.buildWindow(self.screen_title+"   [ {} : {} ]".format(*self.__address))

        # Cria uma entry para guardar o caminho do arquivo ou pasta selecionada
        self.__path_entry = Entry(self.__window,font=self.entry_font)

        # Define o título da entry e a função para selecionar 
        # o caminho do arquivo ou pasta, com base no modo de transferência 
        # selecionado anteriormente.

        if self.__mode == FileTransfer.CLIENT:
            self.__path_entry.title = "Directory to save file: "
            self.__path_entry.insert(0,self.__path_entry.title)
            functionToGetDirectory = askdirectory
        else:
            self.__path_entry.title = "File to upload: "
            self.__path_entry.insert(0,self.__path_entry.title)
            functionToGetDirectory = askopenfilename
        
        # Configura a entry
        self.__path_entry.hasTitle = True
        self.__path_entry.bind("<Button-1>",lambda event: clearEntry(self.__path_entry))
        self.__path_entry.pack(side="left",padx=self.__sep*2)

        # Cria botão para selecionar um arquivo ou pasta
        findButton = Button(self.__window,text="Search",command=setPath,style="TButton")
        findButton.pack(side="left",padx=self.__sep)

        # Cria um botão para iniciar a transferência
        connectButton = Button(self.__window,text="Connect",style="TButton")
        connectButton.config(command=self.buildInterfaceToConnect)
        connectButton.pack(side="left",padx=self.__sep)

        self.__window.mainloop()


    def buildInterfaceToConnect(self):
        """
        Método para criar uma interface onde o usuário possa ver tudo relacionado
        à conexão do client e servidor e transferência do arquivo.
        """

        # Caso o usuário não tenha selecionado um arquivo ou pasta, 
        # não será possível prosseguir.
        if not self.__path:
            return

        if self.__path != self.__path_entry.get():
            self.__path_entry.delete(0,"end")
            self.__path_entry.insert(0,self.__path)
            return

        # Destrói a janela antiga para criar uma nova
        self.__window.destroy()
        self.buildWindow(self.screen_title+"   [ {} : {} ]".format(*self.__address))

        # Cria um label para mostrar todas as informações da transferência e conexão
        self.__infoLabel = Label(self.__window,bg=self.screen_background,font=self.label_font) 
        self.__infoLabel.pack(pady=self.__sep*3)

        # Essa variável irá guardar a resposta da conexão.
        self.__resp = None

        def connect():
            """
            Função para iniciar a conexão
            """
            try:
                # Obtêm uma resposta da conexão
                self.__resp = self.fileTransfer.connect(self.__address)
                self.buildInterfaceToTransfer()
            except:
                self.__infoLabel.config(text="Failed to attempt to connect.")
                Button(self.__window,text="Close",command=self.close,style="TButton").pack()

        # Define o modo da transferência
        self.fileTransfer.changeMode(self.__mode)

        # Informa o usuário que a conexão está sendo estabelecida
        if self.__mode == FileTransfer.CLIENT:
            self.__infoLabel.config(text="Connecting ...")
            self.fileTransfer.changePath(self.__path)
        else:
            self.fileTransfer.changeFileName(self.__path)
            self.__infoLabel.config(text="Awaiting connection ...")

        # Cria um processo para tentar conectar-se sem causar danos à interface gráfica
        Thread(target=connect).start()
        self.__window.mainloop()


    def buildInterfaceToTransfer(self):
        """
        Método para criar uma interface para o usuário 
        acompanhar o progresso da transferência.
        """

        def transfer():
            """
            Função para iniciar a transferência
            """
            def threadFunction():
                """
                Função que será executada dentro de uma Thread para realizar
                a transferência sem causar danos à interface gráfica.
                """

                try:
                    self.fileTransfer.transfer(progressFunction)
                    self.__progressBar.forget()
                    self.__infoLabel.config(text="Transfer completed successfully.")
                    Button(self.__window,text="Close",command=self.close,style="TButton").pack()
                except:
                    self.__progressBar.forget()

                    if self.__mode == FileTransfer.CLIENT:
                        self.__infoLabel.config(text="A failure occurred during the transfer.")
                    else:
                        self.__infoLabel.config(text="Connection terminated.")
                    Button(self.__window,text="Close",command=self.close,style="TButton").pack()

            # Destrói o botão para permitir o download
            downloadButton.destroy()

            # Cria um objeto de DoubleVar para o preenchimento da barra de progresso
            self.__variable = DoubleVar()
            self.__variable.set(0)

            # Cria uma barra de progresso para o usuário ter uma noção maior do andamento da transferência
            self.__progressBar = Progressbar(
                self.__window,
                variable=self.__variable,
                maximum=100,
                length=100*(int(self.screen_geometry[0]/100))-(self.__sep*2)
                )
            self.__progressBar.pack()

            # Executa toda a transferência dentro de uma thread
            Thread(target=threadFunction).start()

        def progressFunction(percent):
            """
            Função para atualizar o progresso da transferência.
            """

            if self.__mode == FileTransfer.CLIENT:

                filename = self.__resp[0]

                # Verifica se o tamanho do nome do arquivo é maior que o tamanho limite. Se sim, ele será reduzido
                if len(filename.split(".")[0]) > self.filename_size:
                    filename = filename.split(".")[0][0:self.filename_size]+"."+filename.split(".")[-1]

                self.__infoLabel.config(text='Downloading "{}" ... {}%'.format(filename,int(percent))) 
            else:
                filename = self.__path[-1]

                # Verifica se o tamanho do nome do arquivo é maior que o tamanho limite. Se sim, ele será reduzido
                if len(filename.split(".")[0]) > self.filename_size:
                    filename = filename.split(".")[0][0:self.filename_size]+"."+filename.split(".")[-1]

                self.__infoLabel.config(text='Sending "{}" ... {}%'.format(filename,int(percent)))
            self.__variable.set(percent)


        # Transforma a resposta da conexão em uma lista
        resp = list(self.__resp)

        # Divide o diretório
        self.__path = os.path.split(self.__path)

        # Cria um botão para que o usuário autorize ou não o download
        downloadButton = Button(self.__window,text="Download",width=self.button_width,command=transfer,style="TButton")

        # Se o usuário estiver realizando o download do arquivo, 
        # será mostrado o nome do arquivo, sua extensão e o tamanho
        # do arquivo formatado em (Bytes,KB,MB,GB,TB). 
        # O botão para permitir o download será mostrado apenas nesse modo.
        # Caso o usuário esteja realizando o envio do arquivo, o programa será 
        # mandado direto para a função de transferência onde o usuário,
        # terá que aguardar o Client autorizar o envio.

        if self.__mode == FileTransfer.CLIENT:

            # Formata o tamanho do arquivo
            resp[1] = int(float(resp[1]))
            size = FileTransfer.getFormattedSize(resp[1])

            # Verifica se o tamanho do nome do arquivo é maior que o tamanho limite. Se sim, ele será reduzido
            if len(resp[0].split(".")[0]) > self.filename_size:
                resp[0] = resp[0].split(".")[0][0:self.filename_size]+"."+resp[0].split(".")[-1]

            self.__infoLabel.config(text="%s [%.2f %s]"%(resp[0],size[0],size[1]))
            downloadButton.pack()

        else:
            self.__infoLabel.config(text="Awaiting confirmation of {} ...".format(resp[0]))
            transfer()


    def close(self):
        """
        Método para fechar o programa
        """
        self.fileTransfer.close()
        self.__window.destroy()
        quit()


    def getWindow(self):
        return self.__window


    def setAddress(self,ip,port):
        self.__address = (ip,port)


    def setMode(self,mode,button=None):
        
        # Altera o modo de transferência
        if mode.lower() == "client":
            mode = FileTransfer.CLIENT
        elif mode.lower() == "host":
            mode = FileTransfer.HOST
        else: raise TypeError

        self.__mode = mode   

        # Essa parte está relacionada à interface para inserir o endereço
        # e o modo de transferência. O estilo de botão será alterado adequamente.
        if button:
            if mode == FileTransfer.CLIENT:
                self.clientButton.config(style="SELECTED.TButton")
                self.hostButton.config(style="TButton")
            else:
                self.clientButton.config(style="TButton")
                self.hostButton.config(style="SELECTED.TButton")
コード例 #9
0
class Payment_GUI():
    def __init__(self, master):
        print("Payment GUI initiated")
        self.master = master
        master.configure(background="white", cursor='none')
        master.title("Coffiota")
        #create frame
        self.topframe = Frame(master, bg='white')
        self.topframe.pack()
        #create and render QR code and price text
        self.qrframe = Frame(self.topframe)
        self.qrframe.pack()

        self.code = pyqrcode.create('')
        self.code_xbm = self.code.xbm(scale=3)
        self.code_bmp = tkinter.BitmapImage(data=self.code_xbm)
        self.code_bmp.config(background="white")

        self.qrcode = tkinter.Label(self.qrframe,
                                    image=self.code_bmp,
                                    borderwidth=0)
        self.qrcode.pack()

        #progress bar

        self.progressFrame = Frame(self.topframe)
        self.progressFrame.pack()
        self.progress = Progressbar(self.progressFrame,
                                    orient=HORIZONTAL,
                                    length=100,
                                    mode='determinate')
        self.progress.pack()

        self.paymentStatusFrame = Frame(self.topframe)
        self.paymentStatusFrame.pack()
        self.paymentState = Label(self.paymentStatusFrame,
                                  text=paymentStatusText,
                                  font=("Helvetica", 9))
        self.paymentState.pack()

        self.close_button = Button(self.topframe,
                                   text="Close",
                                   command=exitGUI)
        self.close_button.pack()
        #create and render transaction status

    def updateQRcode(self, _price, _address):
        self.QRaddr = '{"address":"%s","amount":%d,"message":"","tag":"COFFIOTA"}' % (
            _address, _price)
        self.code = pyqrcode.create(self.QRaddr)
        self.code_xbm = self.code.xbm(scale=3)
        self.code_bmp = tkinter.BitmapImage(data=self.code_xbm)
        self.code_bmp.config(background="white")
        self.qrcode.configure(image=self.code_bmp)
        self.qrcode.image = self.code_bmp

    #def progress(self,_status):
    #status looking for transaction

    #status pending transaction

    #status transaction complete or appropiate balance

    def exitPayment(self):
        self.topframe.destroy()

    def exitGUI(self):
        root.destroy()
コード例 #10
0

if __name__ == '__main__':
    root.title("Sinhalen Subtitle Maker")
    # root.geometry("500x240")
    w = root.winfo_reqwidth()
    h = root.winfo_reqheight()
    ws = root.winfo_screenwidth()
    hs = root.winfo_screenheight()
    x = (ws / 2) - (w / 2)
    y = (hs / 2) - (h / 2)
    root.geometry('+%d+%d' % (x, y))
    root.resizable(0, 0)

    # Dictionary with options
    choices = {'si', 'en', 'ta'}
    tkvar.set('si')  # set the default option
    ents = makeform(root, fields)
    btn_row = Frame(root)
    btn_row.pack(side=TOP, fill=X, padx=10, pady=8)
    b1 = Button(btn_row, text='Open File',
                command=lambda: open_file(root, ents))
    b1.pack(side=LEFT, padx=5, pady=5)
    b3 = Button(btn_row, text='Convert', command=lambda: async_convert(root, ents))
    b3.pack(side=LEFT, padx=10, pady=5)
    b2 = Button(btn_row, text='Quit', command=root.quit)
    b2.pack(side=RIGHT, padx=5, pady=5)
    progress.pack(side=BOTTOM, pady=5)

    root.mainloop()
コード例 #11
0
ファイル: gui.py プロジェクト: ClimenteA/tkinter-boilerplate
    log.close()


root = Tk()
root.title("App v0.1")
root.geometry("600x320")

#root.iconbitmap(os.path.join(os.getcwd(), 'favicon.ico'))

fields = 'input1', 'input2', 'input4', 'input5', 'input6'

ents = makeform(root, fields)

runButton = Button(root,
                   text='Start downloading',
                   command=(lambda e=ents: runActions(progress, status)))
percent = Label(root, text="", anchor=S)
progress = Progressbar(root, length=500, mode='determinate')
status = Label(root,
               text="Click button to start process..",
               relief=SUNKEN,
               anchor=W,
               bd=2)

runButton.pack(pady=15)
percent.pack()
progress.pack()
status.pack(side=BOTTOM, fill=X)

root.mainloop()
コード例 #12
0
             fg="white",
             bg="gray30",
             font='IRANSans 10',
             bd=1)
btn.pack(side=LEFT, padx=(5, 5), pady=(5, 5), fill=BOTH)
btn_whois = Button(frame1,
                   text="اطلاعات",
                   command=t_whois,
                   width=8,
                   fg="white",
                   bg="gray30",
                   font='IRANSans 10',
                   bd=1)
btn_whois.pack(side=LEFT, padx=(5, 5), pady=(5, 5), fill=BOTH)
progress = Progressbar(frame2, orient=VERTICAL, mode='indeterminate')
progress.pack(side=LEFT, anchor=W, padx=(5, 5), pady=(5, 5), fill=BOTH)
get_name = Label(frame2,
                 text=":نام سایت",
                 fg="gray60",
                 bg="lightyellow3",
                 font='IRANSans 10')
get_name.pack(side=TOP, padx=(5, 5), pady=(5, 5), anchor=E)
get_ip = Label(frame2,
               text=":ای پی",
               fg="gray60",
               bg="lightyellow3",
               font='IRANSans 10')
get_ip.pack(side=TOP, padx=(5, 5), pady=(5, 5), anchor=E)
get_resident = Label(frame2,
                     text=":محل سرور",
                     fg="gray60",
コード例 #13
0
class MainWindow:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title('Demo')

    def show(self):
        self.progress = tk.IntVar()
        self.progress_max = 100
        self.progressbar = Progressbar(self.root,
                                       mode='determinate',
                                       orient=tk.HORIZONTAL,
                                       variable=self.progress,
                                       maximum=self.progress_max)
        self.progressbar.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        self.progress.set(0)

        btn = tk.Button(self.root, text='start', command=self.start)
        btn.pack(fill=tk.BOTH, expand=True, padx=15, pady=5)
        self.btn = btn

        self.root.mainloop()

    def start(self):
        self.progress.set(0)
        self.btn.config(state=tk.DISABLED)

        # used to communicate between main thread (UI) and worker thread
        self.thread_queue = queue.Queue()
        collect = QMM(sleep=3, months='3-4', days='1-31')
        print('begin thread: collect.start()')
        new_thread = threading.Thread(target=collect.start(),
                                      kwargs={
                                          'param1': 100,
                                          'param2': 20
                                      })
        new_thread.start()

        # schedule a time-task to check UI
        # it's in main thread, because it's called by self.root
        self.root.after(100, self.listen_for_result)

    def run_loop(self, param1, param2):
        progress = 0
        for entry in range(self.progress_max):
            time.sleep(0.1)
            progress = progress + 1
            self.thread_queue.put(progress)

    def listen_for_result(self):
        '''
        Check if there is something in the queue.
        Must be invoked by self.root to be sure it's running in main thread
        '''
        try:
            progress = self.thread_queue.get(False)
            self.progress.set(progress)
        except queue.Empty:  # must exist to avoid trace-back
            pass
        finally:
            if self.progress.get() < self.progressbar['maximum']:
                self.root.after(100, self.listen_for_result)
            else:
                self.btn.config(state=tk.NORMAL)
class RightPanel(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.pack(side=tk.RIGHT, fill=tk.BOTH)

        self.map_dim = [0, 0]
        self.param_frame = tk.LabelFrame(self, text="Parameters")
        self.param_frame.configure(padx=5, pady=5)
        self.param_frame.grid_columnconfigure(1, weight=1)
        self.param_frame.pack(fill=tk.X)
        tk.Label(self.param_frame, text="M :").grid(row=2, column=0, sticky='sw')
        self.m_scale = tk.Scale(self.param_frame, from_=16, to=128, orient=tk.HORIZONTAL, resolution=16)
        self.m_scale.grid(row=2, column=1, sticky='nsew')
        self.m_scale.set(64)
        tk.Label(self.param_frame, text="N :").grid(row=3, column=0, sticky='sw')
        self.n_scale = tk.Scale(self.param_frame, from_=16, to=128, orient=tk.HORIZONTAL, resolution=16)
        self.n_scale.grid(row=3, column=1, sticky='nsew')
        self.n_scale.set(64)
        tk.Label(self.param_frame, text="Detection :").grid(row=4, column=0, sticky='sw')
        self.combo_detect = tk.ttk.Combobox(self.param_frame, state="readonly")
        self.combo_detect['values'] = ('Peak Detection', 'CA-CFAR') #'OS-CFAR'
        self.combo_detect.current(0)
        self.combo_detect.grid(row=4, column=1, sticky='nsew')
        self.combo_detect.bind("<<ComboboxSelected>>", self.detectionEvent)
        self.label_thresh = tk.Label(self.param_frame, text="Detection\nThreshold :")
        self.label_thresh.grid(row=5, column=0, sticky='sw')
        self.detect_thresh = tk.Scale(self.param_frame, orient=tk.HORIZONTAL, from_=-50, to=-150, resolution=10)
        self.detect_thresh.grid(row=5, column=1, sticky='nsew')
        self.detect_thresh.set(-90)
        self.proba_label = tk.Label(self.param_frame, text="Pᶠᵃ [log10]:")
        self.proba_label.grid(row=6, column=0, sticky='sw')
        self.proba_label.grid_remove()
        self.proba_scale = tk.Scale(self.param_frame, orient=tk.HORIZONTAL, from_=-1, to=-10, resolution=1)
        self.proba_scale.grid(row=6, column=1, sticky='nsew')
        self.proba_scale.set(-9)
        self.proba_scale.grid_remove()
        self.proba_btn = tk.Button(self.param_frame, text="\u2193")
        self.proba_btn.grid(row=6, column=2, sticky='s')
        self.proba_btn.grid_remove()
        self.NCFAR_label = tk.Label(self.param_frame, text="Nᶜᶠᵃʳ :")
        self.NCFAR_label.grid(row=7, column=0, sticky='sw')
        self.NCFAR_label.grid_remove()
        self.NCFAR_scale = tk.Scale(self.param_frame, orient=tk.HORIZONTAL, from_=10, to=50, resolution=10)
        self.NCFAR_scale.grid(row=7, column=1, sticky='nsew')
        self.NCFAR_scale.set(20)
        self.NCFAR_scale.grid_remove()
        self.NCFAR_btn = tk.Button(self.param_frame, text="\u2193")
        self.NCFAR_btn.grid(row=7, column=2, sticky='s')
        self.NCFAR_btn.grid_remove()
        self.guard_label = tk.Label(self.param_frame, text="Guard Cells :")
        self.guard_label.grid(row=8, column=0, sticky='sw')
        self.guard_label.grid_remove()
        self.guard_scale = tk.Scale(self.param_frame, orient=tk.HORIZONTAL, from_=0, to=6, resolution=2)
        self.guard_scale.grid(row=8, column=1, sticky='nsew')
        self.guard_scale.set(2)
        self.guard_scale.grid_remove()
        self.guard_btn = tk.Button(self.param_frame, text="\u2193")
        self.guard_btn.grid(row=8, column=2, sticky='s')
        self.guard_btn.grid_remove()

        self.pfa_var = tk.StringVar()
        self.pfa_label = tk.Label(self.param_frame, textvariable=self.pfa_var)
        self.pfa_label.grid(row=11, column=1, sticky='nsew')
        self.pfa_label.grid_remove()
        tk.Label(self.param_frame, text="AoA\nThreshold :").grid(row=12, column=0, sticky='sw')
        self.aoa_thresh = tk.Scale(self.param_frame, orient=tk.HORIZONTAL, from_=0, to=-10, resolution=1)
        self.aoa_thresh.grid(row=12, column=1, sticky='nsew')
        self.aoa_thresh.set(-6)
        self.aoa_btn = tk.Button(self.param_frame, text="\u2193")
        self.aoa_btn.grid(row=12, column=2, sticky='e')
        self.range_check = tk.IntVar()
        self.range_check.set(1)
        self.range_btn = tk.Checkbutton(self.param_frame, text="Range leakage", variable=self.range_check, onvalue=1, offvalue=0)
        self.range_btn.grid(row=13, column=1, sticky='e')

        self.sim_frame = tk.LabelFrame(self, text="Time simulation")
        self.sim_frame.configure(padx=5, pady=5)
        self.sim_frame.grid_columnconfigure(1, weight=1)
        self.sim_frame.pack(fill=tk.X)
        tk.Label(self.sim_frame, text="Duration [s]:").grid(row=0, column=0, sticky='sw')
        self.time_scale = tk.Scale(self.sim_frame, from_=1, to=20, orient=tk.HORIZONTAL, resolution=1)
        self.time_scale.grid(row=0, column=1, sticky='nsew')
        self.time_scale.set(10)

        tk.Label(self.sim_frame, text="RDM Freq. [Hz]:").grid(row=1, column=0, sticky='sw')
        self.rdm_scale = tk.Scale(self.sim_frame, from_=1, to=4, orient=tk.HORIZONTAL, resolution=1)
        self.rdm_scale.grid(row=1, column=1, sticky='nsew')
        self.rdm_scale.set(2)

        self.run_btn = tk.Button(self.sim_frame, text="Run Simulation")
        self.run_btn['state'] = 'disabled'
        self.run_btn.grid(row=2, column=1, columnspan=3)

        self.analysis_frame = tk.LabelFrame(self, text="Instant analysis")
        self.analysis_frame.configure(padx=5, pady=5)
        self.analysis_frame.pack(fill=tk.Y)
        self.analysis_frame.grid_columnconfigure(1, weight=1)

        style = ttk.Style()
        style.configure("mystyle.Treeview", background='white')
        style.configure("mystyle.Treeview.Heading", font=('Calibri', 10, 'bold'), background='lightgray')

        self.yScroll_1 = tk.Scrollbar(self.analysis_frame, orient=tk.VERTICAL)
        self.thresh_tree = ttk.Treeview(self.analysis_frame, selectmode='extended', yscrollcommand=self.yScroll_1.set,
                                        style="mystyle.Treeview")
        self.yScroll_1.config(command=self.thresh_tree.yview)

        self.thresh_tree.grid(row=1, column=0, columnspan=2)
        self.yScroll_1.grid(row=1, column=2, sticky='ns')

        self.yScroll_2 = tk.Scrollbar(self.analysis_frame, orient=tk.VERTICAL)
        self.CACFAR_tree = ttk.Treeview(self.analysis_frame, selectmode='extended', yscrollcommand=self.yScroll_2.set,
                                        style="mystyle.Treeview")
        self.yScroll_2.config(command=self.CACFAR_tree.yview)
        self.CACFAR_tree.grid(row=1, column=0, columnspan=2)
        self.yScroll_2.grid(row=1, column=2, stick='ns')

        self.CACFAR_tree.grid_remove()
        self.yScroll_2.grid_remove()

        self.configureTrees()

        self.add_btn = tk.Button(self.analysis_frame, text="Add")
        self.add_btn.grid(row=2, column=2)
        self.remove_btn = tk.Button(self.analysis_frame, text="Remove")
        self.remove_btn['state'] = 'disabled'
        self.remove_btn.grid(row=2, column=1, sticky='e')
        self.clear_btn = tk.Button(self.analysis_frame, text="Clear")
        self.clear_btn.grid(row=2, column=0, sticky='w')

        tk.Label(self.analysis_frame, text="Nb. of iteration for\neach parameter :").grid(row=3, column=0, sticky='sw')
        self.run_scale = tk.Scale(self.analysis_frame, from_=10, to=1000, orient=tk.HORIZONTAL, resolution=10)
        self.run_scale.grid(row=3, column=1, sticky='nsew')
        self.run_scale.set(50)
        self.analysis_btn = tk.Button(self.analysis_frame, text="Run Analysis")
        self.analysis_btn['state'] = 'disabled'
        self.analysis_btn.grid(row=4, column=0, columnspan=2)

        self.progress_bar = Progressbar(self, orient=tk.HORIZONTAL, mode='determinate')
        self.progress_bar.pack(fill=tk.X)

    def configureTrees(self):
        # Threshold :
        self.thresh_tree['columns'] = ('N', 'M', 'thresh', 'AoA', 'RL')
        self.thresh_tree['show'] = 'headings'
        self.thresh_tree['height'] = 7
        self.thresh_tree['selectmode'] = None
        self.thresh_tree.column('N', width=30, anchor='c', stretch=False)
        self.thresh_tree.column('M', width=30, anchor='c', stretch=False)
        self.thresh_tree.column('thresh', width=90, anchor='c', stretch=False)
        self.thresh_tree.column('AoA', width=80, anchor='c', stretch=False)
        self.thresh_tree.column('RL', width=80, anchor='c', stretch=False)

        self.thresh_tree.heading("N", text="N")
        self.thresh_tree.heading("M", text="M")
        self.thresh_tree.heading("thresh", text="Detec. Thresh.")
        self.thresh_tree.heading("AoA", text="AoA Thresh.")
        self.thresh_tree.heading('RL', text="Range Leak.")

        # CA-CFAR
        self.CACFAR_tree['columns'] = ('N', 'M', 'pfa', 'NCFAR', 'guard', 'AoA', 'RL')
        self.CACFAR_tree['show'] = 'headings'
        self.CACFAR_tree['height'] = 7
        self.CACFAR_tree['selectmode'] = None
        self.CACFAR_tree.column('N', width=30, anchor='c')
        self.CACFAR_tree.column('M', width=30, anchor='c')
        self.CACFAR_tree.column('pfa', width=30, anchor='c')
        self.CACFAR_tree.column('NCFAR', width=40, anchor='c')
        self.CACFAR_tree.column('guard', width=40, anchor='c')
        self.CACFAR_tree.column('AoA', width=80, anchor='c')
        self.CACFAR_tree.column('RL', width=80, anchor='c')

        self.CACFAR_tree.heading('N', text='N')
        self.CACFAR_tree.heading('M', text='M')
        self.CACFAR_tree.heading('pfa', text='Pfa')
        self.CACFAR_tree.heading('NCFAR', text='Ncfar')
        self.CACFAR_tree.heading('guard', text='Guard')
        self.CACFAR_tree.heading('AoA', text='AoA Thresh.')
        self.CACFAR_tree.heading('RL', text='Range Leak.')

    def setMapDim(self, map_dim):
        self.map_dim = map_dim

    def bar(self, value):
        self.progress_bar['value'] = round(100 * value / self.time_scale.get())
        self.progress_bar.update_idletasks()

    def barAnalysis(self, value):
        self.progress_bar['value'] = round(100 * value / self.run_scale.get())
        self.progress_bar.update_idletasks()

    def addParam(self, param):
        if param['detect'] == "Peak Detection":
            self.thresh_tree.insert(parent='', index='end', iid=param['idx'], values=(param['N'], param['M'], param['thresh'], param['AoA'], param['RL']))
        else:
            self.CACFAR_tree.insert(parent='', index='end', iid=param['idx'], values=(param['N'], param['M'], param['pfa'], param['NCFAR'], param['guard'], param['AoA'], param['RL']))

        self.remove_btn['state'] = "normal"

    def removeParam(self, items):
        detection_type = self.combo_detect.get()
        if detection_type == "Peak Detection":
            for item in items:
                self.thresh_tree.delete(item)
            if len(self.thresh_tree.get_children()) == 0:
                self.remove_btn['state'] = "disabled"
        else:
            for item in items:
                self.CACFAR_tree.delete(item)
            if len(self.CACFAR_tree.get_children()) == 0:
                self.remove_btn['state'] = "disabled"

    def detectionEvent(self, event):
        event.widget.master.focus_set()
        self.changeDetectionMode()

    def changeDetectionMode(self):
        if self.combo_detect.get() == "Peak Detection":
            if len(self.thresh_tree.get_children()) > 0:
                self.remove_btn['state'] = "normal"
            else:
                self.remove_btn['state'] = "disabled"

            self.yScroll_2.grid_remove()
            self.CACFAR_tree.grid_remove()
            self.yScroll_1.grid()
            self.thresh_tree.grid()

            self.proba_label.grid_remove()
            self.proba_scale.grid_remove()
            self.proba_btn.grid_remove()
            self.NCFAR_label.grid_remove()
            self.NCFAR_scale.grid_remove()
            self.NCFAR_btn.grid_remove()
            self.guard_label.grid_remove()
            self.guard_scale.grid_remove()
            self.guard_btn.grid_remove()
            self.pfa_label.grid_remove()
            self.label_thresh.grid()
            self.detect_thresh.grid()

        else:
            if len(self.CACFAR_tree.get_children()) > 0:
                self.remove_btn['state'] = "normal"
            else:
                self.remove_btn['state'] = "disabled"

            self.yScroll_1.grid_remove()
            self.thresh_tree.grid_remove()
            self.yScroll_2.grid()
            self.CACFAR_tree.grid()

            self.label_thresh.grid_remove()
            self.detect_thresh.grid_remove()
            self.pfa_label.grid_remove()
            self.guard_label.grid()
            self.guard_scale.grid()
            self.guard_btn.grid()
            self.proba_label.grid()
            self.proba_scale.grid()
            self.proba_btn.grid()
            self.NCFAR_label.grid()
            self.NCFAR_scale.grid()
            self.NCFAR_btn.grid()

    def updateNScale(self, N):
        if N == 16:
            self.NCFAR_scale.configure(from_=10, to=10)
            self.guard_scale.configure(from_=0, to=2)
        elif N == 32:
            self.NCFAR_scale.configure(from_=10, to=20)
            self.guard_scale.configure(from_=0, to=6)
        elif N == 48:
            self.NCFAR_scale.configure(from_=10, to=30)
            self.guard_scale.configure(from_=0, to=6)
        else:
            self.NCFAR_scale.configure(from_=10, to=50)
            self.guard_scale.configure(from_=0, to=6)

    # ------
    # GET

    def getNM(self):
        return self.n_scale.get(), self.m_scale.get()

    def getDetectionMode(self):
        return self.combo_detect.get()

    def getDetectionThreshold(self):
        return self.detect_thresh.get()

    def getPfa(self):
        return self.proba_scale.get()

    def getNCFAR(self):
        return self.NCFAR_scale.get()

    def getGuardCells(self):
        return self.guard_scale.get()

    def getAngleThreshold(self):
        return self.aoa_thresh.get()

    def getRangeLeak(self):
        return self.range_check.get() == 1
コード例 #15
0
def export_all_fitting_data(calcul_1D, analyze_1D, run_program):
    f = asksaveasfile(title="Export data",
                      mode='w',
                      defaultextension=".txt",
                      filetypes=[('text files', '.txt'), ('all files', '.*')])
    if f is not None and f is not '':
        for widget in analyze_1D.Frame1_2.winfo_children():
            widget.destroy()
        Label(analyze_1D.Frame1_2, text="Export").pack(side=LEFT)
        progress = Progressbar(analyze_1D.Frame1_2,
                               orient="horizontal",
                               mode='determinate')
        progress.pack(side=LEFT)
        progress["value"] = 0
        progress["maximum"] = len(calcul_1D.phi)
        for i in range(len(calcul_1D.two_theta_pearson)):
            progress["value"] = progress["value"] + 1
            progress.update()

            f.write("Range " + str(i + 1) + "\n")
            f.write("Phi=" + str(float(calcul_1D.phi[i])) + "\n")
            f.write("Psi=" + str(float(calcul_1D.psi[i])) + "\n")
            f.write("pic 2 theta: " + str(calcul_1D.two_theta_pearson[i]) +
                    "\n")
            f.write("\n")
            f.write(" two_theta\t")
            f.write("  original\t")
            f.write("background\t")
            f.write("substrat_background\t")
            f.write("   kalpha1\t")
            f.write("   kalpha2\t")
            f.write("fitting_pearson_vii\t")
            f.write("\n")

            for j in range(len(calcul_1D.matrix_two_theta_limit[i])):
                try:
                    f.write(
                        str("%10.4g" %
                            calcul_1D.matrix_two_theta_limit[i][j]) + "\t")
                    f.write(
                        str("%10.4g" %
                            calcul_1D.matrix_intensity_limit[i][j]) + "\t")
                    f.write(
                        str("%10.4g" %
                            calcul_1D.matrix_background_intensity[i][j]) +
                        "\t")
                    f.write(
                        str("%19.4g" % calcul_1D.matrix_real_intensity[i][j]) +
                        "\t")
                    f.write(
                        str("%10.4g" % calcul_1D.matrix_F1_peak1[i][j]) + "\t")
                    f.write(
                        str("%10.4g" % calcul_1D.matrix_F2_peak1[i][j]) + "\t")
                    f.write(
                        str("%19.4g" % calcul_1D.matrix_F_pearson[i][j]) +
                        "\t")
                    f.write("\n")
                except (IndexError, ValueError):
                    pass
            f.write(
                "--------------------------------------------------------------\n"
            )
            f.write("\n")
        f.close()
        for widget in analyze_1D.Frame1_2.winfo_children():
            widget.destroy()
    run_program.fenetre.mainloop()
コード例 #16
0
def export_all_stress_data(stress_calcul, analyze_1D, run_program):
    f = asksaveasfile(title="Export data",
                      mode='w',
                      defaultextension=".text",
                      filetypes=[('text files', '.txt'), ('all files', '.*')])
    if f is not None and f is not '':
        for widget in analyze_1D.Frame1_2.winfo_children():
            widget.destroy()
        Label(analyze_1D.Frame1_2, text="Export").pack(side=LEFT)
        progress = Progressbar(analyze_1D.Frame1_2,
                               orient="horizontal",
                               mode='determinate')
        progress.pack(side=LEFT)
        progress["value"] = 0
        progress["maximum"] = len(stress_calcul.phi_stress) + 2

        if stress_calcul.stress_valid == 1:
            f.write("FUNDAMENTAL METHOD \n")
            f.write("Uniaxial: " + "sigma= " +
                    str(stress_calcul.sigma_phi_uniaxial[0][0]) + "+/-" +
                    str(stress_calcul.sigma_phi_uniaxial[1][0, 0]**0.5) +
                    "MPa" + "\n")
            f.write("Uniaxial+shear: " + "sigma= " +
                    str(stress_calcul.sigma_phi_uniaxial_shear[0][0]) + "+/-" +
                    str(stress_calcul.sigma_phi_uniaxial_shear[1][0, 0]**0.5) +
                    "MPa" + "\n")
            f.write("Uniaxial+shear: " + "shear= " +
                    str(stress_calcul.sigma_phi_uniaxial_shear[0][1]) + "+/-" +
                    str(stress_calcul.sigma_phi_uniaxial_shear[1][1, 1]**0.5) +
                    "MPa" + "\n")
            f.write("--------------\n")
            f.write("SIN2PSI METHOD\n")
            f.write("Linear fit: " + "sigma= " +
                    str(stress_calcul.sigma_phi_linear[0]) + "+/-" +
                    str(stress_calcul.error_sigma_phi_linear[0]) + "MPa" +
                    "\n")
            f.write("Elliptic fit: " + "sigma= " +
                    str(stress_calcul.sigma_phi_elliptic[0]) + "+/-" +
                    str(stress_calcul.error_sigma_phi_elliptic[0]) + "MPa" +
                    "\n")
            f.write("Elliptic fit: " + "shear= " +
                    str(stress_calcul.shear_phi_elliptic[0]) + "+/-" +
                    str(stress_calcul.error_shear_phi_elliptic[0]) + "MPa" +
                    "\n")

        if stress_calcul.sigma12_valid == False and stress_calcul.stress_valid >= 2:
            progress["value"] = progress["value"] + 1
            progress.update()
            f.write('STRESS TENSOR' + "\n")
            f.write("---------------------------------------------------- \n")
            f.write("FUNDAMENTAL METHOD \n")
            f.write("---Biaxial stress----- \n")
            f.write('sigma 11 = ' +
                    str(stress_calcul.tensor_biaxial_simple[0][0]) + "+/-" +
                    str(stress_calcul.tensor_biaxial_simple[1][0, 0]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 22 = ' +
                    str(stress_calcul.tensor_biaxial_simple[0][2]) + "+/-" +
                    str(stress_calcul.tensor_biaxial_simple[1][2, 2]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 12 = sigma 21 = ' +
                    str(stress_calcul.tensor_biaxial_simple[0][1]) + "+/-" +
                    str(stress_calcul.tensor_biaxial_simple[1][1, 1]**0.5) +
                    "MPa" + "\n")
            f.write("---------------------- \n")
            f.write("---Biaxial+shear stress----- \n")
            f.write('sigma 11 = ' +
                    str(stress_calcul.tensor_biaxial_simple_shear[0][0]) +
                    "+/-" +
                    str(stress_calcul.tensor_biaxial_simple_shear[1][0,
                                                                     0]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 22 = ' +
                    str(stress_calcul.tensor_biaxial_simple_shear[0][2]) +
                    "+/-" +
                    str(stress_calcul.tensor_biaxial_simple_shear[1][2,
                                                                     2]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 12 = sigma 21 = ' +
                    str(stress_calcul.tensor_biaxial_simple_shear[0][1]) +
                    "+/-" +
                    str(stress_calcul.tensor_biaxial_simple_shear[1][1,
                                                                     1]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 13 = sigma 31 = ' +
                    str(stress_calcul.tensor_biaxial_simple_shear[0][3]) +
                    "+/-" +
                    str(stress_calcul.tensor_biaxial_simple_shear[1][3,
                                                                     3]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 23 = sigma 32 = ' +
                    str(stress_calcul.tensor_biaxial_simple_shear[0][4]) +
                    "+/-" +
                    str(stress_calcul.tensor_biaxial_simple_shear[1][4,
                                                                     4]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 33 = 0MPa\n')

        if stress_calcul.sigma12_valid == True:
            progress["value"] = progress["value"] + 1
            progress.update()
            f.write('STRESS TENSOR' + "\n")
            f.write("---------------------------------------------------- \n")
            f.write("FUNDAMENTAL METHOD \n")
            f.write("---Biaxial stress----- \n")
            f.write('sigma 11 = ' + str(stress_calcul.tensor_biaxial[0][0]) +
                    "+/-" + str(stress_calcul.tensor_biaxial[1][0, 0]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 22 = ' + str(stress_calcul.tensor_biaxial[0][2]) +
                    "+/-" + str(stress_calcul.tensor_biaxial[1][2, 2]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 12 = sigma 21 = ' +
                    str(stress_calcul.tensor_biaxial[0][1]) + "+/-" +
                    str(stress_calcul.tensor_biaxial[1][1, 1]**0.5) + "MPa" +
                    "\n")
            f.write("---------------------- \n")
            f.write("---Biaxial+shear stress----- \n")
            f.write('sigma 11 = ' +
                    str(stress_calcul.tensor_biaxial_shear[0][0]) + "+/-" +
                    str(stress_calcul.tensor_biaxial_shear[1][0, 0]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 22 = ' +
                    str(stress_calcul.tensor_biaxial_shear[0][2]) + "+/-" +
                    str(stress_calcul.tensor_biaxial_shear[1][2, 2]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 12 = sigma 21 = ' +
                    str(stress_calcul.tensor_biaxial_shear[0][1]) + "+/-" +
                    str(stress_calcul.tensor_biaxial_shear[1][1, 1]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 13 = sigma 31 = ' +
                    str(stress_calcul.tensor_biaxial_shear[0][3]) + "+/-" +
                    str(stress_calcul.tensor_biaxial_shear[1][3, 3]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 23 = sigma 32 = ' +
                    str(stress_calcul.tensor_biaxial_shear[0][4]) + "+/-" +
                    str(stress_calcul.tensor_biaxial_shear[1][4, 4]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 33 = 0MPa\n')
            if stress_calcul.stress_valid >= 3:
                f.write("---Triaxial stress----- \n")
                f.write('sigma 11 = ' +
                        str(stress_calcul.tensor_triaxial[0][0]) + "+/-" +
                        str(stress_calcul.tensor_triaxial[1][0, 0]**0.5) +
                        "MPa" + "\n")
                f.write('sigma 22 = ' +
                        str(stress_calcul.tensor_triaxial[0][2]) + "+/-" +
                        str(stress_calcul.tensor_triaxial[1][2, 2]**0.5) +
                        "MPa" + "\n")
                f.write('sigma 12 = sigma 21 = ' +
                        str(stress_calcul.tensor_triaxial[0][1]) + "+/-" +
                        str(stress_calcul.tensor_triaxial[1][1, 1]**0.5) +
                        "MPa" + "\n")
                f.write('sigma 13 = sigma 31 = ' +
                        str(stress_calcul.tensor_triaxial[0][3]) + "+/-" +
                        str(stress_calcul.tensor_triaxial[1][3, 3]**0.5) +
                        "MPa" + "\n")
                f.write('sigma 23 = sigma 32 = ' +
                        str(stress_calcul.tensor_triaxial[0][4]) + "+/-" +
                        str(stress_calcul.tensor_triaxial[1][4, 4]**0.5) +
                        "MPa" + "\n")
                f.write('sigma 33 = ' +
                        str(stress_calcul.tensor_triaxial[0][5]) + "+/-" +
                        str(stress_calcul.tensor_triaxial[1][5, 5]**0.5) +
                        "MPa" + "\n")
            f.write("---------------------------------------------------- \n")
            f.write("---------------------------------------------------- \n")
            f.write("SIN2PSI METHOD\n")
            f.write("---Biaxial stress----- \n")
            f.write('sigma 11 = ' + str(stress_calcul.tensor_biaxial_1[0][0]) +
                    "+/-" + str(stress_calcul.tensor_biaxial_1[1][0, 0]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 22 = ' + str(stress_calcul.tensor_biaxial_1[0][2]) +
                    "+/-" + str(stress_calcul.tensor_biaxial_1[1][2, 2]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 12 = sigma 21 = ' +
                    str(stress_calcul.tensor_biaxial_1[0][1]) + "+/-" +
                    str(stress_calcul.tensor_biaxial_1[1][1, 1]**0.5) + "MPa" +
                    "\n")
            f.write("---------------------- \n")
            f.write("---Biaxial+shear stress----- \n")
            f.write('sigma 11 = ' +
                    str(stress_calcul.tensor_biaxial_shear_1[0][0]) + "+/-" +
                    str(stress_calcul.tensor_biaxial_shear_1[1][0, 0]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 22 = ' +
                    str(stress_calcul.tensor_biaxial_shear_1[0][2]) + "+/-" +
                    str(stress_calcul.tensor_biaxial_shear_1[1][2, 2]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 12 = sigma 21 = ' +
                    str(stress_calcul.tensor_biaxial_shear_1[0][1]) + "+/-" +
                    str(stress_calcul.tensor_biaxial_shear_1[1][1, 1]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 13 = sigma 31 = ' +
                    str(stress_calcul.tensor_biaxial_shear_1[0][3]) + "+/-" +
                    str(stress_calcul.tensor_biaxial_shear_1[1][3, 3]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 23 = sigma 32 = ' +
                    str(stress_calcul.tensor_biaxial_shear_1[0][4]) + "+/-" +
                    str(stress_calcul.tensor_biaxial_shear_1[1][4, 4]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 33 = 0MPa\n')
            if stress_calcul.stress_valid >= 3:
                f.write("---Triaxial stress----- \n")
                f.write('sigma 11 = ' +
                        str(stress_calcul.tensor_triaxial_1[0][0]) + "+/-" +
                        str(stress_calcul.tensor_triaxial_1[1][0, 0]**0.5) +
                        "MPa" + "\n")
                f.write('sigma 22 = ' +
                        str(stress_calcul.tensor_triaxial_1[0][2]) + "+/-" +
                        str(stress_calcul.tensor_triaxial_1[1][2, 2]**0.5) +
                        "MPa" + "\n")
                f.write('sigma 12 = sigma 21 = ' +
                        str(stress_calcul.tensor_triaxial_1[0][1]) + "+/-" +
                        str(stress_calcul.tensor_triaxial_1[1][1, 1]**0.5) +
                        "MPa" + "\n")
                f.write('sigma 13 = sigma 31 = ' +
                        str(stress_calcul.tensor_triaxial_1[0][3]) + "+/-" +
                        str(stress_calcul.tensor_triaxial_1[1][3, 3]**0.5) +
                        "MPa" + "\n")
                f.write('sigma 23 = sigma 32 = ' +
                        str(stress_calcul.tensor_triaxial_1[0][4]) + "+/-" +
                        str(stress_calcul.tensor_triaxial_1[1][4, 4]**0.5) +
                        "MPa" + "\n")
                f.write('sigma 33 = ' +
                        str(stress_calcul.tensor_triaxial_1[0][5]) + "+/-" +
                        str(stress_calcul.tensor_triaxial_1[1][5, 5]**0.5) +
                        "MPa" + "\n")

            progress["value"] = progress["value"] + 1
            progress.update()
            f.write("---------------------------------------------------- \n")
            f.write("---------------------------------------------------- \n")
            f.write("---------------------------------------------------- \n")
            f.write("---------------------------------------------------- \n")
            f.write('STRESS AT PHI\n')
            f.write("---------------------------------------------------- \n")
            f.write("FUNDAMENTAL METHOD \n")
            for i in range(len(stress_calcul.sigma_phi_biaxial)):
                f.write("----Phi= " + str(stress_calcul.liste_phi[i]) +
                        "(°)----\n")
                f.write("Biaxial: " + "sigma= " +
                        str(stress_calcul.sigma_phi_biaxial[i]) + "+/-" +
                        str(stress_calcul.error_sigma_phi_biaxial[i]) + "MPa" +
                        "\n")
                f.write("Biaxial+shear: " + "sigma= " +
                        str(stress_calcul.sigma_phi_biaxial_shear[i]) + "+/-" +
                        str(stress_calcul.error_sigma_phi_biaxial_shear[i]) +
                        "MPa" + "\n")
                f.write("Biaxial+shear: " + "shear= " +
                        str(stress_calcul.shear_phi_biaxial_shear[i]) + "+/-" +
                        str(stress_calcul.error_shear_phi_biaxial_shear[i]) +
                        "MPa" + "\n")
                if len(stress_calcul.liste_phi) >= 3:
                    f.write("Triaxial: " + "sigma= " +
                            str(stress_calcul.sigma_phi_triaxial[i]) + "+/-" +
                            str(stress_calcul.error_sigma_phi_triaxial[i]) +
                            "MPa" + "\n")
                    f.write("Triaxial: " + "shear= " +
                            str(stress_calcul.shear_phi_triaxial[i]) + "+/-" +
                            str(stress_calcul.error_shear_phi_triaxial[i]) +
                            "MPa" + "\n")
            f.write("---------------------------------------------------- \n")
            f.write("---------------------------------------------------- \n")
            f.write("SIN2PSI METHOD\n")
            for i in range(len(stress_calcul.sigma_phi_linear)):
                f.write("----Phi= " + str(stress_calcul.liste_phi[i]) +
                        "(°)----\n")
                f.write("Linear fit: " + "sigma= " +
                        str(stress_calcul.sigma_phi_linear[i]) + "+/-" +
                        str(stress_calcul.error_sigma_phi_linear[i]) + "MPa" +
                        "\n")
                f.write("Elliptic: " + "sigma= " +
                        str(stress_calcul.sigma_phi_elliptic[i]) + "+/-" +
                        str(stress_calcul.error_sigma_phi_elliptic[i]) +
                        "MPa" + "\n")
                f.write("Elliptic: " + "shear= " +
                        str(stress_calcul.shear_phi_elliptic[i]) + "+/-" +
                        str(stress_calcul.error_shear_phi_elliptic[i]) +
                        "MPa" + "\n")

        f.write("---------------------------------------------------- \n")
        f.write("---------------------------------------------------- \n")

        f.write("phi(°)    psi(°)    peak_2theta(°)\n")
        for i in range(len(stress_calcul.phi_stress)):
            progress["value"] = progress["value"] + 1
            progress.update()
            f.write(str("%3.4g" % stress_calcul.phi_stress[i]))
            f.write(str("%10.4g" % stress_calcul.psi_stress[i]))
            f.write(str("%19.4g" % stress_calcul.two_theta_pearson[i]))
            f.write("\n")
        f.close()
        for widget in analyze_1D.Frame1_2.winfo_children():
            widget.destroy()
    run_program.fenetre.mainloop()
コード例 #17
0
class CalibrationDialog(BeeDialog):

    _main_window = None  #: tk.Tk
    _hive = None  #: Hive
    _bar = None  #: Progressbar
    _close_enabled = True

    _button_box = None  #: Frame
    _start_button = None

    _calibration = None

    _humidity = None

    _yes_button = None
    _no_button = None

    _header = None

    _expected_weight_label = None  #: : tk.Label
    _expected_weight_field = None  #: : tk.Entry
    _expected_weight_box = None

    _weight_display = None
    _temp_display = None

    def __init__(self, main_window: tk.Tk, hive: Hive):
        self._main_window = main_window
        self._hive = hive
        super().__init__(parent=main_window,
                         title="Waage kalibrieren",
                         width=310,
                         height=120)

    def _init_expected_weight_box(self):
        self._expected_weight_box = Frame(self)

        self._expected_weight_label = Label(self._expected_weight_box,
                                            text='Gewicht (g)',
                                            font=('Arial', 10),
                                            anchor='e',
                                            wraplength=100,
                                            background='#ffffcc')
        self._expected_weight_label.grid(column=0, row=0, sticky='e')
        self._expected_weight_field = Entry(self._expected_weight_box,
                                            font=('Arial', 8),
                                            width="20")
        self._expected_weight_field.grid(column=1, row=0)

    def open(self):
        pass

    def cancel(self, event=None):
        if self._close_enabled:
            super().cancel(event)

    def body(self, master):
        self._calibration = HiveCalibration()
        self._header = Label(master, text="")
        self._bar = Progressbar(master, length=210)
        self._init_expected_weight_box()
        self._weight_display = Label(master, text="")
        self._temp_display = Label(master, text="")
        self._prepare_tara()

    def _prepare_tara(self):
        self._header.config(
            text='Drücken Sie "Start" um die Waage\n zu tarieren.')
        self._header.pack()

    def _standard_buttons(self):
        self._button_box = Frame(self)
        self._button_box.pack()
        self._start_button = Button(self._button_box,
                                    text="Start",
                                    width=10,
                                    command=self._calc_offset,
                                    default=ACTIVE)
        self._start_button.pack(side=LEFT, padx=5, pady=5)
        w = Button(self._button_box,
                   text="Abbrechen",
                   width=10,
                   command=self.cancel)
        w.pack(side=LEFT, padx=5, pady=5)

    def _yes_no_buttons(self):
        self._yes_no_button_box = Frame(self)

        self._yes_button = Button(self._yes_no_button_box,
                                  text="Ja",
                                  width=10,
                                  command=self._satisfied,
                                  default=ACTIVE)
        self._yes_button.pack(side=LEFT, padx=5, pady=5)
        self._no_button = Button(self._yes_no_button_box,
                                 text="Nein",
                                 width=10,
                                 command=self._not_satisfied)
        self._no_button.pack(side=LEFT, padx=5, pady=5)

    def init_calc_offset(self):
        pass

    def _satisfied(self):
        DbAccess.update_hive_calibration(self._calibration)
        self._close_enabled = True
        self.cancel()

    def _not_satisfied(self):
        self._start_button.config(command=self._calc_offset)
        self._calibration = HiveCalibration()
        self._yes_no_button_box.pack_forget()
        self._temp_display.pack_forget()
        self._weight_display.pack_forget()
        self._prepare_tara()
        self._button_box.pack()
        self.update_idletasks()

    def buttonbox(self):
        self._standard_buttons()
        self._yes_no_buttons()
        '''add standard button box.

        override if you do not want the standard buttons
        '''
        '''
        w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE)
        w.pack(side=LEFT, padx=5, pady=5)
        w = Button(box, text="Cancel", width=10, command=self.cancel)
        w.pack(side=LEFT, padx=5, pady=5)

        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.cancel)
        '''

    def _progress(self, i, maximum=15):
        self._bar['value'] = int(210 / (maximum - i))
        self.update_idletasks()

    def _calc_reference_unit(self, event=None):
        expected_weight_string = self._expected_weight_field.get()
        print('calc-reference-unit.expected_weight_string: ',
              expected_weight_string)
        expected = int(expected_weight_string)
        print('calc-reference-unit.expected: ', expected)
        self._calibration.entity_id = self._hive.get_id()
        self._humidity = None
        self._bar['value'] = 0
        self._bar.pack()
        self.update_idletasks()
        try:
            self._close_enabled = False
            self._button_box.pack_forget()
            self._close_enabled = False
            self._bar.pack()
            self.update_idletasks()

            pins = self._hive.get_weight().get_bcm().split(",")
            data_pin = pins[0]
            clk_pin = pins[1]

            print('data_pin ' + data_pin)
            print('clk_pin ' + clk_pin)

            hx = HX711(int(data_pin), int(clk_pin), gain=128)
            hx.set_reading_format("LSB", "MSB")
            print('_offset:', self._calibration.offset)
            hx.set_offset(self._calibration.offset)
            self._calibration.value_per_gram = hx.calc_reference_unit(
                lambda i: self._progress(i, 10), expected)
            print('reference_unit -> ', self._calibration.value_per_gram)
            self._calc_temp()
            clean()
            self._start_button.config(command=self._check_weight)
            self._header.config(
                text='Drücken Sie Start um das Gewicht\nzu überprüfen.')
            self._button_box.pack()
            self._bar.pack_forget()
            self._expected_weight_box.pack_forget()
            self._weight_display.pack()
            self._temp_display.pack()
            self.update_idletasks()
            self._close_enabled = True
        except Exception as e:
            print('Error ', e)
            clean()
            self._calibration.offset = None
            self._close_enabled = True

    def _calc_temp(self):
        temp_sensor = self._hive.get_temperature_outside()

        if temp_sensor.get_bcm() == '' or temp_sensor.get_product() == '':
            return

        if temp_sensor.get_product() == 'DHT22':
            self._humidity, self._calibration.temp = dht.read_retry(
                dht.DHT22, int(temp_sensor.get_bcm()))
            print('Temp={0:0.1f}*C  Humidity={1:0.1f}%'.format(
                self._calibration.temp, self._humidity))
        elif temp_sensor.get_product() == 'DHT11':
            self._humidity, self._temp = dht.read_retry(
                dht.DHT11, int(temp_sensor.get_bcm()))
            print('Temp={0:0.1f}*C  Humidity={1:0.1f}%'.format(
                self._calibration.temp, self._humidity))
        else:
            print('Unsupported product ', temp_sensor.get_product())

    def _check_weight(self):
        try:
            self._close_enabled = False
            pins = self._hive.get_weight().get_bcm().split(",")
            data_pin = pins[0]
            clk_pin = pins[1]
            hx = HX711(int(data_pin), int(clk_pin), gain=128)
            hx.set_reading_format("LSB", "MSB")
            print('_reference_unit:', self._calibration.value_per_gram)
            hx.set_reference_unit(self._calibration.value_per_gram)
            hx.reset()
            print('_offset:', self._calibration.offset)
            hx.set_offset(self._calibration.offset)
            val = hx.get_weight(5)
            print('value -> ', val)
            self._header.config(text='Sind Sie mit dem Ergebnis\nzufrieden?')
            self._weight_display.config(
                text=('Gewicht: {0:0.1f}g'.format(val)))
            if self._calibration.temp is not None:
                self._temp_display.config(
                    text=('Temp: {0:0.1f}°C'.format(self._calibration.temp)))
            else:
                self._temp_display.config(text='')

            print('reference_unit -> ', self._calibration.value_per_gram)
            clean()
            self._button_box.pack_forget()
            self._yes_no_button_box.pack()
            self.update_idletasks()
            self._close_enabled = True
        except Exception as e:
            print('Error ', e)
            clean()
            self._calibration.offset = None
            self._close_enabled = True

    def _calc_offset(self, event=None):
        self._calibration.offset = None
        try:
            self._button_box.pack_forget()
            self._close_enabled = False
            self._bar.pack()
            self.update_idletasks()

            pins = self._hive.get_weight().get_bcm().split(",")
            data_pin = pins[0]
            clk_pin = pins[1]

            print('data_pin ' + data_pin)
            print('clk_pin ' + clk_pin)

            hx = HX711(int(data_pin), int(clk_pin), gain=128)
            hx.set_reading_format("LSB", "MSB")
            self._calibration.offset = hx.calc_offset(
                lambda i: self._progress(i))
            print('offset -> ', self._calibration.offset)
            clean()
            self._start_button.config(command=self._calc_reference_unit)
            self._header.config(text='Geben Sie ein Gewicht auf die Waage.')
            self._expected_weight_box.pack()
            self._button_box.pack()
            self._bar.pack_forget()

            self.update_idletasks()
        except Exception as e:
            print('Fehler', e)
            clean()
            self._close_enabled = True
            self._calibration.offset = None
コード例 #18
0
class Application(tk.Frame):
    load_model_btn: Button
    save_model_btn: Button
    image: Union[Label, Label]
    name: str
    acc: Union[Label, Label]
    loss: Union[Label, Label]
    current_epochs: Union[Label, Label]
    open_dialog_btn: Union[Button, Button]
    predict_frame: Union[Frame, Frame]
    train_epochs: Union[Entry, Entry]
    train_frame: Union[Frame, Frame]
    predict_btn: Button
    train_btn: Button
    progress_bar: Progressbar
    info_label: Union[Label, Label]
    num_images: Union[Label, Label]
    num_categories: Union[Label, Label]
    info_frame: Union[Frame, Frame]
    display: Text
    download_image_btn: Button
    left_frame: Frame

    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.classifier = Classifier()

        self.left_frame = Frame(master, style="My.TFrame")
        self.left_frame.pack(
            side=LEFT,
            fill=BOTH,
        )

        # Separator(master, orient=VERTICAL).grid(column=1, row=0, sticky='ns')

        self.right_frame = Frame(master)
        self.right_frame.pack(side=RIGHT, fill=BOTH, padx=10)

        self.create_left()
        self.create_right()

    def create_left(self):
        self.create_download_frame()
        self.create_train_frame()
        self.create_predict_frame()
        self.create_info_frame()

    def create_info_frame(self):
        self.info_frame = Frame(self.left_frame)
        self.info_frame.pack()

        info_num_categories = Label(self.info_frame,
                                    text="Number of categories:")
        info_num_categories.grid(column=0, row=0, sticky=W)
        self.num_categories = Label(self.info_frame,
                                    text=self.classifier.num_categories)
        self.num_categories.grid(column=1, row=0)

        info_num_images = Label(self.info_frame, text="Number of images:")
        info_num_images.grid(column=0, row=1, sticky=W)
        self.num_images = Label(self.info_frame,
                                text=len(self.classifier.image_paths))
        self.num_images.grid(column=1, row=1)

        # ==== Training ====
        label = Label(self.info_frame, text="Epochs:")
        label.grid(column=0, row=2, sticky=W)
        self.current_epochs = Label(self.info_frame, text=0)
        self.current_epochs.grid(column=1, row=2)

        label = Label(self.info_frame, text="Acc:")
        label.grid(column=0, row=3, sticky=W)
        self.acc = Label(self.info_frame, text=0)
        self.acc.grid(column=1, row=3)

        label = Label(self.info_frame, text="Loss:")
        label.grid(column=0, row=4, sticky=W)
        self.loss = Label(self.info_frame, text=0)
        self.loss.grid(column=1, row=4)

        Separator(self.info_frame).grid(row=5, sticky="ew", padx=4)

        self.info_label = Label(self.left_frame)
        self.info_label.pack(fill=X)
        self.progress_bar = Progressbar(self.left_frame,
                                        length=200,
                                        mode="determinate",
                                        orient=HORIZONTAL)
        self.progress_bar.pack(fill=X)
        self.image = Label(self.left_frame)
        self.image.pack(fill=X)

    def create_download_frame(self):
        self.winfo_toplevel().title("Trainer")
        self.download_image_btn = tk.Button(self.left_frame,
                                            text="Download Images",
                                            command=self.download)
        self.download_image_btn.pack(fill=X, pady=(20, 10))
        self.save_model_btn = tk.Button(self.left_frame,
                                        text="Save Model",
                                        command=self.save,
                                        state=DISABLED)
        self.save_model_btn.pack(fill=X, pady=(20, 10))
        self.load_model_btn = tk.Button(self.left_frame,
                                        text="Load Model",
                                        command=self.load)
        self.load_model_btn.pack(fill=X, pady=(20, 10))

    def create_predict_frame(self):
        self.predict_frame = Frame(self.left_frame)
        self.predict_frame.pack(fill=X, pady=(20, 10))
        self.open_dialog_btn = Button(self.predict_frame,
                                      text="Open File",
                                      command=self.openfile,
                                      state=DISABLED)
        self.open_dialog_btn.grid(column=0, row=0)
        self.predict_btn = tk.Button(self.predict_frame,
                                     text="Predict",
                                     command=self.predict,
                                     state=DISABLED)
        self.predict_btn.grid(column=1,
                              row=0,
                              padx=5,
                              sticky='ew',
                              columnspan=2)

    def create_train_frame(self):
        self.train_frame = Frame(self.left_frame)
        self.train_frame.pack(fill=X, pady=(20, 10))
        label = Label(self.train_frame, text="Epochs:")
        label.grid(column=1, row=0)
        self.train_epochs = Entry(self.train_frame, width=6)
        self.train_epochs.grid(column=2, row=0)
        self.train_btn = tk.Button(self.train_frame,
                                   text="Train",
                                   command=self.train,
                                   state=DISABLED)
        self.train_btn.grid(column=3, row=0, columnspan=2, padx=5)

    def create_right(self):
        self.display = tk.Text(self.right_frame)
        self.display.pack(expand=True, fill=BOTH)

    def openfile(self):
        name = askopenfilename(filetypes=(("JPG File", "*.jpg"), ("PNG File",
                                                                  "*.png"),
                                          ("BMP File", "*.bmp"), ("All Files",
                                                                  "*.*")),
                               title="Choose a file.")
        if name and self.classifier.model:
            self.predict_btn.config(state=ACTIVE)
            self.name = name

    def download(self):
        t = threading.Thread(target=self.classifier.load_images,
                             args=(self.download_callback, ))
        t.start()

    def predict(self):
        t = threading.Thread(target=self.classifier.predict,
                             args=(
                                 self.name,
                                 self.predict_callback,
                             ))
        t.start()

    def train(self):
        epoch = self.train_epochs.get()
        if epoch is not None and epoch != "":
            for e in epoch:
                if e not in "0123456789":
                    raise ValueError("Value error")
            t = threading.Thread(target=self.classifier.train,
                                 args=(int(epoch), self.train_callback))
            t.start()
            self.train_btn.config(state=DISABLED)
        else:
            self.display.insert(END, "Epoch value error\n")

    def save(self):
        self.classifier.save()
        self.display.insert(END, "Model has been saved\n")

    def load(self):
        self.classifier.load()
        self.display.insert(END, "Model has been loaded\n")

    def train_callback(self,
                       state: str,
                       epoch: int = 0,
                       loss: float = 0,
                       acc: float = 0):
        if state == "start":
            self.display.insert(END, "Start training\n")
            self.info_label.config(text="Start training")

        elif state == "progress":
            total_epoch = int(self.train_epochs.get())
            progress = ((epoch + 1) / total_epoch) * 100
            self.progress_bar['value'] = progress
            self.current_epochs.config(text=epoch + 1)
            self.acc.config(text='{:.2f}%'.format(100 * acc))
            self.loss.config(text=round(loss, 3))
            self.display.insert(END, f"Started training on epoch {epoch}\n")

        elif state == "end":
            self.display.insert(END, "Finished training\n")
            self.info_label.config(text="Finished training")
            self.train_btn.config(state=ACTIVE)
            self.save_model_btn.config(state=ACTIVE)
            self.open_dialog_btn.config(state=ACTIVE)

    def predict_callback(self, data: dict):
        self.display.insert(END, "=====================\n")
        print(self.name)
        image1 = Image.open(self.name)
        image1.thumbnail((200, 200), Image.ANTIALIAS)
        photo_img = ImageTk.PhotoImage(image1)
        self.image.config(image=photo_img)
        self.image.image = photo_img
        self.display.insert(
            END,
            f"Prediction: {data['id']} {data['name']} {round(100 * data['acc'], 4)} %\n",
            ('important', ))
        self.display.insert(END, "=====================\n")

    def download_callback(self, label, num_completed, total):
        self.info_label.config(text=f"Processing {label}")
        progress = ((num_completed + 1) / total) * 100
        self.progress_bar['value'] = progress
        if progress == 100:
            self.display.insert(END, f"{label} finished\n")
            self.info_label.config(text=f"{label} finished")
            self.train_btn.config(state=ACTIVE)
コード例 #19
0
class import_XRD:
    def __init__(self, main):
        try:
            self.process(main)
        except Exception as e:
            showinfo(title="Warning",
                     message=str(e) + "\n" + "\n" +
                     str(traceback.format_exc()))
            return

        main.root.mainloop()

    def process(self, main):
        format_ = '*.uxd;*.nja;*.raw;*.Profile;*.txt;*.UXD;*.NJA;*.RAW;*.PROFILE;*TXT'
        f = askopenfilenames(parent=main.root,
                             title="Open file",
                             filetypes=[('all supported format', format_),
                                        ('all files', '.*')])
        self.file_link = main.root.tk.splitlist(f)
        if len(self.file_link) > 0:
            self.import_file(main)
            if len(self.data_y) > 0:
                self.progress["value"] = self.progress["value"] + 1
                self.progress.update()
                self.destroy_widget(main)
                self.graphic_frame3_1(main)
                #----------------------
                self.progress["value"] = self.progress["value"] + 1
                self.progress.update()
                self.attribute_graphic_frame3_2(main)
                #----------------------
                self.progress["value"] = self.progress["value"] + 1
                self.progress.update()
                self.attribute_graphic_frame3_3(main)
                #----------------------
                for widget in main.Frame1_2.winfo_children():
                    widget.destroy()
                pack_Frame_1D(main, 1)
            else:
                showinfo(title="Warning", message="The scan is empty")

    def import_file(self, main):
        for widget in main.Frame1_2.winfo_children():
            widget.destroy()
        Label(main.Frame1_2, text="Import files").pack(side=LEFT)
        self.progress = Progressbar(main.Frame1_2,
                                    orient="horizontal",
                                    mode='determinate')
        self.progress.pack()
        self.progress["value"] = 0
        self.progress["maximum"] = len(self.file_link) + 3

        self.filename = []
        self.phi = []
        self.chi = []
        self.omega = []
        self.twotheta = []
        self.data_x = []
        self.data_y = []
        self.k_alpha = []
        self.file_info = []
        self.range_info = []

        for i in range(len(self.file_link)):
            self.progress["value"] = self.progress["value"] + 1
            self.progress.update()

            f = self.file_link[i].split("/")
            self.filename.append(f[len(f) - 1])

            read_scan_1D(self.file_link[i], self)

    def destroy_widget(self, main):
        for widget in main.Frame3_1_1.winfo_children():
            widget.destroy()
        for widget in main.Frame3_1_2.winfo_children():
            widget.destroy()
        for widget in main.Frame3_1_3.winfo_children():
            widget.destroy()
        for widget in main.Frame3_1_4.winfo_children():
            widget.destroy()

        for widget in main.Frame3_2_1.winfo_children():
            widget.destroy()
        for widget in main.Frame3_2_3.winfo_children():
            widget.destroy()

        for widget in main.Frame3_3_4.winfo_children():
            widget.destroy()

        for widget in main.Frame3_4_1.winfo_children():
            widget.destroy()
        for widget in main.Frame3_4_2_1.winfo_children():
            widget.destroy()
        for widget in main.Frame3_4_2_2.winfo_children():
            widget.destroy()
        for widget in main.Frame3_4_3_1.winfo_children():
            widget.destroy()
        for widget in main.Frame3_4_3_2.winfo_children():
            widget.destroy()
        for widget in main.Frame3_4_3_3.winfo_children():
            widget.destroy()

        for widget in main.Frame3_5_1.winfo_children():
            widget.destroy()
        for widget in main.Frame3_5_2_1.winfo_children():
            widget.destroy()
        for widget in main.Frame3_5_2_2.winfo_children():
            widget.destroy()
        for widget in main.Frame3_5_2_3.winfo_children():
            widget.destroy()
        for widget in main.Frame3_5_3_1.winfo_children():
            widget.destroy()
        for widget in main.Frame3_5_3_2.winfo_children():
            widget.destroy()
        for widget in main.Frame3_5_3_3.winfo_children():
            widget.destroy()

        for widget in main.Frame3_6_1.winfo_children():
            widget.destroy()
        for widget in main.Frame3_6_2.winfo_children():
            widget.destroy()
        for widget in main.Frame3_6_3.winfo_children():
            widget.destroy()
        for widget in main.Frame3_7_1.winfo_children():
            widget.destroy()
        for widget in main.Frame3_7_2.winfo_children():
            widget.destroy()

    def graphic_frame3_1(self, main):
        scrollbar = Scrollbar(main.Frame3_1_1)
        scrollbar.pack(side=RIGHT, fill=BOTH)
        mylist = Listbox(main.Frame3_1_1, yscrollcommand=scrollbar.set)
        mylist.insert(END, "0.All original graphs")
        for i in range(len(self.phi)):
            mylist.insert(
                END,
                str(i + 1) + u".\u03C6=" + str(float(self.phi[i])) +
                u"; \u03C7=" + str(float(self.chi[i])) + u"; \u03C9=" +
                str(float(self.omega[i])))
        mylist.pack(side=LEFT, fill=BOTH, expand=YES)
        mylist.bind("<ButtonRelease-1>",
                    lambda event: show_original_graph(event, self, main))
        scrollbar.config(command=mylist.yview)

        f = plt.figure(1, facecolor="0.94")
        for i in range(len(self.phi)):
            plt.plot(self.data_x[i], self.data_y[i], label=str(i + 1))
        plt.xlabel(r"$2\theta$" + '°')
        plt.ylabel("Intensity")
        plt.title("All original graph")
        plt.legend(loc='upper left',
                   bbox_to_anchor=(-0.1, -0.2, 1.2, 0),
                   ncol=10,
                   mode="expand",
                   borderaxespad=0.)
        plt.subplots_adjust(bottom=0.4)
        plt.close()
        canvas = FigureCanvasTkAgg(f, main.Frame3_1_2)
        canvas.get_tk_widget().pack(fill=BOTH, expand=YES)

        canvas = FigureCanvasTkAgg(f, main.Frame3_2_3)
        canvas.get_tk_widget().pack(fill=BOTH, expand=YES)

        fig_style(self, main.Frame3_1_3)

        Button(main.Frame3_1_4,
               text='Export all as image',
               bg="white",
               command=lambda: export_all_original_graph(self, main)).grid(
                   row=1, column=0, sticky=W)

    def graphic_frame3_2(self, main):
        #self.angles_modif_valid=False
        Label(main.Frame3_2_2_1, text="ANGLES MODIFICATION",
              bg="white").grid(row=0, column=0, sticky=W)
        Label(main.Frame3_2_2_1, text=u"PHI \u03C6").grid(row=1,
                                                          column=0,
                                                          sticky=W)
        Label(main.Frame3_2_2_1, text="offset (°)").grid(row=1,
                                                         column=1,
                                                         sticky=W)

        Label(main.Frame3_2_2_1, text=u"CHI \u03C7").grid(row=2,
                                                          column=0,
                                                          sticky=W)
        Label(main.Frame3_2_2_1, text="offset (°)").grid(row=2,
                                                         column=1,
                                                         sticky=W)

        Label(main.Frame3_2_2_1, text=u"2 THETA 2\u03B8").grid(row=3,
                                                               column=0,
                                                               sticky=W)
        Label(main.Frame3_2_2_1, text="offset (°)").grid(row=3,
                                                         column=1,
                                                         sticky=W)

        Label(main.Frame3_2_2_1, text=u"OMEGA \u03C9").grid(row=4,
                                                            column=0,
                                                            sticky=W)
        Label(main.Frame3_2_2_1, text="offset (°)").grid(row=4,
                                                         column=1,
                                                         sticky=W)

        self.phi_invert = IntVar()
        Checkbutton(main.Frame3_2_2_1, text="Invert",
                    variable=self.phi_invert).grid(row=1, column=3, sticky=W)
        self.chi_invert = IntVar()
        Checkbutton(main.Frame3_2_2_1, text="Invert",
                    variable=self.chi_invert).grid(row=2, column=3, sticky=W)

        self.Entry_phi_offset = Entry(main.Frame3_2_2_1)
        self.Entry_chi_offset = Entry(main.Frame3_2_2_1)
        self.Entry_twotheta_offset = Entry(main.Frame3_2_2_1)
        self.Entry_omega_offset = Entry(main.Frame3_2_2_1)

        self.Entry_phi_offset.grid(row=1, column=2, sticky=W)
        self.Entry_chi_offset.grid(row=2, column=2, sticky=W)
        self.Entry_twotheta_offset.grid(row=3, column=2, sticky=W)
        self.Entry_omega_offset.grid(row=4, column=2, sticky=W)

        self.Entry_phi_offset.insert(0, "0")
        self.Entry_chi_offset.insert(0, "0")
        self.Entry_twotheta_offset.insert(0, "0")
        self.Entry_omega_offset.insert(0, "0")

        self.button_apply = Button(main.Frame3_2_2_1,
                                   compound=CENTER,
                                   text="Apply",
                                   bg="white",
                                   command=None)
        self.button_apply.grid(row=5, column=0, sticky=W)
        self.button_init = Button(main.Frame3_2_2_1,
                                  compound=CENTER,
                                  text="Initialize",
                                  bg="white",
                                  command=None)
        self.button_init.grid(row=6, column=0, sticky=W)
        self.button_advance = Button(main.Frame3_2_2_1,
                                     compound=CENTER,
                                     text="Advance",
                                     bg="white",
                                     command=None)
        self.button_advance.grid(row=7, column=0, sticky=W)

    def attribute_graphic_frame3_2(self, main):
        scrollbar = Scrollbar(main.Frame3_2_1)
        scrollbar.pack(side=RIGHT, fill=BOTH, expand=YES)
        mylist = Listbox(main.Frame3_2_1, yscrollcommand=scrollbar.set)
        for i in range(len(self.phi)):
            mylist.insert(
                END,
                str(i + 1) + u".\u03C6=" + str(float(self.phi[i])) +
                u"; \u03C7=" + str(float(self.chi[i])) + u"; \u03C9=" +
                str(float(self.omega[i])))
        mylist.pack(side=LEFT, fill=BOTH, expand=YES)
        scrollbar.config(command=mylist.yview)

        self.angles_modif_valid = False

        self.button_apply.config(
            command=lambda: angles_modif.apply(angles_modif, self, main))
        self.button_init.config(
            command=lambda: angles_modif.init(angles_modif, self, main))
        self.button_advance.config(
            command=lambda: angles_modif.advance(angles_modif, self, main))

    def graphic_frame3_3(self, main):
        #background limit
        f = font.Font(size=9, underline=1)

        i = 0
        Label(main.Frame3_3_1, text="BACKGROUND", bg="white").grid(row=i,
                                                                   column=0,
                                                                   sticky=W)
        Label(main.Frame3_3_1, text=u"2\u03B8 from(°)").grid(row=i,
                                                             column=1,
                                                             sticky=W)
        Label(main.Frame3_3_1, text=u"2\u03B8 to(°)").grid(row=i,
                                                           column=2,
                                                           sticky=W)

        Label(main.Frame3_3_1, text="range 1,2,...").grid(row=i + 1,
                                                          column=0,
                                                          sticky=W)
        self.Entry_background_from = Entry(main.Frame3_3_1, width=10)
        self.Entry_background_from.grid(row=i + 1, column=1, sticky=W)
        #self.Entry_background_from.delete(0,END)
        #self.Entry_background_from.insert(0,str(int(self.data_x[0][0])+1)+','+str(int(self.data_x[0][len(self.data_x[0])-1])-2))

        self.Entry_background_to = Entry(main.Frame3_3_1, width=10)
        self.Entry_background_to.grid(row=i + 1, column=2, sticky=W)
        #self.Entry_background_to.delete(0,END)
        #self.Entry_background_to.insert(0,str(int(self.data_x[0][0])+2)+','+str(int(self.data_x[0][len(self.data_x[0])-1])-1))

        Label(main.Frame3_3_1, text="Polynomial fit").grid(row=i + 2,
                                                           column=0,
                                                           sticky=W)
        Label(main.Frame3_3_1, text="degrees").grid(row=i + 2,
                                                    column=2,
                                                    sticky=W)
        self.Entry_background_polynominal_degrees = Entry(main.Frame3_3_1,
                                                          width=10)
        self.Entry_background_polynominal_degrees.grid(row=i + 2,
                                                       column=1,
                                                       sticky=W)
        self.Entry_background_polynominal_degrees.delete(0, END)
        #self.Entry_background_polynominal_degrees.insert(0,str(1))

        #fitting limits
        i = i + 3
        Label(main.Frame3_3_1, text="--------------------").grid(row=i,
                                                                 column=0,
                                                                 sticky=W)
        Label(main.Frame3_3_1, text="FITTING RANGE",
              bg="white").grid(row=i + 1, column=0, sticky=W)
        Label(main.Frame3_3_1, text=u"2\u03B8").grid(row=i + 1,
                                                     column=1,
                                                     sticky=W)
        Label(main.Frame3_3_1, text="from(°)").grid(row=i + 2,
                                                    column=0,
                                                    sticky=W)
        Label(main.Frame3_3_1, text="to(°)").grid(row=i + 3,
                                                  column=0,
                                                  sticky=W)
        self.Entry_twotheta_from = Entry(main.Frame3_3_1, width=10)
        self.Entry_twotheta_to = Entry(main.Frame3_3_1, width=10)
        self.Entry_twotheta_from.grid(row=i + 2, column=1, sticky=W)
        self.Entry_twotheta_to.grid(row=i + 3, column=1, sticky=W)

        self.Entry_twotheta_from.delete(0, END)
        self.Entry_twotheta_to.delete(0, END)
        #self.Entry_twotheta_from.insert(0,str('%0.2f' % self.data_x[0][0]))
        #self.Entry_twotheta_to.insert(0,str('%0.2f' % self.data_x[0][len(self.data_x[0])-1]))

        #peak option
        i = i + 4
        Label(main.Frame3_3_1, text="--------------------").grid(row=i,
                                                                 column=0,
                                                                 sticky=W)
        Label(main.Frame3_3_1, text="PEAK FIT MODEL",
              bg="white").grid(row=i + 1, column=0, sticky=W)
        Label(main.Frame3_3_1, text="Function", font=f).grid(row=i + 2,
                                                             column=0,
                                                             sticky=W)
        self.function_fit = IntVar()
        Radiobutton(main.Frame3_3_1,
                    text="Pearson_VII",
                    variable=self.function_fit,
                    value=1).grid(row=i + 3, column=0, sticky=W)
        Radiobutton(main.Frame3_3_1,
                    text="Pseudo-Voigt",
                    variable=self.function_fit,
                    value=2).grid(row=i + 4, column=0, sticky=W)
        Radiobutton(main.Frame3_3_1,
                    text="Voigt",
                    variable=self.function_fit,
                    value=3).grid(row=i + 5, column=0, sticky=W)
        Radiobutton(main.Frame3_3_1,
                    text="Gaussian",
                    variable=self.function_fit,
                    value=4).grid(row=i + 6, column=0, sticky=W)
        Radiobutton(main.Frame3_3_1,
                    text="Lorentzian",
                    variable=self.function_fit,
                    value=5).grid(row=i + 7, column=0, sticky=W)
        self.function_fit.set(1)

        Label(main.Frame3_3_1, text="Peak shape", font=f).grid(row=i + 2,
                                                               column=1,
                                                               sticky=W)
        self.peak_shape = IntVar()
        Radiobutton(main.Frame3_3_1,
                    text="Symmetric",
                    variable=self.peak_shape,
                    value=1).grid(row=i + 3, column=1, sticky=W)
        Radiobutton(main.Frame3_3_1,
                    text="Asymmetric",
                    variable=self.peak_shape,
                    value=2).grid(row=i + 4, column=1, sticky=W)
        self.peak_shape.set(1)

        Label(main.Frame3_3_1, text="Peak rejection", font=f).grid(row=i + 5,
                                                                   column=1,
                                                                   sticky=W)
        Label(main.Frame3_3_1, text="Correlation r >").grid(row=i + 6,
                                                            column=1,
                                                            sticky=W)
        self.Entry_r = Entry(main.Frame3_3_1, width=10)
        self.Entry_r.grid(row=i + 6, column=2, sticky=W)
        #self.Entry_r.insert(0,0.5)

        i = i + 8
        Label(main.Frame3_3_1, text="Initial guess", font=f).grid(row=i,
                                                                  column=0,
                                                                  sticky=W)
        self.init_guess = IntVar()
        Radiobutton(main.Frame3_3_1,
                    text="Auto",
                    variable=self.init_guess,
                    value=1).grid(row=i, column=1, sticky=W)
        Radiobutton(main.Frame3_3_1,
                    text="Fix",
                    variable=self.init_guess,
                    value=2).grid(row=i, column=2, sticky=W)
        self.init_guess.set(1)

        Label(main.Frame3_3_1, text=u"2\u03B8(°)").grid(row=i + 1,
                                                        column=1,
                                                        sticky=W)
        Label(main.Frame3_3_1, text="FWHM(°)").grid(row=i + 1,
                                                    column=2,
                                                    sticky=W)

        self.Entry_peak = []
        self.Entry_limit_peak = []
        self.Entry_peak_width = []

        Label(main.Frame3_3_1, text="1 - stress").grid(row=i + 2,
                                                       column=0,
                                                       sticky=W)
        Label(main.Frame3_3_1, text=u"\u00B1(°)").grid(row=i + 3,
                                                       column=0,
                                                       sticky=W)

        self.Entry_peak.append(Entry(main.Frame3_3_1, width=10))
        self.Entry_limit_peak.append(Entry(main.Frame3_3_1, width=10))
        self.Entry_peak_width.append(Entry(main.Frame3_3_1, width=10))

        self.Entry_peak[0].grid(row=i + 2, column=1, sticky=W)
        self.Entry_limit_peak[0].grid(row=i + 3, column=1, sticky=W)
        self.Entry_peak_width[0].grid(row=i + 2, column=2, sticky=W)

        #self.Entry_limit_peak[0].insert(0,2)

        self.row_i = i + 4
        self.number_peak = 1

        self.Label_1 = []
        self.Label_2 = []
        self.Label_3 = []
        self.add_peak = Button(main.Frame3_3_1,
                               compound=CENTER,
                               text="Add",
                               bg="white",
                               command=lambda: add_peak(self, main.Frame3_3_1))
        self.add_peak.grid(row=self.row_i, column=0, sticky=W)

        self.delete_peak = Button(
            main.Frame3_3_1,
            compound=CENTER,
            text="Delete",
            bg="white",
            command=lambda: delete_peak(self, main.Frame3_3_1))

        #Material propreties--------------
        Label(main.Frame3_3_2, text="MATERIAL PROPERTIES",
              bg="white").grid(row=0, column=0, sticky=W)
        Label(main.Frame3_3_2, text="Material").grid(row=1, column=0, sticky=W)
        Label(main.Frame3_3_2, text=u"Source").grid(row=2, column=0, sticky=W)
        Label(main.Frame3_3_2, text=u"{hkl} 2\u03B8(°)").grid(row=3,
                                                              column=0,
                                                              sticky=W)
        Label(main.Frame3_3_2, text=u"Unstressed 2\u03B8(°) ").grid(row=4,
                                                                    column=0,
                                                                    sticky=W)
        Label(main.Frame3_3_2, text=u"s\u2081(MPa\u207B\u00B9)").grid(row=5,
                                                                      column=0,
                                                                      sticky=W)
        Label(main.Frame3_3_2,
              text=u"s\u2082/2(MPa\u207B\u00B9)").grid(row=6,
                                                       column=0,
                                                       sticky=W)
        Label(main.Frame3_3_2, text="Young's modulus(MPa)").grid(row=7,
                                                                 column=0,
                                                                 sticky=W)
        Label(main.Frame3_3_2, text="Poisson's ratio").grid(row=8,
                                                            column=0,
                                                            sticky=W)

        self.Entry_twotheta0 = Entry(main.Frame3_3_2, width=10)
        self.Entry_s1 = Entry(main.Frame3_3_2, width=10)
        self.Entry_half_s2 = Entry(main.Frame3_3_2, width=10)
        self.Entry_Young = Entry(main.Frame3_3_2, width=10)
        self.Entry_Poisson = Entry(main.Frame3_3_2, width=10)

        self.Entry_twotheta0.grid(row=4, column=1, sticky=W)
        self.Entry_s1.grid(row=5, column=1, sticky=W)
        self.Entry_half_s2.grid(row=6, column=1, sticky=W)
        self.Entry_Young.grid(row=7, column=1, sticky=W)
        self.Entry_Poisson.grid(row=8, column=1, sticky=W)

        import_material(self, main.Frame3_3_2)

        i = 9
        Label(main.Frame3_3_2, text="--------------------").grid(row=i,
                                                                 column=0,
                                                                 sticky=W)
        Label(main.Frame3_3_2, text="X-RAYS PROPETIES",
              bg="white").grid(row=i + 1, column=0, sticky=W)
        Label(main.Frame3_3_2,
              text=u"\u03BB" + "(" + u"\u212B" + ")" + " k" + u"\u03B1" +
              "1").grid(row=i + 2, column=0, sticky=W)
        Label(main.Frame3_3_2,
              text=u"\u03BB" + "(" + u"\u212B" + ")" + " k" + u"\u03B1" +
              "2").grid(row=i + 3, column=0, sticky=W)
        Label(main.Frame3_3_2, text="k" + u"\u03B1" + " ratio").grid(row=i + 4,
                                                                     column=0,
                                                                     sticky=W)

        self.Entry_kalpha = []
        for j in range(3):
            self.Entry_kalpha.append(Entry(main.Frame3_3_2, width=10))
            self.Entry_kalpha[j].grid(row=i + 2 + j, column=1, sticky=W)

            self.Entry_kalpha[j].delete(0, END)
            #if len(self.k_alpha)>j:
            #self.Entry_kalpha[j].insert(0,str(self.k_alpha[j]))
        #if len(self.k_alpha)==1:
        #self.Entry_kalpha[1].insert(0,str(0))
        #self.Entry_kalpha[2].insert(0,str(0))
        #if len(self.k_alpha)==2:
        #self.Entry_kalpha[2].insert(0,str(0.5))

        #for j in range(2):
        #self.Entry_kalpha[j].config(state='disabled')

        self.button_init_wavelength = Button(main.Frame3_3_2,
                                             compound=CENTER,
                                             text="Initialize",
                                             bg="white",
                                             command=None)
        self.button_init_wavelength.grid(row=i + 5, column=1, sticky=W)
        Button(main.Frame3_3_2,
               compound=CENTER,
               text="Lock",
               bg="white",
               command=lambda: self.x_ray_lock(self)).grid(row=i + 2,
                                                           column=2,
                                                           sticky=W)
        Button(main.Frame3_3_2,
               compound=CENTER,
               text="Unlock",
               bg="white",
               command=lambda: self.x_ray_unlock(self)).grid(row=i + 3,
                                                             column=2,
                                                             sticky=W)

        i = i + 6
        Label(main.Frame3_3_2, text="--------------------").grid(row=i,
                                                                 column=0,
                                                                 sticky=W)
        self.peak_shift_correction_coefficient = []
        self.i = i
        self.Label_sc = Label(main.Frame3_3_2)
        self.Button_delete = Button(main.Frame3_3_2)
        self.button_psc = Button(main.Frame3_3_2,
                                 compound=CENTER,
                                 text="Peak shift correction",
                                 bg="white",
                                 command=None)
        self.button_psc.grid(row=i + 1, column=0, sticky=W)

        #tools
        Button(main.Frame3_3_3,
               compound=CENTER,
               text="Import template",
               bg="white",
               command=lambda: import_calcul_parameters(self, main)).grid(
                   row=0, column=0)
        Button(main.Frame3_3_3,
               compound=CENTER,
               text="Export template",
               bg="white",
               command=lambda: export_calcul_parameters(self, main)).grid(
                   row=1, column=0)
        Label(main.Frame3_3_3, text="--------------------").grid(row=2,
                                                                 column=0)
        self.Button_limit_preview = Button(main.Frame3_3_3,
                                           compound=CENTER,
                                           text="Limits preview",
                                           bg="white",
                                           command=None)
        self.Button_limit_preview.grid(row=3, column=0)
        self.Button_fit_preview = Button(main.Frame3_3_3,
                                         compound=CENTER,
                                         text="Fit preview",
                                         bg="white",
                                         command=None)
        self.Button_fit_preview.grid(row=4, column=0)
        Label(main.Frame3_3_3, text="--------------------").grid(row=5,
                                                                 column=0)
        self.Button_run_calcul = Button(main.Frame3_3_3,
                                        compound=CENTER,
                                        text="RUN CALCULATION",
                                        bg="white",
                                        command=None)
        self.Button_run_calcul.grid(row=6, column=0)
        #----------------------------
        f = plt.figure(1, facecolor="0.94")
        plt.close(f)
        canvas = FigureCanvasTkAgg(f, main.Frame3_3_4)
        canvas.get_tk_widget().pack(fill=BOTH, expand=YES)

    def attribute_graphic_frame3_3(self, main):
        if self.Entry_background_from.get() in ['', None, '\n']:
            self.Entry_background_from.insert(
                0,
                str(int(self.data_x[0][0]) + 1) + ',' +
                str(int(self.data_x[0][len(self.data_x[0]) - 1]) - 2))

        if self.Entry_background_to.get() in ['', None, '\n']:
            self.Entry_background_to.insert(
                0,
                str(int(self.data_x[0][0]) + 2) + ',' +
                str(int(self.data_x[0][len(self.data_x[0]) - 1]) - 1))

        if self.Entry_background_polynominal_degrees.get() in ['', None, '\n']:
            self.Entry_background_polynominal_degrees.insert(0, str(1))

        if self.Entry_twotheta_from.get() in ['', None, '\n']:
            self.Entry_twotheta_from.insert(0,
                                            str('%0.2f' % self.data_x[0][0]))

        if self.Entry_twotheta_to.get() in ['', None, '\n']:
            self.Entry_twotheta_to.insert(
                0, str('%0.2f' % self.data_x[0][len(self.data_x[0]) - 1]))

        if self.Entry_r.get() in ['', None, '\n']:
            self.Entry_r.insert(0, 0.5)

        if self.Entry_limit_peak[0].get() in ['', None, '\n']:
            self.Entry_limit_peak[0].insert(0, 2)

        for j in range(3):
            if len(self.k_alpha) > j:
                if self.Entry_kalpha[j].get() in ['', None, '\n']:
                    self.Entry_kalpha[j].insert(0, str(self.k_alpha[j]))
        if len(self.k_alpha) == 1:
            if self.Entry_kalpha[1].get() in ['', None, '\n']:
                self.Entry_kalpha[1].insert(0, str(0))
            if self.Entry_kalpha[2].get() in ['', None, '\n']:
                self.Entry_kalpha[2].insert(0, str(0))
        if len(self.k_alpha) == 2:
            if self.Entry_kalpha[2].get() in ['', None, '\n']:
                if import_XRD.k_alpha[0][1] == 0:
                    self.Entry_kalpha[2].insert(0, str(0))
                else:
                    self.Entry_kalpha[2].insert(0, str(0.5))

        for j in range(2):
            self.Entry_kalpha[j].config(state='disabled')

        self.button_init_wavelength.config(command=self.x_ray_initialize)

        i = 15
        Label(main.Frame3_3_2, text="--------------------").grid(row=i,
                                                                 column=0,
                                                                 sticky=W)
        self.peak_shift_correction_coefficient = []
        self.i = i
        self.Label_sc = Label(main.Frame3_3_2)
        self.Button_delete = Button(main.Frame3_3_2)
        self.button_psc.config(
            command=lambda: import_peak_shift_correction(self, self.i, main))

        #tools
        self.Button_limit_preview.config(
            command=lambda: limit_preview(self, angles_modif, main))
        self.Button_fit_preview.config(
            command=lambda: fit_preview(self, angles_modif, main))
        self.Button_run_calcul.config(
            command=lambda: main_calcul(self, angles_modif, main))
        #----------------------------
        f = plt.figure(1, facecolor="0.94")
        for i in range(len(self.phi)):
            plt.plot(self.data_x[i],
                     self.data_y[i],
                     label="" + str(i + 1) + "")
        plt.xlabel(r"$2\theta$")
        plt.ylabel("Intensity")
        plt.title("All original graph")
        plt.legend(loc='upper left',
                   bbox_to_anchor=(-0.1, -0.2, 1.2, 0),
                   ncol=10,
                   mode="expand",
                   borderaxespad=0.,
                   fontsize='x-small')
        plt.subplots_adjust(bottom=0.4)
        plt.close(f)
        canvas = FigureCanvasTkAgg(f, main.Frame3_3_4)
        canvas.get_tk_widget().pack(fill=BOTH, expand=YES)

    def x_ray_initialize(self):
        for j in range(3):
            self.Entry_kalpha[j].delete(0, END)
            if len(self.k_alpha) > j:
                self.Entry_kalpha[j].insert(0, str(self.k_alpha[j]))
        if len(self.k_alpha) == 1:
            self.Entry_kalpha[1].insert(0, str(0))
            self.Entry_kalpha[2].insert(0, str(0))
        if len(self.k_alpha) == 2:
            self.Entry_kalpha[2].insert(0, str(0.5))

    def x_ray_lock(self):
        for j in range(2):
            self.Entry_kalpha[j].config(state='disabled')

    def x_ray_unlock(self):
        for j in range(2):
            self.Entry_kalpha[j].config(state='normal')
コード例 #20
0
class Trainer(Frame):
    def __init__(self, master=None, **kw):
        Frame.__init__(self, master, **kw)
        self.background = '#303030'
        self.border_color = '#404040'
        self.args = {
            "data_dir": "",
            "prepared_data": "processed_data",
            "field": list(FIELDS.keys())[0],
            "batch_size": 4
        }
        self.textboxes = {}
        self.thread = None
        self.running = False
        self._init_ui()

    def _init_ui(self):
        ws = self.master.winfo_screenwidth()
        hs = self.master.winfo_screenheight()
        h = hs - 100
        w = int(h / 1.414) + 100
        x = (ws / 2) - (w / 2)
        y = (hs / 2) - (h / 2)
        self.master.geometry('%dx%d+%d+%d' % (w, h, x, y))
        self.master.maxsize(w, h)
        self.master.minsize(w, h)
        self.master.title("InvoiceNet - Trainer")

        self.pack(fill=BOTH, expand=True)

        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=0)
        self.rowconfigure(1, weight=1)
        self.rowconfigure(2, weight=0)
        self.rowconfigure(3, weight=1)

        self.configure(bg=self.background, bd=0)

        logo_frame = Frame(self,
                           bg=self.background,
                           bd=0,
                           relief=SUNKEN,
                           highlightbackground=self.border_color,
                           highlightthickness=1)
        param_frame = Frame(self,
                            bg=self.background,
                            bd=0,
                            relief=SUNKEN,
                            highlightbackground=self.border_color,
                            highlightthickness=1)
        progress_frame = Frame(self,
                               bg=self.background,
                               bd=0,
                               relief=SUNKEN,
                               highlightbackground=self.border_color,
                               highlightthickness=0)
        main_frame = Frame(self,
                           bg=self.background,
                           bd=0,
                           relief=SUNKEN,
                           highlightbackground=self.border_color,
                           highlightthickness=1)

        logo_frame.grid(row=0, column=0, sticky='news')
        param_frame.grid(row=1, column=0, sticky='news')
        progress_frame.grid(row=2,
                            column=0,
                            sticky='news',
                            padx=50,
                            pady=(0, 20))
        main_frame.grid(row=3, column=0, sticky='news')

        # Logo Frame
        logo_frame.columnconfigure(0, weight=1)
        logo_frame.columnconfigure(1, weight=0)
        logo_frame.columnconfigure(2, weight=0)
        logo_frame.columnconfigure(3, weight=1)
        logo_frame.rowconfigure(0, weight=1)

        self.logo_img = ImageTk.PhotoImage(Image.open(r'widgets/logo.png'))
        Label(logo_frame, bg=self.background,
              image=self.logo_img).grid(row=0,
                                        column=1,
                                        sticky='news',
                                        pady=10)
        Label(logo_frame,
              text="InvoiceNet",
              bg=self.background,
              fg="white",
              font=("Arial", 24, "bold")).grid(row=0,
                                               column=2,
                                               sticky='news',
                                               padx=20,
                                               pady=10)

        # Param Frame
        param_frame.columnconfigure(0, weight=1)
        param_frame.columnconfigure(1, weight=0)
        param_frame.columnconfigure(2, weight=0)
        param_frame.columnconfigure(3, weight=1)
        param_frame.rowconfigure(0, weight=1)
        param_frame.rowconfigure(1, weight=0)
        param_frame.rowconfigure(2, weight=0)
        param_frame.rowconfigure(3, weight=0)
        param_frame.rowconfigure(4, weight=1)

        data_param = Frame(param_frame,
                           bg=self.background,
                           bd=0,
                           relief=SUNKEN,
                           highlightbackground=self.border_color,
                           highlightthickness=0)
        out_param = Frame(param_frame,
                          bg=self.background,
                          bd=0,
                          relief=SUNKEN,
                          highlightbackground=self.border_color,
                          highlightthickness=0)
        field_param = Frame(param_frame,
                            bg=self.background,
                            bd=0,
                            relief=SUNKEN,
                            highlightbackground=self.border_color,
                            highlightthickness=0)
        batch_param = Frame(param_frame,
                            bg=self.background,
                            bd=0,
                            relief=SUNKEN,
                            highlightbackground=self.border_color,
                            highlightthickness=0)

        data_param.grid(row=1, column=1, pady=(0, 20), padx=20)
        out_param.grid(row=2, column=1, pady=20, padx=20)
        field_param.grid(row=1, column=2, pady=(0, 20), padx=20)
        batch_param.grid(row=2, column=2, pady=20, padx=20)

        df = Frame(data_param,
                   bg=self.background,
                   bd=0,
                   relief=SUNKEN,
                   highlightbackground=self.border_color,
                   highlightthickness=0)
        df.pack(side=TOP, fill=BOTH)

        Label(df,
              text="Data Folder:",
              bg=self.background,
              fg="white",
              font=("Arial", 8, "bold"),
              anchor='w').pack(side=LEFT, fill=BOTH)
        HoverButton(df,
                    image_path=r'widgets/open_dir_small.png',
                    command=lambda: self._open_dir("data_dir"),
                    width=18,
                    height=18,
                    bg=self.background,
                    bd=0,
                    highlightthickness=0,
                    activebackground='#558de8').pack(side=RIGHT)

        self.textboxes["data_dir"] = Text(data_param, height=1, width=20)
        self.textboxes["data_dir"].insert('1.0', self.args["data_dir"])
        self.textboxes["data_dir"].pack(side=BOTTOM)

        of = Frame(out_param,
                   bg=self.background,
                   bd=0,
                   relief=SUNKEN,
                   highlightbackground=self.border_color,
                   highlightthickness=0)
        of.pack(side=TOP, fill=BOTH)

        Label(of,
              text="Processed Data Folder:",
              bg=self.background,
              anchor='w',
              fg="white",
              font=("Arial", 8, "bold")).pack(side=LEFT, fill=BOTH)
        HoverButton(of,
                    image_path=r'widgets/open_dir_small.png',
                    command=lambda: self._open_dir("prepared_data"),
                    width=18,
                    height=18,
                    bg=self.background,
                    bd=0,
                    highlightthickness=0,
                    activebackground='#558de8').pack(side=RIGHT)

        self.textboxes["prepared_data"] = Text(out_param, height=1, width=20)
        self.textboxes["prepared_data"].insert('1.0',
                                               self.args["prepared_data"])
        self.textboxes["prepared_data"].pack(side=BOTTOM)

        Label(field_param,
              text="Field:",
              bg=self.background,
              anchor='w',
              fg="white",
              font=("Arial", 8, "bold")).pack(side=TOP, fill=BOTH)
        self.field_text = StringVar(field_param)
        self.field_text.set(list(FIELDS.keys())[0])

        keys = list(FIELDS.keys())
        field_list = OptionMenu(field_param, self.field_text, *keys)
        field_list.configure(highlightthickness=0, width=20, bg='#ffffff')
        field_list.pack(side=BOTTOM)

        for key in keys:
            field_list['menu'].entryconfigure(key, state="normal")

        Label(batch_param,
              text="Batch Size:",
              bg=self.background,
              anchor='w',
              fg="white",
              font=("Arial", 8, "bold")).pack(side=TOP, fill=BOTH)
        self.batch_text = StringVar(batch_param)
        self.batch_text.set("4")
        batch_list = OptionMenu(batch_param, self.batch_text,
                                *[str(2**i) for i in range(8)])
        batch_list.configure(highlightthickness=0, width=20, bg='#ffffff')
        batch_list.pack(side=BOTTOM)

        HoverButton(param_frame,
                    image_path=r'widgets/prepare.png',
                    command=self._prepare_data,
                    text='Prepare Data',
                    compound='center',
                    font=("Arial", 10, "bold"),
                    bg=self.background,
                    bd=0,
                    highlightthickness=0,
                    activebackground=self.background).grid(row=3,
                                                           column=1,
                                                           columnspan=2,
                                                           padx=20,
                                                           pady=(20, 0),
                                                           sticky='news')

        # Progress Frame
        self.progress_label = Label(progress_frame,
                                    text="Preparing data:",
                                    bg=self.background,
                                    anchor='w',
                                    fg="white",
                                    font=("Arial", 8, "bold"),
                                    bd=0,
                                    highlightthickness=0)
        self.progress_label.pack(side=TOP, expand=True, fill=X, pady=(10, 5))
        self.progressbar = Progressbar(progress_frame,
                                       orient=HORIZONTAL,
                                       length=100,
                                       mode='determinate')
        self.progressbar.pack(side=BOTTOM, expand=True, fill=X)

        # Main Frame
        main_frame.columnconfigure(0, weight=1)
        main_frame.rowconfigure(0, weight=1)
        main_frame.rowconfigure(1, weight=1)

        button_frame = Frame(main_frame,
                             bg=self.background,
                             bd=0,
                             relief=SUNKEN,
                             highlightbackground=self.border_color,
                             highlightthickness=0)
        button_frame.grid(row=0, column=0, sticky='news')

        button_frame.rowconfigure(0, weight=1)
        button_frame.columnconfigure(0, weight=1)
        button_frame.columnconfigure(1, weight=0)
        button_frame.columnconfigure(2, weight=1)

        self.start_button = HoverButton(button_frame,
                                        image_path=r'widgets/begin.png',
                                        command=self._start,
                                        text='Start',
                                        compound='center',
                                        font=("Arial", 10, "bold"),
                                        bg=self.background,
                                        bd=0,
                                        highlightthickness=0,
                                        activebackground=self.background)
        self.stop_button = HoverButton(button_frame,
                                       image_path=r'widgets/stop.png',
                                       command=self._stop,
                                       text='Stop',
                                       compound='center',
                                       font=("Arial", 10, "bold"),
                                       bg=self.background,
                                       bd=0,
                                       highlightthickness=0,
                                       activebackground=self.background)

        self.start_button.grid(row=0, column=1)
        self.stop_button.grid(row=0, column=1)
        self.stop_button.grid_forget()

        self.logger = Logger(main_frame,
                             height=18,
                             bg=self.background,
                             bd=0,
                             relief=SUNKEN)
        self.logger.grid(row=1, column=0, sticky='news')

    def _train(self):
        train_data = InvoiceData.create_dataset(
            field=self.args["field"],
            data_dir=os.path.join(self.args["prepared_data"], 'train/'),
            batch_size=self.args["batch_size"])
        val_data = InvoiceData.create_dataset(
            field=self.args["field"],
            data_dir=os.path.join(self.args["prepared_data"], 'val/'),
            batch_size=self.args["batch_size"])

        restore = None
        if os.path.exists(
                os.path.join('./models/invoicenet/', self.args["field"])):
            restore = messagebox.askyesno(
                title="Restore",
                message=
                "A checkpoint was found! Do you want to restore checkpoint for training?"
            )

        restore = True if restore else False

        model = AttendCopyParse(field=self.args["field"], restore=restore)

        print_interval = 20
        early_stop_steps = 0
        best = float("inf")

        train_iter = iter(train_data)
        val_iter = iter(val_data)

        self.logger.log("Initializing training!")
        start = time.time()
        step = 0
        while True:
            train_loss = model.train_step(next(train_iter))
            if not np.isfinite(train_loss):
                raise ValueError("NaN loss")

            if step % print_interval == 0:
                took = time.time() - start
                val_loss = model.val_step(next(val_iter))
                self.logger.log(
                    "[step: %d | %.2f steps/s]: train loss: %.4f val loss: %.4f"
                    % (step, (step + 1) / took, train_loss, val_loss))
                if not np.isfinite(val_loss):
                    self.logger.log("ERROR: NaN loss")
                    self.thread.stop()
                if val_loss < best:
                    early_stop_steps = 0
                    best = val_loss
                    model.save("best")
                else:
                    early_stop_steps += print_interval
                    if early_stop_steps >= 500:
                        self.logger.log(
                            "Validation loss has not improved for 500 steps")
                        self.thread.stop()

            step += 1

            if self.thread.stopped():
                self.logger.log("Training terminated!")
                break

        self.running = False
        self.stop_button.grid_forget()
        self.start_button.grid(row=0, column=1)

    def _get_inputs(self):
        self.args["field"] = self.field_text.get()
        self.args["batch_size"] = int(self.batch_text.get())
        self.args["data_dir"] = self.textboxes["data_dir"].get("1.0", 'end-1c')
        self.args["prepared_data"] = self.textboxes["prepared_data"].get(
            "1.0", 'end-1c')
        if not self.args["prepared_data"].endswith('/'):
            self.args["prepared_data"] += '/'
        if self.args["data_dir"] == '':
            return
        if not self.args["data_dir"].endswith('/'):
            self.args["data_dir"] += '/'

    def _start(self):
        self._get_inputs()

        if not os.path.exists(self.args["prepared_data"]):
            messagebox.showerror("Error",
                                 "Prepared data folder does not exist!")
            return

        files = glob.glob(self.args["prepared_data"] + "**/*.json",
                          recursive=True)
        if not files:
            messagebox.showerror(
                "Error",
                "Could not find processed data in \"{}\". Did you prepare training data?"
                .format(self.args["prepared_data"]))
            return
        if not self.running:
            self.running = True
            self.thread = StoppableThread(target=self._train)
            self.thread.daemon = True
            self.thread.start()
            self.start_button.grid_forget()
            self.stop_button.grid(row=0, column=1)

    def _stop(self):
        if self.running:
            self.thread.stop()
            self.running = False
            self.logger.log("Stopping training...")

    def _open_dir(self, key):
        dir_name = filedialog.askdirectory(
            initialdir='.', title="Select Directory Containing Invoices")
        if not dir_name:
            return
        self.args[key] = dir_name
        self.textboxes[key].delete('1.0', END)
        self.textboxes[key].insert('1.0', self.args[key])

    def _prepare_data(self):
        self._get_inputs()

        if self.args["data_dir"] == '':
            messagebox.showerror("Error", "Data folder does not exist!")
            return

        if not os.path.exists(self.args["data_dir"]):
            messagebox.showerror("Error", "Data folder does not exist!")
            return

        self.progressbar["value"] = 0
        self.progress_label.configure(text="Preparing Data:")

        os.makedirs(os.path.join(self.args["prepared_data"], 'train'),
                    exist_ok=True)
        os.makedirs(os.path.join(self.args["prepared_data"], 'val'),
                    exist_ok=True)

        filenames = [
            os.path.abspath(f)
            for f in glob.glob(self.args["data_dir"] + "**/*.pdf",
                               recursive=True)
        ]
        random.shuffle(filenames)

        idx = int(len(filenames) * 0.2)
        train_files = filenames[idx:]
        val_files = filenames[:idx]

        self.logger.log("Total: {}".format(len(filenames)))
        self.logger.log("Training: {}".format(len(train_files)))
        self.logger.log("Validation: {}".format(len(val_files)))

        total_samples = len(filenames)
        sample_idx = 0
        for phase, filenames in [('train', train_files), ('val', val_files)]:
            self.logger.log("Preparing {} data...".format(phase))
            for filename in tqdm(filenames):
                # try:
                page = pdf2image.convert_from_path(filename, dpi=500)[0]
                page.save(
                    os.path.join(self.args["prepared_data"], phase,
                                 os.path.basename(filename)[:-3] + 'png'))

                height = page.size[1]
                width = page.size[0]

                ngrams = util.create_ngrams(page)
                for ngram in ngrams:
                    if "amount" in ngram["parses"]:
                        ngram["parses"]["amount"] = util.normalize(
                            ngram["parses"]["amount"], key="amount")
                    if "date" in ngram["parses"]:
                        ngram["parses"]["date"] = util.normalize(
                            ngram["parses"]["date"], key="date")

                with open(filename[:-3] + 'json', 'r') as fp:
                    labels = simplejson.loads(fp.read())

                fields = {}
                for field in FIELDS:
                    if field in labels:
                        if FIELDS[field] == FIELD_TYPES["amount"]:
                            fields[field] = util.normalize(labels[field],
                                                           key="amount")
                        elif FIELDS[field] == FIELD_TYPES["date"]:
                            fields[field] = util.normalize(labels[field],
                                                           key="date")
                        else:
                            fields[field] = labels[field]
                    else:
                        fields[field] = ''

                data = {
                    "fields":
                    fields,
                    "nGrams":
                    ngrams,
                    "height":
                    height,
                    "width":
                    width,
                    "filename":
                    os.path.abspath(
                        os.path.join(self.args["prepared_data"], phase,
                                     os.path.basename(filename)[:-3] + 'png'))
                }

                with open(
                        os.path.join(self.args["prepared_data"], phase,
                                     os.path.basename(filename)[:-3] + 'json'),
                        'w') as fp:
                    fp.write(simplejson.dumps(data, indent=2))

                # except Exception as exp:
                #     self.logger.log("Skipping {} : {}".format(filename, exp))

                sample_idx += 1
                self.progress_label.configure(
                    text="Preparing data [{}/{}]:".format(
                        sample_idx, total_samples))
                self.progressbar["value"] = (sample_idx / total_samples) * 100
                self.progressbar.update()

        self.progress_label.configure(text="Completed!")
        self.progressbar["value"] = 100
        self.progressbar.update()
        self.logger.log("Prepared data stored in '{}'".format(
            self.args["prepared_data"]))
コード例 #21
0
def export_all_original_data(import_XRD, main):
    location = askdirectory(title="Please choose a directory")
    if location is not None and location is not '':
        for widget in main.Frame1_2.winfo_children():
            widget.destroy()
        Label(main.Frame1_2, text="Export").pack(side=LEFT)
        progress = Progressbar(main.Frame1_2,
                               orient="horizontal",
                               mode='determinate')
        progress.pack(side=LEFT)
        progress["value"] = 0
        progress["maximum"] = len(import_XRD.nfile)

        rotate = import_XRD.rotate
        flip = import_XRD.flip

        for i in range(len(import_XRD.nfile)):
            progress["value"] = progress["value"] + 1
            progress.update()

            f_split = (import_XRD.file_link[import_XRD.nfile[i]]).split("/")
            filename = f_split[len(f_split) - 1]
            name = str(location) + '/' + str(
                filename.split('.')[0]) + '_' + str(
                    import_XRD.nimage_i[i]) + '.xlf'
            f = open(name, 'w')

            data = read_data_2D(i, import_XRD)
            if len(data.shape) == 3:
                data = data[import_XRD.nimage_i[i]]

            if len(data) == 0:
                showinfo(title="Warning",
                         message="Can not read data of " + str(filename))
                return

            if rotate == 0:
                nrow = import_XRD.nrow[i]
                ncol = import_XRD.ncol[i]
                center_row = import_XRD.center_row[i]
                center_col = import_XRD.center_col[i]
                row_tick = import_XRD.row_tick[i]
                col_tick = import_XRD.col_tick[i]

            if rotate == 90:
                data = np.rot90(data, k=1, axes=(0, 1))
                nrow = import_XRD.ncol[i]
                ncol = import_XRD.nrow[i]
                center_row = import_XRD.center_col[i]
                center_col = import_XRD.center_row[i]
                row_tick = import_XRD.col_tick[i]
                col_tick = import_XRD.row_tick[i]

            if rotate == 180:
                data = np.rot90(data, k=2, axes=(0, 1))
                nrow = import_XRD.nrow[i]
                ncol = import_XRD.ncol[i]
                center_row = import_XRD.center_row[i]
                center_col = import_XRD.center_col[i]
                row_tick = import_XRD.row_tick[i]
                col_tick = import_XRD.col_tick[i]

            if rotate == 270:
                data = np.rot90(data, k=3, axes=(0, 1))
                nrow = import_XRD.ncol[i]
                ncol = import_XRD.nrow[i]
                center_row = import_XRD.center_col[i]
                center_col = import_XRD.center_row[i]
                row_tick = import_XRD.col_tick[i]
                col_tick = import_XRD.row_tick[i]

            if flip == 1:
                data = np.flip(data, axis=0)
            if flip == 2:
                data = np.flip(data, axis=1)

            f.write("Phi=" + str(import_XRD.phi[i]) + "\n")
            f.write("Chi=" + str(import_XRD.chi[i]) + "\n")
            f.write("Omega=" + str(import_XRD.omega[i]) + "\n")
            f.write("2theta=" + str(import_XRD.twotheta_center[i]) + "\n")
            f.write("Wavelength=" + str(import_XRD.k_alpha[i]) + "\n")
            f.write("Distance=" + str(import_XRD.distance[i]) + "\n")
            f.write("------------------------------------------\n")
            f.write("NRow=" + str(nrow) + "\n")
            f.write("Center Row=" + str(center_row) + "\n")
            for j in range(nrow):
                f.write(str(row_tick[j]) + " ")
            f.write("\n")
            f.write("NCol=" + str(ncol) + "\n")
            f.write("Center Col=" + str(center_col) + "\n")
            for j in range(ncol):
                f.write(str(col_tick[j]) + " ")
            f.write("\n")
            f.write("------------------------------------------\n")
            f.write("------------------------------------------\n")

            progress["value"] = progress["value"] + 1
            progress.update()

            for i in range(nrow):
                f.write(" ".join(str(e) for e in data[i]))
                if i < nrow - 1:
                    f.write("\n")

            f.close()

    for widget in main.Frame1_2.winfo_children():
        widget.destroy()
    main.root.mainloop()
コード例 #22
0
def makeModel(window):
    ProblemSelect = page(window, 'Problem Type')
    ProblemSelect.pack()

    problemType = StringVar(value="Text (Classification) -- Default")
    continueVar = BooleanVar()

    explanationBox = Label(ProblemSelect.contentFrame)

    problemTypeChoices = {
        'Numbers (Regression)':
        'Numerical data with continuous numerical output e.g. stock market data',
        'Numbers (Classification)':
        'Numerical data with fixed outputs e.g even and odd numbers',
        'Text (Regression)':
        'Text data with continuous numerical output e.g sentiment analysis',
        'Text (Classification) -- Default':
        'Text data with fixed outputs e.g spam filtering. Default option'
    }

    for choice, description in problemTypeChoices.items():
        option = Radiobutton(ProblemSelect.contentFrame,
                             text=choice,
                             variable=problemType,
                             value=choice,
                             command=lambda description=description:
                             explanationBox.config(text=description))
        option.grid(column=0, sticky='w', padx=5, pady=5)
    map(lambda x: x.deselect(),
        list(ProblemSelect.contentFrame.children.values()))
    list(ProblemSelect.contentFrame.children.values())[-1].invoke()

    explanationBox.grid(column=1, row=3, sticky='e')
    nxtBtn = Button(ProblemSelect.contentFrame,
                    text="next",
                    command=lambda: continueVar.set(True))
    nxtBtn.grid(column=1, columnspan=2, padx=10, ipadx=30, ipady=5)

    ProblemSelect.wait_variable(continueVar)
    ProblemSelect.pack_forget()

    # select which columns to use
    DataCollecting = page(window, 'Select Training Data')
    DataCollecting.pack()

    # load data
    fileNotLoaded = True
    counter = 0
    while fileNotLoaded:
        if counter == 10:
            messagebox.showerror(title='Error', message=retryError)
            sys.exit()
        try:
            counter += 1
            filename = askopenfilename(title='Choose Training Data',
                                       filetypes=dataFiletypes)
            if path.splitext(filename)[1].lower() == '.csv':
                trainingDataDF = read_csv(filename)
            else:
                trainingDataDF = read_excel(filename)
            # If you didn't clean your data, I'm just going to destroy it. Serves you right.
            trainingDataDF = trainingDataDF.apply(
                lambda x: x.interpolate(method='pad'))
            trainingDataDF = trainingDataDF.dropna(how='any')
            if len(trainingDataDF.index) < 50:
                raise ValueError(
                    ': Not enough data. Have to have at least 50 samples of data.\n'
                    'If you think you have enough, it might be because there were'
                    'invalid values that were automatically taken out.')
        except Exception as e:
            messagebox.showerror(title='Error',
                                 message=str(type(e)).split('\'')[1] + str(e))
            continue
        fileNotLoaded = False

    # listbox with all the column names
    columnListbox = ScrollingListbox(DataCollecting.contentFrame, 20)
    columnListbox.grid(column=0,
                       row=0,
                       rowspan=8,
                       padx=10,
                       pady=10,
                       sticky='ns')
    for columName in trainingDataDF.columns:
        columnListbox.listbox.insert('end', columName)

    featureListbox = ScrollingListbox(DataCollecting.contentFrame)
    featureListbox.grid(column=2, row=0, rowspan=4, padx=10, pady=10)

    featureAddButton = Button(
        DataCollecting.contentFrame,
        text='Add >>>',
        command=lambda: addToListBox(columnListbox, featureListbox))
    featureAddButton.grid(column=1, row=1)

    featureRemoveButton = Button(
        DataCollecting.contentFrame,
        text='<<< Remove',
        command=lambda: deleteFromListBox(featureListbox))
    featureRemoveButton.grid(column=1, row=2)

    targetListbox = ScrollingListbox(DataCollecting.contentFrame)
    targetListbox.grid(column=2, row=4, rowspan=4, padx=10, pady=10)

    targetAddButton = Button(
        DataCollecting.contentFrame,
        text='Add >>>',
        command=lambda: addToListBox(columnListbox, targetListbox))
    targetAddButton.grid(column=1, row=5)

    targetRemoveButton = Button(
        DataCollecting.contentFrame,
        text='<<< Remove',
        command=lambda: deleteFromListBox(targetListbox))
    targetRemoveButton.grid(column=1, row=6)

    collectDataButton = Button(
        DataCollecting.contentFrame,
        text='Create',
        command=lambda: continueVar.set(True)
        if len(featureListbox.listbox.get(0, 'end')) > 0 and len(
            targetListbox.listbox.get(0, 'end')
        ) > 0 else messagebox.showwarning(
            title='Warning',
            message='You must have at least one feature and one target'))
    collectDataButton.grid(column=2, row=8, pady=20, ipadx=20)

    DataCollecting.wait_variable(continueVar)
    DataCollecting.pack_forget()

    creating = page(window, 'Creating')
    creating.pack()

    progress = Progressbar(creating.contentFrame)
    progress.pack()
    progress.config(mode='indeterminate')
    progress.start()

    sleep(2)

    featureColumnNames = featureListbox.listbox.get(0, 'end')
    targetColumnNames = targetListbox.listbox.get(0, 'end')

    featureTrain = trainingDataDF[list(featureColumnNames)]
    targetTrain = trainingDataDF[list(targetColumnNames)]

    featureEncoder = LabelEncoder()
    targetEncoder = LabelEncoder()

    if 'Text' in problemType.get():
        featureEncoder.fit(
            array(list(
                set(featureTrain.to_numpy().flatten().tolist()))).reshape(
                    -1, 1).ravel())
        featureTrain = featureTrain.applymap(
            lambda x: featureEncoder.transform(array(x).reshape(1, 1))[0])

    if 'Classification' in problemType.get():
        targetEncoder.fit(
            array(list(
                set(targetTrain.to_numpy().flatten().tolist()))).reshape(
                    -1, 1).ravel())
        targetTrain = targetTrain.applymap(
            lambda x: targetEncoder.transform(array(x).reshape(1, 1))[0])

    model = chooseAlgorithm(problemType.get(), featureTrain, targetTrain)

    progress.stop()
    progress.pack_forget()

    modelname = str(model.__class__).split('.')[-1][:-2]
    filename = modelname + ' ' + datetime.now().strftime("%Y-%m-%d-%H-%M-%S")

    fileNotLoaded = True
    counter = 0
    while fileNotLoaded:
        if counter == 10:
            messagebox.showerror(title='Error', message=retryError)
            sys.exit()
        try:
            counter += 1
            filepath = asksaveasfilename(
                initialfile=filename,
                defaultextension='.mlmc',
                filetypes=[('Edward Machine Learning Creater Model', '*.emlcm')
                           ],
                title='Save As')
            dump([
                model,
                problemType.get(), featureEncoder, targetEncoder,
                featureTrain.columns, targetTrain.columns
            ], filepath, 5)
        except Exception as e:
            messagebox.showerror(title='Error',
                                 message=str(type(e)).split('\'')[1] + str(e))
            continue
        fileNotLoaded = False

    backButton = Button(
        creating.contentFrame,
        text='Back to Home Page',
        font=('Helvetica', 30),
        command=lambda:
        [continueVar.set(True),
         creating.destroy(),
         HomePage(window)])
    backButton.pack(pady=20)

    quitButton = Button(
        creating.contentFrame,
        text='Quit',
        font=('Helvetica', 30),
        command=lambda: [continueVar.set(True),
                         window.destroy()])
    quitButton.pack(pady=20)

    creating.wait_variable(continueVar)
コード例 #23
0
def export_original_data(nfile, nimage, nimage_i, import_XRD, main):
    f = asksaveasfile(title="Export data",
                      mode='w',
                      defaultextension=".xlf",
                      filetypes=[('X-Light format', '.xlf'),
                                 ('all files', '.*')])
    if f is not None and f is not '':
        for widget in main.Frame1_2.winfo_children():
            widget.destroy()
        Label(main.Frame1_2, text="Export").pack(side=LEFT)
        progress = Progressbar(main.Frame1_2,
                               orient="horizontal",
                               mode='determinate')
        progress.pack(side=LEFT)
        progress["value"] = 0
        progress["maximum"] = 3

        f_split = (import_XRD.file_link[nfile]).split("/")
        filename = f_split[len(f_split) - 1]
        rotate = import_XRD.rotate
        flip = import_XRD.flip

        progress["value"] = progress["value"] + 1
        progress.update()

        data = read_data_2D(nimage, import_XRD)
        if len(data.shape) == 3:
            data = data[nimage_i]

        if len(data) == 0:
            showinfo(title="Warning",
                     message="Can not read data of " + str(filename))
            return

        progress["value"] = progress["value"] + 1
        progress.update()

        if rotate == 0:
            nrow = import_XRD.nrow[nimage]
            ncol = import_XRD.ncol[nimage]
            center_row = import_XRD.center_row[nimage]
            center_col = import_XRD.center_col[nimage]
            row_tick = import_XRD.row_tick[nimage]
            col_tick = import_XRD.col_tick[nimage]

        if rotate == 90:
            data = np.rot90(data, k=1, axes=(0, 1))
            nrow = import_XRD.ncol[nimage]
            ncol = import_XRD.nrow[nimage]
            center_row = import_XRD.center_col[nimage]
            center_col = import_XRD.center_row[nimage]
            row_tick = import_XRD.col_tick[nimage]
            col_tick = import_XRD.row_tick[nimage]

        if rotate == 180:
            data = np.rot90(data, k=2, axes=(0, 1))
            nrow = import_XRD.nrow[nimage]
            ncol = import_XRD.ncol[nimage]
            center_row = import_XRD.center_row[nimage]
            center_col = import_XRD.center_col[nimage]
            row_tick = import_XRD.row_tick[nimage]
            col_tick = import_XRD.col_tick[nimage]

        if rotate == 270:
            data = np.rot90(data, k=3, axes=(0, 1))
            nrow = import_XRD.ncol[nimage]
            ncol = import_XRD.nrow[nimage]
            center_row = import_XRD.center_col[nimage]
            center_col = import_XRD.center_row[nimage]
            row_tick = import_XRD.col_tick[nimage]
            col_tick = import_XRD.row_tick[nimage]

        if flip == 1:
            data = np.flip(data, axis=0)
        if flip == 2:
            data = np.flip(data, axis=1)

        f.write("Phi=" + str(import_XRD.phi[nimage]) + "\n")
        f.write("Chi=" + str(import_XRD.chi[nimage]) + "\n")
        f.write("Omega=" + str(import_XRD.omega[nimage]) + "\n")
        f.write("2theta=" + str(import_XRD.twotheta_center[nimage]) + "\n")
        f.write("Wavelength=" + str(import_XRD.k_alpha[nimage]) + "\n")
        f.write("Distance=" + str(import_XRD.distance[nimage]) + "\n")
        f.write("------------------------------------------\n")
        f.write("NRow=" + str(nrow) + "\n")
        f.write("Center Row=" + str(center_row) + "\n")
        for i in range(nrow):
            f.write(str(row_tick[i]) + " ")
        f.write("\n")
        f.write("NCol=" + str(ncol) + "\n")
        f.write("Center Col=" + str(center_col) + "\n")
        for i in range(ncol):
            f.write(str(col_tick[i]) + " ")
        f.write("\n")
        f.write("------------------------------------------\n")
        f.write("------------------------------------------\n")

        progress["value"] = progress["value"] + 1
        progress.update()

        for i in range(nrow):
            f.write(" ".join(str(e) for e in data[i]))
            if i < nrow - 1:
                f.write("\n")

        progress["value"] = progress["value"] + 1
        progress.update()

    f.close()
    for widget in main.Frame1_2.winfo_children():
        widget.destroy()
    main.root.mainloop()
#*************************************************************************************************************************
# Initilizing progress bars

# progressbar with text inside it
s = Style(root)
# add the label to the progressbar style
s.layout("LabeledProgressbar",
         [('LabeledProgressbar.trough',
           {'children': [('LabeledProgressbar.pbar',
                          {'side': 'left', 'sticky': 'ns'}),
                         ("LabeledProgressbar.label",   # label inside the bar
                          {"sticky": ""})],
           'sticky': 'nswe'})])

progress = Progressbar(commandframe, orient="horizontal", length=300, style="LabeledProgressbar")
progress.pack(side=TOP, padx=10, pady=10)
# change the text of the progressbar, 
# the trailing spaces are here to properly center the text
s.configure("LabeledProgressbar", text="Loading Model on GPU please wait:0 %      ")

# uncomment this if you want to make an image button instead of 'Detect' text button
#btnphoto = ImageTk.PhotoImage(Image.open('C:/Users/Talha/Desktop/chkpt/paprika_model/run.png'))
# make detect button
btn = Button(commandframe, text='Detect',  command =play_btn)#image = btnphoto,
btn.pack(side=LEFT, padx=10, pady=10)

# 2nd progress bar with detect button
progress_det = Progressbar(commandframe, length=200, cursor='watch',mode="determinate", orient=HORIZONTAL)
#progress_det = Progressbar(commandframe, orient = HORIZONTAL, length = 100, mode = 'indeterminate') # for shuttling block progress bar
progress_det.pack(side=LEFT, padx=10, pady=10)
コード例 #25
0
def export_calib_data(calib_2D, angles_modif, import_XRD, main):
    from residual_stress_2D.calib_XRD_2D import calib_pyFai

    f = asksaveasfile(title="Export data",
                      mode='w',
                      defaultextension=".xlf",
                      filetypes=[('X-Light format', '.xlf'),
                                 ('all files', '.*')])
    if f is not None and f is not '':
        for widget in main.Frame1_2.winfo_children():
            widget.destroy()
        Label(main.Frame1_2, text="Export").pack(side=LEFT)
        progress = Progressbar(main.Frame1_2,
                               orient="horizontal",
                               mode='determinate')
        progress.pack(side=LEFT)
        progress["value"] = 0
        progress["maximum"] = 3

        rotate = import_XRD.rotate
        flip = import_XRD.flip

        if calib_2D.angles_modif_valid == True:
            twotheta_x = angles_modif.twotheta_x
            gamma_y = angles_modif.gamma_y
            phi = angles_modif.phi[calib_2D.nimage]
            chi = angles_modif.chi[calib_2D.nimage]
            omega = angles_modif.omega[calib_2D.nimage]
            twotheta_center = angles_modif.twotheta_center[calib_2D.nimage]
        else:
            twotheta_x = calib_2D.twotheta_x
            gamma_y = calib_2D.gamma_y
            phi = calib_2D.phi[calib_2D.nimage]
            chi = calib_2D.chi[calib_2D.nimage]
            omega = calib_2D.omega[calib_2D.nimage]
            twotheta_center = calib_2D.twotheta_center[calib_2D.nimage]

        progress["value"] = progress["value"] + 1
        progress.update()

        data = read_data_2D(calib_2D.nimage, import_XRD)

        if len(data.shape) == 3:
            data = data[import_XRD.nimage_i[calib_2D.nimage]]

        if len(data) == 0:
            showinfo(title="Warning",
                     message="Can not read data of " + str(filename))
            return

        if rotate == 0:
            nrow = import_XRD.nrow[calib_2D.nimage]
            ncol = import_XRD.ncol[calib_2D.nimage]
            center_row = import_XRD.center_row[calib_2D.nimage]
            center_col = import_XRD.center_col[calib_2D.nimage]

        if rotate == 90:
            data = np.rot90(data, k=1, axes=(0, 1))
            nrow = import_XRD.ncol[calib_2D.nimage]
            ncol = import_XRD.nrow[calib_2D.nimage]
            center_row = import_XRD.center_col[calib_2D.nimage]
            center_col = import_XRD.center_row[calib_2D.nimage]

        if rotate == 180:
            data = np.rot90(data, k=2, axes=(0, 1))
            nrow = import_XRD.nrow[calib_2D.nimage]
            ncol = import_XRD.ncol[calib_2D.nimage]
            center_row = import_XRD.center_row[calib_2D.nimage]
            center_col = import_XRD.center_col[calib_2D.nimage]

        if rotate == 270:
            data = np.rot90(data, k=3, axes=(0, 1))
            nrow = import_XRD.ncol[calib_2D.nimage]
            ncol = import_XRD.nrow[calib_2D.nimage]
            center_row = import_XRD.center_col[calib_2D.nimage]
            center_col = import_XRD.center_row[calib_2D.nimage]

        if flip == 1:
            data = np.flip(data, axis=0)

        if flip == 2:
            data = np.flip(data, axis=1)

        progress["value"] = progress["value"] + 1
        progress.update()
        calib = calib_pyFai(import_XRD, data, nrow, ncol, center_row,
                            center_col, twotheta_center)

        if len(calib) > 0:
            data = calib[0]
        else:
            showinfo(title="Warning",
                     message="Can not calib file " + str(filename))
            return

        if float(calib_2D.Check_twotheta_flip.get()) == 1:
            data = np.flip(data, axis=1)

        if len(data) > 0:
            progress["value"] = progress["value"] + 1
            progress.update()
            nrow = len(gamma_y)
            ncol = len(twotheta_x)

            f.write("Phi=" + str(phi) + "\n")
            f.write("Chi=" + str(chi) + "\n")
            f.write("Omega=" + str(omega) + "\n")
            f.write("2theta=" + str(twotheta_center) + "\n")
            f.write("Wavelength=" + str(import_XRD.k_alpha[calib_2D.nimage]) +
                    "\n")
            f.write("Distance=" + str(import_XRD.distance[calib_2D.nimage]) +
                    "\n")
            f.write("------------------------------------------\n")
            f.write("NRow=" + str(nrow) + "\n")
            f.write("Center Row=" + str(center_row) + "\n")
            for i in range(nrow):
                f.write(str(gamma_y[i]) + " ")
            f.write("\n")
            f.write("NCol=" + str(ncol) + "\n")
            f.write("Center Col=" + str(center_col) + "\n")
            for i in range(ncol):
                f.write(str(twotheta_x[i]) + " ")
            f.write("\n")
            f.write("------------------------------------------\n")
            f.write("------------------------------------------\n")

            progress["value"] = progress["value"] + 1
            progress.update()

            for i in range(nrow):
                f.write(" ".join(str(e) for e in data[i]))
                f.write("\n")

            progress["value"] = progress["value"] + 1
            progress.update()
    for widget in main.Frame1_2.winfo_children():
        widget.destroy()
    f.close()
    main.root.mainloop()
コード例 #26
0
class GameWindow:
    def __init__(self, master, char):

        self.settingBox = Frame(master,
                                height=450,
                                width=1000,
                                background="white")
        self.settingBox.pack(side=TOP)
        self.settingBox.pack_propagate(0)

        self.battleOptionsBox = Frame(self.settingBox,
                                      height=450,
                                      width=200,
                                      background="grey")
        self.battleOptionsBox.pack(side=LEFT)
        self.battleOptionsBox.pack_propagate(0)

        self.settingBoxCanvas = Canvas(self.settingBox, height=450, width=596)
        self.settingBoxCanvas.pack(side=LEFT)
        self.settingBoxCanvas.pack_propagate(0)
        self.canvasImg = PhotoImage(file="cave.png")
        self.background = self.settingBoxCanvas.create_image(
            300, 225, image=self.canvasImg)

        self.rightMenuBox = Frame(self.settingBox,
                                  height=450,
                                  width=200,
                                  background="grey")
        self.rightMenuBox.pack(side=RIGHT)
        self.rightMenuBox.pack_propagate(0)

        self.bottomFrame = Frame(master,
                                 height=150,
                                 width=1000,
                                 background="green")
        self.bottomFrame.pack(side=BOTTOM)

        self.playerHealthArea = Frame(self.bottomFrame,
                                      height=150,
                                      width=200,
                                      background="grey")
        self.playerHealthArea.pack(side=LEFT)
        self.playerHealthArea.pack_propagate(0)

        self.textArea = Frame(self.bottomFrame,
                              height=150,
                              width=600,
                              background="black")
        self.textArea.pack(side=LEFT)
        self.textArea.pack_propagate(0)

        self.firstLineText = Label(self.textArea,
                                   text="",
                                   font=("helvetica", 20),
                                   fg="white",
                                   bg="black")
        self.firstLineText.pack(side=TOP)
        self.secondLineText = Label(self.textArea,
                                    text="",
                                    font=("helvetica", 20),
                                    fg="white",
                                    bg="black")
        self.secondLineText.pack()
        self.thirdLineText = Label(self.textArea,
                                   text="",
                                   font=("helvetica", 20),
                                   fg="white",
                                   bg="black")
        self.thirdLineText.pack()

        self.enemyHealthArea = Frame(self.bottomFrame,
                                     height=150,
                                     width=200,
                                     background="grey")
        self.enemyHealthArea.pack(side=LEFT)
        self.enemyHealthArea.pack_propagate(0)

        self.playerHealthTitle = Label(self.playerHealthArea,
                                       text="Health",
                                       font=("Helvetica", 25),
                                       bg="grey")
        self.playerHealthTitle.pack(side=TOP)

        self.playerHealthText = Label(self.playerHealthArea,
                                      text=str(char.health) + " / " +
                                      str(char.maxHealth),
                                      font=("Helvetica", 20),
                                      bg="Grey")
        self.playerHealthText.pack()

        self.healthBarVar = IntVar()
        self.healthBarVar.set(char.health)
        self.playerHealthBar = Progressbar(self.playerHealthArea,
                                           orient=HORIZONTAL,
                                           length=100,
                                           variable=self.healthBarVar,
                                           maximum=char.maxHealth)
        self.playerHealthBar.pack()

        self.testHealthButton = Button(
            self.playerHealthArea,
            text="test",
            command=lambda: self.decreaseHealth(char))
        self.testHealthButton.pack()

        self.mainMenu = Menu()
        master.config(menu=self.mainMenu)
        self.fileMenu = Menu()
        self.mainMenu.add_cascade(label="File", menu=self.fileMenu)
        self.fileMenu.add_command(label="Save...",
                                  command=lambda: self.saveCharacter(char))
        self.fileMenu.add_command(label="Open...",
                                  command=lambda: self.openCharacter(char))
        self.fileMenu.add_separator()
        self.fileMenu.add_command(label="Exit", command=master.quit)

    def saveCharacter(
        self, CHARACTER
    ):  # saves the current character object w/ all its attributes to a pickle file
        characterFile = open("character.pickle", "wb")
        pickle.dump(CHARACTER, characterFile)

    def openCharacter(
        self, CHARACTER
    ):  # retrieves the pickle file and sets the current character object's attributes to that of the saved char.
        characterFile = open("character.pickle", "rb")
        savedCharacter = pickle.load(characterFile)
        CHARACTER.XP = savedCharacter.XP
        CHARACTER.level = savedCharacter.level
        CHARACTER.health = savedCharacter.health
        CHARACTER.maxHealth = savedCharacter.maxHealth
        CHARACTER.inventory = savedCharacter.inventory
        CHARACTER.weapon = savedCharacter.weapon
        CHARACTER.armor = savedCharacter.health
        CHARACTER.attackValue = savedCharacter.attackValue
        CHARACTER.defenseValue = savedCharacter.defenseValue
        self.updateHealthBar(CHARACTER)

    def displayEnemy(self, ENEMY, charact):
        self.enemyHealthTitle = Label(self.enemyHealthArea,
                                      text=ENEMY.name + " Health",
                                      font=("Helvetica", 20),
                                      bg="grey")
        self.enemyHealthTitle.pack(side=TOP)

        self.enemyImage = self.settingBoxCanvas.create_image(300,
                                                             225,
                                                             image=ENEMY.image)

        self.enemyHealthText = Label(self.enemyHealthArea,
                                     text=str(ENEMY.health) + " / " +
                                     str(ENEMY.maxHealth),
                                     font=("Helvetica", 20),
                                     bg="Grey")
        self.enemyHealthText.pack()
        self.enemyHealthBarVar = IntVar()
        self.enemyHealthBarVar.set(ENEMY.health)
        self.enemyHealthBar = Progressbar(self.enemyHealthArea,
                                          orient=HORIZONTAL,
                                          length=100,
                                          variable=self.enemyHealthBarVar,
                                          maximum=ENEMY.maxHealth)
        self.enemyHealthBar.pack()

        self.testEnemyHealthButton = Button(
            self.enemyHealthArea,
            text="test",
            command=lambda: ENEMY.attack(charact, self))
        self.testEnemyHealthButton.pack()

    def hideEnemy(self):
        self.enemyHealthText.pack_forget()
        self.enemyHealthTitle.pack_forget()
        self.enemyHealthBar.pack_forget()
        self.testEnemyHealthButton.pack_forget()
        self.settingBoxCanvas.delete(self.enemyImage)

    def decreaseHealth(self, CHARACTER):
        if CHARACTER.health > 0:
            CHARACTER.health -= 1
            self.updateHealthBar(CHARACTER)

    def updateHealthBar(self, CHARACTER):
        if isinstance(CHARACTER, Character):
            self.healthBarVar.set(CHARACTER.health)
            self.playerHealthText.config(text=str(CHARACTER.health) + " / " +
                                         str(CHARACTER.maxHealth))

        elif isinstance(CHARACTER, Enemy):
            self.enemyHealthBarVar.set(CHARACTER.health)
            self.enemyHealthText.config(text=str(CHARACTER.health) + " / " +
                                        str(CHARACTER.maxHealth))

    def displayText(self, text):
        self.firstLineText.config(text='')
        self.secondLineText.config(text='')
        self.thirdLineText.config(text='')

        if len(text) > 40:
            count = 0
            self.firstLine = ''
            self.secondLine = ''
            self.thirdLine = ""
            self.firstLineFull = False
            self.secondLineFull = False
            for i in text:
                count += 1
                if count <= 38:
                    self.firstLine = self.firstLine + i
                elif count > 38 and i != " " and not self.firstLineFull:
                    self.firstLine = self.firstLine + i
                elif count > 38 and i == " ":
                    self.firstLineFull = True

                if self.firstLineFull and not self.secondLineFull and count < 90:
                    self.secondLine = self.secondLine + i
                elif self.firstLineFull and count > 80 and i != " " and not self.secondLineFull:
                    self.secondLine = self.secondLine + i
                elif count > 85 and i == " ":
                    self.secondLineFull = True

                if count > 90 and self.firstLineFull and self.secondLineFull:
                    self.thirdLine = self.thirdLine + i
        else:
            self.firstLine = text
            self.secondLine = ''
            self.thirdLine = ""

        self.firstLineText.config(text=self.firstLine)
        self.secondLineText.config(text=self.secondLine)
        self.thirdLineText.config(text=self.thirdLine)

    def displayBattleMenu(self, char, ENEMY, master):
        self.battleMenuTitle = Label(self.battleOptionsBox,
                                     text="Battle Menu",
                                     font=("helvetica", 28),
                                     bg="grey")
        self.battleMenuTitle.pack(side=TOP)

        self.attackButton = Button(
            self.battleOptionsBox,
            text="Attack",
            width=8,
            font=("helvetica", 20),
            pady=2,
            command=lambda: char.attack(ENEMY, self, master))
        self.attackButton.pack()
        self.attackButton.bind("<Enter>", self.attackDescription)

        self.defendButton = Button(
            self.battleOptionsBox,
            text="Defend",
            width=8,
            font=("helvetica", 20),
            pady=2,
            command=lambda: char.defend(ENEMY, self, master))
        self.defendButton.pack()
        self.defendButton.bind("<Enter>", self.defendDescription)

        self.useItemButton = Button(
            self.battleOptionsBox,
            text="Use Item",
            width=8,
            font=("helvetica", 20),
            pady=2,
            command=lambda: self.displayCharacterInventory(
                char, ENEMY, master))
        self.useItemButton.pack()
        self.useItemButton.bind("<Enter>", self.useItemDescription)

        self.magicButton = Button(self.battleOptionsBox,
                                  text="Magic",
                                  width=8,
                                  font=("helvetica", 20),
                                  pady=2)
        self.magicButton.pack()
        self.magicButton.bind("<Enter>", self.magicDescription)

        self.fleeButton = Button(
            self.battleOptionsBox,
            text="Flee",
            width=8,
            font=("helvetica", 20),
            pady=2,
            command=lambda: char.flee(ENEMY, self, master))
        self.fleeButton.pack()
        self.fleeButton.bind("<Enter>", self.fleeDescription)

    def hideBattleMenu(self):
        self.useItemButton.pack_forget()
        self.attackButton.pack_forget()
        self.magicButton.pack_forget()
        self.fleeButton.pack_forget()
        self.defendButton.pack_forget()
        self.battleMenuTitle.pack_forget()

    def displayCharacterInventory(self, CHARACTER, ENEMY, master):
        print(CHARACTER.inventory)

        self.hideBattleMenu()
        self.inventoryTitle = Label(self.battleOptionsBox,
                                    text="Inventory",
                                    font=("helvetica", 28),
                                    bg="grey")
        self.inventoryTitle.pack(side=TOP)
        for key in CHARACTER.inventory:
            if key == "Gold" and (CHARACTER.inventory["Gold"])["Amount"] > 0:
                self.goldButton = Button(
                    self.battleOptionsBox,
                    text="x" + str(
                        (CHARACTER.inventory["Gold"])["Amount"]) + " Gold",
                    width=8,
                    font=("helvetica", 20),
                    pady=2,
                    command=lambda: self.displayText(
                        "What are you gonna do, pay him off?"))
                self.goldButton.pack()
                self.goldButton.bind(
                    "<Enter>", lambda e: self.displayText(
                        (CHARACTER.inventory["Gold"])["Description"]))
            if key == "Stick" and (CHARACTER.inventory["Stick"])["Amount"] > 0:
                self.stickButton = Button(
                    self.battleOptionsBox,
                    text="x" + str(
                        (CHARACTER.inventory["Stick"])["Amount"]) + " Stick",
                    width=8,
                    font=("helvetica", 20),
                    pady=2,
                    command=lambda: self.displayText(
                        "This is a stick... what could you possibly accomplish with this?"
                    ))
                self.stickButton.pack()
                self.stickButton.bind(
                    "<Enter>", lambda e: self.displayText(
                        (CHARACTER.inventory["Stick"])["Description"]))
            if key == "Health Potion" and (
                    CHARACTER.inventory["Health Potion"])["Amount"] > 0:
                self.potionButton = Button(
                    self.battleOptionsBox,
                    text="x" + str(
                        (CHARACTER.inventory["Health Potion"])["Amount"]) +
                    " Health \nPotions",
                    width=8,
                    font=("helvetica", 20),
                    pady=4,
                    command=lambda: CHARACTER.usePotion(self, ENEMY, master))
                self.potionButton.pack()
                self.potionButton.bind(
                    "<Enter>", lambda e: self.displayText(
                        (CHARACTER.inventory["Health Potion"])["Description"]))

        self.backToBattleMenuButton = Button(
            self.battleOptionsBox,
            text="Back",
            font=("helvetica", 20),
            pady=2,
            command=lambda: self.backToBattleMenu(CHARACTER, ENEMY, master))
        self.backToBattleMenuButton.pack(side=BOTTOM)

    def displayCharacterXPBar(self, CHARACTER):
        self.XPBarVar = IntVar()
        self.XPBarVar.set(CHARACTER.XP)
        self.CharacterXPBar = Progressbar(self.textArea,
                                          orient=HORIZONTAL,
                                          length=500,
                                          variable=self.XPBarVar,
                                          maximum=(CHARACTER.level * 10))
        self.xpTitle = Label(self.textArea,
                             text="%s/%s XP" %
                             (str(CHARACTER.XP), str(CHARACTER.level * 10)),
                             font=('Helvetica', 20),
                             bg="Black",
                             fg="White")
        self.xpTitle.pack(side=LEFT, padx=10)
        self.CharacterXPBar.pack(side=RIGHT, padx=10)

    def hideCharacterXPBar(self):
        self.CharacterXPBar.pack_forget()
        self.xpTitle.pack_forget()

    def hideCharacterInventory(self):
        self.goldButton.pack_forget()
        self.potionButton.pack_forget()
        self.stickButton.pack_forget()
        self.inventoryTitle.pack_forget()
        self.backToBattleMenuButton.pack_forget()

    def backToBattleMenu(self, CHARACTER, ENEMY, master):
        self.hideCharacterInventory()
        self.displayBattleMenu(CHARACTER, ENEMY, master)

    def attackDescription(self, event):
        self.displayText("Attack the enemy with your weapon.")

    def defendDescription(self, event):
        self.displayText("Ready yourself to defend against the enemy.")

    def useItemDescription(self, event):
        self.displayText("Open your inventory and use an Item.")

    def magicDescription(self, event):
        self.displayText("Open your spell list, if you have unlocked magic.")

    def fleeDescription(self, event):
        self.displayText("Attempt to flee from the battle.")
コード例 #27
0
def export_all_calib_data(calib_2D, angles_modif, import_XRD, main):
    from residual_stress_2D.calib_XRD_2D import calib_pyFai

    location = askdirectory(title="Please choose a directory")
    if location is not None and location is not '':
        for widget in main.Frame1_2.winfo_children():
            widget.destroy()
        Label(main.Frame1_2, text="Export").pack(side=LEFT)
        progress = Progressbar(main.Frame1_2,
                               orient="horizontal",
                               mode='determinate')
        progress.pack(side=LEFT)
        progress["value"] = 0
        progress["maximum"] = len(import_XRD.nfile)

        rotate = import_XRD.rotate
        flip = import_XRD.flip

        for i in range(len(import_XRD.nfile)):
            progress["value"] = progress["value"] + 1
            progress.update()

            f_split = (import_XRD.file_link[import_XRD.nfile[i]]).split("/")
            filename = f_split[len(f_split) - 1]
            name = str(location) + '/calib_' + str(
                filename.split('.')[0]) + '_' + str(
                    import_XRD.nimage_i[i]) + '.xlf'
            f = open(name, 'w')

            if calib_2D.angles_modif_valid == True:
                twotheta_x = angles_modif.twotheta_x
                gamma_y = angles_modif.gamma_y
                phi = angles_modif.phi[i]
                chi = angles_modif.chi[i]
                omega = angles_modif.omega[i]
                twotheta_center = angles_modif.twotheta_center[i]
            else:
                twotheta_x = calib_2D.twotheta_x
                gamma_y = calib_2D.gamma_y
                phi = calib_2D.phi[i]
                chi = calib_2D.chi[i]
                omega = calib_2D.omega[i]
                twotheta_center = calib_2D.twotheta_center[i]

            data = read_data_2D(i, import_XRD)

            if len(data.shape) == 3:
                data = data[import_XRD.nimage_i[i]]

            if len(data) == 0:
                showinfo(title="Warning",
                         message="Can not read data of " + str(filename))
                return

            if rotate == 0:
                nrow = import_XRD.nrow[i]
                ncol = import_XRD.ncol[i]
                center_row = import_XRD.center_row[i]
                center_col = import_XRD.center_col[i]

            if rotate == 90:
                data = np.rot90(data, k=1, axes=(0, 1))
                nrow = import_XRD.ncol[i]
                ncol = import_XRD.nrow[i]
                center_row = import_XRD.center_col[i]
                center_col = import_XRD.center_row[i]

            if rotate == 180:
                data = np.rot90(data, k=2, axes=(0, 1))
                nrow = import_XRD.nrow[i]
                ncol = import_XRD.ncol[i]
                center_row = import_XRD.center_row[i]
                center_col = import_XRD.center_col[i]

            if rotate == 270:
                data = np.rot90(data, k=3, axes=(0, 1))
                nrow = import_XRD.ncol[i]
                ncol = import_XRD.nrow[i]
                center_row = import_XRD.center_col[i]
                center_col = import_XRD.center_row[i]

            if flip == 1:
                data = np.flip(data, axis=0)

            if flip == 2:
                data = np.flip(data, axis=1)

            calib = calib_pyFai(import_XRD, data, nrow, ncol, center_row,
                                center_col, twotheta_center)
            if len(calib) > 0:
                data = calib[0]
            else:
                showinfo(title="Warning",
                         message="Can not calib file " + str(filename))
                return

            if float(calib_2D.Check_twotheta_flip.get()) == 1:
                data = np.flip(data, axis=1)

            if len(data) > 0:
                progress["value"] = progress["value"] + 1
                progress.update()
                data = calib[0]
                nrow = len(gamma_y)
                ncol = len(twotheta_x)

                f.write("Phi=" + str(phi) + "\n")
                f.write("Chi=" + str(chi) + "\n")
                f.write("Omega=" + str(omega) + "\n")
                f.write("2theta=" + str(twotheta_center) + "\n")
                f.write("Wavelength=" + str(import_XRD.k_alpha[i]) + "\n")
                f.write("Distance=" + str(import_XRD.distance[i]) + "\n")
                f.write("------------------------------------------\n")
                f.write("NRow=" + str(nrow) + "\n")
                f.write("Center Row=" + str(center_row) + "\n")
                for j in range(nrow):
                    f.write(str(gamma_y[j]) + " ")
                f.write("\n")
                f.write("NCol=" + str(ncol) + "\n")
                f.write("Center Col=" + str(center_col) + "\n")
                for j in range(ncol):
                    f.write(str(twotheta_x[j]) + " ")
                f.write("\n")
                f.write("------------------------------------------\n")
                f.write("------------------------------------------\n")

                progress["value"] = progress["value"] + 1
                progress.update()

                for i in range(nrow):
                    f.write(" ".join(str(e) for e in data[i]))
                    f.write("\n")
            f.close()

    for widget in main.Frame1_2.winfo_children():
        widget.destroy()
    main.root.mainloop()
コード例 #28
0
class ServiceGroup(Frame):

    log = logController
    NameGroup = StringVar
    DelayTime = 1
    lbServiceGroupName = Label
    progressBarProcessing = Progressbar
    progressBarStyle = Style
    progressNumber = DoubleVar
    btStarGroup = Button
    imagebtStarGroup = PhotoImage
    btStopGroup = Button
    imagebtStopGroup = PhotoImage
    linhaDeSeparacao = PanedWindow
    OrganizerButtons = PanedWindow
    StyleServiceGroup = StylesInterface

    def __init__(self, *args, **kw):

        Frame.__init__(self, *args, **kw)

        self.NameGroup = StringVar()

        self.log = logController()

    def SetInformationGroup(self, name="", delay=0):

        self.NameGroup.set(name)
        self.DelayTime = delay

    def resource_path(self, relative_path):
        try:
            base_path = sys._MEIPASS
        except Exception:
            base_path = os.path.abspath("./icons")

        return os.path.join(base_path, relative_path)

    def AtuServices(self):

        serviceTool = win32.lib.win32serviceutil

        for service in self.winfo_children():

            if ('service' in service._name):

                StringMen = 'Atualizando Status do Serviço... ' + service.ServiceName

                self.log.consoleLogAdd(StringMen)

                Status = self.StringStatus(
                    serviceTool.QueryServiceStatus(service.ServiceName)[1])

                service.atuStatus(service.ServiceNameDisplay + "\n" + Status,
                                  Status)

    #Retorna a string de cada status do serviço
    def StringStatus(self, nService=0):

        if (nService == 1):
            return "STOPPED"
        elif (nService == 2):
            return "START PENDING"
        elif (nService == 3):
            return "STOP PENDING"
        elif (nService == 4):
            return "RUNNING"
        elif (nService == 5):
            return "CONTINUE PENDING"
        elif (nService == 6):
            return "PAUSE PENDING"
        elif (nService == 7):
            return "PAUSED"

    def ConfigComponents(self, NumberOfServices=0):

        self.lbServiceGroupName = Label(self)
        self.lbServiceGroupName["bg"] = "#616161"
        self.lbServiceGroupName["textvariable"] = self.NameGroup
        self.lbServiceGroupName["font"] = "Roboto 20"
        self.lbServiceGroupName["fg"] = "white"
        self.lbServiceGroupName.pack(pady=5)

        self.progressNumber = DoubleVar()
        self.progressBarStyle = Style()
        self.progressBarStyle.theme_use('clam')
        self.progressBarStyle.configure("Horizontal.TProgressbar",
                                        troughcolor='#616161',
                                        background="#34A853",
                                        lightcolor='#34A853',
                                        darkcolor="#34A853")
        self.progressBarProcessing = Progressbar(
            self,
            style="Horizontal.TProgressbar",
            variable=self.progressNumber,
            maximum=NumberOfServices)
        self.progressBarProcessing.pack(fill=X, padx=10, pady=10)

        self.OrganizerButtons = PanedWindow(self)
        self.OrganizerButtons["height"] = 80
        self.OrganizerButtons["bg"] = "#616161"
        self.OrganizerButtons.pack(fill=X, padx=10)

        self.btStarGroup = Button(self.OrganizerButtons,
                                  command=self.StartGroup)
        self.btStarGroup["bg"] = "#616161"
        self.btStarGroup["bd"] = 0
        self.btStarGroup["command"] = self.StartGroup
        self.imagebtStarGroup = PhotoImage(
            file=self.resource_path("btStartGroupIcon.png"))
        self.btStarGroup.config(image=self.imagebtStarGroup)
        self.btStarGroup.pack(fill=X, side=LEFT, padx=10)

        self.btStopGroup = Button(self.OrganizerButtons,
                                  command=self.StopGroup)
        self.btStopGroup["bg"] = "#616161"
        self.btStopGroup["bd"] = 0
        self.btStopGroup["command"] = self.StopGroup
        self.imagebtStopGroup = PhotoImage(
            file=self.resource_path("btStopGroupIcon.png"))
        self.btStopGroup.config(image=self.imagebtStopGroup)
        self.btStopGroup.pack(fill=X, side=LEFT, padx=5)

        self.linhaDeSeparacao = PanedWindow(self)
        self.linhaDeSeparacao["height"] = 2
        self.linhaDeSeparacao["bg"] = "#9E9E9E"
        self.linhaDeSeparacao.pack(fill=X, padx=20, pady=5)

    def StartGroup(self):

        taskStartServices = Thread(target=self.OptionRunGroup, args=[1])
        taskStartServices.start()

    def StopGroup(self):

        taskStopServices = Thread(target=self.OptionRunGroup, args=[2])
        taskStopServices.start()

    def OptionRunGroup(self, Tipo=0):

        self.progressNumber.set(0)

        for service in self.winfo_children():

            if ('service' in service._name):

                if (Tipo == 1):

                    service.StartService()

                    updProgress = Thread(target=self.updateProgress, args=[])
                    updProgress.start()

                    sleep(self.DelayTime)
                if (Tipo == 2):

                    service.StopService()

                    updProgress = Thread(target=self.updateProgress, args=[])
                    updProgress.start()

                    sleep(self.DelayTime)

        self.progressNumber.set(0)

    def updateProgress(self):

        self.progressNumber.set(self.progressNumber.get() + 1)
コード例 #29
0
class Window(Frame):
    def __init__(self, root=None):
        Frame.__init__(self, root)
        self.root = root
        self.root.title("Torrent")

        # ---- costanti controllo posizione ----
        self.larg_bottoni = 8
        self.imb_x = "3m"
        self.imb_y = "2m"
        self.imb_int_x = "3"
        self.imb_int_y = "1m"
        # ---- fine costanti di posizionamento ---

        self.pack(fill=BOTH, expand=1)
        self.createWidgets()
        self.file_aggiunti = []

    def createWidgets(self):

        ## creazione di un menu e sua aggiunta
        ## menu = Menu(self.root)
        # self.root.config(menu=menu)
        ## creazione di un oggetto file
        ## file = Menu(menu)
        ## associazione azione all'oggetto
        ## file.add_command(label="Exit", command=self.client_exit)
        ## aggiunta del file al menu
        ## menu.add_cascade(label="File", menu=file)

        ## quadro gestione tracker
        self.quadro_tracker = Frame(self, background="white", borderwidth=0, relief=RIDGE)
        self.quadro_tracker.pack(side=TOP, fill=BOTH, ipadx=self.imb_int_x, ipady=self.imb_int_y)

        ## quadro login logout
        self.quadro_login = Frame(self, background="white", borderwidth=0, relief=RIDGE)
        self.quadro_login.pack(side=TOP, fill=BOTH, ipadx=self.imb_int_x, ipady=self.imb_int_y)

        ## quadro centrale della ricerca
        self.quadro_centrale_ricerca = Frame(self, background="white", borderwidth=0, relief=RIDGE)
        self.quadro_centrale_ricerca.pack(side=TOP, fill=BOTH, ipadx=self.imb_int_x, ipady=self.imb_int_y)

        ## quadro centrale della ricerca
        self.quadro_centrale_file = Frame(self, background="white", borderwidth=0, relief=RIDGE)
        self.quadro_centrale_file.pack(side=TOP, fill=BOTH, ipadx=self.imb_int_x, ipady=self.imb_int_y)

        ## quadro con file caricati
        self.quadro_console = Frame(self, background="white", borderwidth=0, relief=RIDGE)
        self.quadro_console.pack(side=TOP, fill=BOTH, ipadx=self.imb_int_x, ipady=self.imb_int_y)

        ##----------------quadro modifica del tracker------------------------
        self.lb_tracker_ip4 = Label(self.quadro_tracker, text='IPv4 Tracker', background="white")
        self.lb_tracker_ip4.pack(side=LEFT, padx=self.imb_x, pady=self.imb_y)

        self.tracker_ip4 = StringVar()
        self.en_tracker_ip4 = Entry(self.quadro_tracker, textvariable=self.tracker_ip4, width=15)
        self.en_tracker_ip4.pack(side=LEFT, fill=BOTH, padx=self.imb_x, pady=self.imb_y)
        self.tracker_ip4.set(Utility.IPv4_TRACKER)

        self.lb_tracker_ip6 = Label(self.quadro_tracker, text='IPv6 Tracker', background="white")
        self.lb_tracker_ip6.pack(side=LEFT, padx=self.imb_x, pady=self.imb_y)

        self.tracker_ip6 = StringVar()
        self.en_tracker_ip6 = Entry(self.quadro_tracker, textvariable=self.tracker_ip6, width=35)
        self.en_tracker_ip6.pack(side=LEFT, fill=BOTH, padx=self.imb_x, pady=self.imb_y)
        self.tracker_ip6.set(Utility.IPv6_TRACKER)

        self.btn_tracker_config = Button(self.quadro_tracker, command=self.btn_conferma_config_click)
        self.btn_tracker_config.config(text="Conferma", width=self.larg_bottoni)
        self.btn_tracker_config.pack(side=RIGHT, padx=self.imb_x, pady=self.imb_y)

        ## ---------------aggiunta dei pulsanti di login e logout------------
        self.btn_login = Button(self.quadro_login, command=self.btn_login_click)
        self.btn_login.configure(text="LOGIN", width=self.larg_bottoni)
        self.btn_login.pack(side=LEFT, padx=self.imb_x, pady=self.imb_y)

        self.btn_logout = Button(self.quadro_login, command=self.btn_logout_click)
        self.btn_logout.configure(text="LOGOUT", width=self.larg_bottoni)
        self.btn_logout.pack(side=LEFT, padx=self.imb_x, pady=self.imb_y)

        self.status = StringVar()
        self.lb_status = Label(self.quadro_login, textvariable=self.status, background="white")
        self.lb_status.pack(side=RIGHT, padx=self.imb_x, pady=self.imb_y)
        self.status.set("STATUS")
        ## ------------------fine parte login logout -----------------------


        ##------------ quadri di divisione della ricerca e scaricamento-------------
        self.quadro_sinistro_ricerca = Frame(self.quadro_centrale_ricerca, background="white", borderwidth=0, relief=RIDGE)
        self.quadro_sinistro_ricerca.pack(side=LEFT, fill=BOTH, expand=1, ipadx = self.imb_int_x, ipady = self.imb_int_y, padx=self.imb_x, pady=self.imb_y)

        self.quadro_destro_ricerca = Frame(self.quadro_centrale_ricerca, background="white", borderwidth=0, relief=RIDGE,)
        self.quadro_destro_ricerca.pack(side=LEFT, fill=BOTH, expand =1, ipadx=self.imb_int_x, ipady=self.imb_int_y, padx=self.imb_x, pady=self.imb_y)

        ## inserimento widget di ricerca e scaricamento
        self.en_ricerca = Entry(self.quadro_sinistro_ricerca)
        self.en_ricerca.pack(side=TOP, fill=BOTH, padx=self.imb_x, pady=self.imb_y)

        self.btn_ricerca = Button(self.quadro_sinistro_ricerca, command=self.btn_ricerca_click)
        self.btn_ricerca.configure(text="RICERCA", width=self.larg_bottoni)
        self.btn_ricerca.pack(side=TOP, padx=self.imb_x, pady=self.imb_y)

        self.var_progresso = StringVar()
        self.lb_progresso = Label(self.quadro_sinistro_ricerca, textvariable=self.var_progresso, background="white")
        self.lb_progresso.pack(fill=BOTH, side=TOP, padx=self.imb_x, pady=self.imb_y)
        self.var_progresso.set('Progresso Scaricamento')

        self.prog_scaricamento = Progressbar(self.quadro_sinistro_ricerca, orient='horizontal', mode='determinate')
        self.prog_scaricamento.pack(side=TOP, fill=BOTH, padx=self.imb_x, pady=self.imb_y)

        ## inserimento listbox dei risultati della ricerca e bottone scarica dalla selezione
        self.list_risultati = Listbox(self.quadro_destro_ricerca)
        self.list_risultati.pack(side=TOP, fill=BOTH, pady=self.imb_y)

        self.btn_scarica = Button(self.quadro_destro_ricerca, command=self.btn_scarica_click)
        self.btn_scarica.configure(text="SCARICA", width=self.larg_bottoni)
        self.btn_scarica.pack(side=TOP)
        ##--------------- fine parte della ricerca scaricamento -------------------


        ##---------------- parte di aggiunta dei file -----------------------------
        ## quadri di divisione per l'aggiunta
        self.quadro_sinistro_file = Frame(self.quadro_centrale_file, background="white", borderwidth=0, relief=RIDGE)
        self.quadro_sinistro_file.pack(side=LEFT, fill=BOTH, expand=1, ipadx=self.imb_int_x, ipady=self.imb_int_y,padx=self.imb_x, pady=self.imb_y)

        self.quadro_destro_file = Frame(self.quadro_centrale_file, background="white", borderwidth=0, relief=RIDGE)
        self.quadro_destro_file.pack(side=LEFT, fill=BOTH, expand=1, ipadx=self.imb_int_x, ipady=self.imb_int_y,padx=self.imb_x, pady=self.imb_y)

        self.lb_file = Label(self.quadro_sinistro_file, text='Gestione dei File', background="white")
        self.lb_file.pack(side=TOP, padx=self.imb_x, pady=self.imb_y)

        self.btn_aggiungi_file = Button(self.quadro_sinistro_file, command=self.btn_aggiungi_file_click)
        self.btn_aggiungi_file.configure(text="AGGIUNGI", width=self.larg_bottoni)
        self.btn_aggiungi_file.pack(side=TOP, padx=self.imb_x, pady=self.imb_y)

        self.btn_rimuovi_file = Button(self.quadro_sinistro_file, command=self.btn_rimuovi_file_click)
        self.btn_rimuovi_file.configure(text="RIMUOVI", width=self.larg_bottoni)
        self.btn_rimuovi_file.pack(side=TOP, padx=self.imb_x, pady=self.imb_y)

        self.list_file = Listbox(self.quadro_destro_file)
        self.list_file.pack(side=TOP, fill=BOTH, pady=self.imb_y)
        ##---------------- fine parte gestione dei file ---------------------------

        ##---------------- parte di console per le scritture eventuali-------------
        self.text_console = Text(self.quadro_console, state=NORMAL)
        self.text_console.pack(side=TOP, fill=BOTH)
        ##---------------- fine della parte di console ----------------------------

    def btn_conferma_config_click(self):
        Utility.IPv4_TRACKER = self.tracker_ip4.get()
        Utility.IPv6_TRACKER = self.tracker_ip6.get()
        Utility.IP_TRACKER = Utility.IPv4_TRACKER + "|" + Utility.IPv6_TRACKER
        self.print_console('aggiornamento tracker ip4: ' + self.tracker_ip4.get())
        self.print_console('aggiornamento tracker ip6: ' + self.tracker_ip6.get())

    def print_console(self, mess):
        self.text_console.insert(END,mess+'\n')

    ## evento bottone connessione
    def btn_login_click(self):

        try:
            sock_end = Request.create_socket(Utility.IP_TRACKER, Utility.PORT_TRACKER)
            Request.login(sock_end)
            Utility.sessionID = Response.login_ack(sock_end)
            Response.close_socket(sock_end)
            # creazione della cartella temporanea
            try:
                os.stat(Utility.PATHTEMP)
                shutil.rmtree(Utility.PATHTEMP)
            except FileNotFoundError as e:
                pass
            finally:
                os.mkdir(Utility.PATHTEMP)

            if Utility.sessionID != None:
                self.status.set("SEI LOGGATO come " + Utility.sessionID)
                self.print_console('LOGIN effettuato a ' + Utility.IP_TRACKER)
            else:
                self.status.set('SEI DISCONNESSO')
                self.print_console("LOGIN fallita")
        except Exception as e:
            logging.debug(e)

    ## evento bottone disconnessione
    def btn_logout_click(self):
        try:
            sock_end = Request.create_socket(Utility.IP_TRACKER, Utility.PORT_TRACKER)
            Request.logout(sock_end)
            success, n_part = Response.logout_ack(sock_end)
            Response.close_socket(sock_end)

            # se si e' sconnesso
            if success:
                self.status.set('DISCONNESSO - PARTI POSSEDUTE: ' + n_part)
                logging.debug('DISCONNESSO - PARTI POSSEDUTE: ' + n_part)

                ## si rimuove la cartella temporanea, i file
                ## e le parti dal database associate
                Utility.database.removeAllFileForSessionId(Utility.sessionID)
                Utility.sessionID = ''
                ## aggionamento lista con le rimozioni
                self.file_aggiunti.clear()
                self.list_file.delete(0,END)

                try:
                    shutil.rmtree(Utility.PATHTEMP)
                except Exception as e:
                    logging.debug('cartella non esistente')

            ## altrimenti rimane connesso
            else:
                self.status.set('FALLIMENTO DISCONNESSIONE - PARTI SCARICATE: ' + n_part)
                logging.debug('Disconnessione non consentita hai della parti non scaricate da altri')
                self.print_console('Disconnessione non consentita hai della parti non scaricate da altri')
        except Exception as e:
            logging.debug(e)

    def btn_aggiungi_file_click(self):

        if Utility.sessionID != '':
            path_file = askopenfilename(initialdir=Utility.PATHDIR)
            # controllo se il database ha gia' il file

            if path_file != '':
                result = Utility.database.findFile(Utility.sessionID, Utility.generateMd5(path_file), None, 1)

                if len(result) == 0:
                    sock_end = Request.create_socket(Utility.IP_TRACKER, Utility.PORT_TRACKER)
                    Request.add_file(sock_end, path_file)
                    num_parts = Response.add_file_ack(sock_end)
                    Response.close_socket(sock_end)

                    if num_parts != None:
                        md5_file = Utility.generateMd5(path_file)
                        file_name = path_file.split('/')[-1]
                        elem = (md5_file, file_name, num_parts)

                        ## aggiornamento database ocn l'aggiunta del file e delle parti
                        Utility.database.addFile(Utility.sessionID, file_name, md5_file, os.stat(path_file).st_size,Utility.LEN_PART)
                        Utility.database.addPart(md5_file, Utility.sessionID, '1' * int(num_parts))

                        Divide.Divider.divide(Utility.PATHDIR, Utility.PATHTEMP, file_name, Utility.LEN_PART)

                        self.file_aggiunti.append(elem)
                        self.list_file.insert(END, file_name)

                        self.print_console('elemento aggiunto: ' + str(elem))
                        logging.debug('aggiunto: ' + path_file)
                else:
                    self.print_console('file già presente nella condivisione')
            else:
                self.print_console('file non selezionato')
        else:
            self.print_console('Non puoi aggiungere se non sei connesso al tracker')

    def btn_ricerca_click(self):
        try:
            if Utility.sessionID!= '':
                logging.debug("STAI CERCANDO: " + self.en_ricerca.get())
                # prendo il campo di ricerca
                serch=self.en_ricerca.get().strip(' ')
                # Creo la socket di connessione al tracker
                sock = Request.create_socket(Utility.IP_TRACKER, Utility.PORT_TRACKER)
                # Invio richiesta look
                Request.look(sock, Utility.sessionID, serch)
                # Azzero la ricerca precedente
                Utility.listLastSearch=[]
                # Rimuovo la lista dei file scaricati
                self.list_risultati.delete(0,END)
                # Leggo la ALOO
                # Popolo la lista globale con i risultati dell'ultima ricerca
                self.risultati,Utility.listLastSearch = Response.look_ack(sock)
                Response.close_socket(sock)

                # inserisco tutti gli elementi della lista nella lista nel form
                for value in self.risultati:
                    self.list_risultati.insert(END, value[1])
            else:
                self.print_console('Non puoi ricercare se non sei collegato')
        except Exception as e:
            logging.debug(e)

    def btn_scarica_click(self):
        try:
            # Todo da testare in locale prima
            # indice elemento da scaricare
            index = self.list_risultati.curselection()[0]
            logging.debug("selezionato: " + str(self.risultati[index]))
            # prendo l'elemento da scaricare
            info = Utility.listLastSearch[index]
            #Classe che esegue il download di un file
            md5_selected = self.risultati[index][0]
            result = Utility.database.findFile(Utility.sessionID, md5_selected, None, 1)
            if len(result) == 0:
                down=Scaricamento(self.prog_scaricamento, self.var_progresso, self.file_aggiunti, self.list_file, info)
                down.start()
            else:
                self.print_console('hai già questo file! ')
        except Exception as e:
            logging.debug("NULLA SELEZIONATO:  " + str(e))

    def btn_rimuovi_file_click(self):
        try:
            index = self.list_file.curselection()[0]
            del self.file_aggiunti[index]
            self.list_file.delete(index, index)
            logging.debug("rimosso: " + str(index))
        except Exception as e:
            logging.debug("NULLA SELEZIONATO")
コード例 #30
0
ファイル: gui.py プロジェクト: parth-singh71/yt-downloader
class GUI():
    def __init__(self):
        self.is_playlist = False
        # creating window
        self.window = tk.Tk()
        # getting screen width and height of display
        self.width = self.window.winfo_screenwidth()
        self.height = self.window.winfo_screenheight()
        # setting tkinter window size
        self.window.geometry("%dx%d" % (self.width // 4, self.height // 3))
        self.window.title('YTDownloader')
        self.label = tk.Label(
            self.window,
            text="Paste a YouTube video link or a Playlist link to download!",
            wraplength=(self.width // 4) - 20
        )
        self.textbox = tk.Text(
            self.window,
            height=5,
            width=50
        )
        self.var1 = tk.IntVar()
        self.playlist_checkbox = tk.Checkbutton(
            self.window,
            text='Playlist',
            variable=self.var1,
            onvalue=1,
            offvalue=0,
            command=self.update_is_playlist
        )
        self.video_info_label = tk.Label(
            self.window,
            text="",
            wraplength=(self.width // 4) - 20
        )
        self.progress = Progressbar(
            self.window,
            orient=tk.HORIZONTAL,
            length=100,
            mode='determinate'
        )
        self.button = tk.Button(
            self.window,
            text='Download',
            width=25,
            command=self.download
        )
        self.completion_label = tk.Label(
            self.window,
            text="",
            wraplength=(self.width // 4) - 20
        )
        self.build()

    def build(self):
        self.label.pack()
        self.textbox.pack()
        self.playlist_checkbox.pack()
        self.progress.pack()
        self.video_info_label.pack()
        self.button.pack()
        self.completion_label.pack()
        self.window.mainloop()

    def on_progress_callback(self, stream, data_chunk, rem_bytes):
        # print(stream.filesize, rem_bytes)
        percent_remaining = int(
            ((stream.filesize - rem_bytes) / stream.filesize) * 100)
        print(percent_remaining)
        self.progress['value'] = percent_remaining
        self.video_info_label['text'] = stream.title
        self.window.update_idletasks()

    def on_complete_callback(self, stream, file_path):
        print(file_path)
        self.completion_label['text'] = f"Downloaded at location: {file_path}"
        self.window.update_idletasks()

    def download(self):
        link = self.textbox.get("1.0", 'end-1c')
        if self.is_playlist:
            downloader = PlaylistDownloader(
                link=link,
                on_progress_callback=self.on_progress_callback,
                on_complete_callback=self.on_complete_callback,
            )
        else:
            downloader = VideoDownloader(
                link=link,
                on_progress_callback=self.on_progress_callback,
                on_complete_callback=self.on_complete_callback,
            )
        downloader.download()

    def update_is_playlist(self):
        val = self.var1.get()
        if val == 0:
            self.is_playlist = False
        else:
            self.is_playlist = True
コード例 #31
0
ファイル: list box ikinci.py プロジェクト: bbbirkan/phyton
def Accept_movie():
    global label_show_choose
    global imbd
    global imbd_number
    global error_label
    global progress
    global label_loading

    label_show_choose.destroy()
    error_label.destroy()
    progress.destroy()
    label_loading.destroy()

    try:
        index_second_list = movie_choose_list.index(
            movie_choose_list.curselection()) + 1
        temp[temp.get(index_second_list)] = imbd
        imbd_number_more = temp.get(index_second_list)
        you_choose = str(
            movie_choose_list.get(movie_choose_list.curselection()))
    except:
        error_label = Label(root,
                            text="Choose your movie from left side list! ",
                            fg="gray22")
        error_label.pack()

    try:
        label_show_choose = Label(frame_progress, text=you_choose, fg="gray22")
        imbd_number = imbd_number_more
    except (TypeError):
        label_show_choose = Label(frame_progress, text=you_choose, fg="gray22")
    #print(imbd_number)
    label_show_choose.pack()

    movie_Search_list.config(state=DISABLED)
    movie_choose_list.config(state=DISABLED)
    buton_accept.config(state=DISABLED)
    # --------Progress------------
    progress = Progressbar(frame_progress,
                           orient=HORIZONTAL,
                           length=200,
                           mode='determinate')
    progress.pack()
    label_loading = Label(frame_progress, text="Loading..!", fg="gray22")
    label_loading.pack()

    def Progress_fonction():
        progress['value'] = 5

        # DO SOMETHING
        # -------------
        def Opensubtitle_Download(imdb_id):
            global saved_file_name
            alldata = {}
            url = "https://www.opensubtitles.com/api/v1/login"
            headers = {
                'api-key': 'JCa5AqZVFIqhxKTZlg4KGE4LftaUA5Mu',
                'content-type': 'application/json'
            }
            user = {'username': '******', 'password': "******"}

            try:
                login_response = requests.post(url,
                                               data=json.dumps(user),
                                               headers=headers)
                login_response.raise_for_status()
                login_json_response = login_response.json()
                login_token = login_json_response['token']
            except:
                print("Something wrong check again...")

            headers = {
                'Api-Key': 'JCa5AqZVFIqhxKTZlg4KGE4LftaUA5Mu',
            }
            params = (('imdb_id', imdb_id), )
            query_response = requests.get(
                'https://www.opensubtitles.com/api/v1/subtitles?',
                params=params,
                headers=headers)
            query_json_response = query_response.json()
            print("Report:", query_response)
            # pprint(query_json_response)# All data here...
            try:
                query_file_name = query_json_response['data'][0]['attributes'][
                    'files'][0]['file_name']
                query_file_no = query_json_response['data'][0]['attributes'][
                    'files'][0]['file_id']
                movie_img = query_json_response['data'][0]['attributes'][
                    'related_links']['img_url']
            except:
                query_file_name = "N/A"
                query_file_no = "N/A"
                movie_img = "N/A"

            while True:
                if query_file_no != "N/A":
                    print("Movie Image url:", movie_img)
                    print("File Number:", query_file_no)
                    print("Subtile File Name:", query_file_name)

                    Location_folder(main_l)  # Main Location Folder
                    Location_folder("movie")  # Enter Movie folder inside

                    from PIL import Image
                    ImgRequest = requests.get(movie_img)
                    img = open("temp.jpg", "wb")
                    img.write(ImgRequest.content)
                    img.close()
                    img = Image.open("temp.jpg")
                    img.show()

                    download_url = "https://www.opensubtitles.com/api/v1/download"
                    download_headers = {
                        'api-key': 'JCa5AqZVFIqhxKTZlg4KGE4LftaUA5Mu',
                        'authorization': login_token,
                        'content-type': 'application/json'
                    }

                    download_file_id = {'file_id': query_file_no}
                    download_response = requests.post(
                        download_url,
                        data=json.dumps(download_file_id),
                        headers=download_headers)
                    download_json_response = download_response.json()
                    #pprint(query_json_response)# All data here...**********************************************8
                    print('Beginning file download with requests')
                    print("Report:", download_response)

                    link = download_json_response['link']
                    saved_file_name = "subtitle.srt"
                    r = requests.get(link)
                    with open(saved_file_name, 'wb') as f:
                        f.write(r.content)
                    left = download_json_response['remaining']
                    print("Subtitle File Downloaded")
                    print("How many request left:", left)

                    alldata[imbd_id] = {
                        "title": movie_last_name,
                        "image": str(movie_img),
                        "subtitle": str(r.content)
                    }

                    Location_folder(main_l)  # Main Location Folder
                    Location_folder("json_data")  # Enter Movie folder inside

                    with open("Subtitle.json", "r") as jsonFile:
                        mergee = json.load(jsonFile)
                    merge_dic = {**alldata, **mergee}  # merge 2 dictionary

                    with open("Subtitle.json", 'w', encoding='utf8') as f3:
                        json.dump(merge_dic, f3, ensure_ascii=False, indent=1)
                    Location_folder(main_l)  # Main Location Folder
                    Location_folder("movie")  # Enter Movie folder inside
                    break
                else:
                    print("Done! with the error")
                    saved_file_name = "0"
                    break

        # -------------
        progress['value'] = 100
        label_show_choose.config(text="Done")
        time.sleep(2)

        frame_progress.destroy()
        frame_choose_buton.destroy()
        frame_Search.destroy()
        frame_secondlist.destroy()

        Entry_search_movie.destroy()
        movie_Search_list.destroy()
        search_movie_label.destroy()
        movie_choose_list.destroy()
        search_movie_scroll.destroy()
        label_show_choose.destroy()
        progress.destroy()

        frame_LIST.destroy()
        frame_Search.destroy()
        frame_choose_buton.destroy()
        frame_secondlist.destroy()
        frame_progress.destroy()
        frame_info = Frame(height=1000, width=940)
        frame_info.pack()

    threading.Thread(target=Progress_fonction).start()
    # --------------------------------
    return imbd_number
コード例 #32
0
def export_all_fit_data(main_calcul, calib_2D, main):
    f = asksaveasfile(title="Export data",
                      mode='w',
                      defaultextension=".text",
                      filetypes=[('text files', '.txt'), ('all files', '.*')])
    if f is not None and f is not '':
        for widget in main.Frame1_2.winfo_children():
            widget.destroy()
        Label(main.Frame1_2, text="Export").pack(side=LEFT)
        progress = Progressbar(main.Frame1_2,
                               orient="horizontal",
                               mode='determinate')
        progress.pack(side=LEFT)
        progress["value"] = 0
        progress["maximum"] = len(main_calcul.phi) * main_calcul.gamma_number

        for nimage in range(len(main_calcul.phi)):
            for i_graph in range(main_calcul.gamma_number):
                progress["value"] = progress["value"] + 1
                progress.update()

                i = calib_2D.nimage * main_calcul.gamma_number + i_graph
                j_start = int(main_calcul.gamma_f_index +
                              i_graph * main_calcul.gamma_step)
                j_end = int(main_calcul.gamma_f_index +
                            (i_graph + 1) * main_calcul.gamma_step)

                f.write("Phi=" + str(main_calcul.phi[nimage]) + "°\n")
                f.write("Chi=" + str(main_calcul.chi[nimage]) + "°\n")
                f.write("Omega=" + str(main_calcul.omega[nimage]) + "°\n")
                f.write("peak position=" + str(main_calcul.peaks_position[i]) +
                        "° +/- " + str(main_calcul.error_peaks_position[i]) +
                        "°\n")
                f.write("FWHM=" + str(main_calcul.FWHM[i]) + "° +/- " +
                        str(main_calcul.error_FWHM[i]) + "°\n")
                f.write("Peak intensity=" +
                        str(main_calcul.peak_intensity[i]) + " +/- " +
                        str(main_calcul.error_peak_intensity[i]) + "\n")
                f.write("a=" + str(main_calcul.a[i]) + "\n")
                f.write("r=" + str(main_calcul.r[i]) + "\n")
                f.write("gamma integrate from " +
                        str(int(main_calcul.gamma_y[j_start])) + "° to " +
                        str(int(main_calcul.gamma_y[j_end])) + "°\n")
                f.write(" two_theta(°)\t")
                f.write("instensity\t")
                f.write("background\t")
                f.write("substrat_background\t")
                f.write("   I_kalpha1\t")
                f.write("   I_kalpha2\t")
                f.write("I_Pearson_VII fit\t")
                f.write("\n")

                for j in range(len(main_calcul.data_x_limit)):
                    try:
                        f.write(str(main_calcul.data_x_limit[j]) + "\t")
                        f.write(str(main_calcul.data_y_limit[i][j]) + "\t")
                        f.write(
                            str(main_calcul.data_y_background_fit[i][j]) +
                            "\t")
                        f.write(str(main_calcul.data_y_net[i][j]) + "\t")
                        f.write(str(main_calcul.data_y_k1_fit[i][j]) + "\t")
                        f.write(str(main_calcul.data_y_k2_fit[i][j]) + "\t")
                        f.write(str(main_calcul.data_y_fit_total[i][j]) + "\t")
                        f.write("\n")
                    except (IndexError, ValueError):
                        pass
                f.write("--------------------------------------\n")
                f.write("--------------------------------------\n")
        f.close()
        for widget in main.Frame1_2.winfo_children():
            widget.destroy()
    main.root.mainloop()
コード例 #33
0
class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.filename = ""
        self.output = ""
        self.cert = ""
        self.font = ""
        self.fontsize = 48
        self.pack()
        self.create_widgets()

    def create_widgets(self):

        #csv button
        self.csv = tk.Button(self, width=40, height=2)
        self.csv["text"] = "Select csv file"
        self.csv["command"] = self.get_file_name
        self.csv.pack(side="top")

        #output button
        self.out = tk.Button(self, width=40, height=2)
        self.out["text"] = "Select folder output"
        self.out["command"] = self.set_output
        self.out.pack()

        #Font button
        self.font_btn = tk.Button(self, width=40, height=2)
        self.font_btn["text"] = "Select Font Family"
        self.font_btn["command"] = self.get_font
        self.font_btn.pack()

        #Cert button
        self.cert_btn = tk.Button(self, width=40, height=2)
        self.cert_btn["text"] = "Select Certificate form"
        self.cert_btn["command"] = self.get_cert
        self.cert_btn.pack()

        #Generate button
        self.gen = tk.Button(self, width=40, height=2)
        self.gen["text"] = "Generate Certs"
        self.gen["command"] = self.gen_cert
        self.gen.pack()

        #Progress bar
        self.progress = Progressbar(root,
                                    orient=tk.HORIZONTAL,
                                    length=200,
                                    mode='determinate')
        self.progress.pack()

    def get_file_name(self):
        self.filename = filedialog.askopenfilename(
            initialdir=".",
            title="Select file",
            filetypes=(("csv files", "*.csv"), ("all files", "*.*")))
        self.csv.configure(bg="green")
        self.csv.configure(fg="white")
        root.update_idletasks()

    def set_output(self):
        self.output = filedialog.askdirectory(initialdir=".",
                                              title="Select Directory")
        self.out.configure(bg="green")
        self.out.configure(fg="white")

    def get_font(self):
        self.font = filedialog.askopenfilename(
            initialdir=".",
            title="Select file",
            filetypes=(("TTF files", "*.ttf"), ("OTF files", "*.otf"),
                       ("all files", "*.*")))
        self.font_btn.configure(bg="green")
        self.font_btn.configure(fg="white")

    def get_cert(self):
        self.cert = filedialog.askopenfilename(
            initialdir=".",
            title="Select file",
            filetypes=(("PNG files", "*.png"), ("all files", "*.*")))
        self.cert_btn.configure(bg="green")
        self.cert_btn.configure(fg="white")

    def gen_cert(self):

        if (os.path.exists(self.output) == False):
            try:
                os.makedirs(self.output)
            except:
                print('  ** ERROR: Can NOT make the output folder. Exit.',
                      file=sys_stderr)
                exit(1)

        if (os.path.isdir(self.output) == False):
            print('  ** ERROR: "{0}" is not a folder. Exit.'.format(
                self.output),
                  file=sys_stderr)
            exit(1)

        colorhex = "000000".lstrip('#')
        color_tuple = tuple(int(colorhex[i:i + 2], 16) for i in (0, 2, 4))
        ppl = list()  # [('name', 'email'), ('name', 'email')]
        csv_to_dict(ppl, self.filename)
        count = 0
        print('Processing...')
        f = open(self.filename)
        num = len(f.readlines())
        for person in ppl:
            try:
                out_cert = os.path.join(
                    self.output, '{0}+{1}+{2}.pdf'.format(
                        os.path.splitext(self.cert)[0].split('/')[-1],
                        person[0], person[1]))
                if ((False == False) and (os.path.exists(out_cert) == True)):
                    print('\n  ** WARNING: The path for output "{0}" exists.'.
                          format(out_cert),
                          file=sys_stderr)
                    q = str(input('  >> Replace the file? [Y or N] (N): ')
                            ).strip().lower()
                    if (q != 'y'):
                        continue
                # make_person_cert(name, email, cert_img, out_cert, fontfile, fontsize, color_tuple, x, y)
                r = make_person_cert(person[0], person[1], self.cert, out_cert,
                                     self.font, self.fontsize, color_tuple,
                                     None, None)
                if (r == True):
                    print('{0}  -  {1}'.format(person[0], person[1]))
                    count += 1
                    self.progress['value'] = self.progress['value'] + (
                        count * 100 / num)
                    root.update_idletasks()
            except:
                print('  ** ERROR: With [{0}, {1}]. Exit.'.format(
                    person[0], person[1]),
                      file=sys_stderr)
                exit(1)

        print('\nTotal of "{0}" files made in "{1}".'.format(
            count, self.output))
コード例 #34
0
ファイル: singlesyn.py プロジェクト: xialulee/WaveSyn
class OptimizeGroup(Group):
    def __init__(self, *args, **kwargs):
        self._app = kwargs.pop('wavesyn_root')   
        self.__topwin = kwargs.pop('topwin')

        super().__init__(*args, **kwargs)
                
        parameter_frame    = Frame(self)
        parameter_frame.pack(side='left', expand='yes', fill='y')
        self.__num = LabeledEntry(parameter_frame)
        set_attributes(self.__num,
            label_text   = 'num',
            entry_text   = '1',
            label_width  = 5,
            entry_width  = 8,
            checker_function   = self._app.gui.value_checker.check_int
        )
        self.__num.entry.bind('<Return>', lambda event: self._on_solve_click())
        self.__num.pack(side='top')

        self.__pci  = LabeledEntry(parameter_frame)
        set_attributes(self.__pci,
            label_text   = 'PCI',
            entry_text   = '100',
            label_width  = 5,
            entry_width  = 8,
            checker_function = self._app.gui.value_checker.check_int
        )
        self.__pci.pack(side='top')
        
        self.__parallel_checker_variable    = IntVar()
        self.__parallel_checker  = Checkbutton(parameter_frame, text="Parallel", variable=self.__parallel_checker_variable, command=self._on_parallel_checker_click)
        self.__parallel_checker.pack()
        
        progfrm = Frame(self)
        progfrm.pack(side='left', expand='yes', fill='y')

        self.__genbtn = Button(progfrm, text='Generate', command=self._on_solve_click)
        self.__genbtn.pack(side='top')  
        Button(progfrm, text='Stop', command=self._on_stop_button_click).pack(side='top')         
        
        self.__progressbar_variable = IntVar()
        self.__finishedwav = IntVar()        
        self.__progressbar = Progressbar(progfrm, orient='horizontal', variable=self.__progressbar_variable, maximum=100)
        self.__progressbar.pack(side='left')
        self.__progressbar.config(length=55)   
        self.__finishedwavbar = Progressbar(progfrm, orient='horizontal', variable=self.__finishedwav)
        self.__finishedwavbar.pack(side='left')
        self.__finishedwavbar.config(length=30)  

        self.name = 'Generate'

        self.getparams = None
        self.__stopflag = False

        
    def _on_solve_click(self):
        params = self.__topwin.parameter_group.get_parameters()
        repeat_times = self.__num.get_int()   
        
        if self.__parallel_checker_variable.get():
            run = self.__topwin.current_algorithm.process_run
        else:
            run = self.__topwin.current_algorithm.thread_run
        with code_printer():
            run(on_finished=['store', 'plot'], progress_indicator='progress_dialog', repeat_times=repeat_times, **params)


    def _on_stop_button_click(self):
        self.__stopflag = True
        
        
    def _on_parallel_checker_click(self):
        topwin = self.__topwin
        if topwin.current_algorithm.need_cuda:
            self.__parallel_checker_variable.set(0)
            topwin.root_node.gui.dialogs.report(f'''{topwin.node_path}:
Current algorithm "{topwin.current_algorithm.meta.name}" need CUDA worker, which does not support multi-cpu parallel.
            ''')
            
            
    def _cancel_parallel(self):
        self.__parallel_checker_variable.set(0)
コード例 #35
0
def export_all_stress_data(calib_2D, main_calcul, stress_calcul, main):
    f = asksaveasfile(title="Export data",
                      mode='w',
                      defaultextension=".text",
                      filetypes=[('text files', '.txt'), ('all files', '.*')])
    if f is not None and f is not '':
        for widget in main.Frame1_2.winfo_children():
            widget.destroy()
        Label(main.Frame1_2, text="Export").pack(side=LEFT)
        progress = Progressbar(main.Frame1_2,
                               orient="horizontal",
                               mode='determinate')
        progress.pack(side=LEFT)
        progress["value"] = 0
        progress["maximum"] = len(stress_calcul.phi) + 2

        if stress_calcul.stress_valid >= 1:
            f.write("SIN2PSI METHOD\n")
            for i in range(len(stress_calcul.liste_phi)):
                f.write("Phi= " + str(stress_calcul.liste_phi[i]) + "°")
                f.write("Linear fit: " + "sigma= " +
                        str(stress_calcul.sigma_phi_linear[i]) + "+/-" +
                        str(stress_calcul.error_sigma_phi_linear[i]) + "MPa" +
                        "\n")
                f.write("Elliptic fit: " + "sigma= " +
                        str(stress_calcul.sigma_phi_elliptic[i]) + "+/-" +
                        str(stress_calcul.error_sigma_phi_elliptic[i]) +
                        "MPa" + "\n")
                f.write("Elliptic fit: " + "shear= " +
                        str(stress_calcul.shear_phi_elliptic[i]) + "+/-" +
                        str(stress_calcul.error_shear_phi_elliptic[i]) +
                        "MPa" + "\n")
                f.write("-------------------\n")
        f.write("---------------------------------------------------- \n")
        f.write("---------------------------------------------------- \n")

        progress["value"] = progress["value"] + 1
        progress.update()
        f.write("FUNDAMENTAL METHOD \n")
        if len(stress_calcul.liste_phi
               ) == 1 and stress_calcul.length_strain >= 2:
            f.write("---Uniaxial stress----- \n")
            f.write('sigma = ' +
                    str('%0.1f' % stress_calcul.sigma_phi_uniaxial[0]) +
                    "+/-" +
                    str('%0.1f' % stress_calcul.error_sigma_phi_uniaxial[0]) +
                    "MPa" + "\n")

        if len(stress_calcul.liste_phi
               ) == 1 and stress_calcul.length_strain >= 3:
            f.write("---Uniaxial+Shear stress----- \n")
            f.write('sigma = ' +
                    str('%0.1f' % stress_calcul.sigma_phi_uniaxial_shear[0]) +
                    "+/-" +
                    str('%0.1f' %
                        stress_calcul.error_sigma_phi_uniaxial_shear[0]) +
                    "MPa" + "\n")
            f.write('shear = ' +
                    str('%0.1f' % stress_calcul.shear_phi_uniaxial_shear[0]) +
                    "+/-" +
                    str('%0.1f' %
                        stress_calcul.error_shear_phi_uniaxial_shear[0]) +
                    "MPa" + "\n")

        if len(stress_calcul.liste_phi
               ) >= 2 and stress_calcul.length_strain == 3:
            f.write("---Biaxial stress----- \n")
            f.write('sigma 11 = ' + str(stress_calcul.tensor_biaxial[0][0]) +
                    "+/-" + str(stress_calcul.tensor_biaxial[1][0, 0]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 22 = ' + str(stress_calcul.tensor_biaxial[0][1]) +
                    "+/-" + str(stress_calcul.tensor_biaxial[1][1, 1]**0.5) +
                    "MPa" + "\n")
            f.write("---------------------- \n")

        if len(stress_calcul.liste_phi
               ) >= 2 and stress_calcul.length_strain >= 4:
            f.write("---Biaxial stress----- \n")
            f.write('sigma 11 = ' + str(stress_calcul.tensor_biaxial[0][0]) +
                    "+/-" + str(stress_calcul.tensor_biaxial[1][0, 0]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 22 = ' + str(stress_calcul.tensor_biaxial[0][2]) +
                    "+/-" + str(stress_calcul.tensor_biaxial[1][2, 2]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 12 = sigma 21 = ' +
                    str(stress_calcul.tensor_biaxial[0][1]) + "+/-" +
                    str(stress_calcul.tensor_biaxial[1][1, 1]**0.5) + "MPa" +
                    "\n")
            f.write("---------------------- \n")

        if len(stress_calcul.liste_phi
               ) >= 2 and stress_calcul.length_strain == 5:
            f.write("---Biaxial+shear stress----- \n")
            f.write('sigma 11 = ' +
                    str(stress_calcul.tensor_biaxial_shear[0][0]) + "+/-" +
                    str(stress_calcul.tensor_biaxial_shear[1][0, 0]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 22 = ' +
                    str(stress_calcul.tensor_biaxial_shear[0][1]) + "+/-" +
                    str(stress_calcul.tensor_biaxial_shear[1][1, 1]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 13 = sigma 31 = ' +
                    str(stress_calcul.tensor_biaxial_shear[0][2]) + "+/-" +
                    str(stress_calcul.tensor_biaxial_shear[1][2, 2]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 23 = sigma 32 = ' +
                    str(stress_calcul.tensor_biaxial_shear[0][3]) + "+/-" +
                    str(stress_calcul.tensor_biaxial_shear[1][3, 3]**0.5) +
                    "MPa" + "\n")
            f.write("---------------------- \n")

        if len(stress_calcul.liste_phi
               ) >= 2 and stress_calcul.length_strain >= 6:
            f.write("---Biaxial+shear stress----- \n")
            f.write('sigma 11 = ' +
                    str(stress_calcul.tensor_biaxial_shear[0][0]) + "+/-" +
                    str(stress_calcul.tensor_biaxial_shear[1][0, 0]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 22 = ' +
                    str(stress_calcul.tensor_biaxial_shear[0][2]) + "+/-" +
                    str(stress_calcul.tensor_biaxial_shear[1][2, 2]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 12 = sigma 12 = ' +
                    str(stress_calcul.tensor_biaxial_shear[0][1]) + "+/-" +
                    str(stress_calcul.tensor_biaxial_shear[1][1, 1]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 13 = sigma 31 = ' +
                    str(stress_calcul.tensor_biaxial_shear[0][3]) + "+/-" +
                    str(stress_calcul.tensor_biaxial_shear[1][3, 3]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 23 = sigma 32 = ' +
                    str(stress_calcul.tensor_biaxial_shear[0][4]) + "+/-" +
                    str(stress_calcul.tensor_biaxial_shear[1][4, 4]**0.5) +
                    "MPa" + "\n")
            f.write("---------------------- \n")

        if len(stress_calcul.liste_phi
               ) >= 3 and stress_calcul.length_strain >= 6:
            f.write("---Triaxial stress----- \n")
            f.write('sigma 11 = ' + str(stress_calcul.tensor_triaxial[0][0]) +
                    "+/-" + str(stress_calcul.tensor_triaxial[1][0, 0]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 22 = ' + str(stress_calcul.tensor_triaxial[0][2]) +
                    "+/-" + str(stress_calcul.tensor_triaxial[1][2, 2]**0.5) +
                    "MPa" + "\n")
            f.write('sigma 12 = sigma 21 = ' +
                    str(stress_calcul.tensor_triaxial[0][1]) + "+/-" +
                    str(stress_calcul.tensor_triaxial[1][1, 1]**0.5) + "MPa" +
                    "\n")
            f.write('sigma 13 = sigma 31 = ' +
                    str(stress_calcul.tensor_triaxial[0][3]) + "+/-" +
                    str(stress_calcul.tensor_triaxial[1][3, 3]**0.5) + "MPa" +
                    "\n")
            f.write('sigma 23 = sigma 32 = ' +
                    str(stress_calcul.tensor_triaxial[0][4]) + "+/-" +
                    str(stress_calcul.tensor_triaxial[1][4, 4]**0.5) + "MPa" +
                    "\n")
            f.write('sigma 33 = ' + str(stress_calcul.tensor_triaxial[0][5]) +
                    "+/-" + str(stress_calcul.tensor_triaxial[1][5, 5]**0.5) +
                    "MPa" + "\n")
            f.write("---------------------- \n")

        f.write("---------------------------------------------------- \n")
        f.write("---------------------------------------------------- \n")

        f.write(
            "phi(°)    psi(°)    omega(°)     gamma(°)   peak_2theta(°)    phi_gamma(°)     psi_gamma(°)\n"
        )
        for i in range(len(stress_calcul.phi)):
            progress["value"] = progress["value"] + 1
            progress.update()
            for j in range(main_calcul.gamma_number):
                gamma_range = int(main_calcul.gamma_f_index +
                                  j * main_calcul.gamma_step +
                                  main_calcul.gamma_step / 2)
                try:
                    f.write(str("%3.4g" % main_calcul.phi[i]))
                    f.write(str("%10.4g" % main_calcul.chi[i]))
                    f.write(str("%12.4g" % main_calcul.omega[i]))
                    f.write(str("%15.4g" % main_calcul.gamma_y[gamma_range]))
                    f.write(
                        str("%15.4g" % main_calcul.peaks_position[
                            i * main_calcul.gamma_number + j]))
                    f.write(
                        str("%15.4g" % stress_calcul.phi_regroup[
                            i * main_calcul.gamma_number + j]))
                    f.write(
                        str("%15.4g" % stress_calcul.psi_regroup[
                            i * main_calcul.gamma_number + j]))
                except TypeError:
                    pass
                f.write("\n")
        f.close()
        for widget in main.Frame1_2.winfo_children():
            widget.destroy()
    main.root.mainloop()
コード例 #36
0
        def open_func(entry,
                      orig_headers,
                      inp_options,
                      start,
                      skip_rows,
                      skip_cols,
                      name,
                      total_lines,
                      func=0):
            """
            Function for applying input settings to Open
            :param entry: File Name and Directory
            :param orig_headers: original headers
            :param inp_options: Input Settings ;)
            :param start: Start Time
            :param func: 0=CSVw/Delimiter,1=CSV,2=Excel
            :return: Dataframe, Dictionary of Column/FillVal's
            """
            global var
            temp_df = []
            new_field = GenFuncs.strip_dir(entry1)
            if not _test:
                progress = Progressbar(root,
                                       orient=HORIZONTAL,
                                       length=100,
                                       mode='determinate')
                progress.pack(fill=X)
                v = StringVar()
                Label(root, text=new_field).pack()
                Label(root, textvariable=v).pack()
            gen_rules = inp_options[0]
            delimiter = gen_rules['Delimiter']
            terminator = gen_rules['Terminator']
            header_line = gen_rules['Header Line']
            index_col = gen_rules['Index Column']
            chunk = gen_rules['Chunk']
            verbose = gen_rules['Verbose']
            header_func = gen_rules['Header Func']
            var = verbose
            line_count = 0

            only_cols = inp_options[1]
            dtypes = inp_options[2]
            head_func_dtypes = inp_options[3]
            if len(inp_options) > 5:
                search_col = inp_options[4]
                real_l = inp_options[5]
                filter_results = True
            else:
                filter_results = False
            new_field = GenFuncs.strip_dir(entry)
            stripped_headers = []
            for item in orig_headers:
                try:
                    stripped_headers.append(item.strip())
                except AttributeError:
                    stripped_headers.append(item)
            new_dtypes = {}
            if dtypes is not None:
                for key, value in dtypes.items():
                    if key in orig_headers:
                        new_dtypes[key] = value
                    elif key.strip() in orig_headers:
                        new_dtypes[key.strip()] = value
                    elif key in stripped_headers:
                        ind = stripped_headers.index(key)
                        new_dtypes[orig_headers[ind]] = value
                    elif key.strip() in stripped_headers:
                        ind = stripped_headers.index(key.strip())
                        new_dtypes[orig_headers[ind]] = value
                    else:
                        print(key + ':not found in ' + new_field)
            if new_dtypes == {}:
                new_dtypes = None
            new_only_cols = []
            if only_cols is not None:
                for item in only_cols:
                    if item in orig_headers:
                        new_only_cols.append(item)
                    elif item.strip() in orig_headers:
                        new_only_cols.append(item.strip())
                    elif item in stripped_headers:
                        ind = stripped_headers.index(item)
                        new_only_cols.append(orig_headers[ind])
                    elif item.strip() in stripped_headers:
                        ind = stripped_headers.index(item.strip())
                        new_only_cols.append(orig_headers[ind])
                    else:
                        print(item + ':not found in ' + new_field)
            if only_cols is not None and name is None:
                try:
                    header_line = skip_rows
                    if func == 0:
                        for gm_chunk in pd.read_csv(entry,
                                                    sep=delimiter,
                                                    chunksize=chunk,
                                                    header=header_line,
                                                    index_col=index_col,
                                                    usecols=new_only_cols,
                                                    dtype=new_dtypes,
                                                    verbose=verbose,
                                                    lineterminator=terminator,
                                                    low_memory=False):
                            line_count += gm_chunk.shape[0]
                            temp_df.append(gm_chunk)
                            if not _test:
                                progress['value'] = (line_count /
                                                     total_lines) * 100
                                v.set(
                                    str(line_count) + " : " + str(total_lines))
                                root.update_idletasks()
                        data = pd.concat(temp_df,
                                         axis=0,
                                         sort=False,
                                         ignore_index=True)
                    elif func == 1:
                        for gm_chunk in pd.read_csv(entry,
                                                    header=header_line,
                                                    chunksize=chunk,
                                                    index_col=index_col,
                                                    usecols=new_only_cols,
                                                    dtype=new_dtypes,
                                                    verbose=verbose,
                                                    lineterminator=terminator,
                                                    low_memory=False):
                            line_count += gm_chunk.shape[0]
                            temp_df.append(gm_chunk)
                            if not _test:
                                progress['value'] = (line_count /
                                                     total_lines) * 100
                                v.set(
                                    str(line_count) + " : " + str(total_lines))
                                root.update_idletasks()
                        data = pd.concat(temp_df,
                                         axis=0,
                                         sort=False,
                                         ignore_index=True)
                    elif func == 2:
                        settings = [
                            entry, header_line, name, index_col, new_only_cols,
                            new_dtypes, skip_rows, verbose, line_count
                        ]
                        data = readExcel(entry, chunk, progress, v, 0,
                                         settings)
                    try:
                        data.columns = [col.strip() for col in data.columns]
                    except AttributeError:  # 'int'object has no attribute 'strip'  < - files with int headers
                        pass
                    if filter_results:
                        data = Retrieve_R.esult_frames(data, search_col,
                                                       real_l, entry)
                    if not data.empty:
                        data, NA_list = reduce_mem_usage(data)  # [0]
                    else:
                        print('no results in 1')
                        NA_list = []
                    return data, NA_list
                except ValueError as e:
                    print(e)
            else:
                try:
                    if name != None:
                        header_line = 0
                    if func == 0:
                        for gm_chunk in pd.read_csv(entry,
                                                    sep=delimiter,
                                                    header=header_line,
                                                    names=name,
                                                    chunksize=chunk,
                                                    index_col=index_col,
                                                    dtype=new_dtypes,
                                                    skiprows=skip_rows,
                                                    verbose=verbose,
                                                    lineterminator=terminator,
                                                    low_memory=False):
                            line_count += gm_chunk.shape[0]
                            temp_df.append(gm_chunk)
                            if not _test:
                                progress['value'] = (line_count /
                                                     total_lines) * 100
                                v.set(
                                    str(line_count) + " : " + str(total_lines))
                                root.update_idletasks()
                        data = pd.concat(temp_df,
                                         axis=0,
                                         sort=False,
                                         ignore_index=True)
                    elif func == 1:
                        for gm_chunk in pd.read_csv(entry,
                                                    header=header_line,
                                                    names=name,
                                                    chunksize=chunk,
                                                    index_col=index_col,
                                                    dtype=new_dtypes,
                                                    skiprows=skip_rows,
                                                    verbose=verbose,
                                                    lineterminator=terminator,
                                                    low_memory=False):
                            line_count += gm_chunk.shape[0]
                            temp_df.append(gm_chunk)
                            if not _test:
                                progress['value'] = (line_count /
                                                     total_lines) * 100
                                v.set(
                                    str(line_count) + " : " + str(total_lines))
                                root.update_idletasks()
                        data = pd.concat(temp_df,
                                         axis=0,
                                         sort=False,
                                         ignore_index=True)
                    elif func == 2:
                        settings = [
                            entry, header_line, name, index_col, new_only_cols,
                            new_dtypes, skip_rows, verbose, line_count
                        ]
                        data = readExcel(entry, chunk, progress, v, 1,
                                         settings)
                    if skip_cols > 0:
                        for i in range(skip_cols):
                            data.drop(data.columns[1], axis=1)
                    if name != None and len(new_only_cols) > 0:
                        data = data[new_only_cols]
                    try:
                        data.columns = [col.strip() for col in data.columns]
                    except AttributeError:  # 'int'object has no attribute 'strip'  < - files with int headers
                        pass
                    if filter_results:
                        data = Retrieve_R.esult_frames(data, search_col,
                                                       real_l, entry)
                    if not data.empty:
                        data, NA_list = reduce_mem_usage(data)  # [0]
                    else:
                        print('no results due to header func criteria')
                        NA_list = []

                    end = time.time()
                    print('-------' + str(end - start) + '-------')
                    return data, NA_list

                except ValueError as e:
                    print(e)
コード例 #37
0
ファイル: frame.py プロジェクト: lazarel/Plantogotchi
start_label = tk.Label(text="Press 'Return' to start!", font=('Helvetica', 12))
start_label.pack()

water_level_label = tk.Label(text="Water level", font=('Helvetica', 12))
water_level_label.pack()

stress_level_label = tk.Label(text="Situation normal", font=('Helvetica', 12))
stress_level_label.pack()

water_bar = Progressbar(orient="horizontal",
                        length=200,
                        maximum=150,
                        mode="determinate",
                        style='green.Horizontal.TProgressbar')
water_bar.pack()

# add a 'day' label.
day_label = tk.Label(text="Day: " + str(day), font=('Helvetica', 12))
day_label.pack()

# ADDING IMAGES
dying_plant = tk.PhotoImage(file="dying_plant.png")
normal_plant = tk.PhotoImage(file="normal_plant.png")
mature_plant = tk.PhotoImage(file="mature_plant.png")
stress_plant = tk.PhotoImage(file="stress_plant.png")
mature_stress_plant = tk.PhotoImage(file="mature_stress_plant.png")
mature_dying_plant = tk.PhotoImage(file="mature_dying_plant.png")
died_plant = tk.PhotoImage(file="died_plant.png")
mature_died_plant = tk.PhotoImage(file="mature_died_plant.png")
water_button = tk.PhotoImage(file="water_splash.png")