Beispiel #1
1
class ComboBox(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()
        self.speed = 1.0

    def initUI(self):
        self.parent.title("Combobox")
        self.pack(fill = BOTH, expand=True)
        frame = Frame(self)
        frame.pack(fill=X)
        
        field = Label(frame, text = "Typing Speed:", width = 15)
        field.pack(side = LEFT, padx = 5, pady = 5)
        
        self.box_value = StringVar()
        self.box = Combobox(frame, textvariable=self.box_value, width = 5)
        self.box['values'] = ('1x', '2x', '5x', '10x' )
        self.box.current(0)
        self.box.pack(fill = X, padx =5, expand = True)
        self.box.bind("<<ComboboxSelected>>", self.value)
        

    def value(self,event):
        self.speed =  float(self.box.get()[:-1])
class FrOptions(LabelFrame):
    def __init__(self, title, txt, dicoprofils):
        LabelFrame.__init__(self, text=title)
        self.listing_profils(dicoprofils)

        # Dropdowm list of available profiles
        self.ddprofils = Combobox(self,
                                  values = dicoprofils.keys(),
                                  width = 35,
                                  height = len(dicoprofils.keys())*20)
        self.ddprofils.current(1)   # set the dropdown list to first element

        # export options
        caz_doc = Checkbutton(self, text = u'HTML / Word (.doc/.docx)',
                                    variable = self.master.opt_doc)
        caz_xls = Checkbutton(self, text = u'Excel 2003 (.xls)',
                                    variable = self.master.opt_xls)
        caz_xml = Checkbutton(self, text = u'XML (ISO 19139)',
                                    variable = self.master.opt_xml)

        # Basic buttons
        self.action = StringVar()
        self.action.set(txt.get('gui_choprofil'))
        self.val = Button(self, textvariable = self.action,
                                relief= 'raised',
                                command = self.bell)
        can = Button(self, text = 'Cancel (quit)',
                                relief= 'groove',
                                command = self.master.destroy)
        # Widgets placement
        self.ddprofils.bind('<<ComboboxSelected>>', self.alter_val)
        self.ddprofils.grid(row = 1, column = 0, columnspan = 3, sticky = N+S+W+E, padx = 2, pady = 5)
        caz_doc.grid(row = 2, column = 0, sticky = N+S+W, padx = 2, pady = 1)
        caz_xls.grid(row = 3, column = 0, sticky = N+S+W, padx = 2, pady = 1)
        caz_xml.grid(row = 4, column = 0, sticky = N+S+W, padx = 2, pady = 1)
        self.val.grid(row = 5, column = 0, columnspan = 2,
                            sticky = N+S+W+E, padx = 2, pady = 5)
        can.grid(row = 5, column = 2, sticky = N+S+W+E, padx = 2, pady = 5)

    def listing_profils(self, dictprofils):
        u""" List existing profilesin folder \data\profils """
        for i in glob(r'../data/profils/*.xml'):
            dictprofils[path.splitext(path.basename(i))[0]] = i
##        if new > 0:
##            listing_lang()
##            load_textes(deroul_lang.get())
##            deroul_profils.setlist(sorted(dico_profils.keys()))
##            fen_choix.update()
        # End of function
        return dictprofils

    def alter_val(self, inutile):
        u""" Switch the label of the validation button contained in basics class
        in the case that a new profile is going to be created"""
        if self.ddprofils.get() == self.master.blabla.get('gui_nouvprofil'):
            self.action.set(self.master.blabla.get('gui_crprofil'))
        else:
            self.action.set(self.master.blabla.get('gui_choprofil'))
        # End of functionFin de fonction
        return self.action
Beispiel #3
0
class ComboBox(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()
        self.speed = 1.0

    def initUI(self):
        self.parent.title("Combobox")
        self.pack(fill=BOTH, expand=True)
        frame = Frame(self)
        frame.pack(fill=X)

        field = Label(frame, text="Typing Speed:", width=15)
        field.pack(side=LEFT, padx=5, pady=5)

        self.box_value = StringVar()
        self.box = Combobox(frame, textvariable=self.box_value, width=5)
        self.box['values'] = ('1x', '2x', '5x', '10x')
        self.box.current(0)
        self.box.pack(fill=X, padx=5, expand=True)
        self.box.bind("<<ComboboxSelected>>", self.value)

    def value(self, event):
        self.speed = float(self.box.get()[:-1])
Beispiel #4
0
    def initUI(self):
      
        self.parent.title("TRAM")
        self.style = Style()
        self.style.theme_use("default")

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

        #Model Text
        self.t = Text(self, borderwidth=3, relief="sunken")
        self.t.config(font=("consolas", 12), undo=True, wrap='word')
        self.t.grid(row=0, column=0, padx=2, pady=2, sticky=(N, W, E, S))
        
        
        
        #Search Panel
        searchPanel = LabelFrame(self, text="Find your model")
        searchPanel.grid(row=0, column=1, padx=2, pady=2, sticky=N) 
        
        Label(searchPanel, text="Model name").grid(row=0, column=0, padx=2, pady=2, sticky=W)
        
        searchQueryEntry = Entry(searchPanel, textvariable=self.searchQuery)
        searchQueryEntry.grid(row=0, column=1, padx=2, pady=2, sticky=W)
        
        Label(searchPanel, text="Transformation").grid(row=1, column=0, padx=2, pady=2, sticky=W)
        preferredTransformation = StringVar()
        box = Combobox(searchPanel, textvariable=preferredTransformation, state='readonly')
        box['values'] = ('Any...', 'Object Change', 'Object Extension', 'Specialization', 'Functionality Extension', 'System Extension', 'Soft Simplification', 'Hard Simplification')
        box.current(0)
        box.grid(row=1, column=1, padx=2, pady=2, sticky=W)
        
        findButton = Button(searchPanel, text="Find", command = self.__findModels)
        findButton.grid(row=2, column=1, padx=2, pady=2, sticky=E)
        
        #Listbox with recommendations
        recommendationPanel = LabelFrame(self, text="Recommended models (transformations)")
        recommendationPanel.grid(row=0, column=1, padx=2, pady=2, sticky=(W,E,S))
        self.l = Listbox(recommendationPanel)
        self.l.pack(fill=BOTH, expand=1)
        
        #Button frame
        transformButtonPanel = Frame(recommendationPanel)
        transformButtonPanel.pack(fill=BOTH, expand=1)
        
        viewButton = Button(transformButtonPanel, text="View", command = self.__loadSelectedModel)
        viewButton.grid(row=1, column=0, padx=2, pady=2)
        
        transformButton = Button(transformButtonPanel, text="Transform", command = self.__transformModel)
        transformButton.grid(row=1, column=2, padx=2, pady=2)
Beispiel #5
0
class LevelsWindow(Tk):
    def __init__(self, menu):
        Tk.__init__(self)
        
        self.title("Pick a level")
        
        icon = PhotoImage(file=os.getcwd() + '/res/logo/logo.gif')
        self.tk.call("wm", "iconphoto", self._w, icon)
        
        self.eval('tk::PlaceWindow %s center' % self.winfo_pathname(self.winfo_id()))
        
        self.levels = [file[:-4] for file in listdir("res/levels")]
        self.protocol("WM_DELETE_WINDOW", self.shutdownTTK)
        
        if not self.levels:  # No levels
            self.withdraw()
            tkMessageBox.showwarning("Error", 'There doesn\'t seem to be any levels saved. Create one pressing the "Design Level" button!')
            self.shutdownTTK()
            
        else:
            self.menu = menu
            
            self.value = StringVar()
            self.levels_list = Combobox(self, textvariable=self.value, state='readonly')
            
            self.levels_list['values'] = self.levels
            self.levels_list.current(0)
            self.levels_list.grid(column=0, row=0)
            
            self.button = Button(self, text="Begin Level", command=self.begin_level)
            self.button.grid(column=0, row=1)
            self.mainloop()
    
            
            
    def begin_level(self):
        level = self.levels_list.get()
        self.shutdownTTK()
        self.menu.call_to("GameWindow", level)
    
    
    def shutdownTTK(self):
        # For some unholy reason, TTK won't shut down when we destroy the window
        # so we have to explicitly kill it.
        self.eval('::ttk::CancelRepeat')
        self.destroy()
Beispiel #6
0
    def __init__(self, parent, parenttab, name, section, paramprefix):
        EditInput.__init__(self, parent, parenttab, name)
        self._section = section
        self._paramprefix = paramprefix
        
        fontlist = list(tkFont.families())
        fontlist.sort()
        self._bvb = tki.BooleanVar()
        self._bvi = tki.BooleanVar()
        self._bvs = tki.BooleanVar()
        self._bvu = tki.BooleanVar()
        
        l = tki.Label(self, text = lang[lng.txtFontsize])
        l.grid(row = 0, column = 0, padx = 5, pady = 2, sticky = tki.W)
        
        tcmd = (self.register(self._ehOnValidateEntry), '%d', '%P')
        e = tki.Entry(self, validate = 'key', validatecommand = tcmd, width = _sizechars)
        self._esize = e
        e.grid(row = 1, column = 0, padx = 5, pady = 2, sticky = tki.W)

        l = tki.Label(self, text = lang[lng.txtFontName])
        l.grid(row = 2, column = 0, padx = 5, pady = 2, sticky = tki.W)
        
        cb = Combobox(self, values = fontlist)
        self._cbfontname = cb
        cb.grid(row = 3, column = 0, padx = 5, pady = 2, sticky = tki.W)
        cb.bind('<<ComboboxSelected>>', self._setDirty)
        cb.current(0)

        cb = tki.Checkbutton(self, text = lang[lng.txtBold], onvalue = True, offvalue = False, variable = self._bvb, command = self._setDirty)
        self._cbb = cb
        cb.grid(row = 0, column = 1, padx = 5, pady = 2, sticky = tki.W)
        
        cb = tki.Checkbutton(self, text = lang[lng.txtItalics], onvalue = True, offvalue = False, variable = self._bvi, command = self._setDirty)
        self._cbi = cb
        cb.grid(row = 1, column = 1, padx = 5, pady = 2, sticky = tki.W)

        cb = tki.Checkbutton(self, text = lang[lng.txtStrikethrough], onvalue = True, offvalue = False, variable = self._bvs, command = self._setDirty)
        self._cbs = cb
        cb.grid(row = 2, column = 1, padx = 5, pady = 2, sticky = tki.W)

        cb = tki.Checkbutton(self, text = lang[lng.txtUnderline], onvalue = True, offvalue = False, variable = self._bvu, command = self._setDirty)
        self._cbu = cb
        cb.grid(row = 3, column = 1, padx = 5, pady = 2, sticky = tki.W)
Beispiel #7
0
    def initUI(self):

        # master = Frame(self)
        #Headers - заголовок запроса
        headers = {
            'User-Agent':
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) '
            'AppleWebKit/537.36 (KHTML, like Gecko) '
            'Chrome/39.0.2171.95 Safari/537.36'
        }
        aClearResponse = []

        # Закрытие формы
        def closeForm():
            sys.exit()

        # Забираем значение инпута
        def inputValue():
            sParse = Keyword.get()
            sDomain = DomainAnalys.get()
            TextLog.delete(1.0, END)
            TextLog.insert(
                1.0, "\nВы ввели имя домена: " + sDomain +
                '\nИ выбрали поисковую систему ' + DropDown.get())
            TextLog.insert(1.0, "Вы ввели ключевую фразу: " + sParse)
            aValue = []
            aValue.append(sParse)
            aValue.append(sDomain)

            return aValue

        #Получаем ответ от сервера в виде HTML документа
        def getValueButton():
            sIntVal = re.split(r",", inputValue()[0])
            for sInputValue in sIntVal:
                val = function.createRequest(str(sInputValue), DropDown.get(),
                                             "Parse")
                print("Сгенерированный HTTP запрос: " + val)
                response = function.getPage(val, headers)
                TextLog.insert(1.0, "Ответ " + response)
                xPathResponse(response, sInputValue)

        #Получаем результаты анализа от сервера
        def getDomainValue():
            sIntVal = re.split(r",", inputValue()[1])
            for sInputValue in sIntVal:
                val = function.createRequest(str(sInputValue), DropDown.get(),
                                             "Analys")
                print("Сгенерированный HTTP запрос: " + val)
                response = function.getPage(val, headers)
                TextLog.insert(1.0, "Ответ " + response)
                xPathResponse(response, sInputValue)

        def xPathResponse(response, keyword):
            #Разделяем полученную строку на список и убираем []
            aClearResponse = []
            aDirtResponse = []
            try:
                aResponse = re.split(r",\[",
                                     re.findall(r'\[\".*\d\]', response)[0])
                print(len(aResponse))
                for i in range(len(aResponse)):
                    aDirtResponse.append(re.sub(r'[\]\[]', '', aResponse[i]))
                    aClearResponse.append(
                        re.sub(r'[\]\[]', '', aDirtResponse[i]))
                    TextResult.insert(
                        1.0,
                        re.sub(r'[\]\[]', '', aClearResponse[i]) + '\n')
                    # print(aClearResponse)
            except Exception:
                win32api.MessageBox(
                    0, 'Запрос "%s" ничего не вернул :(' % (keyword),
                    'Ошибка!')
                aClearResponse = 'Error'
            return aClearResponse

        # # Задаем путь для сохранения файла
        # def directory():
        def saveExcel(type):
            sFilePath = fd.asksaveasfilename(filetypes=(("Excel files",
                                                         "*.xls"),
                                                        ("All files", "*.*")))
            #Проверяем на пустоту путь сохранения файлы и если не пусто, то выполняем сохранение
            if sFilePath != '':
                aClearResponse = []
                aAllKeyResponse = []
                sError = []
                #Проверка, откуда произошел вызов функции
                if type == "Parse":
                    sIntVal = re.split(r",", inputValue()[0])
                else:
                    sIntVal = re.split(r",", inputValue()[1])

                for sInputValue in sIntVal:
                    val = function.createRequest(str(sInputValue),
                                                 DropDown.get(), type)
                    response = function.getPage(val, headers)
                    aClearResponse = xPathResponse(response, sInputValue)
                    if aClearResponse == 'Error':
                        sError.append(sInputValue + " Error")
                    else:
                        for i in aClearResponse:
                            aAllKeyResponse.append(i)

                ##Проверка на ошибки
                if len(sError) == len(sIntVal):
                    win32api.MessageBox(
                        0,
                        'Ни один из запросов не дал результатов. Файл не будет сохранен',
                        'Ошибка!')
                elif len(sError) > 1:
                    win32api.MessageBox(
                        0,
                        'Не удалось сохранить все, что было указано в запросе! Скорее всего один из запросов не дал результатов',
                        'Ошибка!')
                    function.createEXCEL(aAllKeyResponse, sFilePath)
                else:
                    function.createEXCEL(aAllKeyResponse, sFilePath)

        #Получаем значение из выпадающег осписка
        # value = (listbox.get(listbox.curselection()))

        self.parent.title("Парсер")
        self.style = Style()
        self.style.theme_use("default")

        #Задаем размеры формы
        w = 1200
        h = 500
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        x = (sw - w) / 2
        y = (sh - h) / 2
        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))

        # Располагаем объекты на форме
        # Объявляем все элементы:
        KeywordLabel = Label(
            text="Введите ключевое слово или слова через запятую:")
        DropDownLabel = Label(text='Выберите поисковую систему:')
        Keyword = Entry()
        DropDown = Combobox(self.parent)
        Close = Button(text="Закрыть", command=closeForm)
        Parse = Button(text='Начать парсинг', command=getValueButton)
        TextLog = Text(width=50, height=20)
        TextResult = Text(width=50, height=20)
        SaveValue = Button(text="Сохранить параметры парсинга",
                           command=inputValue)
        SaveExcel = Button(text='Сохранить в EXCEL документ',
                           command=lambda: saveExcel('Parse'))

        #Интерфейсные объекты для анализа
        DomainAnalysLabel = Label(text="Введите название домена для анализа:")
        DomainAnalys = Entry()
        Analys = Button(text='Начать анализ', command=getDomainValue)
        AnalysSave = Button(
            text='Сохранить в EXCEL документ результаты анализа',
            command=lambda: saveExcel('Analys'))

        # NameSpace
        DropDown['values'] = ('Yandex', 'Google')
        DropDown.current(1)  # вариант по-умолчанию

        # Размещаем элементы

        #0-й столбец
        TextLog.grid(row=0, column=0)
        KeywordLabel.grid(row=1, column=0, sticky="w")
        Keyword.grid(row=2, column=0)
        DomainAnalysLabel.grid(row=3, column=0, sticky="w")
        DomainAnalys.grid(row=4, column=0)
        DropDownLabel.grid(row=5, column=0)
        DropDown.grid(row=6, column=0)
        SaveValue.grid(row=7, column=0)

        #1-й столбец
        TextResult.grid(row=0, column=1)
        Parse.grid(row=1, column=1)
        SaveExcel.grid(row=2, column=1)
        Analys.grid(row=6, column=1)
        AnalysSave.grid(row=7, column=1)

        #2-й столбец
        Close.grid(row=7, column=3)

        # Забираем с инпутов значения

        # вставка начальных данных
        Keyword.insert(0, "Ключевое слово")
        TextLog.insert(
            1.0, "Здесь будут отображаться все этапы прохождения программы")
class Preferences_win(Toplevel):
    def __init__(self, parent):
        Toplevel.__init__(self)

        img = ImageTk.PhotoImage(file=os.path.join(os.path.dirname(__file__),
                                                   'Icons/LMS8001_PLLSim.png'))
        self.tk.call('wm', 'iconphoto', self._w, img)

        self.parent = parent
        if (sys.platform == 'win32'):
            font_paths = matplotlib.font_manager.win32InstalledFonts(
                fontext='ttf')
            self.font_names = []
            for font_path in font_paths:
                font_inst = matplotlib.ft2font.FT2Font(font_path)
                font_prop = matplotlib.font_manager.ttfFontProperty(font_inst)
                self.font_names.append(font_prop.name)
        elif (sys.platform == 'linux2'):
            font_list = matplotlib.font_manager.get_fontconfig_fonts()
            self.font_names = [
                matplotlib.font_manager.FontProperties(fname=fname).get_name()
                for fname in font_list
            ]
        else:
            print 'Unsupported OS type. Exiting Preferences Window.'
            tkMessageBox.showinfo('Unsupported OS type',
                                  'Exiting Preferences Window')
            self.destroy()

        self.initUI()
        center_Window(self)
        self.protocol("WM_DELETE_WINDOW", self.on_Quit)

    def on_OK(self):
        self.on_Apply()
        self.on_Quit()

    def on_Apply(self):
        self.parent.line_color = self.combobox_color.get()
        self.parent.font_name = self.combobox_fonts.get()
        maplotlib_font = {'family': self.parent.font_name}
        matplotlib.rc('font', **maplotlib_font)

    def on_Quit(self):
        self.parent.Pref_win = None
        self.destroy()

    def initUI(self):
        self.title('Preferences')
        self.rowconfigure(0, pad=6)
        self.rowconfigure(1, pad=1)
        self.rowconfigure(2, pad=6)
        self.columnconfigure(0, pad=1)
        self.columnconfigure(1, pad=1)
        self.columnconfigure(2, pad=1)

        label1 = Label(self, text='Graph Font')
        self.combobox_fonts = Combobox(self, values=self.font_names, width=16)
        self.combobox_fonts.current(
            self.font_names.index(self.parent.font_name))
        label1.grid(row=0, column=0, sticky=W)
        self.combobox_fonts.grid(row=0, column=1, columnspan=2, sticky=W)

        label2 = Label(self, text='Line Color')
        self.combobox_color = Combobox(self,
                                       values=self.parent.line_colors,
                                       width=8)
        self.combobox_color.current(
            self.parent.line_colors.index(self.parent.line_color))
        label2.grid(row=1, column=0, sticky=W)
        self.combobox_color.grid(row=1, column=1, columnspan=2, sticky=W)

        buttonOK = Button(self, text='OK', command=self.on_OK, width=16)
        buttonApply = Button(self,
                             text='Apply',
                             command=self.on_Apply,
                             width=16)
        buttonQuit = Button(self, text='Quit', command=self.on_Quit, width=16)
        buttonOK.grid(row=2, column=0, sticky=W + E + S)
        buttonApply.grid(row=2, column=1, sticky=W + E + S)
        buttonQuit.grid(row=2, column=2, sticky=W + E + S)
Beispiel #9
0
class Page(Frame):
	def __init__(self, parent, index=0):
		Frame.__init__(self, parent, height=530, relief=RAISED, borderwidth=1)
		self.parent = parent
		if index == 0:
			self.loadScriptPage()
		elif index == 1:
			self.scriptProcessPage()
		elif index == 2:
			self.sonifyProcessPage()
		elif index == 3:
			self.finishedPage()
		else:
			print "No Page here!"

		
	def loadScriptPage(self):
		
		# Button States
		self.parent.prevButton.config(state='disabled')
		if self.parent.scriptname != '':
			self.parent.nextButton.config(state='normal')

		explain = Label(self, text=txt.selectscript, justify=CENTER, font=root.fontH1)
		explain.pack(pady=50)

		self.loadedscript = Label(self, text=self.parent.scriptname, justify=CENTER, font=root.fontH1)
		self.loadedscript.pack()

		loadscriptBtn = Button(self, text="Load Script", command=self.getScript)
		loadscriptBtn.pack(pady=10)

	def scriptProcessPage(self):
		self.parent.prevButton.config(state='normal')
		self.parent.nextButton.config(state='normal')

		explain = Label(self, text="Character Selection", justify=CENTER, font=root.fontH1)
		explain.grid(row=0, columnspan=3, pady=20)

		# Instance Script
		self.parent.Script = ScreenPlay(normpath(self.parent.scriptpath))

		actorNames = self.parent.Script.topcharacters
		self.actorActive = []
		self.actorGender = []

		for i in range(6):
			Label(self, text=actorNames[i], width=20).grid(row=i+1, padx=10, pady=8)
			participateFrame = Frame(self ,relief=RAISED, borderwidth=1)
			participateFrame.grid(row=i+1,column=1, padx=10, ipady=2, ipadx=5)
			
			participate = BooleanVar()
			self.actorActive.append(participate)
			self.actorActive[i].set(True)

			Radiobutton(participateFrame, text="ON", variable=self.actorActive[i], value=True, command=self.updateVars).pack(side=LEFT)
			Radiobutton(participateFrame, text="OFF",  variable=self.actorActive[i], value=False, command=self.updateVars).pack(side=LEFT)

			genderFrame = Frame(self, relief=RAISED, borderwidth=1)
			genderFrame.grid(row=i+1,column=2, padx=30, ipady=2)
			
			gender = StringVar()
			self.actorGender.append(gender)
			self.actorGender[i].set('F')

			Label(genderFrame, text="Gender:").pack(side=LEFT, padx=10)

			Radiobutton(genderFrame, text="Female", variable=self.actorGender[i], value='F', command=self.updateVars).pack(side=LEFT, padx=5)
			Radiobutton(genderFrame, text="Male",  variable=self.actorGender[i], value='M', command=self.updateVars).pack(side=LEFT, padx=5)

		Label(self, text="______________________", justify=CENTER, state='disabled').grid(row=8, columnspan=3, pady=10)
		Label(self, text="Sonification Settings", justify=CENTER, font=root.fontH1).grid(row=9, columnspan=3, pady=10)

		sonificationFrame = Frame(self)
		sonificationFrame.grid(row=10, columnspan=3)

		Label(sonificationFrame, text="Tone Length", width=22).grid(row=0, column=0)
		self.tonelen = Combobox(sonificationFrame, state='readonly', values=['1/1','1/2','1/4', '1/8'])
		self.tonelen.bind("<<ComboboxSelected>>", self.updateCombobox)
		self.tonelen.current(1)
		self.tonelen.grid(row=0, column=1, padx=10, pady=5)

		Label(sonificationFrame, text="Sonification BPM", width=22).grid(row=1, column=0)
		self.bpm = Combobox(sonificationFrame, state='readonly', values=[100, 120, 140, 160, 180, 200, 220, 240, 260])
		self.bpm.bind("<<ComboboxSelected>>", self.updateCombobox)
		self.bpm.current(4)
		self.bpm.grid(row=1, column=1, padx=10, pady=5)

		Label(sonificationFrame, text="Dialogue Length per Tone", justify=LEFT).grid(row=2, column=0)
		self.dpt = Combobox(sonificationFrame, state='readonly', values=[1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 5500, 6000])
		self.dpt.bind("<<ComboboxSelected>>", self.updateCombobox)
		self.dpt.current(4)
		self.dpt.grid(row=2, column=1, padx=10, pady=5)

		self.submitSettings()

	def submitSettings(self):
		actorSelections = []
		sonifySettings = []

		for i in range(6):
			selected = self.actorActive[i].get()
			gender = self.actorGender[i].get()

			actorSelections.append( [selected , gender ] )

		sonifySettings.append(self.tonelen.get())
		sonifySettings.append(self.bpm.get())
		sonifySettings.append(self.dpt.get())

		self.parent.actorSelections = actorSelections
		self.parent.sonifySettings = sonifySettings
		# print actorSelections
		# print sonifySettings

	def finishedPage(self):
		Label(self, text="Sonification Complete!", justify=CENTER, font=root.fontH1).pack(pady=200)



	def sonifyProcessPage(self):

		Label(self, text="Processing", justify=CENTER, font=root.fontH1).pack(pady=20)

		self.processing = Label(self, text="", justify=CENTER)
		self.processing.pack(pady=20)

		self.pbar = Progressbar(self, orient='horizontal', mode='indeterminate')
		self.pbar.start(10)
		self.pbar.pack()

		self.after(100, self.sonifyProcess)


	def sonifyProcess(self):
		# Create Output Directory
		path = dirname(normpath(self.parent.scriptpath))

		self.outdir = join(path, 'output_' + str(self.parent.movietitle))

		self.tempdir = join(self.outdir, 'temp')
		self.tempdir = join(self.tempdir, '')

		if not isdir(self.tempdir):
			makedirs(self.tempdir)

		notelen = self.parent.sonifySettings[0]
		notelen = int( notelen[-1:] )
		bpm = int( self.parent.sonifySettings[1] )
		cutoff = int( self.parent.sonifySettings[2] )

		# Create dictionary based on settings
		self.parent.Script.createSceneDictionary(cutoff=cutoff)
		sceneAmount = len(self.parent.Script.scenedictionary)

		for index, character in enumerate(self.parent.Script.topcharacters):
			selected = self.parent.actorSelections[index][0]
			gender = self.parent.actorSelections[index][1]

			if selected:
				charSong = Sonification(character, gender, index)

				for scene in range(sceneAmount-1):

					if character in self.parent.Script.sceneComposition(scene):
						textamount = self.parent.Script.sceneComposition(scene)[character]
						participation = ( float(textamount) / float(cutoff) ) * 100
					else:
						participation = None

					self.processing.config(text= 'Creating Audio for ' + character.title())
					self.update()
					charSong.songBrick(participation, length=notelen)

				charSong.make_song(self.update, bpm=bpm, path=self.tempdir)

		self.mergeAudiotracks()
		

	def mergeAudiotracks(self):

		self.processing.config(text='Creating Multichannel Audiofile\nThis can take a while!')
		self.update()

		outfile = join(self.outdir, 'output.wav')
		
		filearray = []

		for index, character in enumerate(self.parent.Script.topcharacters):
			filename = character.lower() + str(index) + '.wav'
			filearray.append( join(self.tempdir, filename) )

		amix.mix_audiofiles(filearray, outfile, self.update)

		self.parent.nextPage()



	def getScript(self):
		scriptpath = askopenfilename(parent=self.parent, filetypes=[('Fountain Script File','.fountain')], title='Select Script')
		self.parent.scriptpath = scriptpath
		self.parent.scriptname = basename(self.parent.scriptpath)
		self.parent.movietitle = splitext(self.parent.scriptname)[0]

		self.loadedscript.config(text=self.parent.scriptname)
		self.parent.nextButton.config(state='normal')


	def updateVars(self):
		self.submitSettings()

	def updateCombobox(self, event):
		self.submitSettings()
Beispiel #10
0
class IniGenGui(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.inigen = IniGen()
        self.initUIGlobals()

    def initUIGlobals(self):
        """
      This is the first part of the window to be rendered. After these have been
       set by the user and 'Emit Globals' has been clicked, the given algorithm
       can then specify how to generate the second part of the window. All fields
       are disabled for user input after globals have been emitted.

      Information in Global Parameters:
        Algorithm
          - name of the algorithm to use
        File Name
          - name of the output file to be generated
        Min Time
          - Minimum Time for distillers to run
        Max Time
          - Maximum Time for distillers to run
        Set Enabled:
          - checkbox to specify if the distiller should be enabled True or False
    """
        self.parent.title("Ini Generator")

        Style().configure("TButton", padding=(0, 5, 0, 5), font='serif 10')

        # initialize row counter. This is incremented after each element added to grid
        row = 0
        # initialize column counter. This is incremented after a column has been filled
        self.column = 0

        # Globals: entries for info common to all runs
        label_globals = Label(self, text="Globals")
        label_globals.grid(row=row, column=self.column)
        row += 1

        label_alg = Label(self, text="Algorithm")
        label_alg.grid(row=row, column=self.column, sticky=E + W)
        row += 1
        self.cbox_alg = Combobox(self,
                                 values=algorithms.keys(),
                                 state='readonly')
        self.cbox_alg.current(0)
        self.cbox_alg.grid(row=row, column=self.column, sticky=E + W + S + N)
        row += 1

        label_filename = Label(self, text="Output File Name")
        label_filename.grid(row=row, column=self.column, sticky=E + W)
        row += 1
        self.entry_filename = Entry(self)
        self.entry_filename.grid(row=row, column=self.column, sticky=W + E)
        row += 1

        label_mintime = Label(self, text="Min Time")
        label_mintime.grid(row=row, column=self.column, sticky=E + W)
        row += 1
        self.entry_mintime = Entry(self)
        self.entry_mintime.grid(row=row, column=self.column, sticky=W + E)
        row += 1

        label_maxtime = Label(self, text="Max Time")
        label_maxtime.grid(row=row, column=self.column, sticky=W + E)
        row += 1
        self.entry_maxtime = Entry(self)
        self.entry_maxtime.grid(row=row, column=self.column, sticky=W + E)
        row += 1

        self.enabled = IntVar()
        self.check_enabled = Checkbutton(self,
                                         text="set enabled",
                                         variable=self.enabled)
        self.check_enabled.grid(row=row, column=self.column, sticky=W + E)
        row += 1

        # Control: buttons used to emmiting text and generating file
        self.button_emit_globals = Button(self,
                                          text="Emit Globals",
                                          command=self.emit_globals)
        self.button_emit_globals.grid(row=row,
                                      column=self.column,
                                      sticky=W + E)
        row += 1

        button_addrun = Button(self, text="Add Run", command=self.emit_run)
        button_addrun.grid(row=row, column=self.column, sticky=W + E)
        row += 1

        button_generate = Button(self,
                                 text="Generate File",
                                 command=self.generate_file)
        button_generate.grid(row=row, column=self.column, sticky=W + E)
        row += 1

        self.column += 1

        self.pack()

    def initUIRuns(self):
        """
      Second part of gui to be rendered. This contains all the fields needed to emit
       a single run within a distiller file. Multiple runs can be added by clicking
       'Add Run' multiple times.

      Information in Run Parameters:
        Run Name
          - header name for run
        Dependencies
          - description and uuid fields for each dependency in the algorithm
        Params
          - parameter fields for each parameter in the algorithm
    """

        self.entry_run_name = None
        self.entries_dep_description = []
        self.entries_dep_uuid = []
        self.entries_param = []

        row = 0

        label_runs = Label(self, text="Runs")
        label_runs.grid(row=row, column=self.column)
        row += 1

        label_run_name = Label(self, text="Run Name")
        label_run_name.grid(row=row, column=self.column, sticky=W + E)
        row += 1

        self.entry_run_name = Entry(self)
        self.entry_run_name.grid(row=row, column=self.column, sticky=W + E)
        row += 1

        algorithm = self.cbox_alg.get()
        settings = algorithms[algorithm]

        for dep in settings['deps']:

            if row >= 21:
                self.column += 1
                row = 1

            label_dep_description = Label(self,
                                          text="{0} (description)".format(dep))
            label_dep_description.grid(row=row,
                                       column=self.column,
                                       sticky=W + E)
            row += 1

            entry_dep_description = Entry(self)
            entry_dep_description.grid(row=row,
                                       column=self.column,
                                       sticky=W + E)
            row += 1

            label_dep_uuid = Label(self, text="{0} (uuid)".format(dep))
            label_dep_uuid.grid(row=row, column=self.column, sticky=W + E)
            row += 1

            entry_dep_uuid = Entry(self)
            entry_dep_uuid.grid(row=row, column=self.column, sticky=W + E)
            row += 1

            self.entries_dep_description.append(entry_dep_description)
            self.entries_dep_uuid.append(entry_dep_uuid)

        for param in settings['params']:

            if row >= 21:
                self.column += 1
                row = 1

            label_param = Label(self, text=param)
            label_param.grid(row=row, column=self.column, sticky=W + E)
            row += 1

            entry_param = Entry(self)
            entry_param.grid(row=row, column=self.column, sticky=W + E)
            row += 1

            self.entries_param.append(entry_param)

        row = 0
        self.column += 1

        self.text_file = Text(self)
        self.text_file.grid(row=row,
                            column=self.column,
                            rowspan=31,
                            sticky=W + E + N + S,
                            padx=5,
                            pady=5)
        self.column += 1
        scrollbar = Scrollbar(self, command=self.text_file.yview)
        self.text_file.config(yscrollcommand=scrollbar.set)
        scrollbar.grid(row=row, column=self.column, rowspan=31, sticky=N + S)

        self.pack()

    def emit_globals(self):
        self.algorithm = algorithms[self.cbox_alg.get()]
        path = self.algorithm['path']
        if self.enabled.get():
            enabled = 'True'
        else:
            enabled = 'False'

        lines = self.inigen.emit_global(path, enabled)

        self.mintime = self.entry_mintime.get()
        self.maxtime = self.entry_maxtime.get()

        self.cbox_alg.configure(state='disabled')
        self.entry_filename.configure(state='disabled')
        self.entry_mintime.configure(state='disabled')
        self.entry_maxtime.configure(state='disabled')
        self.check_enabled.configure(state='disabled')
        self.button_emit_globals.configure(state='disabled')

        self.initUIRuns()
        self.update_text(lines)

    def emit_run(self):
        label = self.entry_run_name.get()
        chunking = 'parallel'  #hardcoded for now
        mintime = self.mintime
        maxtime = self.maxtime
        lines = self.inigen.emit_run_header(label, chunking, mintime, maxtime)
        self.update_text(lines)

        deps = []
        for i in range(len(self.entries_dep_description)):
            deps.append([
                self.entries_dep_description[i].get(),
                self.algorithm['deps'][i], self.entries_dep_uuid[i].get()
            ])
        params = []
        for i in range(len(self.entries_param)):
            params.append(
                [self.algorithm['params'][i], self.entries_param[i].get()])
        outputs = self.algorithm['outputs']
        lines = self.inigen.emit_run_body(deps, params, outputs)
        self.update_text(lines)

    def generate_file(self):
        self.inigen.generate_file(self.entry_filename.get())
        self.quit()

    def update_text(self, lines):
        self.text_file.configure(state='normal')
        string = "\n".join(lines)
        self.text_file.insert(END, string)
        self.text_file.configure(state='disabled')
Beispiel #11
0
class MainFrame(Frame):

    TOP_FRAME_BACKGROUND_COLOR = 'gray75'

    w_ = 500
    h_ = 400

    a_ = 5.
    b_ = 5.

    pad_l = 10

    def __init__(self, parent):
        Frame.__init__(self, parent, background='white')

        self.parent_ = parent

        # this is the main frame we are working on
        self.img_frame = Frame(self, background='navy')
        self.entry1 = None
        self.entry2 = None
        self.cb = None

        #
        self.init_ui()
        self.centering()

        # broken TV app))
        # while True:
        self.state = 0
        self.init_random_image()
        # time.sleep(0.05)

    def centering(self):
        pos_x = (self.parent_.winfo_screenwidth() - self.w_) / 2
        pos_y = (self.parent_.winfo_screenheight() - self.h_) / 2

        self.parent_.geometry('{}x{}+{}+{}'.format(self.w_, self.h_, pos_x, pos_y))

    def init_ui(self):
        self.parent_.title('Rough surface generator')
        self.pack(fill=BOTH, expand=True)

        # top panel with controls
        frame_top = Frame(self, background=self.TOP_FRAME_BACKGROUND_COLOR)
        frame_top.pack(fill=X)

        self.cb = Combobox(frame_top, values=('Gaussian', 'Laplace'))
        self.cb.current(0)
        self.cb.pack(side=LEFT, padx=5, expand=True)

        l1 = Label(frame_top, text=r'Cx', background=self.TOP_FRAME_BACKGROUND_COLOR, width=4)
        l1.pack(side=LEFT, padx=5, expand=True)

        self.entry1 = Entry(frame_top,
                            validate='key',
                            validatecommand=(self.register(self.on_validate),
                                             '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W'),
                            width=10)
        self.entry1.pack(side=LEFT, padx=5, expand=True)
        self.entry1.insert(0, str(self.a_))

        l1 = Label(frame_top, text=r'Cy', width=4, background=self.TOP_FRAME_BACKGROUND_COLOR)
        l1.pack(side=LEFT, padx=5)

        self.entry2 = Entry(frame_top,
                            validate='key',
                            validatecommand=(self.register(self.on_validate),
                                             '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W'),
                            width=10)
        self.entry2.pack(side=LEFT, padx=5, expand=True)
        self.entry2.insert(0, str(self.b_))

        but1 = Button(frame_top, text='RUN', command=self.button_action)
        but1.pack(side=RIGHT, padx=5, pady=5)

        # central panel. It will have a label with an image. Image may have a random noise state, or
        # transformed image state
        self.img_frame.pack(fill=BOTH, expand=True)
        img_label = Label(self.img_frame, background=None)
        img_label.pack(expand=True, fill=BOTH, padx=5, pady=5)

    def on_validate(self, d, i, P, s, S, v, V, W):
        """
        :param d: type of action: 1 - insert, 0 - delete, -1 - other
        :param i: index of char string to be inserted/deleted, or -1
        :param P: value of the entry if the edit is allowed
        :param s: value of entry prior to editing
        :param S: the text string being inserted or deleted, if any
        :param v: the type of validation that is currently set
        :param V: the type of validation that triggered the callback
                    (key, focusin, focusout, forced)
        :param W: the tk name of the widget
        :return: True/False -> Valid / Invalid

        Found it here:
            https://stackoverflow.com/questions/4140437/interactively-validating-entry-widget-content-in-tkinter
        Very good answer!
        """

        if d == '1':
            if W == str(self.entry1):
                try:
                    float(s + S)
                    return True
                except ValueError:
                    self.entry1.delete(0, 'end')
                    self.entry1.insert(0, s)

                    print("Not a number, entry 1")
                    return False
            if W == str(self.entry2):
                try:
                    float(s + S)
                    return True
                except ValueError:
                    self.entry2.delete(0, 'end')
                    self.entry2.insert(0, s)

                    print("Not a number, entry 2")
                    return False
        return True

    def init_random_image(self):
        """
            Create a rough surface image from a random noise
        """
        self.update()

        # set a colormap
        c_map = cm.get_cmap('bwr')

        # width and height of the image
        w_ = self.img_frame.winfo_width()-self.pad_l
        h_ = self.img_frame.winfo_height()-self.pad_l

        # generate random noise
        random_map = np.random.random((h_, w_))

        # generate a meshgrid for the filter
        xv, yv = np.meshgrid(np.linspace(-int(w_ / 2.), int(w_ / 2.), w_),
                             np.linspace(-int(h_ / 2.), int(h_ / 2.), h_))

        # define correlation length and width
        if len(self.entry1.get()) > 0:
            clx = float(self.entry1.get())
        else:
            return

        if len(self.entry2.get()) > 0:
            cly = float(self.entry2.get())
        else:
            return

        #
        if self.cb.get().startswith('G'):
            # Gaussian filter
            filter_ = np.exp(-np.power(xv, 2) / clx - np.power(yv, 2) / cly)
        else:
            # Laplace filter
            filter_ = np.exp(-np.abs(xv) / clx - np.abs(yv) / cly)

        # this is a resulting map
        random_map = np.fft.ifft2(np.multiply(np.fft.fft2(random_map), np.fft.fft2(filter_)))
        random_map = np.real(random_map)

        # normalize to [0, 1]
        random_map -= np.min(random_map)
        random_map /= np.max(random_map)

        # create PhotoImage object to add on the panel
        img = ImageTk.PhotoImage(
            Image.fromarray(
                # image really likes unsigned ints))
                np.uint8(
                    # convert to colormap you like
                    c_map(
                        # give a random image to color map with values between 0 and 1
                        # np.random.random(
                        #     (self.img_frame.winfo_height()-self.pad_l, self.img_frame.winfo_width()-self.pad_l)
                        # )
                        random_map
                    )*255
                )
            )
        )

        # Gray colormap
        # img = ImageTk.PhotoImage(
        #     Image.fromarray(np.random.random_integers(0, 255,
        #                                   (self.img_frame.winfo_height()-self.pad_l,
        #                                    self.img_frame.winfo_width()-self.pad_l)).astype(np.int8)
        #                     ).convert('L')
        # )

        keys = self.img_frame.children.keys()
        for key in keys:
            self.img_frame.children[key].configure(image=img)
            self.img_frame.children[key].image = img

    def button_action(self):
        """
        """
        self.init_random_image()
Beispiel #12
0
class CMDHost(object):
    def __init__(self):
        # Styles
        self.style = MainWindowStyles()
        self.mw = Tk()
        self.setup()

    def setup(self):
        self.mw.title("Python Z-5212 Command Host " + c.port + ", " + c.baud)
        resize_and_center(self.mw, 800, 600)

        # Variables
        self.cmd_message = StringVar(self.mw, "--empty--")
        self.conn_status = StringVar(self.mw, '...')

        # Top Frame (name entry box, buttons, conn status)
        self.login_frame = Frame(self.mw, **self.style.Frame)
        self.lower_frame = Frame(self.mw, **self.style.Frame)
        self.login_frame.pack(side="top", fill="x")
        self.lower_frame.pack(side="top", fill="both", expand=1)

        # The lower left (message entry, chat history) and lower right
        self.left_frame = Frame(self.lower_frame, **self.style.Frame)
        self.right_frame = Frame(self.lower_frame, **self.style.Frame)
        self.right_frame.pack(side="right", fill="y")
        self.left_frame.pack(side="right", fill="both", expand=1)

        # The cmd entry & history frames
        self.message_frame = Frame(self.login_frame, **self.style.Frame)
        self.dialogue_frame = Frame(self.left_frame, **self.style.Frame)
        self.message_frame.pack(side="top", fill="x")
        self.dialogue_frame.pack(side="top", fill="both", expand=1)

        ###
        # Top Frame Widgets
        ###
        self.enter_Connecte_button = Button(self.login_frame,
                                            text="Connect",
                                            command=self.conn,
                                            **self.style.Button)
        self.enter_Connecte_button.pack(side="left", padx=5, pady=5)

        self.status_label = Label(self.login_frame,
                                  textvariable=self.conn_status,
                                  **self.style.Label).pack(side="left",
                                                           padx=5,
                                                           pady=5)

        self.enter_Connecte_button = Button(self.login_frame,
                                            text="Send CMD",
                                            command=self.send,
                                            **self.style.Button).pack(
                                                side="right", padx=5, pady=5)

        self.ports_Combobox = Combobox(self.login_frame,
                                       values=c.port,
                                       width=8)
        # assign function to combobox
        self.ports_Combobox.bind('<<ComboboxSelected>>', self.port_on_select)
        self.ports_Combobox.current(portindex)
        self.ports_Combobox.pack(side="left", padx=5, pady=5)

        self.baud_rate_Combo = Combobox(self.login_frame,
                                        values=c.baud,
                                        width=8)
        self.baud_rate_Combo.bind('<<ComboboxSelected>>',
                                  self.baud_rate_on_select)
        self.baud_rate_Combo.current(baudindex)
        self.baud_rate_Combo.pack(side="left", padx=5, pady=5)

        ###
        # Message Frame Widgets
        ###

        self.message_entry = Entry(self.message_frame,
                                   textvariable=self.cmd_message,
                                   state="disabled",
                                   **self.style.Entry)
        self.message_entry.pack(
            side="top",
            fill="x",
            padx=10,
            pady=10,
            expand=1,
        )

        ###
        # commandlist Frame Widgets
        ###

        self.commandlist_label = Label(self.right_frame,
                                       text="SSI Command List",
                                       anchor="w",
                                       **self.style.Label)
        self.commandlist_label.pack(side="top", fill="x")

        self.commandlist = Scrolled(
            self.right_frame,
            Listbox,
            attributes=self.style.Listbox,
            scrollbar=self.style.Scrollbar,
        )
        self.commandlist.pack(side="top", fill="both", expand=1)

        # Add command
        self.commandlist.widget.insert(END, "0x10 FLUSH_MACRO_PDF")
        self.commandlist.widget.insert(END, "0x11 ABORT_MACRO_PDF")
        self.commandlist.widget.insert(END, "0x12 CUSTOM_DEFAULTS")
        self.commandlist.widget.insert(END, "0x80 SSI_MGMT_COMMAND")
        self.commandlist.widget.insert(END, "0xA3 REQUEST_REVISION")
        self.commandlist.widget.insert(END, "0xA4 REPLY_REVISION")
        self.commandlist.widget.insert(END, "0xB0 Reserved")
        self.commandlist.widget.insert(END, "0xB1 IMAGE_DATA")
        self.commandlist.widget.insert(END, "0xB4 VIDEO_DATA")
        self.commandlist.widget.insert(END, "0xC0 ILLUMINATION_OFF")
        self.commandlist.widget.insert(END, "0xC1 ILLUMINATION_ON")
        self.commandlist.widget.insert(END, "0xC4 AIM_OFF")
        self.commandlist.widget.insert(END, "0xC5 AIM_ON")
        self.commandlist.widget.insert(END, "0xC6 PARAM_SEND")
        self.commandlist.widget.insert(END, "0xC7 PARAM_REQUEST")
        self.commandlist.widget.insert(END, "0xC8 PARAM_DEFAULTS")
        self.commandlist.widget.insert(END, "0xC9 CHANGE_ALL_CODE_TYPES")
        self.commandlist.widget.insert(END, "0xCA PAGER_MOTOR_ACTIVATION")
        self.commandlist.widget.insert(END, "0xD0 CMD_ACK")
        self.commandlist.widget.insert(END, "0xD1 CMD_NAK")
        self.commandlist.widget.insert(END, "0xD2 FLUSH_QUEUE")
        self.commandlist.widget.insert(END, "0xD3 CAPABILITIES_REQUEST")
        self.commandlist.widget.insert(END, "0xD4 CAPABILITIES_REPLY")
        self.commandlist.widget.insert(END, "0xD5 BATCH_REQUEST")
        self.commandlist.widget.insert(END, "0xD6 BATCH_DATA")
        self.commandlist.widget.insert(END, "0xD8 CMD_ACK_ACTION")
        self.commandlist.widget.insert(END, "0xE4 START_SESSION")
        self.commandlist.widget.insert(END, "0xE5 STOP_SESSION")
        self.commandlist.widget.insert(END, "0xE6 BEEP")
        self.commandlist.widget.insert(END, "0xE7 LED_ON")
        self.commandlist.widget.insert(END, "0xE8 LED_OFF")
        self.commandlist.widget.insert(END, "0xE9 SCAN_ENABLE")
        self.commandlist.widget.insert(END, "0xEA SCAN_DISABLE")
        self.commandlist.widget.insert(END, "0xEB SLEEP")
        self.commandlist.widget.insert(END, "0xF3 DECODE_DATA")
        self.commandlist.widget.insert(END, "0xF6 EVENT")
        self.commandlist.widget.insert(END, "0xF7 IMAGER_MODE")
        self.commandlist.widget.insert(END, "N/A WAKEUP")

        ###
        # Dialogue Frame Widgets
        ###

        self.dialogue_text = Scrolled(
            self.dialogue_frame,
            Text,
            attributes=self.style.Dialogue,
            scrollbar=self.style.Scrollbar,
        )
        self.chat_styles(self.dialogue_text.widget)
        self.dialogue_text.pack(side="top",
                                fill="both",
                                padx=10,
                                pady=0,
                                expand=1)

        # Dummy junk
        messages = [
            [["[JK] ", "Host"], ["Welcome to the JK SSI tool."]],
            [["[JK] ", "Host"], ["There are only a few rules:"]],
            [["[JK] ", "Host"], ["   Be respectful and sensitive to me"]],
            [["[JK] ", "Host"], ["   And HAVE FUN!"]],
            [["[JK] ", "Host"], [""]],
            [["[JK] ", "Host"],
             ["Termination of use can happen without warning!"]],
            [["[JK] ", "Host"], [""]],
            [["[JK] ", "Host"], ["JK SSI Tool version v0.01"]],
        ]

        for line in messages:
            self.insert_readonly(self.dialogue_text, 0.0, "\n")
            line.reverse()
            for part in line:
                self.insert_readonly(self.dialogue_text, 0.0, *part)
                #self.insert_readonly(self.dialogue_text, END, "[Admin]", "admin")

    @staticmethod
    def chat_styles(widget):
        """Configure chat text styles."""
        # User colors
        widget.tag_configure("user", foreground="#FFFFFF")
        widget.tag_configure("guest", foreground="#FF9900")
        widget.tag_configure("admin", foreground="#00FFFF")
        widget.tag_configure("server", foreground="#00FF00")
        widget.tag_configure("client", foreground="#FF0000")

    def insert_readonly(self, widget, *args):
        """Insert text into a readonly (disabled) widget."""
        widget.widget.configure(state="normal")
        widget.widget.insert(*args)
        widget.widget.configure(state="disabled")

    def start(self):
        self.mw.mainloop()

    def exit(self):
        self.serConnector.close()

    def conn(self):
        self.serConnector = connect(c)
        serConnector = self.serConnector
        if serConnector.is_open:
            self.conn_status.set('Open')
        else:
            self.conn_status.set('Connect fail')

    def send(self):
        value = self.commandlist.getSelectedIndex()
        print(self.commandlist.get(value))

    def baud_rate_on_select(self, event=None):
        print("event.widget:", event.widget.get())

    def port_on_select(self, event=None):
        print("event.widget:", event.widget.get())
Beispiel #13
0
class Game:

    version = "4.0"

    def __init__(self):
        self.root = Tk()
        self.initgui()
        self.gridgui()
        self.configurewidgets()

    def initgui(self):
        self.root.title("Tick tack toe")
        self.root.resizable(False, False)
        self.frame_board = Frame(self.root, bg="black")
        self.canvas = Canvas(self.frame_board,
                             width=600,
                             height=600,
                             bg="beige")

        self.frame_options = Frame(self.root)
        self.button_setup = Button(self.frame_options, text="Setup", width=10)
        self.button_start = Button(self.frame_options, text="Start", width=10)
        self.button_reset = Button(self.frame_options, text="Reset", width=10)
        self.button_reload = Button(self.frame_options,
                                    text="Load Bots",
                                    width=10)
        self.button_test = Button(self.frame_options, text="Test", width=10)

        self.entry_test = Entry(self.frame_options, width=10)

        self.label1 = Label(self.frame_options, text="Player 1")
        self.label2 = Label(self.frame_options, text="Player 2")
        self.combo1 = Combobox(self.frame_options, state="readonly")
        self.combo2 = Combobox(self.frame_options, state="readonly")

        self.entry_shape1 = Entry(self.frame_options, width=5)
        self.entry_shape2 = Entry(self.frame_options, width=5)

        self.label_size = Label(self.frame_options, text="Board Size")
        self.entry_size = Entry(self.frame_options, width=10)

        self.label_movements = Label(self.frame_options, text="Steps")
        self.movements = Listbox(self.frame_options, width=25, height=15)

        self.chainVar = 0
        self.button_chain = Button(self.frame_options,
                                   text="Show Chains",
                                   width=10)

        self.button_help = Button(self.frame_options, text="?", width=3)
        self.label_version = Label(self.frame_options,
                                   text="Version v" + self.version)

    def gridgui(self):
        self.frame_board.grid(row=0, column=0, padx=5, pady=5)
        self.canvas.grid(padx=5, pady=5)

        self.frame_options.grid(row=0, column=1, padx=5, pady=5)
        self.button_reload.grid(pady=5, columnspan=2)
        self.button_setup.grid(pady=5, columnspan=2)
        self.button_start.grid(pady=5, columnspan=2)
        self.button_test.grid(row=3, column=0, pady=5)
        self.entry_test.grid(row=3, column=1, pady=5)

        self.label1.grid(row=4, column=0, stick=W, pady=5)
        self.entry_shape1.grid(row=4, column=1)
        self.combo1.grid(stick=W, pady=5, columnspan=2)
        self.label2.grid(row=6, column=0, stick=W, pady=5)
        self.entry_shape2.grid(row=6, column=1)
        self.combo2.grid(stick=W, pady=5, columnspan=2)

        self.label_size.grid(row=8, stick=W, pady=5, columnspan=2)
        self.entry_size.grid(row=8, stick=E, pady=5, columnspan=2)

        self.button_chain.grid(columnspan=2)

        self.button_reset.grid(columnspan=2)

        self.label_movements.grid(columnspan=2)
        self.movements.grid(columnspan=2)
        self.label_version.grid(row=14, column=0, pady=5)
        self.button_help.grid(row=14, column=1, pady=5)

    def configurewidgets(self):
        self.reset(None)

        self.button_reload.bind("<ButtonRelease-1>", self.reloadbots)
        self.button_reset.bind("<ButtonRelease-1>", self.reset)
        self.button_chain.bind("<ButtonRelease-1>", self.drawChains)
        self.button_help.bind("<ButtonRelease-1>", self.helpGit)

    def helpGit(self, event):
        webbrowser.open("https://github.com/OmerCinal/Tic-Tac-Toe")

    def reloadbots(self, event):
        path = os.path.dirname(os.path.realpath(__file__))
        files = [
            f.split(".")[0] for f in os.listdir(path)
            if (os.path.isfile(path + "/" + f) and (f.split(".")[-1] == "py"))
        ]

        if "Game" in files:
            files.remove("Game")

        self.modules = dict(
            map((lambda x: (x.__name__, x)), map(__import__, files)))

        self.combo1["values"] = self.modules.keys()
        self.combo2["values"] = self.modules.keys()
        self.combo1.current(0)
        self.combo2.current(0)

        self.updateButtons()

    def setup(self, event):
        if not hasattr(self, "modules"):
            self.root.bell()
            return
        error = ""
        try:
            self.name1 = self.combo1.get()
            self.shape1 = self.entry_shape1.get()
            self.player1 = getattr(self.modules[self.name1], self.name1)(0, 1,
                                                                         2)
        except:
            error += " 1 "

        try:
            self.name2 = self.combo2.get()
            self.shape2 = self.entry_shape2.get()
            self.player2 = getattr(self.modules[self.name2], self.name2)(0, 2,
                                                                         1)
        except:
            error += " 2 "

        if error:
            self.message("Error with the following players:" + error)
            return

        self.size = self.validateSize(self.entry_size.get())
        self.movements.delete(0, END)

        if not self.size:
            self.message(
                "Board size cannot contain letters\nand it must be an even number"
            )
            return

        self.drawboard(self.size)
        self.board = [[0] * self.size for _ in range(self.size)]
        self.updateButtons()

    def drawboard(self, size):
        space = 50
        start = (space * 3) / 2
        board = self.canvas
        board.delete(ALL)

        for i in range(size):
            board.create_text(space * (i + 2),
                              space,
                              text=str(i),
                              anchor=W,
                              tag="coord",
                              font=50)
            board.create_text(space,
                              space * (i + 2),
                              text=str(i),
                              anchor=W,
                              tag="coord",
                              font=50)

        for i in range(size + 1):
            board.create_line(start,
                              start + space * i,
                              start + space * size,
                              start + space * i,
                              tag="line",
                              width=2.0,
                              fill="goldenrod")
            board.create_line(start + space * i,
                              start,
                              start + space * i,
                              start + space * size,
                              tag="line",
                              width=2.0,
                              fill="goldenrod")

    def start(self, event):
        if not hasattr(self, "board"):
            self.message("Please Set the game first")
            return
        self.board = [[0] * self.size for _ in range(self.size)]

        self.player1.board = self.board
        self.player2.board = self.board

        score1, score2, steps = self.playOnce(self.player1,
                                              self.player2,
                                              record=True)

        self.drawboard(self.size)
        self.updateboard()

        self.movements.delete(0, END)
        for step in steps:
            self.movements.insert(END, step)

        self.canvas.create_text(300,
                                25,
                                text="".join(
                                    (self.shape1, ": ", str(score1), ";  ",
                                     self.shape2, ": ", str(score2))))

    def test(self, event):
        if not hasattr(self, "board"):
            self.message("Please Set the game first")
            return

        try:
            testrange = self.validateInt(self.entry_test.get())
        except:
            self.message("Number of tests can only be integers")
            return

        clear = self.canvas.delete
        write = self.canvas.create_text
        update = self.canvas.update
        scores1 = [0] * testrange
        scores2 = [0] * testrange
        turn = True

        for step in range(testrange):
            self.board = [[0] * self.size for _ in xrange(self.size)]
            self.player1.board = self.board
            self.player2.board = self.board
            if turn:
                scores1[step], scores2[step] = self.playOnce(
                    self.player1, self.player2)
                turn = False
            else:
                scores2[step], scores1[step] = self.playOnce(
                    self.player2, self.player1)
                turn = True

            if step % 10 == 0:
                clear(ALL)
                write(300,
                      100,
                      text="".join(
                          ("Games played: %", str(
                              (step * 100.0) / testrange))),
                      font=50)
                update()

        avg1 = sum(scores1) / len(scores1)
        avg2 = sum(scores2) / len(scores2)
        wins1, wins2, ties = 0, 0, 0

        for p1, p2 in zip(scores1, scores2):
            if p1 > p2:
                wins1 += 1
            elif p1 < p2:
                wins2 += 1
            else:
                ties += 1

        result = [
            "Results:", "", self.name1 + " (" + self.shape1 + ")",
            self.name2 + " (" + self.shape2 + ")", "",
            "Player:\t" + self.shape1 + ",\t" + self.shape2,
            "Wins:  \t" + str(wins1) + ",\t" + str(wins2),
            "Avg:   \t" + str(avg1) + ",\t" + str(avg2),
            "Ties:  \t" + str(ties), "",
            "Winner: " + (self.shape1 if wins1 > wins2 else self.shape2)
        ]

        self.canvas.delete(ALL)
        self.canvas.create_text(100,
                                100,
                                text="\n".join(result),
                                anchor=NW,
                                font=50)

    def playOnce(self, player1, player2, record=False, show=False):
        play1 = player1.play
        play2 = player2.play

        if record:
            step = 1
            steps = []
        while not self.endgame():
            x1, y1 = play1()
            self.board[x1][y1] = 1

            x2, y2 = play2()
            self.board[x2][y2] = 2

            if show:
                self.updateboard()

            if record:
                steps.append("".join(
                    (str(step), "- ", self.shape1, ": (", str(x1),
                     ", ", str(y1), "); ", self.shape2, ": (", str(x2), ", ",
                     str(y2), ")")))
                step += 1

        s1, s2 = self.getScores(1, 2)
        if record:
            return s1, s2, steps
        return s1, s2

    def updateboard(self):
        write = self.canvas.create_text
        rng = range(self.size)
        space = 50
        self.canvas.delete("shape")

        for x in rng:
            for y in rng:
                if self.board[x][y] == 1:
                    write(space * (y + 2),
                          space * (x + 2),
                          text=self.shape1,
                          tags=("shape1", "shape"),
                          font=("Times", 20, "bold"))
                elif self.board[x][y] == 2:
                    write(space * (y + 2),
                          space * (x + 2),
                          text=self.shape2,
                          tags=("shape2", "shape"),
                          font=("Times", 20, "bold"))

    def reset(self, event):
        self.canvas.delete(ALL)
        if hasattr(self, "modules"): del self.modules
        if hasattr(self, "board"): del self.board
        self.combo1["values"] = ("None")
        self.combo2["values"] = ("None")
        self.combo1.current(0)
        self.combo2.current(0)
        self.entry_size.delete(0, END)
        self.entry_test.delete(0, END)
        self.entry_shape1.delete(0, END)
        self.entry_shape2.delete(0, END)
        self.entry_size.insert(END, "10")
        self.entry_shape1.insert(END, "X")
        self.entry_shape2.insert(END, "O")
        self.entry_test.insert(END, "1000")
        self.movements.delete(0, END)

        msg = """
        Tic Tac Toe
        
        1-Load the bots inside the directory by pressing "Load Bots"
        2-Configure the game and press "Setup"
        3-"Start" for one game
          "Test" for # of games

        Click the question mark for more information
        """
        self.canvas.create_text(100, 100, text=msg, font=100, anchor=W)

        self.updateButtons()

    def message(self, msg):
        self.canvas.delete(ALL)
        self.canvas.create_text(300, 100, text=msg, font=20)
        self.root.bell()

    def updateButtons(self):
        if hasattr(self, "modules"):
            self.button_setup["state"] = NORMAL
            self.button_setup.bind("<ButtonRelease-1>", self.setup)
        else:
            self.button_setup["state"] = DISABLED
            self.button_setup.unbind("<ButtonRelease-1>")
        if hasattr(self, "board"):
            self.button_start["state"] = NORMAL
            self.button_test["state"] = NORMAL
            self.button_start.bind("<ButtonRelease-1>", self.start)
            self.button_test.bind("<ButtonRelease-1>", self.test)
        else:
            self.button_start["state"] = DISABLED
            self.button_test["state"] = DISABLED
            self.button_start.unbind("<ButtonRelease-1>")
            self.button_test.unbind("<ButtonRelease-1>")

    def getScores(self, p1, p2):
        def getHorizontal(x, y, p):
            x1, x2 = x, x
            while x1 > 0:
                if self.board[x1 - 1][y] == p:
                    x1 -= 1
                else:
                    break

            while x2 < self.size - 1:
                if self.board[x2 + 1][y] == p:
                    x2 += 1
                else:
                    break

            return (x1, y, x2, y) if (x2 - x1) > 1 else 0

        def getVertical(x, y, p):
            y1, y2 = y, y
            while y1 > 0:
                if self.board[x][y1 - 1] == p:
                    y1 -= 1
                else:
                    break

            while y2 < self.size - 1:
                if self.board[x][y2 + 1] == p:
                    y2 += 1
                else:
                    break

            return (x, y1, x, y2) if (y2 - y1) > 1 else 0

        def getDiagonal1(x, y, p):
            x1, y1, x2, y2 = x, y, x, y
            while x1 > 0 and y1 > 0:
                if self.board[x1 - 1][y1 - 1] == p:
                    x1 -= 1
                    y1 -= 1
                else:
                    break

            while x2 < self.size - 1 and y2 < self.size - 1:
                if self.board[x2 + 1][y2 + 1] == p:
                    x2 += 1
                    y2 += 1
                else:
                    break

            return (x1, y1, x2, y2) if ((x2 - x1 > 1) or (y2 - y1 > 1)) else 0

        def getDiagonal2(x, y, p):
            x1, y1, x2, y2 = x, y, x, y
            while x1 < self.size - 1 and y1 > 0:
                if self.board[x1 + 1][y1 - 1] == p:
                    x1 += 1
                    y1 -= 1
                else:
                    break

            while x2 > 0 and y2 < self.size - 1:
                if self.board[x2 - 1][y2 + 1] == p:
                    x2 -= 1
                    y2 += 1
                else:
                    break

            return (x1, y1, x2, y2) if ((x2 - x1 > 1) or (y2 - y1 > 1)) else 0

        self.chains = {p1: [], p2: []}  #p:[ (x1,y1,x2,y2) ]
        rng = range(len(self.board))

        for x in rng:
            for y in rng:
                player = self.board[x][y]

                hor = getHorizontal(x, y, player)
                ver = getVertical(x, y, player)
                crs1 = getDiagonal1(x, y, player)
                crs2 = getDiagonal2(x, y, player)

                self.chains[player].extend(
                    filter((lambda x: x and (x not in self.chains[player])),
                           [hor, ver, crs1, crs2]))

        scores = {p1: 0, p2: 0}

        for player in self.chains:
            for chain in self.chains[player]:
                length = max(chain[2] - chain[0], chain[3] - chain[1]) + 1
                scores[player] += sum(range(3, length + 1))

        return scores[p1], scores[p2]

    def drawChains(self, event):
        if self.canvas.find_withtag("chain"):
            self.canvas.delete("chain")
            return
        if not self.canvas.find_withtag("shape") or not hasattr(
                self, "chains"):
            return
        space = 50
        start = 2 * space
        colors = {1: "red", 2: "blue"}
        for p in self.chains:
            for x1, y1, x2, y2 in self.chains[p]:
                self.canvas.create_line(start + y1 * space,
                                        start + x1 * space,
                                        start + y2 * space,
                                        start + x2 * space,
                                        fill=colors[p],
                                        tag="chain",
                                        state=NORMAL,
                                        width=5.0)

    def endgame(self):
        for row in self.board:
            if not all(row):
                return False
        return True

    @staticmethod
    def validateSize(val):
        try:
            if int(val) % 2 == 0:
                return int(val)
            return False
        except:
            return False

    @staticmethod
    def validateInt(val):
        try:
            return int(val)
        except:
            return False
Beispiel #14
0
class MainFrame(Frame):
    def __init__(self, parent, stdoutq):
        Frame.__init__(self, parent)

        self.parent = parent
        self.width = 750
        self.height = 450
        self.title = ximaexport.__version__
        self.stdoutq = stdoutq

        self.initUI()

        self.hasdb = False
        self.hasout = False
        self.exit = False

        self.path_frame = self.addPathFrame()
        self.action_frame = self.addActionFrame()
        self.message_frame = self.addMessageFrame()
        self.printStr()

        self.stateq = Queue.Queue()

    def centerWindow(self):
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        x = (sw - self.width) / 2
        y = (sh - self.height) / 2
        self.parent.geometry('%dx%d+%d+%d' \
                %(self.width,self.height,x,y))

    def initUI(self):
        self.parent.title(self.title)
        self.style = Style()
        #Choose from default, clam, alt, classic
        self.style.theme_use('alt')
        self.pack(fill=tk.BOTH, expand=True)
        self.centerWindow()

    def printStr(self):
        while self.stdoutq.qsize() and self.exit == False:
            try:
                msg = self.stdoutq.get()
                self.text.update()
                self.text.insert(tk.END, msg)
                self.text.see(tk.END)
            except Queue.Empty:
                pass
        self.after(100, self.printStr)

    def checkReady(self):

        if self.hasdb and self.hasout:
            self.start_button.configure(state=tk.NORMAL)
            #print('XimaExport Ready.')
            printch('XimaExport 就绪.')
        else:
            self.start_button.configure(state=tk.DISABLED)

    def addPathFrame(self):
        frame = Frame(self)
        frame.pack(fill=tk.X, expand=0, side=tk.TOP, padx=8, pady=5)

        frame.columnconfigure(1, weight=1)

        #------------------Database file------------------
        label=tk.Label(frame,text=dgbk('ting.sqlite文件:'),\
                bg='#bbb')
        label.grid(row=0,column=0,\
                sticky=tk.W,padx=8)

        self.db_entry = tk.Entry(frame)
        self.db_entry.grid(row=0, column=1, sticky=tk.W + tk.E, padx=8)

        self.db_button = tk.Button(frame,
                                   text=dgbk('打开'),
                                   command=self.openFile)
        self.db_button.grid(row=0, column=2, padx=8, sticky=tk.E)

        #--------------------Output dir--------------------
        label2=tk.Label(frame,text=dgbk('导出到文件夹:'),\
                bg='#bbb')
        label2.grid(row=2,column=0,\
                sticky=tk.W,padx=8)

        self.out_entry = tk.Entry(frame)
        self.out_entry.grid(row=2, column=1, sticky=tk.W + tk.E, padx=8)
        self.out_button = tk.Button(frame,
                                    text=dgbk('选择'),
                                    command=self.openDir)
        self.out_button.grid(row=2, column=2, padx=8, sticky=tk.E)

    def openDir(self):
        self.out_entry.delete(0, tk.END)
        dirname = askdirectory()
        self.out_entry.insert(tk.END, dirname)
        if len(dirname) > 0:
            #print('Output folder: %s' %dirname)
            printch('输出到文件夹:')
            print('   ' + dirname)
            self.hasout = True
            self.checkReady()

    def openFile(self):
        self.db_entry.delete(0, tk.END)
        ftypes = [('sqlite files', '*.sqlite'), ('ALL files', '*')]
        filename = askopenfilename(filetypes=ftypes)
        self.db_entry.insert(tk.END, filename)
        if len(filename) > 0:
            #print('Database file: %s' %filename)
            printch('数据文件:')
            print('   ' + filename)
            self.probeAlbums()

    def probeAlbums(self):
        dbfile = self.db_entry.get()
        try:
            db = sqlite3.connect(dbfile)
            df = ximaexport.getData(db)
            self.albumlist = ximaexport.getAlbumList(df, None)  #(id, name)
            self.albumnames = ['All'] + [ii[1] for ii in self.albumlist
                                         ]  #names to display
            self.albummenu['values'] = tuple(self.albumnames)
            self.albummenu.current(0)
            db.close()

            self.hasdb = True
            self.checkReady()

        except Exception as e:
            #print('Failed to recoganize the given database file.')
            printch('无法识别sqlite数据文件.')
            print(e)

    def addActionFrame(self):

        frame = Frame(self, relief=tk.RAISED, borderwidth=1)
        frame.pack(fill=tk.X,side=tk.TOP,\
                expand=0,padx=8,pady=5)

        #label=tk.Label(frame,text='Actions:',bg='#bbb')
        #label.grid(row=0,column=0,sticky=tk.W,padx=8)

        #---------------Action checkbuttons---------------
        frame.columnconfigure(0, weight=1)

        #---------------------2nd row---------------------
        subframe = Frame(frame)
        subframe.grid(row=1,column=0,columnspan=6,sticky=tk.W+tk.E,\
                pady=5)

        #-------------------Album options-------------------
        albumlabel=tk.Label(subframe,text=dgbk('专辑:'),\
                bg='#bbb')
        albumlabel.pack(side=tk.LEFT, padx=8)

        self.album = tk.StringVar()
        self.albumnames = [
            'All',
        ]
        self.albummenu=Combobox(subframe,textvariable=\
                self.album,values=self.albumnames,state='readonly')
        self.albummenu.current(0)
        self.albummenu.bind('<<ComboboxSelected>>', self.setAlbum)
        self.albummenu.pack(side=tk.LEFT, padx=8)

        #-------------------Quit button-------------------
        quit_button=tk.Button(subframe,text=dgbk('退出'),\
                command=self.quit)
        quit_button.pack(side=tk.RIGHT, padx=8)

        #-------------------Stop button-------------------
        '''
        self.stop_button=tk.Button(subframe,text='Stop',\
                command=self.stop)
        self.stop_button.pack(side=tk.RIGHT,padx=8)
        '''

        #-------------------Start button-------------------
        self.start_button=tk.Button(subframe,text=dgbk('开始'),\
                command=self.start,state=tk.DISABLED)
        self.start_button.pack(side=tk.RIGHT, pady=8)

        #-------------------Help button-------------------
        self.help_button=tk.Button(subframe,text=dgbk('帮助'),\
                command=self.showHelp)
        self.help_button.pack(side=tk.RIGHT, padx=8)

    def setAlbum(self, x):
        import json
        self.albummenu.selection_clear()
        self.album = self.albummenu.get()
        self.albummenu.set(self.album)
        if self.album == 'All':
            #print('Work on all albums.')
            printch('导出所有专辑.')
        else:
            #print('Select album: '+self.album)
            printch('导出所选专辑:')
            print('   ' + self.album)

    def showHelp(self):
        helpstr = dgbk('''\n\n
导出喜马拉雅下载音频,并自动按专辑归档、重命名:\n
1. 找到手机/pad中的喜马拉雅数据文件夹:\n
    (1)苹果用户:链接电脑itunes,在app一栏中找到“喜马拉雅”,单击,右侧会出现“喜马拉雅”的数据文件。选择“iDoc”,并导出到电脑。\n
    (2)安卓用户:链接电脑后,拷贝出ting文件夹。\n
2. 运行ximaexport-gui.exe。\n
    在 “ting.sqlite文件”一栏,选择步骤1中拷贝出的文件夹里的 ting.sqlite. 文件。\n
    在 “导出到文件夹”一栏,选择音频存储位置。\n
    在 “专辑”下拉菜单,选择要导出的专辑。若全部导出选择“All”。\n
    点击“开始”开始处理。
''')

        tkMessageBox.showinfo(title='Help', message=helpstr)
        #print(self.menfolder.get())

    def start(self):
        dbfile = self.db_entry.get()
        outdir = self.out_entry.get()
        self.album = self.albummenu.get()

        self.out_button.configure(state=tk.DISABLED)
        self.start_button.configure(state=tk.DISABLED)
        self.help_button.configure(state=tk.DISABLED)
        self.albummenu.configure(state=tk.DISABLED)
        self.messagelabel.configure(text=dgbk('信息 (处理中...)'))

        album = None if self.album == 'All' else self.album

        args = [dbfile, outdir, album, True]

        self.workthread = WorkThread('work', False, self.stateq)
        self.workthread.deamon = True

        self.workthread.args = args
        self.workthread.start()
        self.reset()

    def reset(self):
        while self.stateq.qsize() and self.exit == False:
            try:
                msg = self.stateq.get()
                if msg == 'done':
                    self.db_button.configure(state=tk.NORMAL)
                    self.out_button.configure(state=tk.NORMAL)
                    self.start_button.configure(state=tk.NORMAL)
                    self.help_button.configure(state=tk.NORMAL)
                    self.albummenu.configure(state='readonly')
                    self.messagelabel.configure(text=dgbk('消息'))
                    return
            except Queue.Empty:
                pass
        self.after(100, self.reset)

    def stop(self):
        #self.workthread.stop()
        pass

    def addMessageFrame(self):
        frame = Frame(self)
        frame.pack(fill=tk.BOTH,side=tk.TOP,\
                expand=1,padx=8,pady=5)

        self.messagelabel = tk.Label(frame, text=dgbk('消息'), bg='#bbb')
        self.messagelabel.pack(side=tk.TOP, fill=tk.X)

        self.text = tk.Text(frame)
        self.text.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        self.text.height = 10

        scrollbar = tk.Scrollbar(self.text)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

        self.text.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.text.yview)
Beispiel #15
0
class CoreGUI(object):
    def __init__(self):
        self.mw = Tk()
        self.style = MainWindowStyles()
        self.quality = IntVar()
        self.setup(self.mw)

    def setup(self, parent):
        parent.title("Z5212 Debug Client by 2017 ZEBEX, Inc. Version 1.3")
        resize_and_center(parent, 900, 480)

        self.conn_status = StringVar()
        self.conn_status.set('...')

        # Top Frame (name entry box, buttons, conn status)
        self.conn_frame = Frame(parent, **self.style.Frame)
        self.conn_frame.pack(side="top", fill="x")

        self.lower_frame = Frame(parent, **self.style.Frame)
        self.lower_frame.pack(side="top", fill="both", expand=1)

        # The message entry
        self.display_frame = Frame(self.lower_frame, **self.style.Frame)
        self.display_frame.pack(side="top",
                                fill="both",
                                expand=1,
                                padx=5,
                                pady=5)

        self.right_frame = Frame(self.lower_frame, **self.style.Frame)
        self.right_frame.pack(side="right", fill="y")

        ###
        # Top Frame Widgets
        ###
        self.name_label = Label(self.conn_frame,
                                textvariable=self.conn_status,
                                **self.style.Label).pack(side="left",
                                                         padx=5,
                                                         pady=5)

        Button(self.conn_frame, text='連線', command=self.conn, **self.style.SettingButton)\
            .pack(side="left", padx=5, pady=5)

        Button(self.conn_frame, text="重新開始", command=self.reopen, **self.style.SettingButton)\
            .pack(side="left", padx=5, pady=5)

        self.ports_Combobox = Combobox(self.conn_frame, values=c.port, width=8)
        # assign function to combobox
        self.ports_Combobox.bind('<<ComboboxSelected>>', self.port_on_select)
        self.ports_Combobox.current(portindex)

        self.baud_rate_Combo = Combobox(self.conn_frame,
                                        values=c.baud,
                                        width=8)
        self.baud_rate_Combo.bind('<<ComboboxSelected>>',
                                  self.baud_rate_on_select)
        self.baud_rate_Combo.current(baudindex)

        self.enter_exit_button = Button(self.conn_frame,
                                        text="回復預設值",
                                        command=self.quit,
                                        **self.style.Button)

        self.ports_Combobox.pack(side="left", padx=5, pady=5)
        self.baud_rate_Combo.pack(side="left", padx=5, pady=5)
        self.enter_exit_button.pack(side="left", padx=5, pady=5)

        ###
        # Image Frame Widgets get image, set quality
        ###

        self.img_frame = Frame(self.conn_frame, **self.style.Frame)
        image_q_label = Label(self.img_frame,
                              text='Quality',
                              anchor="w",
                              **self.style.Label)
        image_q_label.pack(side=LEFT, fill="x")
        self.quality.set(85)
        Radiobutton(self.img_frame,
                    text='L',
                    variable=self.quality,
                    value=35,
                    command=self.selected_quality).pack(side=RIGHT, anchor="w")
        Radiobutton(self.img_frame,
                    text='M',
                    variable=self.quality,
                    value=85,
                    command=self.selected_quality).pack(side=RIGHT, anchor="w")
        Radiobutton(self.img_frame,
                    text='H',
                    variable=self.quality,
                    value=93,
                    command=self.selected_quality).pack(side=RIGHT, anchor="w")

        self.img_frame.pack(side="left", padx=5, pady=5)

        Button(self.conn_frame,
               text='拍照',
               command=self.getimg,
               **self.style.SettingButton).pack(side="left", padx=5, pady=5)

        ###
        # Display Frame Widgets
        ###
        self.display_frame.configure(background='#666666')
        # Create a canvas
        self.canvas = Canvas(self.display_frame,
                             width=640,
                             height=360,
                             bg="#666666")
        self.loadImage('Capture.jpg')

    def conn(self):
        self.conn_status.set("...")
        c = Config('')
        c.baud = self.baud_rate_Combo.get()
        c.port = self.ports_Combobox.get()
        c.isRs232 = int(c.baud) - 115200 <= 0
        c.dump()
        self.serConnector = connect(c)
        serConnector = self.serConnector
        Has_response = handshake(self.serConnector)
        if Has_response:
            setDefault(c, self.serConnector)
            self.conn_status.set('已連線')
            commGUI(self.right_frame, c.Gain, self.serConnector, "Gain")
            commGUI(self.right_frame, c.Shutter, self.serConnector, "Shutter")
            commGUI(self.right_frame, c.light, self.serConnector, "light")

    def baud_rate_on_select(self, event=None):
        print("event.widget:", event.widget.get())

    def port_on_select(self, event=None):
        print("event.widget:", event.widget.get())

    def quit(self):
        self.serConnector.write("quit".encode('ascii') + '\r\n')

    def reopen(self):
        portindex = self.ports_Combobox.getint
        baudindex = self.baud_rate_Combo.getint
        try:
            self.serConnector.close()
        except AttributeError:
            pass
        self.mw.destroy()
        app = CoreGUI()

    def getimg(self):
        self.canvas.delete("all")
        getImage("image" + str(self.quality.get()), self.serConnector,
                 c.isRs232)
        self.loadImage('Capture.jpg')

    def loadImage(self, filename):
        # Load the image file
        try:
            im = Image.open(filename)
        except IOError:
            print 'IOError'
            return
        # Put the image into a canvas compatible class, and stick in an
        # arbitrary variable to the garbage collector doesn't destroy it
        self.canvas.image = ImageTk.PhotoImage(im)
        # Add the image to the canvas, and set the anchor to the top left / north west corner
        self.canvas.create_image(0, 0, image=self.canvas.image, anchor='nw')
        self.canvas.pack()

    def start(self):
        self.mw.mainloop()

    def selected_quality(self):
        pass
Beispiel #16
0
    class Monitor(Frame):
        def __init__(self, parent, port, baud_rate, ser, toolchain, bii):
            '''
            Params:
                parent: The parent Frame
                port: string
                baud_rate:
                ser: serial
            '''

            Frame.__init__(self, parent)
            self.parent = parent
            self.port = port
            self.baud_rate = baud_rate
            self.ser = ser
            self.toolchain = toolchain
            self.bii = bii
            self.initUI()

        def initUI(self):
            self.parent.title("Biicode serial monitor %s" % self.port)
            self.style = Style()  # We need to define a style, otherwhise seems flat whit in macos
            self.style.theme_use(get_style())
            for x in range(1):
                Grid.columnconfigure(self, x, weight=1)
            for y in [1, 2]:
                Grid.rowconfigure(self, y, weight=1)

            self._make_top_bar()
            self._make_user_input()
            self._make_rcv_log()
            self._make_button_bar()

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

            self.serial_buffer = ""
            self.count = 0
            self.running = True
            self.after(50, self.read_serial)  # check serial again soon

        def _make_top_bar(self):
            menubar = Menu(self.parent)
            filemenu = Menu(menubar, tearoff=0)
            biimenu = Menu(menubar, tearoff=0)
            editmenu = Menu(menubar, tearoff=0)

            biimenu.add_command(label="Work (Save and process)", command=self.bii.work)
            biimenu.add_command(label="Find", command=self.bii.find)
            menubar.add_cascade(label="bii", menu=biimenu)

            filemenu.add_command(label="Flash code", command=self.upload)
            filemenu.add_separator()
            filemenu.add_command(label="Exit", command=self.parent.quit)
            menubar.add_cascade(label="File", menu=filemenu)

            editmenu.add_command(label="Clear", command=self.clear)
            # editmenu.add_separator()
            menubar.add_cascade(label="Edit", menu=editmenu)
            self.parent.config(menu=menubar)

        def _make_button_bar(self):
            self.button_upload = Button(self, text="Flash code", command=self.upload)
            self.button_upload.style = self.style
            self.button_upload.grid(row=0, column=0, padx=2, pady=2)

            self.baud_rate = 9600
            self.button_combobox = Combobox(self)
            self.button_combobox.bind("<<ComboboxSelected>>", self._update_baud_rate)
            bauds = (300, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, 115200)
            self.button_combobox['values'] = bauds
            self.button_combobox.current(4)
            self.button_combobox.grid(row=3, column=1, padx=2, pady=2)

        def _make_user_input(self):
            # make user input
            self.user_input = Text(self, width=52, height=3, takefocus=1,
                                   borderwidth=1, relief='ridge')
            self.user_input.grid(row=1, column=0, padx=2, pady=2, sticky=N + S + E + W)

            # make send button
            self.button_send = Button(self, text="Send", command=self.send_clicked)
            self.button_send.style = self.style
            self.button_send.grid(row=1, column=1, padx=2, pady=2, sticky=N + S + E + W)

        def _make_rcv_log(self):
            # make receive log
            recvLogFrame = Frame(self, width=400, height=200)
            recvLogFrame.style = self.style
            recvLogFrame.grid(row=2, column=0, padx=2, pady=2, sticky=N + S + E + W)
            self.start_stop_button = Button(self, text="Stop", command=self.start_stop_clicked)
            self.start_stop_button.style = self.style
            self.start_stop_button.grid(row=2, column=1, padx=2, pady=2, sticky=N + S + E + W)

            # make a scrollbar
            self.scrollbar = Scrollbar(recvLogFrame)
            self.scrollbar.pack(side=RIGHT, fill=Y)

            # make a text box to put the serial output
            self.log = Text(recvLogFrame, width=50, height=30, takefocus=0,
                            borderwidth=1, relief='ridge')
            self.log.pack(fill=BOTH, expand=True)

            # attach text box to scrollbar
            self.log.config(yscrollcommand=self.scrollbar.set)
            self.scrollbar.config(command=self.log.yview)

        def send_clicked(self):
            data = str(self.user_input.get(1.0, "end-1c") + '\0')
            self.ser.write(data)
            self._log(data)
            self.user_input.delete(1.0, END)

        def _log(self, msg):
            # if platform.system() == 'Darwin':
            #    print '>> %s' % msg
            # else:
            self.log.insert(END, '\n>> %s' % msg)
            self.log.yview(END)
            self.update_idletasks()

        def clear(self):
            self.log.delete(1.0, END)
            self.update_idletasks()

        def start_stop_clicked(self):
            if self.running:
                self.running = False
                self.start_stop_button['text'] = 'Start'
            else:
                self.running = True
                self.start_stop_button['text'] = 'Stop'
                self.read_serial()  # check serial again soon

        def upload(self):
            self.bii.work()
            try:
                if platform.system() == 'Darwin':
                    self.toolchain.upload()
                else:
                    self.ser.close()
                    self.toolchain.upload()
                    self.ser.open()
                self._log('** Code uploaded **')
            except BiiException:
                self._log('** Code upload failed **')

        def _update_baud_rate(self, event=None):
            new_rate = self.button_combobox.get()
            if new_rate != self.baud_rate:
                self.baud_rate = new_rate
                self.ser.setBaudrate(new_rate)
                logger.debug('Updated serial speed to %s' % new_rate)
                self.update_idletasks()

        def read_serial(self):
            self.log.update()  # display input text

            self._read_character()
            if self.running:
                self.after(100, self.read_serial)  # check serial again soon
            self.after(100, self.update_idletasks)

        def _read_character(self):
            try:
                c = self.ser.read()  # attempt to read a character from Serial
            except SerialException as e:
                logger.error("Couldn't read serial port: %s" % str(e))
                return

            # was anything read?
            while len(c) > 0 and c != '\r':
                # get the buffer from outside of this function
                # check if character is a delimeter
                if c == '\r':
                    c = ''  # don't want returns. chuck it
                if c == '\n':
                    # self.serial_buffer += "\n"  # add the newline to the buffer
                    self.log.insert(END, "\n")
                    self.log.insert(END, self.serial_buffer)
                    self.log.yview(END)
                    self.update_idletasks()
                    self.serial_buffer = ""  # empty the buffer
                else:
                    self.serial_buffer += c  # add to the buffer
                c = self.ser.read()
Beispiel #17
0
class LoggerDialog(Toplevel):
    def __init__(self, master, customers, payments, refresh):
        Toplevel.__init__(self,master)

        self.root = master
        self.refresh = refresh

        self.title("Check In")
        self.iconname = "Check In"

        self.name = StringVar() # variable for customer
        self.customers = customers # customers object
        self.payments = payments
        self.names = []
        self.workout = StringVar()
        self.workouts = []
        self.workouts_form = []
        self.date = StringVar()
        self.date.set(strftime("%m/%d/%Y"))
        self.refresh_time = 15 # in minutes
        self.output = '' # for the output label at the bottom
        self.schedule = Schedule()

        self.logger = Logger() #throws IOError if file is open

        inf = Frame(self)
        inf.pack(padx=10,pady=10,side='top')
        Label(inf, text="Name:").grid(row=0,column=0,sticky=E,ipady=2,pady=2,padx=10)
        Label(inf, text='Date:').grid(row=1,column=0,sticky=E,ipady=2,pady=2,padx=10)
        Label(inf, text="Workout:").grid(row=2,column=0,sticky=E,ipady=2,pady=2,padx=10)

        self.name_cb = Combobox(inf, textvariable=self.name, width=30,
                                values=self.names)
        self.name_cb.grid(row=0,column=1,sticky=W,columnspan=2)
        self.date_ent = Entry(inf, textvariable=self.date)
        self.date_ent.grid(row=1,column=1,sticky=W)
        self.date_ent.bind('<FocusOut>', self.update_workouts)
        Button(inf,text='Edit', command=self.enable_date_ent).grid(row=1,column=2,sticky=E)
        self.workout_cb = Combobox(inf, textvariable=self.workout, width=30,
                                   values=self.workouts_form,state='readonly')
        self.workout_cb.grid(row=2,column=1,sticky=W,columnspan=2)

        self.log_btn=Button(inf,text="Log Workout",command=self.log,width=12)
        self.log_btn.grid(row=3,column=1,columnspan=2,pady=4,sticky='ew')
        
        stf = Frame(self)
        stf.pack(padx=10,pady=10,fill='x',side='top')
        self.scrolled_text = ScrolledText(stf,height=15,width=50,wrap='word',state='disabled')
        self.scrolled_text.pack(expand=True,fill='both')

        self.update_workouts()
        self.update_names()

        self.bind('<Return>',self.log)
        self.name_cb.focus_set()  # set the focus here when created

        #disable the date field
        self.disable_date_ent()

        #start time caller
        self.time_caller()

    def output_text(self,outstr):
        self.scrolled_text['state'] = 'normal'
        self.scrolled_text.insert('end',outstr)
        self.scrolled_text.see('end')
        self.scrolled_text['state'] = 'disabled'

    def log(self, e=None):
        #check to see if name is blank
        logged = False
        if self.name.get() == '':
            self.output_text("! - Please select your name.\n")
        elif self.workout.get() not in self.workouts_form:
            self.output_text("! - Select valid workout.\n")
        elif self.name.get() not in self.names: # new customer
            self.new_customer_error()
        else: # log the workout
            name = self.name.get().split(' ',2)
            (line, r) = self.customers.find(name[2],name[0],name[1])
            name_str = str(self.name.get())
            date = datetime.strptime(str(self.date.get()),'%m/%d/%Y')

            if not line:
                self.output_text("!! - No record: " + self.name.get() + ".\n")

            while (not logged):
                try:
                    self.logger.log(self.workouts[self.workout_cb.current()][0],
                                    self.workouts[self.workout_cb.current()][1],
                                    name_str, day=date)
                    logged = True
                except IOError:
                    showerror("Error writting to file", "Please close " + self.logger.filename + " and press OK.")


            if logged:
                self.output_text(self.name.get() + " - " + line[3] + "\n")
                logged_payment = False
                while(not logged_payment):
                    try:
                        if line[3] == 'Monthly':
                            payment_due = self.payments.next_payment_due(name_str)
                            if payment_due < datetime.today():
                                self.output_text("$ - Please pay your monthly dues.\n")
                            else:
                                self.output_text("$ - Next payment due: " + payment_due.strftime("%B %d, %Y\n"))
                        elif line[3] == 'Punch Card':
                            punch = self.payments.punch(name_str)
                            if punch == 0:
                                self.output_text("$ - Last punch on card, please purchase another.\n")
                            elif not punch:
                                self.output_text("$ - Please purchase another punch card.\n")
                            else:
                                self.output_text("$ - You have " + str(punch) + " remaining workouts on your card.\n")
                        elif line[3] == 'Drop In':
                            self.payments.drop_in(name_str, date)
                            self.output_text("$ - Drop In payment logged.\n")
                        logged_payment = True
                    except IOError:
                        # this is bad, you logged a workout and you failed to log payment
                        showerror("Error writting to file", "Please close " + self.payments.filename + " and press OK.")
                    else:
                        #exception not raised
                        try: #accessing log file here
                            workout_count = str(workouts_this_month(name_str,self.logger.filename,date.strftime("%B"))) 
                            self.output_text("Workouts you've completed this month: " + workout_count + "\n")
                        except IOError:
                            showerror("Error reading from file", "Please close " + self.logger.filename + " and press OK.")

                self.refresh()
            
    def new_customer_error(self):
        self.ncd = NewCustomerDialog(self,self.customers,self.refresh)
        if askquestion(title="New Customer?",
            message="Add new customer: " + self.name.get(),
            parent = self) == 'yes':

            temp = self.name.get().split(' ')
            self.ncd.fname.set(temp[0])
            if len(temp) == 2:
                self.ncd.lname.set(temp[1])
            elif len(temp) == 3:
                self.ncd.mname.set(temp[1])
                self.ncd.lname.set(temp[2])
            elif len(temp) > 3:
                self.ncd.mname.set(temp[1])
                self.ncd.lname.set(' '.join(temp[2:4]))

            self.ncd.show()

        if self.ncd.new_customer_name:
            self.add_name(self.ncd.new_customer_name)
            self.output_text("+ - " + self.ncd.new_customer_name + " added.\n")

    def disable_date_ent(self, e=None):
        self.date_ent['state'] = 'disabled'

    def enable_date_ent(self, e=None):
        self.date_ent['state'] = 'normal'
        
    def time_caller(self):
        #updates every 15 min automatically
        msec = self.refresh_time * 6000

        self.update_time_now() #update time to current time
        self.set_workout_now()
        self.update_workouts() #update the workouts
        
        self.after(msec, self.time_caller) #call again

    def update_time_now(self):
        self.enable_date_ent()
        self.date.set(strftime("%m/%d/%Y"))

    def set_workout_now(self):
        #set workout field
        if len(self.workouts) == 0:
            self.disable_date_ent()
            return #no workouts
        index = 0
        now = datetime.today()
        for i, workout in enumerate(self.workouts):
            test = datetime.combine(date.today(),workout[0])
            if now < (test - timedelta(minutes=15)):
                index = i
                break
        self.workout_cb.current(index)
        self.disable_date_ent()
            
    def update_workouts(self, e=None):
        try:
            self.populate_workouts()
            self.workout_cb['values'] = self.workouts_form
        except ValueError:
            self.workout.set(' Enter Valid Date ')
        if len(self.workouts) > 0 and e:
            self.workout_cb.current(0)
            
    def populate_workouts(self):
        today = datetime.strptime(str(self.date.get()), "%m/%d/%Y") #get date
        dow = self.schedule.weekday_to_str(today.weekday()) #get dow string

        self.workouts = self.schedule.get_wkday(dow)
        self.workouts_form = []
        for w in self.workouts:
            self.workouts_form.append(w[0].strftime("%H:%M") + ' - ' + w[1])
        if len(self.workouts) == 0:
            self.workout.set(' No workouts today ')

    def update_names(self):
        self.populate_names()
        if len(self.names) == 0: self.names = ['']
        self.name_cb['values'] = self.names
        self.name_cb.set(' ')

    def add_name(self, name):
        self.names.append(name)
        split_names = [x.split(' ') for x in self.names]
        split_names.sort(key = lambda x: ' '.join([x[2],x[0],x[1]]))
        self.names = [' '.join(x) for x in split_names]
        self.name_cb['values'] = self.names
        self.name.set(name)
        
    def populate_names(self):
        try:
            clist = self.customers.get_list()
        except IOError:
            self.output_text("! - " + self.customers.filename + " open in another application.\n")
            return
        clist.sort(key = lambda x: ', '.join(x[0:3]).lower())
        self.names = []
        for line in clist:
            self.names.append(' '.join([line[1],line[2],line[0]]))

    def find_line(self, name):
        [fname, mname, lname] = name.split(' ')
        try:
            return self.customers.find(lname, fname, mname)
        except IOError:
            self.output_text("! - " + self.customers.filename + " open in another application.\n")
            return None
Beispiel #18
0
    class Monitor(Frame):
        def __init__(self, parent, port, baud_rate, ser, toolchain, bii):
            '''
            Params:
                parent: The parent Frame
                port: string
                baud_rate:
                ser: serial
            '''

            Frame.__init__(self, parent)
            self.parent = parent
            self.port = port
            self.baud_rate = baud_rate
            self.ser = ser
            self.toolchain = toolchain
            self.bii = bii
            self.initUI()

        def initUI(self):
            self.parent.title("Biicode serial monitor %s" % self.port)
            self.style = Style(
            )  # We need to define a style, otherwhise seems flat whit in macos
            self.style.theme_use(get_style())
            for x in range(1):
                Grid.columnconfigure(self, x, weight=1)
            for y in [1, 2]:
                Grid.rowconfigure(self, y, weight=1)

            self._make_top_bar()
            self._make_user_input()
            self._make_rcv_log()
            self._make_button_bar()

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

            self.serial_buffer = ""
            self.count = 0
            self.running = True
            self.after(50, self.read_serial)  # check serial again soon

        def _make_top_bar(self):
            menubar = Menu(self.parent)
            filemenu = Menu(menubar, tearoff=0)
            biimenu = Menu(menubar, tearoff=0)
            editmenu = Menu(menubar, tearoff=0)

            biimenu.add_command(label="Work (Save and process)",
                                command=self.bii.work)
            biimenu.add_command(label="Find", command=self.bii.find)
            menubar.add_cascade(label="bii", menu=biimenu)

            filemenu.add_command(label="Flash code", command=self.upload)
            filemenu.add_separator()
            filemenu.add_command(label="Exit", command=self.parent.quit)
            menubar.add_cascade(label="File", menu=filemenu)

            editmenu.add_command(label="Clear", command=self.clear)
            # editmenu.add_separator()
            menubar.add_cascade(label="Edit", menu=editmenu)
            self.parent.config(menu=menubar)

        def _make_button_bar(self):
            self.button_upload = Button(self,
                                        text="Flash code",
                                        command=self.upload)
            self.button_upload.style = self.style
            self.button_upload.grid(row=0, column=0, padx=2, pady=2)

            self.baud_rate = 9600
            self.button_combobox = Combobox(self)
            self.button_combobox.bind("<<ComboboxSelected>>",
                                      self._update_baud_rate)
            bauds = (300, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400,
                     57600, 115200)
            self.button_combobox['values'] = bauds
            self.button_combobox.current(4)
            self.button_combobox.grid(row=3, column=1, padx=2, pady=2)

        def _make_user_input(self):
            # make user input
            self.user_input = Text(self,
                                   width=52,
                                   height=3,
                                   takefocus=1,
                                   borderwidth=1,
                                   relief='ridge')
            self.user_input.grid(row=1,
                                 column=0,
                                 padx=2,
                                 pady=2,
                                 sticky=N + S + E + W)

            # make send button
            self.button_send = Button(self,
                                      text="Send",
                                      command=self.send_clicked)
            self.button_send.style = self.style
            self.button_send.grid(row=1,
                                  column=1,
                                  padx=2,
                                  pady=2,
                                  sticky=N + S + E + W)

        def _make_rcv_log(self):
            # make receive log
            recvLogFrame = Frame(self, width=400, height=200)
            recvLogFrame.style = self.style
            recvLogFrame.grid(row=2,
                              column=0,
                              padx=2,
                              pady=2,
                              sticky=N + S + E + W)
            self.start_stop_button = Button(self,
                                            text="Stop",
                                            command=self.start_stop_clicked)
            self.start_stop_button.style = self.style
            self.start_stop_button.grid(row=2,
                                        column=1,
                                        padx=2,
                                        pady=2,
                                        sticky=N + S + E + W)

            # make a scrollbar
            self.scrollbar = Scrollbar(recvLogFrame)
            self.scrollbar.pack(side=RIGHT, fill=Y)

            # make a text box to put the serial output
            self.log = Text(recvLogFrame,
                            width=50,
                            height=30,
                            takefocus=0,
                            borderwidth=1,
                            relief='ridge')
            self.log.pack(fill=BOTH, expand=True)

            # attach text box to scrollbar
            self.log.config(yscrollcommand=self.scrollbar.set)
            self.scrollbar.config(command=self.log.yview)

        def send_clicked(self):
            data = str(self.user_input.get(1.0, "end-1c") + '\0')
            self.ser.write(data)
            self._log(data)
            self.user_input.delete(1.0, END)

        def _log(self, msg):
            # if platform.system() == 'Darwin':
            #    print '>> %s' % msg
            # else:
            self.log.insert(END, '\n>> %s' % msg)
            self.log.yview(END)
            self.update_idletasks()

        def clear(self):
            self.log.delete(1.0, END)
            self.update_idletasks()

        def start_stop_clicked(self):
            if self.running:
                self.running = False
                self.start_stop_button['text'] = 'Start'
            else:
                self.running = True
                self.start_stop_button['text'] = 'Stop'
                self.read_serial()  # check serial again soon

        def upload(self):
            self.bii.work()
            try:
                if platform.system() == 'Darwin':
                    self.toolchain.upload()
                else:
                    self.ser.close()
                    self.toolchain.upload()
                    self.ser.open()
                self._log('** Code uploaded **')
            except BiiException:
                self._log('** Code upload failed **')

        def _update_baud_rate(self, event=None):
            new_rate = self.button_combobox.get()
            if new_rate != self.baud_rate:
                self.baud_rate = new_rate
                self.ser.setBaudrate(new_rate)
                logger.debug('Updated serial speed to %s' % new_rate)
                self.update_idletasks()

        def read_serial(self):
            self.log.update()  # display input text

            self._read_character()
            if self.running:
                self.after(100, self.read_serial)  # check serial again soon
            self.after(100, self.update_idletasks)

        def _read_character(self):
            try:
                c = self.ser.read()  # attempt to read a character from Serial
            except SerialException as e:
                logger.error("Couldn't read serial port: %s" % str(e))
                return

            # was anything read?
            while len(c) > 0 and c != '\r':
                # get the buffer from outside of this function
                # check if character is a delimeter
                if c == '\r':
                    c = ''  # don't want returns. chuck it
                if c == '\n':
                    # self.serial_buffer += "\n"  # add the newline to the buffer
                    self.log.insert(END, "\n")
                    self.log.insert(END, self.serial_buffer)
                    self.log.yview(END)
                    self.update_idletasks()
                    self.serial_buffer = ""  # empty the buffer
                else:
                    self.serial_buffer += c  # add to the buffer
                c = self.ser.read()
Beispiel #19
0
class PaymentFrame(Frame):
    """docstring for PaymentFrame"""
    def __init__(self, master, customers, payments, output_text, refresh):
        Frame.__init__(self, master)

        self.refresh = refresh
        self.master = master
        self.output_text = output_text
        self.customers = customers
        self.payments = payments

        self.pname = StringVar()
        self.pnames = []
        self.mname = StringVar()
        self.mnames = []
        self.date = StringVar()
        self.nmonths = StringVar()
        self.punches = StringVar()

        self.nmonths.set('1')
        self.punches.set(str(10))
        self.date.set(strftime("%m/%d/%Y"))

        self.columnconfigure(0,weight=1)

        # Monthly Customers
        monthly_lf = LabelFrame(self, text="Monthly Customers Payment")
        monthly_lf.grid(padx=5,pady=5,row=0,column=0,sticky='ew')
        
        Label(monthly_lf,text="Name:").grid(row=0,column=0,sticky='e',padx=(10,0),pady=(10,2))
        Label(monthly_lf,text="Date:").grid(row=0,column=3,sticky='e',padx=(10,0),pady=(10,2))
        Label(monthly_lf,text="# Months:").grid(row=1,column=0,columnspan=2,sticky='e',padx=(10,0),pady=(2,10))
        self.mname_cb = Combobox(monthly_lf,textvariable=self.mname,width=20,values=self.mnames,
            state='readonly')
        self.mname_cb.grid(row=0,column=1,columnspan=2,sticky='ew',pady=(10,2))
        Entry(monthly_lf,textvariable=self.date,width=15).grid(row=0,column=4,sticky='ew',padx=(0,10),pady=(10,2))
        Entry(monthly_lf,textvariable=self.nmonths).grid(row=1,column=2,sticky='ew',pady=(2,10))
        Button(monthly_lf,text='Submit',command=self.monthly_payment).grid(row=1,column=4,sticky='ew',padx=(0,10),pady=(2,10))

        for i in range(5):
            monthly_lf.columnconfigure(i,weight=1)

        # Punch Card Customers
        puch_lf = LabelFrame(self, text="Punch Card Customers (Purchace Card)")
        puch_lf.grid(padx=5,pady=5,row=1,column=0,sticky='ew')

        Label(puch_lf,text="Name:").grid(row=0,column=0,sticky='e',padx=(10,0),pady=(10,2))
        Label(puch_lf,text="Punches:").grid(row=0,column=2,sticky='e',pady=(10,2))
        self.pname_cb = Combobox(puch_lf,textvariable=self.pname,width=20,values=self.pnames,state='readonly')
        self.pname_cb.grid(row=0,column=1,sticky='ew',pady=(10,2))
        Entry(puch_lf,textvariable=self.punches,width=15).grid(row=0,column=3,sticky='ew',padx=(0,10),pady=(10,2))
        Button(puch_lf,text='Submit',command=self.new_punchcard).grid(row=3,column=3,sticky='ew',padx=(0,10),pady=(2,10))

        for i in range(4):
            puch_lf.columnconfigure(i,weight=1)

        self.update_names()

    def monthly_payment(self):
        nextpayment_date = datetime.strptime(self.date.get(), "%m/%d/%Y")
        try:
            nextpayment_date = self.payments.monthly_payment(self.mname.get(),datetime.strptime(self.date.get(), "%m/%d/%Y"), int(self.nmonths.get()))
        except IOError:
            showerror("Error writting to file", "Please close " + self.payments.filename + " and press OK.")
        except ValueError:
            self.output_text("! - Bad value for date (mm/dd/yyyy) or # Months \n")
        else:
            if int(self.nmonths.get()) > 1:
                self.output_text("$ - " + self.mname.get() + " Paid for " + self.nmonths.get() + " months\n")
            else:
                self.output_text("$ - " + self.mname.get() + " Paid for 1 month\n")

            self.output_text("$ - Next Payment Due: " + nextpayment_date.strftime("%B %d, %Y") + "\n")
            self.refresh()

    def new_punchcard(self):
        try:
            punches = int(self.punches.get())
            if punches < 1 or punches > 10:
                raise ValueError
            self.payments.new_punchcard(self.pname.get(), punches = punches)
            self.output_text("$ - New Puncard: " + self.pname.get() + "\n")
        except IOError:
            showerror("Error writting to file", "Please close " + self.payments.filename + " and press OK.")
        except ValueError:
            self.output_text("! - Bad value for number of punches: " + self.punches.get() + "\n")
        else:
            self.reset_punchcard()
            self.refresh()

    def reset_punchcard(self):
        self.punches.set(str(10))

    def reset_monthly(self):
        self.date.set(strftime("%m/%d/%Y"))
        self.nmonths.set('1')

    def update_names(self):
        '''
        run by refresh
        '''
        self.populate_names()
        if len(self.mnames) == 0: self.mnames = ['']
        self.mname_cb['values'] = self.mnames
        self.mname_cb.current(0)
        if len(self.pnames) == 0: self.pnames = ['']
        self.pname_cb['values'] = self.pnames
        self.pname_cb.current(0)
        self.reset_punchcard()
        self.reset_monthly()
        
    def populate_names(self):
        # try:
        clist = self.customers.get_list()
        # except IOError:
        #     self.output_text("! - " + self.customers.filename + " open in another application.\n")
        #     return
        clist.sort(key = lambda x: ', '.join(x[0:3]).lower())
        self.mnames = [' '.join([line[1],line[2],line[0]]) for line in clist if line[3]=='Monthly']
        self.pnames = [' '.join([line[1],line[2],line[0]]) for line in clist if line[3]=='Punch Card']
Beispiel #20
0
# txt = Entry(window,width=10, state='disabled') # does not allow user to enter the text
# use the new button to show the text
def show_text():
    ''' show this text when the button is clicked'''
    lbl3 = Label(window, text="input text", font=("Arial", 12))
    lbl3.grid(column=2, row=2)


btn2 = Button(window, text="show text", bg="blue", fg="red", command=show_text)
btn2.grid(column=1, row=2)
''' combox '''

combo = Combobox(window)
combo['values'] = (1, 2, 3, 4, 5, "Text")
combo.current(1)  #set the selected item
combo.grid(column=0, row=3)
val = combo.get()
# print(val)
chk_state = BooleanVar()
chk_state.set(False)  #set check state
chk = Checkbutton(window, text='Choose', var=chk_state)
chk.grid(column=1, row=3)
''' radiobutton ( [1] [2] [3] button )'''

selected = IntVar()
rad1 = Radiobutton(window, text='First', value=1, variable=selected)
rad2 = Radiobutton(window, text='Second', value=2, variable=selected)
rad3 = Radiobutton(window, text='Third', value=3, variable=selected)

Beispiel #21
0
class SolinetteGUI(Tk):
    def __init__(self):
        # basics settings
        Tk.__init__(self)               # constructor of parent graphic class
        self.title(u'Solinette: geolocalizar direcciones en Lima y Callo')
        self.iconbitmap('icone_Solinette.ico')
        self.resizable(width = False, height = False)
        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        # Frames
        self.FrPath = LabelFrame(self, name ='primero',
                            text = u'1: las direcciones para geolocalizar',
                            padx = 5, pady = 5)
        self.FrAttr = LabelFrame(self, name ='segundo',
                            text = u'2: columnas indispensables',
                            padx = 5, pady = 5)
        self.FrConn = LabelFrame(self, name ='tercero',
                            text = u'3: parámetros de conexión a la base de datos',
                            padx=5, pady=5)

        # Variables
        inutile = ['Esperando que se elige el archivo Excel']
        self.typcols = []
        self.host = StringVar()
        self.port = IntVar()
        self.dbnb = StringVar()
        self.usua = StringVar()
        self.mdpa = StringVar()
        self.ok = 0
        self.dico_cols = OD()
        self.dico_vals = OD()
        self.dico_param = {}

            ## Frame 1
        # target folder
        labtarg = Label(self.FrPath, text = u'Archivo Excel (.xls): ')
        self.target = Entry(self.FrPath, width = 35)
        self.browsetarg = Button(self.FrPath,
                                 text = 'Explorar',
                                 command = self.setpathtarg)

        # widgets placement
        labtarg.grid(row = 1, column = 1, columnspan = 1, sticky = N+S+W+E, padx = 2, pady = 2)
        self.target.grid(row = 1, column = 2, columnspan = 1, sticky = N+S+W+E, padx = 2, pady = 2)
        self.browsetarg.grid(row = 1, column = 3, columnspan = 1, sticky = N+S+W+E, padx = 2, pady = 2)

            ## Frame 2
        # Drop-down lists of columns
        labdir = Label(self.FrAttr, text = u'Columna dirección: ')
        self.ddl_dir = Combobox(self.FrAttr, values = inutile)
        labdis = Label(self.FrAttr, text = u'Columna distrito: ')
        self.ddl_dis = Combobox(self.FrAttr, values = inutile)

        # nombre de la tabla en PostgreSQL
        labtabl = Label(self.FrAttr, text = u'Nombre de la tabla: ')
        self.tabl = Entry(self.FrAttr, width = 35)

        # widgets placement
        labdir.grid(row = 1, column = 1, sticky = N+S+W, padx = 2, pady = 2)
        self.ddl_dir.grid(row = 1, column = 2, sticky = N+S+W+E, padx = 2, pady = 2)
        labdis.grid(row = 2, column = 1, sticky = N+S+W, padx = 2, pady = 2)
        self.ddl_dis.grid(row = 2, column = 2, sticky = N+S+W+E, padx = 2, pady = 2)
        labtabl.grid(row = 3, column = 1, sticky = N+S+W, padx = 2, pady = 2)
        self.tabl.grid(row = 3, column = 2, sticky = N+S+W+E, padx = 2, pady = 2)

            ## Frame 3

        # Etiquetas
        Label(self.FrConn, text = u'Host: ').grid(row = 1, column = 1,
                                                  padx = 2, pady = 2,
                                                  sticky = N+S+W)
        Label(self.FrConn, text = u'Puerto: ').grid(row = 2, column = 1,
                                             padx = 2, pady = 2,
                                             sticky = N+S+W)
        Label(self.FrConn, text = u'Base de datos: ').grid(row = 3,
                                                    column = 1,
                                                    padx = 2,
                                                    pady = 2,
                                                    sticky = N+S+W)
        Label(self.FrConn, text = u'Usuario: ').grid(row = 4,
                                              column = 1,
                                              padx = 2,
                                              pady = 2,
                                              sticky = N+S+W)
        Label(self.FrConn, text = u'Contraseña: ').grid(row = 5,
                                                 column = 1,
                                                 padx = 2,
                                                 pady = 2,
                                                 sticky = N+S+W)

        # Formulario
        self.H = Entry(self.FrConn, textvariable = self.host)
        self.P = Entry(self.FrConn, textvariable = self.port)
        self.D = Entry(self.FrConn, textvariable = self.dbnb)
        self.U = Entry(self.FrConn, textvariable = self.usua)
        self.M = Entry(self.FrConn, textvariable = self.mdpa, show='*')
        # pre relleno
        self.host.set('localhost')
        self.port.set('5432')
        self.usua.set('postgres')
        self.mdpa.set('')
        self.dbnb.set('solinette')

        # widgets placement
        self.H.grid(row = 1, column = 2, padx = 3, pady = 5, sticky = N+S+W+E)
        self.P.grid(row = 2, column = 2, padx = 3, pady = 5, sticky = N+S+W+E)
        self.D.grid(row = 3, column = 2, padx = 3, pady = 5, sticky = N+S+W+E)
        self.U.grid(row = 4, column = 2, padx = 3, pady = 5, sticky = N+S+W+E)
        self.M.grid(row = 5, column = 2, padx = 3, pady = 5, sticky = N+S+W+E)


            ## Global frame
        # Hola
        Label(self, text = '¡Hola! ' + env.get(u'USERNAME')).grid(row = 0, column = 0,
                                                 columnspan = 2, sticky = W+E,
                                                 padx = 2, pady = 5)
        # Imagen
        self.icone = PhotoImage(file = r'sources/logo_Solinette.GIF')
        Label(self, borderwidth = 2, relief = 'ridge',
                                     image = self.icone).grid(row = 1,
                                                              rowspan = 4,
                                                              column = 0,
                                                              padx = 1,
                                                              pady = 1,
                                                              sticky = W)

        # Basic buttons
        self.val = Button(self, text = u'Probar la conexión',
                                relief= 'raised',
                                command = self.process,
                                state = DISABLED)
        can = Button(self, text = 'Cancel (quit)',
                                relief= 'groove',
                                command = self.quit)

        # widgets placement
        self.FrPath.grid(row = 2, column = 1, sticky = N+S+W+E, padx = 2, pady = 2)
        self.val.grid(row = 5, column = 1, columnspan = 2,
                            sticky = N+S+W+E, padx = 2, pady = 5)
        can.grid(row = 5, column = 0, sticky = N+S+W+E, padx = 2, pady = 5)

    def setpathtarg(self):
        """ ...browse and insert the path of target folder """
        self.xls = askopenfilename(parent = self,
                                   title = u'Seleccionar el archivo Excel',
                                   filetypes = (("Archivos Excel (2003)", "*.xls"),
                                                ("All files", "*.*")),
                                   initialdir = '../sources')

        if path.splitext(self.xls)[1] == '.xls':
            hoy = '_' + strftime('%y%m%d', localtime())
            self.target.insert(0, self.xls)
            self.licolumns()
            self.browsetarg.config(state=DISABLED)
            self.target.config(state=DISABLED)
            self.FrAttr.grid(row = 3, column = 1, sticky = N+S+W+E, padx = 2, pady = 2)
            self.FrConn.grid(row = 4, column = 1, sticky = N+S+W+E, padx = 2, pady = 2)
            self.tabl.insert(0, path.basename(self.xls).split('.')[0] + hoy)
            self.val.config(state = ACTIVE)
        # end of function
        return self.xls

    def licolumns(self):
        u""" litsing columns names and types from Excel file """
        book = xlrd.open_workbook(self.target.get())   # lectura del archivo
        if book.nsheets > 1:
            print book.sheets()
        ish = 0
        sheet = book.sheet_by_index(ish)    # ouverture de la feuille 1
        # names of columns (first row/line)
        cols = sheet.row_values(0)
        self.ddl_dir['values'] = cols
        self.ddl_dis['values'] = cols
        self.ddl_dir.current(1)
        self.ddl_dis.current(2)
        # types of columns
        self.typcols = list(sheet.row_types(1))
        # add universal ID to list of columns
        self.dico_cols['SOL_IDU'] = 9
        # loop on names and types of columns
        for i in range(len(cols)):
            self.dico_cols[cols[i]] = self.typcols[i]
        # End of function
        return book, self.typcols, self.dico_cols, self.ddl_dir, self.ddl_dis

    def check_campos(self):
        u""" Verifica que los campos del formulario son bien rellenos """
        # conteo y mensaje de los errores
        err = 0
        msj = u'Rellenar todos los campos'
        # checkeo de los campos vacios
        if self.host.get() == u'':
            self.H.configure(background = 'red')
            err = err +1
        if self.port.get() == 0:
            self.P.configure(background = 'red')
            err = err +1
        if self.dbnb.get() == u'':
            self.D.configure(background = 'red')
            err = err +1
        if self.usua.get() == u'':
            self.U.configure(background = 'red')
            err = err +1
        if self.mdpa.get() == u'':
            self.M.configure(background = 'red')
            err = err +1
        if self.tabl.get() == u'':
            self.tabl.configure(background = 'red')
            err = err +1
        if self.ddl_dir.get() == u'':
            self.ddl_dir.configure(background = 'red')
            err = err +1
        if self.ddl_dis.get() == u'':
            self.ddl_dis.configure(background = 'red')
            err = err +1
        # se colunas direcciones y distrito son diferentes
        if self.ddl_dir.get() == self.ddl_dis.get():
            msj = msj + u'\nLas dos columnas no deben ser iguales'
            err = err +1

        # Acción según si hay error(es) o no
        if err != 0:
            showerror(title = u'Error: campo(s) vacío(s)',
                      message = msj)
        # End of function
        return err

    def testconnexion(self):
        u""" testing connection settings """
        try:
            conn = pg.connect(host = self.host.get(), dbname = self.dbnb.get(),
                              port = self.port.get(), user = self.usua.get(),
                              password = self.mdpa.get())
            curs = conn.cursor()
            # check PostgreSQL and PostGIS versions
            try:
                curs.execute('SELECT version()')
                ver = curs.fetchone()
                print ver
            except DatabaseError, e:
                showerror(title = u'Prueba de conexión ',
                message = 'Prueba de conexión fracasó. Mensaje de error:\n' + str(e))
                return
            # check if destination table already exists
            query = "select table_name from information_schema.tables where 'sql_identifier' LIKE 'public'" #% (self.tabl.get())
            curs.execute(query)
            li_tablas = curs.fetchall()
            print 'elle existe déjà connard : ', li_tablas
            # información al usuario
            self.val.config(text='¡D A L E!')
            showinfo(title = u'Prueba de conexión ',
                     message = u'Prueba de conexión terminó con éxito')
            self.ok = 1
            # clausura de la conexión
            conn.close()

        except pg.OperationalError, e:
            showerror(title = u'Prueba de conexión ',
                      message = 'Prueba de conexión fracasó. Mensaje de error:\n' + str(e))
            return
class wine_DB_manager:  #Class for wrapping TKinter widgets
    def __init__(self, master):  #Initilize the attributes of the class

        master.minsize(width=600, height=700)  #Set window size and title
        master.title("Member and Store Manager")

        master.grid_columnconfigure(
            0, weight=1
        )  #Configure first and last columns for centering columns 1-5
        master.grid_columnconfigure(6, weight=1)
        master.grid_rowconfigure(
            12, weight=1
        )  #Configure last row for filling left over space at the bottom

        self.imp_store_label = Label(
            master, text="Import Store Information (.CSV)"
        )  #Initilize lable, entry, and buttons for importing stores
        self.imp_store_entry = Entry(master, width=70)
        self.imp_store_browse_button = Button(
            master,
            text="Browse",
            command=lambda: self.browse_for_CSV("store"))
        self.imp_store_import_button = Button(
            master,
            text="Import",
            command=lambda: self.import_to_DB(self.imp_store_entry.get(),
                                              "store"))

        self.imp_member_label = Label(
            master, text="Import Member Information (.CSV)"
        )  #Initilize lable, entry, and buttons for importing members
        self.imp_member_entry = Entry(master, width=70)
        self.imp_member_browse_button = Button(
            master,
            text="Browse",
            command=lambda: self.browse_for_CSV("member"))
        self.imp_member_import_button = Button(
            master,
            text="Import",
            command=lambda: self.import_to_DB(self.imp_member_entry.get(),
                                              "member"))

        self.horz_divider = Frame(
            master, height=1, width=500, bg="black"
        )  #Initilize a frame shaped as a horizonal line as a divider

        self.view_all_members_button = Button(
            master,
            text="View All Members",
            width=17,
            command=lambda: self.select_all_members()
        )  #Initilize button for selecting all members and displaying them in tree

        self.zip_label = Label(
            master, text="Zip Code"
        )  #Initilize lable, entry, combobox, and buttons for
        self.zip_entry = Entry(
            master,
            width=10)  #finding who paid dues by zip code and month paid
        self.month_label = Label(master, text="Month")
        self.month_combobox = Combobox(master, width=10)
        self.month_combobox['values'] = ('January', 'February', 'March',
                                         'April', 'May', 'June', 'July',
                                         'August', 'September', 'October',
                                         'November', 'December')
        self.find_users_that_paid = Button(
            master,
            text="Current Paid Users",
            width=20,
            command=lambda: self.select_paid_dues_month(
                self.zip_entry.get(), self.month_combobox.current()))

        self.state_label = Label(
            master,
            text="State")  #Initilize lable, entry, combobox, and buttons for
        self.state_combobox = Combobox(
            master,
            width=3)  #finding users who have joined the club since a date
        self.state_combobox['values'] = ('MD', 'NC', 'PA', 'VA', 'WV'
                                         )  #and belong to a specific state
        self.date_label = Label(master, text="Date (YYYY-MM-DD)")
        self.date_entry = Entry(master, width=10)
        self.find_users_that_joined = Button(
            master,
            text="Users Joined Since",
            width=20,
            command=lambda: self.select_users_joined_since(
                self.state_combobox.get(), self.date_entry.get()))

        self.users_that_love_total_wine = Button(
            master,
            text="Users that Love Total Wine",
            width=20,
            command=lambda: self.select_users_love_Tot_Wine(
            ))  #Initilize button for finding users that love Total Wines

        self.users_favorite_stores = Button(
            master,
            text="User's Favorite Stores",
            width=20,
            command=lambda: self.select_users_fav_stores()
        )  #Initilize button for finding users, their favorite stores, and store locations

        self.table_tree = Treeview(
            master, selectmode="extended")  #Initilize tree for data viewing
        self.table_tree["columns"] = (
            "one", "two", "three", "four", "five", "six", "seven", "eight",
            "nine", "ten", "eleven")  #Provide max column count and identifiers
        for columns in self.table_tree[
                "columns"]:  #For loop to add all columns
            self.table_tree.column(columns, width=70, anchor=W)
        self.table_tree['show'] = 'headings'  #Remove empty identity column

        self.vert_scroll_bar = Scrollbar(
            orient="vertical",
            command=self.table_tree.yview)  #Initilize scroll bar
        self.table_tree.configure(yscrollcommand=self.vert_scroll_bar.set
                                  )  #Add scroll bar to table_tree

        self.imp_store_label.grid(
            sticky="W", row=1, column=1, padx=10,
            pady=(20, 0))  #Grid positioning for all initialized attributes
        self.imp_store_entry.grid(sticky="W",
                                  row=2,
                                  column=1,
                                  columnspan=3,
                                  padx=10)
        self.imp_store_browse_button.grid(row=2, column=4, padx=10)
        self.imp_store_import_button.grid(row=2, column=5)

        self.imp_member_label.grid(sticky="W", row=3, column=1, padx=10)
        self.imp_member_entry.grid(sticky="W",
                                   row=4,
                                   column=1,
                                   columnspan=3,
                                   padx=10)
        self.imp_member_browse_button.grid(row=4, column=4, padx=10)
        self.imp_member_import_button.grid(row=4, column=5)

        self.horz_divider.grid(row=5, column=0, columnspan=7, pady=20)

        self.view_all_members_button.grid(row=6, column=1, columnspan=5)

        self.zip_label.grid(sticky="W", row=7, column=1, pady=(15, 0))
        self.zip_entry.grid(sticky="W", row=8, column=1, pady=5)
        self.month_label.grid(sticky="W",
                              row=7,
                              column=1,
                              padx=(100, 0),
                              pady=(15, 0))
        self.month_combobox.grid(sticky="W",
                                 row=8,
                                 column=1,
                                 padx=(100, 0),
                                 pady=5)
        self.find_users_that_paid.grid(sticky="W",
                                       row=9,
                                       column=1,
                                       columnspan=3,
                                       pady=5)

        self.state_label.grid(sticky="W", row=7, column=4, pady=(15, 0))
        self.state_combobox.grid(sticky="W", row=8, column=4, pady=5)
        self.date_label.grid(sticky="W",
                             row=7,
                             column=4,
                             columnspan=3,
                             padx=(85, 0),
                             pady=(15, 0))
        self.date_entry.grid(sticky="W",
                             row=8,
                             column=4,
                             columnspan=2,
                             padx=(85, 0),
                             pady=5)
        self.find_users_that_joined.grid(sticky="W",
                                         row=9,
                                         column=4,
                                         columnspan=2,
                                         pady=5)

        self.users_that_love_total_wine.grid(sticky="W",
                                             row=10,
                                             column=1,
                                             columnspan=3,
                                             pady=(15, 0))

        self.users_favorite_stores.grid(sticky="W",
                                        row=10,
                                        column=4,
                                        columnspan=2,
                                        pady=(15, 0))

        self.table_tree.grid(sticky="NWES",
                             row=11,
                             column=0,
                             columnspan=7,
                             rowspan=2,
                             pady=10,
                             padx=(10, 0))
        self.vert_scroll_bar.grid(sticky="NWES",
                                  row=11,
                                  column=7,
                                  rowspan=2,
                                  pady=10,
                                  padx=(0, 10))

    def browse_for_CSV(
        self, CSV_type
    ):  #Class method for browse buttons. Used for passing file path to TKinter entries

        file = tkFileDialog.askopenfile(
            parent=root, mode='rb',
            title='Choose a file')  #Opens browse for file window

        if (file != None):  #If file exists read into data and close file

            data = file.read()
            file.close()

            if (
                    CSV_type == "store"
            ):  #In order to resuse code, this method works for both buttons
                self.imp_store_entry.delete(
                    0, END)  #through using a passed button identity variable
                self.imp_store_entry.insert(0, os.path.abspath(file.name))

            else:
                self.imp_member_entry.delete(0, END)  #Empties entry widget
                self.imp_member_entry.insert(
                    0, os.path.abspath(file.name)
                )  #Inserts file path into entry widget using os.path import
        else:  #Catches no file selected possibility
            tkMessageBox.showinfo("Error", "No File Selected")

        return None

    def create_DB_connection(
        self
    ):  #Class method for opening a database connection to the pythonsqlite.db file

        try:
            DB_file = "SQLite_db\pythonsqlite.db"
            conn = sqlite3.connect(DB_file)
            return conn

        except Error as e:  #Catches non-connectivity errors
            print(e)

        return None

    def import_to_DB(
        self, file_path, CSV_type
    ):  #Class method for import buttons. Used to open csv files from path string
        #in entry widgets. Then opens db connection to import data to db
        try:
            self.CSV_file = open(file_path, "r")  #Opens CSV file in read mode
        except IOError as e:  #Catches file not found error
            tkMessageBox.showinfo("Error", "File Not Found")
            return

        CSV_reader = csv.reader(
            self.CSV_file
        )  #Reads CSV file into CSV_reader using csv.reader import
        conn = self.create_DB_connection()  #Calls for DB connection to open

        cur = conn.cursor()

        if (
                CSV_type == "store"
        ):  #In order to resuse code, this method works for both buttons by passed type.
            if (next(CSV_reader)[0][0:8] !=
                    "Store id"):  #Checks CSV for proper store headings
                tkMessageBox.showinfo(
                    "CSV Type Error",
                    "Please Import a CSV file formated for store data.")
                self.CSV_file.close(
                )  #If not proper headings close file and display message
                return
            else:  #Create table Stores
                cur.execute(
                    '''CREATE TABLE IF NOT EXISTS Stores (                                                                                 
                                store_id INTEGER PRIMARY KEY, 
                                store_name VARCHAR, 
                                location VARCHAR)''')

                for row in CSV_reader:  #Insert new values for each row in CSV
                    cur.execute(
                        '''INSERT OR IGNORE INTO Stores (                                                                                  
                                    store_id, 
                                    store_name, 
                                    location) 
                                    VALUES (?, ?, ?)''', row)
                tkMessageBox.showinfo(
                    "Success!",
                    "Successfully Updated the Database")  #Display confirmation
                self.imp_store_entry.delete(0, END)  #Clear import entry

        else:
            if (next(CSV_reader)[0][0:6] !=
                    "Member"):  #Checks CSV for proper member headings
                tkMessageBox.showinfo(
                    "CSV Type Error",
                    "Please Import a CSV file formated for member data.")
                self.CSV_file.close(
                )  #If not proper headings close file and display message
                return
            else:  #Create table Members
                cur.execute('''CREATE TABLE IF NOT EXISTS Members (     
                                member_id INTEGER PRIMARY KEY, 
                                last_name VARCHAR, 
                                first_name VARCHAR, 
                                street VARCHAR, 
                                city VARCHAR, 
                                state VARCHAR, 
                                zip VARCHAR, 
                                phone VARCHAR, 
                                favorite_store INTEGER, 
                                date_joined DATE, 
                                dues_paid DATE, 
                                FOREIGN KEY(favorite_store) 
                                REFERENCES Stores(store_id))''')

                for row in CSV_reader:  #Insert new values for each row in CSV
                    cur.execute(
                        '''INSERT OR IGNORE INTO Members (
                                        member_id, 
                                        last_name, 
                                        first_name, 
                                        street, 
                                        city , 
                                        state, 
                                        zip, 
                                        phone, 
                                        favorite_store, 
                                        date_joined, 
                                        dues_paid) 
                                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''',
                        row)
                tkMessageBox.showinfo("Success!",
                                      "Successfully Updated the Database")
                self.imp_member_entry.delete(0, END)

        self.CSV_file.close()  #Close CSV file
        conn.commit()  #Commit DB changes
        conn.close()  #Close DB Connection

        return None

    def generate_member_column_names(
            self
    ):  #Class utility method for adding member column headers to tree

        all_member_column_names = ("Member ID", "Last Name", "First Name",
                                   "Street", "City", "State", "Zip Code",
                                   "Phone", "Favorite Store", "Date Joined",
                                   "Dues Paid")

        for index, columns in enumerate(self.table_tree["columns"]
                                        ):  #For loop to add all column headers
            self.table_tree.heading(columns,
                                    text=all_member_column_names[index])

        return None

    def select_all_members(
        self
    ):  #Class method for View All Members Buttons and outputs new data to tree

        cur = self.create_DB_connection().cursor(
        )  #Calls for DB connection to open
        cur.execute("SELECT * FROM Members ORDER BY last_name ASC"
                    )  #SQL Statement to SELECT all members and their data.

        rows = cur.fetchall()  #Fetches data into rows

        self.table_tree.delete(*self.table_tree.get_children()
                               )  #Deletes old data in tree if present

        self.generate_member_column_names(
        )  #Call utility to generate column member headers

        for index, row in enumerate(
                rows):  #Inserts sql data into tree rows for viewing
            self.table_tree.insert('', index, values=(row))

        self.create_DB_connection().close()  #Close DB Connection
        return None

    def select_paid_dues_month(
        self, zip, month
    ):  #Class method for Current Paid User Button and outputs new data to tree

        month = month + 1  #Add 1 to month index count since it range is 0-11 and months are 1-12
        if (month < 10):
            self.month_string = "0" + str(month)

        cur = self.create_DB_connection().cursor(
        )  #Calls for DB connection to open

        if (month not in range(1, 12)):  #If no month selected display message
            tkMessageBox.showinfo("Error", "No Month Selected")
            return

        if (len(zip) != 5):  #If zip not 5 digits display message
            tkMessageBox.showinfo("Error", "Enter a Zip Code")
            return

        try:
            cur.execute("SELECT * FROM Members WHERE zip = " + zip +
                        " AND strftime('%m',dues_paid) = '" +
                        self.month_string +
                        "'")  #If zip is numeric execute Select Statement
        except Error as e:  #Catches error if zip not numeric
            tkMessageBox.showinfo("Error", "Enter a Zip Code")
            return

        rows = cur.fetchall()

        self.table_tree.delete(*self.table_tree.get_children()
                               )  #Deletes old data in tree if present

        self.generate_member_column_names(
        )  #Call utility to generate column member headers

        for index, row in enumerate(
                rows):  #Inserts sql data into tree rows for viewing
            self.table_tree.insert('', index, values=(row))

        self.create_DB_connection().close()  #Close DB Connection
        return None

    def select_users_joined_since(
        self, state, the_date
    ):  #Class method for Current Paid User Button and outputs new data to tree

        cur = self.create_DB_connection().cursor(
        )  #Calls for DB connection to open

        if state == "":  #if no state selected display message
            tkMessageBox.showinfo("Error", "No State Selected")
            return

        try:  #Checks date format YYYY-MM-DD
            datetime.datetime.strptime(the_date, '%Y-%m-%d')
        except ValueError:  #Catches invalid date format
            tkMessageBox.showinfo(
                "Error", "Incorrect data format, should be YYYY-MM-DD")
            return

        cur.execute(
            "SELECT * FROM Members WHERE state = '" + state +
            "' AND date_joined > '" + the_date + "'"
        )  #Execute Select members Where state and date are what user selected.

        rows = cur.fetchall()

        self.table_tree.delete(*self.table_tree.get_children()
                               )  #Deletes old data in tree if present

        self.generate_member_column_names(
        )  #Call utility to generate column member headers

        for index, row in enumerate(
                rows):  #Inserts sql data into tree rows for viewing
            self.table_tree.insert('', index, values=(row))

        self.create_DB_connection().close()  #Close DB Connection
        return None

    def select_users_love_Tot_Wine(
        self
    ):  #Class method for Users That Love Tot Wine and outputs new data to tree

        cur = self.create_DB_connection().cursor(
        )  #Calls for DB connection to open
        #Execute Select Where, and Join on foreign key values.
        cur.execute('''SELECT Members.last_name,
                            Members.first_name, 
                            Stores.store_name 
                            FROM Members 
                            JOIN Stores 
                            ON Members.favorite_store = Stores.store_id 
                            WHERE favorite_store = '3' ''')

        rows = cur.fetchall()

        self.table_tree.delete(*self.table_tree.get_children()
                               )  #Deletes old data in tree if present

        all_member_column_names = ("Last Name", "First Name", "Favorite Store",
                                   "", "", "", "", "", "", "", "")

        for index, columns in enumerate(
                self.table_tree["columns"]
        ):  #Generate *custom* column member headers
            self.table_tree.heading(columns,
                                    text=all_member_column_names[index])

        for index, row in enumerate(
                rows):  #Inserts sql data into tree rows for viewing
            self.table_tree.insert('', index, values=(row))

        self.create_DB_connection().close()  #Close DB Connection
        return None

    def select_users_fav_stores(
        self
    ):  #Class method for Users Favorite Stores and outputs new data to tree

        cur = self.create_DB_connection().cursor(
        )  #Calls for DB connection to open
        #Execute Select Where, and Join on foreign key values.
        cur.execute('''SELECT Members.last_name,
                    Members.first_name, 
                    Stores.store_name, 
                    Stores.location
                    FROM Members 
                    JOIN Stores 
                    ON Members.favorite_store = Stores.store_id ''')

        rows = cur.fetchall()

        self.table_tree.delete(*self.table_tree.get_children()
                               )  #Deletes old data in tree if present

        all_member_column_names = ("Last Name", "First Name", "Favorite Store",
                                   "Location", "", "", "", "", "", "", "")

        for index, columns in enumerate(
                self.table_tree["columns"]
        ):  #Generate *custom* column member headers
            self.table_tree.heading(columns,
                                    text=all_member_column_names[index])

        for index, row in enumerate(
                rows):  #Inserts sql data into tree rows for viewing
            self.table_tree.insert('', index, values=(row))

        self.create_DB_connection().close()  #Close DB Connection
        return None
class IniGenGui(Frame):

  def __init__(self, parent):
    Frame.__init__(self, parent)
    self.parent = parent
    self.inigen = IniGen()
    self.initUIGlobals()


  def initUIGlobals(self):
    """
      This is the first part of the window to be rendered. After these have been
       set by the user and 'Emit Globals' has been clicked, the given algorithm
       can then specify how to generate the second part of the window. All fields
       are disabled for user input after globals have been emitted.

      Information in Global Parameters:
        Algorithm
          - name of the algorithm to use
        File Name
          - name of the output file to be generated
        Min Time
          - Minimum Time for distillers to run
        Max Time
          - Maximum Time for distillers to run
        Set Enabled:
          - checkbox to specify if the distiller should be enabled True or False
    """
    self.parent.title("Ini Generator")

    Style().configure("TButton", padding=(0, 5, 0, 5), font='serif 10')

    # initialize row counter. This is incremented after each element added to grid
    row = 0
    # initialize column counter. This is incremented after a column has been filled
    self.column = 0

    # Globals: entries for info common to all runs
    label_globals = Label(self, text="Globals")
    label_globals.grid(row=row, column=self.column)
    row += 1

    label_alg = Label(self, text="Algorithm")
    label_alg.grid(row=row, column=self.column, sticky=E+W)
    row += 1
    self.cbox_alg = Combobox(self, values=algorithms.keys(), state='readonly')
    self.cbox_alg.current(0)
    self.cbox_alg.grid(row=row, column=self.column, sticky=E+W+S+N)
    row += 1

    label_filename = Label(self, text="Output File Name")
    label_filename.grid(row=row, column=self.column, sticky=E+W)
    row += 1
    self.entry_filename = Entry(self)
    self.entry_filename.grid(row=row, column=self.column, sticky=W+E)
    row += 1

    label_mintime = Label(self, text="Min Time")
    label_mintime.grid(row=row, column=self.column, sticky=E+W)
    row += 1
    self.entry_mintime = Entry(self)
    self.entry_mintime.grid(row=row, column=self.column, sticky=W+E)
    row += 1

    label_maxtime = Label(self, text="Max Time")
    label_maxtime.grid(row=row, column=self.column, sticky=W+E)
    row += 1
    self.entry_maxtime = Entry(self)
    self.entry_maxtime.grid(row=row, column=self.column, sticky=W+E)
    row += 1

    self.enabled = IntVar()
    self.check_enabled = Checkbutton(self, text="set enabled", variable=self.enabled)
    self.check_enabled.grid(row=row, column=self.column, sticky=W+E)
    row += 1

    # Control: buttons used to emmiting text and generating file
    self.button_emit_globals = Button(self, text="Emit Globals", command=self.emit_globals)
    self.button_emit_globals.grid(row=row, column=self.column, sticky=W+E)
    row += 1

    button_addrun = Button(self, text="Add Run", command=self.emit_run)
    button_addrun.grid(row=row, column=self.column, sticky=W+E)
    row += 1

    button_generate = Button(self, text="Generate File", command=self.generate_file)
    button_generate.grid(row=row, column=self.column, sticky=W+E)
    row += 1

    self.column += 1

    self.pack()

  def initUIRuns(self):
    """
      Second part of gui to be rendered. This contains all the fields needed to emit
       a single run within a distiller file. Multiple runs can be added by clicking
       'Add Run' multiple times.

      Information in Run Parameters:
        Run Name
          - header name for run
        Dependencies
          - description and uuid fields for each dependency in the algorithm
        Params
          - parameter fields for each parameter in the algorithm
    """

    self.entry_run_name = None
    self.entries_dep_description = []
    self.entries_dep_uuid = []
    self.entries_param = []

    row = 0

    label_runs = Label(self, text="Runs")
    label_runs.grid(row=row, column=self.column)
    row += 1

    label_run_name = Label(self, text="Run Name")
    label_run_name.grid(row=row, column=self.column, sticky=W+E)
    row += 1

    self.entry_run_name = Entry(self)
    self.entry_run_name.grid(row=row, column=self.column, sticky=W+E)
    row += 1

    algorithm = self.cbox_alg.get()
    settings = algorithms[algorithm]

    for dep in settings['deps']:

      if row >= 21:
        self.column += 1
        row = 1

      label_dep_description = Label(self, text="{0} (description)".format(dep))
      label_dep_description.grid(row=row, column=self.column, sticky=W+E)
      row += 1

      entry_dep_description = Entry(self)
      entry_dep_description.grid(row=row, column=self.column, sticky=W+E)
      row += 1

      label_dep_uuid = Label(self, text="{0} (uuid)".format(dep))
      label_dep_uuid.grid(row=row, column=self.column, sticky=W+E)
      row += 1

      entry_dep_uuid = Entry(self)
      entry_dep_uuid.grid(row=row, column=self.column, sticky=W+E)
      row += 1

      self.entries_dep_description.append(entry_dep_description)
      self.entries_dep_uuid.append(entry_dep_uuid)

    for param in settings['params']:

      if row >= 21:
        self.column += 1
        row = 1

      label_param = Label(self, text=param)
      label_param.grid(row=row, column=self.column, sticky=W+E)
      row += 1

      entry_param = Entry(self)
      entry_param.grid(row=row, column=self.column, sticky=W+E)
      row += 1

      self.entries_param.append(entry_param)

    row = 0
    self.column += 1

    self.text_file = Text(self)
    self.text_file.grid(row=row, column=self.column, rowspan=31, sticky=W+E+N+S, padx=5, pady=5)
    self.column += 1
    scrollbar = Scrollbar(self, command=self.text_file.yview)
    self.text_file.config(yscrollcommand=scrollbar.set)
    scrollbar.grid(row=row, column=self.column, rowspan=31, sticky=N+S)

    self.pack()

  def emit_globals(self):
    self.algorithm = algorithms[self.cbox_alg.get()]
    path = self.algorithm['path']
    if self.enabled.get():
      enabled = 'True'
    else:
      enabled = 'False'

    lines = self.inigen.emit_global(path, enabled)

    self.mintime = self.entry_mintime.get()
    self.maxtime = self.entry_maxtime.get()

    self.cbox_alg.configure(state='disabled')
    self.entry_filename.configure(state='disabled')
    self.entry_mintime.configure(state='disabled')
    self.entry_maxtime.configure(state='disabled')
    self.check_enabled.configure(state='disabled')
    self.button_emit_globals.configure(state='disabled')

    self.initUIRuns()
    self.update_text(lines)

  def emit_run(self):
    label = self.entry_run_name.get()
    chunking = 'parallel' #hardcoded for now
    mintime = self.mintime
    maxtime = self.maxtime
    lines = self.inigen.emit_run_header(label, chunking, mintime, maxtime)
    self.update_text(lines)

    deps = []
    for i in range(len(self.entries_dep_description)):
      deps.append([self.entries_dep_description[i].get(),
                   self.algorithm['deps'][i],
                   self.entries_dep_uuid[i].get()])
    params = []
    for i in range(len(self.entries_param)):
      params.append([self.algorithm['params'][i],
                     self.entries_param[i].get()])
    outputs = self.algorithm['outputs']
    lines = self.inigen.emit_run_body(deps, params, outputs)
    self.update_text(lines)

  def generate_file(self):
    self.inigen.generate_file(self.entry_filename.get())
    self.quit()

  def update_text(self, lines):
    self.text_file.configure(state='normal')
    string = "\n".join(lines)
    self.text_file.insert(END, string)
    self.text_file.configure(state='disabled')
Beispiel #24
0
class Ui(Frame):  # Implementation of Ui class which represents the main frame.
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.DATABASE = 'pokemon.db'
        self.engine = search_engine.PokemonSearchEngine()
        self.search_key = StringVar()
        self.pokemons = dict()
        self.pokemon_types = ['All Types']
        self.COLOR_CHART = {
            'Bug': 'olive drab',
            'Dragon': 'tomato',
            'Electric': 'gold',
            'Fairy': 'HotPink1',
            'Fighting': 'orange red',
            'Fire': 'dark orange',
            'Flying': 'deep sky blue',
            'Ghost': 'dark violet',
            'Grass': 'yellow green',
            'Ground': 'goldenrod',
            'Ice': 'cyan',
            'Normal': 'gray',
            'Poison': 'medium orchid',
            'Psychic': 'hot pink',
            'Rock': 'saddle brown',
            'Steel': 'lightgrey',
            'Water': 'steel blue'
        }

        self.init_ui()

    # UI Generator Functions
    def init_ui(self):
        frm_options = Frame(self)
        frm_title = Frame(frm_options,
                          bg='red',
                          highlightbackground="black",
                          highlightthickness=2)
        frm_fetch = Frame(frm_options,
                          bg='red',
                          highlightbackground="black",
                          highlightthickness=2)
        frm_search = Frame(frm_options,
                           bg='red',
                           highlightbackground="black",
                           highlightthickness=2)
        frm_filter = Frame(frm_search, bg='red')
        frm_filter_label = Frame(frm_filter, bg='red')
        frm_results = Frame(frm_options,
                            bg='red',
                            highlightbackground="black",
                            highlightthickness=2)
        frm_pokemon = Frame(frm_results, bg='red')
        Label(frm_title, text='POKEDEX', bg='red', fg='white', font='Calibri 20 bold')\
            .pack(fill=X)

        Button(frm_fetch,
               text='Fetch Pokemon\nData',
               bg='yellow',
               command=self.btn_fetchdata_onclick).pack(side=LEFT,
                                                        padx=5,
                                                        pady=20)
        self.progress = Progressbar(frm_fetch,
                                    orient="horizontal",
                                    length=200,
                                    mode="determinate")
        self.progress.pack(fill=X, padx=15, pady=30, expand=True)
        self.lbl_progress = Label(self.progress, text='')
        self.lbl_progress.pack(pady=5)
        Label(frm_search, text='Search&Filtering', bg='red', font='Calibri 15 bold')\
            .pack()
        Entry(frm_search, textvariable=self.search_key, width=40)\
            .pack(fill=X, padx=15, pady=15)
        Label(frm_filter_label, text='Filter By Type', bg='red', font='Calibri 12')\
            .pack(side=LEFT, padx=5)
        frm_filter_label.pack(side=TOP, fill=X)
        self.cb_filter_type = Combobox(frm_filter)
        self.cb_filter_type.pack(side=LEFT,
                                 fill=X,
                                 padx=5,
                                 pady=5,
                                 expand=True)
        Button(frm_filter,
               text='SEARCH',
               bg='yellow',
               command=self.btn_search_onclick).pack(side=RIGHT,
                                                     fill=X,
                                                     padx=10)

        self.lbl_result = Label(frm_results,
                                text='Total Number Of Results',
                                bg='red',
                                font='Calibri 13 bold')
        self.lbl_result.pack()
        self.lb_pokemons = Listbox(frm_pokemon)
        self.lb_pokemons.pack(side=LEFT, padx=20, pady=10)
        Button(frm_pokemon,
               text='Get Pokemon\nData',
               bg='yellow',
               command=self.btn_getpokemon_onclick).pack(side=RIGHT, padx=10)

        frm_options.pack(side=LEFT, fill=BOTH, expand=True)
        frm_title.pack(fill=X)
        frm_fetch.pack(fill=X)
        frm_search.pack(fill=X)
        frm_filter.pack(fill=X)
        frm_results.pack(fill=X)
        frm_pokemon.pack(fill=X)
        self.pack(fill=BOTH, expand=True)

    def pack_pokemon_detail(self, pokemon):
        self.frm_detail = Frame(self,
                                bg='red',
                                highlightbackground="black",
                                highlightthickness=2)

        Label(self.frm_detail,
              text=pokemon.name,
              bg='red',
              font='Calibri 18 bold').pack()
        Label(self.frm_detail,
              text=pokemon.id,
              bg='red',
              font='Calibri 13 bold').pack()
        cnvs_img = Canvas(self.frm_detail, bg='red')
        urllib.urlretrieve(pokemon.img, '1.png')
        cnvs_img.pack(fill=Y)
        Img = Image.open('1.png')
        Img = Img.resize((400, 250))
        self.c = ImageTk.PhotoImage(Img)
        cnvs_img.create_image(0, 0, anchor=NW, image=self.c)
        for type in pokemon.type:
            Label(self.frm_detail,
                  text=type,
                  bg=self.COLOR_CHART[type],
                  width=20,
                  font='Calibri 10 bold').pack()
        Label(self.frm_detail,
              text='Height: ' + pokemon.height,
              bg='red',
              font='Calibri 10 bold').pack()
        Label(self.frm_detail,
              text='Weight: ' + pokemon.weight,
              bg='red',
              font='Calibri 10 bold').pack()
        Label(self.frm_detail,
              text='Category: ' + pokemon.category,
              bg='red',
              font='Calibri 10 bold').pack()
        Label(self.frm_detail,
              text='Ability: ' + pokemon.ability,
              bg='red',
              font='Calibri 10 bold').pack()
        Label(self.frm_detail,
              text='Weakness: ' + ', '.join(pokemon.weakness),
              bg='red',
              font='Calibri 10 bold').pack()
        self.frm_detail.pack(side=RIGHT, fill=BOTH)

    # GUI Element's Events
    def btn_fetchdata_onclick(self):
        try:
            self.read_from_db(self.DATABASE, self.pokemons)
        except anydbm.error:
            for pokemon in self.load_data('all_pokemon.txt'):
                self.pokemons[pokemon] = self.engine.search(pokemon)
                self.progress['value'] += 0.70
                self.progress.update()
            self.create_database(self.DATABASE, self.pokemons)
        finally:
            self.lbl_progress['text'] = 'FINISHED'
            self.get_pokemon_types()

    def btn_search_onclick(self):
        if self.cb_filter_type.get() == 'All Types':
            source = self.filter_pokemon(self.search_key.get())
        else:
            source = self.filter_pokemon_by_type(self.search_key.get().lower(),
                                                 self.cb_filter_type.get())

        self.lbl_result['text'] = 'Total: ' + str(len(source)) + ' Result'
        self.clear_and_insert_to_listbox(self.lb_pokemons, source)

    def btn_getpokemon_onclick(self):
        try:
            self.frm_detail.pack_forget()
        except:
            print 'All Calculated, No Problem'
        finally:
            self.pack_pokemon_detail(
                self.pokemons[self.lb_pokemons.get(ACTIVE)])

    # Utilities
    def filter_pokemon_by_type(self, query_string, type):
        results = []
        for pokemon_name, pokemon_object in self.pokemons.items():
            if query_string in pokemon_name.lower(
            ) and type in pokemon_object.type:
                results.append(pokemon_name)

        return sorted(results)

    def filter_pokemon(self, query_string):
        results = []
        for pokemon_name, pokemon_object in self.pokemons.items():
            if query_string in pokemon_name:
                results.append(pokemon_name)

        return sorted(results)

    def get_pokemon_types(self):
        for pokemon, pokemon_object in self.pokemons.items():
            for type in pokemon_object.type:
                if type not in self.pokemon_types:
                    self.pokemon_types.append(type)
        self.cb_filter_type['values'] = sorted(self.pokemon_types)
        self.cb_filter_type.current(0)

    @staticmethod
    def clear_and_insert_to_listbox(listbox, source):
        listbox.delete(0, END)
        for item in source:
            listbox.insert(END, item)

    @staticmethod
    def load_data(filename):
        data = []
        with open(filename, 'r') as file:
            for line in file:
                data.append(line.replace('\n', ''))

        return data

    @staticmethod
    def create_database(filename, datas):
        db = anydbm.open(filename, 'c')
        for key, value in datas.items():
            db[key] = pickle.dumps(value)

    @staticmethod
    def read_from_db(filename, source):
        db = anydbm.open(filename, 'r')
        for pokemon in db:
            source[pokemon] = pickle.loads(db[pokemon])
Beispiel #25
0
class ReportsFrame(Frame):
    def __init__(self,master,customers,payments,output_text):
        Frame.__init__(self,master)
        self.customers = customers
        self.payments = payments
        self.master = master
        self.output_text = output_text

        self.year_months = find_years_months(getcwd()) # use cwd, this should be set

        self.year = StringVar()
        self.month = StringVar()
        self.years = sorted(self.year_months.keys())
        self.months = []

        lf = LabelFrame(self, text="Generate Report")
        lf.grid(padx=5,pady=5,row=0,column=0,sticky='ew')

        Label(lf,text="Year: ").grid(row=0,column=0,sticky='e',padx=(10,0),pady=(10,2))
        Label(lf,text="Month: ").grid(row=1,column=0,sticky='e',padx=(10,0),pady=2)

        self.year_cb = Combobox(lf,textvariable=self.year,width=12,values=self.years,state='readonly')
        self.month_cb = Combobox(lf,textvariable=self.month,width=12,values=self.months,state='readonly')
        
        self.year_cb.grid(row=0,column=1,sticky='w',padx=(0,10),pady=(10,2))
        self.month_cb.grid(row=1,column=1,sticky='w',padx=(0,10),pady=2)

        btn = Button(lf,text="Save Report",command=self.report,width=30)
        btn.grid(row=2,column=0,columnspan=2,sticky='n',pady=(2,10),padx=10)

        #configure the grid to expand
        self.columnconfigure(0,weight=1)
        lf.rowconfigure(0,weight=1)
        lf.rowconfigure(1,weight=1)
        lf.columnconfigure(0,weight=1)
        lf.columnconfigure(1,weight=1)

        self.year_cb.bind('<<ComboboxSelected>>',self.year_selected)

        self.update() #update the values

    def report(self):
        '''
        generate the report, run by clicking Button
        '''
        if self.year.get() is '':
            self.output_text("! - Please Select a Year")
            return
        if self.month.get() is '':
            self.output_text("! - Please select a Month")
            return

        year = self.year.get()
        inputf = 'jim_data' + year + '.xlsx'
        month = self.month.get()
        outputf_def = month + year + '_report.xlsx'
        outputf = tkFileDialog.asksaveasfilename(parent=self,
            defaultextension='.xlsx', initialfile=outputf_def)
        if outputf is '': return #file not selected

        #output report
        month_report(inputf,month,year,outputf,self.customers,self.payments)

        self.output_text("* - " + self.month.get() + ' ' + self.year.get() + ' report saved to: ' + outputf + '\n')

        # print stat(outputf)

        if sys.platform == 'darwin':
            system('open ' + outputf + ' &')
        else:
            system(outputf) # open the file

    def update(self):
        '''
        method for updating values when things change
        '''
        self.year_months = find_years_months(getcwd()) # use cwd, this should be set
        self.years = sorted(self.year_months.keys())
        self.months = ['']
        if len(self.years) == 0: self.years = ['']
        self.year_cb['values'] = self.years
        self.month_cb['values'] = self.months
        self.month_cb.current(0)

    def year_selected(self,event=None):
        '''
        run when year is year is selected 
        '''
        self.months = self.year_months[self.year.get()]
        self.month_cb['values'] = self.months
        self.month_cb.current(0)
Beispiel #26
0
	def initUI(self):
		self.master.title('Bureau of Labor Statistics: Market Summary')
		#self.pack(fill=BOTH, expand=True)
		#self.grid_rowconfigure(0, weight=1)
		#self.grid_columnconfigure(0, weight=1)
		self.grid()
		

		######### Menu setup ###########
		menubar = Menu(self.master)
		
		file_menu = Menu(menubar)
		file_menu.add_command(label='Open...', command=self.select_file)
		file_menu.add_separator()
		file_menu.add_command(label='Close', command=self.quit)
		menubar.add_cascade(label='File', menu=file_menu)


		about_menu = Menu(menubar)
		about_menu.add_command(label='About')
		menubar.add_cascade(label='Help', menu=about_menu)

		self.master.config(menu=menubar)
		# end menu setup

		
		####### Logo ########
		logo = Image.open('img/BLS logo.jpg')
		logoo = ImageTk.PhotoImage(logo)
		logo_label = Label(self, image=logoo)
		logo_label.image = logoo
		logo_label.grid(row=0, columnspan=2)
		# end logo
	
		##### Combobox ########		
		occ_label = Label(self, text='Occupations:')
		occ_label.grid(row=1)
	
		choices = ['None']
		self.v = StringVar()
		cb = Combobox(self, textvariable=self.v,state='disabled', width=30)
		cb['values'] = choices
		cb.current(0)
		cb.bind('<<ComboboxSelected>>', self.on_select)
		self.my_cb['cb'] = cb
		cb.grid(row=1, column=1, pady=7, sticky=W)
		# end combobox
		
		###### Results #######
		j_label = Label(self, text='Job:')
		j_label.grid(row=2, padx=3, pady=3, sticky=W)

		jr_label = Label(self, text='None', anchor=W, justify=LEFT, width=30)
		self.my_labels['jr_label'] = jr_label
		jr_label.grid(row=2, column=1, pady=3, sticky=W)

		s_label = Label(self, text='Salary:')
		s_label.grid(row=3, padx=3, pady=3, sticky=W)

		sr_label = Label(self, text='None')
		self.my_labels['sr_label'] = sr_label
		sr_label.grid(row=3, column=1, pady=3, sticky=W)
		# end results

		####### Listbox #######
		lb = Listbox(self, width=30)
		lb.grid(row=0, column=2, rowspan=5, padx=10)

		
		####### Footer ###########
		closeButton = Button(self, text='Close', command=self.quit)
		closeButton.grid(row=4, column=2, sticky=E)
Beispiel #27
0
    def __init__(self, parent, parenttab, name, section, paramprefix):
        EditInput.__init__(self, parent, parenttab, name)
        self._section = section
        self._paramprefix = paramprefix

        fontlist = list(tkFont.families())
        fontlist.sort()
        self._bvb = tki.BooleanVar()
        self._bvi = tki.BooleanVar()
        self._bvs = tki.BooleanVar()
        self._bvu = tki.BooleanVar()

        l = tki.Label(self, text=lang[lng.txtFontsize])
        l.grid(row=0, column=0, padx=5, pady=2, sticky=tki.W)

        tcmd = (self.register(self._ehOnValidateEntry), '%d', '%P')
        e = tki.Entry(self,
                      validate='key',
                      validatecommand=tcmd,
                      width=_sizechars)
        self._esize = e
        e.grid(row=1, column=0, padx=5, pady=2, sticky=tki.W)

        l = tki.Label(self, text=lang[lng.txtFontName])
        l.grid(row=2, column=0, padx=5, pady=2, sticky=tki.W)

        cb = Combobox(self, values=fontlist)
        self._cbfontname = cb
        cb.grid(row=3, column=0, padx=5, pady=2, sticky=tki.W)
        cb.bind('<<ComboboxSelected>>', self._setDirty)
        cb.current(0)

        cb = tki.Checkbutton(self,
                             text=lang[lng.txtBold],
                             onvalue=True,
                             offvalue=False,
                             variable=self._bvb,
                             command=self._setDirty)
        self._cbb = cb
        cb.grid(row=0, column=1, padx=5, pady=2, sticky=tki.W)

        cb = tki.Checkbutton(self,
                             text=lang[lng.txtItalics],
                             onvalue=True,
                             offvalue=False,
                             variable=self._bvi,
                             command=self._setDirty)
        self._cbi = cb
        cb.grid(row=1, column=1, padx=5, pady=2, sticky=tki.W)

        cb = tki.Checkbutton(self,
                             text=lang[lng.txtStrikethrough],
                             onvalue=True,
                             offvalue=False,
                             variable=self._bvs,
                             command=self._setDirty)
        self._cbs = cb
        cb.grid(row=2, column=1, padx=5, pady=2, sticky=tki.W)

        cb = tki.Checkbutton(self,
                             text=lang[lng.txtUnderline],
                             onvalue=True,
                             offvalue=False,
                             variable=self._bvu,
                             command=self._setDirty)
        self._cbu = cb
        cb.grid(row=3, column=1, padx=5, pady=2, sticky=tki.W)
class Gui(Frame):
    """ Gui class for Graphical User Interface"""
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.searcher = Searcher()
        self.initUI()

    def initUI(self):
        self.pack(fill=BOTH, expand=True)
        Grid.columnconfigure(self, 0, weight=1)
        Label(self,
              text='Classroom Finder',
              font=('Arial', 20, 'bold'),
              bg='cyan',
              fg='white').grid(sticky=W + E,
                               columnspan=3)  # classroom finder header
        Label(self, text='Url:').grid(column=0, row=1, pady=10, padx=(50, 0))
        self.urlentry = Entry(self, width=100)  # url entry to get url
        self.urlentry.grid(column=1, row=1, padx=(0, 80))
        self.color_label = Label(
            self, bg='red', width=10)  # color label to make red,yellow,green
        self.color_label.grid(column=0,
                              row=2,
                              sticky=E,
                              columnspan=2,
                              padx=(120),
                              pady=(0, 40))
        self.fetchbtn = Button(self,
                               text='Fetch',
                               height=2,
                               width=10,
                               command=self.dynamic)  # fetch button
        self.fetchbtn.grid(column=1,
                           row=2,
                           sticky=E,
                           padx=(0, 30),
                           pady=(10, 50))
        Label(self,
              text='Filters',
              bg='cyan',
              fg='white',
              font=('Arial', 20, 'bold'),
              width=10).grid(column=0, row=3, padx=10)
        self.frame = Frame(self, borderwidth=3,
                           relief=GROOVE)  # frame to keep filters part
        self.frame.grid(column=0,
                        row=4,
                        columnspan=3,
                        sticky=W + E + S + N,
                        pady=10,
                        padx=10)
        Label(self.frame, text='Where am I?').grid(sticky=W)
        self.where_combo = Combobox(self.frame,
                                    state='readonly')  # where am i combobox
        self.where_combo.grid(column=1, row=0, pady=20)
        self.where_combo.bind(
            '<<ComboboxSelected>>',
            self.change_build)  # to update room button wrt where combo
        Label(self.frame, text='Room').grid(sticky=W)
        self.room_combo = Combobox(self.frame,
                                   state='readonly')  # rooms combobox
        self.room_combo.grid(column=1, row=1)
        Label(self.frame, text='Start').grid(sticky=W)
        self.start_combo = Combobox(self.frame, state='readonly',
                                    width=7)  # start time combobox
        self.start_combo.grid(column=1, row=2, pady=20, sticky=W)
        Label(self.frame, text='End').grid(column=2, row=2, sticky=W)
        self.end_combo = Combobox(self.frame, state='readonly',
                                  width=7)  # end time combobox
        self.end_combo.grid(column=3, row=2, sticky=W)
        Label(self.frame, text='Day').grid(sticky=W)
        self.day_combo = Combobox(self.frame,
                                  state='readonly')  # days combobox
        self.day_combo.grid(column=1, row=3, pady=(0, 20))
        self.search = Button(self.frame,
                             text='Search',
                             width=10,
                             height=2,
                             command=self.add_treeview)  # seach button
        self.search.grid(padx=(0, 50), columnspan=2)
        Label(self.frame, text='Classroom results', bg='gray',
              fg='white').grid(sticky=N + E + W,
                               column=4,
                               row=0,
                               rowspan=5,
                               padx=(55, 0))
        self.scroll = Scrollbar(
            self.frame, orient='vertical')  # vertical scrollbar for treeview
        self.tree = Treeview(self.frame,
                             columns=('', '', '', '', ''),
                             selectmode='extended',
                             show='headings')
        listofcolumn = [
            'Room', 'Traffic', 'Availability %', 'Closeness', 'Overall Score'
        ]  # colums to treeview
        counter = 1
        for column in listofcolumn:
            self.tree.column('#' + str(counter), width=90)  # to resize columns
            self.tree.heading('#' + str(counter), text=column,
                              anchor=CENTER)  # to set headings
            counter += 1
        self.scroll.config(command=self.tree.yview)
        self.tree.config(yscrollcommand=self.scroll.set)
        self.tree.grid(column=4, row=0, rowspan=5, padx=(40, 0), pady=(30, 0))
        self.scroll.grid(column=5,
                         row=0,
                         rowspan=5,
                         sticky=N + S,
                         pady=(30, 0))
        self.urlentry.insert(
            0,
            'https://www.sehir.edu.tr/en/announcements/2018-2019-bahar-donemi-ders-programi'
        )

    def dynamic(self):
        self.color_label.configure(
            bg='yellow'
        )  # make color label yellow at the beginning of the process
        self.update_idletasks()
        self.searcher.fetch(self.urlentry.get(
        ))  # to call fetch method in searcher class to start process
        self.color_label.configure(bg='green')
        room_num = [
            room.room_num
            for room in self.searcher.buildings['ACAD BUILD 1'].classrooms
        ]
        self.where_combo.configure(
            values=[build for build in sorted(self.searcher.buildings)])
        self.where_combo.current(
            0)  # to get values in combobox and set value 0 as a default
        self.room_combo.configure(values=[room for room in sorted(room_num)])
        self.room_combo.current(0)
        self.start_combo.configure(
            values=["{}:00".format(time) for time in range(9, 20)])
        self.start_combo.current(
            0)  # start and end combo both have the same interval from 9 to 19
        self.end_combo.configure(
            values=["{}:00".format(time) for time in range(9, 20)])
        self.end_combo.current(len(self.end_combo['values']) - 1)
        self.day_combo.configure(
            values=["Monday", 'Tuesday', 'Wednesday', 'Thursday', 'Friday'])
        self.day_combo.current(0)

    def change_build(
            self, event
    ):  # when where am i combobox chance, room combobox also chance
        building = self.where_combo.get()
        room_num = [
            room.room_num
            for room in self.searcher.buildings[building].classrooms
        ]
        self.room_combo.configure(values=[room for room in sorted(room_num)])
        self.room_combo.current(0)

    def add_treeview(self):  # to add scores in treeview
        self.tree.delete(*self.tree.get_children())
        self.overall_scores = self.searcher.search(
            self.day_combo.get(),
            self.where_combo.get(), self.room_combo.get(),
            self.start_combo.get(), self.end_combo.get()
        )  # key operator for the sorted dict by values which overall score
        for item, score in sorted(self.overall_scores.items(),
                                  key=operator.itemgetter(1),
                                  reverse=True):
            if item.availability_score == 0:  # to avoid from availability score 0
                continue
            room = str(item.classroom.building_num) + str(
                item.classroom.room_num)
            self.tree.insert('',
                             'end',
                             values=(room, item.traffic_score,
                                     item.availability_score,
                                     item.closeness_score, score))
Beispiel #29
0
class Example(Frame):
    counter = 0

    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent

        self.initUI()

    def nuevoVoluntario(self, nombre, apellidos, dni, direccion, correo_electronico, localidad_id, estudio_id,
                        parroquial_id, proyecto_id, telefono_1, telefono_2, genero, fecha_nacimiento,t,estado,id):
        global cnx
        cursor = cnx.cursor()
        if estado:
            query = (
                "INSERT INTO caritas.voluntario (nombre, apellidos, dni, direccion, correo_electronico, localidad_id, estudio_id, parroquial_id, proyecto_id, telefono_1, telefono_2, genero, fecha_nacimiento) VALUES ('%s','%s','%s','%s','%s','%d','%d','%d','%d','%s','%s','%s','%s')" % (
                    nombre, apellidos, dni, direccion, correo_electronico, localidad_id, estudio_id, parroquial_id,
                    proyecto_id,
                    telefono_1, telefono_2, genero, fecha_nacimiento))
        else:
            query = (
                "UPDATE caritas.voluntario SET nombre = ('%s'), apellidos = ('%s'), dni = ('%s'), direccion = ('%s'), correo_electronico = ('%s'), localidad_id = ('%d'), estudio_id = ('%d'), parroquial_id = ('%d'),proyecto_id = ('%d'), telefono_1 = ('%s'), telefono_2 = ('%s'), genero = ('%s'), fecha_nacimiento = ('%s') WHERE id = ('%d')"
                % ( nombre, apellidos, dni, direccion, correo_electronico, localidad_id, estudio_id, parroquial_id,proyecto_id, telefono_1, telefono_2, genero, fecha_nacimiento,id))
        cursor.execute(query)
        cnx.commit()
        cursor.close()

        t.destroy()

    def getEstudios(self):
        global cnx
        cursor = cnx.cursor(dictionary=True)
        query = ("SELECT * FROM estudio e")
        cursor.execute(query)
        valores = []
        strings = []
        for row in cursor:
            valores.append(row['id'])
            strings.append(row['nombre'])

        cursor.close()
        self.listadoEstudios = [strings, valores]

    def getParroquial(self):
        global cnx
        cursor = cnx.cursor(dictionary=True)
        query = ("SELECT * FROM parroquial e")
        cursor.execute(query)
        valores = []
        strings = []
        for row in cursor:
            valores.append(row['id'])
            strings.append(row['nombre'])

        cursor.close()
        self.listadoParroquial = [strings, valores]

    def getPais(self):
        global cnx
        cursor = cnx.cursor(dictionary=True)
        query = ("SELECT * FROM pais e")
        cursor.execute(query)
        valores = []
        strings = []
        for row in cursor:
            valores.append(row['id'])
            strings.append(row['nombre'])

        cursor.close()
        self.listadoPais = [strings, valores]

    def nuevoEstudio(self):
        t = Toplevel(self)
        t.wm_title("Estudio")

        Label(t, text="Nombre").grid(row=0, column=1)
        E2 = Entry(t)
        E2.grid(row=1, column=1)

        button1 = Button(t, text="Cancelar", command=lambda: t.destroy())
        button2 = Button(t, text="Guardar", command=lambda: self.nuevaEntradaEstudios(E2.get(), t))
        button3 = Button(t, text="Borrar", command=lambda: self.BorrarEstudios(E2.get(), t))
        button3.config(state="disabled")

        button1.grid(row=2, column=0)
        button2.grid(row=2, column=1)
        button3.grid(row=2, column=2)

    def nuevoPais(self):
        t = Toplevel(self)
        t.wm_title("Pais")

        Label(t, text="Nombre").grid(row=0, column=1)
        E2 = Entry(t)
        E2.grid(row=1, column=1)

        button1 = Button(t, text="Cancelar", command=lambda: t.destroy())
        button2 = Button(t, text="Guardar", command=lambda: self.nuevaEntradaPais(E2.get(), t))
        button3 = Button(t, text="Borrar", command=lambda: self.BorrarPais(E2.get(), t))
        button3.config(state="disabled")

        button1.grid(row=2, column=0)
        button2.grid(row=2, column=1)
        button3.grid(row=2, column=2)

    def nuevaParroquia(self):
        t = Toplevel(self)
        t.wm_title("Parroquial")

        Label(t, text="Nombre").grid(row=0, column=1)
        E2 = Entry(t)
        E2.grid(row=1, column=1)

        button1 = Button(t, text="Cancelar", command=lambda: t.destroy())
        button2 = Button(t, text="Guardar", command=lambda: self.nuevaEntradaParroquia(E2.get(), t))
        button3 = Button(t, text="Borrar", command=lambda: self.BorrarParroquial(E2.get(), t))
        button3.config(state="disabled")

        button1.grid(row=2, column=0)
        button2.grid(row=2, column=1)
        button3.grid(row=2, column=2)

    def editarEstudio(self):
        t = Toplevel(self)
        t.wm_title("Estudio")

        Label(t, text="Nombre").grid(row=0, column=1)
        E2 = Entry(t)
        E2.insert(END, self.selectorEstudios.get())
        E2.grid(row=1, column=1)

        nombreOld = self.selectorEstudios.get()


        button1 = Button(t, text="Cancelar", command=lambda: t.destroy())
        button2 = Button(t, text="Guardar", command=lambda: self.actualizarEstudio(nombreOld, E2.get(), t))
        button3 = Button(t, text="Borrar", command=lambda: self.BorrarEstudios(E2.get(), t))

        button1.grid(row=2, column=0)
        button2.grid(row=2, column=1)
        button3.grid(row=2, column=2)

    def editarPais(self):
        t = Toplevel(self)
        t.wm_title("Pais")

        Label(t, text="Nombre").grid(row=0, column=1)
        E2 = Entry(t)
        E2.insert(END, self.selectorPais.get())
        E2.grid(row=1, column=1)

        nombreOld = self.selectorPais.get()

        button1 = Button(t, text="Cancelar", command=lambda: t.destroy())
        button2 = Button(t, text="Guardar", command=lambda: self.actualizarPais(nombreOld, E2.get(), t))
        button3 = Button(t, text="Borrar", command=lambda: self.BorrarPais(E2.get(), t))

        button1.grid(row=2, column=0)
        button2.grid(row=2, column=1)
        button3.grid(row=2, column=2)

    def editarParroquia(self):
        t = Toplevel(self)
        t.wm_title("Estudio")

        Label(t, text="Nombre").grid(row=0, column=1)
        E2 = Entry(t)
        E2.insert(END, self.selectorParroquial.get())
        E2.grid(row=1, column=1)

        nombreOld = self.selectorParroquial.get()

        button1 = Button(t, text="Cancelar", command=lambda: t.destroy())
        button2 = Button(t, text="Guardar", command=lambda: self.actualizarParroquia(nombreOld, E2.get(), t))
        button3 = Button(t, text="Borrar", command=lambda: self.BorrarParroquial(E2.get(), t))

        button1.grid(row=2, column=0)
        button2.grid(row=2, column=1)
        button3.grid(row=2, column=2)

    def actualizarPais(self, nombreOld, nombreN, t):
        global cnx
        cursor = cnx.cursor()
        query = ("UPDATE caritas.pais SET nombre= ('%s') WHERE nombre = ('%s')" % (nombreN, nombreOld))
        cursor.execute(query)
        cnx.commit()
        cursor.close()

        self.getPais()
        self.selectorPais['values'] = self.listadoPais[0]

        t.destroy()

    def actualizarEstudio(self, nombreOld, nombreN, t):
        global cnx
        cursor = cnx.cursor()
        query = ("UPDATE caritas.estudio SET nombre= ('%s') WHERE nombre = ('%s')" % (nombreN, nombreOld))
        cursor.execute(query)
        cnx.commit()
        cursor.close()

        self.getEstudios()
        self.selectorEstudios['values'] = self.listadoEstudios[0]

        t.destroy()

    def actualizarParroquia(self, nombreOld, nombreN, t):
        global cnx
        cursor = cnx.cursor()
        query = ("UPDATE caritas.parroquial SET nombre= ('%s') WHERE nombre = ('%s')" % (nombreN, nombreOld))
        cursor.execute(query)
        cnx.commit()
        cursor.close()

        self.getParroquial()
        self.selectorParroquial['values'] = self.listadoParroquial[0]

        t.destroy()

    def BorrarEstudios(self, nombre, t):
        global cnx
        cursor = cnx.cursor()
        query = ("DELETE FROM caritas.estudio WHERE nombre = ('%s')" % nombre)
        cursor.execute(query)
        cnx.commit()
        cursor.close()

        self.getEstudios()
        self.selectorEstudios['values'] = self.listadoEstudios[0]

        t.destroy()

    def BorrarPais(self, nombre, t):
        global cnx
        cursor = cnx.cursor()
        query = ("DELETE FROM caritas.pais WHERE nombre = ('%s')" % nombre)
        cursor.execute(query)
        cnx.commit()
        cursor.close()

        self.getPais()
        self.selectorPais['values'] = self.listadoPais[0]

        t.destroy()

    def BorrarParroquial(self, nombre, t):
        global cnx
        cursor = cnx.cursor()
        query = ("DELETE FROM caritas.parroquial WHERE nombre = ('%s')" % nombre)
        cursor.execute(query)
        cnx.commit()
        cursor.close()

        self.getParroquial()
        self.selectorParroquial['values'] = self.listadoParroquial[0]

        t.destroy()

    def nuevaEntradaEstudios(self, nombre, t):
        global cnx
        cursor = cnx.cursor()
        query = ("INSERT INTO caritas.estudio (nombre) VALUE ('%s')" % nombre)
        cursor.execute(query)
        cnx.commit()
        cursor.close()

        self.getEstudios()
        self.selectorEstudios['values'] = self.listadoEstudios[0]

        t.destroy()

    def nuevaEntradaPais(self, nombre, t):
        global cnx
        cursor = cnx.cursor()
        query = ("INSERT INTO caritas.pais (nombre) VALUE ('%s')" % nombre)
        cursor.execute(query)
        cnx.commit()
        cursor.close()

        self.getPais()
        self.selectorPais['values'] = self.listadoPais[0]

        t.destroy()

    def nuevaEntradaParroquia(self, nombre, t):
        global cnx
        cursor = cnx.cursor()
        query = ("INSERT INTO caritas.parroquial (nombre) VALUE ('%s')" % nombre)
        cursor.execute(query)
        cnx.commit()
        cursor.close()

        self.getParroquial()
        self.selectorParroquial['values'] = self.listadoParroquial[0]

        t.destroy()

    def ventanaVoluntarios(self,row):

        id = -1
        guardar = TRUE
        # Creamos una ventana nueva
        t = Toplevel(self)
        t.wm_title("Crear Voluntario")

        # Etiqueta y entrada de nombre
        Label(t, text="Nombre").grid(row=0)
        entradaNombre = Entry(t)
        entradaNombre.grid(row=0, column=1,sticky = "ew")

        # Etiqueta y entrada de apellidos
        Label(t, text="Apellidos").grid(row=1)
        entradaApellidos = Entry(t)
        entradaApellidos.grid(row=1, column=1,sticky = "ew")

        # Etiqueta y entrada de DNI
        Label(t, text="DNI").grid(row=2)
        entradaDNI = Entry(t)
        entradaDNI.grid(row=2, column=1,sticky = "ew")

        # Etiqueta y entrada de Dirreccion
        Label(t, text="Direccion").grid(row=3)
        entradaDireccion = Entry(t)
        entradaDireccion.grid(row=3, column=1)

        # Etiqueta y seleccion de Estudios
        Label(t, text="Estudios").grid(row=4)
        box_value = StringVar()
        self.getEstudios()
        self.selectorEstudios = Combobox(t, textvariable=box_value, state='readonly')
        self.selectorEstudios['values'] = self.listadoEstudios[0]
        self.selectorEstudios.configure(width=25)
        self.selectorEstudios.current(0)
        self.selectorEstudios.grid(row=4, column=1)

        botonEditarEstudios = Button(t, text="Editar", command=self.editarEstudio)
        botonNuevosEstudios = Button(t, text="Nuevo", command=self.nuevoEstudio)
        botonEditarEstudios.grid(row=4, column=2)
        botonNuevosEstudios.grid(row=4, column=3)

        # Etiqueta y seleccion de Genero
        Label(t, text="Genero").grid(row=5)
        seleccionGenero = Combobox(t, values=["Masculino (M)", "Femenino (F)"], state='readonly')
        seleccionGenero.grid(row=5, column=1)

        # Etiqueta y seleccion de Parroquial
        Label(t, text="Parroquial").grid(row=6)
        box_value = StringVar()
        self.getParroquial()
        self.selectorParroquial = Combobox(t, textvariable=box_value, state='readonly')
        self.selectorParroquial['values'] = self.listadoParroquial[0]
        self.selectorParroquial.configure(width=25)
        self.selectorParroquial.current(0)
        self.selectorParroquial.grid(row=6, column=1)

        botonEditarParroquial = Button(t, text="Editar", command=self.editarParroquia)
        botonNuevaParroqual = Button(t, text="Nuevo", command=self.nuevaParroquia)
        botonEditarParroquial.grid(row=6, column=2)
        botonNuevaParroqual.grid(row=6, column=3)

        # Etiqueta y seleccion de Correo
        Label(t, text="Correo").grid(row=0, column=4)
        entradaCorreo = Entry(t)
        entradaCorreo.grid(row=0, column=5)

        Label(t, text="Telefono 1").grid(row=1, column=4)
        entradaTelefono1 = Entry(t)
        entradaTelefono1.grid(row=1, column=5)

        Label(t, text="Telefono 2").grid(row=2, column=4)
        entradaTelefono2 = Entry(t)
        entradaTelefono2.grid(row=2, column=5)

        # Etiqueta y entrada de Fecha
        Label(t, text="Fecha").grid(row=3, column=4)
        entradaAno = Entry(t)
        entradaMes = Entry(t)
        entradaDia = Entry(t)
        entradaAno.grid(row=3, column=5)
        entradaMes.grid(row=3, column=6)
        entradaDia.grid(row=3, column=7)

        # Etiqueta y seleccion de Pais
        Label(t, text="Pais").grid(row=4, column=4)
        box_value = StringVar()
        self.getPais()
        self.selectorPais = Combobox(t, textvariable=box_value, state='readonly')
        self.selectorPais['values'] = self.listadoPais[0]
        self.selectorPais.configure(width=25)
        self.selectorPais.current(0)
        self.selectorPais.grid(row=4, column=5)

        botonEditarPais = Button(t, text="Editar", command=self.editarPais)
        botonNuevaPais = Button(t, text="Nuevo", command=self.nuevoPais)
        botonEditarPais.grid(row=4, column=6)
        botonNuevaPais.grid(row=4, column=7)

        #Rellenamos los cambos si estamos editando
        if row > -1:
            voluntario = self.table.model.getRecordAtRow(row)
            entradaNombre.insert(END,voluntario['nombre'])
            entradaApellidos.insert(END,voluntario['apellidos'])
            entradaCorreo.insert(END,voluntario['correo_electronico'])
            entradaTelefono1.insert(END,voluntario['telefono_1'])
            entradaTelefono2.insert(END,voluntario['telefono_2'])
            entradaDireccion.insert(END,voluntario['direccion'])
            entradaDNI.insert(END,voluntario['dni'])
            self.selectorEstudios.set(voluntario['estudio'])
            self.selectorParroquial.set(voluntario['parroquial'])
            guardar = FALSE
            id = voluntario['id']





        button5 = Button(t, text="Guardar", command=lambda: self.nuevoVoluntario(entradaNombre.get(),
                                                                                 entradaApellidos.get(),entradaDNI.get(),entradaDireccion.get(),
                                                                                 entradaCorreo.get(),1,self.listadoEstudios[1][self.selectorEstudios.current()],
                                                                                 self.listadoParroquial[1][self.selectorParroquial.current()],
                                                                                 1,entradaTelefono1.get(),entradaTelefono2.get(),"M","2001-01-01",t,guardar,id))
        button6 = Button(t, text="Cancelar", command=t.destroy)

        button5.grid(row=7, column=4)
        button6.grid(row=7, column=5)


    def validarVoluntario(self, nombre, apellidos, dni, direccion, correo_electronico, localidad_id, estudio_id,
                        parroquial_id, proyecto_id, telefono_1, telefono_2, genero, fecha_nacimiento,t,estado,id):

        guarda = True
        error = ""

        if len(nombre)<3 :
            error = error + "Nombre debe tener mas de 2 caracteres\n"
            guarda = False

        if len(apellidos)<3 :
            error = error + "Apellidos debe tener mas de 2 caracteres\n"
            guarda = False

        if len(dni)==9 and dni[8].isalpha() and dni[0-7].isdigit():
            error = error + "Dni tiene el formato NNNNNNNNX donde N es un digito y X una letra \n"
            guarda = False

        if len(direccion)==0:
            error = error + "Introduzca una Dirección \n"
            guarda = False

        if len(correo_electronico)<5:
            error = error + "Introduzca una dirección de correo valida \n"
            guarda = False


        if len(telefono_1)<9:
            error = error + "Introduzca un numero valido \n"
            guarda = False

        if len(telefono_1)==0:
            telefono_1=0

        if guarda:self.nuevoVoluntario(nombre, apellidos, dni, direccion, correo_electronico, localidad_id, estudio_id,
                        parroquial_id, proyecto_id, telefono_1, telefono_2, genero, fecha_nacimiento,t,estado,id)
        # añadir el error
        else:
            print error

    def ventanaImprimir(self):
        t = Toplevel(self)
        t.wm_title("Imprimir")

        Label(t, text="Numero de Copias por etiqueta").pack()
        w = Spinbox(t, from_=1, to=10)
        w.pack()

        buttonImprimir = Button(t, text="Imprimir",  command=lambda:self.imprimir(int(w.get()),t))
        buttonImprimir.pack()

    def agregarListado(self,numero):
        voluntario = self.table.model.getRecordAtRow(numero)
        modelNuevo = TableModel()

        modelNuevo.addColumn("nombre")
        modelNuevo.addColumn("apellidos")
        modelNuevo.addColumn("dni")
        modelNuevo.addColumn("direccion")
        modelNuevo.addColumn("correo_electronico")
        modelNuevo.addColumn("estudio")
        modelNuevo.addColumn("parroquial")
        modelNuevo.addColumn("proyecto")
        modelNuevo.addColumn("genero")
        modelNuevo.addColumn("fecha_nacimiento")
        modelNuevo.addColumn("telefono_1")
        modelNuevo.addColumn("telefono_2")

        arrayListado = self.selectTable.getModel().data
        valores = {}
        i=1
        for values in arrayListado:
            valores['row',i]=arrayListado['row',i]
            i+=1
        valores['row',i]=voluntario
        modelNuevo.importDict(valores)

        self.selectTable.updateModel(modelNuevo)
        self.selectTable.redrawTable()

    def quitarListado(self,numero):
        voluntario = self.selectTable.model.getRecordAtRow(numero)
        modelNuevo = TableModel()

        modelNuevo.addColumn("nombre")
        modelNuevo.addColumn("apellidos")
        modelNuevo.addColumn("dni")
        modelNuevo.addColumn("direccion")
        modelNuevo.addColumn("correo_electronico")
        modelNuevo.addColumn("estudio")
        modelNuevo.addColumn("parroquial")
        modelNuevo.addColumn("proyecto")
        modelNuevo.addColumn("genero")
        modelNuevo.addColumn("fecha_nacimiento")
        modelNuevo.addColumn("telefono_1")
        modelNuevo.addColumn("telefono_2")

        print numero

        arrayListado = self.selectTable.getModel().data
        valores = {}
        i=1
        for values in arrayListado:
            if numero+1 != i:
                valores['row',i]=arrayListado['row',i]
            i+=1
        modelNuevo.importDict(valores)

        self.selectTable.updateModel(modelNuevo)
        self.selectTable.redrawTable()

    def imprimir(self,numero,label):
        pdf = fpdf.FPDF(format='letter')
        pdf.add_page()
        pdf.set_font("Arial", size=14)

        indice=1
        columna=1
        fila=0
        p=0
        for ficha in self.listadoSeleccionado:
            row = self.listadoSeleccionado['row',indice]
            for x in range(0, numero):
                if p==9:
                    pdf.add_page()
                    p=0
                else:
                    p+=1

                texto = 'Nombre: %s\nApellidos: %s\nDireccion: %s\nTelefono: %s' %(row["nombre"],row["apellidos"],row["direccion"],row["telefono_1"])
                pdf.multi_cell(65, 10,texto,align='C')
                pdf.set_xy(70*columna,60*fila +10)
                columna = columna + 1
                if columna == 4:
                    columna=1
                    fila=fila+1
                    pdf.set_xy(10,60*fila +10)

            indice = indice + 1
        pdf.output("tutorial.pdf")

        label.destroy()

    def buscar(self,nombre,apellidos):

        modelCompleto = TableModel()
        modelNuevo = TableModel()

        modelNuevo.addColumn("nombre")
        modelNuevo.addColumn("apellidos")
        modelNuevo.addColumn("dni")
        modelNuevo.addColumn("direccion")
        modelNuevo.addColumn("correo_electronico")
        modelNuevo.addColumn("estudio")
        modelNuevo.addColumn("parroquial")
        modelNuevo.addColumn("proyecto")
        modelNuevo.addColumn("genero")
        modelNuevo.addColumn("fecha_nacimiento")
        modelNuevo.addColumn("telefono_1")
        modelNuevo.addColumn("telefono_2")

        self.listilla= queryAllVoluntarios()
        modelCompleto.importDict(self.listilla)
        searchterms = [('nombre', nombre, 'contains', 'AND'),('apellidos', apellidos, 'contains', 'AND')]
        result=modelCompleto.getDict(modelCompleto.columnNames, filters=searchterms)
        modelNuevo.importDict(result)
        self.listadoSeleccionado = result
        self.table.updateModel(modelNuevo)
        self.table.redrawTable()

    def eventoClic(self):
        print "Clicado"
        return


    def initUI(self):

        self.parent.title("Caritas")
        self.style = Style()
        self.style.theme_use("default")

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

        frameMenu = Frame(self)
        frameMenu.pack(fill="both", expand="0", side=RIGHT)

        labelBusqueda = LabelFrame(frameMenu, text="Busqueda")
        labelBusqueda.pack(fill="x",expand =1)

        labelVoluntarios = LabelFrame(frameMenu)
        labelVoluntarios.pack(fill="both",expand =0)

        frameTabla = Frame(self)
        frameTabla.pack(fill="both", expand="1", side=LEFT)

        labelTabla = LabelFrame(frameTabla)
        labelTabla.pack(fill="both", expand="1")

        labelBotonera = LabelFrame(frameTabla)
        labelTabla.pack(fill="both", expand="1")

        labelSelect = LabelFrame(frameTabla)
        labelSelect.pack(fill="both", expand="1")

        model = TableModel()
        modelSelect = TableModel()

        model.addColumn("nombre")
        model.addColumn("apellidos")
        model.addColumn("dni")
        model.addColumn("direccion")
        model.addColumn("correo_electronico")
        model.addColumn("estudio")
        model.addColumn("parroquial")
        model.addColumn("proyecto")
        model.addColumn("genero")
        model.addColumn("fecha_nacimiento")
        model.addColumn("telefono_1")
        model.addColumn("telefono_2")

        modelSelect.addColumn("nombre")
        modelSelect.addColumn("apellidos")
        modelSelect.addColumn("dni")
        modelSelect.addColumn("direccion")
        modelSelect.addColumn("correo_electronico")
        modelSelect.addColumn("estudio")
        modelSelect.addColumn("parroquial")
        modelSelect.addColumn("proyecto")
        modelSelect.addColumn("genero")
        modelSelect.addColumn("fecha_nacimiento")
        modelSelect.addColumn("telefono_1")
        modelSelect.addColumn("telefono_2")

        #Tabla Voluntarios
        self.listilla= queryAllVoluntarios()
        model.importDict(self.listilla)
        self.table = TableCanvas(labelTabla, model=model,editable=False)
        self.table.createTableFrame()
        self.table.handle_double_click(self.eventoClic)

        #Tabla Seleccionados
        self.selectTable = TableCanvas(labelSelect, model=modelSelect,editable=False)
        self.selectTable.createTableFrame()
        self.listadoSeleccionado = []

        L1 = Label(labelBusqueda, text="Nombre")
        L1.pack()
        E1 = Entry(labelBusqueda)
        E1.pack()

        L2 = Label(labelBusqueda, text="Apellidos")
        L2.pack()
        E2 = Entry(labelBusqueda)
        E2.pack()

        botonArriba = Button(labelVoluntarios, text="Agregar al listado",  command=lambda:self.agregarListado(self.table.getSelectedRow()))
        botonArriba.pack()
        botonAbajo = Button(labelVoluntarios, text="Quitar del listado",  command=lambda:self.quitarListado(self.selectTable.getSelectedRow()))
        botonAbajo.pack()

        button = Button(labelBusqueda, text="Buscar", command=lambda: self.buscar(E1.get(),E2.get()))
        button.pack()

        button = Button(labelVoluntarios, text="Nuevo Voluntario",  command=lambda:self.ventanaVoluntarios(-1))
        button.pack()

        buttonEditar = Button(labelVoluntarios, text="Editar Voluntario",  command=lambda:self.ventanaVoluntarios(self.table.getSelectedRow()))
        buttonEditar.pack()

        buttonImprimir = Button(labelVoluntarios, text="Imprimir",  command=lambda:self.ventanaImprimir())
        buttonImprimir.pack()
Beispiel #30
0
class MainFrame(Frame):
    def __init__(self,parent,stdoutq):
        Frame.__init__(self,parent)

        self.parent=parent
        self.width=750
        self.height=450
        self.title=ximaexport.__version__
        self.stdoutq=stdoutq
        
        self.initUI()

        self.hasdb=False
        self.hasout=False
        self.exit=False

        self.path_frame=self.addPathFrame()
        self.action_frame=self.addActionFrame()
        self.message_frame=self.addMessageFrame()
        self.printStr()

        self.stateq=Queue.Queue()


    def centerWindow(self):
        sw=self.parent.winfo_screenwidth()
        sh=self.parent.winfo_screenheight()
        x=(sw-self.width)/2
        y=(sh-self.height)/2
        self.parent.geometry('%dx%d+%d+%d' \
                %(self.width,self.height,x,y))


    def initUI(self):
        self.parent.title(self.title)
        self.style=Style()
        #Choose from default, clam, alt, classic
        self.style.theme_use('alt')
        self.pack(fill=tk.BOTH,expand=True)
        self.centerWindow()


    def printStr(self):
        while self.stdoutq.qsize() and self.exit==False:
            try:
                msg=self.stdoutq.get()
                self.text.update()
                self.text.insert(tk.END,msg)
                self.text.see(tk.END)
            except Queue.Empty:
                pass
        self.after(100,self.printStr)



    def checkReady(self):

        if self.hasdb and self.hasout:
            self.start_button.configure(state=tk.NORMAL)
            #print('XimaExport Ready.')
            printch('XimaExport 就绪.')
        else:
            self.start_button.configure(state=tk.DISABLED)


    def addPathFrame(self):
        frame=Frame(self)
        frame.pack(fill=tk.X,expand=0,side=tk.TOP,padx=8,pady=5)

        frame.columnconfigure(1,weight=1)

        #------------------Database file------------------
        label=tk.Label(frame,text=dgbk('ting.sqlite文件:'),\
                bg='#bbb')
        label.grid(row=0,column=0,\
                sticky=tk.W,padx=8)

        self.db_entry=tk.Entry(frame)
        self.db_entry.grid(row=0,column=1,sticky=tk.W+tk.E,padx=8)

        self.db_button=tk.Button(frame,text=dgbk('打开'),command=self.openFile)
        self.db_button.grid(row=0,column=2,padx=8,sticky=tk.E)

        #--------------------Output dir--------------------
        label2=tk.Label(frame,text=dgbk('导出到文件夹:'),\
                bg='#bbb')
        label2.grid(row=2,column=0,\
                sticky=tk.W,padx=8)

        self.out_entry=tk.Entry(frame)
        self.out_entry.grid(row=2,column=1,sticky=tk.W+tk.E,padx=8)
        self.out_button=tk.Button(frame,text=dgbk('选择'),command=self.openDir)
        self.out_button.grid(row=2,column=2,padx=8,sticky=tk.E)
        


    def openDir(self):
        self.out_entry.delete(0,tk.END)
        dirname=askdirectory()
        self.out_entry.insert(tk.END,dirname)
        if len(dirname)>0:
            #print('Output folder: %s' %dirname)
            printch('输出到文件夹:')
	    print('   '+dirname)
            self.hasout=True
            self.checkReady()


    def openFile(self):
        self.db_entry.delete(0,tk.END)
        ftypes=[('sqlite files','*.sqlite'),('ALL files','*')]
        filename=askopenfilename(filetypes=ftypes)
        self.db_entry.insert(tk.END,filename)
        if len(filename)>0:
            #print('Database file: %s' %filename)
            printch('数据文件:')
	    print('   '+filename)
            self.probeAlbums()


    def probeAlbums(self):
        dbfile=self.db_entry.get()
        try:
            db=sqlite3.connect(dbfile)
            df=ximaexport.getData(db)
            self.albumlist=ximaexport.getAlbumList(df,None)   #(id, name)
            self.albumnames=['All']+[ii[1] for ii in self.albumlist] #names to display
            self.albummenu['values']=tuple(self.albumnames)
            self.albummenu.current(0)
            db.close()

            self.hasdb=True
            self.checkReady()

        except Exception as e:
            #print('Failed to recoganize the given database file.') 
            printch('无法识别sqlite数据文件.') 
            print(e)



    
    def addActionFrame(self):

        frame=Frame(self,relief=tk.RAISED,borderwidth=1)
        frame.pack(fill=tk.X,side=tk.TOP,\
                expand=0,padx=8,pady=5)

        #label=tk.Label(frame,text='Actions:',bg='#bbb')
        #label.grid(row=0,column=0,sticky=tk.W,padx=8)

        #---------------Action checkbuttons---------------
        frame.columnconfigure(0,weight=1)

        #---------------------2nd row---------------------
        subframe=Frame(frame)
        subframe.grid(row=1,column=0,columnspan=6,sticky=tk.W+tk.E,\
                pady=5)

        #-------------------Album options-------------------
        albumlabel=tk.Label(subframe,text=dgbk('专辑:'),\
                bg='#bbb')
        albumlabel.pack(side=tk.LEFT, padx=8)

        self.album=tk.StringVar()
        self.albumnames=['All',]
        self.albummenu=Combobox(subframe,textvariable=\
                self.album,values=self.albumnames,state='readonly')
        self.albummenu.current(0)
        self.albummenu.bind('<<ComboboxSelected>>',self.setAlbum)
        self.albummenu.pack(side=tk.LEFT,padx=8)
        
        #-------------------Quit button-------------------
        quit_button=tk.Button(subframe,text=dgbk('退出'),\
                command=self.quit)
        quit_button.pack(side=tk.RIGHT,padx=8)

        #-------------------Stop button-------------------
        '''
        self.stop_button=tk.Button(subframe,text='Stop',\
                command=self.stop)
        self.stop_button.pack(side=tk.RIGHT,padx=8)
        '''
                
        #-------------------Start button-------------------
        self.start_button=tk.Button(subframe,text=dgbk('开始'),\
                command=self.start,state=tk.DISABLED)
        self.start_button.pack(side=tk.RIGHT,pady=8)

        #-------------------Help button-------------------
        self.help_button=tk.Button(subframe,text=dgbk('帮助'),\
                command=self.showHelp)
        self.help_button.pack(side=tk.RIGHT,padx=8)





    def setAlbum(self,x):
	import json
        self.albummenu.selection_clear()
        self.album=self.albummenu.get()
        self.albummenu.set(self.album)
        if self.album=='All':
            #print('Work on all albums.')
            printch('导出所有专辑.')
        else:
            #print('Select album: '+self.album)
            printch('导出所选专辑:')
	    print('   '+self.album)





    def showHelp(self):
        helpstr=dgbk('''\n\n
导出喜马拉雅下载音频,并自动按专辑归档、重命名:\n
1. 找到手机/pad中的喜马拉雅数据文件夹:\n
    (1)苹果用户:链接电脑itunes,在app一栏中找到“喜马拉雅”,单击,右侧会出现“喜马拉雅”的数据文件。选择“iDoc”,并导出到电脑。\n
    (2)安卓用户:链接电脑后,拷贝出ting文件夹。\n
2. 运行ximaexport-gui.exe。\n
    在 “ting.sqlite文件”一栏,选择步骤1中拷贝出的文件夹里的 ting.sqlite. 文件。\n
    在 “导出到文件夹”一栏,选择音频存储位置。\n
    在 “专辑”下拉菜单,选择要导出的专辑。若全部导出选择“All”。\n
    点击“开始”开始处理。
''')

        tkMessageBox.showinfo(title='Help', message=helpstr)
        #print(self.menfolder.get())



    def start(self):
        dbfile=self.db_entry.get()
        outdir=self.out_entry.get()
        self.album=self.albummenu.get()

        self.out_button.configure(state=tk.DISABLED)
        self.start_button.configure(state=tk.DISABLED)
        self.help_button.configure(state=tk.DISABLED)
        self.albummenu.configure(state=tk.DISABLED)
        self.messagelabel.configure(text=dgbk('信息 (处理中...)'))

        album=None if self.album=='All' else self.album

        args=[dbfile,outdir,album,True]

        self.workthread=WorkThread('work',False,self.stateq)
        self.workthread.deamon=True

        self.workthread.args=args
        self.workthread.start()
        self.reset()


    def reset(self):
        while self.stateq.qsize() and self.exit==False:
            try:
                msg=self.stateq.get()
                if msg=='done':
                    self.db_button.configure(state=tk.NORMAL)
                    self.out_button.configure(state=tk.NORMAL)
                    self.start_button.configure(state=tk.NORMAL)
                    self.help_button.configure(state=tk.NORMAL)
                    self.albummenu.configure(state='readonly')
                    self.messagelabel.configure(text=dgbk('消息'))
                    return
            except Queue.Empty:
                pass
        self.after(100,self.reset)


    
    def stop(self):
        #self.workthread.stop()
        pass
        

    def addMessageFrame(self):
        frame=Frame(self)
        frame.pack(fill=tk.BOTH,side=tk.TOP,\
                expand=1,padx=8,pady=5)

        self.messagelabel=tk.Label(frame,text=dgbk('消息'),bg='#bbb')
        self.messagelabel.pack(side=tk.TOP,fill=tk.X)

        self.text=tk.Text(frame)
        self.text.pack(side=tk.TOP,fill=tk.BOTH,expand=1)
        self.text.height=10

        scrollbar=tk.Scrollbar(self.text)
        scrollbar.pack(side=tk.RIGHT,fill=tk.Y)

        self.text.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.text.yview)
Beispiel #31
0
class Application(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.root = master
        self.root.title('company_info(Version:v1.0.3   Author:qing.guo)')
        self.root.geometry('720x460')
        self.root.resizable(0, 0)  # 禁止调整窗口大小
        self.root.protocol("WM_DELETE_WINDOW", self.close)
        self.root.iconbitmap(get_path('company.ico'))

    def creatWidgets(self):
        frame_left = Frame(self.root, width=360, height=460, bg='#C1CDCD')
        frame_right = Frame(self.root, width=360, height=460, bg='#C1CDCD')
        frame_left.grid_propagate(0)
        frame_right.propagate(0)
        frame_right.grid_propagate(0)
        frame_left.grid(row=0, column=0)
        frame_right.grid(row=0, column=1)

        self.v1 = StringVar()
        self.v2 = StringVar()

        Label(frame_left, text=u"选择数据类型:", bg='#C1CDCD').grid(row=0,
                                                              column=0,
                                                              pady=10,
                                                              padx=5)
        self.cb1 = Combobox(frame_left, width=30, textvariable=self.v1)
        self.cb1.grid(row=0,
                      column=1,
                      columnspan=2,
                      ipady=1,
                      padx=5,
                      pady=10,
                      sticky=W)
        self.cb1['values'] = [
            u'公司id', u'公司名称', u'机器人32位id或uid', u'服务器32位id或uid'
        ]
        self.cb1.current(0)

        Label(frame_left, text=u"输入查询数据 :", bg='#C1CDCD').grid(row=1,
                                                               column=0,
                                                               pady=10,
                                                               padx=5)
        Entry(frame_left, width=33, textvariable=self.v2).grid(row=1,
                                                               column=1,
                                                               columnspan=2,
                                                               padx=2,
                                                               pady=10,
                                                               ipady=2,
                                                               sticky=W)
        self.b1 = Button(frame_left,
                         text=u"查询归属公司id",
                         command=self.test1,
                         bg='#C1CDCD')
        self.b1.grid(row=2, column=1, padx=5, pady=8)
        self.b2 = Button(frame_left,
                         text=u"查询公司服务器",
                         command=self.test2,
                         bg='#C1CDCD')
        self.b2.grid(row=3, column=1, padx=5, pady=8)

        self.b3 = Button(frame_left,
                         text=u"查询公司机器人",
                         command=self.test3,
                         bg='#C1CDCD')
        self.b3.grid(row=4, column=1, padx=5, pady=8)

        self.b4 = Button(frame_left,
                         text=u"查询公司人员信息",
                         command=self.test4,
                         bg='#C1CDCD')
        self.b4.grid(row=5, column=1, padx=5, pady=8)

        self.b5 = Button(frame_left,
                         text=u"查询部门人员信息",
                         command=self.test5,
                         bg='#C1CDCD')
        self.b5.grid(row=6, column=1, padx=5, pady=8)

        self.b6 = Button(frame_left,
                         text=u"查询剩余可用服务器",
                         command=self.test6,
                         bg='#C1CDCD')
        self.b6.grid(row=7, column=1, padx=5, pady=8)

        self.b7 = Button(frame_left,
                         text=u"查询剩余可用机器人",
                         command=self.test7,
                         bg='#C1CDCD')
        self.b7.grid(row=8, column=1, padx=5, pady=8)

        self.b8 = Button(frame_left,
                         text=u"删除当前公司所有信息",
                         command=self.test8,
                         bg='#C1CDCD')
        self.b8.grid(row=9, column=1, padx=5, pady=8)

        #Scrollbar
        scrollbar = Scrollbar(frame_right, bg='#C1CDCD')
        scrollbar.pack(side=RIGHT, fill=Y)
        self.text_msglist = Text(frame_right,
                                 yscrollcommand=scrollbar.set,
                                 bg='#C1CDCD')
        self.text_msglist.pack(side=RIGHT, fill=BOTH)
        scrollbar['command'] = self.text_msglist.yview
        self.text_msglist.tag_config('green', foreground='#008B00')
        self.text_msglist.tag_config('blue', foreground='#0000FF')
        self.text_msglist.tag_config('red', foreground='#FF3030')

    def test(self, flag):
        r = redis.StrictRedis(host='58.60.230.238',
                              port=6278,
                              db=0,
                              password='******',
                              encoding='utf-8',
                              socket_timeout=5)
        self.com = comp.Company(flag, r, app)
        self.com.setDaemon(True)
        self.com.start()

    def check(self, flag):
        r = redis.StrictRedis(host='58.60.230.238',
                              port=6278,
                              db=0,
                              password='******',
                              encoding='utf-8',
                              socket_timeout=5)
        self.v3 = StringVar()
        window = Toplevel(self, bg='#C1CDCD')
        window.title('check permission')
        window.geometry('400x100')
        window.resizable(0, 0)  # 禁止调整窗口大小
        Label(window, text=u'请输入操作密码:', bg='#C1CDCD').grid(row=0,
                                                           column=0,
                                                           pady=10,
                                                           padx=5)
        e = Entry(window, width=30, textvariable=self.v3)
        e.grid(row=0, column=1, padx=5, pady=10, sticky=W)
        e.focus()
        self.v3.set('')
        r.set('comp_pwd', 'qhkj_987', nx=True)

        def check_pwd():
            input_pwd = self.v3.get()
            redis_pwd = r.get('comp_pwd')
            if input_pwd == redis_pwd:
                if flag == 6:
                    self.b6.config(state='disabled')
                    self.test(6)
                elif flag == 7:
                    self.b7.config(state='disabled')
                    self.test(7)
                elif flag == 8:
                    self.b8.config(state='disabled')
                    self.test(8)
            else:
                self.text_msglist.insert(END, "输入密码错误\n", 'red')
            window.destroy()

        Button(window, text=u"确定", width=20, command=check_pwd,
               bg='#C1CDCD').grid(row=1, column=1, pady=10, padx=5)
        window.protocol("WM_DELETE_WINDOW", window.destroy)

    def test1(self):
        self.b1.config(state='disabled')
        self.test(1)

    def test2(self):
        self.b2.config(state='disabled')
        self.test(2)

    def test3(self):
        self.b3.config(state='disabled')
        self.test(3)

    def test4(self):
        self.b4.config(state='disabled')
        self.test(4)

    def test5(self):
        self.b5.config(state='disabled')
        self.test(5)

    def test6(self):
        self.check(6)

    def test7(self):
        self.check(7)

    def test8(self):
        self.check(8)

    def close(self):
        self.root.quit()
        self.root.destroy()
class path_planner_gui(StoppableThread):
    DEFAULT_START_LAT = 55.434352  #55.43526 #55.431122
    DEFAULT_START_LON = 10.415182  #10.41086 #10.420436
    DEFAULT_GOAL_LAT = 55.42474  #55.427203
    DEFAULT_GOAL_LON = 10.41975  #10.419043

    # for testing altitude - points near Hindsgavl, Middelfart
    # start_point_3dDICT = {'lat': 55.505618, 'lon': 9.681612, 'alt_rel': 0}
    # goal_point_3dDICT  = {'lat': 55.518093, 'lon': 9.699519, 'alt_rel': 0}
    # goal inside geofence: 55.429331, 10.422770

    DEFAULT_STEP_SIZE_HORZ_ASTAR = 100
    DEFAULT_STEP_SIZE_VERT_ASTAR = 10
    DEFAULT_STEP_SIZE_HORZ_RRT = 50
    DEFAULT_STEP_SIZE_VERT_RRT = 10
    DEFAULT_SEARCH_TIME_MAX = 120  # unit: s
    DEFAULT_ITERATIONS_MAX = 3000

    DEFAULT_TIME_STEP = 1.0  # unit: s
    DEFAULT_ACCELERATION_FACTOR = 10.0  # unitless

    DEFAULT_STEP_SIZE_HORZ_LOCAL_ASTAR = 50
    DEFAULT_STEP_SIZE_VERT_LOCAL_ASTAR = 5
    DEFAULT_SEARCH_TIME_MAX_LOCAL = 180  # unit: s

    DEFAULT_STEP_SIZE_HORZ_LOCAL_RRT = 25
    DEFAULT_STEP_SIZE_VERT_LOCAL_RRT = 5
    DEFAULT_ITERATIONS_MAX_LOCAL = 3000  # unit: s

    INITIAL_PLANNER = 1

    def __init__(self, parent_class, auto_start=False):
        # self.__class__ = type(self.__class__.__name__, (base_class, object), dict(self.__class__.__dict__))
        # super(self.__class__, self).__init__()
        self.parent_class = parent_class

        StoppableThread.__init__(self)
        self.q = Queue()

        self.logger = logging.getLogger(__name__)
        if auto_start:
            self.start()

    def stop_thread(self):
        self.callback_close()
        self.stop()

    def callback_close(self):
        self.root.quit()
        self.logger.info(
            'Tkinter GUI has stopped but thread will first be joined upon closing of the program'
        )

    def on_main_thread(self, func):
        self.q.put(func)

    def check_queue(self):
        while True:
            try:
                task = self.q.get(block=False)
            except Empty:
                break
            else:
                self.root.after_idle(task)
        self.root.after(100, self.check_queue)

    def set_label_no_fly_zones(self, txt, color='black'):
        self.label_data_source_no_fly_zones_res.configure(text=txt)
        self.label_data_source_no_fly_zones_res.configure(fg=color)

    def set_label_height_map(self, txt, color='black'):
        self.label_data_source_height_map_res.configure(text=txt)
        self.label_data_source_height_map_res.configure(fg=color)

    def set_label_drone_id(self, txt, color='black'):
        self.label_data_source_droneID_res.configure(text=txt)
        self.label_data_source_droneID_res.configure(fg=color)

    def set_label_adsb(self, txt, color='black'):
        self.label_data_source_adsb_res.configure(text=txt)
        self.label_data_source_adsb_res.configure(fg=color)

    def set_label_weather(self, txt, color='black'):
        self.label_data_source_weather_res.configure(text=txt)
        self.label_data_source_weather_res.configure(fg=color)

    def set_label_rally_points(self, txt, color='black'):
        self.label_data_rally_point_res.configure(text=txt)
        self.label_data_rally_point_res.configure(fg=color)

    def set_global_plan_start_heuristic(self, val, color='black'):
        self.label_global_plan_start_heuristic_res.configure(text='%.02f' %
                                                             val)
        self.label_global_plan_start_heuristic_res.configure(fg=color)

    def set_global_plan_cur_heuristic(self, val, color='black'):
        self.label_global_plan_cur_heuristic_res.configure(text='%.02f' % val)
        self.label_global_plan_cur_heuristic_res.configure(fg=color)

    def set_global_plan_horz_step_size(self, val, color='black'):
        self.label_global_plan_horz_step_size_res.configure(text='%.01f [m]' %
                                                            val)
        self.label_global_plan_horz_step_size_res.configure(fg=color)

    def set_global_plan_vert_step_size(self, val, color='black'):
        self.label_global_plan_vert_step_size_res.configure(text='%.01f [m]' %
                                                            val)
        self.label_global_plan_vert_step_size_res.configure(fg=color)

    def set_global_plan_status(self, txt, color='black'):
        self.label_global_plan_status_res.configure(text=txt)
        self.label_global_plan_status_res.configure(fg=color)

    def set_global_plan_search_time(self, val, color='black'):
        self.label_global_plan_search_time_res.configure(text='%.01f [s]' %
                                                         val)
        self.label_global_plan_search_time_res.configure(fg=color)

    def set_global_plan_nodes_visited(self, val, color='black'):
        self.label_global_plan_nodes_visited_res.configure(text='%i' % val)
        self.label_global_plan_nodes_visited_res.configure(fg=color)

    def set_global_plan_nodes_explored(self, val, color='black'):
        self.label_global_plan_nodes_explored_res.configure(text='%i' % val)
        self.label_global_plan_nodes_explored_res.configure(fg=color)

    def set_label_gpe_fitness(self, val, color='black'):
        self.label_gpe_fitness_res.configure(text='%f' % val)
        self.label_gpe_fitness_res.configure(fg=color)

    def set_label_gpe_dist_tot(self, val, color='black'):
        self.label_gpe_dist_tot_res.configure(text='%.02f [m]' % val)
        self.label_gpe_dist_tot_res.configure(fg=color)

    def set_label_gpe_dist_horz(self, val, color='black'):
        self.label_gpe_dist_horz_res.configure(text='%.02f [m]' % val)
        self.label_gpe_dist_horz_res.configure(fg=color)

    def set_label_gpe_dist_vert(self, val, color='black'):
        self.label_gpe_dist_vert_res.configure(text='%.02f [m]' % val)
        self.label_gpe_dist_vert_res.configure(fg=color)

    def set_label_gpe_eta(self, val, color='black'):
        self.label_gpe_eta_res.configure(text='%.02f [s]' % val)
        self.label_gpe_eta_res.configure(fg=color)

    def set_label_gpe_wps(self, val, color='black'):
        self.label_gpe_wps_res.configure(text='%i' % val)
        self.label_gpe_wps_res.configure(fg=color)

    def set_label_gpe_runtime(self, val, color='black'):
        self.label_gpe_runtime_res.configure(text='%.02f [s]' % val)
        self.label_gpe_runtime_res.configure(fg=color)

    def set_label_gpe_bytes_tot(self, val, color='black'):
        self.label_gpe_bytes_tot_res.configure(text='%i' % val)
        self.label_gpe_bytes_tot_res.configure(fg=color)

    def set_label_gpe_objects_tot(self, val, color='black'):
        self.label_gpe_objects_tot_res.configure(text='%i' % val)
        self.label_gpe_objects_tot_res.configure(fg=color)

    def set_label_gpe_bytes_planner(self, val, color='black'):
        self.label_gpe_bytes_planner_res.configure(text='%i' % val)
        self.label_gpe_bytes_planner_res.configure(fg=color)

    def set_label_gpe_objects_planner(self, val, color='black'):
        self.label_gpe_objects_planner_res.configure(text='%i' % val)
        self.label_gpe_objects_planner_res.configure(fg=color)

    def set_scrolledtext_global_path(self, txt):
        self.scrolledtext_global_path.delete(1.0, END)
        self.scrolledtext_global_path.insert(INSERT, txt)

    def set_scrolledtext_local_path(self, txt):
        self.scrolledtext_local_path.delete(1.0, END)
        self.scrolledtext_local_path.insert(INSERT, txt)

    def enable_button_global_plan(self):
        self.button_global_plan.configure(state='normal')

    def diable_button_global_plan(self):
        self.button_global_plan.configure(state='disabled')

    def set_label_local_plan_status(self, txt, color='black'):
        self.label_local_plan_status_res.configure(text=txt)
        self.label_local_plan_status_res.configure(fg=color)

    def set_label_local_plan_time(self, val, color='black'):
        self.label_local_plan_time_res.configure(text='%.02f [s]' % val)
        self.label_local_plan_time_res.configure(fg=color)

    def set_label_local_uav_y(self, val, color='black'):
        self.label_local_uav_y_res.configure(text='%.01f [m]' % val)
        self.label_local_uav_y_res.configure(fg=color)

    def set_label_local_uav_x(self, val, color='black'):
        self.label_local_uav_x_res.configure(text='%.01f [m]' % val)
        self.label_local_uav_x_res.configure(fg=color)

    def set_label_local_uav_z_rel(self, val, color='black'):
        self.label_local_uav_z_rel_res.configure(text='%.01f [m]' % val)
        self.label_local_uav_z_rel_res.configure(fg=color)

    def set_label_local_uav_status(self, txt, color='black'):
        self.label_local_uav_status_res.configure(text=txt)
        self.label_local_uav_status_res.configure(fg=color)

    def global_planner_thread(self, point_start, point_goal, path_planner,
                              step_size_horz, step_size_vert, search_time_max):
        if self.parent_class.plan_path_global(
                point_start,
                point_goal,
                path_planner,
                step_size_horz=step_size_horz,
                step_size_vert=step_size_vert,
                search_time_max=search_time_max
        ):  # Plan path and test the result to update the GUI
            self.button_local_plan.configure(state='normal')
            self.button_global_plan.configure(state='normal')
            self.button_gen_global_sim_files.configure(state='normal')
            self.button_global_plan.configure(text='Start global planning')
            self.button_show_result_webpage_global.configure(state='normal')
            self.button_evaluate_path.configure(state='normal')
            self.button_web_visualize_global.configure(state='normal')
        else:  # The global path planner failed and therefore diable the local path planner and change the option to continue
            self.button_local_plan.configure(state='disabled')
            self.button_global_plan.configure(state='normal')
            self.button_gen_global_sim_files.configure(state='disabled')
            self.button_show_result_webpage_global.configure(state='disabled')
            path_planner = str(self.combo_planner_type.get())
            if path_planner == self.parent_class.PATH_PLANNER_NAMES[0]:
                self.button_global_plan.configure(
                    text='Continue global planning')
            elif path_planner == self.parent_class.PATH_PLANNER_NAMES[1]:
                self.button_global_plan.configure(text='Retry global planning')
            self.button_evaluate_path.configure(state='disabled')
            self.button_web_visualize_global.configure(state='disabled')

    def start_global_path_planning(self):
        self.button_global_plan.configure(state='disabled')
        self.button_gen_global_sim_files.configure(state='disabled')
        self.button_local_plan.configure(state='disabled')
        self.button_show_result_webpage_global.configure(state='disabled')
        self.button_evaluate_path.configure(state='disabled')
        self.button_web_visualize_global.configure(state='disabled')

        # Get data from the GUI
        path_planner = self.combo_planner_type.get()
        start_point_3dDICT = {
            'lat': float(self.input_start_point_lat.get()),
            'lon': float(self.input_start_point_lon.get()),
            'alt_rel': 0
        }
        goal_point_3dDICT = {
            'lat': float(self.input_goal_point_lat.get()),
            'lon': float(self.input_goal_point_lon.get()),
            'alt_rel': 0
        }
        step_size_horz = float(self.input_step_size_horz.get())
        step_size_vert = float(self.input_step_size_vert.get())
        search_time_max = float(self.input_search_time_max.get())

        # Create and start the thread
        thread_global_planning = threading.Thread(
            target=self.global_planner_thread,
            args=(start_point_3dDICT, goal_point_3dDICT, path_planner,
                  step_size_horz, step_size_vert, search_time_max))
        thread_global_planning.start()
        #thread_global_planning.join()

    def local_planner_thread(self, path_planner, step_size_horz,
                             step_size_vert, max_search_time, time_step,
                             acceleration_factor):
        self.parent_class.plan_path_local(
            path_planner=path_planner,
            step_size_horz=step_size_horz,
            step_size_vert=step_size_vert,
            max_search_time=max_search_time,
            time_step=time_step,
            acceleration_factor=acceleration_factor)
        self.button_global_plan.configure(state='normal')
        self.button_gen_global_sim_files.configure(state='normal')
        self.button_local_plan.configure(state='normal')
        self.button_web_visualize_local.configure(state='normal')
        self.button_show_result_webpage_local.configure(state='normal')
        self.button_gen_local_sim_files.configure(state='normal')

    def start_local_path_planning(self):
        self.button_global_plan.configure(state='disabled')
        self.button_gen_global_sim_files.configure(state='disabled')
        self.button_local_plan.configure(state='disabled')
        self.button_web_visualize_local.configure(state='disabled')
        self.button_show_result_webpage_local.configure(state='disabled')
        self.button_gen_local_sim_files.configure(state='disabled')
        # Get data from the GUI
        path_planner = str(self.combo_planner_type.get())
        time_step = float(self.input_time_step.get())
        acceleration_factor = float(self.input_acceleration_factor.get())
        step_size_horz = float(self.input_replan_step_size_horz.get())
        step_size_vert = float(self.input_replan_step_size_vert.get())
        search_time_max = float(self.input_replan_search_time_max.get())
        # Create and start the thread
        thread_local_planning = threading.Thread(
            target=self.local_planner_thread,
            args=(path_planner, step_size_horz, step_size_vert,
                  search_time_max, time_step, acceleration_factor))
        thread_local_planning.start()

    def show_result_webpage_global_thread(self):
        self.parent_class.draw_planned_path_global()
        self.parent_class.map_plotter_global.show_plot()

    def show_result_webpage_global(self):
        show_result_webpage_global = threading.Thread(
            target=self.show_result_webpage_global_thread)
        show_result_webpage_global.start()

    def gen_global_sim_files_thread(self):
        self.parent_class.generate_simulation_files_global()

    def gen_global_sim_files(self):
        gen_global_sim = threading.Thread(
            target=self.gen_global_sim_files_thread)
        gen_global_sim.start()

    def gen_local_sim_files_thread(self):
        self.parent_class.generate_simulation_files_local()

    def gen_local_sim_files(self):
        gen_local_sim = threading.Thread(
            target=self.gen_local_sim_files_thread)
        gen_local_sim.start()

    def show_result_webpage_local_thread(self):
        self.parent_class.draw_planned_path_local()
        self.parent_class.map_plotter_local.show_plot()

    def show_result_webpage_local(self):
        show_result_webpage_local = threading.Thread(
            target=self.show_result_webpage_local_thread)
        show_result_webpage_local.start()

    def show_web_visualize_global(self):
        route_id = self.parent_class.visualize_path_3d_global()
        if not None:
            url = 'http://uas.heltner.net/routes/' + str(route_id) + '/3d'
            webbrowser.open_new(url)

    def show_web_visualize_local(self):
        route_id = self.parent_class.visualize_path_3d_local()
        if not None:
            url = 'http://uas.heltner.net/routes/' + str(route_id) + '/3d'
            webbrowser.open_new(url)

    def path_evaluation_thread(self):
        self.parent_class.evaluate_path()

    def start_evaluation(self):
        # Create and start the thread
        thread_evaluate_path = threading.Thread(
            target=self.path_evaluation_thread)
        thread_evaluate_path.start()

    def change_planner(self, event=None):
        path_planner = str(self.combo_planner_type.get())
        if path_planner == self.parent_class.PATH_PLANNER_NAMES[0]:
            self.input_step_size_horz.delete(0, END)
            self.input_step_size_horz.insert(0,
                                             self.DEFAULT_STEP_SIZE_HORZ_ASTAR)
            self.input_step_size_vert.delete(0, END)
            self.input_step_size_vert.insert(0,
                                             self.DEFAULT_STEP_SIZE_VERT_ASTAR)
            self.label_search_time_max.configure(text='Max search time [s]:')
            self.input_search_time_max.delete(0, END)
            self.input_search_time_max.insert(0, self.DEFAULT_SEARCH_TIME_MAX)
            self.input_replan_step_size_horz.delete(0, END)
            self.input_replan_step_size_horz.insert(
                0, self.DEFAULT_STEP_SIZE_HORZ_LOCAL_ASTAR)
            self.input_replan_step_size_vert.delete(0, END)
            self.input_replan_step_size_vert.insert(
                0, self.DEFAULT_STEP_SIZE_VERT_LOCAL_ASTAR)
            self.label_replan_search_time_max.configure(
                text='Replan max search time [s]:')
            self.input_replan_search_time_max.delete(0, END)
            self.input_replan_search_time_max.insert(
                0, self.DEFAULT_SEARCH_TIME_MAX_LOCAL)
        elif path_planner == self.parent_class.PATH_PLANNER_NAMES[1]:
            self.input_step_size_horz.delete(0, END)
            self.input_step_size_horz.insert(0,
                                             self.DEFAULT_STEP_SIZE_HORZ_RRT)
            self.input_step_size_vert.delete(0, END)
            self.input_step_size_vert.insert(0,
                                             self.DEFAULT_STEP_SIZE_VERT_RRT)
            self.label_search_time_max.configure(text='Max iterations:')
            self.input_search_time_max.delete(0, END)
            self.input_search_time_max.insert(0, self.DEFAULT_ITERATIONS_MAX)
            self.input_replan_step_size_horz.delete(0, END)
            self.input_replan_step_size_horz.insert(
                0, self.DEFAULT_STEP_SIZE_HORZ_LOCAL_RRT)
            self.input_replan_step_size_vert.delete(0, END)
            self.input_replan_step_size_vert.insert(
                0, self.DEFAULT_STEP_SIZE_VERT_LOCAL_RRT)
            self.label_replan_search_time_max.configure(
                text='Replan max iterations:')
            self.input_replan_search_time_max.delete(0, END)
            self.input_replan_search_time_max.insert(
                0, self.DEFAULT_ITERATIONS_MAX_LOCAL)

    def run(self):
        self.root = Tk()
        self.root.protocol("WM_DELETE_WINDOW", self.callback_close)
        self.root.title("UAV Path Planner")
        #self.root.geometry('{}x{}'.format(460, 350))
        """ Left side layout """
        row_num_left = 0
        self.label_start_point = Label(self.root,
                                       text="Path Planning",
                                       font=("Arial Bold", 12))
        self.label_start_point.grid(row=row_num_left, column=0, columnspan=2)
        row_num_left += 1
        self.label_planner_type = Label(self.root, text="Type:")
        self.label_planner_type.grid(row=row_num_left, column=0)
        self.combo_planner_type = Combobox(self.root)
        self.combo_planner_type[
            'values'] = self.parent_class.PATH_PLANNER_NAMES
        if self.INITIAL_PLANNER == 0:
            self.combo_planner_type.current(0)
        elif self.INITIAL_PLANNER == 1:
            self.combo_planner_type.current(1)
        self.combo_planner_type.bind('<<ComboboxSelected>>',
                                     self.change_planner)
        self.combo_planner_type.grid(row=row_num_left, column=1)

        row_num_left += 1
        self.label_start_point = Label(self.root,
                                       text="Start point (geodetic)",
                                       font=("Arial Bold", 10))
        self.label_start_point.grid(row=row_num_left, column=0, columnspan=2)
        row_num_left += 1
        self.label_start_point_lat = Label(self.root, text="Latitude [dd]:")
        self.label_start_point_lat.grid(row=row_num_left, column=0)
        self.input_start_point_lat = Entry(self.root, width=10)
        self.input_start_point_lat.insert(0, self.DEFAULT_START_LAT)
        self.input_start_point_lat.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_start_point_lon = Label(self.root, text="Longitude [dd]:")
        self.label_start_point_lon.grid(row=row_num_left, column=0)
        self.input_start_point_lon = Entry(self.root, width=10)
        self.input_start_point_lon.insert(0, self.DEFAULT_START_LON)
        self.input_start_point_lon.grid(row=row_num_left, column=1)

        row_num_left += 1
        self.label_goal_point = Label(self.root,
                                      text="Goal point (geodetic)",
                                      font=("Arial Bold", 10))
        self.label_goal_point.grid(row=row_num_left, column=0, columnspan=2)
        row_num_left += 1
        self.label_goal_point_lat = Label(self.root, text="Latitude [dd]:")
        self.label_goal_point_lat.grid(row=row_num_left, column=0)
        self.input_goal_point_lat = Entry(self.root, width=10)
        self.input_goal_point_lat.insert(0, self.DEFAULT_GOAL_LAT)
        self.input_goal_point_lat.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_goal_point_lon = Label(self.root, text="Longitude [dd]:")
        self.label_goal_point_lon.grid(row=row_num_left, column=0)
        self.input_goal_point_lon = Entry(self.root, width=10)
        self.input_goal_point_lon.insert(0, self.DEFAULT_GOAL_LON)
        self.input_goal_point_lon.grid(row=row_num_left, column=1)

        row_num_left += 1
        self.label_options = Label(self.root,
                                   text="Options global path planner",
                                   font=("Arial Bold", 10))
        self.label_options.grid(row=row_num_left, column=0, columnspan=2)
        row_num_left += 1
        self.label_step_size_horz = Label(self.root,
                                          text="Horizontal step-size [m]:")
        self.label_step_size_horz.grid(row=row_num_left, column=0)
        self.input_step_size_horz = Entry(self.root, width=10)
        if self.INITIAL_PLANNER == 0:
            self.input_step_size_horz.insert(0,
                                             self.DEFAULT_STEP_SIZE_HORZ_ASTAR)
        elif self.INITIAL_PLANNER == 1:
            self.input_step_size_horz.insert(0,
                                             self.DEFAULT_STEP_SIZE_HORZ_RRT)
        self.input_step_size_horz.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_step_size_vert = Label(self.root,
                                          text="Vertical step-size [m]:")
        self.label_step_size_vert.grid(row=row_num_left, column=0)
        self.input_step_size_vert = Entry(self.root, width=10)
        if self.INITIAL_PLANNER == 0:
            self.input_step_size_vert.insert(0,
                                             self.DEFAULT_STEP_SIZE_VERT_ASTAR)
        elif self.INITIAL_PLANNER == 1:
            self.input_step_size_vert.insert(0,
                                             self.DEFAULT_STEP_SIZE_VERT_RRT)
        self.input_step_size_vert.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_search_time_max = Label(self.root, text="")
        if self.INITIAL_PLANNER == 0:
            self.label_search_time_max.configure(text='Max search time [s]:')
        elif self.INITIAL_PLANNER == 1:
            self.label_search_time_max.configure(text='Max iterations:')
        self.label_search_time_max.grid(row=row_num_left, column=0)
        self.input_search_time_max = Entry(self.root, width=10)
        if self.INITIAL_PLANNER == 0:
            self.input_search_time_max.insert(0, self.DEFAULT_SEARCH_TIME_MAX)
        elif self.INITIAL_PLANNER == 1:
            self.input_search_time_max.insert(0, self.DEFAULT_ITERATIONS_MAX)
        self.input_search_time_max.grid(row=row_num_left, column=1)

        row_num_left += 1
        self.button_global_plan = Button(
            self.root,
            text="Start global planning",
            command=self.start_global_path_planning)
        self.button_global_plan.configure(state='disabled')
        self.button_global_plan.grid(row=row_num_left, column=0, columnspan=2)

        row_num_left += 1
        self.label_options_local = Label(self.root,
                                         text="Options local path planner",
                                         font=("Arial Bold", 10))
        self.label_options_local.grid(row=row_num_left, column=0, columnspan=2)
        row_num_left += 1
        self.label_time_step = Label(self.root, text="Time step [s]:")
        self.label_time_step.grid(row=row_num_left, column=0)
        self.input_time_step = Entry(self.root, width=10)
        self.input_time_step.insert(0, self.DEFAULT_TIME_STEP)
        self.input_time_step.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_acceleration_factor = Label(self.root,
                                               text="Playback speed:")
        self.label_acceleration_factor.grid(row=row_num_left, column=0)
        self.input_acceleration_factor = Entry(self.root, width=10)
        self.input_acceleration_factor.insert(0,
                                              self.DEFAULT_ACCELERATION_FACTOR)
        self.input_acceleration_factor.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_replan_step_size_horz = Label(
            self.root, text="Replan horizontal step-size [m]:")
        self.label_replan_step_size_horz.grid(row=row_num_left, column=0)
        self.input_replan_step_size_horz = Entry(self.root, width=10)
        if self.INITIAL_PLANNER == 0:
            self.input_replan_step_size_horz.insert(
                0, self.DEFAULT_STEP_SIZE_HORZ_LOCAL_ASTAR)
        elif self.INITIAL_PLANNER == 1:
            self.input_replan_step_size_horz.insert(
                0, self.DEFAULT_STEP_SIZE_HORZ_LOCAL_RRT)
        self.input_replan_step_size_horz.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_replan_step_size_vert = Label(
            self.root, text="Replan vertical step-size [m]:")
        self.label_replan_step_size_vert.grid(row=row_num_left, column=0)
        self.input_replan_step_size_vert = Entry(self.root, width=10)
        if self.INITIAL_PLANNER == 0:
            self.input_replan_step_size_vert.insert(
                0, self.DEFAULT_STEP_SIZE_VERT_LOCAL_ASTAR)
        elif self.INITIAL_PLANNER == 1:
            self.input_replan_step_size_vert.insert(
                0, self.DEFAULT_STEP_SIZE_VERT_LOCAL_RRT)
        self.input_replan_step_size_vert.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_replan_search_time_max = Label(
            self.root, text="Replan max search time [s]:")
        if self.INITIAL_PLANNER == 0:
            self.label_replan_search_time_max.configure(
                text='Replan max search time [s]:')
        elif self.INITIAL_PLANNER == 1:
            self.label_replan_search_time_max.configure(
                text='Replan max iterations:')
        self.label_replan_search_time_max.grid(row=row_num_left, column=0)
        self.input_replan_search_time_max = Entry(self.root, width=10)
        if self.INITIAL_PLANNER == 0:
            self.input_replan_search_time_max.insert(
                0, self.DEFAULT_SEARCH_TIME_MAX_LOCAL)
        elif self.INITIAL_PLANNER == 1:
            self.input_replan_search_time_max.insert(
                0, self.DEFAULT_ITERATIONS_MAX_LOCAL)
        self.input_replan_search_time_max.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.button_local_plan = Button(self.root,
                                        text="Start local planning",
                                        command=self.start_local_path_planning)
        self.button_local_plan.configure(
            state='disabled'
        )  # disable the button since it cannot make a local plan before it has made a global plan
        self.button_local_plan.grid(row=row_num_left, column=0, columnspan=2)
        row_num_left += 1
        self.label_sim_info = Label(self.root,
                                    text="Simulation information",
                                    font=("Arial Bold", 12))
        self.label_sim_info.grid(row=row_num_left, column=0, columnspan=2)
        row_num_left += 1
        self.label_local_plan_status = Label(self.root, text="Status:")
        self.label_local_plan_status.grid(row=row_num_left, column=0)
        self.label_local_plan_status_res = Label(self.root, text="idle")
        self.label_local_plan_status_res.configure(fg='green')
        self.label_local_plan_status_res.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_local_plan_time = Label(self.root, text="Time:")
        self.label_local_plan_time.grid(row=row_num_left, column=0)
        self.label_local_plan_time_res = Label(self.root, text="N/A")
        self.label_local_plan_time_res.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_local_uav_y = Label(self.root, text="UAV y:")
        self.label_local_uav_y.grid(row=row_num_left, column=0)
        self.label_local_uav_y_res = Label(self.root, text="N/A")
        self.label_local_uav_y_res.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_local_uav_x = Label(self.root, text="UAV x:")
        self.label_local_uav_x.grid(row=row_num_left, column=0)
        self.label_local_uav_x_res = Label(self.root, text="N/A")
        self.label_local_uav_x_res.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_local_uav_z_rel = Label(self.root, text="UAV z_rel:")
        self.label_local_uav_z_rel.grid(row=row_num_left, column=0)
        self.label_local_uav_z_rel_res = Label(self.root, text="N/A")
        self.label_local_uav_z_rel_res.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_local_uav_status = Label(self.root, text="UAV status:")
        self.label_local_uav_status.grid(row=row_num_left, column=0)
        self.label_local_uav_status_res = Label(self.root, text="N/A")
        self.label_local_uav_status_res.grid(row=row_num_left, column=1)
        """ Right side layout """
        row_num_right = 0
        self.label_data_sources = Label(self.root,
                                        text="Data sources",
                                        font=("Arial Bold", 12))
        self.label_data_sources.grid(row=row_num_right, column=2, columnspan=2)
        row_num_right += 1
        self.label_data_source_no_fly_zones = Label(self.root,
                                                    text="No-fly zones:")
        self.label_data_source_no_fly_zones.grid(row=row_num_right, column=2)
        self.label_data_source_no_fly_zones_res = Label(self.root,
                                                        text="not loaded")
        self.label_data_source_no_fly_zones_res.configure(fg='red')
        self.label_data_source_no_fly_zones_res.grid(row=row_num_right,
                                                     column=3)
        row_num_right += 1
        self.label_data_source_height_map = Label(self.root,
                                                  text="Altitude map:")
        self.label_data_source_height_map.grid(row=row_num_right, column=2)
        self.label_data_source_height_map_res = Label(self.root,
                                                      text="not loaded")
        self.label_data_source_height_map_res.configure(fg='red')
        self.label_data_source_height_map_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_data_source_droneID = Label(self.root, text="DroneID:")
        self.label_data_source_droneID.grid(row=row_num_right, column=2)
        self.label_data_source_droneID_res = Label(self.root,
                                                   text="not loaded")
        self.label_data_source_droneID_res.configure(fg='red')
        self.label_data_source_droneID_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_data_source_adsb = Label(self.root, text="ADS-B:")
        self.label_data_source_adsb.grid(row=row_num_right, column=2)
        self.label_data_source_adsb_res = Label(self.root, text="not loaded")
        self.label_data_source_adsb_res.configure(fg='red')
        self.label_data_source_adsb_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_data_source_weather = Label(self.root, text="Weather:")
        self.label_data_source_weather.grid(row=row_num_right, column=2)
        self.label_data_source_weather_res = Label(self.root,
                                                   text="not loaded")
        self.label_data_source_weather_res.configure(fg='red')
        self.label_data_source_weather_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_data_rally_point = Label(self.root, text="Rally points:")
        self.label_data_rally_point.grid(row=row_num_right, column=2)
        self.label_data_rally_point_res = Label(self.root, text="not loaded")
        self.label_data_rally_point_res.configure(fg='red')
        self.label_data_rally_point_res.grid(row=row_num_right, column=3)

        row_num_right += 1
        # gpe = global path evaluator
        self.label_gpe = Label(self.root,
                               text="Global path evaluator",
                               font=("Arial Bold", 12))
        self.label_gpe.grid(row=row_num_right, column=2, columnspan=2)
        row_num_right += 1
        self.button_evaluate_path = Button(self.root,
                                           text="Evaluate",
                                           command=self.start_evaluation)
        self.button_evaluate_path.configure(
            state='disabled')  # Disabled because no global plan has been made
        self.button_evaluate_path.grid(row=row_num_right,
                                       column=2,
                                       columnspan=2)
        row_num_right += 1
        self.label_gpe_fitness = Label(self.root, text="Fitness:")
        self.label_gpe_fitness.grid(row=row_num_right, column=2)
        self.label_gpe_fitness_res = Label(self.root, text="N/A")
        self.label_gpe_fitness_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_gpe_dist_tot = Label(self.root, text="Total distance:")
        self.label_gpe_dist_tot.grid(row=row_num_right, column=2)
        self.label_gpe_dist_tot_res = Label(self.root, text="N/A")
        self.label_gpe_dist_tot_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_gpe_dist_horz = Label(self.root,
                                         text="Horizontal distance:")
        self.label_gpe_dist_horz.grid(row=row_num_right, column=2)
        self.label_gpe_dist_horz_res = Label(self.root, text="N/A")
        self.label_gpe_dist_horz_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_gpe_dist_vert = Label(self.root, text="Vertical distance:")
        self.label_gpe_dist_vert.grid(row=row_num_right, column=2)
        self.label_gpe_dist_vert_res = Label(self.root, text="N/A")
        self.label_gpe_dist_vert_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_gpe_eta = Label(self.root, text="Estimated flight time:")
        self.label_gpe_eta.grid(row=row_num_right, column=2)
        self.label_gpe_eta_res = Label(self.root, text="N/A")
        self.label_gpe_eta_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_gpe_wps = Label(self.root, text="Waypoints:")
        self.label_gpe_wps.grid(row=row_num_right, column=2)
        self.label_gpe_wps_res = Label(self.root, text="N/A")
        self.label_gpe_wps_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_gpe_runtime = Label(self.root, text="Runtime:")
        self.label_gpe_runtime.grid(row=row_num_right, column=2)
        self.label_gpe_runtime_res = Label(self.root, text="N/A")
        self.label_gpe_runtime_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_gpe_bytes_tot = Label(self.root, text="Bytes total:")
        self.label_gpe_bytes_tot.grid(row=row_num_right, column=2)
        self.label_gpe_bytes_tot_res = Label(self.root, text="N/A")
        self.label_gpe_bytes_tot_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_gpe_objects_tot = Label(self.root, text="Objects total:")
        self.label_gpe_objects_tot.grid(row=row_num_right, column=2)
        self.label_gpe_objects_tot_res = Label(self.root, text="N/A")
        self.label_gpe_objects_tot_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_gpe_bytes_planner = Label(self.root, text="Bytes planner:")
        self.label_gpe_bytes_planner.grid(row=row_num_right, column=2)
        self.label_gpe_bytes_planner_res = Label(self.root, text="N/A")
        self.label_gpe_bytes_planner_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_gpe_objects_planner = Label(self.root,
                                               text="Objects planner:")
        self.label_gpe_objects_planner.grid(row=row_num_right, column=2)
        self.label_gpe_objects_planner_res = Label(self.root, text="N/A")
        self.label_gpe_objects_planner_res.grid(row=row_num_right, column=3)

        row_num_right += 1
        self.label_planning_info = Label(self.root,
                                         text="Planning information",
                                         font=("Arial Bold", 12))
        self.label_planning_info.grid(row=row_num_right,
                                      column=2,
                                      columnspan=2)
        row_num_right += 1
        self.label_global_plan_status = Label(self.root, text="Status:")
        self.label_global_plan_status.grid(row=row_num_right, column=2)
        self.label_global_plan_status_res = Label(self.root, text="idle")
        self.label_global_plan_status_res.configure(fg='green')
        self.label_global_plan_status_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_global_plan_start_heuristic = Label(self.root,
                                                       text="Start heuristic:")
        self.label_global_plan_start_heuristic.grid(row=row_num_right,
                                                    column=2)
        self.label_global_plan_start_heuristic_res = Label(self.root,
                                                           text="N/A")
        self.label_global_plan_start_heuristic_res.grid(row=row_num_right,
                                                        column=3)
        row_num_right += 1
        self.label_global_plan_cur_heuristic = Label(self.root,
                                                     text="Best heuristic:")
        self.label_global_plan_cur_heuristic.grid(row=row_num_right, column=2)
        self.label_global_plan_cur_heuristic_res = Label(self.root, text="N/A")
        self.label_global_plan_cur_heuristic_res.grid(row=row_num_right,
                                                      column=3)
        row_num_right += 1
        self.label_global_plan_horz_step_size = Label(
            self.root, text="Horizontal step-size:")
        self.label_global_plan_horz_step_size.grid(row=row_num_right, column=2)
        self.label_global_plan_horz_step_size_res = Label(self.root,
                                                          text="N/A")
        self.label_global_plan_horz_step_size_res.grid(row=row_num_right,
                                                       column=3)
        row_num_right += 1
        self.label_global_plan_vert_step_size = Label(
            self.root, text="Vertical step-size:")
        self.label_global_plan_vert_step_size.grid(row=row_num_right, column=2)
        self.label_global_plan_vert_step_size_res = Label(self.root,
                                                          text="N/A")
        self.label_global_plan_vert_step_size_res.grid(row=row_num_right,
                                                       column=3)
        row_num_right += 1
        self.label_global_plan_search_time = Label(self.root,
                                                   text="Search time:")
        self.label_global_plan_search_time.grid(row=row_num_right, column=2)
        self.label_global_plan_search_time_res = Label(self.root, text="N/A")
        self.label_global_plan_search_time_res.grid(row=row_num_right,
                                                    column=3)
        row_num_right += 1
        self.label_global_plan_nodes_visited = Label(self.root,
                                                     text="Nodes visited:")
        self.label_global_plan_nodes_visited.grid(row=row_num_right, column=2)
        self.label_global_plan_nodes_visited_res = Label(self.root, text="N/A")
        self.label_global_plan_nodes_visited_res.grid(row=row_num_right,
                                                      column=3)
        row_num_right += 1
        self.label_global_plan_nodes_explored = Label(self.root,
                                                      text="Nodes explored:")
        self.label_global_plan_nodes_explored.grid(row=row_num_right, column=2)
        self.label_global_plan_nodes_explored_res = Label(self.root,
                                                          text="N/A")
        self.label_global_plan_nodes_explored_res.grid(row=row_num_right,
                                                       column=3)
        """ Both sides """
        if row_num_left > row_num_right:
            row_num_both = row_num_left
        else:
            row_num_both = row_num_right
        row_num_both += 1
        self.label_global_path = Label(self.root, text="Global path:")
        self.label_global_path.grid(row=row_num_both, column=0)
        self.scrolledtext_global_path = tkst.ScrolledText(self.root, height=5)
        self.scrolledtext_global_path.grid(row=row_num_both,
                                           column=1,
                                           columnspan=3)

        row_num_both += 1
        self.label_local_path = Label(self.root, text="Local path:")
        self.label_local_path.grid(row=row_num_both, column=0)
        self.scrolledtext_local_path = tkst.ScrolledText(self.root, height=5)
        self.scrolledtext_local_path.grid(row=row_num_both,
                                          column=1,
                                          columnspan=3)

        row_num_both += 1
        self.button_show_result_webpage_global = Button(
            self.root,
            text="2D global path visualization (local)",
            command=self.show_result_webpage_global)
        self.button_show_result_webpage_global.configure(
            state='disabled')  # Disabled because no global plan has been made
        self.button_show_result_webpage_global.grid(row=row_num_both,
                                                    column=0,
                                                    columnspan=2)
        #row_num_both += 1
        self.button_show_result_webpage_local = Button(
            self.root,
            text="2D local path visualization (local)",
            command=self.show_result_webpage_local)
        self.button_show_result_webpage_local.configure(
            state='disabled')  # Disabled because no global plan has been made
        self.button_show_result_webpage_local.grid(row=row_num_both,
                                                   column=2,
                                                   columnspan=2)

        row_num_both += 1
        self.button_web_visualize_global = Button(
            self.root,
            text="3D global path visualization (online)",
            command=self.show_web_visualize_global)
        self.button_web_visualize_global.configure(
            state='disabled')  # Disabled because no global plan has been made
        self.button_web_visualize_global.grid(row=row_num_both,
                                              column=0,
                                              columnspan=2)
        #row_num_both += 1
        self.button_web_visualize_local = Button(
            self.root,
            text="3D local path visualization (online)",
            command=self.show_web_visualize_local)
        self.button_web_visualize_local.configure(
            state='disabled')  # Disabled because no global plan has been made
        self.button_web_visualize_local.grid(row=row_num_both,
                                             column=2,
                                             columnspan=2)

        row_num_both += 1
        self.button_gen_global_sim_files = Button(
            self.root,
            text="Generate global path simulation files",
            command=self.gen_global_sim_files)
        self.button_gen_global_sim_files.configure(
            state='disabled')  # Disabled because no global plan has been made
        self.button_gen_global_sim_files.grid(row=row_num_both,
                                              column=0,
                                              columnspan=2)
        #row_num_both += 1
        self.button_gen_local_sim_files = Button(
            self.root,
            text="Generate local path simulation files",
            command=self.gen_local_sim_files)
        self.button_gen_local_sim_files.configure(
            state='disabled')  # Disabled because no global plan has been made
        self.button_gen_local_sim_files.grid(row=row_num_both,
                                             column=2,
                                             columnspan=2)

        row_num_both += 1
        self.label_credit = Label(
            self.root,
            text="Copyright (c) 2018, Tobias Lundby, BSD 3-Clause License",
            fg="grey",
            font=("Arial 8 italic"))
        self.label_credit.grid(row=row_num_both, column=0, columnspan=4)

        # Configure the queue callback
        self.root.after(250, self.check_queue)

        # Start the main loop
        self.root.mainloop()
Beispiel #33
0
class Application(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.root = master
        self.root.title('FPS(v1.0.0,qing.guo)')
        self.root.geometry('650x400')
        self.root.resizable(0, 0)  # 禁止调整窗口大小
        self.root.protocol("WM_DELETE_WINDOW", self.close)
        self.root.iconbitmap(get_path('fps.ico'))

    def creatWidgets(self):
        frame_left_top = Frame(self.root, width=410, height=220, bg='#C1CDCD')
        frame_left_center = Frame(self.root,
                                  width=410,
                                  height=80,
                                  bg='#C1CDCD')
        frame_left_bottom = Frame(self.root,
                                  width=410,
                                  height=100,
                                  bg='#C1CDCD')
        frame_right = Frame(self.root, width=240, height=400, bg='#C1CDCD')

        frame_left_top.grid_propagate(0)
        frame_left_center.grid_propagate(0)
        frame_left_bottom.grid_propagate(0)
        frame_right.propagate(0)
        frame_right.grid_propagate(0)

        frame_left_top.grid(row=0, column=0)
        frame_left_center.grid(row=1, column=0)
        frame_left_bottom.grid(row=2, column=0)
        frame_right.grid(row=0, column=1, rowspan=3)

        self.v1 = StringVar()
        self.v2 = StringVar()
        self.v3 = StringVar()
        self.v4 = StringVar()
        self.v5 = StringVar()
        self.v6 = StringVar()
        self.v7 = StringVar()
        self.v8 = StringVar()
        self.v4.set('0.2')

        type_list = [u'UI页面', u'视频/电影']
        swipe_list = [u'竖直方向', u'水平方向']
        swipe_config = [u'开启', u'关闭']
        swipe_speed = ['25ms', '50ms',  '75ms', '100ms', '150ms', '200ms', '300ms', '400ms',\
                       '500ms', '600ms', '700ms', '800ms']

        Label(frame_left_top, text=u"测试类型:", bg='#C1CDCD').grid(row=0,
                                                                column=0,
                                                                pady=20,
                                                                sticky=NW,
                                                                padx=5)
        self.cb1 = Combobox(frame_left_top,
                            width=11,
                            textvariable=self.v1,
                            values=type_list)
        self.cb1.grid(row=0, column=1, ipady=1, padx=5)
        # cb1.set(u'Activity页面')
        self.cb1.current(0)
        #Label
        Button(frame_left_top,
               text=u"获取设备id:",
               command=self.set_device,
               bg='#C1CDCD').grid(row=0, column=2, pady=20, padx=13)
        Entry(frame_left_top, width=15, textvariable=self.v2).grid(row=0,
                                                                   column=3,
                                                                   padx=5,
                                                                   ipady=1)

        Label(frame_left_top, text=u"滑动方向:", bg='#C1CDCD').grid(row=1,
                                                                column=0,
                                                                pady=20,
                                                                sticky=NW,
                                                                padx=5)
        self.cb2 = Combobox(frame_left_top,
                            width=11,
                            textvariable=self.v3,
                            values=swipe_list)
        self.cb2.grid(row=1, column=1, ipady=1, padx=5)
        self.cb2.current(0)
        Button(frame_left_top,
               text=u"设置滑动系数:",
               command=self.set_precent,
               bg='#C1CDCD').grid(row=1, column=2, pady=20, sticky=NW, padx=13)
        Entry(frame_left_top, width=15, textvariable=self.v4).grid(row=1,
                                                                   column=3,
                                                                   padx=5,
                                                                   ipady=1)

        Label(frame_left_top, text=u"滑动速度:", bg='#C1CDCD').grid(row=2,
                                                                column=0,
                                                                pady=20,
                                                                sticky=NW,
                                                                padx=5)
        self.cb3 = Combobox(frame_left_top,
                            width=11,
                            textvariable=self.v5,
                            values=swipe_speed)
        self.cb3.grid(row=2, column=1, padx=5, ipady=1)
        self.cb3.current(8)

        Button(frame_left_top,
               text=u"最大滑动次数:",
               command=self.set_max_steps,
               bg='#C1CDCD').grid(row=2, column=2, pady=20, sticky=NW, padx=13)
        Entry(frame_left_top, width=15, textvariable=self.v6).grid(row=2,
                                                                   column=3,
                                                                   padx=5,
                                                                   ipady=1)

        Label(frame_left_center, text=u"自动滑动", bg='#C1CDCD').grid(row=0,
                                                                  column=0,
                                                                  padx=5,
                                                                  sticky=NW,
                                                                  pady=15)
        self.cb4 = Combobox(frame_left_center,
                            width=6,
                            textvariable=self.v7,
                            values=swipe_config)
        self.cb4.grid(row=0, column=1, ipady=1, padx=5)
        self.cb4.current(0)

        self.b1 = Button(frame_left_center,
                         text=u"开始测试",
                         command=self.start_test,
                         bg='#C1CDCD')
        self.b1.grid(row=0, column=2, padx=30, pady=15)
        self.b2 = Button(frame_left_center,
                         text=u"结束测试",
                         command=self.end_test,
                         bg='#C1CDCD')
        self.b2.grid(row=0, column=3, padx=30, pady=15)
        Button(frame_left_bottom,
               text=u"测试结果",
               command=self.open_file,
               bg='#C1CDCD').grid(row=0, column=0, padx=13, pady=15)
        Entry(frame_left_bottom, width=49, textvariable=self.v8).grid(row=0,
                                                                      column=1,
                                                                      ipady=1,
                                                                      padx=10,
                                                                      pady=15)
        self.v8.set(MyThread.path)
        #Scrollbar
        scrollbar = Scrollbar(frame_right)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.text_msglist = Text(frame_right,
                                 yscrollcommand=scrollbar.set,
                                 bg='#C1CDCD')
        self.text_msglist.pack(side=RIGHT, fill=BOTH)

        scrollbar['command'] = self.text_msglist.yview

        self.text_msglist.tag_config('green', foreground='#008B00')
        self.text_msglist.tag_config('blue', foreground='#0000FF')
        self.text_msglist.tag_config('red', foreground='#FF3030')
        self.text_msglist.tag_config('purple', foreground='#CD00CD')

        self.cb1.bind('<<ComboboxSelected>>', self.cb1_select)
        self.cb2.bind('<<ComboboxSelected>>', self.cb2_select)
        text_message = u"测试前请打开需要测试的页面,测试过程中需保持在同一Activity界面中,切换到其他Activity则无数据输出\n\n"
        self.text_msglist.insert(END, text_message, 'green')

    def cb1_select(self, event):
        if self.v1.get() == u'视频/电影':
            self.cb4.current(1)
        else:
            self.cb4.current(0)

    def cb2_select(self, event):
        if self.v3.get() == u'水平方向':
            self.cb3.current(2)
        else:
            self.cb3.current(8)

    def start_test(self):

        MyThread.myThread1.set_flag('False')
        self.b1.config(state=DISABLED)
        self.b2.config(state=NORMAL)
        test_type = self.v1.get()
        device = self.v2.get()
        direction = self.v3.get()
        ratio = self.v4.get()
        speed = self.v5.get()
        max_steps = self.v6.get()
        auto = self.v7.get()

        if device == '' or device.isspace():
            self.text_msglist.insert(END, 'please input device id\n', 'red')
            self.b1.config(state=NORMAL)
            return -1
        elif auto == u'开启':
            try:
                ratio = float(ratio)
            except ValueError:
                self.text_msglist.insert(END, 'please input swipe precent\n',
                                         'red')
                self.b1.config(state=NORMAL)
                return -1
            if ratio < 0 or ratio >= 0.5:
                self.text_msglist.insert(END, 'precent range is [0,0.5)\n',
                                         'red')
                self.b1.config(state=NORMAL)
                return -1
            elif max_steps == '' or max_steps.isspace(
            ) or not max_steps.isdigit():
                self.text_msglist.insert(END, 'please input swipe precent\n',
                                         'red')
                self.b1.config(state=NORMAL)
                return -1
        if auto == u'关闭':
            ratio = 0
            max_steps = 0
        thread1 = MyThread.myThread1(1, device, direction, speed, ratio,
                                     max_steps, test_type, auto,
                                     self.text_msglist)
        thread1.setDaemon(True)
        thread1.start()

    def end_test(self):
        self.b1.config(state=NORMAL)
        MyThread.myThread1.set_flag('True')
        self.b2.config(state=DISABLED)

    def set_device(self):
        device_info = os.popen('adb devices').readlines()
        device = device_info[-2]
        device_id = device.split('\t')[0]
        self.v2.set(device_id)
        self.text_msglist.insert(END, u'请确认获取的设备id正确,默认获取最新连接的设备\n\n', 'green')
        self.text_msglist.see(END)

    def set_precent(self):
        self.text_msglist.insert(
            END, u'滑动系数n(0>=n<0.5,表示屏幕两端各减去n倍屏宽或长),剩下的区域即为实际滑动的区域。\n', 'green')
        self.text_msglist.insert(END, u'当UI布局为全屏时,可以设置0表示全屏滑动\n\n', 'green')
        self.text_msglist.see(END)

    def set_max_steps(self):
        self.text_msglist.insert(END, u'最大滑动次数max,表示滑动达到最大次数后,反向滑动,如此循环\n\n',
                                 'green')
        self.text_msglist.see(END)

    def open_file(self):
        filename = tkFileDialog.askopenfilename(initialdir=MyThread.path)
        if filename == '':
            return 0
        os.startfile(filename)

    def close(self):
        if MyThread.flag:
            print MyThread.flag
            result = tkMessageBox.askokcancel(title=u"退出", message=u"确定退出程序?")
        else:
            result = tkMessageBox.askokcancel(title=u"警告",
                                              message=u"测试还未完成,确定要退出程序?")
        if result:
            self.root.quit()
            self.root.destroy()
Beispiel #34
0
class Metadator(Tk):
    def __init__(self):
        u"""
        Main window constructor
        Creates 1 frame and 2 labeled subframes
        """
        # first: the log
        # see: http://sametmax.com/ecrire-des-logs-en-python/
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.DEBUG)  # all errors will be get
        log_form = logging.Formatter('%(asctime)s || %(levelname)s || %(message)s')
        logfile = RotatingFileHandler('Metadator_LOG.log', 'a', 5000000, 1)
        logfile.setLevel(logging.DEBUG)
        logfile.setFormatter(log_form)
        self.logger.addHandler(logfile)
        self.logger.info('\n\t ======== Metadator ========')  # first messages
        self.logger.info('Starting the UI')

        # checking the path to GDAL in the path
        if "GDAL_DATA" not in env.keys():
            try:
                gdal.SetConfigOption(str('GDAL_DATA'),
                                     str(path.abspath(r'data/gdal')))
            except:
                print("Oups! Something has gone wrong...\
                      see: https://github.com/Guts/Metadator/issues/21")
        else:
            pass

        # basics settings
        Tk.__init__(self)           # constructor of parent graphic class
        self.title(u'Metadator {0}'.format(MetadatorVersion))
        self.style = Style()        # more friendly windows style
        if opersys == 'win32':
            self.logger.info('Op. system: {0}'.format(platform.platform()))
            self.iconbitmap('Metadator.ico')    # windows icon
            self.uzer = env.get(u'USERNAME')
        elif opersys == 'linux2':
            self.logger.info('Op. system: {0}'.format(platform.platform()))
            self.uzer = env.get(u'USER')
            icon = Image("photo", file=r'data/img/metadator.gif')
            self.call('wm', 'iconphoto', self._w, icon)
            self.minsize(580, 100)
            self.style.theme_use('clam')
        elif opersys == 'darwin':
            self.logger.info('Op. system: {0}'.format(platform.platform()))
            self.uzer = env.get(u'USER')
        else:
            self.logger.warning('Operating system not tested')
            self.logger.info('Op. system: {0}'.format(platform.platform()))
        self.resizable(width=False, height=False)
        self.focus_force()

        self.logger.info('GDAL version: {}'.format(gdal.__version__))

        # variables
        self.def_rep = ""       # folder to search for
        self.def_lang = 'FR'    # language to start
        self.def_doc = IntVar()     # to export into Word
        self.def_xls = IntVar()     # to export into Excel 2003
        self.def_xml = IntVar()     # to export into ISO 19139
        self.def_cat = IntVar()     # to merge all output Word files
        self.def_odt = IntVar()     # to export into OpenDocumentText
        self.def_dict = IntVar()    # to make a dictionnary of data
        self.def_kass = IntVar()    # to handle field name case sensitive
        self.def_stat = IntVar()    # to active/disable stats fields
        self.li_pro = []            # list for profiles in language selected
        self.li_shp = []            # list for shapefiles path
        self.li_tab = []            # list for MapInfo tables path
        self.num_folders = 0        # number of folders explored
        self.today = strftime("%Y-%m-%d")   # date of the day
        self.dico_layer = OD()      # dictionary about layer properties
        self.dico_profil = OD()     # dictionary from profile selected
        self.dico_fields = OD()     # dictionary for fields information
        self.dico_rekur = OD()      # dictionary of recurring attributes
        self.dico_err = OD()     # errors list
        self.dico_help = OD()                # dictionary of help texts
        li_lang = [lg for lg in listdir(r'locale')]   # available languages
        self.blabla = OD()      # texts dictionary

        # GUI fonts
        ft_tit = tkFont.Font(family="Times", size=10, weight=tkFont.BOLD)

        # fillfulling
        self.load_settings()
        self.load_texts(self.def_lang)
        self.li_profiles(self.def_lang)
        self.li_rekurs(self.def_lang)
        self.recup_help(self.def_lang)

        # Tabs
        self.nb = Notebook(self)
        self.tab_globals = Frame(self.nb)   # tab_id = 0
        self.tab_options = Frame(self.nb)   # tab_id = 1
        self.tab_attribs = Frame(self.nb)   # tab_id = 2
        self.nb.add(self.tab_globals,
                    text=self.blabla.get('gui_tab1'), padding=3)
        self.nb.add(self.tab_options,
                    text=self.blabla.get('gui_tab2'), padding=3)
        self.nb.add(self.tab_attribs,
                    text=self.blabla.get('gui_tab3'), padding=3)
        self.logger.info('UI created')

                ### Tab 1: global
        # Frames
        self.FrPath = Labelframe(self.tab_globals,
                                 name='main',
                                 text=self.blabla.get('tab1_fr1'))
        self.FrProg = Labelframe(self.tab_globals,
                                 name='progression',
                                 text=self.blabla.get('tab1_frprog'))
            ## Frame 1
        # target folder
        self.labtarg = Label(self.FrPath, text=self.blabla.get('tab1_path'))
        self.target = Entry(self.FrPath, width=25)
        self.browsetarg = Button(self.FrPath,       # browse button
                                 text=self.blabla.get('tab1_browse'),
                                 command=lambda: self.setpathtarg(),
                                 takefocus=True)
        self.browsetarg.focus_force()               # force the focus on
        self.profil = Label(self.FrPath, text=self.blabla.get('tab1_prof'))
        # profiles switcher
        self.ddl_profil = Combobox(self.FrPath, values=self.li_pro, width=5)
        self.ddl_profil.current(0)
        self.ddl_profil.bind("<<ComboboxSelected>>", self.select_profil)
        # widgets placement
        self.labtarg.grid(row=1, column=1, columnspan=1,
                          sticky=N + S + W + E, padx=2, pady=8)
        self.target.grid(row=1, column=2, columnspan=1,
                         sticky=N + S + W + E, padx=2, pady=8)
        self.browsetarg.grid(row=1, column=3,
                             sticky=N + S + W + E, padx=2, pady=8)
        self.profil.grid(row=2, column=1,
                         sticky=N + S + W + E, padx=2, pady=8)
        self.ddl_profil.grid(row=2, column=2, sticky=W + E + N + S,
                             columnspan=2, padx=2, pady=8)

        # tooltips
        InfoBulle(self.target, message=self.dico_help.get(30)[1])
        InfoBulle(self.browsetarg, message=self.dico_help.get(30)[1])
        InfoBulle(self.ddl_profil, message=self.dico_help.get(31)[1])

            ## Frame 2
        # variables
        self.status = StringVar(self.FrProg, '')
        # widgets
        self.prog_layers = Progressbar(self.FrProg, orient="horizontal")
        self.prog_fields = Progressbar(self.FrProg, orient="horizontal")
        # widgets placement
        Label(self.FrProg, textvariable=self.status,
                           foreground='DodgerBlue').pack(expand=1)
        self.prog_layers.pack(expand=1, fill=X)

        # Frames placement
        self.FrPath.pack(expand=1, fill='both')
        self.FrProg.pack(expand=1, fill='both')

                ### Tab 2: options
        # Export options
        caz_doc = Checkbutton(self.tab_options,
                              text=u'HTML / Word (.doc/.docx)',
                              variable=self.def_doc,
                              command=lambda: self.catalog_dependance())
        caz_xls = Checkbutton(self.tab_options,
                              text=u'Excel 2003 (.xls)',
                              variable=self.def_xls)
        caz_xml = Checkbutton(self.tab_options,
                              text=u'XML (ISO 19139)',
                              variable=self.def_xml)
        self.caz_cat = Checkbutton(self.tab_options,
                                   text=self.blabla.get('tab2_merge'),
                                   variable=self.def_cat)
        caz_odt = Checkbutton(self.tab_options,
                              text=u'Open Document Text (.odt)',
                              variable=self.def_odt)
        # widgets placement
        caz_doc.grid(row=1,
                     column=0,
                     sticky=N + S + W + E,
                     padx=2, pady=2)
        self.caz_cat.grid(row=2,
                          column=0,
                          sticky=N + S + W + E,
                          padx=2, pady=2)
        caz_xls.grid(row=1,
                     column=1,
                     sticky=N + S + W + E,
                     padx=2, pady=2)
        caz_xml.grid(row=2,
                     column=1,
                     sticky=N + S + W + E,
                     padx=2, pady=2)
        caz_odt.grid(row=3,
                     column=1,
                     sticky=N + S + W + E,
                     padx=2, pady=2)
        # disabling the widgets which work only on Windows OS
        if opersys != 'win32':
            self.logger.info('Disabling Windows reserved functions.')
            self.def_doc.set(0)
            self.def_cat.set(0)
            caz_doc.configure(state='disabled')
            self.caz_cat.configure(state='disabled')
        else:
            pass
        # make the catalog option depending on the Word option
        self.catalog_dependance()

        # tooltips
        InfoBulle(caz_doc,
                  message=self.dico_help.get(33)[1],
                  image=self.dico_help.get(33)[2])
        InfoBulle(caz_xls,
                  message=self.dico_help.get(34)[1],
                  image=self.dico_help.get(34)[2])
        InfoBulle(caz_xml,
                  message=self.dico_help.get(35)[1],
                  image=self.dico_help.get(35)[2])
        InfoBulle(caz_odt,
                  message=self.dico_help.get(36)[1],
                  image=self.dico_help.get(36)[2])
        InfoBulle(self.caz_cat,
                  message=self.dico_help.get(37)[1],
                  image=self.dico_help.get(37)[2])

                ### Tab 3: recurring attributes
        # Attribute selector
        self.lab_chps = Label(self.tab_attribs, text=self.blabla.get('tab3_sele'))
        self.ddl_attr = Combobox(self.tab_attribs, values=self.dico_rekur.keys())
        self.ddl_attr.bind("<<ComboboxSelected>>", self.edit_rekur)
        self.supr = Button(self.tab_attribs, text=self.blabla.get('tab3_supp'),
                           command=self.del_rekur)
        # frame
        self.FrRekur = Labelframe(self.tab_attribs,
                                  name='attributes',
                                  text=self.blabla.get('tab3_tit'))
        # attribute settings
        self.tab3_LBnom = Label(self.FrRekur,
                                text=self.blabla.get('tab3_nom'),
                                state=DISABLED)
        self.tab3_ENnom = Entry(self.FrRekur, state=DISABLED)
        self.tab3_LBdesc = Label(self.FrRekur,
                                 text=self.blabla.get('tab3_desc'),
                                 state=DISABLED)
        self.tab3_TXdesc = Text(self.FrRekur,
                                height=5, width=30,
                                wrap=WORD, state=DISABLED)
        self.tab3_CBcass = Checkbutton(self.FrRekur,
                                       text=self.blabla.get('tab3_cass'),
                                       variable=self.def_kass,
                                       state=DISABLED)
        self.tab3_CBstat = Checkbutton(self.FrRekur,
                                       text=self.blabla.get('tab3_stat'),
                                       variable=self.def_stat,
                                       state=DISABLED)
        # Validation button
        self.save = Button(self.FrRekur,
                           text=self.blabla.get('tab3_save'),
                           command=self.save_rekur,
                           state='disabled')

        # widgets placement
        self.lab_chps.grid(row=1, column=1, sticky=N + S + W,
                           padx=2, pady=2)
        self.ddl_attr.grid(row=1, column=2, sticky=N + S + W + E,
                           padx=2, pady=2)
        self.supr.grid(row=1, column=3, sticky=N + S + W + E,
                       padx=2, pady=2)
        self.tab3_LBnom.grid(row=1, column=0, columnspan=1,
                             sticky=N + S + W, padx=2, pady=2)
        self.tab3_ENnom.grid(row=1, column=1, columnspan=1,
                             sticky=N + S + W + E, padx=2, pady=2)
        self.tab3_LBdesc.grid(row=2, column=0, columnspan=1,
                              sticky=N + S + W + E, padx=2, pady=2)
        self.tab3_TXdesc.grid(row=2, column=1, columnspan=2,
                              sticky=N + S + W + E, padx=2, pady=2)
        self.tab3_CBcass.grid(row=3, column=0, columnspan=1,
                              sticky=N + S + W + E, padx=2, pady=2)
        self.tab3_CBstat.grid(row=3, column=1, columnspan=1,
                              sticky=N + S + W + E, padx=2, pady=2)
        self.save.grid(row=5, column=0, columnspan=4,
                       sticky=N + S + W + E, padx=2, pady=2)

        # Frame placement
        self.FrRekur.grid(row=2, column=1, columnspan=3,
                          sticky=N + S + W + E, padx=2, pady=2)

        # tooltips
        InfoBulle(self.lab_chps, message=self.dico_help.get(38)[1])
        InfoBulle(self.ddl_attr, message=self.dico_help.get(39)[1])
        InfoBulle(self.supr, message=self.dico_help.get(40)[1])
        InfoBulle(self.tab3_CBcass, message=self.dico_help.get(41)[1])
        InfoBulle(self.tab3_CBstat, message=self.dico_help.get(42)[1])

            ## Main frame
        # Hola
        self.welcome = Label(self,
                             text=self.blabla.get('hi') + self.uzer,
                             font=ft_tit,
                             foreground="red2")
        # Image
        self.icone = PhotoImage(master=self, file=r'data/img/metadator.gif')
        Label(self, image=self.icone).grid(row=2,
                                           column=0,
                                           padx=2,
                                           pady=2,
                                           sticky=N + S + W + E)
        # credits
        s = Style(self)
        s.configure('Kim.TButton', foreground='DodgerBlue',
                    borderwidth=0, relief="flat")
        Button(self,
               text='by Julien M. (2015)',
               style='Kim.TButton',
               command=lambda: open_new('https://github.com/Guts')).grid(row=3,
                                                                         padx=2,
                                                                         pady=2,
                                                                         sticky=W+E)
        # language switcher
        self.ddl_lang = Combobox(self, values=li_lang, width=5)
        self.ddl_lang.current(li_lang.index(self.def_lang))
        self.ddl_lang.bind("<<ComboboxSelected>>", self.change_lang)
        # Go go go button
        self.val = Button(self,
                          text=self.blabla.get('tab1_go'),
                          state='active',
                          command=lambda: self.process())
        # Cancel button
        self.can = Button(self,
                          text=self.blabla.get('gui_quit'),
                          command=self.destroy)
        # widgets placement
        self.welcome.grid(row=0, column=0, columnspan=1, sticky=N + S + W + E,
                          padx=2, pady=2)
        self.ddl_lang.grid(row=1, column=0, sticky=N, padx=2, pady=0)
        self.can.grid(row=4, column=0, sticky=N + S + W + E, padx=2, pady=2)
        self.val.grid(row=4, column=1, sticky=N + S + W + E, padx=2, pady=2)

        # tooltips
        InfoBulle(self.ddl_lang, message=self.dico_help.get(32)[1])

                ### Notebook placement
        self.nb.grid(row=0, rowspan=4, column=1, sticky=N + S + W + E)
        # keep updated list of profiles
        self.maj()

    def maj(self):
        """
        update the profiles dropdown list every second
        """
        try:
            self.li_profiles(self.ddl_lang.get())
            self.ddl_profil['values'] = self.li_pro
            self.after(1000, self.maj)
        except WindowsError:    # avoid an error occuring with browse button
            self.after(1000, self.maj)
            pass

    def alter_state(self, parent, new_state):
        """
        just a function to change easily  the state of  all children widgets
        of a parent class

        parent=Tkinter class with children (Frame, Labelframe, Tk, etc.)
        new_state=Tkinter keyword for widget state (ACTIVE, NORMAL, DISABLED)
        """
        for child in parent.winfo_children():
            child.configure(state=new_state)
        # end of function
        return parent, new_state

    def catalog_dependance(self):
        """ unselect the catalog option if the word option is unselected """
        if self.def_doc.get() == 0:
            self.def_cat.set(0)
            self.caz_cat.config(state='disabled')
        elif self.def_doc.get() == 1:
            self.caz_cat.config(state='normal')
        # end of function
        return

    def load_settings(self):
        u""" load settings from last execution """
        confile = 'options.ini'
        config = ConfigParser.RawConfigParser()
        config.read(confile)
        # basics
        self.def_lang = config.get('basics', 'def_codelang')
        self.def_rep = config.get('basics', 'def_rep')
        # export preferences
        self.def_doc.set(config.get('export_preferences', 'def_word'))
        self.def_cat.set(config.get('export_preferences', 'def_cat'))
        self.def_xls.set(config.get('export_preferences', 'def_xls'))
        self.def_xml.set(config.get('export_preferences', 'def_xml'))
        self.def_dict.set(config.get('export_preferences', 'def_dict'))
        self.def_odt.set(config.get('export_preferences', 'def_odt'))
        # log
        self.logger.info('Last options loaded')
        # End of function
        return config, self.def_rep, self.def_lang, self.def_doc

    def save_settings(self):
        u""" save options in order to make the next execution easier """
        confile = 'options.ini'
        config = ConfigParser.RawConfigParser()
        # add sections
        config.add_section('basics')
        config.add_section('export_preferences')
        # basics
        config.set('basics', 'def_codelang', self.ddl_lang.get())
        config.set('basics', 'def_rep', self.target.get())
        # export preferences
        config.set('export_preferences', 'def_word', self.def_doc.get())
        config.set('export_preferences', 'def_cat', self.def_cat.get())
        config.set('export_preferences', 'def_xls', self.def_xls.get())
        config.set('export_preferences', 'def_xml', self.def_xml.get())
        config.set('export_preferences', 'def_dict', self.def_dict.get())
        config.set('export_preferences', 'def_odt', self.def_odt.get())
        # Writing the configuration file
        with open(confile, 'wb') as configfile:
            config.write(configfile)
        # End of function
        return config

    def change_lang(self, event):
        u""" update the texts dictionary with the language selected """
        new_lang = event.widget.get()
        # change to the new language selected
        self.load_texts(new_lang)
        self.li_profiles(new_lang)
        self.li_rekurs(new_lang)
        self.ddl_profil.delete(0, END)
        self.ddl_profil.config(values=self.li_pro)
        self.ddl_profil.update()
        self.ddl_attr.config(values=self.dico_rekur.keys())
        self.recup_help(new_lang)
        # update widgets text
          # tab1
        self.nb.tab(0, text=self.blabla.get('gui_tab1'))
        self.welcome.config(text=self.blabla.get('hi') + self.uzer)
        self.can.config(text=self.blabla.get('gui_quit'))
        self.FrPath.config(text=self.blabla.get('tab1_fr1'))
        self.FrProg.config(text=self.blabla.get('tab1_frprog'))
        self.labtarg.config(text=self.blabla.get('tab1_path'))
        self.browsetarg.config(text=self.blabla.get('tab1_browse'))
        self.val.config(text=self.blabla.get('tab1_go'))
        self.profil.config(text=self.blabla.get('tab1_prof'))
          # tab2
        self.nb.tab(1, text=self.blabla.get('gui_tab2'))
        self.caz_cat.config(text=self.blabla.get('tab2_merge'))
          # tab3
        self.nb.tab(2, text=self.blabla.get('gui_tab3'))
        self.lab_chps.config(text=self.blabla.get('tab3_sele'))
        self.supr.config(text=self.blabla.get('tab3_supp'))
        self.FrRekur.config(text=self.blabla.get('tab3_tit'))
        self.tab3_LBnom.config(text=self.blabla.get('tab3_nom'))
        self.tab3_LBdesc.config(text=self.blabla.get('tab3_desc'))
        self.tab3_CBcass.config(text=self.blabla.get('tab3_cass'))
        self.tab3_CBstat.config(text=self.blabla.get('tab3_stat'))
        self.save.config(text=self.blabla.get('tab3_save'))

        # End of function
        return self.blabla

    def load_texts(self, lang='FR'):
        u"""
        Load texts according to the selected language
        """
        # clearing the text dictionary
        self.blabla.clear()
        # open xml cursor
        xml = ET.parse('locale/{0}/lang_{0}.xml'.format(lang))
        # Looping and gathering texts from the xml file
        for elem in xml.getroot().getiterator():
            self.blabla[elem.tag] = elem.text
        # updating the GUI
        self.update()
        # en of function
        return self.blabla

    def setpathtarg(self):
        """ ...browse and insert the path of target folder """
        foldername = askdirectory(parent=self,
                                  initialdir=self.def_rep,
                                  mustexist=True,
                                  title=self.blabla.get('gui_cible'))
        # check if a folder has been choosen
        if foldername:
            try:
                self.target.delete(0, END)
                self.target.insert(0, foldername)
            except:
                info(title=self.blabla.get('nofolder'),
                     message=self.blabla.get('nofolder'))
                return

        # count shapefiles and MapInfo files in a separated thread
        proc = threading.Thread(target=self.li_geofiles,
                                args=(foldername, ))
        proc.daemon = True
        proc.start()

        # end of function
        return foldername

    def li_geofiles(self, foldertarget):
        u""" List shapefiles and MapInfo files (.tab, not .mid/mif) contained
        in the folders structure """
        # reseting global variables
        self.li_shp = []
        self.li_tab = []
        self.browsetarg.config(state=DISABLED)
        # Looping in folders structure
        self.status.set(self.blabla.get('tab1_prog1'))
        self.prog_layers.start()
        for root, dirs, files in walk(unicode(foldertarget)):
            self.num_folders = self.num_folders + len(dirs)
            for f in files:
                """ looking for files with geographic data """
                try:
                    unicode(path.join(root, f))
                    full_path = path.join(root, f)
                except UnicodeDecodeError:
                    full_path = path.join(root, f.decode('latin1'))
                # Looping on files contained
                if path.splitext(full_path.lower())[1].lower() == '.shp'\
                   and (path.isfile('{0}.dbf'.format(full_path[:-4]))
                        or path.isfile('{0}.DBF'.format(full_path[:-4])))\
                   and (path.isfile('{0}.shx'.format(full_path[:-4]))
                        or path.isfile('{0}.SHX'.format(full_path[:-4]))):
                    """ listing compatible shapefiles """
                    # add complete path of shapefile
                    self.li_shp.append(full_path)
                elif path.splitext(full_path.lower())[1] == '.tab'\
                    and (path.isfile(full_path[:-4] + '.dat')
                         or path.isfile(full_path[:-4] + '.DAT'))\
                    and (path.isfile(full_path[:-4] + '.map')
                         or path.isfile(full_path[:-4] + '.MAP'))\
                    and (path.isfile(full_path[:-4] + '.id')
                         or path.isfile(full_path[:-4] + '.ID')):
                    """ listing MapInfo tables """
                    # add complete path of MapInfo file
                    self.li_tab.append(full_path)
        # stopping the progress bar
        self.prog_layers.stop()
        # Lists ordering and tupling
        self.li_shp.sort()
        self.li_shp = tuple(self.li_shp)
        self.li_tab.sort()
        self.li_tab = tuple(self.li_tab)
        # setting the label text and activing the buttons
        self.status.set(unicode(len(self.li_shp)) + u' shapefiles - '
                        + unicode(len(self.li_tab)) + u' tables (MapInfo) - '
                        + unicode(self.num_folders) + self.blabla.get('log_numfold'))
        self.browsetarg.config(state=ACTIVE)
        self.val.config(state=ACTIVE)
        # End of function
        return foldertarget, self.li_shp, self.li_tab

    def li_profiles(self, lang):
        u"""
        list profiles already existing
        """
        # reseting global variable
        self.li_pro = []
        # Looping in folders structure
        folder_profiles = path.join('locale/', lang + '/profiles/')
        self.li_pro = [lg[:-4] for lg in listdir(folder_profiles)]
        self.li_pro.append(self.blabla.get('tab1_new'))
        # End of function
        return folder_profiles, self.li_pro

    def li_rekurs(self, lang):
        u"""
        List recurring attributes that already exist in the selected language
        """
        # clearing the text dictionary
        self.dico_rekur.clear()
        champis = path.abspath(r'locale/{0}/champignons_{0}.xml'.format(lang))
        xml = ET.parse(champis)
        # Looping and gathering texts from the xml file
        for elem in xml.findall('champ'):
            rek_name = elem.find('intitule').text
            rek_desc = elem.find('description').text
            rek_kass = elem.find('case').text
            rek_stat = elem.find('stats').text
            self.dico_rekur[rek_name] = rek_desc, rek_kass, rek_stat
        self.dico_rekur[self.blabla.get('tab3_new')] = '', 0, 0
        # updating the GUI
        self.update()
        # End of function
        return self.dico_rekur

    def edit_rekur(self, event):
        u"""
        preparing the form to edit a recurring attribute
        """
        rekur = event.widget.get()
        # deactivate the selector
        self.ddl_attr.config(state=DISABLED)
        # activate the form
        self.alter_state(self.FrRekur, NORMAL)
        # change to the new language selected
        self.tab3_ENnom.insert(0, rekur)
        self.tab3_TXdesc.insert(1.0, self.dico_rekur.get(rekur)[0])
        self.def_kass.set(self.dico_rekur.get(rekur)[1])
        self.def_stat.set(self.dico_rekur.get(rekur)[2])
        # End of function
        return self.dico_rekur

    def save_rekur(self):
        u""" save the recurring attribute edited """
        # check if the attribute already exists
        if self.tab3_ENnom.get() in self.dico_rekur:
            if not askyesno(title=self.blabla.get('tab3_alert_exist1'),
                            message=self.blabla.get('tab3_alert_exist2')):
                return
            else:
                pass
        else:
            pass

        # save
        self.dico_rekur[self.tab3_ENnom.get()] = self.tab3_TXdesc.get(1.0, END).rstrip(),\
                                                 self.def_kass.get(),\
                                                 self.def_stat.get()
        # reset the form
        self.tab3_ENnom.delete(0, END)
        self.tab3_TXdesc.delete(1.0, END)
        self.def_kass.set(0)
        self.def_stat.set(0)
        # deactivate the form
        self.alter_state(self.FrRekur, DISABLED)
        # updating the dropdown list
        self.ddl_attr.config(state=NORMAL)
        self.ddl_attr.delete(0, END)
        self.ddl_attr['values'] = self.dico_rekur.keys()

        # End of function
        return self.dico_rekur

    def del_rekur(self):
        u""" delete the selected recurring attribute """
        # reactivate the selector
        self.ddl_attr.config(state=ACTIVE)
        self.dico_rekur.pop(self.ddl_attr.get())

        self.ddl_attr.delete(0, END)
        self.ddl_attr['values'] = self.dico_rekur.keys()
        # reset the form
        self.tab3_ENnom.delete(0, END)
        self.tab3_TXdesc.delete(1.0, END)
        self.def_kass.set(0)
        self.def_stat.set(0)
        # deactivate the form
        self.alter_state(self.FrRekur, DISABLED)

        # End of function
        return self.dico_rekur

    def saveas_rekurs(self, lang):
        u""" save the recurring fields into the file dedicated """
        rekur = ET.Element(u'champs')
        xml_path = r'locale/{0}/champignons_{0}.xml'.format(lang)
        self.dico_rekur.pop(self.blabla.get('tab3_new'))
        with open(xml_path, 'w') as champis:
            for elem in self.dico_rekur.keys():
                rek = ET.SubElement(rekur, u'champ')
                # name of recurring attribute
                rek_name = ET.SubElement(rek, u'intitule')
                rek_name.text = elem
                # description of recurring attribute
                rek_desc = ET.SubElement(rek, u'description')
                rek_desc.text = self.dico_rekur.get(elem)[0]
                # stats option of recurring attribute
                rek_stats = ET.SubElement(rek, u'stats')
                rek_stats.text = unicode(self.dico_rekur.get(elem)[1])
                # case sensitive option of recurring attribute
                rek_case = ET.SubElement(rek, u'case')
                rek_case.text = unicode(self.dico_rekur.get(elem)[2])

        # creating the xml tree
        out_rekurs = ET.ElementTree(rekur)
        # saving it
        out_rekurs.write(xml_path,
                         encoding='utf-8',
                         xml_declaration='version="1.0"',
                         method='xml')

        # End of function
        return self.dico_rekur

    def select_profil(self, event):
        """ when a profile is selected... """
        profsel = event.widget.get()
        # if user wants to use an existing profile or create a new one
        if profsel == self.blabla.get('tab1_new'):
            self.val.config(text=self.blabla.get('tab1_crprofil'))
        else:
            self.val.config(text=self.blabla.get('tab1_go'))

        # end of function
        return self.val

    def recup_profil(self, lang):
        """ get the information from the profile selected """
        # clearing the profile dictionary
        self.dico_profil.clear()
        # specific path to profile file
        path_profile = path.join('locale/{0}/profiles/{1}.xml'.format(lang,
                                                                      self.ddl_profil.get()))
        with open(path_profile, 'r') as profile:
            # open xml parser
            xml = ET.parse(profile)
            # basic informations
            self.dico_profil['description'] = xml.find('description').text
            self.dico_profil['sources'] = xml.find('sources').text
            self.dico_profil['url'] = xml.find('url').text
            self.dico_profil['url_label'] = xml.find('url_label').text
            self.dico_profil[u'diffusion'] = xml.find('diffusion').text
            # data language
            lang_data = xml.find(u'lang_data')
            self.dico_profil[u"lang_data"] = lang_data.find(u'name').text
            # metadata language
            lang_metad = xml.find(u'lang_metad')
            self.dico_profil[u"lang_md"] = lang_metad.find(u'name').text
            # diffusion constraints
            diff = xml.find(u'diffusion')
            self.dico_profil['diffusion'] = diff.find(u'name').text
            # update rythm
            rythm = xml.find(u'rythm')
            self.dico_profil['rythm'] = rythm.find(u'name').text
            # INSPIRE themes
            themes = xml.find('themesinspire')
            li_themesinspire = [theme.find('name').text for theme in themes.findall('theme')]
            self.dico_profil['themesinspire'] = li_themesinspire
            # custom keywords
            keywords = xml.find('keywords')
            li_keywords = [keyword.find('name').text for keyword in keywords.findall('keyword')]
            self.dico_profil['keywords'] = li_keywords
            # places keywords
            geokeywords = xml.find('geokeywords')
            li_geokeywords = [geokeyword.find('name').text for geokeyword in geokeywords.findall('geokeyword')]
            self.dico_profil['geokeywords'] = li_geokeywords
            # contacts
            contacts = xml.find(u'contacts')
            # point of contact
            cont = contacts.find(u'pointdecontact')
            self.dico_profil[u'cont_name'] = cont.find(u'name').text
            self.dico_profil[u'cont_orga'] = cont.find(u'org').text
            self.dico_profil[u'cont_mail'] = cont.find(u'mail').text
            self.dico_profil[u'cont_role'] = cont.find(u'role').text
            self.dico_profil[u'cont_func'] = cont.find(u'func')[0].text
            self.dico_profil[u'cont_street'] = cont.find(u'street').text
            self.dico_profil[u'cont_city'] = cont.find(u'city').text
            self.dico_profil[u'cont_cp'] = cont.find(u'cp').text
            self.dico_profil[u'cont_country'] = cont.find(u'country').text
            self.dico_profil[u'cont_phone'] = cont.find(u'tel').text
            # second contact (responsable, etc.)
            resp = contacts.find(u'second_contact')
            self.dico_profil[u'resp_name'] = resp.find(u'name').text
            self.dico_profil[u'resp_orga'] = resp.find(u'org').text
            self.dico_profil[u'resp_mail'] = resp.find(u'mail').text
            self.dico_profil[u'resp_role'] = resp.find(u'role').text
            self.dico_profil[u'resp_func'] = resp.find(u'func')[0].text
            self.dico_profil[u'resp_street'] = resp.find(u'street').text
            self.dico_profil[u'resp_city'] = resp.find(u'city').text
            self.dico_profil[u'resp_cp'] = resp.find(u'cp').text
            self.dico_profil[u'resp_country'] = resp.find(u'country').text
            self.dico_profil[u'resp_phone'] = resp.find(u'tel').text
        # End of function
        return self.dico_profil

    def recup_help(self, lang):
        """ get the help texts """
        # specific path to xml file
        path_help = 'locale/%s/help_%s.xml' % (lang, lang)
        # reading and parsing the xml
        with open(path_help, 'r') as source:
            xml = ET.parse(source)                  # xml cursor
            for tooltip in xml.findall('tooltip'):
                idu = tooltip.find('id').text
                ref = tooltip.find('ref').text
                txt = tooltip.find('txt').text
                img = tooltip.find('image').text
                doc = tooltip.find('doc').text
                # fillfulling the INSPIRE dictionary
                self.dico_help[int(idu)] = ref, txt, img, doc
        # End of function
        return self.dico_help

    def process(self):
        u""" launch the different processes """
        # display the main tab
        self.nb.select(0)
        # check option selected: process or create a new profile
        if self.ddl_profil.get() == self.blabla.get('tab1_new'):
            # launching the profile form
            self.logger.info('Creation of a new profile')
            tr_profile = threading.Thread(target=NewProfile,
                                          args=(self.blabla,
                                                self.ddl_lang.get(),
                                                self.dico_help,
                                                self.li_pro))
            tr_profile.daemon = True
            tr_profile.run()
            # NewProfile(self.blabla, self.ddl_lang.get(), self.li_pro)
            self.li_profiles(self.ddl_lang.get())   # updating the dropdow list
            self.ddl_profil['values'] = self.li_pro
            return
        # check if the target folder has been selected
        if self.target.get() == "":
            info(title=self.blabla.get('info_blanktarget1'),
                 message=self.blabla.get('info_blanktarget2'))
            return
        # check if a profile has been selected
        if self.ddl_profil.get() == "":
            info(title=self.blabla.get('info_blankprofile1'),
                 message=self.blabla.get('info_blankprofile2'))
            return
        # disabling others GUI parts
        self.tab_globals.focus_force()
        self.alter_state(self.FrPath, DISABLED)

        # check if there are some layers into the folder structure
        if len(self.li_shp) + len(self.li_tab) == 0:
            self.logger.warning("No geofiles found in the folder structure")
            self.status.set(self.blabla.get('log_nodata'))
            return
        # specific variables
        dest = path.join(self.target.get(), 'metadator')
        if not path.isdir(dest):    # test if folder already exists
            mkdir(dest, 0777)       # if not, we create it
        # getting profile informations
        self.recup_profil(self.ddl_lang.get())
        # saving options in a separated thread
        tr_options = threading.Thread(target=self.save_settings)
        tr_options.daemon = True
        tr_options.start()
        self.logger.info('Current options saved')
        # saving recurring fiels in a separated thread
        tr_rekurs = threading.Thread(target=self.saveas_rekurs,
                                     args=(self.ddl_lang.get(), ))
        tr_rekurs.daemon = True
        tr_rekurs.start()
        # configuring the progression bar
        self.prog_layers["maximum"] = len(self.li_shp) + len(self.li_tab)
        self.prog_layers["value"]
        # Processing the shapefiles
        self.logger.info('\tStart processing the files')
        for shp in self.li_shp:
            """ looping on shapefiles list """
            self.logger.info('Processing: %s' % path.basename(shp))
            self.status.set(path.basename(shp))
            # reset recipient data
            self.dico_layer.clear()
            self.dico_fields.clear()
            # getting separated process threads
            Read_SHP(shp,
                     self.dico_layer,
                     self.dico_fields,
                     'shape',
                     self.blabla)
            # checking layer error
            if self.dico_layer.get('error'):
                # increment the progress bar
                self.prog_layers["value"] = self.prog_layers["value"] + 1
                self.update()
                self.logger.warning('This shape has an issue: %s' % shp)
                continue
            # getting fields statistics only if needed
            if self.def_doc.get() == 1 or self.def_xls.get() == 1 or self.def_odt.get() == 1:
                StatsFields(shp, self.dico_fields, self.dico_rekur, self.blabla)
            # export according to options selected
            if self.def_doc.get() == 1:
                ExportToHTML(dest,
                             self.dico_layer,
                             self.dico_fields,
                             self.dico_profil,
                             self.dico_rekur,
                             self.blabla)
                html_path = path.join(dest,
                                      "{0}_MD.html".format(self.dico_layer['name'][:-4]))
                ExportToDocX(html_path, dest)
            if self.def_xls.get() == 1:
                ExportToXLS(dest,
                            self.dico_layer,
                            self.dico_fields,
                            self.dico_profil,
                            self.dico_rekur,
                            self.blabla)
            if self.def_xml.get() == 1:
                ExportToXML(dest,
                            self.dico_layer,
                            self.dico_profil,
                            '',
                            self.blabla,
                            1,
                            0)
            if self.def_odt.get() == 1:
                ExportToODT(dest,
                            self.dico_layer,
                            self.dico_fields,
                            self.dico_profil,
                            self.dico_rekur,
                            self.blabla)
            # increment the progress bar
            self.prog_layers["value"] = self.prog_layers["value"] + 1
            self.update()

        # Processing the MapInfo tables
        for tab in self.li_tab:
            """ looping on MapInfo tables list """
            self.logger.info('Processing: %s' % path.basename(tab))
            self.status.set(path.basename(tab))
            # reset recipient data
            self.dico_layer.clear()
            self.dico_fields.clear()
            # getting the informations
            Read_TAB(tab,
                     self.dico_layer,
                     self.dico_fields,
                     'table',
                     self.blabla)
            # checking layer error
            if self.dico_layer.get('error'):
                self.logger.warning('This MapInfo table has an issue: %s' % tab)
                # increment the progress bar
                self.prog_layers["value"] = self.prog_layers["value"] +1
                self.update()
                continue
            # getting fields statistics only if needed
            if self.def_doc.get() == 1 \
               or self.def_xls.get() == 1 \
               or self.def_odt.get() == 1:
                StatsFields(tab, self.dico_fields, self.dico_rekur, self.blabla)
            # export according to options selected
            if self.def_doc.get() == 1:
                ExportToHTML(dest,
                             self.dico_layer,
                             self.dico_fields,
                             self.dico_profil,
                             self.dico_rekur,
                             self.blabla)
                html_path = path.join(dest,
                                      "{0}_MD.html".format(self.dico_layer['name'][:-4]))
                ExportToDocX(html_path, dest)
            if self.def_xls.get() == 1:
                ExportToXLS(dest,
                            self.dico_layer,
                            self.dico_fields,
                            self.dico_profil,
                            self.dico_rekur,
                            self.blabla)
            if self.def_xml.get() == 1:
                ExportToXML(dest,
                            self.dico_layer,
                            self.dico_profil,
                            '',
                            self.blabla,
                            1,
                            0)
            if self.def_odt.get() == 1:
                ExportToODT(dest,
                            self.dico_layer,
                            self.dico_fields,
                            self.dico_profil,
                            self.dico_rekur,
                            self.blabla)
            # increment the progress bar
            self.prog_layers["value"] = self.prog_layers["value"] + 1
            self.update()

        # Word catalog export
        if self.def_doc.get() == 1 and self.def_cat.get() == 1:
            self.status.set(self.blabla.get('info_cat'))
            self.update()
            DocxMerger(dest, '00_Metadator_Catalog', 'metadator_')
        else:
            pass

        # final message
        # msg = self.blabla.get('info_end2') + self.blabla.get('info_end3')
        # info(title=self.blabla.get('info_end'), message=msg)
        # opening the destination folder
        self.open_dir_file(dest)
        # cleaning up
        logging.info('Hurray! It worked! All seem to have been fine!')
        self.destroy()
        # end of function
        return

    def open_dir_file(self, target):
        """
        Open a file or a directory in the explorer of the operating system
        http://sametmax.com/ouvrir-un-fichier-avec-le-bon-programme-en-python
        """
        # check if the file or the directory exists
        if not path.exists(target):
            raise IOError('No such file: {0}'.format(target))

        # check the read permission
        if not access(target, R_OK):
            raise IOError('Cannot access file: {0}'.format(target))

        # open the directory or the file according to the os
        if opersys == 'win32':  # Windows
            proc = startfile(target)

        elif opersys.startswith('linux'):  # Linux:
            proc = subprocess.Popen(['xdg-open', target],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)

        elif opersys == 'darwin':  # Mac:
            proc = subprocess.Popen(['open', '--', target],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)

        else:
            raise NotImplementedError(
                "Your `%s` isn't a supported operating system`." % opersys)

        # end of function
        return proc
Beispiel #35
0
class MainFrame(Frame):
    def __init__(self, parent, stdoutq):
        Frame.__init__(self, parent)

        self.parent = parent
        self.width = 850
        self.height = 650
        self.title = menotexport.__version__
        self.stdoutq = stdoutq

        self.initUI()

        self.hasdb = False
        self.hasout = False
        self.hasaction = False
        self.exit = False

        self.path_frame = self.addPathFrame()
        self.action_frame = self.addActionFrame()
        self.message_frame = self.addMessageFrame()
        self.printStr()

        self.stateq = Queue.Queue()
        #self.workproc=Pool(1)

    def centerWindow(self):
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        x = (sw - self.width) / 2
        y = (sh - self.height) / 2
        self.parent.geometry('%dx%d+%d+%d' \
                %(self.width,self.height,x,y))

    def initUI(self):
        self.parent.title(self.title)
        self.style = Style()
        #Choose from default, clam, alt, classic
        self.style.theme_use('alt')
        self.pack(fill=tk.BOTH, expand=True)
        self.centerWindow()

    def printStr(self):
        while self.stdoutq.qsize() and self.exit == False:
            try:
                msg = self.stdoutq.get()
                self.text.update()
                self.text.insert(tk.END, msg)
                self.text.see(tk.END)
            except Queue.Empty:
                pass
        self.after(100, self.printStr)

    def checkReady(self):
        if self.isexport.get()==1 or self.ishighlight.get()==1\
                or self.isnote.get()==1 or self.isbib.get()==1:
            self.hasaction = True
        else:
            self.hasaction = False

        if self.hasdb and self.hasout and self.hasaction:
            self.start_button.configure(state=tk.NORMAL)
            print('# <Menotexport>: Menotexport Ready.')
        else:
            self.start_button.configure(state=tk.DISABLED)

    def addPathFrame(self):
        frame = Frame(self)
        frame.pack(fill=tk.X, expand=0, side=tk.TOP, padx=8, pady=5)

        frame.columnconfigure(1, weight=1)

        #------------------Database file------------------
        label=tk.Label(frame,text='Mendeley Data file:',\
                bg='#bbb')
        label.grid(row=0,column=0,\
                sticky=tk.W,padx=8)

        self.db_entry = tk.Entry(frame)
        self.db_entry.grid(row=0, column=1, sticky=tk.W + tk.E, padx=8)

        self.db_button = tk.Button(frame, text='Open', command=self.openFile)
        self.db_button.grid(row=0, column=2, padx=8, sticky=tk.E)

        hint = '''
Default location on Linux:
~/.local/share/data/Mendeley\ Ltd./Mendeley\ Desktop/[email protected]
Default location on Windows:
C:\Users\Your_name\AppData\Local\Mendeley Ltd\Mendeley Desktop\[email protected]'''

        hint_label=tk.Label(frame,text=hint,\
                justify=tk.LEFT,anchor=tk.NW)
        hint_label.grid(row=1,column=0,columnspan=3,\
                sticky=tk.W,padx=8)

        #--------------------Output dir--------------------
        label2=tk.Label(frame,text='Output folder:',\
                bg='#bbb')
        label2.grid(row=2,column=0,\
                sticky=tk.W,padx=8)

        self.out_entry = tk.Entry(frame)
        self.out_entry.grid(row=2, column=1, sticky=tk.W + tk.E, padx=8)
        self.out_button = tk.Button(frame, text='Choose', command=self.openDir)
        self.out_button.grid(row=2, column=2, padx=8, sticky=tk.E)

    def openDir(self):
        self.out_entry.delete(0, tk.END)
        dirname = askdirectory()
        self.out_entry.insert(tk.END, dirname)
        if len(dirname) > 0:
            print('# <Menotexport>: Output folder: %s' % dirname)
            self.hasout = True
            self.checkReady()

    def openFile(self):
        self.db_entry.delete(0, tk.END)
        ftypes = [('sqlite files', '*.sqlite'), ('ALL files', '*')]
        initialdir = '~/.local/share/data/Mendeley Ltd./Mendeley Desktop'
        initialdir = os.path.expanduser(initialdir)
        if os.path.isdir(initialdir):
            filename = askopenfilename(filetypes=ftypes, initialdir=initialdir)
        else:
            filename = askopenfilename(filetypes=ftypes)
        self.db_entry.insert(tk.END, filename)
        if len(filename) > 0:
            print('# <Menotexport>: Database file: %s' % filename)
            self.probeFolders()

    def probeFolders(self):
        dbfile = self.db_entry.get()
        try:
            db = sqlite3.connect(dbfile)
            self.menfolderlist = menotexport.getFolderList(db,
                                                           None)  #(id, name)
            self.foldernames = ['All'] + [ii[1] for ii in self.menfolderlist
                                          ]  #names to display
            self.foldersmenu['values'] = tuple(self.foldernames)
            self.foldersmenu.current(0)
            db.close()

            self.hasdb = True
            self.checkReady()

        except Exception as e:
            print(
                '# <Menotexport>: Failed to recoganize the given database file.'
            )
            print(e)

    def addActionFrame(self):

        frame = Frame(self, relief=tk.RAISED, borderwidth=1)
        frame.pack(fill=tk.X,side=tk.TOP,\
                expand=0,padx=8,pady=5)

        label = tk.Label(frame, text='Actions:', bg='#bbb')
        label.grid(row=0, column=0, sticky=tk.W, padx=8)

        #---------------Action checkbuttons---------------
        self.isexport = tk.IntVar()
        self.ishighlight = tk.IntVar()
        self.isnote = tk.IntVar()
        self.isbib = tk.IntVar()
        self.isris = tk.IntVar()
        self.isseparate = tk.IntVar()
        self.iszotero = tk.IntVar()
        self.iscustomtemp = tk.IntVar()

        self.check_export=tk.Checkbutton(frame,text='Export PDFs',\
                variable=self.isexport,command=self.doExport)

        self.check_highlight=tk.Checkbutton(frame,\
                text='Extract highlights',\
                variable=self.ishighlight,command=self.doHighlight)

        self.check_note=tk.Checkbutton(frame,\
                text='Extract notes',\
                variable=self.isnote,command=self.doNote)

        self.check_bib=tk.Checkbutton(frame,\
                text='Export .bib',\
                variable=self.isbib,command=self.doBib)

        self.check_ris=tk.Checkbutton(frame,\
                text='Export .ris',\
                variable=self.isris,command=self.doRis)

        self.check_separate=tk.Checkbutton(frame,\
                text='Save separately',\
                variable=self.isseparate,command=self.doSeparate,\
                state=tk.DISABLED)

        self.check_iszotero=tk.Checkbutton(frame,\
                text='For import to Zotero',\
                variable=self.iszotero,command=self.doIszotero,\
                state=tk.DISABLED)

        self.check_custom_template=tk.Checkbutton(frame,\
                text='Use custom template (experimental)',\
                variable=self.iscustomtemp,command=self.doCustomTemp,\
                state=tk.DISABLED)

        frame.columnconfigure(0, weight=1)

        self.check_export.grid(row=1, column=1, padx=8, sticky=tk.W)
        self.check_highlight.grid(row=1, column=2, padx=8, sticky=tk.W)
        self.check_note.grid(row=1, column=3, padx=8, sticky=tk.W)
        self.check_bib.grid(row=2, column=1, padx=8, sticky=tk.W)
        self.check_ris.grid(row=2, column=2, padx=8, sticky=tk.W)
        self.check_separate.grid(row=2, column=3, padx=8, sticky=tk.W)
        self.check_iszotero.grid(row=3, column=1, padx=8, sticky=tk.W)
        self.check_custom_template.grid(row=3, column=2, padx=8, sticky=tk.W)

        #---------------------2nd row---------------------
        subframe = Frame(frame)
        subframe.grid(row=4,column=0,columnspan=6,sticky=tk.W+tk.E,\
                pady=5)

        #-------------------Folder options-------------------
        folderlabel=tk.Label(subframe,text='Mendeley folder:',\
                bg='#bbb')
        folderlabel.pack(side=tk.LEFT, padx=8)

        self.menfolder = tk.StringVar()
        self.menfolderlist = [
            'All',
        ]
        self.foldersmenu=Combobox(subframe,textvariable=\
                self.menfolder,values=self.menfolderlist,state='readonly')
        self.foldersmenu.current(0)
        self.foldersmenu.bind('<<ComboboxSelected>>', self.setfolder)
        self.foldersmenu.pack(side=tk.LEFT, padx=8)

        #-------------------Quit button-------------------
        quit_button=tk.Button(subframe,text='Quit',\
                command=self.quit)
        quit_button.pack(side=tk.RIGHT, padx=8)

        #-------------------Stop button-------------------
        '''
        self.stop_button=tk.Button(subframe,text='Stop',\
                command=self.stop)
        self.stop_button.pack(side=tk.RIGHT,padx=8)
        '''

        #-------------------Start button-------------------
        self.start_button=tk.Button(subframe,text='Start',\
                command=self.start,state=tk.DISABLED)
        self.start_button.pack(side=tk.RIGHT, pady=8)

        #-------------------Help button-------------------
        self.help_button=tk.Button(subframe,text='Help',\
                command=self.showHelp)
        self.help_button.pack(side=tk.RIGHT, padx=8)

    def setfolder(self, x):
        self.foldersmenu.selection_clear()
        self.menfolder = self.foldersmenu.get()
        self.foldersmenu.set(self.menfolder)
        if self.menfolder == 'All':
            print('# <Menotexport>: Work on all folders.')
        else:
            print('# <Menotexport>: Select Mendeley folder: ' +
                  str(self.menfolder))

    def doExport(self):
        if self.isexport.get() == 1:
            print('# <Menotexport>: Export annotated PDFs.')
        else:
            print('# <Menotexport>: Dont export annotated PDFs.')

        self.checkReady()

    def doHighlight(self):
        if self.ishighlight.get() == 1:
            print('# <Menotexport>: Extract highlighted texts.')
            self.check_separate.configure(state=tk.NORMAL)
            self.check_custom_template.configure(state=tk.NORMAL)
        else:
            print('# <Menotexport>: Dont extract highlighted texts.')
            if self.isnote.get() == 0:
                self.check_separate.configure(state=tk.DISABLED)
                self.check_custom_template.configure(state=tk.DISABLED)
        self.checkReady()

    def doNote(self):
        if self.isnote.get() == 1:
            print('# <Menotexport>: Extract notes.')
            self.check_separate.configure(state=tk.NORMAL)
            self.check_custom_template.configure(state=tk.NORMAL)
        else:
            print('# <Menotexport>: Dont extract notes.')
            self.check_separate.state = tk.DISABLED
            if self.ishighlight.get() == 0:
                self.check_separate.configure(state=tk.DISABLED)
                self.check_custom_template.configure(state=tk.DISABLED)
        self.checkReady()
        self.checkReady()

    def doBib(self):
        if self.isbib.get() == 1:
            print('# <Menotexport>: Export to .bib file.')
            self.check_iszotero.configure(state=tk.NORMAL)
        else:
            print('# <Menotexport>: Dont export .bib file.')
            if self.isris.get() == 0:
                self.check_iszotero.configure(state=tk.DISABLED)
        self.checkReady()

    def doRis(self):
        if self.isris.get() == 1:
            print('# <Menotexport>: Export to .ris file.')
            self.check_iszotero.configure(state=tk.NORMAL)
        else:
            print('# <Menotexport>: Dont export .ris file.')
            if self.isbib.get() == 0:
                self.check_iszotero.configure(state=tk.DISABLED)
        self.checkReady()

    def doSeparate(self):
        if self.isseparate.get() == 1:
            print('# <Menotexport>: Save annotations separately.')
        else:
            print('# <Menotexport>: Save all annotations to single file.')

    def doIszotero(self):
        if self.iszotero.get() == 1:
            print(
                '# <Menotexport>: Save .bib/.ris file in Zotero preferred format.'
            )
        else:
            print('# <Menotexport>: Save .bib/.ris file to default format.')

    def doCustomTemp(self):
        if self.iscustomtemp.get() == 1:
            print(
                '# <Menotexport>: Use custom template for exported annotations.'
            )
        else:
            print(
                '# <Menotexport>: Use default template for exported annotations.'
            )

    def showHelp(self):
        helpstr = '''
%s\n\n
- Export PDFs: Bulk export PDFs.\n
- Extract highlights: Extract highlighted texts and output to txt files.\n
- Extract notes: Extract notes and output to txt files.\n
- Export .bib: Export meta-data and annotations to .bib files.\n
- Export .ris: Export meta-data and annotations to .ris files.\n
- For import to Zotero: Exported .bib and/or .ris files have suitable format to import to Zotero.\n
- Save separately: If on, save each PDF's annotations to a separate txt.\n
- Use custom annotation template: Use a custom template to format the exported annotations.
  See annotation_template.py for details.
- See README.md for more info.\n
''' % self.title

        tkMessageBox.showinfo(title='Help', message=helpstr)
        #print(self.menfolder.get())

    def start(self):
        dbfile = self.db_entry.get()
        outdir = self.out_entry.get()
        self.menfolder = self.foldersmenu.get()

        # get (folderid, folder) for folder
        for ii in self.menfolderlist:
            if ii[1] == self.menfolder:
                folder_sel = [ii[0], ii[1].split('/')[-1]]

        action = []
        if self.isexport.get() == 1:
            action.append('p')
        if self.ishighlight.get() == 1:
            action.append('m')
        if self.isnote.get() == 1:
            action.append('n')
        if self.isbib.get() == 1:
            action.append('b')
        if self.isris.get() == 1:
            action.append('r')
        if self.isseparate.get() == 1:
            separate = True
        else:
            separate = False
        if self.iszotero.get() == 1:
            iszotero = True
        else:
            iszotero = False
        if self.iscustomtemp.get() == 1:
            action.append('t')

        if 'p' in action or 'm' in action or 'n' in action or 'b' in action or 'r' in action:
            self.db_button.configure(state=tk.DISABLED)
            self.out_button.configure(state=tk.DISABLED)
            self.start_button.configure(state=tk.DISABLED)
            self.help_button.configure(state=tk.DISABLED)
            self.foldersmenu.configure(state=tk.DISABLED)
            self.check_export.configure(state=tk.DISABLED)
            self.check_highlight.configure(state=tk.DISABLED)
            self.check_note.configure(state=tk.DISABLED)
            self.check_bib.configure(state=tk.DISABLED)
            self.check_ris.configure(state=tk.DISABLED)
            self.check_separate.configure(state=tk.DISABLED)
            self.check_iszotero.configure(state=tk.DISABLED)
            self.check_custom_template.configure(state=tk.DISABLED)
            self.messagelabel.configure(text='Message (working...)')

            folder = None if self.menfolder == 'All' else folder_sel

            args = [dbfile, outdir, action, folder, separate, iszotero, True]

            self.workthread = WorkThread('work', False, self.stateq)
            self.workthread.deamon = True

            self.workthread.args = args
            self.workthread.start()
            self.reset()
            '''
            self.workproc.apply_async(menotexport.main,args,\
                    callback=self.reset)
            self.workproc.join()
            '''

    def reset(self):
        while self.stateq.qsize() and self.exit == False:
            try:
                msg = self.stateq.get()
                if msg == 'done':
                    self.db_button.configure(state=tk.NORMAL)
                    self.out_button.configure(state=tk.NORMAL)
                    self.start_button.configure(state=tk.NORMAL)
                    self.help_button.configure(state=tk.NORMAL)
                    self.foldersmenu.configure(state='readonly')
                    self.check_export.configure(state=tk.NORMAL)
                    self.check_highlight.configure(state=tk.NORMAL)
                    self.check_note.configure(state=tk.NORMAL)
                    self.check_bib.configure(state=tk.NORMAL)
                    self.check_separate.configure(state=tk.NORMAL)
                    self.check_iszotero.configure(state=tk.NORMAL)
                    self.check_custom_template.configure(state=tk.NORMAL)
                    self.messagelabel.configure(text='Message')
                    return
            except Queue.Empty:
                pass
        self.after(100, self.reset)

    def stop(self):
        #self.workthread.stop()
        pass

    def addMessageFrame(self):
        frame = Frame(self)
        frame.pack(fill=tk.BOTH,side=tk.TOP,\
                expand=1,padx=8,pady=5)

        self.messagelabel = tk.Label(frame, text='Message', bg='#bbb')
        self.messagelabel.pack(side=tk.TOP, fill=tk.X)

        self.text = tk.Text(frame)
        self.text.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        self.text.height = 10

        scrollbar = tk.Scrollbar(self.text)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

        self.text.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.text.yview)
Beispiel #36
0
mframe.grid(row=1,column=3)
spin = Checkbutton(root, text="Spinning Discs", command=None, variable=s)
spin.grid(row=2,column=3)
pink = Checkbutton(root, text="Display M (pink ball)", command=None, variable=p)
pink.grid(row=3,column=3)
vector = Checkbutton(root, text="Display center of mass vector", command=None, variable=v)
vector.grid(row=4,column=3)

na_cb = Checkbutton(root, text="No animation", command=None, variable=no_anim)
na_cb.grid(row=5,column=1)


mu_box = Combobox(root, state="readonly")
mu_box['values'] = tuple(str(i) for i in arange(0,5,0.1))
mu_box.grid(row=1, column=1)
mu_box.current(10)

wmu_box = Combobox(root, state="readonly")
wmu_box['values'] = tuple(str(i) for i in arange(0,5,0.1))
wmu_box.grid(row=2, column=1)
wmu_box.current(1)

amp_box = Combobox(root, state="readonly")
amp_box['values'] = tuple(str(i) for i in arange(0.25,5,0.25))
amp_box.grid(row=3, column=1)
amp_box.current(1)

N_box = Combobox(root, state="readonly")
N_box['values'] = tuple(str(i) for i in arange(1,60,1))
N_box.grid(row=4, column=1)
N_box.current(54)
Beispiel #37
0
settings_tab = ttk.Frame(tab_parent)
tab_parent.add(main_tab, text="Main")
tab_parent.add(settings_tab, text="Settings")
tab_parent.pack(expand=1, fill='both')

################################### Main Tab ######################################
frame_protocol = LabelFrame(main_tab, text="Trainer", relief=GROOVE)
label_subject = Label(frame_protocol, text="Subject Name: ")
entry_subject = Entry(frame_protocol)
entry_subject.insert(END, 'test')
protocol_type = ["Four Class Recorder", "Six Class Recorder", "Hand Recorder"]
label_protocol = Label(frame_protocol, text="Training Protocol: ")
combo_protocol = Combobox(frame_protocol,
                          values=protocol_type,
                          state='readlonly')
combo_protocol.current(0)
button_protocol = Button(frame_protocol,
                         text="Start Protocol",
                         command=run_protocol)

frame_protocol.grid(row=0, sticky='NSEW')
label_subject.grid(row=0, column=0, sticky='E')
entry_subject.grid(row=0, column=1, sticky='WE')
label_protocol.grid(row=1, column=0, sticky='E')
combo_protocol.grid(row=1, column=1, sticky='WE')
button_protocol.grid(row=2, column=1, sticky='WE')

frame_device = LabelFrame(main_tab, text="Device", relief=GROOVE)
device_type = ["Screen Output", "Device"]
label_deviceType = Label(frame_device, text="Device Type: ")
combo_deviceType = Combobox(frame_device,
Beispiel #38
0
class TimeEntryWidget(Frame):
    """Widget to handle starting and stopping the current time entry"""

    def __init__(self, parent, projects, onCreation=None):
        Frame.__init__(self, parent)

        self.onCreation = onCreation

        self.time = StringVar()
        self.time.set("00:00:00")
        self.timeEntry = None

        self.projects = projects.values()
        self.projects.sort(key=lambda x: x.name)

        l = Label(self, text="Description")
        l.grid(row=0, column=0)

        self.description = StringVar()
        e = Entry(self, textvariable=self.description, font=("Helvetica", 16))
        e.grid(row=1, column=0)

        l = Label(self, text="Project")
        l.grid(row=0, column=1)

        values = map(lambda x: x.name, self.projects)
        self.projectChooser = Combobox(self, values=values, font=("Helvetica", 16))
        self.projectChooser.grid(row=1, column=1)

        self.timeEntryClock = Label(self, textvariable=self.time, font=("Helvetica", 16))
        self.timeEntryClock.grid(row=1, column=2)

        self.submitText = StringVar()
        self.submitText.set("Start")
        self.submit = Button(self, textvariable=self.submitText, command=self.start, font=("Helvetica", 16))
        self.submit.grid(row=1, column=3, padx=10)

    def selectedProject(self):
        return self.projects[self.projectChooser.current()]

    def start(self):
        self.submitText.set("Stop")
        self.submit["command"] = self.stop
        project = self.selectedProject()
        self.timeEntry = project.startTimeEntry(self.description.get())
        self.onCreation(self.timeEntry)
        self._tick()

    def stop(self):
        self.submitText.set("Start")
        self.submit["command"] = self.start
        self.timeEntry.stop()
        self.timeEntry = None
        self.description.set("")

    def _tick(self):
        if self.timeEntry:
            duration = datetime.datetime.now() - self.timeEntry.data["start"]
            self.time.set(time.strftime("%H:%M:%S", time.gmtime(duration.seconds)))
            self.after(1000, self._tick)
        else:
            self.time.set("00:00:00")
Beispiel #39
0
class MainFrame(Frame):
    def __init__(self,parent,stdoutq):
        Frame.__init__(self,parent)

        self.parent=parent
        self.width=700
        self.height=400
        self.title='Menotexport v1.0'
        self.stdoutq=stdoutq

        self.initUI()

        self.hasdb=False
        self.hasout=False
        self.hasaction=False
        self.exit=False

        self.path_frame=self.addPathFrame()
        self.action_frame=self.addActionFrame()
        self.message_frame=self.addMessageFrame()
        self.printStr()

        self.stateq=Queue.Queue()
        #self.workproc=Pool(1)




    def centerWindow(self):
        sw=self.parent.winfo_screenwidth()
        sh=self.parent.winfo_screenheight()
        x=(sw-self.width)/2
        y=(sh-self.height)/2
        self.parent.geometry('%dx%d+%d+%d' \
                %(self.width,self.height,x,y))


    def initUI(self):
        self.parent.title(self.title)
        self.style=Style()
        #Choose from default, clam, alt, classic
        self.style.theme_use('alt')
        self.pack(fill=tk.BOTH,expand=True)
        self.centerWindow()


    def printStr(self):
        while self.stdoutq.qsize() and self.exit==False:
            try:
                msg=self.stdoutq.get()
                self.text.update()
                self.text.insert(tk.END,'# '+msg)
                self.text.see(tk.END)
            except Queue.Empty:
                pass
        self.after(100,self.printStr)


    def checkReady(self):
        if self.isexport.get()==1 or self.ishighlight.get()==1\
                or self.isnote.get()==1:
            self.hasaction=True
        else:
            self.hasaction=False

        if self.hasdb and self.hasout and self.hasaction:
            self.start_button.configure(state=tk.NORMAL)
            print('Menotexport Ready.')
        else:
            self.start_button.configure(state=tk.DISABLED)


    def addPathFrame(self):
        frame=Frame(self)
        frame.pack(fill=tk.X,expand=0,side=tk.TOP,padx=8,pady=5)

        frame.columnconfigure(1,weight=1)

        #------------------Database file------------------
        label=tk.Label(frame,text='Mendeley Data file:',\
                bg='#bbb')
        label.grid(row=0,column=0,\
                sticky=tk.W,padx=8)

        self.db_entry=tk.Entry(frame)
        self.db_entry.grid(row=0,column=1,sticky=tk.W+tk.E,padx=8)

        self.db_button=tk.Button(frame,text='Open',command=self.openFile)
        self.db_button.grid(row=0,column=2,padx=8,sticky=tk.E)

        hint='''
Default location on Linux:
~/.local/share/data/Mendeley\ Ltd./Mendeley\ Desktop/[email protected]
Default location on Windows:
C:\Users\Your_name\AppData\Local\Mendeley Ltd\Mendeley Desktop\[email protected]'''

        hint_label=tk.Label(frame,text=hint,\
                justify=tk.LEFT,anchor=tk.NW)
        hint_label.grid(row=1,column=0,columnspan=3,\
                sticky=tk.W,padx=8)

        #--------------------Output dir--------------------
        label2=tk.Label(frame,text='Output folder:',\
                bg='#bbb')
        label2.grid(row=2,column=0,\
                sticky=tk.W,padx=8)

        self.out_entry=tk.Entry(frame)
        self.out_entry.grid(row=2,column=1,sticky=tk.W+tk.E,padx=8)
        self.out_button=tk.Button(frame,text='Choose',command=self.openDir)
        self.out_button.grid(row=2,column=2,padx=8,sticky=tk.E)
        


    def openDir(self):
        self.out_entry.delete(0,tk.END)
        dirname=askdirectory()
        self.out_entry.insert(tk.END,dirname)
        if len(dirname)>0:
            print('Output folder: %s' %dirname)
            self.hasout=True
            self.checkReady()


    def openFile(self):
        self.db_entry.delete(0,tk.END)
        ftypes=[('sqlite files','*.sqlite'),('ALl files','*')]
        filename=askopenfilename(filetypes=ftypes)
        self.db_entry.insert(tk.END,filename)
        if len(filename)>0:
            print('Database file: %s' %filename)
            self.probeFolders()


    def probeFolders(self):
        dbfile=self.db_entry.get()
        try:
            db=sqlite3.connect(dbfile)
            query=\
            '''SELECT Documents.title,
                      DocumentFolders.folderid,
                      Folders.name
               FROM Documents
               LEFT JOIN DocumentFolders
                   ON Documents.id=DocumentFolders.documentId
               LEFT JOIN Folders
                   ON Folders.id=DocumentFolders.folderid
            '''
            ret=db.execute(query)
            data=ret.fetchall()
            df=pd.DataFrame(data=data,columns=['title',\
                    'folerid','name'])
            fetchField=lambda x, f: x[f].unique().tolist()
            folders=fetchField(df,'name')
            folders.sort()
            folders.remove(None)

            self.menfolderlist=['All',]+folders
            self.foldersmenu['values']=tuple(self.menfolderlist)
            self.foldersmenu.current(0)
            db.close()

            self.hasdb=True
            self.checkReady()

        except Exception as e:
            print('Failed to recoganize the given database file.') 
            print(e)





    
    def addActionFrame(self):

        frame=Frame(self,relief=tk.RAISED,borderwidth=1)
        frame.pack(fill=tk.X,side=tk.TOP,\
                expand=0,padx=8,pady=5)

        label=tk.Label(frame,text='Actions:',bg='#bbb')
        label.grid(row=0,column=0,sticky=tk.W,padx=8)

        #---------------Action checkbuttons---------------
        self.isexport=tk.IntVar()
        self.ishighlight=tk.IntVar()
        self.isnote=tk.IntVar()
        self.isseparate=tk.IntVar()

        self.check_export=tk.Checkbutton(frame,text='Export PDFs',\
                variable=self.isexport,command=self.doExport)

        self.check_highlight=tk.Checkbutton(frame,\
                text='Extract highlights',\
                variable=self.ishighlight,command=self.doHighlight)

        self.check_note=tk.Checkbutton(frame,\
                text='Extract notes',\
                variable=self.isnote,command=self.doNote)

        self.check_separate=tk.Checkbutton(frame,\
                text='Save separately',\
                variable=self.isseparate,command=self.doSeparate,\
                state=tk.DISABLED)

        frame.columnconfigure(0,weight=1)

        self.check_export.grid(row=0,column=1,padx=8,sticky=tk.W)
        self.check_highlight.grid(row=0,column=2,padx=8,sticky=tk.W)
        self.check_note.grid(row=0,column=3,padx=8,sticky=tk.W)
        self.check_separate.grid(row=0,column=4,padx=8,sticky=tk.W)

        #---------------------2nd row---------------------
        subframe=Frame(frame)
        subframe.grid(row=1,column=0,columnspan=5,sticky=tk.W+tk.E,\
                pady=5)

        #-------------------Folder options-------------------
        folderlabel=tk.Label(subframe,text='Mendeley folder:',\
                bg='#bbb')
        folderlabel.pack(side=tk.LEFT, padx=8)

        self.menfolder=tk.StringVar()
        self.menfolderlist=['All',]
        self.foldersmenu=Combobox(subframe,textvariable=\
                self.menfolder,values=self.menfolderlist,state='readonly')
        self.foldersmenu.current(0)
        self.foldersmenu.bind('<<ComboboxSelected>>',self.setfolder)
        self.foldersmenu.pack(side=tk.LEFT,padx=8)

        
        #-------------------Quit button-------------------
        quit_button=tk.Button(subframe,text='Quit',\
                command=self.quit)
        quit_button.pack(side=tk.RIGHT,padx=8)

        #-------------------Stop button-------------------
        '''
        self.stop_button=tk.Button(subframe,text='Stop',\
                command=self.stop)
        self.stop_button.pack(side=tk.RIGHT,padx=8)
        '''
                
        #-------------------Start button-------------------
        self.start_button=tk.Button(subframe,text='Start',\
                command=self.start,state=tk.DISABLED)
        self.start_button.pack(side=tk.RIGHT,pady=8)

        #-------------------Help button-------------------

        self.help_button=tk.Button(subframe,text='Help',\
                command=self.showHelp)
        self.help_button.pack(side=tk.RIGHT,padx=8)



    def setfolder(self,x):
        self.foldersmenu.selection_clear()
        self.menfolder=self.foldersmenu.get()
        self.foldersmenu.set(self.menfolder)
        if self.menfolder=='All':
            print('Work on all folders.')
        else:
            print('Select Mendeley folder: '+str(self.menfolder))



    def doExport(self):
        if self.isexport.get()==1:
            print('Export annotated PDFs.')
        else:
            print('Dont export annotated PDFs.')

        self.checkReady()



    def doHighlight(self):
        if self.ishighlight.get()==1:
            print('Extract highlighted texts.')
            self.check_separate.configure(state=tk.NORMAL)
        else:
            print('Dont extract highlighted texts.')
            if self.isnote.get()==0:
                self.check_separate.configure(state=tk.DISABLED)
        self.checkReady()

    def doNote(self):
        if self.isnote.get()==1:
            print('Extract notes.')
            self.check_separate.configure(state=tk.NORMAL)
        else:
            print('Dont extract notes.')
            self.check_separate.state=tk.DISABLED
            if self.ishighlight.get()==0:
                self.check_separate.configure(state=tk.DISABLED)
        self.checkReady()


    def doSeparate(self):
        if self.isseparate.get()==1:
            print('Save annotations separately.')
        else:
            print('Save all annotations to single file.')



    def showHelp(self):
        helpstr='''
Menotexport v1.0\n\n
- Export PDFs: Bulk export PDFs with annotations to <output folder>.\n
- Extract highlights: Extract highlighted texts and output to a txt file in <output folder>.\n
- Extract highlights: Extract notes and output to a txt file in <output folder>.\n
- Save separately: If on, save each PDF's annotations to a separate txt.\n
- See README.md for more info.\n
'''

        tkMessageBox.showinfo(title='Help', message=helpstr)
        print(self.menfolder.get())




    def start(self):
        dbfile=self.db_entry.get()
        outdir=self.out_entry.get()
        action=[]
        if self.isexport.get()==1:
            action.append('e')
        if self.ishighlight.get()==1:
            action.append('m')
        if self.isnote.get()==1:
            action.append('n')
        if self.isseparate.get()==1:
            separate=True
        else:
            separate=False
            
        if 'e' in action or 'm' in action or 'n' in action:
            self.db_button.configure(state=tk.DISABLED)
            self.out_button.configure(state=tk.DISABLED)
            self.start_button.configure(state=tk.DISABLED)
            self.help_button.configure(state=tk.DISABLED)
            self.foldersmenu.configure(state=tk.DISABLED)
            self.check_export.configure(state=tk.DISABLED)
            self.check_highlight.configure(state=tk.DISABLED)
            self.check_note.configure(state=tk.DISABLED)
            self.check_separate.configure(state=tk.DISABLED)
	    self.messagelabel.configure(text='Message (working...)')

            folder=None if self.menfolder=='All' else [self.menfolder,]

            args=[dbfile,outdir,action,folder,True,True,separate,True]

            self.workthread=WorkThread('work',False,self.stateq)
            self.workthread.deamon=True

            self.workthread.args=args
            self.workthread.start()
            self.reset()
            '''
            self.workproc.apply_async(menotexport.main,args,\
                    callback=self.reset)
            self.workproc.join()
            '''



    def reset(self):
        while self.stateq.qsize() and self.exit==False:
            try:
                msg=self.stateq.get()
                if msg=='done':
                    self.db_button.configure(state=tk.NORMAL)
                    self.out_button.configure(state=tk.NORMAL)
                    self.start_button.configure(state=tk.NORMAL)
                    self.help_button.configure(state=tk.NORMAL)
                    self.foldersmenu.configure(state='readonly')
                    self.check_export.configure(state=tk.NORMAL)
                    self.check_highlight.configure(state=tk.NORMAL)
                    self.check_note.configure(state=tk.NORMAL)
                    self.check_separate.configure(state=tk.NORMAL)
                    self.messagelabel.configure(text='Message')
                    return
            except Queue.Empty:
                pass
        self.after(100,self.reset)


    
    def stop(self):
        #self.workthread.stop()
        pass
        

    def addMessageFrame(self):
        frame=Frame(self)
        frame.pack(fill=tk.BOTH,side=tk.TOP,\
                expand=1,padx=8,pady=5)

        self.messagelabel=tk.Label(frame,text='Message',bg='#bbb')
        self.messagelabel.pack(side=tk.TOP,fill=tk.X)

        self.text=tk.Text(frame)
        self.text.pack(side=tk.TOP,fill=tk.BOTH,expand=1)
        self.text.height=10

        scrollbar=tk.Scrollbar(self.text)
        scrollbar.pack(side=tk.RIGHT,fill=tk.Y)

        self.text.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.text.yview)
Beispiel #40
0
class MainFrame(Frame):
    def __init__(self,parent,stdoutq):
        Frame.__init__(self,parent)

        self.parent=parent
        self.width=850
        self.height=650
        self.title=menotexport.__version__
        self.stdoutq=stdoutq

        self.initUI()

        self.hasdb=False
        self.hasout=False
        self.hasaction=False
        self.exit=False

        self.path_frame=self.addPathFrame()
        self.action_frame=self.addActionFrame()
        self.message_frame=self.addMessageFrame()
        self.printStr()

        self.stateq=Queue.Queue()
        #self.workproc=Pool(1)




    def centerWindow(self):
        sw=self.parent.winfo_screenwidth()
        sh=self.parent.winfo_screenheight()
        x=(sw-self.width)/2
        y=(sh-self.height)/2
        self.parent.geometry('%dx%d+%d+%d' \
                %(self.width,self.height,x,y))


    def initUI(self):
        self.parent.title(self.title)
        self.style=Style()
        #Choose from default, clam, alt, classic
        self.style.theme_use('alt')
        self.pack(fill=tk.BOTH,expand=True)
        self.centerWindow()


    def printStr(self):
        while self.stdoutq.qsize() and self.exit==False:
            try:
                msg=self.stdoutq.get()
                self.text.update()
                self.text.insert(tk.END,msg)
                self.text.see(tk.END)
            except Queue.Empty:
                pass
        self.after(100,self.printStr)


    def checkReady(self):
        if self.isexport.get()==1 or self.ishighlight.get()==1\
                or self.isnote.get()==1 or self.isbib.get()==1:
            self.hasaction=True
        else:
            self.hasaction=False

        if self.hasdb and self.hasout and self.hasaction:
            self.start_button.configure(state=tk.NORMAL)
            print('# <Menotexport>: Menotexport Ready.')
        else:
            self.start_button.configure(state=tk.DISABLED)


    def addPathFrame(self):
        frame=Frame(self)
        frame.pack(fill=tk.X,expand=0,side=tk.TOP,padx=8,pady=5)

        frame.columnconfigure(1,weight=1)

        #------------------Database file------------------
        label=tk.Label(frame,text='Mendeley Data file:',\
                bg='#bbb')
        label.grid(row=0,column=0,\
                sticky=tk.W,padx=8)

        self.db_entry=tk.Entry(frame)
        self.db_entry.grid(row=0,column=1,sticky=tk.W+tk.E,padx=8)

        self.db_button=tk.Button(frame,text='Open',command=self.openFile)
        self.db_button.grid(row=0,column=2,padx=8,sticky=tk.E)

        hint='''
Default location on Linux:
~/.local/share/data/Mendeley\ Ltd./Mendeley\ Desktop/[email protected]
Default location on Windows:
C:\Users\Your_name\AppData\Local\Mendeley Ltd\Mendeley Desktop\[email protected]'''

        hint_label=tk.Label(frame,text=hint,\
                justify=tk.LEFT,anchor=tk.NW)
        hint_label.grid(row=1,column=0,columnspan=3,\
                sticky=tk.W,padx=8)

        #--------------------Output dir--------------------
        label2=tk.Label(frame,text='Output folder:',\
                bg='#bbb')
        label2.grid(row=2,column=0,\
                sticky=tk.W,padx=8)

        self.out_entry=tk.Entry(frame)
        self.out_entry.grid(row=2,column=1,sticky=tk.W+tk.E,padx=8)
        self.out_button=tk.Button(frame,text='Choose',command=self.openDir)
        self.out_button.grid(row=2,column=2,padx=8,sticky=tk.E)
        


    def openDir(self):
        self.out_entry.delete(0,tk.END)
        dirname=askdirectory()
        self.out_entry.insert(tk.END,dirname)
        if len(dirname)>0:
            print('# <Menotexport>: Output folder: %s' %dirname)
            self.hasout=True
            self.checkReady()


    def openFile(self):
        self.db_entry.delete(0,tk.END)
        ftypes=[('sqlite files','*.sqlite'),('ALL files','*')]
        initialdir='~/.local/share/data/Mendeley Ltd./Mendeley Desktop'
        initialdir=os.path.expanduser(initialdir)
        if os.path.isdir(initialdir):
            filename=askopenfilename(filetypes=ftypes,initialdir=initialdir)
        else:
            filename=askopenfilename(filetypes=ftypes)
        self.db_entry.insert(tk.END,filename)
        if len(filename)>0:
            print('# <Menotexport>: Database file: %s' %filename)
            self.probeFolders()


    def probeFolders(self):
        dbfile=self.db_entry.get()
        try:
            db=sqlite3.connect(dbfile)
            self.menfolderlist=menotexport.getFolderList(db,None)   #(id, name)
            self.foldernames=['All']+[ii[1] for ii in self.menfolderlist] #names to display
            self.foldersmenu['values']=tuple(self.foldernames)
            self.foldersmenu.current(0)
            db.close()

            self.hasdb=True
            self.checkReady()

        except Exception as e:
            print('# <Menotexport>: Failed to recoganize the given database file.') 
            print(e)





    
    def addActionFrame(self):

        frame=Frame(self,relief=tk.RAISED,borderwidth=1)
        frame.pack(fill=tk.X,side=tk.TOP,\
                expand=0,padx=8,pady=5)

        label=tk.Label(frame,text='Actions:',bg='#bbb')
        label.grid(row=0,column=0,sticky=tk.W,padx=8)

        #---------------Action checkbuttons---------------
        self.isexport=tk.IntVar()
        self.ishighlight=tk.IntVar()
        self.isnote=tk.IntVar()
        self.isbib=tk.IntVar()
        self.isris=tk.IntVar()
        self.isseparate=tk.IntVar()
        self.iszotero=tk.IntVar()
        self.iscustomtemp=tk.IntVar()

        self.check_export=tk.Checkbutton(frame,text='Export PDFs',\
                variable=self.isexport,command=self.doExport)

        self.check_highlight=tk.Checkbutton(frame,\
                text='Extract highlights',\
                variable=self.ishighlight,command=self.doHighlight)

        self.check_note=tk.Checkbutton(frame,\
                text='Extract notes',\
                variable=self.isnote,command=self.doNote)

        self.check_bib=tk.Checkbutton(frame,\
                text='Export .bib',\
                variable=self.isbib,command=self.doBib)

        self.check_ris=tk.Checkbutton(frame,\
                text='Export .ris',\
                variable=self.isris,command=self.doRis)

        self.check_separate=tk.Checkbutton(frame,\
                text='Save separately',\
                variable=self.isseparate,command=self.doSeparate,\
                state=tk.DISABLED)

        self.check_iszotero=tk.Checkbutton(frame,\
                text='For import to Zotero',\
                variable=self.iszotero,command=self.doIszotero,\
                state=tk.DISABLED)

        self.check_custom_template=tk.Checkbutton(frame,\
                text='Use custom template (experimental)',\
                variable=self.iscustomtemp,command=self.doCustomTemp,\
                state=tk.DISABLED)

        frame.columnconfigure(0,weight=1)

        self.check_export.grid(row=1,column=1,padx=8,sticky=tk.W)
        self.check_highlight.grid(row=1,column=2,padx=8,sticky=tk.W)
        self.check_note.grid(row=1,column=3,padx=8,sticky=tk.W)
        self.check_bib.grid(row=2,column=1,padx=8,sticky=tk.W)
        self.check_ris.grid(row=2,column=2,padx=8,sticky=tk.W)
        self.check_separate.grid(row=2,column=3,padx=8,sticky=tk.W)
        self.check_iszotero.grid(row=3,column=1,padx=8,sticky=tk.W)
        self.check_custom_template.grid(row=3,column=2,padx=8,sticky=tk.W)

        #---------------------2nd row---------------------
        subframe=Frame(frame)
        subframe.grid(row=4,column=0,columnspan=6,sticky=tk.W+tk.E,\
                pady=5)

        #-------------------Folder options-------------------
        folderlabel=tk.Label(subframe,text='Mendeley folder:',\
                bg='#bbb')
        folderlabel.pack(side=tk.LEFT, padx=8)

        self.menfolder=tk.StringVar()
        self.menfolderlist=['All',]
        self.foldersmenu=Combobox(subframe,textvariable=\
                self.menfolder,values=self.menfolderlist,state='readonly')
        self.foldersmenu.current(0)
        self.foldersmenu.bind('<<ComboboxSelected>>',self.setfolder)
        self.foldersmenu.pack(side=tk.LEFT,padx=8)
        
        #-------------------Quit button-------------------
        quit_button=tk.Button(subframe,text='Quit',\
                command=self.quit)
        quit_button.pack(side=tk.RIGHT,padx=8)

        #-------------------Stop button-------------------
        '''
        self.stop_button=tk.Button(subframe,text='Stop',\
                command=self.stop)
        self.stop_button.pack(side=tk.RIGHT,padx=8)
        '''
                
        #-------------------Start button-------------------
        self.start_button=tk.Button(subframe,text='Start',\
                command=self.start,state=tk.DISABLED)
        self.start_button.pack(side=tk.RIGHT,pady=8)

        #-------------------Help button-------------------
        self.help_button=tk.Button(subframe,text='Help',\
                command=self.showHelp)
        self.help_button.pack(side=tk.RIGHT,padx=8)



    def setfolder(self,x):
        self.foldersmenu.selection_clear()
        self.menfolder=self.foldersmenu.get()
        self.foldersmenu.set(self.menfolder)
        if self.menfolder=='All':
            print('# <Menotexport>: Work on all folders.')
        else:
            print('# <Menotexport>: Select Mendeley folder: '+str(self.menfolder))



    def doExport(self):
        if self.isexport.get()==1:
            print('# <Menotexport>: Export annotated PDFs.')
        else:
            print('# <Menotexport>: Dont export annotated PDFs.')

        self.checkReady()



    def doHighlight(self):
        if self.ishighlight.get()==1:
            print('# <Menotexport>: Extract highlighted texts.')
            self.check_separate.configure(state=tk.NORMAL)
            self.check_custom_template.configure(state=tk.NORMAL)
        else:
            print('# <Menotexport>: Dont extract highlighted texts.')
            if self.isnote.get()==0:
                self.check_separate.configure(state=tk.DISABLED)
                self.check_custom_template.configure(state=tk.DISABLED)
        self.checkReady()

    def doNote(self):
        if self.isnote.get()==1:
            print('# <Menotexport>: Extract notes.')
            self.check_separate.configure(state=tk.NORMAL)
            self.check_custom_template.configure(state=tk.NORMAL)
        else:
            print('# <Menotexport>: Dont extract notes.')
            self.check_separate.state=tk.DISABLED
            if self.ishighlight.get()==0:
                self.check_separate.configure(state=tk.DISABLED)
                self.check_custom_template.configure(state=tk.DISABLED)
        self.checkReady()
        self.checkReady()

    def doBib(self):
        if self.isbib.get()==1:
            print('# <Menotexport>: Export to .bib file.')
            self.check_iszotero.configure(state=tk.NORMAL)
        else:
            print('# <Menotexport>: Dont export .bib file.')
            if self.isris.get()==0:
                self.check_iszotero.configure(state=tk.DISABLED)
        self.checkReady()

    def doRis(self):
        if self.isris.get()==1:
            print('# <Menotexport>: Export to .ris file.')
            self.check_iszotero.configure(state=tk.NORMAL)
        else:
            print('# <Menotexport>: Dont export .ris file.')
            if self.isbib.get()==0:
                self.check_iszotero.configure(state=tk.DISABLED)
        self.checkReady()

    def doSeparate(self):
        if self.isseparate.get()==1:
            print('# <Menotexport>: Save annotations separately.')
        else:
            print('# <Menotexport>: Save all annotations to single file.')

    def doIszotero(self):
        if self.iszotero.get()==1:
            print('# <Menotexport>: Save .bib/.ris file in Zotero preferred format.')
        else:
            print('# <Menotexport>: Save .bib/.ris file to default format.')

    def doCustomTemp(self):
        if self.iscustomtemp.get()==1:
            print('# <Menotexport>: Use custom template for exported annotations.')
        else:
            print('# <Menotexport>: Use default template for exported annotations.')



    def showHelp(self):
        helpstr='''
%s\n\n
- Export PDFs: Bulk export PDFs.\n
- Extract highlights: Extract highlighted texts and output to txt files.\n
- Extract notes: Extract notes and output to txt files.\n
- Export .bib: Export meta-data and annotations to .bib files.\n
- Export .ris: Export meta-data and annotations to .ris files.\n
- For import to Zotero: Exported .bib and/or .ris files have suitable format to import to Zotero.\n
- Save separately: If on, save each PDF's annotations to a separate txt.\n
- Use custom annotation template: Use a custom template to format the exported annotations.
  See annotation_template.py for details.
- See README.md for more info.\n
''' %self.title

        tkMessageBox.showinfo(title='Help', message=helpstr)
        #print(self.menfolder.get())




    def start(self):
        dbfile=self.db_entry.get()
        outdir=self.out_entry.get()
        self.menfolder=self.foldersmenu.get()

        # get (folderid, folder) for folder
        for ii in self.menfolderlist:
            if ii[1]==self.menfolder:
                folder_sel=[ii[0],ii[1].split('/')[-1]]

        action=[]
        if self.isexport.get()==1:
            action.append('p')
        if self.ishighlight.get()==1:
            action.append('m')
        if self.isnote.get()==1:
            action.append('n')
        if self.isbib.get()==1:
            action.append('b')
        if self.isris.get()==1:
            action.append('r')
        if self.isseparate.get()==1:
            separate=True
        else:
            separate=False
        if self.iszotero.get()==1:
            iszotero=True
        else:
            iszotero=False
        if self.iscustomtemp.get()==1:
            action.append('t')

            
        if 'p' in action or 'm' in action or 'n' in action or 'b' in action or 'r' in action:
            self.db_button.configure(state=tk.DISABLED)
            self.out_button.configure(state=tk.DISABLED)
            self.start_button.configure(state=tk.DISABLED)
            self.help_button.configure(state=tk.DISABLED)
            self.foldersmenu.configure(state=tk.DISABLED)
            self.check_export.configure(state=tk.DISABLED)
            self.check_highlight.configure(state=tk.DISABLED)
            self.check_note.configure(state=tk.DISABLED)
            self.check_bib.configure(state=tk.DISABLED)
            self.check_ris.configure(state=tk.DISABLED)
            self.check_separate.configure(state=tk.DISABLED)
            self.check_iszotero.configure(state=tk.DISABLED)
            self.check_custom_template.configure(state=tk.DISABLED)
            self.messagelabel.configure(text='Message (working...)')

            folder=None if self.menfolder=='All' else folder_sel

            args=[dbfile,outdir,action,folder,separate,iszotero,True]

            self.workthread=WorkThread('work',False,self.stateq)
            self.workthread.deamon=True

            self.workthread.args=args
            self.workthread.start()
            self.reset()
            '''
            self.workproc.apply_async(menotexport.main,args,\
                    callback=self.reset)
            self.workproc.join()
            '''



    def reset(self):
        while self.stateq.qsize() and self.exit==False:
            try:
                msg=self.stateq.get()
                if msg=='done':
                    self.db_button.configure(state=tk.NORMAL)
                    self.out_button.configure(state=tk.NORMAL)
                    self.start_button.configure(state=tk.NORMAL)
                    self.help_button.configure(state=tk.NORMAL)
                    self.foldersmenu.configure(state='readonly')
                    self.check_export.configure(state=tk.NORMAL)
                    self.check_highlight.configure(state=tk.NORMAL)
                    self.check_note.configure(state=tk.NORMAL)
                    self.check_bib.configure(state=tk.NORMAL)
                    self.check_separate.configure(state=tk.NORMAL)
                    self.check_iszotero.configure(state=tk.NORMAL)
                    self.check_custom_template.configure(state=tk.NORMAL)
                    self.messagelabel.configure(text='Message')
                    return
            except Queue.Empty:
                pass
        self.after(100,self.reset)


    
    def stop(self):
        #self.workthread.stop()
        pass
        

    def addMessageFrame(self):
        frame=Frame(self)
        frame.pack(fill=tk.BOTH,side=tk.TOP,\
                expand=1,padx=8,pady=5)

        self.messagelabel=tk.Label(frame,text='Message',bg='#bbb')
        self.messagelabel.pack(side=tk.TOP,fill=tk.X)

        self.text=tk.Text(frame)
        self.text.pack(side=tk.TOP,fill=tk.BOTH,expand=1)
        self.text.height=10

        scrollbar=tk.Scrollbar(self.text)
        scrollbar.pack(side=tk.RIGHT,fill=tk.Y)

        self.text.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.text.yview)
Beispiel #41
0
class App:
    def __init__(self, master,cam):
        self.cam = cam
        self.master = master
        self.frame = None
        self.canvas = None
        self.histCanvas = None
        self.video = None
        self.position = None



##window frame
        self.frame = tk.LabelFrame(self.master,text='Captured video')
        self.frame.pack()

##toolbar
        self.toolbar = tk.Frame(self.master)
        self.toolbar.configure(background='grey',borderwidth=2)
        self.toolbar.pack(side=tk.BOTTOM,padx=5,pady=5)                       #),expand=tk.YES,fill=tk.BOTH)



##adding buttons to toolbar
        self.button = tk.Button(self.toolbar, text="QUIT", fg="red", command=master.destroy)
        self.button.configure(background='tan')
        self.button.pack(side=tk.LEFT,padx=5, pady=5)
## ttk Combobox
        self.efLabel = Labelframe(self.toolbar, text="Choose an effect:")
        self.efLabel.pack(anchor = tk.W, padx=5, pady=2)
        self.efCombo = Combobox(self.efLabel, values = ['none','erode','smooth','dilate','laplace','threshold_otsu'], state='readonly')
        self.efCombo.current(0)
        self.efCombo.bind('<FocusIn>', self._update_values)
        self.efCombo.pack(anchor=tk.NW,padx=5, pady=5)

##fps

## for using of command binding see: 'Thinkink in Tkinter' tt077.py
        self.camon = tk.Button(self.toolbar, text="CAM on", fg="darkgreen", command=lambda: self.video.setOnoff(True))
        self.camon.configure(background='tan')
        self.camon.pack(side=tk.LEFT,padx=5, pady=5)

        self.camoff = tk.Button(self.toolbar, text="CAM off", fg="blue", command=lambda: self.video.setOnoff(False))
        self.camoff.configure(background='tan')
        self.camoff.pack(side=tk.LEFT,padx=5, pady=5)

        self.detector = tk.Button(self.toolbar, text="detect face", fg="blue", command=lambda: self.video.setDetection())
        self.detector.configure(background='tan')
        self.detector.pack(side=tk.LEFT,padx=5, pady=5)

        self.effect = tk.Button(self.toolbar, text="effect", fg="yellow", command=lambda: self.video.setEffect(self.efCombo.get()))
        self.effect.configure(background='tan')
        self.effect.pack(side=tk.LEFT,padx=5, pady=5)

        self.hi_there = tk.Button(self.toolbar, text="Hello")                   #, command=self.say_hi)
        self.hi_there.bind("<Control-Button-1>", self.say_hi)                   #event binding
        self.hi_there.configure(background='tan')
        self.hi_there.pack(side=tk.LEFT,padx=5, pady=5)
##canvas to draw on
        self.canvas = tk.Canvas(self.frame, width=620,height=460)
        self.canvas.configure(background="black",relief='ridge',highlightthickness=5,borderwidth=5)
        self.canvas.pack(side=tk.RIGHT,padx=5,pady=5)                             #(expand=tk.YES,fill=tk.BOTH)
##canvas to draw histogram
        self.histLabel = Labelframe(self.frame, text="Histogram")
        self.histLabel.pack(anchor = tk.W, padx=5, pady=2)
        self.histCanvas = tk.Canvas(self.histLabel, width=300,height=240)
        self.histCanvas.configure(background="black",relief='ridge',highlightthickness=5,borderwidth=5)
        self.histCanvas.pack(side=tk.TOP,padx=5,pady=5)
##sliders
        var=tk.DoubleVar()
        self.contrast = tk.Scale(self.frame, orient=tk.HORIZONTAL,
        label='Contrast',variable=var,resolution=0.5,from_=0.0, to=100.0, command=self._update_contrast)
        self.contrast.pack(side=tk.LEFT, anchor=tk.NW, padx=5, pady=5)
        self.brightness = tk.Scale(self.frame, orient=tk.HORIZONTAL,
        label='Brightness',from_=0, to=100, command=self._update_brightness)
        #self.brightness.bind('<FocusIn>', self._update_brightness)
        self.brightness.pack(side=tk.LEFT, anchor=tk.NW, padx=5, pady=5)
##position label
        self.position = tk.StringVar()
        self.xyLabel = tk.Label(self.toolbar, textvariable = self.position, fg='red',width=30,justify='left').pack(padx=1, pady=5)

##set the camera
        self.video = Camera(self.cam,self.master,self.canvas,self.histCanvas,self.frame,self.position)
        self.video.setOnoff(False)
##==============================================================================
##pooling video from camera
    def pool(self):
        if self.video != None:
            self.id=self.master.after(33,lambda: self.video.update_video())

##            self.master.after(50, lambda: self.pool())

##==============================================================================
##for test purposes only
    def say_hi(self, event):
        print "hi there, everyone!"
##==============================================================================
##combo event
    def _update_values(self, evt):
        # add entered text to combobox list of values
        widget = evt.widget           # get widget
        txt = widget.get()            # get current text
        #vals = widget.cget('values')  # get values

        print txt
        #print vals
##for editable widgets: update list of items with entered value
##        if not vals:
##            widget.configure(values = (txt, ))
##        elif txt not in vals:
##            widget.configure(values = vals + (txt, ))

        return 'break'  # don't propagate event
##==============================================================================
    def _update_brightness(self, val):
        self.video.setBrightness(float(val))
##==============================================================================
    def _update_contrast(self, val):
        self.video.setContrast(float(val))
class SerialTerm(Tk):
    def __init__(self, serial_queue, serial_thread):
        Tk.__init__(self)
        self.title("Foss SerialTerminal for Multi")
        self.serial_queue = serial_queue
        self.serial_thread  = serial_thread

        menu_bar = Menu(self)

        file_menu = Menu(menu_bar, tearoff=0)
        file_menu.add_command(label="Save as...")
        file_menu.add_command(label="Exit", command=self.quit)
        menu_bar.add_cascade(label="File", menu=file_menu)

        self.parser_menu = Menu(menu_bar, tearoff=0)
        self.serial_parser_enabled = IntVar()
        self.serial_parser_enabled.set(1)
        self.parser_menu.add_checkbutton(
            label="Serial parser enabled",
            variable=self.serial_parser_enabled
        )
        self.parser_menu.add_command(label="Edit parser rules", command=self.open_conditionals_editor)
        menu_bar.add_cascade(label="Parser", menu=self.parser_menu)


        self.config(menu=menu_bar)
        main_frame = Frame(self)
        output_frame = Frame(main_frame)
        input_frame = Frame(main_frame)

        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(0, weight=1)
        main_frame.grid(column=0, row=0, padx=3, pady=3, sticky=(N, W, E, S))
        main_frame.grid_columnconfigure(0, weight=1)
        main_frame.grid_rowconfigure(0, weight=1)



        output_text_vertical_scrollbar = Scrollbar(output_frame, orient=VERTICAL)
        output_text_horizontal_scrollbar = Scrollbar(output_frame, orient=HORIZONTAL)
        self.output_text = Text(
            output_frame,
            wrap=NONE,
            xscrollcommand=output_text_horizontal_scrollbar.set,
            yscrollcommand=output_text_vertical_scrollbar.set
        )
        self.output_text.configure(bg="white", state="disabled")
        self.output_text.grid(column=0, row=0, sticky=(N, S, E, W))
        output_text_vertical_scrollbar.grid(column=1, row=0, sticky=(N, S))
        output_text_vertical_scrollbar.config(command=self.output_text.yview)
        output_text_horizontal_scrollbar.grid(column=0, row=1, sticky=(E, W))
        output_text_horizontal_scrollbar.config(command=self.output_text.xview)

        output_frame.grid(column=0, row=0, sticky=(N, S, E, W))
        output_frame.grid_columnconfigure(0, weight=1)
        output_frame.grid_rowconfigure(0, weight=1)


        self.input_string = StringVar()
        input_entry = Entry(input_frame, textvariable=self.input_string)
        input_entry.grid(column=0, row=0, sticky=(E, W))

        line_end_selection_items = ["CR&NL", "NL", "CR", "None"]
        self.line_end_selection = Combobox(
            input_frame,
            values=line_end_selection_items,
            state="readonly",
            width=len(max(line_end_selection_items, key=len))
        )
        self.line_end_selection.current(newindex=0)
        self.line_end_selection.grid(column=1, row=0)

        serial_port_names = ["Port"]
        serial_port_names.extend([s.name for s in serial.tools.list_ports.comports()])
        self.port_name_selection = Combobox(
            input_frame,
            values = serial_port_names,
            state="readonly",
            width=len(max(serial_port_names, key=len))
        )
        self.port_name_selection.current(newindex=0)
        self.port_name_selection_index = 0
        self.port_name_selection.grid(column=2, row=0)


        baudrates = [
            "300 baud",
            "1200 baud",
            "2400 baud",
            "4800 baud",
            "9600 baud",
            "19200 baud",
            "38400 baud",
            "57600 baud",
            "74880 baud",
            "115200 baud",
            "230400 baud",
            "250000 baud"
        ]

        self.baudrate_selection = Combobox(
            input_frame,
            values = baudrates,
            state="readonly",
            width=len(max(baudrates, key=len))
        )
        self.baudrate_selection.current(newindex=9)
        self.baudrate_selection.grid(column=3, row=0)

        input_frame.grid(column=0, row=1, sticky=(E, W))
        input_frame.grid_columnconfigure(0, weight=1)

        self.port_name_selection.bind("<<ComboboxSelected>>", self.port_name_selected)
        self.baudrate_selection.bind("<<ComboboxSelected>>", self.baudrate_selected)

        self.after(100, self.serial_tick)

        # TODO Load from pickle file.
        self.conditionals = [
            ["Enabled", "line.startswith(\"Hello\")", "Python", "print 'Fooobaaaaar. Jibb.'"],
            ["Enabled", "line.startswith(\"Foo\")", "Debugger", "halt\nreset"],
        ]
        self.counter = 0


    def open_conditionals_editor(self):
        self.conditionals_editor = Toplevel(master=self)
        self.parser_menu.entryconfig("Edit parser rules", state="disabled")
        ConditionalsEditor(self.conditionals_editor, self.conditionals, self.closing_conditionals_editor)

    def closing_conditionals_editor(self):
        self.parser_menu.entryconfig("Edit parser rules", state="normal")


    def update_output_text(self, line):
        self.output_text.configure(state="normal")
        self.output_text.insert(END, line)
        self.output_text.configure(state="disabled")
        self.output_text.see(END)

    def evaluate_conditionals(self, line):
        if self.serial_parser_enabled.get() == 1:
            for condition in self.conditionals:
                if condition[0] == "Enabled":
                    if eval(condition[1]):
                        if condition[2] == "Python":
                            exec(condition[3], locals())
                        elif condition[2] == "Debugger":
                            print "Send to debugger: %s"%condition[3]



    def serial_tick(self):
        while True:
            try:
                line = self.serial_queue.get_nowait()
                self.update_output_text(line)
                self.evaluate_conditionals(line)
            except Queue.Empty:
                break
        self.after(100, self.serial_tick)

    def port_name_selected(self, event):
        port_name = event.widget.selection_get()
        if port_name == "Port":
            event.widget.current(newindex=self.port_name_selection_index)
            return
        self.port_name_selection_index = event.widget.current()
        self.serial_thread.set_port(port_name)

    def baudrate_selected(self, event):
        self.serial_thread.set_baudrate(event.widget.selection_get())
class App:
    def __init__(self, master, cam):
        self.cam = cam
        self.master = master
        self.frame = None
        self.canvas = None
        self.histCanvas = None
        self.video = None
        self.position = None

        ##window frame
        self.frame = tk.LabelFrame(self.master, text='Captured video')
        self.frame.pack()

        ##toolbar
        self.toolbar = tk.Frame(self.master)
        self.toolbar.configure(background='grey', borderwidth=2)
        self.toolbar.pack(side=tk.BOTTOM, padx=5, pady=5)  # ),expand=tk.YES,fill=tk.BOTH)

        ##adding buttons to toolbar
        self.button = tk.Button(self.toolbar, text="QUIT", fg="red", command=master.destroy)
        self.button.configure(background='tan')
        self.button.pack(side=tk.LEFT, padx=5, pady=5)
        ## ttk Combobox
        self.efLabel = Labelframe(self.toolbar, text="Choose an effect:")
        self.efLabel.pack(anchor=tk.W, padx=5, pady=2)
        self.efCombo = Combobox(self.efLabel, values=['none', 'erode', 'smooth', 'dilate', 'laplace', 'threshold_otsu'],
                                state='readonly')
        self.efCombo.current(0)
        self.efCombo.bind('<FocusIn>', self._update_values)
        self.efCombo.pack(anchor=tk.NW, padx=5, pady=5)

        ##fps

        ## for using of command binding see: 'Thinkink in Tkinter' tt077.py
        self.camon = tk.Button(self.toolbar, text="CAM on", fg="darkgreen", command=lambda: self.video.setOnoff(True))
        self.camon.configure(background='tan')
        self.camon.pack(side=tk.LEFT, padx=5, pady=5)

        self.camoff = tk.Button(self.toolbar, text="CAM off", fg="blue", command=lambda: self.video.setOnoff(False))
        self.camoff.configure(background='tan')
        self.camoff.pack(side=tk.LEFT, padx=5, pady=5)

        self.detector = tk.Button(self.toolbar, text="detect face", fg="blue",
                                  command=lambda: self.video.setDetection())
        self.detector.configure(background='tan')
        self.detector.pack(side=tk.LEFT, padx=5, pady=5)

        self.effect = tk.Button(self.toolbar, text="effect", fg="yellow",
                                command=lambda: self.video.setEffect(self.efCombo.get()))
        self.effect.configure(background='tan')
        self.effect.pack(side=tk.LEFT, padx=5, pady=5)

        self.hi_there = tk.Button(self.toolbar, text="Hello")  # , command=self.say_hi)
        self.hi_there.bind("<Control-Button-1>", self.say_hi)  # event binding
        self.hi_there.configure(background='tan')
        self.hi_there.pack(side=tk.LEFT, padx=5, pady=5)
        ##canvas to draw on
        self.canvas = tk.Canvas(self.frame, width=620, height=460)
        self.canvas.configure(background="black", relief='ridge', highlightthickness=5, borderwidth=5)
        self.canvas.pack(side=tk.RIGHT, padx=5, pady=5)  # (expand=tk.YES,fill=tk.BOTH)
        ##canvas to draw histogram
        self.histLabel = Labelframe(self.frame, text="Histogram")
        self.histLabel.pack(anchor=tk.W, padx=5, pady=2)
        self.histCanvas = tk.Canvas(self.histLabel, width=300, height=240)
        self.histCanvas.configure(background="black", relief='ridge', highlightthickness=5, borderwidth=5)
        self.histCanvas.pack(side=tk.TOP, padx=5, pady=5)
        ##sliders
        var = tk.DoubleVar()
        self.contrast = tk.Scale(self.frame, orient=tk.HORIZONTAL,
                                 label='Contrast', variable=var, resolution=0.5, from_=0.0, to=100.0,
                                 command=self._update_contrast)
        self.contrast.pack(side=tk.LEFT, anchor=tk.NW, padx=5, pady=5)
        self.brightness = tk.Scale(self.frame, orient=tk.HORIZONTAL,
                                   label='Brightness', from_=0, to=100, command=self._update_brightness)
        # self.brightness.bind('<FocusIn>', self._update_brightness)
        self.brightness.pack(side=tk.LEFT, anchor=tk.NW, padx=5, pady=5)
        ##position label
        self.position = tk.StringVar()
        self.xyLabel = tk.Label(self.toolbar, textvariable=self.position, fg='red', width=30, justify='left').pack(
            padx=1, pady=5)

        ##set the camera
        self.video = Camera(self.cam, self.master, self.canvas, self.histCanvas, self.frame, self.position)
        self.video.setOnoff(False)

    ##==============================================================================
    ##pooling video from camera
    def pool(self):
        if self.video != None:
            self.id = self.master.after(33, lambda: self.video.update_video())

            ##            self.master.after(50, lambda: self.pool())

            ##==============================================================================
            ##for test purposes only

    def say_hi(self, event):
        print "hi there, everyone!"

    ##==============================================================================
    ##combo event
    def _update_values(self, evt):
        # add entered text to combobox list of values
        widget = evt.widget  # get widget
        txt = widget.get()  # get current text
        # vals = widget.cget('values')  # get values

        print txt
        # print vals
        ##for editable widgets: update list of items with entered value
        ##        if not vals:
        ##            widget.configure(values = (txt, ))
        ##        elif txt not in vals:
        ##            widget.configure(values = vals + (txt, ))

        return 'break'  # don't propagate event

    ##==============================================================================
    def _update_brightness(self, val):
        self.video.setBrightness(float(val))

    ##==============================================================================
    def _update_contrast(self, val):
        self.video.setContrast(float(val))
class Application(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.initUI()
        self.state = "inactive"
        #state remembers last clicked cluster button so when user clicks the refine analysis button
        #program is going to perform analysis on districts or parties with the information it gets from state.
        self.data_manager = DataCenter(
        )  #this is data center object to manage data processes.

    def initUI(self):
        self.pack(fill=BOTH)
        self.UI_frame = Frame(self)
        self.UI_frame.pack(side=TOP, fill=BOTH)
        self.header = Label(self.UI_frame,
                            text="Election Data Analysis Tool v.1.0",
                            background="red",
                            font=('Arial', '23', 'bold'),
                            foreground="white")
        self.header.pack(side=TOP, fill=BOTH, ipady=7)
        self.upload_data_button = Button(self.UI_frame,
                                         text="Load Election Data",
                                         height=2,
                                         width=20,
                                         command=self.upload_data)
        self.cluster_district_button = Button(self.UI_frame,
                                              text="Cluster Districts",
                                              height=2,
                                              width=20,
                                              command=self.cluster_district)
        self.cluster_parties_button = Button(self.UI_frame,
                                             text="Cluster Political Parties",
                                             height=2,
                                             width=20,
                                             command=self.cluster_parties)
        self.upload_data_button.pack(side=TOP, pady=10)
        self.cluster_district_button.pack(side=LEFT, padx=(255, 10))
        self.cluster_parties_button.pack(side=LEFT)

        self.analysis_frame = Frame(self)
        self.canvas_frame = Frame(self.analysis_frame)
        self.canvas_frame.pack(side=TOP, fill=BOTH, padx=90, pady=10)
        self.canvas_horizontal_scroll = Scrollbar(self.canvas_frame,
                                                  orient="horizontal")
        self.canvas_vertical_scroll = Scrollbar(self.canvas_frame,
                                                orient="vertical")
        self.canvas = Canvas(self.canvas_frame,
                             background="white",
                             height=250,
                             width=700)
        self.canvas.grid(row=0, column=0)
        self.canvas_horizontal_scroll.grid(row=1,
                                           column=0,
                                           columnspan=2,
                                           sticky=W + E)
        self.canvas_vertical_scroll.grid(row=0, column=1, sticky=S + N)
        self.canvas.configure(xscrollcommand=self.canvas_horizontal_scroll.set,
                              yscrollcommand=self.canvas_vertical_scroll.set)
        self.canvas_horizontal_scroll.configure(command=self.canvas.xview)
        self.canvas_vertical_scroll.configure(command=self.canvas.yview)
        self.canvas.configure(scrollregion=(0, 0, 1200, 800))
        #scrollregion helps us to cover all of the dendogram with scrollbars.
        self.panel_frame = Frame(self.analysis_frame)
        self.panel_frame.pack(side=TOP, fill=BOTH)
        self.district_label = Label(self.panel_frame, text="Districts:")
        self.district_listbox = Listbox(self.panel_frame,
                                        selectmode="multiple")
        self.listbox_scroll = Scrollbar(self.panel_frame)
        self.district_listbox.configure(yscrollcommand=self.listbox_scroll.set)
        self.listbox_scroll.configure(command=self.district_listbox.yview)
        self.threshold_label = Label(self.panel_frame, text="Threshold:")
        threshold_list = ["%0", "%1", "%10", "%20", "%30", "%40",
                          "%50"]  #list for threshold combobox
        self.threshold_combobox = Combobox(self.panel_frame,
                                           width=7,
                                           state="readonly",
                                           values=threshold_list)
        self.threshold_combobox.current(0)  #default threshold is %0
        self.refine_button = Button(self.panel_frame,
                                    text="Refine Analysis",
                                    height=2,
                                    width=20,
                                    command=self.refined_analysis)
        self.district_label.pack(side=LEFT, padx=(120, 5))
        self.district_listbox.pack(side=LEFT)
        self.listbox_scroll.pack(side=LEFT, fill=Y)
        self.threshold_label.pack(side=LEFT, padx=10)
        self.threshold_combobox.pack(side=LEFT)
        self.refine_button.pack(side=LEFT, padx=20)

    def upload_data(self):
        self.district_listbox.delete(0, END)
        txt_file = tkFileDialog.askopenfilename(
            title="Select file",
            filetypes=(("txt files", "*.txt"), ("all files", "*.*")))
        self.data_manager.txt_manager(txt_file)  #txt reader function
        self.data_manager.create_matrix(
            district_list=self.data_manager.district_dictionary.keys(),
            threshold="%0")
        #program creates matrix with default values which is all districts and %0 threshold right after reading txt.
        for district in sorted(self.data_manager.district_dictionary.keys()):
            self.district_listbox.insert(END, district)
        #inserting districts to listbox

    def cluster_district(self):
        self.state = "district"
        #if user clickes cluster districts state changes to district.
        self.analysis_frame.pack(side=TOP, fill=BOTH)
        self.canvas.delete("all")  #clearing canvas
        # https://stackoverflow.com/questions/15839491/how-to-clear-tkinter-canvas
        self.party_list, self.district_list, self.data = clusters.readfile(
            "matrix.txt")
        new_data = clusters.rotatematrix(self.data)
        #we need to rotated matrix to cluster districts.
        clust = clusters.hcluster(new_data, distance=clusters.sim_distance)
        clusters.drawdendrogram(clust,
                                self.district_list,
                                jpeg='districts.jpg')
        self.insert_image("districts.jpg")  #insert clustered image to canvas

    def cluster_parties(self):
        self.state = "party"  #if user clickes cluster parties state changes to party.
        self.analysis_frame.pack(side=TOP, fill=BOTH)
        self.canvas.delete("all")  #clearing canvas
        # https://stackoverflow.com/questions/15839491/how-to-clear-tkinter-canvas
        self.party_list, self.district_list, self.data = clusters.readfile(
            "matrix.txt")
        clust = clusters.hcluster(self.data, distance=clusters.sim_distance)
        clusters.drawdendrogram(clust, self.party_list, jpeg='parties.jpg')
        self.insert_image("parties.jpg")  #insert clustered image to canvas

    def insert_image(self, name):
        #function to create PIL image and inserting canvas.
        img = Image.open(name)
        self.canvas.img = ImageTk.PhotoImage(img)
        self.canvas.create_image(0, 0, image=self.canvas.img, anchor="nw")
        #from link in the pdf related canvas. we need to justify left corner our dendogram to have a nice usage.

    def refined_analysis(self):
        """
        we use try-except structure to raise zero-division error that occurs when user selects less districts
        and let cluster algorithm fail.
        """
        try:
            selected_districts = map(lambda x: self.district_listbox.get(x),
                                     self.district_listbox.curselection())
            #we use map function through list of indexes user choosed to get name of districts efficiently.
            if len(selected_districts) == 0:
                selected_districts = self.data_manager.district_dictionary.keys(
                )
            #if our selection list is empty we tell program to use all of districts.
            self.data_manager.create_matrix(
                district_list=selected_districts,
                threshold=self.threshold_combobox.get())
            #executing create_matrix function with selected list and threshold value from combobox.
            if self.state == "district":  #here program decides to execute cluster_district or cluster_parties.
                self.cluster_district()
            else:
                self.cluster_parties()
        except:
            raise Exception(
                "You need to select more district to have an refined analysis!."
            )
class VideoGUI():
    def __init__(self):
        self.ENTRY_WITDH = 20
        self.button_width = 6
        self.default_dir = './'
        self.gui()

    def emptyIt(self):
        self.link_contend.set('')
        return 0

    def chooseFile(self):
        self.fname = tkFileDialog.askopenfilename(title=u"Choose File",
                                                  initialdir=(os.path.expanduser(self.default_dir)))
        self.link_contend.set(self.fname)
        return self.fname

    def startFFmpeg(self):
        self.result_link_contend.set('convert done!')
        input_path = self.link_contend.get()
        output_type = self.outType.get()
        output_path = input_path.split('.')[0] + '.' + output_type
        if output_type == 'wav':
            cmd = 'ffmpeg -i ' + input_path + ' -y ' + output_path
        elif output_type == 'mp4':
            cmd = 'ffmpeg -i ' + input_path + ' ' + output_path
        else:
            cmd = 'ffmpeg'
        os.system(cmd)
        self.result_link_contend.set(output_path)
        self.link_contend.set('convert done!')

        return 0

    def gui(self):
        self.root = Tk()
        self.root.title('video converter')
        self.entry_link = Entry(self.root, width=self.ENTRY_WITDH, state='disabled')
        self.entry_link.grid(row=0, column=0, columnspan=2)
        self.link_contend = StringVar()
        self.entry_link.config(textvariable=self.link_contend)
        self.link_contend.set('plz choose:')
        self.choose_button = Button(self.root, text='choose', width=self.button_width, command=self.chooseFile)
        self.choose_button.grid(row=1, column=0, columnspan=1)
        self.clear_button = Button(self.root, text='empty', width=self.button_width, command=self.emptyIt)
        self.clear_button.grid(row=1, column=1, columnspan=1)
        self.outType = StringVar()
        self.typeChosen = Combobox(self.root, width=self.ENTRY_WITDH, textvariable=self.outType)
        self.typeChosen['values'] = ('wav', 'mp4', 'flv', 'mp3', 'gif')
        self.typeChosen.current(3)
        self.typeChosen.grid(row=2, column=0, columnspan=2)

        self.startButton = Button(self.root, text='Start Convert', width=self.button_width * 2,
                                  command=self.startFFmpeg)
        self.startButton.grid(row=3, column=0, columnspan=2)

        self.result_link = Entry(self.root, width=self.ENTRY_WITDH, state='disabled')
        self.result_link.grid(row=4, column=0, columnspan=2)
        self.result_link_contend = StringVar()
        self.result_link.config(textvariable=self.result_link_contend)
        self.result_link_contend.set('plz hold on:')

        mainloop()
class Application(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.root = master
        self.root.title('get_app_version (v1.0.0,qing.guo)')
        self.root.geometry('700x410')
        self.root.resizable(0, 0)  # 禁止调整窗口大小
        self.root.protocol("WM_DELETE_WINDOW", self.close)
        self.root.iconbitmap(get_path('get_app.ico'))

    def creatWidgets(self):
        frame_left = Frame(self.root, width=380, height=410, bg='#C1CDCD')
        frame_right = Frame(self.root, width=320, height=410, bg='#C1CDCD')

        frame_left.grid_propagate(0)
        frame_right.propagate(0)
        frame_right.grid_propagate(0)

        frame_left.grid(row=0, column=0)
        frame_right.grid(row=0, column=1)

        self.v1 = StringVar()
        self.v2 = StringVar()
        self.v3 = StringVar()
        self.v4 = StringVar()
        self.v5 = StringVar()
        self.v4.set(get_app.result_path)

        web_list = [u'应用宝', u'...', u'...']

        Label(frame_left, text=u"选择网站类型:", bg='#C1CDCD').grid(row=0,
                                                              column=0,
                                                              pady=20,
                                                              padx=5)
        self.cb1 = Combobox(frame_left,
                            width=30,
                            textvariable=self.v1,
                            values=web_list)
        self.cb1.grid(row=0, column=1, ipady=1, padx=5, sticky=W)
        self.cb1.current(0)

        Label(frame_left, text=u"设置基准日期 :", bg='#C1CDCD').grid(row=1,
                                                               column=0,
                                                               pady=30,
                                                               padx=5)
        Entry(frame_left, width=33, textvariable=self.v2).grid(row=1,
                                                               column=1,
                                                               padx=2,
                                                               pady=30,
                                                               ipady=2,
                                                               sticky=W)

        Button(frame_left,
               text=u"选择配置文件 :",
               command=self.open_file1,
               bg='#C1CDCD').grid(row=2, column=0, pady=30, padx=5)
        Entry(frame_left, width=33, textvariable=self.v3).grid(row=2,
                                                               column=1,
                                                               padx=2,
                                                               pady=30,
                                                               ipady=2,
                                                               sticky=W)

        self.b1 = Button(frame_left,
                         text=u"开始获取",
                         command=self.start_test,
                         bg='#C1CDCD')
        self.b1.grid(row=3, column=0, padx=25, pady=30)

        self.b2 = Button(frame_left,
                         text=u"停止获取",
                         command=self.end_test,
                         bg='#C1CDCD')
        self.b2.grid(row=3, column=1, padx=25, pady=30)

        Button(frame_left, text=u"查看结果", command=self.open_file2,
               bg='#C1CDCD').grid(row=4, column=0, padx=3, pady=15)
        Entry(frame_left, width=34, textvariable=self.v4).grid(row=4,
                                                               column=1,
                                                               ipady=1,
                                                               padx=3,
                                                               pady=15)

        self.v2.set(get_app.current_date)

        #Scrollbar
        scrollbar = Scrollbar(frame_right, bg='#C1CDCD')
        scrollbar.pack(side=RIGHT, fill=Y)
        self.text_msglist = Text(frame_right,
                                 yscrollcommand=scrollbar.set,
                                 bg='#C1CDCD')
        self.text_msglist.pack(side=RIGHT, fill=BOTH)
        scrollbar['command'] = self.text_msglist.yview
        self.text_msglist.tag_config('green', foreground='#008B00')
        self.text_msglist.tag_config('blue', foreground='#0000FF')
        self.text_msglist.tag_config('red', foreground='#FF3030')
        self.text_msglist.tag_config('purple', foreground='#CD00CD')
        text_message1 = u"1.选择数据APK来源网站,目前支持应用宝\n"
        self.text_msglist.insert(END, text_message1, 'green')
        text_message2 = u"2.设置基准日期,检测应用在基准日期之后的更新情况,格式示例: 2017-05-12\n"
        self.text_msglist.insert(END, text_message2, 'green')
        text_message3 = u"3.选择配置文件路径,不同网站配置文件可能不同\n"
        self.text_msglist.insert(END, text_message3, 'green')

    def start_test(self):

        get_app.Get_App.set_flag('True')
        web_type = self.v1.get()
        base_date = self.v2.get()
        config_path = self.v3.get()

        if base_date == '' or base_date.isspace():
            self.text_msglist.insert(END, 'please input base date\n', 'red')
            self.b1.config(state=NORMAL)
            return -1
        if config_path == '' or config_path.isspace():
            self.text_msglist.insert(END, 'please choose config path\n', 'red')
            self.b1.config(state=NORMAL)
            return -1

        self.b1.config(state=DISABLED)
        self.b2.config(state=NORMAL)
        thread1 = get_app.Get_App('get_app', app, web_type, base_date,
                                  config_path)
        thread1.setDaemon(True)
        thread1.start()

    def end_test(self):
        self.b1.config(state=NORMAL)
        get_app.Get_App.set_flag('False')
        self.b2.config(state=DISABLED)
        self.text_msglist.insert(END, 'click end test button,end_test\n',
                                 'blue')

    def open_file1(self):
        filename = tkFileDialog.askopenfilename(initialdir=get_app.log_path)
        print filename
        if filename == '':
            return 0
        self.v3.set(filename)

    def open_file2(self):
        filename = tkFileDialog.askopenfilename(initialdir=get_app.result_path)
        if filename == '':
            return 0
        os.startfile(filename)

    def close(self):

        if get_app.flag:
            result = tkMessageBox.askokcancel(title=u"警告",
                                              message=u"测试还未完成,确定要退出程序?")
        else:
            result = tkMessageBox.askokcancel(title=u"退出", message=u"确定退出程序?")
        if result:
            self.root.quit()
            self.root.destroy()
Beispiel #47
0
class CustomerFrame(Frame):
    def __init__(self, master, customers, output_text, refresh):
        Frame.__init__(self, master)
        self.output_text = output_text
        self.refresh = refresh
        self.root = master
        self.customers = customers

        self.name = StringVar() #edit customer
        self.names = []
        self.ncd = NewCustomerDialog(self.root, self.customers, self.refresh, edit=True)

        self.fname = StringVar()
        self.lname = StringVar()
        self.mname = StringVar()
        self.payment = StringVar()
        self.date = StringVar()
        self.iconname="New Customer"

        lf = LabelFrame(self, text="New Customer")
        lf.grid(padx=5,pady=5,row=0,column=0,sticky='ew')
        
        ### dialog content        
        Label(lf, text="Name: ").grid(row=0,column=0,sticky='e',padx=(10,0),pady=(10,2))
        Label(lf, text="Type: ").grid(row=1,sticky='e',pady=2,padx=(10,0))
        Label(lf, text="Date: ").grid(row=1,column=2,sticky='e',ipady=2,padx=(10,0))

        self.fname_en = Entry(lf, width=20, textvariable=self.fname)
        self.mname_en = Entry(lf, width=4, textvariable=self.mname)
        self.lname_en = Entry(lf, width=20, textvariable=self.lname)
        self.payment_cb = Combobox(lf, textvariable=self.payment, width=12,
                                   values=("Drop In", "Punch Card", "Monthly", "Inactive"))
        self.date_en = Entry(lf, width=15, textvariable=self.date)
        
        self.fname_en.grid(row=0,column=1,sticky='ew',pady=(10,2))
        self.mname_en.grid(row=0,column=2,sticky='ew',pady=(10,2))
        self.lname_en.grid(row=0,column=3,sticky='ew',padx=(0,10),pady=(10,2))
        self.payment_cb.grid(row=1,column=1,sticky='ew')
        self.date_en.grid(row=1,column=3,columnspan=2,sticky='ew',padx=(0,10))
        
        ### buttons
        Button(lf, text='Reset Values', width=15,
               command=self.reset_values).grid(row=3,column=0,columnspan=2,sticky='ew',padx=10,pady=(2,10))
        Button(lf, text='Submit', width=15,
               command=self.add_customer).grid(row=3,column=3,sticky='ew',padx=(0,10),pady=(2,10))

        for i in range(4):
            lf.columnconfigure(i, weight=1)

        # edit customer
        lf = LabelFrame(self, text="Edit Customer")
        lf.grid(padx=5,pady=5,row=1,column=0,sticky='ew')

        Label(lf, text="Name: ").grid(row=0,column=0,sticky='e',pady=10,padx=(10,0))
        self.name_cb = Combobox(lf, textvariable=self.name, width=30, values=self.names)
        self.name_cb.grid(row=0,column=1,sticky='ew',pady=10)
        Button(lf, text="Edit",width=15,command=self.edit).grid(row=0,column=2,sticky='ew',padx=10,pady=10)

        for i in range(3):
            lf.columnconfigure(i,weight=1)
        self.columnconfigure(0,weight=1)

        self.fname_en.focus_set() #cursor goes here when frame is created
        self.update_names()
        self.reset_values() #zero out all values in new customer

    def edit(self):
        old_name = str(self.name.get())
        parsed = old_name.split(' ',2)
        (line,row) = self.customers.find(parsed[2],parsed[0],parsed[1])
        
        self.ncd.show(line)
        self.refresh() #refresh the global refresh
        name = ' '.join([self.ncd.fname.get(),self.ncd.mname.get(),self.ncd.lname.get()])
        self.output_text("+ - Modified: " + old_name + ' (' + line[3] + ') -> ' + name + " (" + self.ncd.payment.get() + ")\n")

    def update_names(self):
        '''
        update names in edit Combobox
        '''
        self.populate_names()
        if len(self.names) == 0: self.names = ['']
        self.name_cb['values'] = self.names
        self.name_cb.current(0)

    def populate_names(self):
        try:
            clist = self.customers.get_list()
        except IOError:
            self.output_text("! - " + self.customers.filename + " open in another application.\n")
            return
        clist.sort(key = lambda x: ', '.join(x[0:3]).lower())
        self.names = []
        for line in clist:
            self.names.append(' '.join([line[1],line[2],line[0]]))

    def reset_values(self):
        self.fname.set('')
        self.mname.set('')
        self.lname.set('')
        # blow out the field every time this is created
        self.date.set(date.today().strftime("%m/%d/%Y"))
        self.payment_cb.set("Drop In")

    def add_customer(self, event=None):
        # validate and show errors
        if self.fname.get() == '':
            showerror("Error!", "First name field blank!")
        elif self.lname.get() == '':
            showerror("Error!", "Last name field blank!")
        elif self.mname.get() == '':
            showerror("Error!", "Middle initial field blank!")
        elif self.payment.get() not in ("Drop In", "Punch Card", "Monthly", "Inactive"):
            showerror("Error!", "Incorect Customer type!")
        elif not re.compile(r'[01]?\d/[0123]?\d/[12]\d{1,3}').search(self.date.get()):
            showerror("Error!", "Bad entry for date, use format mm/dd/yyyy")
        else:
            # do work
            name = ' '.join([self.fname.get(),self.mname.get(),self.lname.get()])
            old, row = self.customers.find(str(self.lname.get()).strip(), str(self.fname.get()).strip(),
                                           str(self.mname.get()).strip())
            new = [str(self.lname.get()).strip(), str(self.fname.get()).strip(), str(self.mname.get()).strip(),
                   str(self.payment.get()).strip(), datetime.strptime(self.date.get(), "%m/%d/%Y")]
            
            if not old: #add customer
                self.customers.add(new)
                self.output_text("+ - New Customer: " + name + " (" + self.payment.get() + ")\n")
                self.refresh()
            else:
                var = IntVar()
                
                diag = AlreadyExistsDialog(self.root, new, old, var)
                diag.show()
                if var.get() == 0: # edit
                    pass
                if var.get() == 1: # replace customer
                    self.customers.replace(row, new)
                    self.output_text("+ - Modified: " + name + " (" + self.payment.get() + ")\n")
                    self.refresh()
Beispiel #48
0
class Window(Frame):
    def __init__(self, parent, window_type):
        Frame.__init__(self, parent, msg=None)

        self.parent = parent
        if window_type == "main":
            self.initUI_main()
        if window_type == "err":
            self.initUI_err()

    def initUI_main(self):
        self.parent.title("Personal Helper")
        self.pack(fill=BOTH, expand=True)

        self.columnconfigure(0, weight=1)
        self.columnconfigure(7, weight=1)
        self.columnconfigure(5, pad=10)
        self.columnconfigure(3, pad=10)
        self.columnconfigure(1, weight=3)
        self.rowconfigure(0, weight=0)
        self.rowconfigure(5, weight=1)
        self.rowconfigure(5, pad=7)
        self.rowconfigure(6, pad=6)

        lbl = Label(self, text="Windows")
        lbl.grid(sticky=W + N, pady=4, padx=5)

        check_box = {"work": IntVar(), "boost": IntVar()}

        check1 = Checkbutton(self,
                             text="work-Mode",
                             variable=check_box["work"])
        check1.grid(row=7, column=0)

        check2 = Checkbutton(self,
                             text="boost games",
                             variable=check_box["boost"])
        check2.grid(row=7, column=1)

        ### old version, may be used again later
        area = Treeview(self)
        area['show'] = 'headings'
        area["columns"] = ("one", "two", "three", "four")
        area.column("one", width=10)
        area.column("two", width=10)
        area.column("three", width=10)
        area.column("four", width=10)
        area.heading("one", text="process name")
        area.heading("two", text="Priority")
        area.heading("three", text="PID")
        area.heading("four", text="Usage")
        ###about this part
        #area.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N)
        #######

        #comboboxes and relevant buttons

        self.block_drop = Combobox(self, postcommand=self.update_blocked)
        self.block_drop['values'] = working_bans
        self.block_drop.current(0)
        self.block_drop.grid(row=1, column=1, pady=1)
        self.entry = Entry(self)
        self.entry.insert(0, "enter to block")
        self.entry.grid(row=1, column=4)

        block_btn_remv = Button(self,
                                text="Remove",
                                command=lambda: remove_from_list(
                                    working_bans, self.block_drop.get()))
        block_btn_remv.grid(row=1, column=2)

        block_btn_add = Button(
            self,
            text="Add",
            command=lambda: add_to_list(working_bans, self.entry.get(), self.
                                        entry, defults["block"]))
        block_btn_add.grid(row=1, column=3)

        ############
        #boosted combo
        self.boost_drop = Combobox(self, postcommand=self.update_boosted)
        self.boost_drop['values'] = boosted
        self.boost_drop.current(0)
        self.boost_drop.grid(row=2, column=1, pady=1)
        self.entry2 = Entry(self)
        self.entry2.insert(0, "enter to buff priority")
        self.entry2.grid(row=2, column=4, pady=4)

        boost_btn_remv = Button(
            self,
            text="Remove",
            command=lambda: remove_from_list(boosted, self.boost_drop.get()))
        boost_btn_remv.grid(row=2, column=2)

        boost_btn_add = Button(
            self,
            text="Add",
            command=lambda: add_to_list(boosted, self.entry2.get(), self.
                                        entry2, defults["boost"]))
        boost_btn_add.grid(row=2, column=3)

        #########################################

        #degraded combo
        self.deg_drop = Combobox(self, postcommand=self.update_degraded)
        self.deg_drop['values'] = degraded
        self.deg_drop.current(0)
        self.deg_drop.grid(row=3, column=1, pady=1)
        self.entry3 = Entry(self)
        self.entry3.insert(0, "enter to lower priority")
        self.entry3.grid(row=3, column=4, pady=4)

        deg_btn_remv = Button(
            self,
            text="Remove",
            command=lambda: remove_from_list(degraded, self.deg_drop.get()))
        deg_btn_remv.grid(row=3, column=2)

        deg_btn_add = Button(
            self,
            text="Add",
            command=lambda: add_to_list(degraded, self.entry3.get(), self.
                                        entry3, defults["degrade"]))
        deg_btn_add.grid(row=3, column=3)

        ####
        #music combo

        self.music_drop = Combobox(self, postcommand=self.update_music)
        self.music_drop['values'] = music_list.keys()
        self.music_drop.current(0)
        self.music_drop.grid(row=4, column=1, pady=1)
        self.entry4 = Entry(self)
        self.entry4.insert(0, "enter url")
        self.entry4.grid(row=4, column=5)
        self.entry5 = Entry(self)
        self.entry5.insert(0, "enter song's name")
        self.entry5.grid(row=4, column=4)

        music_btn_remv = Button(self,
                                text="Remove",
                                command=lambda: remove_from_list(
                                    music_list, self.music_drop.get()))
        music_btn_remv.grid(row=4, column=2)

        music_btn_add = Button(
            self,
            text="Add",
            command=lambda: add_music(music_list, self.entry5.get(
            ), self.entry4.get(), self.entry5, defults["music"]))
        music_btn_add.grid(row=4, column=3)

        abtn = Button(self, text="Activate", command=scan_computer_programs)
        abtn.grid(row=1, column=5, sticky=E)

        sbtn = Button(self, text="Stop", command=lambda: stop_running())
        sbtn.grid(row=2, column=5, pady=6, sticky=E)

        cbtn = Button(self, text="Close", command=quit)
        cbtn.grid(row=3, column=5, pady=4, sticky=E)

        hbtn = Button(self, text="Save", command=save_lists)
        hbtn.grid(row=6, column=0, sticky=W)

        tsbtn = Button(self,
                       text="TaskManager",
                       command=lambda: os.system("TaskManager\pyProcMon.py"))
        tsbtn.grid(row=3, column=5, sticky=E)

        obtn = Button(
            self,
            text="start",
            command=lambda: call_running(area, threads["procs"], check_box))
        obtn.grid(row=6, column=5, sticky=E)

    def initUI_err(self):
        self.parent.title("Personal Helper")
        self.pack(fill=BOTH, expand=True)

    def update_boosted(self):
        self.boost_drop['values'] = boosted
        try:
            self.boost_drop.current(0)
        except:
            self.boost_drop.set("empty")

    def update_blocked(self):
        self.block_drop['values'] = working_bans
        try:
            self.block_drop.current(0)
        except:
            self.block_drop.set("empty")

    def update_degraded(self):
        self.deg_drop['values'] = degraded
        try:
            self.block_drop.current(0)
        except:
            self.block_drop.set("empty")

    def update_music(self):
        self.music_drop['values'] = music_list.keys()
        try:
            self.block_drop.current(0)
        except:
            self.block_drop.set("empty")
Beispiel #49
0
class Window(Frame):
    def __init__(self, parent, window_type):
        Frame.__init__(self, parent, msg = None)

        self.parent = parent
        if window_type == "main":
            self.initUI_main()
        if window_type == "err":
            self.initUI_err()

    def initUI_main(self):
        self.parent.title("Personal Helper")
        self.pack(fill=BOTH, expand=True)

        self.columnconfigure(0, weight=1)
        self.columnconfigure(7, weight=1)
        self.columnconfigure(5, pad=10)
        self.columnconfigure(3, pad=10)
        self.columnconfigure(1, weight=3)
        self.rowconfigure(0, weight=0)
        self.rowconfigure(5, weight=1)
        self.rowconfigure(5, pad=7)
        self.rowconfigure(6, pad=6)


        lbl = Label(self, text="Windows")
        lbl.grid(sticky=W+N, pady=4, padx=5)


        check_box = {"work": IntVar(),
                     "boost": IntVar()}

        check1 = Checkbutton(self, text="work-Mode", variable=check_box["work"])
        check1.grid(row=7, column=0)

        check2 = Checkbutton(self, text="boost games", variable=check_box["boost"])
        check2.grid(row=7, column=1)


        ### old version, may be used again later
        area = Treeview(self)
        area['show'] = 'headings'
        area["columns"] = ("one", "two", "three", "four")
        area.column("one", width=10)
        area.column("two", width=10)
        area.column("three", width=10)
        area.column("four", width=10)
        area.heading("one", text="process name")
        area.heading("two", text="Priority")
        area.heading("three", text="PID")
        area.heading("four", text="Usage")
        ###about this part
        #area.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N)
        #######

        #comboboxes and relevant buttons

        self.block_drop = Combobox(self, postcommand= self.update_blocked)
        self.block_drop['values'] = working_bans
        self.block_drop.current(0)
        self.block_drop.grid(row=1, column=1, pady=1)
        self.entry = Entry(self)
        self.entry.insert(0, "enter to block")
        self.entry.grid(row=1, column=4)

        block_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(working_bans, self.block_drop.get()))
        block_btn_remv.grid(row=1, column=2)

        block_btn_add = Button(self, text="Add", command=lambda: add_to_list(working_bans, self.entry.get(), self.entry, defults["block"]))
        block_btn_add.grid(row=1, column=3)

        ############
        #boosted combo
        self.boost_drop = Combobox(self, postcommand=self.update_boosted)
        self.boost_drop['values'] = boosted
        self.boost_drop.current(0)
        self.boost_drop.grid(row=2, column=1, pady=1)
        self.entry2 = Entry(self)
        self.entry2.insert(0, "enter to buff priority")
        self.entry2.grid(row=2, column=4, pady=4)

        boost_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(boosted, self.boost_drop.get()))
        boost_btn_remv.grid(row=2, column=2)

        boost_btn_add = Button(self, text="Add", command=lambda: add_to_list(boosted, self.entry2.get(), self.entry2, defults["boost"]))
        boost_btn_add.grid(row=2, column=3)

        #########################################

        #degraded combo
        self.deg_drop = Combobox(self, postcommand=self.update_degraded)
        self.deg_drop['values'] = degraded
        self.deg_drop.current(0)
        self.deg_drop.grid(row=3, column=1, pady=1)
        self.entry3 = Entry(self)
        self.entry3.insert(0, "enter to lower priority")
        self.entry3.grid(row=3, column=4, pady=4)

        deg_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(degraded, self.deg_drop.get()))
        deg_btn_remv.grid(row=3, column=2)

        deg_btn_add = Button(self, text="Add", command=lambda: add_to_list(degraded, self.entry3.get(), self.entry3, defults["degrade"]))
        deg_btn_add.grid(row=3, column=3)

        ####
        #music combo

        self.music_drop = Combobox(self, postcommand=self.update_music)
        self.music_drop['values'] = music_list.keys()
        self.music_drop.current(0)
        self.music_drop.grid(row=4, column=1, pady=1)
        self.entry4 = Entry(self)
        self.entry4.insert(0, "enter url")
        self.entry4.grid(row=4, column=5)
        self.entry5 = Entry(self)
        self.entry5.insert(0, "enter song's name")
        self.entry5.grid(row=4, column=4)

        music_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(music_list, self.music_drop.get()))
        music_btn_remv.grid(row=4, column=2)

        music_btn_add = Button(self, text="Add", command=lambda: add_music(music_list, self.entry5.get(),self.entry4.get() ,self.entry5, defults["music"]))
        music_btn_add.grid(row=4, column=3)


        abtn = Button(self, text="Activate", command=scan_computer_programs)
        abtn.grid(row=1, column=5, sticky=E)

        sbtn = Button(self, text="Stop", command=lambda: stop_running())
        sbtn.grid(row=2, column=5, pady=6, sticky=E)

        cbtn = Button(self, text="Close", command=quit)
        cbtn.grid(row=3, column=5, pady=4, sticky=E)

        hbtn = Button(self, text="Save", command=save_lists)
        hbtn.grid(row=6, column=0, sticky=W)

        tsbtn = Button(self, text="TaskManager", command=lambda: os.system("TaskManager\pyProcMon.py"))
        tsbtn.grid(row=3, column=5, sticky=E)

        obtn = Button(self, text="start", command=lambda: call_running(area, threads["procs"], check_box))
        obtn.grid(row=6, column=5, sticky=E)

    def initUI_err(self):
        self.parent.title("Personal Helper")
        self.pack(fill=BOTH, expand=True)

    def update_boosted(self):
        self.boost_drop['values'] = boosted
        try:
            self.boost_drop.current(0)
        except:
            self.boost_drop.set("empty")

    def update_blocked(self):
        self.block_drop['values'] = working_bans
        try:
            self.block_drop.current(0)
        except:
            self.block_drop.set("empty")

    def update_degraded(self):
        self.deg_drop['values'] = degraded
        try:
            self.block_drop.current(0)
        except:
            self.block_drop.set("empty")

    def update_music(self):
        self.music_drop['values'] = music_list.keys()
        try:
            self.block_drop.current(0)
        except:
            self.block_drop.set("empty")
class EpiGui:

    REQ_MASTER_VERSION = 'Epi Master 1.14'

    CURRENT_EPI_ID = -1

    CHOOSE_MASTER = 1
    SET_PARAMS = 2
    SEED_EPIDEMIC = 3

    BUTTON_COL = 16
    TOP = 1
    LEFT = 12

    STATUS_SUSCEPTIBLE = 'green'
    STATUS_INFECTED = 'red'
    STATUS_RECOVERED = 'blue'

    # The defaults are:
    # (1) The ID of an epidemic (so we can distinguish one epidemic from another)
    # (2) Previously used sets of parameters for an epidemic.
    #
    # I store these in a defaults.ini file, with a CSV-like format:-
    # First line is always:    epid,1    -
    # All other lines:         "Param Set",r0_value,"r_type",min_poi,max_poi,transmit_power,exposure_time
    #              eg:         "Default",2,"poisson",1,5,4,10

    # Here I load all the parameter sets...

    def load_defaults(self):
        with open("defaults.ini","r") as ini_file:
            for line in ini_file:
                line = line.replace('\r','')
                line = line.replace('\n','')
                s = line.split(",")

                if ((len(s) == 2) & (s[0] == 'epid')):
                    self.CURRENT_EPI_ID = int(s[1])+1

                elif (len(s)==10):
                    self.paramsets.append(s[0].replace('"', ''))
                    self.p_r0.append(s[1])
                    self.p_rtype.append(s[2])
                    self.p_poimin.append(s[3])
                    self.p_poimax.append(s[4])
                    self.p_rpower.append(s[5])
                    self.p_exposure.append(str(s[6]))
                    self.p_btrans.append(s[7])
                    self.p_brec.append(s[8])
                    self.p_icons.append(s[9])

        self.cb_paramset['values']=self.paramsets
        self.cb_paramset.current(0)
        self.remember_paramset = 0
        self.select_parameterset()

    # Save the defaults.ini file with new data.

    def save_defaults(self):
        out_file = open("defaults.ini", "w")
        out_file.write("epid,{0}\n".format(self.CURRENT_EPI_ID))
        for i in range(0, len(self.paramsets)):
            out_file.write('"{0}",{1},{2},{3},{4},{5},{6},{7},{8},{9}\n'.format(
                self.paramsets[i],
                self.p_r0[i],
                self.p_rtype[i],
                self.p_poimin[i],
                self.p_poimax[i],
                self.p_rpower[i],
                self.p_exposure[i],
                self.p_btrans[i],
                self.p_brec[i],
                self.p_icons[i]))

        out_file.close()

    # Choose a particular parameter set from the list...

    def change_paramset(self, event):
        i = self.cb_paramset.current()
        if (self.remember_paramset != i):
            resp = False
            if (self.b_save_pset['state'] == 'active'):
                resp = tkMessageBox.askyesnocancel(self.lang.save_first, self.lang.save_first_q)
            if (resp == True):
                self.save_params(index = self.remember_paramset)
                resp = False

            # Either... there were no changes, or, there were changes we didn't want to save,
            # Or, there were changes we saved and wanted to continue... resp == False for all 3.

            if (resp == False):
                self.select_parameterset()
                self.remember_paramset = i

    def select_parameterset(self):
        i = self.cb_paramset.current()
        self.sv_r0.set(self.p_r0[i])
        self.cb_rtype.current(int(self.p_rtype[i]))
        self.cb_poimin.current(self.cb_poimin['values'].index(self.p_poimin[i]))
        self.cb_poimax.current(self.cb_poimax['values'].index(self.p_poimax[i]))
        self.cb_rpower.current(self.cb_rpower['values'].index(self.p_rpower[i]))
        self.cb_exposure.current(self.cb_exposure['values'].index(self.p_exposure[i]))
        self.cb_btrans.current(int(self.p_btrans[i]))
        self.cb_brec.current(int(self.p_brec[i]))
        self.cb_icons.current(int(self.p_icons[i]))

        if (len(self.paramsets) > 1):
            self.b_del_pset['state'] = 'active'
        else:
            self.b_del_pset['state'] = 'disabled'
        self.b_save_pset['state'] = 'disabled'

    # Delete a parameter set

    def del_params(self):
        if tkMessageBox.askokcancel(self.lang.delete, self.lang.delete_conf):
            i = self.cb_paramset.current()
            del self.p_r0.remove[i]
            del self.p_rtype[i]
            del self.p_poimax[i]
            del self.p_poimin[i]
            del self.p_rpower[i]
            del self.p_exposure[i]
            del self.p_btrans[i]
            del self.p_brec[i]
            del self.p_icons[i]
            del self.paramsets[i]
            self.b_save_pset['state'] = 'disabled'
            self.cb_paramset['values'] = self.paramsets
            self.cb_paramset.current(min(i, len(self.paramsets) - 1))
            self.save_defaults()
            self.select_parameterset()

    # Save changes to the parameter set structure in RAM.
    # And then write all parameter sets to the file.

    def validate_params(self):
        # Do some validation first.
        valid = True
        try:
            float(self.sv_r0.get())
        except:
            tkMessageBox.showerror(self.lang.error, self.lang.err_r0)
            valid = False

        try:
            int(self.sv_epidno.get())
        except:
            tkMessageBox.showerror(self.lang.error, self.lang.epi_id_err)
            valid = False

        return valid

    # Save parameter config...

    def save_params(self, index = -1):

        # Default: save the currently viewed parameter set (index=-1)
        # If this happened because of a "save unsaved changes", then index can specify
        # which parameter set we want to save.


        if self.validate_params():
            if (index==-1):
                index = self.cb_paramset.current()

            self.p_r0[index] = self.sv_r0.get()
            self.p_rtype[index] = self.cb_rtype.current()
            self.p_poimin[index] = self.cb_poimin.get()
            self.p_poimax[index] = self.cb_poimax.get()
            self.p_rpower[index] = self.cb_rpower.get()
            self.p_exposure[index] = self.cb_exposure.get()
            self.p_btrans[index] = self.cb_btrans.current()
            self.p_brec[index] = self.cb_brec.current()
            self.p_icons[index] = self.cb_icons.current()
            self.save_defaults()
            self.b_save_pset['state']='disabled'

    # Save current settings as a new parameter set

    def saveas_params(self):
        new_name = tkSimpleDialog.askstring(self.lang.name, self.lang.name_pset)

        # Handle cancel / empty string

        if new_name is not None:
            new_name = new_name.strip()
            if (len(new_name) == 0):
                new_name = None

        # Handle duplicate name

        if new_name is not None:
            try:
                self.paramsets.index(new_name)
                tkMessageBox.showerror(self.lang.error, self.lang.dup_pset)
                new_name = None
            except:
                pass

        # Ok, save and select.
        if new_name is not None:
            self.p_exposure.append(self.cb_exposure.get())
            self.p_rpower.append(self.cb_rpower.get())
            self.p_poimin.append(self.cb_poimin.get())
            self.p_poimax.append(self.cb_poimax.get())
            self.p_rtype.append(self.cb_rtype.current())
            self.p_r0.append(self.sv_r0.get())
            self.p_btrans.append(self.cb_btrans.current())
            self.p_brec.append(self.cb_brec.current())
            self.p_icons.append(self.cb_icons.current())
            self.paramsets.append(new_name)
            self.save_defaults()
            self.cb_paramset['values'] = self.paramsets
            self.cb_paramset.current(len(self.cb_paramset['values']) - 1)
            self.select_parameterset()
            self.b_save_pset['state'] = 'disabled'

    # Events where parameters are changed.

    def set_params_unsaved(self, event):
        self.b_save_pset['state'] = 'active'

    def change_poimin(self, event):
        maxv = int(self.cb_poimax.current())
        minv = int(self.cb_poimin.current())
        if (minv>maxv):
            self.cb_poimax.current(minv)

    def change_poimax(self, event):
        maxv = int(self.cb_poimax.current())
        minv = int(self.cb_poimin.current())
        if (maxv<minv):
            self.cb_poimin.current(maxv)

    # Exit confirmation dialogue

    def ask_quit(self):
        if tkMessageBox.askokcancel(self.lang.exit, self.lang.really_exit):
            self.window.destroy()


    def click_set_master(self):
        proceed = False
        if (self.sv_software.get() != self.REQ_MASTER_VERSION):
            tkMessageBox.showerror(self.lang.error, self.lang.mb_master_err)
        else:
            self.set_task_text(self.lang.instructions_2)
            proceed = True

        if (proceed):
            self.b_setMaster['state']='disabled'
            self.b_sendParams['state']='active'
            self.grid_forget_all([self.cb_masters, self.b_rescan, self.l_port,
            self.l_software, self.l_software2,
            self.l_serialno, self.l_serialno2,
            self.l_mbitver, self.l_mbitver2])
            self.l_epidno.grid(column = self.LEFT, row = self.TOP, sticky = "E")
            self.e_epidno.grid(column = 1 + self.LEFT, row = self.TOP, sticky = "W")
            self.l_paramset.grid(column = self.LEFT, row = 1 + self.TOP, sticky = "E")
            self.cb_paramset.grid(column = 1 + self.LEFT, row = 1 + self.TOP, sticky = "W")
            self.b_save_pset.grid(column = 2 + self.LEFT, row = 1 + self.TOP, sticky = "W")
            self.b_del_pset.grid(column = 3 + self.LEFT, row = 1 + self.TOP, sticky = "W")
            self.b_saveas_pset.grid(column = 4 + self.LEFT, row = 1 + self.TOP, sticky = "W")

            self.l_r0.grid(column = self.LEFT, row = 2 + self.TOP, sticky = "E")
            self.e_r0.grid(column = 1 + self.LEFT, row = 2 + self.TOP, sticky = "W")
            self.l_rtype.grid(column = self.LEFT, row = 3 + self.TOP, sticky = "E")
            self.cb_rtype.grid(column = 1 + self.LEFT, row = 3 + self.TOP, sticky = "W")
            self.l_poimin.grid(column = self.LEFT, row = 4 + self.TOP, sticky = "W")
            self.cb_poimin.grid(column = 1 + self.LEFT, row = 4 + self.TOP, sticky = "E")
            self.l_poimax.grid(column = self.LEFT, row = 5 + self.TOP, sticky = "W")
            self.cb_poimax.grid(column = 1 + self.LEFT, row = 5 + self.TOP, sticky = "E")
            self.l_rpower.grid(column = self.LEFT, row = 6 + self.TOP, sticky = "E")
            self.cb_rpower.grid(column = 1 + self.LEFT, row = 6 + self.TOP, sticky = "W")
            self.l_exposure.grid(column = self.LEFT, row = 7 + self.TOP, sticky = "E")
            self.cb_exposure.grid(column = 1 + self.LEFT, row = 7 + self.TOP, sticky = "E")
            self.l_btrans.grid(column = self.LEFT, row = 8 + self.TOP, sticky = "E")
            self.cb_btrans.grid(column = 1 + self.LEFT, row = 8 + self.TOP, sticky = "E")
            self.l_brec.grid(column = self.LEFT, row = 9 + self.TOP, sticky = "E")
            self.cb_brec.grid(column = 1 + self.LEFT, row = 9 + self.TOP, sticky = "E")
            self.l_icons.grid(column = self.LEFT, row = 10 + self.TOP, sticky = "E")
            self.cb_icons.grid(column = 1 + self.LEFT, row = 10 + self.TOP, sticky = "E")


    def update_seed_epi_button(self):
        self.b_seedEpidemic['state'] = 'disabled'
        sid = self.sv_seedid.get()
        if (len(sid)>0):
            sid = int(sid)
            if (self.minions[sid % 10][sid / 10]['bg'] == self.STATUS_SUSCEPTIBLE):
                self.b_seedEpidemic['state'] = 'active'


    def click_send_params(self):
        self.save_defaults()
        self.sv_susc.set('0')
        self.sv_inf.set('0')
        self.sv_recov.set('0')
        self.b_setMaster.grid_forget()
        self.b_sendParams.grid_forget()
        self.b_seedEpidemic.grid(column = 0, row = 18, columnspan = 5)
        self.b_resetEpidemic.grid(column = 5, row = 18, columnspan = 5)
        self.serial_link.send_params()
        self.set_task_text(self.lang.instructions_3)
        self.grid_forget_all([self.l_epidno, self.e_epidno, self.l_paramset, self.cb_paramset,
                self.b_save_pset, self.b_del_pset, self.b_saveas_pset, self.l_r0,
                self.e_r0, self.l_rtype, self.cb_rtype, self.l_poimin, self.cb_poimin,
                self.l_poimax, self.cb_poimax, self.l_rpower, self.cb_rpower,
                self.l_exposure, self.cb_exposure, self.l_brec, self.cb_brec,
                self.l_btrans, self.cb_btrans, self.l_icons, self.cb_icons])

        self.l_epidno.grid(column = self.LEFT, row = 0, sticky = "E")
        self.l_epidconst.grid(column = self.LEFT + 1, row = 0, sticky = "W")
        self.b_screen_off.grid(column = self.LEFT, row=17 + self.TOP)
        self.b_screen_on.grid(column = self.LEFT+1, row=17 + self.TOP)
        
        self.l_seedid.grid(column = self.LEFT, row = self.TOP, sticky = "E")
        self.l_seedid2.grid(column = 1 + self.LEFT, row = self.TOP, sticky = "W")
        self.b_rndseed.grid(column = 2 + self.LEFT, row = self.TOP, sticky = "W")
        self.l_forcer.grid(column = self.LEFT, row = 1 + self.TOP, sticky = "E")
        self.tb_forcer.grid(column = 1 + self.LEFT, row = 1 + self.TOP, sticky = "W")
        self.l_ncons.grid(column = self.LEFT, row = 2 + self.TOP, sticky = "E")
        self.cb_forcer.grid(column = 1 + self.LEFT, row = 2 + self.TOP, sticky = "W")
        self.b_sendParams['state']='disabled'
        self.b_seedEpidemic['state']='disabled'

        self.l_susc.grid(column = self.LEFT, row = 6 + self.TOP, sticky = "E")
        self.l_susc2.grid(column = 1 + self.LEFT, row = 6 + self.TOP, sticky = "E")
        self.l_inf.grid(column = self.LEFT, row = 7 + self.TOP, sticky = "E")
        self.l_inf2.grid(column = 1 + self.LEFT, row = 7 + self.TOP, sticky = "E")
        self.l_recov.grid(column = self.LEFT, row = 8 + self.TOP, sticky = "E")
        self.l_recov2.grid(column = 1 + self.LEFT, row = 8 + self.TOP, sticky = "E")

    def click_seed_epi(self):
        m_id = int(self.sv_seedid.get())
        if (self.minions[m_id % 10][m_id / 10]['bg']==self.STATUS_SUSCEPTIBLE):
            self.serial_link.seed_epidemic()
            self.sv_seedid.set("")
        else:
            tkMessageBox.showerror(self.lang.too_slow, self.lang.no_longer_susc)


    def click_reset_epi(self):
        confirm = tkSimpleDialog.askstring(self.lang.end_epi, self.lang.reset_or_power_off)

        if (confirm == 'RESET') or (confirm == 'POWEROFF'):

            self.grid_forget_all([self.l_seedid, self.l_seedid2, self.b_rndseed, self.l_forcer, self.tb_forcer,
                self.l_ncons, self.cb_forcer, self.b_seedEpidemic, self.b_resetEpidemic, self.l_epidconst, self.l_epidno, 
                self.l_susc, self.l_susc2, self.l_inf, self.l_inf2, self.l_recov, self.l_recov2, self.b_screen_off,
                self.b_screen_on])

            if (confirm == 'RESET'):
                self.serial_link.reset_epidemic()
                self.CURRENT_EPI_ID = 1 + self.CURRENT_EPI_ID
                self.sv_epidno.set(self.CURRENT_EPI_ID)
                self.show_first_interface()

            elif (confirm == 'POWEROFF'):
                self.serial_link.poweroff_minions()

    def click_minion(self, m_id):
        m_id = int(m_id)
        if (self.serial_link.serial_port != 0):
            if (self.minions[m_id % 10][m_id / 10]['bg']==self.STATUS_SUSCEPTIBLE):
                self.sv_seedid.set(m_id)
            else:
                self.sv_seedid.set('')
        self.update_seed_epi_button()

    def click_random_minion(self):
        candidates = 0
        for m_id in range(0, 99):
            if (self.minions[m_id % 10][m_id / 10]['bg']==self.STATUS_SUSCEPTIBLE):
                candidates = candidates + 1

        if (candidates>0):
            r = random.randint(1,candidates)
            for m_id in range(0, 99):
                if (self.minions[m_id % 10][m_id / 10]['bg']==self.STATUS_SUSCEPTIBLE):
                    r = r - 1
                    if (r == 0):
                        self.sv_seedid.set(m_id)
                        self.update_seed_epi_button()
                        break

    def set_minion_status(self, minion_id, status):
        m_id = int(minion_id)
        if (self.minions[m_id % 10][m_id / 10]['bg'] != status):
            self.minions[m_id % 10][m_id / 10]['bg'] = status
            if (status == self.STATUS_SUSCEPTIBLE):
                self.sv_susc.set(str(int(self.sv_susc.get())+1))
            elif (status == self.STATUS_INFECTED):
                self.sv_susc.set(str(int(self.sv_susc.get())-1))
                self.sv_inf.set(str(int(self.sv_inf.get())+1))
            elif (status == self.STATUS_RECOVERED):
                self.sv_inf.set(str(int(self.sv_inf.get())-1))
                self.sv_recov.set(str(int(self.sv_recov.get())+1))

        self.update_seed_epi_button()

    # Update the instructions box for what to do in this stage of the epidemic.

    def set_task_text(self, t):
        self.st_instruct['state'] = 'normal'
        self.st_instruct.delete('1.0', END)
        self.st_instruct.insert('insert', t)
        self.st_instruct['state'] = 'disabled'

    # Remove all the give components from the grid layout.

    def grid_forget_all(self, widgets):
        for widget in widgets:
            widget.grid_forget()

    def click_forcer(self):
        if (self.iv_forcer.get()==0):
            self.cb_forcer['state'] = 'disabled'
        else:
            self.cb_forcer['state'] = 'active'

    def show_first_interface(self):
        self.l_port.grid(column = self.LEFT, row = self.TOP)
        self.cb_masters.grid(column = 1 + self.LEFT, row = self.TOP)
        self.b_rescan.grid(column = 2 + self.LEFT, row = self.TOP)
        self.l_software.grid(column = self.LEFT, row = 1 + self.TOP, sticky = "E")
        self.l_software2.grid(column = 1 + self.LEFT, row = 1 + self.TOP, sticky = "W")
        self.l_serialno.grid(column = self.LEFT, row = 2 + self.TOP, sticky = "E")
        self.l_serialno2.grid(column = 1 + self.LEFT, row = 2 + self.TOP, sticky = "W")
        self.l_mbitver.grid(column = self.LEFT, row = 3 + self.TOP, sticky = "E")
        self.l_mbitver2.grid(column = 1 + self.LEFT, row = 3 + self.TOP, sticky = "W")
        self.set_task_text(self.lang.instructions_1)
        self.b_sendParams['state'] = 'disabled'
        self.b_setMaster['state'] = 'active'

        self.b_setMaster.grid(column = 0, row = 18, columnspan = 5)
        self.b_sendParams.grid(column = 5, row = 18, columnspan = 5)
        for i in range(100):
            self.set_minion_status(i, '#f0f0f0')
            self.inf_reported[i] = 0
            self.rec_reported[i] = 0
                        
        self.serial_link.refresh_microbit_comports()

    def click_screens_off(self):
        self.serial_link.screens_off()
        
    def click_screens_on(self):
        self.serial_link.screens_on()
    # Create the GUI.

    def __init__(self, serial_link):

        # Basic definitions for the GUI components.

        self.window = Tk()
        self.lang = EpiLang()
        self.serial_link = serial_link
        self.serial_link.set_gui_link(self)

        # GUI elements present on all pages.

        self.minions =  [[0 for x in xrange(10)] for y in xrange(10)]
        
        for x in range(10):
            for y in range(10):
                n=((y * 10) + x)
                if (n < 10): n = "0" + str(n)
                self.minions[x][y] = Button(self.window, text = n,
                    command = lambda n1 = n: self.click_minion(n1))
                self.minions[x][y].grid(column = x, row = y)
                
        self.inf_reported = [0 for x in range(100)]
        self.rec_reported = [0 for x in range(100)]

        self.b_setMaster = Button(self.window, text = self.lang.set_master_mb, command = self.click_set_master)
        self.b_sendParams = Button(self.window, text = self.lang.send_params, command = self.click_send_params)
        self.b_seedEpidemic = Button(self.window, text = self.lang.seed_epi, command = self.click_seed_epi)
        self.b_resetEpidemic = Button(self.window, text = self.lang.reset_epi, command = self.click_reset_epi)

        self.l_task = Label(self.window, text = self.lang.current_task)
        self.st_font = tkFont.Font(family = "Calibri", size = 10)
        self.st_instruct = tkst.ScrolledText(self.window, width = 30, height = 5, font = self.st_font,
                                        wrap = 'word', state = 'disabled')


        self.l_task.grid(column = 0, row = 13, columnspan = 10)
        self.st_instruct.grid(column=0, row = 14, columnspan = 10)


        # GUI elements for the Micro:Bit master selection page

        self.l_port = Label(self.window, text = self.lang.using_port)
        self.cb_masters = Combobox(self.window, state = 'readonly')
        self.cb_masters.bind("<<ComboboxSelected>>", self.serial_link.get_master_info)
        self.cb_masters_double_click = 0
        self.b_rescan = Button(self.window, text = self.lang.rescan,
            command = self.serial_link.refresh_microbit_comports)
        self.l_software = Label(self.window, text = self.lang.software)
        self.sv_software = StringVar()
        self.sv_software.set("")
        self.l_software2 = Label(self.window, textvariable = self.sv_software)

        self.l_serialno = Label(self.window, text = self.lang.serial_no)
        self.sv_serialno = StringVar()
        self.l_serialno2 = Label(self.window, textvariable = self.sv_serialno)
        self.l_mbitver = Label(self.window, text = self.lang.mb_version)
        self.sv_mbitver = StringVar()
        self.l_mbitver2 = Label(self.window, textvariable = self.sv_mbitver)

        # GUI elements for the parameter settings page

        self.l_epidno = Label(self.window, text = self.lang.epi_id)
        self.sv_epidno = StringVar()
        self.e_epidno = Entry(self.window, textvariable = self.sv_epidno)
        self.l_epidconst = Label(self.window, textvariable = self.sv_epidno, font=('Arial', 12, 'bold'))

        self.l_paramset = Label(self.window, text = self.lang.saved_params)
        self.cb_paramset = Combobox(self.window, state = 'readonly')
        self.b_save_pset = Button(self.window, text = self.lang.save, command = self.save_params)
        self.b_del_pset = Button(self.window, text = self.lang.delete, command = self.del_params)
        self.b_saveas_pset = Button(self.window, text = self.lang.save_as, command = self.saveas_params)

        self.l_r0 = Label(self.window, text = self.lang.R0)
        self.sv_r0 = StringVar()
        self.e_r0 = Entry(self.window, textvariable = self.sv_r0)
        self.l_rtype = Label(self.window, text = self.lang.R_type)
        self.cb_rtype = Combobox(self.window, state = 'readonly')
        self.l_poimin = Label(self.window, text = self.lang.poi_min);
        self.cb_poimin = Combobox(self.window, state = 'readonly')
        self.l_poimax = Label(self.window, text = self.lang.poi_max);
        self.cb_poimax = Combobox(self.window, state = 'readonly')

        self.l_rpower = Label(self.window, text = self.lang.transmit_range)
        self.cb_rpower = Combobox(self.window, state = 'readonly')
        self.l_exposure = Label(self.window, text = self.lang.exposure)
        self.cb_exposure = Combobox(self.window, state = 'readonly')
        self.l_btrans = Label(self.window, text = self.lang.transmit_button)
        self.cb_btrans = Combobox(self.window, state = 'readonly')
        self.l_brec = Label(self.window, text = self.lang.receive_button)
        self.cb_brec = Combobox(self.window, state = 'readonly')
        self.l_icons = Label(self.window, text = self.lang.icon_set)
        self.cb_icons = Combobox(self.window, state = 'readonly')

        self.cb_rtype['values'] = [self.lang.constant, self.lang.poisson]
        self.cb_rpower['values'] = range(0, 8)
        self.cb_exposure['values'] = [1, 5, 10, 20, 30, 40, 50, 60, 90, 120, 150, 180, 210, 240, 270, 300, 360, 420, 480, 540, 600]
        self.cb_poimin['values'] = range(0, 99)
        self.cb_poimax['values'] = range(1, 100)
        self.cb_btrans['values'] = ['Auto','A','B','A+B']
        self.cb_brec['values'] = ['Auto','A','B','A+B']
        self.cb_icons['values'] = ['SIR', 'I+R', '-I-']

        self.cb_poimin.bind("<<ComboboxSelected>>", self.change_poimin)
        self.cb_poimax.bind("<<ComboboxSelected>>", self.change_poimax)
        self.cb_paramset.bind("<<ComboboxSelected>>", self.change_paramset)
        self.remember_paramset = -1
        self.cb_rtype.bind("<<ComboboxSelected>>", self.set_params_unsaved)
        self.cb_rpower.bind("<<ComboboxSelected>>", self.set_params_unsaved)
        self.cb_exposure.bind("<<ComboboxSelected>>", self.set_params_unsaved)
        self.cb_btrans.bind("<<ComboboxSelected>>", self.set_params_unsaved)
        self.cb_brec.bind("<<ComboboxSelected>>", self.set_params_unsaved)
        self.cb_icons.bind("<<ComboboxSelected>>", self.set_params_unsaved)
        self.e_r0.bind("<Key>", self.set_params_unsaved)

        # Gui Elements for the Seeding / Progress Page

        self.l_seedid = Label(self.window, text = "Victim:")
        self.sv_seedid = StringVar()
        self.l_seedid2 = Label(self.window, textvariable = self.sv_seedid)
        self.b_rndseed = Button(self.window, text = 'Random', command = self.click_random_minion)
        self.l_forcer = Label(self.window, text = "Force contacts")
        self.iv_forcer = IntVar()
        self.iv_forcer.set(1)
        self.tb_forcer = Checkbutton(self.window, text="", variable = self.iv_forcer, command=self.click_forcer)
        self.l_ncons = Label(self.window, text = "No. contacts")
        self.cb_forcer = Combobox(self.window, state = 'readonly')

        self.l_susc = Label(self.window, text = "Susceptible:")
        self.sv_susc = StringVar()
        self.l_susc2 = Label(self.window, textvariable = self.sv_susc)
        self.l_inf = Label(self.window, text="Infected:")
        self.sv_inf = StringVar()
        self.l_inf2 = Label(self.window, textvariable = self.sv_inf)
        self.l_recov = Label(self.window, text = "Recovered:")
        self.sv_recov = StringVar()
        self.l_recov2 = Label(self.window, textvariable = self.sv_recov)

        self.cb_forcer['values'] = range(1,100)
        self.cb_forcer.current(3)
        
        self.b_screen_off = Button(self.window, text = "Screens OFF", command = self.click_screens_off)
        self.b_screen_on = Button(self.window, text = "Screens ON", command = self.click_screens_on)
        

        # Load the previously-saved configurations

        self.paramsets = []
        self.p_r0 = []
        self.p_rtype = []
        self.p_poimin = []
        self.p_poimax = []
        self.p_rpower = []
        self.p_exposure = []
        self.p_btrans = []
        self.p_brec = []
        self.p_icons = []

        self.load_defaults()
        self.sv_epidno.set(self.CURRENT_EPI_ID)

        # Window specific stuff. Set what happens on exit
        # Set the size, title, and application icon for the window.

        self.window.protocol("WM_DELETE_WINDOW", self.ask_quit)
        self.window.title(self.lang.title)
        self.window.geometry("640x480")
        imgicon = PhotoImage(file = os.path.join('microepi.gif'))
        self.window.tk.call('wm', 'iconphoto', self.window._w, imgicon)

        # Show first interface

        self.show_first_interface()

        self.window.mainloop()
Beispiel #51
0
    restart = gui.gui_init()
    while restart:
        restart = gui.gui_init()


root = Tk()
root.overrideredirect(True)
x = (root.winfo_screenwidth() - 600) / 2
y = (root.winfo_screenheight() - 400) / 2
root.geometry('600x400+%d+%d' % (x, y))

with open('settings\\logins.pcl') as filename:
    logins = pickle.load(filename)
    last_user = pickle.load(filename)

back = PhotoImage(file='static//interface//login.pbm')
frame = Canvas(root, relief=GROOVE)
frame.pack(side=TOP, fill=BOTH, expand=YES, padx=2, pady=2)
frame.create_image(0,0, anchor='nw', image=back)

box = Combobox(frame)
box['values'] = logins
box.current(logins.index(last_user))
box.grid(column=0, row=1)

Button(frame, text='Войти', command=login).grid(column=0, row=3, columnspan=2, pady=20)
Button(frame, text='Выход', command=root.destroy).grid(column=0, row=8, columnspan=2, pady=40)

root.mainloop()

# выбор фона и файл настроек, очиcтка списка логинов
class Gui(Frame):
    """ GUI class for Grahphical User Interface"""
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.appdata = AppData()  # to create AppData object
        self.initUI()

    def initUI(self):
        self.pack(fill=BOTH, expand=True)
        Label(self,
              text='Election Data Analysis Tool v1.0',
              bg='red',
              fg='white',
              font=('Arial', 15, 'bold')).pack(fill=X, anchor=N)  # header
        self.load_data_btn = Button(self,
                                    text='Load Election Data',
                                    width=30,
                                    height=2,
                                    command=self.appdata.readfile)
        self.load_data_btn.pack(pady=10, anchor=N)
        self.buttonsframe = Frame(self)  # to keep buttons in frame
        self.buttonsframe.pack(fill=X, anchor=N)
        self.districtsbtn = Button(self.buttonsframe,
                                   text='Cluster Districts',
                                   width=30,
                                   height=3,
                                   command=self.clusterdistricts)
        self.districtsbtn.pack(side=LEFT, padx=(180, 5))
        self.partiesbtn = Button(self.buttonsframe,
                                 text='Cluster Political Parties',
                                 width=30,
                                 height=3,
                                 command=self.clusterparties)
        self.partiesbtn.pack(side=LEFT)
        self.check_dynamic = True  # to check dynamic function is called

    def dynamic(self):
        self.canvasframe = Frame(self)  # to keep canvas
        self.canvasframe.pack(fill=X)
        self.canvas = Canvas(self.canvasframe, bg='grey')
        self.vbar = Scrollbar(self.canvasframe,
                              orient=VERTICAL)  # vertical scrollbar
        self.vbar.pack(side=RIGHT, fill=Y)
        self.vbar.config(
            command=self.canvas.yview)  # to adapt vertical scrollbar to canvas
        self.hbar = Scrollbar(self.canvasframe,
                              orient=HORIZONTAL)  # horizontal scrollbar
        self.hbar.pack(side=BOTTOM, fill=X)
        self.hbar.config(command=self.canvas.xview
                         )  # to adapt horizontal scrollbar to canvas
        self.canvas.pack(fill=X)
        self.canvas.config(
            xscrollcommand=self.hbar.set,
            yscrollcommand=self.vbar.set)  # to set scrollbars in canvas
        self.bottomframe = Frame(self)  # Frame to keep listbox and so on
        self.bottomframe.pack(fill=X)
        Label(self.bottomframe,
              text='Districts:').pack(side=LEFT,
                                      padx=(150, 0))  # districts label
        self.scroll = Scrollbar(self.bottomframe,
                                orient="vertical")  # Scrollbar to listbox
        self.listbox = Listbox(self.bottomframe,
                               selectmode='multiple',
                               yscrollcommand=self.scroll.set)
        self.listbox.pack(side=LEFT)
        self.scroll.config(command=self.listbox.yview
                           )  # to adapt vertical scrollbar to canvas
        self.scroll.pack(side=LEFT, fill="y")
        Label(self.bottomframe, text='Treshould:').pack(side=LEFT)
        self.combo = Combobox(
            self.bottomframe,
            values=['0%', '1%', '10%', '20%', '30%', '40%', '50%'],
            width=5)  # create combobox to keep persantages
        self.combo.pack(side=LEFT)
        self.combo.current(0)
        self.analysisbtn = Button(self.bottomframe,
                                  text="Refine Analysis",
                                  width=30,
                                  height=2,
                                  command=self.refine_analysis)
        self.analysisbtn.pack(side=LEFT)
        for i in sorted(
                self.appdata.districts):  # to append all districts in listbox
            self.listbox.insert(END, i)

    def clusterdistricts(self, persantage=0, selected_text_list=[]):
        if self.check_dynamic:  # to check dynamic func called or not
            self.dynamic()
            self.check_dynamic = False  # after the called dynamic it will be false to don't enter again
        matrix = []  # to keep matrix nested list
        rows = set()  # to keep districts in a list
        for name, dist_obj in sorted(
                self.appdata.districts.items()):  # to move in the districts
            if name in selected_text_list or selected_text_list == []:  # if selected_text list is empty or name in it
                list2append = [
                ]  # to keep parties' vote for a single districts
                rows.add(name)
                for tag in sorted(
                        self.appdata.parties):  # to check all parties
                    try:  # if it gives any error it will go except part
                        if dist_obj.election_results[
                                tag] >= persantage:  # if persantage is less than vote
                            list2append.append(
                                dist_obj.election_results[tag])  # append it
                        else:
                            raise KeyError  # if not less than vote raise a keyerror and enter except part
                    except KeyError:
                        list2append.append(
                            0
                        )  # if less than or not have a that party append 0
                matrix.append(
                    list2append
                )  # to append each districts paries in matrix list
        clust = hcluster(matrix, distance=sim_distance)  # make a cluster
        drawdendrogram(clust, sorted(list(rows)))
        im = Image.open(
            'clusters.jpg')  # to open jpg file and insert in canvas
        self.canvas.image = ImageTk.PhotoImage(im)
        self.canvas.create_image(0, 0, image=self.canvas.image, anchor='nw')
        self.canvas.config(
            scrollregion=self.canvas.bbox(ALL))  # to use all canvas box
        self.cluster = 'districts'  # to define which cluster will be refining

    def clusterparties(self, persantage=0, selected_text_list=[]):
        """ # Same thing with the clusterdistricts method but for the parties """
        if self.check_dynamic:  # to check dynamic
            self.dynamic()
            self.check_dynamic = False  # after the calling dynamic do it false
        matrix = []  # matrix for the votes as a nested list
        rows = set()  # rows list to keep parties' acronyms
        for acronym, party_obj in sorted(self.appdata.parties.items()):
            list2append = []  # to keep each parties votes
            rows.add(acronym)
            for tag in sorted(
                    self.appdata.districts
            ):  # move in a districts as a sorted to be a regular
                if tag in selected_text_list or selected_text_list == []:  # if checkbox not selected or not choosen
                    try:
                        if party_obj.election_results[
                                tag] >= persantage:  # if vote grader and equal to persantage
                            list2append.append(
                                party_obj.election_results[tag]
                            )  # append it in list2append list
                        else:
                            raise KeyError  # if not grater and equal raise KeyError
                    except KeyError:  # if it give an error append 0 in a list
                        list2append.append(0)
            matrix.append(list2append)  # add list2append in a matrix
        clust = hcluster(
            matrix, distance=sim_distance)  # make a cluster with using matrix
        drawdendrogram(clust,
                       sorted(list(rows)))  # draw a dendogram as a jpg file
        im = Image.open('clusters.jpg')
        self.canvas.image = ImageTk.PhotoImage(im)
        self.canvas.create_image(0, 0, image=self.canvas.image, anchor='nw')
        self.canvas.config(scrollregion=self.canvas.bbox(ALL))
        self.cluster = 'parties'  # to define which cluster will be refining

    def refine_analysis(self):
        try:
            pers = self.combo.get().split(
                '%')  # pers to split % from persantage of combobox
            persantage = float(pers[0])  # to convert persantage to float value
            selected_text_list = [
                self.listbox.get(i) for i in self.listbox.curselection()
            ]  # to take all selected districts
            if self.cluster == 'districts':  # to define which cluster will be refining
                self.clusterdistricts(persantage, selected_text_list)
            else:
                self.clusterparties(persantage, selected_text_list)
        except:
            pass  # Eliminate the error case when clicking refine analysis button before the click cluster's button.
Beispiel #53
0
class Frame1(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent, background="white")   
        
        self.parent = parent
        
        self.initUI()
        
    def initUI(self):
        
        self.lbox = Listbox(self, height = 10, width = 55)
        sbar = Scrollbar(self, command=self.lbox.yview)
        sbar.place(x=360, y=240)
        self.lbox.config(yscrollcommand=sbar.set)
        self.lbox.place(x=10, y=240)

        self.lbox.insert('end',  "Interface Básica de Controle dos Motores - v1.0")
        self.lbox.insert('end', "S.O. (%s)"  % (sys.platform))
      
        self.parent.title("Interface básica para controle dos motores - v1.0")
        self.pack(fill=BOTH, expand=1)

        self.opts = ""
        self.cbox = Combobox(self, textvariable=self.opts, state='readonly')
        for n,s in scan():
            self.opts += "%s " % (s)
              
        self.cbox['values'] = self.opts
        if(self.opts != ""):
            self.cbox.current(0)
        self.cbox.place(x=10, y=10)
        "self.cbox.bind('<<ComboboxSelected>>', self.conectar)"

        btConectar = Button(self, text="Conectar", width=10)
        btConectar.bind("<Button-1>", self.conectar)
        btConectar.place(x=200, y=10)
        
        btFrente = Button(self, text="/\\", width=5)
        btFrente.bind("<Button-1>", self.comandoF)
        btFrente.place(x=160, y=100)
        btTraz = Button(self, text="\/", width=5)
        btTraz.bind("<Button-1>", self.comandoT)
        btTraz.place(x=160, y=130)

        btEsqFrente = Button(self, text="/\\", width=5)
        btEsqFrente.place(x=50, y=70)
        btEsqFrente.bind("<Button-1>", self.comandoEF)
        btEsqTraz = Button(self, text="\/", width=5)
        btEsqTraz.place(x=50, y=150)
        btEsqTraz.bind("<Button-1>", self.comandoET)

        btDirFrente = Button(self, text="/\\", width=5)
        btDirFrente.place(x=260, y=70)
        btDirFrente.bind("<Button-1>", self.comandoDF)
        btDirTraz = Button(self, text="\/", width=5)
        btDirTraz.place(x=260, y=150)
        btDirTraz.bind("<Button-1>", self.comandoDT)

        btGiraEsq = Button(self, text=">>", width=5)
        btGiraEsq.place(x=90, y=200)
        btGiraEsq.bind("<Button-1>", self.comandoGE)
        btParar = Button(self, text="-x-", width=5)
        btParar.place(x=160, y=200)
        btParar.bind("<Button-1>", self.comandoP)
        btGiraDir = Button(self, text="<<", width=5)
        btGiraDir.place(x=230, y=200)
        btGiraDir.bind("<Button-1>", self.comandoGD)  
        

    def conectar(self, event):
        self.lbox.insert('end', "conectando...")
        self.lbox.insert('end', "Porta:", self.cbox.get())
        self.lbox.insert('end', "Baund: 9600")

        self.arduino = None   

        try:
            self.arduino = serial.Serial(self.cbox.get(), 9600);
            self.lbox.insert('end', "Conectado! \n")
        
            try:
               self.lbox.insert('end', self.arduino.readline() )
               self.lbox.insert('end', self.arduino.readline())
               self.lbox.insert('end', self.arduino.readline())
               self.lbox.insert('end', self.arduino.readline())
                   
            except serial.serialutil.SerialException:
               pass
        except:
            pass
        finally:
            if self.arduino:
                "self.arduino.close()"
                pass
            
    def comandoP(self, event):
        self.lbox.insert('0', "Comando 3000")
        try:
            self.arduino.write("3000\n")
            self.lbox.insert('0', self.arduino.readline() )
        except:
            pass
        
    def comandoF(self, event):
        self.lbox.insert('0', "Comando 3300")
        try:
            self.arduino.write("3300\n")
            self.lbox.insert('0', self.arduino.readline() )
        except:
            pass

    def comandoT(self, event):
        self.lbox.insert('0', "Comando 3700")
        try:
            self.arduino.write("3700\n")
            self.lbox.insert('0', self.arduino.readline() )
        except:
            pass

    def comandoEF(self, event):
        self.lbox.insert('0', "Comando 2300")
        try:
            self.arduino.write("2300\n")
            self.lbox.insert('0', self.arduino.readline())
        except:
            pass

    def comandoET(self, event):
        self.lbox.insert('0', "Comando 2700")
        try:
            self.arduino.write("2700\n")
            self.lbox.insert('0',  self.arduino.readline())
        except:
            pass

    def comandoDF(self, event):
        self.lbox.insert('0',  "Comando 1300")
        try:
            self.arduino.write("1300\n")
            self.lbox.insert('0',  self.arduino.readline())
        except:
            pass

    def comandoDT(self, event):
        self.lbox.insert('0',  "Comando 1700")
        try:
            self.arduino.write("1700\n")
            self.lbox.insert('0',  self.arduino.readline())
        except:
            pass

    def comandoGE(self, event):
        self.lbox.insert('0',  "Comando 4300")
        try:
            self.arduino.write("4300\n")
            self.lbox.insert('0',  self.arduino.readline() )
        except:
            pass

    def comandoGD(self, event):
        self.lbox.insert('0',  "Comando 4700")
        try:
            self.arduino.write("4700\n")
            self.lbox.insert('0',  self.arduino.readline() )
        except:
            pass
Beispiel #54
0
class oknoGUI(object):
    def __init__(self):
        self.oknoGlowne = Tk()
	self.okno = None
        self.okno_szer = 250
        self.okno_wys = 250
        self.siec=tworzenie_sieci();
        self.img = None
        self.rysowanie = None
        self.inicjacja()

    def inicjacja(self):
        self.oknoGlowne.title( "OCR CYFR" )
	self.oknoGlowne.geometry('252x500')
        self.okno = Canvas(self.oknoGlowne, width=self.okno_szer, height=self.okno_wys, bg='black')
	self.okno.place(x=0, y=0)
        self.okno.bind( "<B1-Motion>", self.maluj )

        self.img = Image.new('RGB', (self.okno_szer, self.okno_wys), 'black')
        self.rysowanie = ImageDraw.Draw(self.img)

	label3=Label(self.oknoGlowne,text="wynik ",fg="black")
	label3.place(x=10, y=251)
	
	self.wynik=Entry(self.oknoGlowne)
	self.wynik.place(x=75, y=251)

        self.odczytButton = Button(self.oknoGlowne, text='Odczytaj', command=self.odczytaj, anchor = SW)
        self.odczytButton.place(x=10, y=281)

        self.wyczyscButton = Button(self.oknoGlowne, text='Wyczysc', command=self.wyczysc, anchor = NW)
        self.wyczyscButton.place(x=100, y=281)
	
	self.testButton = Button(self.oknoGlowne, text='Test', command=self.test, anchor = SW)
        self.testButton.place(x=190, y=281)
	
	label1=Label(self.oknoGlowne,text="liczba iteracji treningu",fg="black")
	label1.place(x=0, y=311)

	data=(1,2,3,4,5,6,7,8,9,10)
	self.liczba_iteracji=Combobox(self.oknoGlowne,values=data,width=5)
	self.liczba_iteracji.current(0)
	self.liczba_iteracji.place(x=150, y=311)	

        self.uczenieButton= Button(self.oknoGlowne, text='uczenie', command=self.ucz, anchor = S)
	self.uczenieButton.place(x=100, y=331)
 	
	label3=Label(self.oknoGlowne,text="nazwa pliku",fg="black")
	label3.place(x=1, y=371)

	self.nazwa_pliku_1=Entry(self.oknoGlowne,width=15)
	self.nazwa_pliku_1.insert(END,'siec.h5')
	self.nazwa_pliku_1.place(x=100, y=371)

	self.ladujButton= Button(self.oknoGlowne, text='ladowanie', command=self.laduj, anchor = S)
	self.ladujButton.place(x=100, y=391)
	
	label2=Label(self.oknoGlowne,text="nazwa pliku",fg="black")
	label2.place(x=1, y=431)
	
	self.nazwa_pliku=Entry(self.oknoGlowne,text='siec.h5',width=15)
	self.nazwa_pliku.insert(END,'siec.h5')
	self.nazwa_pliku.place(x=100, y=431)

	self.zapiszButton = Button(self.oknoGlowne, text='zapisz', command=self.zapisz, anchor = S)
	self.zapiszButton.place(x=100, y=451)	
		
        mainloop()
        self.img.close()

        img = Image.open('img/temp.jpg')
        img = img.resize((28,28))
        img.save('img/temp.jpg')
        img.close()

    def wyczysc(self):
        self.okno.delete("all")
        self.img = Image.new('RGB', (self.okno_szer, self.okno_wys), 'black')
        self.rysowanie = ImageDraw.Draw(self.img)
	self.wynik.delete(0,END)

    def odczytaj(self):
        plik="img/temp.jpg"
        self.img.save(plik)
	wynik_img=odczyt_img(plik,self.siec)
	print('\nwynik: ')
	print(wynik_img)
	self.wynik.insert(END,wynik_img)
	
 	self.okno.delete("all")
	self.img = Image.new('RGB', (self.okno_szer, self.okno_wys), 'black')
        self.rysowanie = ImageDraw.Draw(self.img)

    def ucz(self):
	self.odczytButton.config(state="disable")
	self.wyczyscButton.config(state="disable")
	self.uczenieButton.config(state="disable")
	self.zapiszButton.config(state="disable")
	self.ladujButton.config(state="disable")
	self.testButton.config(state="disable")
	self.okno.config(state="disable")
	self.oknoGlowne.update()

	iteracja=int(self.liczba_iteracji.get())

	if iteracja > 0 and iteracja < 11:
       		try:
			self.siec=uczenie_sieci(self.siec,iteracja)
			tkMessageBox.showinfo('sykces', 'Uczenie Zakonczone!')
		except:
			tkMessageBox.showerror('Error', 'nieznany blad uczenia sie!')
		
	else:
		tkMessageBox.showerror('Error', 'bledna liczba iteracji!')

        self.okno.config(state="normal")
        self.odczytButton.config(state="normal")
	self.wyczyscButton.config(state="normal")
	self.uczenieButton.config(state="normal")
	self.zapiszButton.config(state="normal")
	self.ladujButton.config(state="normal")
	self.testButton.config(state="normal")
	self.oknoGlowne.update()
  
    def zapisz(self):
	nazwa=self.nazwa_pliku.get()

	if len(nazwa) != 0 :
		zapsi_model(self.siec, nazwa)
		tkMessageBox.showinfo("sykces", "Zapisano pomyslnie!")
	else:
		tkMessageBox.showerror('Error', 'brak nazwy pliku!')

	
    def laduj(self):
	self.odczytButton.config(state="disable")
	self.wyczyscButton.config(state="disable")
	self.uczenieButton.config(state="disable")
	self.zapiszButton.config(state="disable")
	self.ladujButton.config(state="disable")
	self.testButton.config(state="disable")
	self.okno.config(state="disable")
	self.oknoGlowne.update()
		
	nazwa=self.nazwa_pliku_1.get()

	if len(nazwa)!=0:
        	self.siec=wczytaj_model(nazwa)
		tkMessageBox.showinfo('sykces', 'Zaladowano pomylnie!')
	else:
		tkMessageBox.showerror('Error', 'brak nazwy pliku!')

	self.okno.config(state="normal")
        self.odczytButton.config(state="normal")
	self.wyczyscButton.config(state="normal")
	self.uczenieButton.config(state="normal")
	self.zapiszButton.config(state="normal")
	self.ladujButton.config(state="normal")
	self.testButton.config(state="normal")
	self.oknoGlowne.update()
	
    def test(self):
	self.odczytButton.config(state="disable")
	self.wyczyscButton.config(state="disable")
	self.uczenieButton.config(state="disable")
	self.zapiszButton.config(state="disable")
	self.ladujButton.config(state="disable")
	self.testButton.config(state="disable")
	self.okno.config(state="disable")
	self.oknoGlowne.update()

	self.wynik.delete(0,END)
	self.wynik.insert(END,test_mnist(self.siec)) 
	
	self.okno.config(state="normal")
        self.odczytButton.config(state="normal")
	self.wyczyscButton.config(state="normal")
	self.uczenieButton.config(state="normal")
	self.zapiszButton.config(state="normal")
	self.ladujButton.config(state="normal")
	self.testButton.config(state="normal")
	self.oknoGlowne.update()

    def maluj(self, clik):
        x1, y1 = clik.x, clik.y
        x2, y2 = ( clik.x + 10), ( clik.y + 10 )
        self.okno.create_oval( x1, y1, x2, y2, fill = "#FFFFFF", width=0 )
        self.rysowanie.ellipse([x1,y1,x2,y2], fill='white')