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 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
class SelectGame(tkSimpleDialog.Dialog, object): """Server settings window class.""" def __init__(self, *args, **kwargs): """Initiates SelectGame instance with additional attributes. :param args: positional arguments - positional arguments passed to parent __init__ method :param kwargs: keyword arguments - keyword arguments passed to parent __init__ method """ self.select_game, self.num_players, self.num_turns = None, None, None super(SelectGame, self).__init__(*args, **kwargs) def body(self, master): """Creates select game window. :param master: instance - master widget instance :return: Entry instance """ self.resizable(False, False) Label(master, text='Type in new game title or select existing one').grid(row=0, columnspan=2) Label(master, text='Select game:').grid(row=1, sticky='W') Label(master, text='Number of players:').grid(row=2, sticky='W') Label(master, text='Game duration:').grid(row=3, sticky='W') self.select_game = Combobox(master) self.select_game.bind('<Button-1>', self.refresh_games) self.select_game.grid(row=1, column=1, sticky='W') self.num_players = Entry(master) self.num_players.insert(END, self.parent.num_players if self.parent.num_players else '') self.num_players.grid(row=2, column=1, sticky='W') self.num_turns = Entry(master) self.num_turns.insert(END, self.parent.num_turns if self.parent.num_turns else '') self.num_turns.grid(row=3, column=1, sticky='W') return self.select_game def apply(self): """Assigns entered values to parent game and num_players attributes.""" self.parent.game = self.select_game.get() if self.select_game.get() != '' else None if self.parent.game not in self.parent.available_games: self.parent.num_players = int(self.num_players.get()) if self.num_players.get().isdigit() else None self.parent.num_turns = int(self.num_turns.get()) if self.num_turns.get().isdigit() else None def refresh_games(self, _): """Refreshes games list.""" self.select_game.configure(values=self.parent.available_games)
class PreferencesDialog(Dialog): def __init__(self, parent, title, font, size): self._master = parent self.result = False self.font = font self.size = size Dialog.__init__(self, parent, title) def body(self, master): self._npFrame = LabelFrame(master, text='Annotation window text') self._npFrame.pack(fill=X) self._fontFrame = Frame(self._npFrame, borderwidth=0) self._fontLabel = Label(self._fontFrame, text='Font:', width=5) self._fontLabel.pack(side=LEFT, padx=3) self._fontCombo = Combobox(self._fontFrame, values=sorted(families()), state='readonly') self._fontCombo.pack(side=RIGHT, fill=X) self._sizeFrame = Frame(self._npFrame, borderwidth=0) self._sizeLabel = Label(self._sizeFrame, text='Size:', width=5) self._sizeLabel.pack(side=LEFT, padx=3) self._sizeCombo = Combobox(self._sizeFrame, values=range(8, 15), state='readonly') self._sizeCombo.pack(side=RIGHT, fill=X) self._fontFrame.pack() self._sizeFrame.pack() self._npFrame.pack(fill=X) self._fontCombo.set(self.font) self._sizeCombo.set(self.size) def apply(self): self.font = self._fontCombo.get() self.size = self._sizeCombo.get() self.result = True def cancel(self, event=None): if self.parent is not None: self.parent.focus_set() self.destroy()
class PreferencesDialog(Dialog): def __init__(self, parent, title, font, size): self._master = parent self.result = False self.font = font self.size = size Dialog.__init__(self, parent, title) def body(self, master): self._npFrame = LabelFrame(master, text='Annotation window text') self._npFrame.pack(fill=X) self._fontFrame = Frame(self._npFrame, borderwidth=0) self._fontLabel = Label(self._fontFrame, text='Font:', width=5) self._fontLabel.pack(side=LEFT, padx=3) self._fontCombo = Combobox(self._fontFrame, values=sorted(families()), state='readonly') self._fontCombo.pack(side=RIGHT, fill=X) self._sizeFrame = Frame(self._npFrame, borderwidth=0) self._sizeLabel = Label(self._sizeFrame, text='Size:', width=5) self._sizeLabel.pack(side=LEFT, padx=3) self._sizeCombo = Combobox(self._sizeFrame, values=range(8,15), state='readonly') self._sizeCombo.pack(side=RIGHT, fill=X) self._fontFrame.pack() self._sizeFrame.pack() self._npFrame.pack(fill=X) self._fontCombo.set(self.font) self._sizeCombo.set(self.size) def apply(self): self.font = self._fontCombo.get() self.size = self._sizeCombo.get() self.result = True def cancel(self, event=None): if self.parent is not None: self.parent.focus_set() self.destroy()
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()
class MyEntry: #Класс для уменьшений объёма кода однотипных элементов для ввода параметров. def __init__(self, place_class, string_class, DefaultValue, choise_class = False, button_add = False): #При создании принимается место прикрепления виджета и строковое значение для надписи. # A string value to add a combobox or a button could be also inputed. def button_finfo(): messagebox.showinfo(locale(u"ui_iftxt", Settingz["str_langu"]), button_add) # Here it is a function to show information window. self.frame_class = Frame(place_class) self.frame_class.pack(side = TOP, fill = BOTH) #Внутри – рамка для виджетов, растягивается по ширине окна. self.label_class = Label(self.frame_class, text = string_class) self.label_class.pack(side = LEFT) #В ней – надписи для описания вводимых значений выровнены по левому краю. self.entry_class = Entry(self.frame_class, width = 15) self.entry_class.pack(side = RIGHT) self.entry_class.insert(0, DefaultValue) #И элементы для ввода значений шириной в 15 знаков выровнены по правому краю. if choise_class: self.box_class = Combobox(self.frame_class, values = choise_class, width = 2) self.box_class.set(choise_class[0]) self.box_class.pack(side = RIGHT) elif button_add: self.button_class = Button(self.frame_class, text = u"?", command = button_finfo, width = -1) self.button_class.pack(side = RIGHT) # The combobox widget or the button will be created if it is set. def get(self): return(self.entry_class.get()) #Метод .get() передаётся от элемента для ввода объекту описываемого класса. def getbox(self): if self.box_class.get() in ["+", "~"]: return(True) else: return(False)
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)
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))
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()
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.
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
class Application(Frame): def __init__(self, master=None, config=config): self.config = config self.log = logging.getLogger("{0}.{1}".format(self.__class__.__name__, id(self))) self.display_connections = False Frame.__init__(self, master) self.grid() Style().configure("TFrame", background="#444") self.paint_tile = 1 self.init_ui() def init_ui(self): self.connections = {} self.button_frame = Frame(self) self.button_frame.grid(row=0, column=0, columnspan=2) self.map_frame = Frame(self) self.map_frame.grid(row=1, column=0, padx=5, pady=5) self.picker_frame = Frame(self) self.picker_frame.grid(row=1, column=1) self.button_new = Button(self.button_frame) self.button_new["text"] = "New" self.button_new["command"] = self.new_map self.button_new.grid(row=0, column=0, padx=2) self.open = Button(self.button_frame) self.open["text"] = "Open" self.open["command"] = self.open_map self.open.grid(row=0, column=1, padx=2) self.save = Button(self.button_frame) self.save["text"] = "Save" self.save["command"] = self.save_map self.save.grid(row=0, column=2, padx=2) self.get_map_list() self.map_list.grid(row=0, column=3, padx=2) def get_map_list(self): self.available_maps = sorted(m for m in get_available_maps(config=self.config)) self.map_list = Combobox(self.button_frame, height=24, width=24, values=self.available_maps) if len(self.available_maps): self.map_list.set(self.available_maps[0]) def new_map(self): self.map_name = None self.init_map() self.map.blockdata_filename = os.path.join(self.config.map_dir, 'newmap.blk') self.map.blockdata = bytearray([self.paint_tile] * 20 * 20) self.map.width = 20 self.map.height = 20 self.draw_map() self.init_picker() def open_map(self): self.map_name = self.map_list.get() self.init_map() self.draw_map() self.init_picker() def save_map(self): if hasattr(self, 'map'): if self.map.blockdata_filename: filename = tkFileDialog.asksaveasfilename(initialfile=self.map.blockdata_filename) with open(filename, 'wb') as save: save.write(self.map.blockdata) self.log.info('blockdata saved as {}'.format(self.map.blockdata_filename)) else: self.log.info('dunno how to save this') else: self.log.info('nothing to save') def init_map(self): if hasattr(self, 'map'): self.map.kill_canvas() self.map = Map(self.map_frame, self.map_name, config=self.config) self.init_map_connections() def draw_map(self): self.map.init_canvas(self.map_frame) self.map.canvas.pack() #.grid(row=1,column=1) self.map.draw() self.map.canvas.bind('<Button-1>', self.paint) self.map.canvas.bind('<B1-Motion>', self.paint) def init_picker(self): self.current_tile = Map(self.button_frame, tileset_id=self.map.tileset_id, config=self.config) self.current_tile.blockdata = [self.paint_tile] self.current_tile.width = 1 self.current_tile.height = 1 self.current_tile.init_canvas() self.current_tile.draw() self.current_tile.canvas.grid(row=0, column=4, padx=4) if hasattr(self, 'picker'): self.picker.kill_canvas() self.picker = Map(self, tileset_id=self.map.tileset_id, config=self.config) self.picker.blockdata = range(len(self.picker.tileset.blocks)) self.picker.width = 4 self.picker.height = len(self.picker.blockdata) / self.picker.width self.picker.init_canvas(self.picker_frame) if hasattr(self.picker_frame, 'vbar'): self.picker_frame.vbar.destroy() self.picker_frame.vbar = Scrollbar(self.picker_frame, orient=VERTICAL) self.picker_frame.vbar.pack(side=RIGHT, fill=Y) self.picker_frame.vbar.config(command=self.picker.canvas.yview) self.picker.canvas.config(scrollregion=(0,0,self.picker.canvas_width, self.picker.canvas_height)) self.map_frame.update() self.picker.canvas.config(height=self.map_frame.winfo_height()) self.picker.canvas.config(yscrollcommand=self.picker_frame.vbar.set) self.picker.canvas.pack(side=LEFT, expand=True) self.picker.canvas.bind('<4>', lambda event : self.scroll_picker(event)) self.picker.canvas.bind('<5>', lambda event : self.scroll_picker(event)) self.picker_frame.vbar.bind('<4>', lambda event : self.scroll_picker(event)) self.picker_frame.vbar.bind('<5>', lambda event : self.scroll_picker(event)) self.picker.draw() self.picker.canvas.bind('<Button-1>', self.pick_block) def scroll_picker(self, event): if event.num == 4: self.picker.canvas.yview('scroll', -1, 'units') elif event.num == 5: self.picker.canvas.yview('scroll', 1, 'units') def pick_block(self, event): block_x = int(self.picker.canvas.canvasx(event.x)) / (self.picker.tileset.block_width * self.picker.tileset.tile_width) block_y = int(self.picker.canvas.canvasy(event.y)) / (self.picker.tileset.block_height * self.picker.tileset.tile_height) i = block_y * self.picker.width + block_x self.paint_tile = self.picker.blockdata[i] self.current_tile.blockdata = [self.paint_tile] self.current_tile.draw() def paint(self, event): block_x = event.x / (self.map.tileset.block_width * self.map.tileset.tile_width) block_y = event.y / (self.map.tileset.block_height * self.map.tileset.tile_height) i = block_y * self.map.width + block_x if 0 <= i < len(self.map.blockdata): self.map.blockdata[i] = self.paint_tile self.map.draw_block(block_x, block_y) def init_map_connections(self): if not self.display_connections: return for direction in self.map.connections.keys(): if direction in self.connections.keys(): if hasattr(self.connections[direction], 'canvas'): self.connections[direction].kill_canvas() if self.map.connections[direction] == {}: self.connections[direction] = {} continue self.connections[direction] = Map(self, self.map.connections[direction]['map_name'], config=self.config) if direction in ['north', 'south']: x1 = 0 y1 = 0 x2 = x1 + eval(self.map.connections[direction]['strip_length'], self.config.constants) y2 = y1 + 3 else: # east, west x1 = 0 y1 = 0 x2 = x1 + 3 y2 = y1 + eval(self.map.connections[direction]['strip_length'], self.config.constants) self.connections[direction].crop(x1, y1, x2, y2) self.connections[direction].init_canvas(self.map_frame) self.connections[direction].canvas.pack(side={'west':LEFT,'east':RIGHT}[direction]) self.connections[direction].draw()
class main: def __init__(self, master): #-----------------------Interface gráfica---------------------------------------------------- self.frame1 = Frame(master, bg = COR_FUNDO) self.frame1.place(relheight = 1.0, relwidth = 1.0) self.botao_refresh = Button(self.frame1, text = 'Atualizar dispositivos', font = ('Courier','10'), fg = 'black', bg = COR_BOTAO_2, borderwidth = 3, command = self.devices) self.botao_refresh.place(relx = 0.202, rely = 0.02, relwidth = 0.54) Label(self.frame1, text = 'Escolha o dispositivo(CUIDADO)', font=('Courier','14'), fg = 'red', bg = COR_FUNDO).place(relx = 0.02, rely = 0.12) self.device = Combobox(self.frame1, font = ('Ariel','15')) self.device.place(relx = 0.04, rely = 0.20, relwidth = 0.90) Label(self.frame1, text='Escolha o Sistema de arquivos', font=('Courier','14'), fg = 'white', bg = COR_FUNDO).place(relx = 0.02, rely = 0.32) self.sis = Combobox(self.frame1, font = ('Ariel','15')) self.sis.place(relx = 0.04, rely = 0.40, relwidth = 0.90) self.botao_formatar = Button(self.frame1, text = 'Formatar', font = ('Courier','25'), fg = 'black', bg = COR_BOTAO_1, borderwidth = 3, command = self.formatar) self.botao_formatar.bind("<Button-1>", self.mudabotao) self.botao_formatar.place(relx = 0.21, rely = 0.82, relwidth = 0.54) self.devices() self.sis_file() #----------------------Funções--------------------------------------------------------------- def devices(self): #devices = subprocess.check_output(['cat','/proc/partitions']).split('\n') self.device['values'] = USBdrv().mounted_drvs def sis_file(self): sis_file = ['ext2','vfat','ntfs','reiserfs'] self.sis['values'] = sis_file def mudabotao(self,event): self.botao_formatar['text'] = 'Espere' def formatar(self): dv = self.device.get() st = self.sis.get() try: subprocess.call(['umount','%s'%dv]) if st == 'vfat': subprocess.call(['mkfs.vfat', '%s' %dv]) elif st == 'ntfs': subprocess.call(['mkfs.ntfs', '%s' %dv]) elif st == 'reiserfs': subprocess.call(['mkfs.reiserfs', '%s' %dv]) else: subprocess.call(['mkfs.ext2', '%s' %dv]) tkMessageBox.showinfo('Aviso!',u'Device formatado com sucesso') except: tkMessageBox.showinfo('Erro!',u'Device ocupado, ou inválido, ou você não é root') self.devices() self.botao_formatar['text'] = 'Formatar'
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()
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)
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()
# 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) def clicked(): print(selected.get())
class UIBidding(Notify): class CoincheException(Exception): def __init__(self, pid): self.pid = pid def __init__(self, root, x, y, size_x, size_y): Notify.__init__(self) # Memorise the frame self._root = root self._frame = Frame(width = size_x, height = size_y) # No resize self._frame.pack_propagate(0) # Style self._frame.config(borderwidth = 5) self._x = x self._y = y # Init the buttons self._init_buttons() # Will be used to notify the main thread when waiting for a call self.need_bid_event = Event() # Will be used to notify the main thread when waiting for a coinche self.coinche_event = Event() self.pid = 0 self._last_bid = None self.enable() def display(self): """ Display the widget on the table """ self._frame.place(in_ = self._root, x = self._x, y = self._y) def hide(self): """ Hide the pannel when the biddings are closed for example """ self._frame.place_forget() def _init_color_buttons(self): """ Init the buttons to select the color """ # Dedicated frame for buttons self._buttons_frame = Frame() # This dictionnary will contains all the color buttons self._buttons = dict() # Several colors are available colors = list(Bidding.colors) colors.pop() # The buttons need to have a fixed size h = 2 w = 2 for c in colors: self._buttons[c] = Button(self._buttons_frame, text=c, \ height=h, width=w, \ command=lambda c=c: self._click_color(c)) self._buttons[c].pack(side = LEFT) # Pack the dedicated frame into the main frame self._buttons_frame.pack(in_ = self._frame) self._selected_color = None def _init_value_box(self): """ Init the list box which select the value of the bid """ availableValue = Bidding.values # TODO: display "pass" instead of "0" #availableValue[0] = "pass" self._value_box = Combobox(self._frame, \ values = availableValue, \ # TODO # Only justify the selected value #justify = RIGHT, \ state = 'readonly') self._value_box.bind("<<ComboboxSelected>>", lambda x: self._update_bid_button()) self._value_box.set(availableValue[0]) self._value_box.pack(fill = X) @staticmethod def raise_(e): raise e def _init_bid_button(self): # To bid self._bid_button = Button(self._frame, text = "Pass", \ command = self._click_bidding) self._bid_button.pack(fill = X) # To coinche self._coinche_button = Button(self._frame, text = "Coinche", \ command = lambda: self._event[EVT_UI_COINCHE]()) self._coinche_button.pack(fill = X) def _init_buttons(self): """ Init the buttons """ # Put the value box on top of the buttons self._init_value_box() self._init_color_buttons() self._init_bid_button() def _click_color(self, color): self._selected_color = color self._update_bid_button() def _click_bidding(self): """ Callback function on bidding click """ if self._bid_button.config('text')[-1] == "Pass": self._last_bid = Bidding(self.pid) else: if self._selected_color is None: self._event[CONSOLE_RED]("Choose a color!") return c = self._selected_color v = int(self._value_box.get()) self._last_bid = Bidding(self.pid, v, c) # Notify the consumer (main thread) self.need_bid_event.set() # Reset the event self.need_bid_event.clear() def _click_coinche(self): # Notify the consumer self.coinche_event.set() # Reset the event self.coinche_event.clear() def _update_bid_button(self): value = self._value_box.get() color = self._selected_color if value == "0" and color is None: self._bid_button.config(text = "Pass") elif value == "0": self._bid_button.config(text = "Bid " + color) elif color is None: self._bid_button.config(text = "Bid " + value) else: self._bid_button.config(text = "Bid " + value + " " + color) @property def last_bid(self): return self._last_bid @last_bid.setter def last_bid(self, value): if value is None: self._bid_button.config(text = "Pass") self._last_bid = None else: raise Exception("Should not be called") def disable(self): """ Disable the bid button """ self._bid_button.config(state = DISABLED) def enable(self): """ Enable the bid button """ self._bid_button.config(state = NORMAL)
class ConnectGui: def __init__(self,root): root.title("Connect Four") self.turn= 1 self.last_piece= None self.p1= None self.p2= None frame = Frame(root) frame.pack(side=TOP) label1 = Label(frame, text="Player 1:") label1.pack(side= LEFT) self.combobox = Combobox(frame, values= ('Human', 'Minimax', 'Random')) self.combobox.pack(side=LEFT) label2 = Label(frame, text="Player 2:") label2.pack(side=LEFT) self.combobox1 = Combobox(frame, values= ('Human', 'Minimax','Random')) self.combobox1.pack(side= LEFT) frame2= Frame(root) frame2.pack(side=TOP) label3= Label(frame2, text= "(If Minimax Chosen) Ply-Depth:") label3.pack(side= LEFT) self.spinner = Spinbox(frame2,width=5,from_=2, to=5) self.spinner.pack(side= LEFT ) playbutton = Button(frame2, text= "Start Game", command= self.play_game) playbutton.pack(side= LEFT, padx= 20) frame1= Frame(root) frame1.pack(side=TOP) for x in range(7): button0 = Button(frame1, text= "Column %i" %(x+1), command = functools.partial(self.human_turn,x)) button0.grid(row=0, column= x) self.b= connectfour.ConnectFour() self.board= Canvas(frame1, width= 705, height= 605) self.board.grid(row= 1, columnspan=7) #for x in range(7): # self.board.create_line(5, x*100+5, 705,x*100+5) #for x in range(8): # self.board.create_line(x*100+5, 5, x*100+5, 605) def human_turn(self, col): assert self.p1 and self.p2!= None assert self.b.is_game_over()== None if self.b.board[5][col]== None: y= 0 while self.b.board[y][col]!= None: y+=1 self.b.play_turn(self.turn, col) if self.last_piece!= None: self.board.itemconfig(self.last_piece, outline= "black", width= 1) if self.turn== 1: self.last_piece= self.board.create_oval(100*col+5,505-100*y,100*col+105,605-100*y, fill= "red", outline= "green", width= 5) self.turn=2 if self.b.is_game_over()!= None: win= self.b.is_game_over() for i in range(4): self.board.create_oval(100*(win[1]+i*win[3])+5,505-100*(win[0]+i*win[2]),100*(win[1]+i*win[3])+105,605-100*(win[0]+i*win[2]), outline= "blue", width= 7) return if self.p2== "Human": pass elif self.p2== "Random": return self.random_turn() elif self.p2== "Minimax": return self.minimax_turn() elif self.turn==2: self.last_piece=self.board.create_oval(100*col+5,505-100*y,100*col+105,605-100*y, fill= "yellow", outline= "green", width= 5) self.turn=1 if self.b.is_game_over()!= None: win= self.b.is_game_over() for i in range(4): self.board.create_oval(100*(win[1]+i*win[3])+5,505-100*(win[0]+i*win[2]),100*(win[1]+i*win[3])+105,605-100*(win[0]+i*win[2]), outline= "blue", width= 7) return if self.p1== "Human": pass elif self.p1== "Random": return self.random_turn() elif self.p1== "Minimax": return self.minimax_turn() def random_turn(self): if self.last_piece!= None: self.board.itemconfig(self.last_piece, outline= "black", width= 1) cols = [] for col in range(7): if self.b.get_position(5, col) == None: cols.append(col) col= random.choice(cols) if self.b.board[5][col]== None: y= 0 while self.b.board[y][col]!= None: y+=1 self.b.play_turn(self.turn, col) if self.turn== 1: self.last_piece= self.board.create_oval(100*col+5,505-100*y,100*col+105,605-100*y, fill= "red", outline= "green", width= 5) self.turn=2 elif self.turn==2: self.last_piece=self.board.create_oval(100*col+5,505-100*y,100*col+105,605-100*y, fill= "yellow", outline= "green", width= 5) self.turn=1 if self.b.is_game_over()!= None: win= self.b.is_game_over() for i in range(4): self.board.create_oval(100*(win[1]+i*win[3])+5,505-100*(win[0]+i*win[2]),100*(win[1]+i*win[3])+105,605-100*(win[0]+i*win[2]), outline= "blue", width= 7) def minimax_turn(self): if self.last_piece!= None: self.board.itemconfig(self.last_piece, outline= "black", width= 1) player= minimax.MinimaxPlayer(playernum=self.turn, ply_depth=int(self.spinner.get()), utility=utility.WithColumnUtility(5, 10, [1, 2, 3, 4, 3, 2, 1])) root = minimax.MinimaxNode.init_root(self.b, self.turn) childval = player.minimax(root, 0) for child in root.children: if child.get_minimax_value() == childval: col= child.from_parent_column y=0 while self.b.board[y][col]!= None: y+=1 self.b.play_turn(self.turn, col) if self.turn== 1: self.last_piece= self.board.create_oval(100*col+5,505-100*y,100*col+105,605-100*y, fill= "red", outline= "green", width= 5) self.turn=2 elif self.turn==2: self.last_piece=self.board.create_oval(100*col+5,505-100*y,100*col+105,605-100*y, fill= "yellow", outline= "green", width= 5) self.turn=1 if self.b.is_game_over()!= None: win= self.b.is_game_over() for i in range(4): self.board.create_oval(100*(win[1]+i*win[3])+5,505-100*(win[0]+i*win[2]),100*(win[1]+i*win[3])+105,605-100*(win[0]+i*win[2]), outline= "blue", width= 7) return def play_game(self): self.board.delete(ALL) self.b= connectfour.ConnectFour() self.turn= 1 self.last_piece= None for x in range(7): self.board.create_line(5, x*100+5, 705,x*100+5) for x in range(8): self.board.create_line(x*100+5, 5, x*100+5, 605) self.p1= self.combobox.get() self.p2= self.combobox1.get() assert self.p1 and self.p2 != None assert self.p1 or self.p2== "Human" if self.p1== "Human": pass elif self.p1== "Random": self.random_turn() elif self.p1== "Minimax": self.minimax_turn()
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
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()
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')
class BoardConfigAdvance(Frame): def __init__(self, master=None, main=None): Frame.__init__(self, master) self.parent = master self.main = main self.parent.geometry("280x174") self.parent.title(os.getenv("NAME") + " - Advance Board Config") self.master.configure(padx=10, pady=10) self.HEAPSIZE = {"512 byte": 512, "1024 byte": 1024,} self.OPTIMIZATION = "-O2 -O3 -Os".split() self.mips16_var = IntVar() self.checkBox_mips16 = Checkbutton(self.parent, text="Mips16", anchor="w", variable=self.mips16_var) self.checkBox_mips16.pack(expand=True, fill=BOTH, side=TOP) frame_heap = Frame(self.parent) Label(frame_heap, text="Heap size:", anchor="w", width=12).pack(side=LEFT, fill=X, expand=True) self.comboBox_heapsize = Combobox(frame_heap, values=self.HEAPSIZE.keys()) self.comboBox_heapsize.pack(fill=X, expand=True, side=RIGHT) frame_heap.pack(fill=X, expand=True, side=TOP) frame_opt = Frame(self.parent) Label(frame_opt, text="Optimization:", anchor="w", width=12).pack(side=LEFT, fill=X, expand=True) self.comboBox_optimization = Combobox(frame_opt, values=self.OPTIMIZATION) self.comboBox_optimization.pack(fill=X, expand=True, side=RIGHT) frame_opt.pack(fill=X, expand=True, side=TOP) frame_buttons = Frame(self.parent) Button(frame_buttons, text="Accept", command=self.accept_config).pack(fill=X, expand=True, side=LEFT) Button(frame_buttons, text="Restore Default", command=self.restore_default).pack(fill=X, expand=True, side=RIGHT) frame_buttons.pack(fill=X, expand=True, side=BOTTOM) self.load_config() #---------------------------------------------------------------------- def quit(self): self.master.destroy() #---------------------------------------------------------------------- def load_config(self): #Called in the parent frame #self.main.configIDE.load_config() if self.main.configIDE.config("Board", "mips16", True): self.checkBox_mips16.select() else: self.checkBox_mips16.deselect() heapsize = self.main.configIDE.config("Board", "heapsize", 512) for key in self.HEAPSIZE.keys(): if self.HEAPSIZE[key] == heapsize: self.comboBox_heapsize.set(key) break optimization = self.main.configIDE.config("Board", "optimization", "-O3") self.comboBox_optimization.set(optimization) #---------------------------------------------------------------------- def restore_default(self): self.checkBox_mips16.select() self.comboBox_heapsize.set(self.HEAPSIZE.keys()[1]) self.comboBox_optimization.set(self.OPTIMIZATION[1]) #---------------------------------------------------------------------- def accept_config(self): self.save_config() self.main.configIDE.save_config() self.quit() #---------------------------------------------------------------------- def save_config(self): self.main.configIDE.set("Board", "mips16", self.mips16_var.get()==1) heapsize = self.HEAPSIZE[self.comboBox_heapsize.get()] self.main.configIDE.set("Board", "heapsize", heapsize) self.main.configIDE.set("Board", "optimization", self.comboBox_optimization.get())
class App(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.levels = list() self.signs = list() self.items = [i for i in range(0,64)] self.items.remove(16) self.current_item = 0 self.parent = parent self.max_width = 600 self.max_height = 600 self.client = Client() self.initDimensions() self.initUI() self.event = None self.reset_canvas() def connect(self): res = self.client.regis() if(res == 1): time.sleep(1) self.connect_button.config(state = 'disabled') self.disconnect_button.config(state = 'normal') def disconnect(self): self.client.close() self.connect_button.config(state = 'normal') self.disconnect_button.config(state = 'disabled') def initDimensions(self): self.canvas_width = self.max_width self.canvas_height = self.max_height self.rows = 10 self.cols = 10 # self.h = 1; self.cellwidth = self.canvas_width/self.cols self.cellheight = self.canvas_height/self.rows self.initData() def add_new_level(self): temp=dict() temp2 = dict() self.levels.append(temp) self.signs.append(temp2) def insert_new_level(self, loc): temp=dict() temp2 = dict() self.levels.insert(loc,temp) self.signs.insert(loc,temp2) def initData(self): self.levels = list() self.signs = list() self.rect = dict() self.rect_text = dict() self.curr_level = 0 self.overlay_level = 0 self.overlayToggle = False self.levels.append(dict()) self.signs.append(dict()) self.current_item = 1 def reset_canvas(self): self.canvas.delete(ALL) self.parent.title("Craft Builder: Dimensions: " + str(self.rows) + 'x' + str(len(self.levels)) +'x' + str(self.cols)) def redraw_overlay(self): c = set(self.levels[self.overlay_level].keys()) if self.overlayToggle == 1: for key in c: x1 = key[1] * self.cellwidth y1 = (self.rows - key[0] - 1) * self.cellheight x2 = x1 + self.cellwidth y2 = y1 + self.cellheight if (key[0], key[1]) in self.rect: self.canvas.itemconfig(self.rect[key[0],key[1]], width = OVERLAYWIDTH) else: self.rect[key[0],key[1]] = self.canvas.create_rectangle(x1,y1,x2,y2, fill='white', outline = 'black', width = OVERLAYWIDTH, tag = 'block') self.rect_text[key[0],key[1]] = self.canvas.create_text((x1+x2)/2,(y1+y2)/2, text = '', font=('verdana', 7), tag = 'blocktext') def redraw_level(self): # self.canvas.delete(ALL) # self.rect=dict() # self.rect_text = dict() start = time.clock() b = set(self.levels[self.curr_level].keys()) for key in b: val = self.levels[self.curr_level][key] if (key[0], key[1]) in self.rect: self.canvas.itemconfig(self.rect[key[0],key[1]], fill = COLORS[val], outline = 'black', width = DEFAULTWIDTH) self.canvas.itemconfig(self.rect_text[key[0],key[1]], text = val) else: x1 = key[1] * self.cellwidth y1 = (self.rows - key[0] - 1) * self.cellheight x2 = x1 + self.cellwidth y2 = y1 + self.cellheight self.rect[key[0],key[1]] = self.canvas.create_rectangle(x1,y1,x2,y2, fill = COLORS[val], outline = 'black', width = DEFAULTWIDTH, tag = 'block') self.rect_text[key[0],key[1]] = self.canvas.create_text((x1+x2)/2,(y1+y2)/2, text = val, font=('verdana', 7), tag = 'blocktext') items_to_remove = list() for key in self.rect: if key not in self.levels[self.curr_level]: self.canvas.delete(self.rect[key[0],key[1]]) self.canvas.delete(self.rect_text[key[0],key[1]]) items_to_remove.append(key) for i in items_to_remove: self.rect.pop(i) self.rect_text.pop(i) self.parent.title("Craft Builder: Dimensions: " + str(self.rows) + 'x' + str(len(self.levels)) +'x' + str(self.cols)) self.redraw_overlay() def updateDimensions(self,r,c,y=1): self.rows = r self.cols = c self.cellwidth = self.max_width/self.cols self.cellheight = self.max_height/self.rows if(self.cellwidth<=self.cellheight): self.cellheight = self.cellwidth else: self.cellwidth = self.cellheight self.canvas_height = self.rows * self.cellheight self.canvas_width = self.cols * self.cellwidth self.canvas.config(width = self.canvas_width, height = self.canvas_height) self.canvas.delete(ALL) self.initData() for i in range(y-1): self.levels.append(dict()) self.signs.append(dict()) def altMenu(self, event): # print "Keycode:", event.keycode, "State:", event.keysym, event.type self.event = event if event.type == '2': self.altAction = True self.clear_button.config(text = 'Multi Clear', bg = 'white') self.delete_button.config(text = 'Multi Delete', bg='white') self.insert_button.config(text = 'Multi Insert', bg='white') self.copy_level_button.config(text = 'Multi Copy', bg = 'white') elif event.type == '3': defaultbg = self.parent.cget('bg') self.altAction = False self.clear_button.config(text = 'Clear Level', bg = defaultbg) self.delete_button.config(text = 'Delete', bg = defaultbg) self.insert_button.config(text = 'Insert', bg = defaultbg) self.copy_level_button.config(text = 'Copy overlay level', bg = defaultbg) sys.stdout.flush() def initUI(self): self.altAction = False self.parent.title("Craft Builder") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=0) self.columnconfigure(0, pad = 7) self.columnconfigure(1, pad = 7) self.columnconfigure(2, pad = 7) self.columnconfigure(9, weight =1 ) self.columnconfigure(3, pad=7) self.columnconfigure(5, pad=7) self.rowconfigure(1, weight=1) self.rowconfigure(5, pad=7) self.rowconfigure(6, pad=7) self.rowconfigure(7, pad=7) self.rowconfigure(8, pad=7) area = Frame(self, width=500, height=500, borderwidth = 2, relief = 'sunken') area.grid(row=1, column=0, columnspan=11, rowspan=4, padx=5, sticky=E+W+S+N) self.canvas = Canvas(area, bg='white', width=self.canvas_width, height=self.canvas_height) self.canvas.pack() self.canvas.bind("<Button-1>", self.callbackLeftClick) self.canvas.bind("<B1-Motion>", self.callbackLeftClick) self.canvas.bind("<Button-3>", self.callbackRightClick) self.canvas.bind("<B3-Motion>", self.callbackRightClick) self.canvas.bind("<Button-5>", self.scrollWheel) self.canvas.bind("<Button-4>", self.scrollWheel) self.parent.bind("<Shift_L>", self.altMenu) self.parent.bind("<KeyRelease-Shift_L>", self.altMenu) self.new_button = Button(self, text="New", command = self.onNew, width = 6) self.new_button.grid(row=5, column=0) save_button = Button(self, text="Save", command = self.onSave, width = 6) save_button.grid(row=6, column=0) load_button = Button(self, text="Load", command = self.onLoad, width = 6) load_button.grid(row=7, column=0) self.connect_button = Button(self, text="Connect", command = self.connect, width = 6) self.connect_button.grid(row=8, column=0) self.clear_button = Button(self, text="Clear Level", command = self.onClear, width =8) self.clear_button.grid(row=5, column=1) self.delete_button = Button(self, text="Delete Level", command = self.onDelete, width =8) self.delete_button.grid(row=6, column=1) self.insert_button = Button(self, text="Insert Level", command = self.onInsertLevel, width =8) self.insert_button.grid(row=7, column=1) self.disconnect_button = Button(self, text="Disconnect", command = self.disconnect, width = 8) self.disconnect_button.grid(row=8, column=1) self.disconnect_button['state'] = 'disabled' lbl_a = Label(self, text="Curr. Level", font=("Verdana", 10)) lbl_a.grid(row = 5, column = 2) lbl_b = Label(self, text="Overlay Level", font=("Verdana", 10)) lbl_b.grid(row = 6, column = 2) self.copy_level_button = Button(self, text="Copy overlay level", command = self.onCopy, width = 12) self.copy_level_button.grid(row=7, column=2, columnspan=1) load_world_button = Button(self, text="Load from world", command = self.onLoadFromWorld, width = 12) load_world_button.grid(row=8, column=2) self.currLevelCombo = Combobox(self, values = range(len(self.levels)), width = 5, state = 'readonly') self.currLevelCombo.grid(row = 5, column = 3) self.currLevelCombo.bind("<<ComboboxSelected>>", self.currLevelChooser) self.currLevelCombo.set(0) self.overlayLevelCombo = Combobox(self, values = range(len(self.levels)), width = 5, state = 'readonly') self.overlayLevelCombo.grid(row = 6, column = 3) self.overlayLevelCombo.bind("<<ComboboxSelected>>", self.overlayLevelChooser) self.overlayLevelCombo.set(0) self.new_level_button = Button(self, text="New Level", command = self.onNewLevel, width = 12) self.new_level_button.grid(row=7, column=3,columnspan=1) paste_button = Button(self, text="Paste in world", command = self.onPaste, width = 12) paste_button.grid(row=8, column=3) lbl_d = Label(self, text="Item", font=("Verdana", 10)) lbl_d.grid(row = 5, column = 4) self.toggle = Checkbutton(self, text="Overlay Toggle", command = self.onToggle) self.toggle.grid(row=6, column=4) rotate_button = Button(self, text="Rotate", command = self.onRotate, width = 12) rotate_button.grid(row=7, column=4,columnspan=1) paste_sign_button = Button(self, text="Paste Signs", command = self.onPasteSign, width = 12) paste_sign_button.grid(row=8, column=4) self.itemCombo = Combobox(self, values = self.items, width = 5, state = 'readonly') self.itemCombo.grid(row = 5, column = 5) self.itemCombo.bind("<<ComboboxSelected>>", self.itemChooser) self.itemCombo.set(1) self.current_item = 1 self.lbl_e = Label(self, text="", font=("Verdana", 8), width = 12, relief = 'ridge') self.lbl_e.grid(row = 6, column = 5) add_geo_button = Button(self, text="Add Geometry", command = self.addGeo, width = 12) add_geo_button.grid(row=8, column=5) try: global builder import builder except ImportError: add_geo_button.config(state = 'disabled') def scrollWheel(self, event): if event.num == 5: #scroll down if self.curr_level==len(self.levels) -1: pass else: self.curr_level = self.curr_level + 1 self.currLevelCombo.set(self.curr_level) self.redraw_level() else: #scroll up if self.curr_level == 0: pass else: self.curr_level = self.curr_level - 1 self.currLevelCombo.set(self.curr_level) self.redraw_level() def onInsertLevel(self): if self.altAction == 1: self.w=popupWindow(self,title = "Enter num_levels to insert and level below which to insert\n" + "seperated by a space.") self.wait_window(self.w.top) self.altAction = 0 data = self.w.value.split(' ') try: if len(data) == 2: for i in range(int(data[0])): self.insert_new_level(int(data[1])) self.redraw_level() else: print 'Not enough arguments' except ValueError: print 'Error in values' else: self.insert_new_level(self.curr_level) self.currLevelCombo.config(values = range(len(self.levels))) self.overlayLevelCombo.config(values = range(len(self.levels))) self.redraw_level() def onCopy(self): if self.altAction == 1: self.w=popupWindow(self,title = "Enter the arguments start_level end_level num_times\n" + "and level above which to copy, all seperated by spaces.") self.wait_window(self.w.top) self.altAction = 0 data = self.w.value.split(' ') try: if len(data) == 4: st,sto = sorted((data[0],data[1])) st = int(st) sto = int(sto) n = data[2] l = int(data[3]) + 1 for i in range(int(n)): for j in range(st, sto +1): for col in range(self.cols): for row in range(self.rows): if (row,col) in self.levels[j]: if l+j-st < len(self.levels) : self.levels[l+j-st][row,col] = self.levels[j][row,col] l = l +(sto-st+1) else: print 'Not enough arguments' except ValueError: print 'Error in values' else: for col in range(self.cols): for row in range(self.rows): if (row,col) in self.levels[self.overlay_level]: self.levels[self.curr_level][row,col] = self.levels[self.overlay_level][row,col] sys.stdout.flush() self.redraw_level() def onClear(self): if self.altAction == 1: self.w=popupWindow(self,title = "Enter the arguments start_level end_levels to clear\n" + "seperated by a space.") self.wait_window(self.w.top) self.altAction = 0 data = self.w.value.split() try: if len(data) == 2: st,sto = sorted((data[0],data[1])) st = int(st) sto = int(sto) for i in range(st,sto+1): if i < len(self.levels): self.levels[i] = dict() self.signs[i] = dict() self.redraw_level() else: print 'Not enough arguments' except ValueError: print 'Error in values' else: if tkMessageBox.askquestion('Clear', "Clear Level: " + str(self.curr_level)) == 'yes': self.levels[self.curr_level] = dict() self.signs[self.curr_level] = dict() self.redraw_level() else: pass def onDelete(self): if self.altAction == 1: self.w=popupWindow(self,title = "Enter the arguments start_level end_levels to delete\n" + "seperated by a space.") self.wait_window(self.w.top) self.altAction = 0 data = self.w.value.split() try: if len(data) == 2: st,sto = sorted((data[0],data[1])) st = int(st) sto = int(sto) for i in range(sto,st-1,-1): if i < len(self.levels) and i >=0 and len(self.levels)>1: self.levels.pop(i) self.signs.pop(i) elif i < len(self.levels) and i ==0 : self.levels[i] = dict() self.signs[i] = dict() self.currLevelCombo.config(values = range(len(self.levels))) self.overlayLevelCombo.config(values = range(len(self.levels))) self.curr_level = 0 self.currLevelCombo.set(0) self.overlayLevelCombo.set(0) self.redraw_level() else: print 'Not enough arguments' except ValueError: print 'Error in values' else: if tkMessageBox.askquestion('Delete', "Delete Level: " + str(self.curr_level)) == 'yes': if len(self.levels) == 1: self.onClear() else: self.levels.pop(self.curr_level) self.signs.pop(self.curr_level) self.currLevelCombo.config(values = range(len(self.levels))) self.overlayLevelCombo.config(values = range(len(self.levels))) if self.overlayToggle == 1: self.toggle.invoke() self.overlayToggle = 0 if self.curr_level != 0: self.curr_level = self.curr_level - 1 self.currLevelCombo.set(self.curr_level) else: self.currLevelCombo.set(self.curr_level) self.redraw_level() def addGeo(self): self.w=popupWindow(self,title = "Enter Command: help for Help") self.wait_window(self.w.top) try: c = self.w.value.split(' ') if c[0] == 'help': self.h = HelpWindow(self, title = 'Enter command followed by args seperated by spaces\n' + 'Available commands (sphere, pyramid, cuboid)\n' + '1. pyramid x1 x2 y z1 z2 fill(0/1) \n' + '2. sphere cx cy cz r fill(0/1) \n' + '4. circle_x x y z r fill(0/1) \n' + '5. circle_y x y z r fill(0/1) \n' + '6. circle_z x y z r fill(0/1) \n' + '7. cylinder_x x1 x2 y z r fill(0/1) \n' + '8. cylinder_y x y1 y2 z r fill(0/1) \n' + '9. cylinder_z x y z1 z2 r fill(0/1) \n' + '10. cuboid x1 x2 y1 y2 z1 z2 fill(0/1) \n' ) elif c[0] == 'sphere': if len(c) - 1 == 5: result = builder.sphere(int(c[1]),int(c[2]),int(c[3]),int(c[4]),int(c[5])) for i in result: if i[1] < len(self.levels) and i[1] >=0: if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0: self.levels[i[1]][i[0],i[2]] = self.current_item elif c[0] == 'pyramid': if len(c) - 1 == 6: result = builder.pyramid(int(c[1]),int(c[2]),int(c[3]),int(c[4]),int(c[5]),int(c[6])) for i in result: if i[1] < len(self.levels) and i[1] >= 0: if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0: self.levels[i[1]][i[0],i[2]] = self.current_item elif c[0] == 'circle_x': if len(c) - 1 == 5: result = builder.circle_x(int(c[1]),int(c[2]),int(c[3]),int(c[4]),int(c[5])) for i in result: if i[1] < len(self.levels) and i[1] >= 0: if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0: self.levels[i[1]][i[0],i[2]] = self.current_item elif c[0] == 'circle_y': if len(c) - 1 == 5: result = builder.circle_y(int(c[1]),int(c[2]),int(c[3]),int(c[4]),int(c[5])) for i in result: if i[1] < len(self.levels) and i[1] >= 0: if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0: self.levels[i[1]][i[0],i[2]] = self.current_item elif c[0] == 'circle_z': if len(c) - 1 == 5: result = builder.circle_z(int(c[1]),int(c[2]),int(c[3]),int(c[4]),int(c[5])) for i in result: if i[1] < len(self.levels) and i[1] >= 0: if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0: self.levels[i[1]][i[0],i[2]] = self.current_item elif c[0] == 'cylinder_x': if len(c) - 1 == 6: x1,x2 = sorted([int(c[1]),int(c[2])]) result = builder.cylinder_x(x1,x2,int(c[3]),int(c[4]),int(c[5]),int(c[6])) for i in result: if i[1] < len(self.levels) and i[1] >= 0: if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0: self.levels[i[1]][i[0],i[2]] = self.current_item elif c[0] == 'cylinder_y': if len(c) - 1 == 6: y1,y2 = sorted([int(c[2]),int(c[3])]) result = builder.cylinder_y(int(c[1]),y1,y2,int(c[4]),int(c[5]),int(c[6])) for i in result: if i[1] < len(self.levels) and i[1] >= 0: if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0: self.levels[i[1]][i[0],i[2]] = self.current_item elif c[0] == 'cylinder_z': if len(c) - 1 == 6: z1,z2 = sorted([int(c[3]),int(c[4])]) result = builder.cylinder_z(int(c[1]),int(c[2]),z1,z2,int(c[5]),int(c[6])) for i in result: if i[1] < len(self.levels) and i[1] >= 0: if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0: self.levels[i[1]][i[0],i[2]] = self.current_item elif c[0] == 'cuboid': if len(c) - 1 == 7: result = builder.cuboid(int(c[1]),int(c[2]),int(c[3]),int(c[4]),int(c[5]),int(c[6]),int(c[7])) for i in result: if i[1] < len(self.levels) and i[1] >= 0: if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0: self.levels[i[1]][i[0],i[2]] = self.current_item pass newLevels = list() for i, j in enumerate(self.levels): temp = dict() for key, val in j.iteritems(): if int(val) != 0: temp[key] = val newLevels.append(temp) self.levels = newLevels self.redraw_level() except RuntimeError: pass def onPaste(self): self.w=popupWindow(self,title = "On world, facing north (i.e x increases ahead of you,\n"+ "and z increases to your right.\n" + "Enter origin point (x y z) seperated by spaces: eg. 12 12 12:") self.wait_window(self.w.top) data = self.w.value.split(' ') try: xo = int(data[0]) yo = int(data[1]) zo = int(data[2]) if tkMessageBox.askquestion('Coords', "Is this (x,y,z) correct: " + str(xo) +',' +str(yo) + ',' + str(zo)) == 'yes': print 'Pasting' count = 0 for j,i in enumerate(self.levels): for key,value in i.iteritems(): xr = int(xo + key[0]) yr = int(yo + j) zr = int(zo + key[1]) # self.client.client_send(xr,yr,zr,0) if int(value) != 0: self.client.client_send(xr,yr,zr,int(value)) count = count + 1 if count % NUMPERSEC == 0: time.sleep(1) else: pass except ValueError: pass def onPasteSign(self): self.w=popupWindow(self,title = "Facing north, enter origin point(x y z): eg. 12 12 12:") self.wait_window(self.w.top) data = self.w.value.split(' ') try: xo = int(data[0]) yo = int(data[1]) zo = int(data[2]) if tkMessageBox.askquestion('Coords', "Is this (x,y,z) correct: " + str(xo) +',' +str(yo) + ',' + str(zo)) == 'yes': print 'Pasting' count = 0 for j,i in enumerate(self.signs): for key,value in i.iteritems(): xr = int(xo + key[0]) yr = int(yo + j) zr = int(zo + key[1]) for num,val in enumerate(value): if val!=-1: # print j,i,num, val self.client.client_send_sign(xr, yr, zr, num, val) sys.stdout.flush() except ValueError: pass def onLoadFromWorld(self): self.w=popupWindow(self,title = "Enter bottom left point: (x y z)") self.wait_window(self.w.top) try: [x1,y1,z1] = [int(i) for i in self.w.value.split(' ')] self.w=popupWindow(self,title = "Enter top right point: (x y z)") self.wait_window(self.w.top) [x2,y2,z2] = [int(i) for i in self.w.value.split(' ')] x1,x2 = sorted([x1,x2]) y1,y2 = sorted([y1,y2]) z1,z2 = sorted([z1,z2]) if tkMessageBox.askquestion('Coords', "Bottom left: " + str(x1) +',' +str(y1) + ',' + str(z1) + '\n' + \ "Top right: " + str(x2) +',' +str(y2) + ',' + str(z2)) == 'yes': print 'Copying',x1,y1,z1,' to',x2,y2,z2 data = self.client.read_db(x1,y1,z1,x2,y2,z2, db_name) signs = self.client.read_signs(x1,y1,z1,x2,y2,z2, db_name) newData = list() for i in data: temp = dict() for key,value in i.iteritems(): if value != 0: temp[key[0], key[1]] = value newData.append(temp) newSignData = list() for i in signs: temp = dict() for key,value in i.iteritems(): temp[key[0], key[1]] = value newSignData.append(temp) if self.overlayToggle == 1: self.toggle.invoke() self.overlayToggle = 0 self.updateDimensions(x2-x1+1, z2-z1+1, len(newData)) self.reset_canvas() self.levels = newData self.signs = newSignData sys.stdout.flush() self.redraw_level() self.currLevelCombo.config(values = range(len(self.levels))) self.overlayLevelCombo.config(values = range(len(self.levels))) except ValueError: pass def onSave(self): filename = asksaveasfilename(parent=self) pickle.dump({'Dimensions' : [self.rows,self.cols,len(self.levels)],'Levels' : self.levels, 'Signs' : self.signs}, open(filename, 'wb')) def onLoad(self): if self.overlayToggle == 1: self.toggle.invoke() self.overlayToggle = 0 filename = askopenfilename(parent=self) try: obj = pickle.load(open(filename, 'rb')) self.updateDimensions(int(obj['Dimensions'][0]), int(obj['Dimensions'][1]), int(obj['Dimensions'][2])) self.reset_canvas() self.levels = obj['Levels'] if 'Signs' in obj: self.signs = obj['Signs'] self.redraw_level() self.currLevelCombo.config(values = range(len(self.levels))) self.overlayLevelCombo.config(values = range(len(self.levels))) except IOError: pass def onToggle(self): if self.overlayToggle == 0: self.overlayToggle =1 self.redraw_level() else: self.overlayToggle = 0 self.redraw_level() def onNewLevel(self): self.add_new_level() self.currLevelCombo.config(values = range(len(self.levels))) self.overlayLevelCombo.config(values = range(len(self.levels))) self.redraw_level() def onRotate(self): self.rotatedData = list() self.rotatedSignData = list() for i in self.levels: temp = dict() for key,value in i.iteritems(): xr = (key[0] * math.cos(math.radians(-90)) - (key[1]) * math.sin(math.radians(-90))) zr = (key[0] * math.sin(math.radians(-90)) + (key[1]) * math.cos(math.radians(-90))) temp[int(math.floor(xr)),int(math.floor(zr))] = value self.rotatedData.append(temp) sign_map = {0:2, 3:0, 1:3, 2:1, 6:5, 7:6, 4:7, 5:4} #FOR ROTATION CALCULATION for i in self.signs: temp = dict() for key,value in i.iteritems(): xr = (key[0] * math.cos(math.radians(-90)) - (key[1]) * math.sin(math.radians(-90))) zr = (key[0] * math.sin(math.radians(-90)) + (key[1]) * math.cos(math.radians(-90))) new_value = [value[sign_map[0]], value[sign_map[1]], value[sign_map[2]], value[sign_map[3]], value[sign_map[4]], value[sign_map[5]], value[sign_map[6]], value[sign_map[7]]] temp[int(math.floor(xr)),int(math.floor(zr))] = new_value self.rotatedSignData.append(temp) #Moving to origin x,z : 0,0 self.newData=list() self.newSignData=list() for i in self.rotatedData: temp=dict() for key,value in i.iteritems(): temp[key[0], int(key[1])+int((self.rows-1))] = value self.newData.append(temp) for i in self.rotatedSignData: temp=dict() for key,value in i.iteritems(): temp[key[0], int(key[1])+int((self.rows-1))] = value self.newSignData.append(temp) temp = self.rows self.rows = self.cols self.cols = temp temp = self.curr_level temp2 = self.overlay_level temp3 = self.overlayToggle temp4 = self.current_item self.updateDimensions(self.rows, self.cols,len(self.newData)) self.reset_canvas() self.levels = self.newData self.signs = self.newSignData self.curr_level = temp self.overlay_level = temp2 self.overlayToggle = temp3 self.itemCombo.set(temp4) self.currLevelCombo.config(values = range(len(self.levels))) self.overlayLevelCombo.config(values = range(len(self.levels))) self.currLevelCombo.set(self.curr_level) self.overlayLevelCombo.set(self.overlay_level) self.redraw_level() def onNew(self): if self.overlayToggle == 1: self.toggle.invoke() self.overlayToggle = 0 self.w=popupWindow(self,title = "Enter Dimensions in XxZxY format (e.g. 10x20x3)") self.wait_window(self.w.top) try: data = self.w.value.split('x') if len(data) == 2: self.updateDimensions(int(data[0]), int(data[1]),1) else: self.updateDimensions(int(data[0]), int(data[1]),int(data[2])) # self.initData() self.reset_canvas() self.currLevelCombo.config(values = range(len(self.levels))) self.overlayLevelCombo.config(values = range(len(self.levels))) except ValueError: pass def currLevelChooser(self, event): self.curr_level = int(self.currLevelCombo.get()) self.redraw_level() def overlayLevelChooser(self, event): self.overlay_level = int(self.overlayLevelCombo.get()) self.redraw_level() def itemChooser(self, event): self.current_item = int(self.itemCombo.get()) def callbackLeftClick(self,event): if self.current_item == 0: return col = int(math.floor((event.x)/self.cellwidth)) row = int(math.floor((event.y)/self.cellheight)) x1 = col * self.cellwidth y1 = row * self.cellheight x2 = x1 + self.cellwidth y2 = y1 + self.cellheight if (self.rows - row - 1,col) in self.rect: self.canvas.itemconfig(self.rect[self.rows - row - 1,col],fill=COLORS[self.current_item]) self.canvas.itemconfig(self.rect_text[self.rows - row - 1,col], text = str(self.current_item)) else: self.rect[self.rows - row - 1,col] = self.canvas.create_rectangle(x1,y1,x2,y2, fill=COLORS[self.current_item], outline = 'black', width = DEFAULTWIDTH, tag = 'block') self.rect_text[self.rows - row - 1,col] = self.canvas.create_text((x1+x2)/2,(y1+y2)/2, text = self.current_item, font=('verdana', 7), tag = 'blocktext') self.levels[self.curr_level][self.rows - row - 1,col] = self.current_item if row < self.rows and row >=0 and col < self.cols and col >= 0: self.lbl_e.config(text = 'x,y,z: ' + str(self.rows-row-1) + ',' + str(self.curr_level) + ',' + str(col)) def callbackRightClick(self,event): col = int(math.floor((event.x)/self.cellwidth)) row = int(math.floor((event.y)/self.cellheight)) if (self.rows - row - 1,col) in self.rect: self.canvas.delete(self.rect[self.rows - row - 1,col]) self.canvas.delete(self.rect_text[self.rows - row - 1,col]) self.rect.pop((self.rows - row -1, col)) self.rect_text.pop((self.rows - row -1, col)) self.levels[self.curr_level].pop((self.rows - row - 1,col),None) if row < self.rows and row >=0 and col < self.cols and col >= 0: self.lbl_e.config(text = 'x,y,z: ' + str(self.rows-row-1) + ',' + str(self.curr_level) + ',' + str(col))
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)
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')
class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack(fill=BOTH, expand=1) self.initUI() self.setGeometry() self.component = NewComponent() def setGeometry(self): x = 300 y = 100 self.master.geometry("400x300+%d+%d" % (x, y)) self.master.update() def initUI(self): #setup title self.master.title("Component Creator") self.style = Style() self.style.theme_use("clam") #indicator label self.labelName = Label(self, text="Component Name:") self.labelName.place(x=10, y=10) self.master.update() # create variable and namefield for input of component name sv = StringVar() sv.trace("w", lambda name, index, mode, sv=sv: self.nameChanged(sv)) self.nameField = Entry(self, textvariable=sv) self.nameField.place(x=10 + self.labelName.winfo_width() + 10, y=10) self.master.update() # label for image name that will show img name for a given component name self.imgNameVar = StringVar() self.imgNameVar.set('imageName:') self.labelImageName = Label(self, textvariable=self.imgNameVar) self.labelImageName.place(x=10 + self.labelName.winfo_width() + 10, y=40) # checkbox for visible component or not self.cbVar = IntVar() self.cb = Checkbutton(self, text="Visible Component", variable=self.cbVar) self.cb.place(x=10, y=70) # dropdown list for category self.labelCategory = Label(self, text="Category:") self.labelCategory.place(x=10, y=110) self.master.update() acts = [ 'UserInterface', 'Layout', 'Media', 'Animation', 'Sensors', 'Social', 'Storage', 'Connectivity', 'LegoMindStorms', 'Experimental', 'Internal', 'Uninitialized' ] self.catBox = Combobox(self, values=acts) self.catBox.place(x=10 + self.labelCategory.winfo_width() + 10, y=110) # button to select icon image self.getImageButton = Button(self, text="Select icon", command=self.getImage) self.getImageButton.place(x=10, y=150) self.master.update() # explanation for resizing self.resizeVar = IntVar() self.resizeCB = Checkbutton( self, text="ON=Resize Image (Requires PIL)\nOFF=Provide 16x16 Image", variable=self.resizeVar) self.resizeCB.place(x=10 + self.getImageButton.winfo_width() + 10, y=150) # create button self.createButton = Button(self, text="Create", command=self.create) self.createButton.place(x=10, y=230) #cancel button self.cancelButton = Button(self, text="Cancel", command=self.quit) self.cancelButton.place(x=200, y=230) # open file picker for selecting an icon def getImage(self): ftypes = [('All Picture Files', ('*.jpg', '*.png', '*.jpeg', '*.bmp')), ('All files', '*')] self.component.imgFile = askopenfilename(filetypes=ftypes, title="Select an Icon file") # update component name and image name for component by lowercasing first letter def nameChanged(self, sv): s = sv.get() self.component.compName = s self.component.compImgName = s[:1].lower() + s[1:] if s else '' self.imgNameVar.set('imageName: %s' % self.component.compImgName) # tries to create component def create(self): # sets parameters for new component based on input values self.component.visibleComponent = bool(self.cbVar.get()) self.component.resizeImage = bool(self.resizeVar.get()) self.component.category = self.catBox.get().upper() self.component.compName = self.nameField.get() try: # check if component already exists try: open( '../../components/src/com/google/appinentor/components/runtime/%s.java', 'r') tkMessageBox.showerror( "Duplicate Component", "%s already exists" % self.component.compName) # if doesnt exist will raise error except IOError: # check for name input if not self.component.compImgName: tkMessageBox.showerror("Missing Name", "Please enter component name") return #check for category selection if not self.component.category: tkMessageBox.showerror("Missing Category", "Please select a category") return # check if selected an icon if not self.component.imgFile: tkMessageBox.showerror("Missing Icon", "Please select an icon image") return # copy image file to folder, can get error if user checked resize and doest have PIL installed try: self.component.copyImageToFolder() except ImportError, e: tkMessageBox.showerror( "Unable to import PIL", "Please install PIL or unselect checkbox") return # add references to the image file, can get error if component already exists try: self.component.addImageReference() except DuplicateError, e: tkMessageBox.showerror( "Duplicate Component", "%s already exists" % self.component.compName) return # will create mock component if is visible and add references to SimpleComponentDescriptor self.component.createMockComponent() # will create the actual component file self.component.createComponent() tkMessageBox.showinfo('Success', 'Component created successfully')
class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack(fill=BOTH, expand=1) self.initUI() self.setGeometry() self.component = NewComponent() def setGeometry(self): x = 300 y = 100 self.master.geometry("400x300+%d+%d" % (x, y)) self.master.update() def initUI(self): #setup title self.master.title("Component Creator") self.style = Style() self.style.theme_use("clam") #indicator label self.labelName = Label(self, text="Component Name:") self.labelName.place(x=10, y=10) self.master.update() # create variable and namefield for input of component name sv = StringVar() sv.trace("w", lambda name, index, mode, sv=sv: self.nameChanged(sv)) self.nameField = Entry(self, textvariable=sv) self.nameField.place(x=10+self.labelName.winfo_width() + 10, y=10) self.master.update() # label for image name that will show img name for a given component name self.imgNameVar = StringVar() self.imgNameVar.set('imageName:') self.labelImageName = Label(self, textvariable=self.imgNameVar) self.labelImageName.place(x=10+self.labelName.winfo_width()+10,y=40) # checkbox for visible component or not self.cbVar = IntVar() self.cb = Checkbutton(self, text="Visible Component", variable=self.cbVar) self.cb.place(x=10, y=70) # dropdown list for category self.labelCategory = Label(self, text="Category:") self.labelCategory.place(x=10, y=110) self.master.update() acts = ['UserInterface', 'Layout', 'Media', 'Animation', 'Sensors', 'Social', 'Storage', 'Connectivity', 'LegoMindStorms', 'Experimental', 'Internal', 'Uninitialized'] self.catBox = Combobox(self, values=acts) self.catBox.place(x=10+self.labelCategory.winfo_width()+10, y=110) # button to select icon image self.getImageButton = Button(self, text="Select icon", command=self.getImage) self.getImageButton.place(x=10, y=150) self.master.update() # explanation for resizing self.resizeVar = IntVar() self.resizeCB = Checkbutton(self, text="ON=Resize Image (Requires PIL)\nOFF=Provide 16x16 Image", variable=self.resizeVar) self.resizeCB.place(x=10+self.getImageButton.winfo_width()+10, y=150) # create button self.createButton = Button(self, text="Create", command=self.create) self.createButton.place(x=10, y=230) #cancel button self.cancelButton = Button(self, text="Cancel", command=self.quit) self.cancelButton.place(x=200, y=230) # open file picker for selecting an icon def getImage(self): ftypes = [('All Picture Files', ('*.jpg', '*.png', '*.jpeg', '*.bmp')), ('All files', '*')] self.component.imgFile = askopenfilename(filetypes=ftypes, title="Select an Icon file") # update component name and image name for component by lowercasing first letter def nameChanged(self, sv): s = sv.get() self.component.compName = s self.component.compImgName = s[:1].lower() + s[1:] if s else '' self.imgNameVar.set('imageName: %s' % self.component.compImgName) # tries to create component def create(self): # sets parameters for new component based on input values self.component.visibleComponent = bool(self.cbVar.get()) self.component.resizeImage = bool(self.resizeVar.get()) self.component.category = self.catBox.get().upper() self.component.compName = self.nameField.get() try: # check if component already exists try: open('../../components/src/com/google/appinentor/components/runtime/%s.java', 'r') tkMessageBox.showerror("Duplicate Component","%s already exists" % self.component.compName) # if doesnt exist will raise error except IOError: # check for name input if not self.component.compImgName: tkMessageBox.showerror("Missing Name","Please enter component name") return #check for category selection if not self.component.category: tkMessageBox.showerror("Missing Category","Please select a category") return # check if selected an icon if not self.component.imgFile: tkMessageBox.showerror("Missing Icon","Please select an icon image") return # copy image file to folder, can get error if user checked resize and doest have PIL installed try: self.component.copyImageToFolder() except ImportError, e: tkMessageBox.showerror("Unable to import PIL","Please install PIL or unselect checkbox") return # add references to the image file, can get error if component already exists try: self.component.addImageReference() except DuplicateError, e: tkMessageBox.showerror("Duplicate Component","%s already exists" % self.component.compName) return # will create mock component if is visible and add references to SimpleComponentDescriptor self.component.createMockComponent() # will create the actual component file self.component.createComponent() tkMessageBox.showinfo('Success', 'Component created successfully')
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 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)
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 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)
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])
class App: """Main class for the gui layer.""" def __init__(self, master): self.master = master self.master.title("Gaussian Elimination / Jacobi Method") self.create_widgets(master) # options for opening or saving a file self.file_opt = options = {} options['filetypes'] = [('all files', '*'), ('text files', '.txt'), ('csv files', '.csv')] def create_widgets(self, master): """Populate the main window with gui components.""" # buttons, slider, combobox etc. frame0 = Frame(master) frame0.grid(row=1, column=0, sticky=N) self.scale = Scale(frame0, from_=2, to=2000, orient=HORIZONTAL, label='Matrix / vector size (n):') self.scale.pack(fill="x") btn_gen_mtx = Button(frame0, text="Generate matrix A (n x n)", command=self.gen_mtx) btn_gen_mtx.pack(fill="x") btn_gen_vec = Button(frame0, text="Generate vector B (n)", command=self.gen_vec) btn_gen_vec.pack(fill="x") btn_load_mtx = Button(frame0, text="Load matrix A", command=self.load_mtx) btn_load_mtx.pack(fill="x") btn_load_vec = Button(frame0, text="Load vector B", command=self.load_vec) btn_load_vec.pack(fill="x") btn_solve = Button(frame0, text="SOLVE", command=self.solve) btn_solve.pack(fill="x") self.combobox = Combobox(frame0, state="readonly", values=("Gauss Method", "Jacobi Method", "numpy.linalg.solve()")) self.combobox.pack(fill="x") self.combobox.set("Gauss Method") # default choice btn_quit = Button(frame0, text="Quit", command=self.quit) btn_quit.pack(fill='x', pady=28) # scrollbar text widget (matrix a) self.frame1 = Frame(master) xscrollbar1 = Scrollbar(self.frame1, orient=HORIZONTAL) xscrollbar1.grid(row=1, column=0, sticky=E+W) yscrollbar1 = Scrollbar(self.frame1) yscrollbar1.grid(row=0, column=1, sticky=N+S) self.text1 = Text(self.frame1, wrap=NONE, bd=0, state=DISABLED, xscrollcommand=xscrollbar1.set, yscrollcommand=yscrollbar1.set) self.text1.grid(row=0, column=0, sticky=N+S+W+E) xscrollbar1.config(command=self.text1.xview) yscrollbar1.config(command=self.text1.yview) self.frame1.grid_rowconfigure(0, weight=1) self.frame1.grid_columnconfigure(0, weight=1) self.frame1.grid(row=1, column=1, sticky=N+S+W+E) # scrollbar text widget (vector b) self.frame2 = Frame(master) xscrollbar2 = Scrollbar(self.frame2, orient=HORIZONTAL) xscrollbar2.grid(row=1, column=0, sticky=E+W) yscrollbar2 = Scrollbar(self.frame2) yscrollbar2.grid(row=0, column=1, sticky=N+S) self.text2 = Text(self.frame2, width=30, wrap=NONE, bd=0, state=DISABLED, xscrollcommand=xscrollbar2.set, yscrollcommand=yscrollbar2.set) self.text2.grid(row=0, column=0, sticky=N+S+E+W) xscrollbar2.config(command=self.text2.xview) yscrollbar2.config(command=self.text2.yview) self.frame2.grid_rowconfigure(0, weight=1) self.frame2.grid_columnconfigure(0, weight=1) self.frame2.grid(row=1, column=2, sticky=N+S) # scrollbar text widget (vector x) self.frame3 = Frame(master) xscrollbar3 = Scrollbar(self.frame3, orient=HORIZONTAL) xscrollbar3.grid(row=1, column=0, sticky=E+W) yscrollbar3 = Scrollbar(self.frame3) yscrollbar3.grid(row=0, column=1, sticky=N+S) self.text3 = Text(self.frame3, width=30, wrap=NONE, bd=0, state=DISABLED, xscrollcommand=xscrollbar3.set, yscrollcommand=yscrollbar3.set) self.text3.grid(row=0, column=0, sticky=N+S+E+W) xscrollbar3.config(command=self.text3.xview) yscrollbar3.config(command=self.text3.yview) self.frame3.grid_rowconfigure(0, weight=1) self.frame3.grid_columnconfigure(0, weight=1) self.frame3.grid(row=1, column=3, sticky=N+S) # labels label1 = Label(master, text="Matrix A") label1.grid(row=0, column=1) label2 = Label(master, text="Vector B") label2.grid(row=0, column=2) label3 = Label(master, text="Vector X") label3.grid(row=0, column=3) self.bottom_label = Label(master) self.bottom_label.grid(row=2, column=0, columnspan=4, sticky=W+E) # which row/column should grow/shrink when resizing the main window self.master.grid_rowconfigure(1, weight=1) self.master.grid_columnconfigure(1, weight=1) def quit(self): """A callback method for quitting the app.""" self.master.destroy() def gen_mtx(self): """A callback method for generating matrix A.""" self.bottom_label.config(text='') self.subp_launcher(ngm.posdef_diag_dom, self.scale.get()) self.cw = CancelWindow(self.master, self.subp) def gen_vec(self): """A callback method for generating vector B.""" self.bottom_label.config(text='') self.subp_launcher(ngm.gen_rnd_vec, self.scale.get()) self.cw = CancelWindow(self.master, self.subp) def load_mtx(self): """A callback method for loading matrix A.""" # TODO: add a handler for exceptions raised by nmgj.check_input_data() self.bottom_label.config(text='') filename = tkFileDialog.askopenfilename(**self.file_opt) if filename: self.a = nmgj.load_mtx(filename) self.display_text(self.text1, self.a) def load_vec(self): """A callback method for loading vector B.""" self.bottom_label.config(text='') filename = tkFileDialog.askopenfilename(**self.file_opt) if filename: self.b = nmgj.load_vec(filename) self.display_text(self.text2, self.b) def delete_text(self, text_wgt): """A helper function for text widget refreshing.""" text_wgt.config(state=NORMAL) text_wgt.delete(1.0, END) text_wgt.config(state=DISABLED) def display_text(self, text_wgt, text): """A helper function for text widget refreshing.""" text_wgt.config(state=NORMAL) text_wgt.delete(1.0, END) if text is not None: text_wgt.insert(END, text) text_wgt.config(state=DISABLED) def solve(self): """A callback method for solving a given set of equations.""" self.x = None self.delete_text(self.text3) if (self.a is None or self.b is None) or (len(self.a) != len(self.b)): # TODO: consider different error message for the 'None' case tkMessageBox.showerror("Error", "Dimensions mismatch.") return choice = self.combobox.get() f = { "Gauss Method": nmgj.gauss, "Jacobi Method": nmgj.jacobi, "numpy.linalg.solve()": nmgj.la.solve, }.get(choice) self.subp_launcher(f, self.a, self.b) self.cw = CancelWindow(self.master, self.subp) def calc_residual(self, a, x, b): """Handles calculation of residual & dislpaying the results.""" self.res_min, self.res_avg, self.res_max = nmgj.calc_residual(a, x, b) self.display_text(self.text3, self.x) self.bottom_label.config(text='Residual: min ' + str(self.res_min) + ' avg ' + str(self.res_avg) + ' max ' + str(self.res_max)) def subp_launcher(self, f, *args): """Creates a queue for communication, spawns the subprocess and schedules checking if it's still active. """ # note: there will be no more than one subprocess at any given time self.q = mp.Queue() self.subp = mp.Process(target=self.subp_wrapper, args=(f, args)) self.subp.start() #print "subprocess started - pid:", self.subp.pid # for diagnostics self.check_subp(f) def subp_wrapper(self, f, args): """Wraps the subprocess f, creates the temp file for data passing and puts its name on the queue. """ results = f(*args) # Generally, out-of-band signalling is better than in-band signalling - # hence temporary file for data, and queue for communication *only*. # And also, although you can safely put objects up to 32 MB through # the queue, there's a 'hidden' pipe mechanism involved here (with its # own limits), so the order in which you use join() and get() methods # may be sigificant (see: http://bugs.python.org/issue8426). with NamedTemporaryFile(delete=False) as temp: np.savez(temp, results) temp.flush() self.q.put(temp.name) def check_subp(self, f): """Checks if the subprocess is still alive, otherwise does the cleanup.""" if self.subp.is_alive() is False: if self.subp.exitcode > 0: self.subp.terminate() self.subp.join() #print 'subprocess finished' # for diagnostics self.subp_cleanup(f) return self.master.after(100, self.check_subp, f) # every 100 ms def subp_cleanup(self, f): """Cleans up after the calculations, displays the solution.""" if self.q.empty() is not True: temp = self.q.get() results = np.load(temp).items()[0][1] os.remove(temp) else: results = None if f == ngm.posdef_diag_dom: self.a = results self.display_text(self.text1, self.a) elif f == ngm.gen_rnd_vec: self.b = results self.display_text(self.text2, self.b) elif f in (nmgj.gauss, nmgj.jacobi, nmgj.la.solve): self.x = results self.display_text(self.text3, results) if self.x is not None: self.calc_residual(self.a, self.x, self.b)
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 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 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
class App: def __init__(self,master): #User Interface #TODO: Add progressbar so people know when the program is working root.title('Transit Survey Desire Lines') root.iconbitmap(default='busicon.ico') self.titleText=Label(master,text="OKI Transit On-board Survey Processor").grid(row=0,column=0,columnspan=4) self.licenseText=Label(master,text="Licensed 2012 GPL v3").grid(row=1,column=0,columnspan=4) self.websiteText=Label(master,text="www.oki.org").grid(row=2,column=0,columnspan=4) self.workspaceLabel=Label(master,text="GIS Workspace:").grid(row=3,column=0) self.workspaceText=Text(master,height=1,width=50) self.workspaceText.grid(row=3,column=1) self.workspaceBrowse=Button(master,text="Browse MDB",command=self.loadTemplate).grid(row=3,column=2) self.workspaceFGDB=Button(master,text="Browse GDB",command=self.loadFolder).grid(row=3,column=3) self.tableLabel=Label(master,text="Table:").grid(row=4,column=0) self.tableLB=Combobox(master,values=["None yet"]) self.tableLB.bind('<<ComboboxSelected>>',self.getFieldsFromTable) self.tableLB.grid(row=4,column=1) self.idLabel=Label(master,text="Survey IDs:").grid(row=4,column=2) self.idCombo=Combobox(master,values=["None yet"]) self.idCombo.grid(row=4,column=3) self.modeToLabel=Label(master,text="Mode To:").grid(row=5,column=0) self.modeToCombo=Combobox(master,values=["None yet"]) self.modeToCombo.grid(row=5,column=1) self.modeFrLabel=Label(master,text="Mode From:").grid(row=5, column=2) self.modeFrCombo=Combobox(master,values=["None yet"]) self.modeFrCombo.grid(row=5,column=3) self.oxLabel=Label(master,text="Origin X Field:").grid(row=6, column=0) self.oxCombo=Combobox(master,values=["None yet"]) self.oxCombo.grid(row=6, column=1) self.oyLabel=Label(master,text="Origin Y Field:").grid(row=6, column=2) self.oyCombo=Combobox(master,values=["None yet"]) self.oyCombo.grid(row=6,column=3) self.bxLabel=Label(master,text="Board X Field:").grid(row=7, column=0) self.bxCombo=Combobox(master,values=["None yet"]) self.bxCombo.grid(row=7, column=1) self.byLabel=Label(master,text="Board Y Field:").grid(row=7, column=2) self.byCombo=Combobox(master,values=["None yet"]) self.byCombo.grid(row=7,column=3) self.axLabel=Label(master,text="Alight X Field:").grid(row=8, column=0) self.axCombo=Combobox(master,values=["None yet"]) self.axCombo.grid(row=8, column=1) self.ayLabel=Label(master,text="Alight Y Field:").grid(row=8, column=2) self.ayCombo=Combobox(master,values=["None yet"]) self.ayCombo.grid(row=8,column=3) self.dxLabel=Label(master,text="Dest X Field:").grid(row=9, column=0) self.dxCombo=Combobox(master,values=["None yet"]) self.dxCombo.grid(row=9, column=1) self.dyLabel=Label(master,text="Dest Y Field:").grid(row=9, column=2) self.dyCombo=Combobox(master,values=["None yet"]) self.dyCombo.grid(row=9,column=3) self.breakerLabel=Label(master,text="The below are for graphing and are not needed for Desirelines").grid(row=10,column=0,columnspan=4) self.surveyBusLabel=Label(master,text="Survey Bus:").grid(row=11,column=0) self.surveyBusCombo=Combobox(master,values=["None yet"]) self.surveyBusCombo.grid(row=11,column=1) self.firstBusLabel=Label(master,text="First Bus:").grid(row=11,column=2) self.firstBusCombo=Combobox(master,values=["None yet"]) self.firstBusCombo.grid(row=11,column=3) self.goButton=Button(master,text="Create Desirelines!",command=self.buildDL).grid(row=12,column=0) self.quitButton=Button(master,text="Quit",command=master.quit).grid(row=12,column=1) self.graphOB=Button(master,text="Graph OB",command=self.graphOB).grid(row=12,column=2) self.graphAD=Button(master,text="Graph AD",command=self.graphAD).grid(row=12,column=3) self.addQCVarsButton=Button(master,text="Add QC Variables",command=self.QCVars).grid(row=13,column=0) self.CupholderButton=Button(master,text="Cupholder!",command=self.cupholder).grid(row=13,column=3) def loadTemplate(self): #Loads a personal geodatabase file filename=tkFileDialog.askopenfilename(filetypes=(("Personal Geodatabases","*.mdb"))) if(filename): try: self.workspaceText.insert(END,filename) env.workspace=filename except Exception as e: tkMessageBox.showerror("Failed to read file",e.message) return def loadFolder(self): #Loads a file geodatabase (looks like a folder to Windows Explorer, etc.) foldername=tkFileDialog.askdirectory() if(foldername): try: self.workspaceText.insert(END,foldername) env.workspace=foldername self.getTablesFromGdb() except Exception as e: tkMessageBox.showerror("Failed to read folder",e.message) return def getTablesFromGdb(self): #Gets a table list from the geodatabase and fills the table combobox self.tableList=arcpy.ListTables() tl=() for table in self.tableList: tl=tl+(table,) self.tableLB['values']=tl def getFieldsFromTable(self,something): #Gets the fields from the selected table and loads all (relevant) comboboxes featClass=self.tableLB.get() try: fl=() if(featClass and featClass!=-1): fields=arcpy.ListFields(featClass) for field in fields: fl=fl+(field.name,) self.oxCombo['values']=fl self.oyCombo['values']=fl self.bxCombo['values']=fl self.byCombo['values']=fl self.axCombo['values']=fl self.ayCombo['values']=fl self.dxCombo['values']=fl self.dyCombo['values']=fl self.idCombo['values']=fl self.modeToCombo['values']=fl self.modeFrCombo['values']=fl self.surveyBusCombo['values']=fl self.firstBusCombo['values']=fl except: return def buildDL(self): #this is the main process to build the desire lines try: #Check Inputs if self.idCombo.get() and self.modeToCombo.get() and self.modeFrCombo.get() and self.oxCombo.get() and self.oyCombo.get() and self.bxCombo.get() and self.byCombo.get() and self.axCombo.get() and self.ayCombo.get() and self.dxCombo.get() and self.dyCombo.get(): SurveyIDField=self.idCombo.get() ModeToField=self.modeToCombo.get() ModeFrField=self.modeFrCombo.get() OXField=self.oxCombo.get() OYField=self.oyCombo.get() BXField=self.bxCombo.get() BYField=self.byCombo.get() AXField=self.axCombo.get() AYField=self.ayCombo.get() DXField=self.dxCombo.get() DYField=self.dyCombo.get() #Origin ~> Boarding OutputFC="OBDesireLines" arcpy.CreateFeatureclass_management(env.workspace,OutputFC,"POLYLINE") arcpy.AddField_management(OutputFC,"SurveyID","LONG") arcpy.AddField_management(OutputFC,"ModeTo","LONG") arcpy.AddField_management(OutputFC,"ModeFrom","LONG") arcpy.AddField_management(OutputFC,"DistanceSL","DOUBLE") rows=arcpy.SearchCursor(self.tableLB.get()) insRows=arcpy.InsertCursor(OutputFC) x=1 for row in rows: if(x % 100 == 0): print "Working on ",x insRow=insRows.newRow() insRow.SurveyID=row.getValue(SurveyIDField) insRow.ModeTo=row.getValue(ModeToField) insRow.ModeFrom=row.getValue(ModeFrField) lineArray=arcpy.Array() pnt1=arcpy.Point() pnt2=arcpy.Point() if(row.getValue(OXField) and row.getValue(OYField) and row.getValue(BXField) and row.getValue(BYField)): pnt1.X=row.getValue(OXField) pnt1.Y=row.getValue(OYField) lineArray.add(pnt1) pnt2.X=row.getValue(BXField) pnt2.Y=row.getValue(BYField) lineArray.add(pnt2) insRow.shape=lineArray insRow.DistanceSL=math.sqrt(math.pow(pnt2.X-pnt1.X,2)+math.pow(pnt2.Y-pnt1.Y,2)) insRows.insertRow(insRow) x+=1 #Alight ~> Destination OutputFC="ADDesireLines" arcpy.CreateFeatureclass_management(env.workspace,OutputFC,"POLYLINE") arcpy.AddField_management(OutputFC,"SurveyID","LONG") arcpy.AddField_management(OutputFC,"ModeTo","LONG") arcpy.AddField_management(OutputFC,"ModeFrom","LONG") arcpy.AddField_management(OutputFC,"DistanceSL","DOUBLE") rows=arcpy.SearchCursor(self.tableLB.get()) insRows=arcpy.InsertCursor(OutputFC) x=1 for row in rows: if(x % 100 == 0): print "Working on ",x insRow=insRows.newRow() insRow.SurveyID=row.getValue(SurveyIDField) insRow.ModeTo=row.getValue(ModeToField) insRow.ModeFrom=row.getValue(ModeFrField) lineArray=arcpy.Array() pnt1=arcpy.Point() pnt2=arcpy.Point() if(row.getValue(AXField) and row.getValue(AYField) and row.getValue(DXField) and row.getValue(DYField)): pnt1.X=row.getValue(AXField) pnt1.Y=row.getValue(AYField) lineArray.add(pnt1) pnt2.X=row.getValue(DXField) pnt2.Y=row.getValue(DYField) lineArray.add(pnt2) insRow.shape=lineArray insRow.DistanceSL=math.sqrt(math.pow(pnt2.X-pnt1.X,2)+math.pow(pnt2.Y-pnt1.Y,2)) insRows.insertRow(insRow) x+=1 #TODO: add something about progress else: tkMessageBox.showerror("Error Creating Featureclass","You need to select a field for ALL input boxes!") except Exception as e: tkMessageBox.showerror("Error Creating Featureclass",e.message) def graphOB(self): #Graphs Origin-Boarding Locations try: #Check Inputs if 1==1: #self.modeToCombo.get() and self.oxCombo.get() and self.oyCombo.get() and self.bxCombo.get() and self.byCombo.get() and self.surveyBusCombo.get() and self.firstBusCombo.get(): ###Not needed #SurveyIDField=self.idCombo.get() #ModeFrField=self.modeFrCombo.get() #AXField=self.axCombo.get() #AYField=self.ayCombo.get() #DXField=self.dxCombo.get() #DYField=self.dyCombo.get() ## Debugging ##ModeToField=self.modeToCombo.get() ModeToField="OGET" ##OXField=self.oxCombo.get() OXField="OXCORD" ##OYField=self.oyCombo.get() OYField="OYCORD" ##BXField=self.bxCombo.get() BXField="BX" ##BYField=self.byCombo.get() BYField="BY_" ##sBusField=self.surveyBusCombo.get() sBusField="RTCODE" ##fBusField=self.firstBusCombo.get() fBusField="BUS1" #read all this stuff into an array rows=arcpy.SearchCursor(self.tableLB.get()) x=1 rowData=[] for row in rows: if(x % 100 == 0): print "Reading on ",x if(row.getValue(sBusField)==row.getValue(fBusField)): if(row.getValue(OXField)>0 and row.getValue(BXField)>0 and row.getValue(OYField)>0 and row.getValue(BYField)>0): iRow=[row.getValue(ModeToField),math.sqrt(math.pow(row.getValue(OXField)-row.getValue(BXField),2)+math.pow(row.getValue(OYField)-row.getValue(BYField),2))/5280] rowData.append(iRow) newRowData=self.sortList(rowData) #Graph creation iWalk=0 iBike=0 iDrive=0 graphItemsWalk=[] graphItemsBike=[] graphItemsDrive=[] for item in newRowData: if(item[0]==1): graphItemsWalk.append((iWalk,item[1])) iWalk+=1 elif(item[0]==2): graphItemsBike.append((iBike,item[1])) iBike+=1 else: graphItemsDrive.append((iDrive,item[1])) iDrive+=1 if(iWalk==0): graphItemsWalk.append((0,0)) if(iBike==0): graphItemsBike.append((0,0)) if(iDrive==0): graphItemsDrive.append((0,0)) graphItems=[] giWalk=[] giBike=[] giDrive=[] for item in graphItemsWalk: giWalk.append((item[0]*100/iWalk,item[1])) for item in graphItemsBike: giBike.append((item[0]*100/iBike,item[1])) for item in graphItemsDrive: giDrive.append((item[0]*100/iDrive,item[1])) graphItems.append(giWalk) graphItems.append(giBike) graphItems.append(giDrive) cairoplot.scatter_plot('C:\\GraphO2B.SVG',data=graphItems,width=600,height=400,border=20,axis=True,grid=True,series_colors=[(1,0,0),(0,1,0),(0,0,1)],y_title='Miles') cairoplot.scatter_plot('C:\\GraphO2B_Walk.SVG',data=graphItemsWalk,width=600,height=400,border=20,axis=True,grid=True,series_colors=[(1,0,0)],y_title='Miles') cairoplot.scatter_plot('C:\\GraphO2B_Bike.SVG',data=graphItemsBike,width=600,height=400,border=20,axis=True,grid=True,series_colors=[(1,0,0)],y_title='Miles') cairoplot.scatter_plot('C:\\GraphO2B_Drive.SVG',data=graphItemsDrive,width=600,height=400,border=20,axis=True,grid=True,series_colors=[(1,0,0)],y_title='Miles') print "Completed for now" except Exception as e: tkMessageBox.showerror("Problem somewhere",e.message) def graphAD(self): #Graphs Origin-Boarding Locations try: #Check Inputs if 1==1: #self.modeFromCombo.get() and self.oxCombo.get() and self.oyCombo.get() and self.bxCombo.get() and self.byCombo.get() and self.surveyBusCombo.get() and self.firstBusCombo.get(): ###Not needed #SurveyIDField=self.idCombo.get() #ModeFrField=self.modeFrCombo.get() #AXField=self.axCombo.get() #AYField=self.ayCombo.get() #DXField=self.dxCombo.get() #DYField=self.dyCombo.get() ## Debugging ##ModeToField=self.modeToCombo.get() ModeFromField="DGET" ##DXField=self.oxCombo.get() DXField="DXCORD" ##OYField=self.oyCombo.get() DYField="DYCORD" ##BXField=self.bxCombo.get() AXField="AX" ##BYField=self.byCombo.get() AYField="AY" ##sBusField=self.surveyBusCombo.get() sBusField="RTCODE" ##fBusField=self.firstBusCombo.get() fBusField="BUS1" #read all this stuff into an array rows=arcpy.SearchCursor(self.tableLB.get()) x=1 rowData=[] for row in rows: if(row.getValue("BUS4")): lastBus=row.getValue("BUS4") elif(row.getValue("BUS3")): lastBus=row.getValue("BUS3") elif(row.getValue("BUS2")): lastBus=row.getValue("BUS2") else: lastBus=row.getValue("BUS1") if(x % 100 == 0): print "Reading on ",x if(row.getValue(sBusField)==lastBus): if(row.getValue(DXField)>0 and row.getValue(AXField)>0 and row.getValue(DYField)>0 and row.getValue(AYField)>0): iRow=[row.getValue(ModeFromField),math.sqrt(math.pow(row.getValue(DXField)-row.getValue(AXField),2)+math.pow(row.getValue(DYField)-row.getValue(AYField),2))/5280] rowData.append(iRow) newRowData=self.sortList(rowData) #Graph creation iWalk=0 iBike=0 iDrive=0 graphItemsWalk=[] graphItemsBike=[] graphItemsDrive=[] for item in newRowData: if(item[0]==1): graphItemsWalk.append((iWalk,item[1])) iWalk+=1 elif(item[0]==2): graphItemsBike.append((iBike,item[1])) iBike+=1 else: graphItemsDrive.append((iDrive,item[1])) iDrive+=1 if(iWalk==0): graphItemsWalk.append((0,0)) iWalk=1 if(iBike==0): graphItemsBike.append((0,0)) iBike=1 if(iDrive==0): graphItemsDrive.append((0,0)) iDrive=1 graphItems=[] giWalk=[] giBike=[] giDrive=[] for item in graphItemsWalk: giWalk.append((item[0]*100/iWalk,item[1])) for item in graphItemsBike: giBike.append((item[0]*100/iBike,item[1])) for item in graphItemsDrive: giDrive.append((item[0]*100/iDrive,item[1])) graphItems.append(giWalk) graphItems.append(giBike) graphItems.append(giDrive) cairoplot.scatter_plot('C:\\GraphA2D.SVG',data=graphItems,width=600,height=400,border=20,axis=True,grid=True,series_colors=[(1,0,0),(0,1,0),(0,0,1)],y_title='Miles') cairoplot.scatter_plot('C:\\GraphA2D_Walk.SVG',data=graphItemsWalk,width=600,height=400,border=20,axis=True,grid=True,series_colors=[(1,0,0)],y_title='Miles') cairoplot.scatter_plot('C:\\GraphA2D_Bike.SVG',data=graphItemsBike,width=600,height=400,border=20,axis=True,grid=True,series_colors=[(1,0,0)],y_title='Miles') cairoplot.scatter_plot('C:\\GraphA2D_Drive.SVG',data=graphItemsDrive,width=600,height=400,border=20,axis=True,grid=True,series_colors=[(1,0,0)],y_title='Miles') print "Completed for now" except Exception as e: tkMessageBox.showerror("Problem somewhere",e.message) def sortList(self,list): recs=len(list) outputlist=[] currentlowest=[] while len(outputlist)<recs: for item in list: if(currentlowest==[]): currentlowest=item for itemcompare in list: if(itemcompare[1]>item[1]): item=itemcompare #At this point, item should be the smallest distance in list outputlist.append(item) list.remove(item) return outputlist def QCVars(self): if(tkMessageBox.askyesno("Modify Table","This WILL modify the input table. Continue?") and self.tableLB.get()): print "This battlestation will be fully operational" #check for and delete QC fields inputFeatClass=self.tableLB.get() fieldList=arcpy.ListFields(inputFeatClass,"QC_*") for field in fieldList: arcpy.DeleteField_management(inputFeatClass,field.name) arcpy.AddField_management(inputFeatClass,"QC_WalkToDistance","DOUBLE") arcpy.AddField_management(inputFeatClass,"QC_BikeToDistance","DOUBLE") arcpy.AddField_management(inputFeatClass,"QC_DriveToDistance","DOUBLE") arcpy.AddField_management(inputFeatClass,"QC_WalkFromDistance","DOUBLE") arcpy.AddField_management(inputFeatClass,"QC_BikeFromDistance","DOUBLE") arcpy.AddField_management(inputFeatClass,"QC_DriveFromDistance","DOUBLE") arcpy.AddField_management(inputFeatClass,"QC_DriveToLocalRoute","SHORT") arcpy.AddField_management(inputFeatClass,"QC_BoardWrongState","SHORT") arcpy.AddField_management(inputFeatClass,"QC_AlightWrongState","SHORT") #Field Definitions #if(self.modeToCombo.get() and self.oxCombo.get() and self.oyCombo.get() and self.bxCombo.get() and self.byCombo.get() and self.surveyBusCombo.get() and self.firstBusCombo.get(): ###Not needed #SurveyIDField=self.idCombo.get() #ModeFrField=self.modeFrCombo.get() #AXField=self.axCombo.get() #AYField=self.ayCombo.get() #DXField=self.dxCombo.get() #DYField=self.dyCombo.get() ## Debugging ##ModeToField=self.modeToCombo.get() ModeToField="OGET" ##OXField=self.oxCombo.get() OXField="OXCORD" ##OYField=self.oyCombo.get() OYField="OYCORD" ##BXField=self.bxCombo.get() BXField="BX" ##BYField=self.byCombo.get() BYField="BY_" ##sBusField=self.surveyBusCombo.get() sBusField="RTCODE" ##fBusField=self.firstBusCombo.get() fBusField="BUS1" #read all this stuff into an array ModeFromField="DGET" ##DXField=self.oxCombo.get() DXField="DXCORD" ##OYField=self.oyCombo.get() DYField="DYCORD" ##BXField=self.bxCombo.get() AXField="AX" ##BYField=self.byCombo.get() AYField="AY" ##sBusField=self.surveyBusCombo.get() rows=arcpy.UpdateCursor(self.tableLB.get()) x=1 rowData=[] for row in rows: if(x % 100 == 0): print "Reading on ",x #ToDistance if(row.getValue(sBusField)==row.getValue(fBusField)): if(row.getValue(OXField)>0 and row.getValue(BXField)>0 and row.getValue(OYField)>0 and row.getValue(BYField)>0): dist=math.sqrt(math.pow(row.getValue(OXField)-row.getValue(BXField),2)+math.pow(row.getValue(OYField)-row.getValue(BYField),2))/5280 if(row.getValue(ModeToField)==1): row.setValue("QC_WalkToDistance",dist) elif(row.getValue(ModeToField)==2): row.setValue("QC_BikeToDistance",dist) else: row.setValue("QC_DriveToDistance",dist) else: row.setValue("QC_WalkToDistance",-1) row.setValue("QC_BikeToDistance",-1) row.setValue("QC_DriveToDistance",-1) #FromDistance if(row.getValue("BUS4")): lastBus=row.getValue("BUS4") elif(row.getValue("BUS3")): lastBus=row.getValue("BUS3") elif(row.getValue("BUS2")): lastBus=row.getValue("BUS2") else: lastBus=row.getValue("BUS1") if(row.getValue(sBusField)==lastBus): if(row.getValue(DXField)>0 and row.getValue(AXField)>0 and row.getValue(DYField)>0 and row.getValue(AYField)>0): dist=math.sqrt(math.pow(row.getValue(DXField)-row.getValue(AXField),2)+math.pow(row.getValue(DYField)-row.getValue(AYField),2))/5280 if(row.getValue(ModeFromField)==1): row.setValue("QC_WalkFromDistance",dist) elif(row.getValue(ModeFromField)==2): row.setValue("QC_BikeFromDistance",dist) else: row.setValue("QC_DriveFromDistance",dist) else: row.setValue("QC_WalkFromDistance",-1) row.setValue("QC_BikeFromDistance",-1) row.setValue("QC_DriveFromDistance",-1) rows.updateRow(row) print "DBG: Complete for now" elif(self.tableLB.get()==''): tkMessageBox.showerror("Problem","You must select a table to proceed") else: print "Your lack of faith is disturbing" def cupholder(self): tkMessageBox.showinfo("Cupholder","Lord Vadar finds your computer's lack of a cupholder disturbing.") ctypes.windll.WINMM.mciSendStringW(u"set cdaudio door open",None,0,None)
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 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 Application(Frame): def __init__(self, master=None, config=config): self.config = config self.log = logging.getLogger("{0}.{1}".format(self.__class__.__name__, id(self))) self.display_connections = False Frame.__init__(self, master) self.grid() Style().configure("TFrame", background="#444") self.paint_tile = 1 self.init_ui() def init_ui(self): self.connections = {} self.button_frame = Frame(self) self.button_frame.grid(row=0, column=0, columnspan=2) self.map_frame = Frame(self) self.map_frame.grid(row=1, column=0, padx=5, pady=5) self.picker_frame = Frame(self) self.picker_frame.grid(row=1, column=1) self.button_new = Button(self.button_frame) self.button_new["text"] = "New" self.button_new["command"] = self.new_map self.button_new.grid(row=0, column=0, padx=2) self.open = Button(self.button_frame) self.open["text"] = "Open" self.open["command"] = self.open_map self.open.grid(row=0, column=1, padx=2) self.save = Button(self.button_frame) self.save["text"] = "Save" self.save["command"] = self.save_map self.save.grid(row=0, column=2, padx=2) self.get_map_list() self.map_list.grid(row=0, column=3, padx=2) def get_map_list(self): self.available_maps = sorted( m for m in get_available_maps(config=self.config)) self.map_list = Combobox(self.button_frame, height=24, width=24, values=self.available_maps) if len(self.available_maps): self.map_list.set(self.available_maps[0]) def new_map(self): self.map_name = None self.init_map() self.map.blockdata_filename = os.path.join(self.config.map_dir, 'newmap.blk') self.map.blockdata = bytearray([self.paint_tile] * 20 * 20) self.map.width = 20 self.map.height = 20 self.draw_map() self.init_picker() def open_map(self): self.map_name = self.map_list.get() self.init_map() self.draw_map() self.init_picker() def save_map(self): if hasattr(self, 'map'): if self.map.blockdata_filename: filename = tkFileDialog.asksaveasfilename( initialfile=self.map.blockdata_filename) with open(filename, 'wb') as save: save.write(self.map.blockdata) self.log.info('blockdata saved as {}'.format( self.map.blockdata_filename)) else: self.log.info('dunno how to save this') else: self.log.info('nothing to save') def init_map(self): if hasattr(self, 'map'): self.map.kill_canvas() self.map = Map(self.map_frame, self.map_name, config=self.config) self.init_map_connections() def draw_map(self): self.map.init_canvas(self.map_frame) self.map.canvas.pack() #.grid(row=1,column=1) self.map.draw() self.map.canvas.bind('<Button-1>', self.paint) self.map.canvas.bind('<B1-Motion>', self.paint) def init_picker(self): self.current_tile = Map(self.button_frame, tileset_id=self.map.tileset_id, config=self.config) self.current_tile.blockdata = [self.paint_tile] self.current_tile.width = 1 self.current_tile.height = 1 self.current_tile.init_canvas() self.current_tile.draw() self.current_tile.canvas.grid(row=0, column=4, padx=4) if hasattr(self, 'picker'): self.picker.kill_canvas() self.picker = Map(self, tileset_id=self.map.tileset_id, config=self.config) self.picker.blockdata = range(len(self.picker.tileset.blocks)) self.picker.width = 4 self.picker.height = len(self.picker.blockdata) / self.picker.width self.picker.init_canvas(self.picker_frame) if hasattr(self.picker_frame, 'vbar'): self.picker_frame.vbar.destroy() self.picker_frame.vbar = Scrollbar(self.picker_frame, orient=VERTICAL) self.picker_frame.vbar.pack(side=RIGHT, fill=Y) self.picker_frame.vbar.config(command=self.picker.canvas.yview) self.picker.canvas.config(scrollregion=(0, 0, self.picker.canvas_width, self.picker.canvas_height)) self.map_frame.update() self.picker.canvas.config(height=self.map_frame.winfo_height()) self.picker.canvas.config(yscrollcommand=self.picker_frame.vbar.set) self.picker.canvas.pack(side=LEFT, expand=True) self.picker.canvas.bind('<4>', lambda event: self.scroll_picker(event)) self.picker.canvas.bind('<5>', lambda event: self.scroll_picker(event)) self.picker_frame.vbar.bind('<4>', lambda event: self.scroll_picker(event)) self.picker_frame.vbar.bind('<5>', lambda event: self.scroll_picker(event)) self.picker.draw() self.picker.canvas.bind('<Button-1>', self.pick_block) def scroll_picker(self, event): if event.num == 4: self.picker.canvas.yview('scroll', -1, 'units') elif event.num == 5: self.picker.canvas.yview('scroll', 1, 'units') def pick_block(self, event): block_x = int(self.picker.canvas.canvasx(event.x)) / ( self.picker.tileset.block_width * self.picker.tileset.tile_width) block_y = int(self.picker.canvas.canvasy(event.y)) / ( self.picker.tileset.block_height * self.picker.tileset.tile_height) i = block_y * self.picker.width + block_x self.paint_tile = self.picker.blockdata[i] self.current_tile.blockdata = [self.paint_tile] self.current_tile.draw() def paint(self, event): block_x = event.x / (self.map.tileset.block_width * self.map.tileset.tile_width) block_y = event.y / (self.map.tileset.block_height * self.map.tileset.tile_height) i = block_y * self.map.width + block_x if 0 <= i < len(self.map.blockdata): self.map.blockdata[i] = self.paint_tile self.map.draw_block(block_x, block_y) def init_map_connections(self): if not self.display_connections: return for direction in self.map.connections.keys(): if direction in self.connections.keys(): if hasattr(self.connections[direction], 'canvas'): self.connections[direction].kill_canvas() if self.map.connections[direction] == {}: self.connections[direction] = {} continue self.connections[direction] = Map( self, self.map.connections[direction]['map_name'], config=self.config) if direction in ['north', 'south']: x1 = 0 y1 = 0 x2 = x1 + eval(self.map.connections[direction]['strip_length'], self.config.constants) y2 = y1 + 3 else: # east, west x1 = 0 y1 = 0 x2 = x1 + 3 y2 = y1 + eval(self.map.connections[direction]['strip_length'], self.config.constants) self.connections[direction].crop(x1, y1, x2, y2) self.connections[direction].init_canvas(self.map_frame) self.connections[direction].canvas.pack(side={ 'west': LEFT, 'east': RIGHT }[direction]) self.connections[direction].draw()
class Window(Tk): def __init__(self): Tk.__init__(self) # Global Elements self.main_color = '#333333' self.sub_color = '#444444' self.the_file = None self.upper_list = [ 'SELECT', 'FROM', 'ORDER', 'GROUP', 'BY', 'IS', 'NULL', 'ISNULL', 'NOTNULL', 'TRUE', 'FALSE', 'JOIN', 'LEFT', 'RIGHT', 'WHERE', 'HAVING', 'PARTITION', 'OVER', 'WITH', 'AS', 'NOT', 'AND', 'OR', 'ON', 'IN', 'BETWEEN', 'UNBOUNDED', 'PROCEEDING', 'FOLLOWING', 'UNION', 'ALL', 'CASE', 'WHEN', 'THEN', 'ELSE', 'END', 'COALESCE', 'NVL', 'AVG', 'MAX', 'SUM', 'COUNT', 'WITHIN', 'LISTAGG' ] text_box_font_options = { 'name': [ 'none', 'Courier', 'Georgia', 'Gothic', 'Impact', 'System', 'Tahoma', 'Times', 'Verdana' ], 'size': [] } for num in range(6, 101): text_box_font_options['size'].append(num) # Program attributes self.state('zoomed') # starts maximized self.title('Casing Formatter') self.config(bg=self.main_color) # Frames self.main_frame = Frame(self, bg=self.main_color, width=600, height=400) self.main_frame.pack(side=TOP, fill=BOTH, expand=TRUE) self.button_frame = Frame(self.main_frame, bg=self.main_color) self.button_frame.pack(side=LEFT, fill=BOTH) self.text_frame = Frame(self.main_frame, bg=self.main_color) self.text_frame.pack( side=LEFT, fill=BOTH, expand=TRUE, ) # Scrollbar self.text_scrollbar = Scrollbar(self.main_frame) self.text_scrollbar.pack(side=RIGHT, fill=BOTH) # Buttons button_font = 'helvetica 18 bold' self.open_file_button = Button(self.button_frame, text='Open File', command=self.open_file, font='helvetica 14', relief=RAISED, bg='deepskyblue4', fg='white') self.open_file_button.pack(side=TOP, padx=5, pady=4) self.upper_button = Button(self.button_frame, text='A', width=3, command=self.cap_file, font=button_font, relief=RAISED, bg=self.sub_color, fg='white') self.upper_button.pack(side=TOP, padx=5, pady=4) self.lower_button = Button(self.button_frame, text='a', width=3, command=self.lower_file, font=button_font, relief=RAISED, bg=self.sub_color, fg='white') self.lower_button.pack(side=TOP, padx=5, pady=4) self.semi_lower_button = Button(self.button_frame, text='Ab', width=3, command=self.semi_lower_file, font=button_font, relief=RAISED, bg=self.sub_color, fg='white') self.semi_lower_button.pack(side=TOP, padx=5, pady=4) self.semi_lower_button = Button(self.button_frame, text='Apply Font', command=self.text_box_font, font='helvetica 14', relief=RAISED, bg=self.sub_color, fg='white') self.semi_lower_button.pack(side=BOTTOM, padx=5, pady=4) # Font drop-down menus self.font_name_dropdown = Combobox( self.button_frame, values=text_box_font_options['name'], justify='center') self.font_name_dropdown.set(text_box_font_options['name'][0]) self.font_name_dropdown.pack(side=BOTTOM, padx=5, pady=4) self.font_style = self.font_name_dropdown.get() self.font_size_dropdown = Combobox( self.button_frame, values=text_box_font_options['size'], justify='center') self.font_size_dropdown.set(12) self.font_size_dropdown.pack(side=BOTTOM, padx=5, pady=4) self.text_font_size = self.font_size_dropdown.get() # Text boxes self.text_box_before = Text(self.text_frame, relief=SUNKEN, bg=self.sub_color, fg='grey', font=(self.font_style, self.text_font_size), wrap=WORD, yscrollcommand=self.text_scrollbar.set) self.text_box_before.pack(side=LEFT, fill=BOTH, expand=TRUE, padx=2) self.text_box_after = Text(self.text_frame, relief=SUNKEN, bg=self.sub_color, fg='grey', font=(self.font_style, self.text_font_size), wrap=WORD, yscrollcommand=self.text_scrollbar.set) self.text_box_after.pack(side=LEFT, fill=BOTH, expand=TRUE, padx=2) self.text_scrollbar.config(command=self.yview) # Bottom Status bar self.status_text = StringVar() self.status_text.set('') self.status_label = Label(self, textvariable=self.status_text, relief=SUNKEN, font='system 8', fg='#333333') self.status_label.pack(side=BOTTOM, fill=X) def yview(self, *args): # Used to make both text boxes scroll at the same time self.text_box_before.yview(*args) self.text_box_after.yview(*args) def create_output_file(self): # This allows you to choose a directory for the output file self.savedir = tkFileDialog.askdirectory( title='Select folder to save results') if self.savedir != '': self.output_file = open(self.savedir + '/' + self.open_file, 'w') else: self.status_text.set('') self.status_label.config(bg='white') def cap_file(self): if self.the_file != None: sql_file = self.the_file.read() self.create_output_file() self.output_file.write(sql_file.upper()) self.output_file.close() new_sql_file = open(self.savedir + '/' + self.open_file, 'r') self.text_box_before.insert(END, sql_file) self.text_box_after.insert(END, new_sql_file.read()) new_sql_file.close() self.status_text.set('Saved as: ' + self.open_file) self.status_label.config(bg='#777777') self.text_color() def lower_file(self): if self.the_file != None: sql_file = self.the_file.read() self.create_output_file() self.output_file.write(sql_file.lower()) self.output_file.close() new_sql_file = open(self.savedir + '/' + self.open_file, 'r') self.text_box_before.insert(END, sql_file) self.text_box_after.insert(END, new_sql_file.read()) new_sql_file.close() self.status_text.set('Saved as: ' + self.open_file) self.status_label.config(bg='#777777') self.text_color() def semi_lower_file(self): if self.the_file != None: sql_file = self.the_file.read() temp_split = sql_file.split(' ') sql_file_formatted = [] for item in temp_split: for word in re.sub(r'[^A-Za-z0-9._]', '\n', item).split('\n'): if word.upper() in self.upper_list: item = item.replace(word, word.upper()) else: item = item.replace(word, word.lower()) sql_file_formatted.append(item) sql_file_formatted = ' '.join(sql_file_formatted) self.create_output_file() self.output_file.write(sql_file_formatted) self.output_file.close() new_sql_file = open(self.savedir + '/' + self.open_file, 'r') self.text_box_before.insert(END, sql_file) self.text_box_after.insert(END, new_sql_file.read()) new_sql_file.close() self.status_text.set('Saved as: ' + self.open_file) self.status_label.config(bg='#777777') self.text_color() def open_file(self): self.text_box_before.delete(1.0, END) self.text_box_after.delete(1.0, END) self.the_file = tkFileDialog.askopenfile( parent=self, mode='r', title='Choose a file to format...') if self.the_file != None: self.open_file = re.sub( r'[^A-Za-z0-9._]', '', str(self.the_file).split(' ')[2].split('/')[-1]) self.status_text.set('Selected: ' + self.open_file) self.status_label.config(bg='lightblue') else: self.status_text.set('') self.status_label.config(bg='white') return self.the_file def text_color(self): # Colors the words in the before and after text boxes, for the words that are in the upper list temp_split = self.text_box_after.get(1.0, END) temp_split = temp_split.split('\n') line_count = 0 for line in temp_split: line_count += 1 temp_list = re.sub(r'[^A-Za-z0-9._]', ' ', line).split(' ') recon = [] for item in temp_list: recon.append(item) letter = len(' '.join(recon)) if item.upper() in self.upper_list: self.text_box_after.tag_add( "start", str(line_count) + "." + str(letter - len(item)), str(line_count) + "." + str(letter)) self.text_box_after.tag_config("start", foreground='orange', font=(self.font_style, self.text_font_size, ' bold')) self.text_box_before.tag_add( "start", str(line_count) + "." + str(letter - len(item)), str(line_count) + "." + str(letter)) self.text_box_before.tag_config("start", foreground='orange', font=(self.font_style, self.text_font_size, ' bold')) def text_box_font(self): self.text_box_after.tag_add("font", 1.0, END) self.text_box_after.tag_config("font", font=(self.font_name_dropdown.get(), self.font_size_dropdown.get())) self.text_box_before.tag_add("font", 1.0, END) self.text_box_before.tag_config("font", font=(self.font_name_dropdown.get(), self.font_size_dropdown.get()))
class Application(Frame): def __init__(self, master=None, config=config): self.config = config self.log = logging.getLogger("{0}.{1}".format(self.__class__.__name__, id(self))) self.display_connections = True Frame.__init__(self, master) self.pack(fill=BOTH, expand=True) Style().configure("TFrame", background="#444") self.paint_tile = 1 self.init_ui() def init_ui(self): self.connections = {} self.button_frame = Frame(self) self.button_frame.grid(row=0, column=0, columnspan=2) self.map_frame = Frame(self) self.map_frame.grid(row=1, column=0, padx=5, pady=5, sticky=N + S + E + W) self.picker_frame = Frame(self) self.picker_frame.grid(row=1, column=1) self.button_new = Button(self.button_frame) self.button_new["text"] = "New" self.button_new["command"] = self.new_map self.button_new.grid(row=0, column=0, padx=2) self.menubar = Menu(self) menu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="File", menu=menu) menu.add_command(label="New") menu.add_command(label="Open") menu.add_command(label="Save") self.open = Button(self.button_frame) self.open["text"] = "Open" self.open["command"] = self.open_map self.open.grid(row=0, column=1, padx=2) self.save = Button(self.button_frame) self.save["text"] = "Save" self.save["command"] = self.save_map self.save.grid(row=0, column=2, padx=2) self.get_map_list() self.map_list.grid(row=0, column=3, padx=2) def get_map_list(self): self.available_maps = sorted( m for m in get_available_maps(config=self.config)) self.map_list = Combobox(self.button_frame, height=24, width=24, values=self.available_maps) if len(self.available_maps): self.map_list.set(self.available_maps[0]) def new_map(self): self.map_name = None self.init_map() self.map.map.blockdata = bytearray([self.paint_tile] * 20 * 20) self.map.map.width = 20 self.map.map.height = 20 self.draw_map() self.init_picker() def open_map(self): self.map_name = self.map_list.get() self.init_map() self.draw_map() self.init_picker() def save_map(self): if hasattr(self, 'map'): if self.map.map.blk_path: initial = self.map.map.blk_path else: initial = self.config.path filename = tkFileDialog.asksaveasfilename(initialfile=initial) if filename: with open(filename, 'wb') as save: save.write(self.map.map.blockdata) self.log.info('blockdata saved as {}'.format(filename)) else: self.log.info('nothing to save') def init_map(self): if hasattr(self, 'map'): self.map.kill_canvas() self.map = MapRenderer(self.config, parent=self.map_frame, name=self.map_name) self.init_map_connections() def draw_map(self): self.map.init_canvas(self.map_frame) self.map.canvas.pack() #.grid(row=1,column=1) self.map.draw() self.map.canvas.bind('<Button-1>', self.paint) self.map.canvas.bind('<B1-Motion>', self.paint) def init_picker(self): """This should really be its own class.""" self.current_tile = MapRenderer( self.config, parent=self.button_frame, tileset=Tileset(id=self.map.map.tileset.id)) self.current_tile.map.blockdata = [self.paint_tile] self.current_tile.map.width = 1 self.current_tile.map.height = 1 self.current_tile.init_canvas() self.current_tile.draw() self.current_tile.canvas.grid(row=0, column=4, padx=4) if hasattr(self, 'picker'): self.picker.kill_canvas() self.picker = MapRenderer(self.config, parent=self, tileset=Tileset(id=self.map.map.tileset.id)) self.picker.map.blockdata = range(len(self.picker.map.tileset.blocks)) self.picker.map.width = 4 self.picker.map.height = len( self.picker.map.blockdata) / self.picker.map.width self.picker.init_canvas(self.picker_frame) if hasattr(self.picker_frame, 'vbar'): self.picker_frame.vbar.destroy() self.picker_frame.vbar = Scrollbar(self.picker_frame, orient=VERTICAL) self.picker_frame.vbar.pack(side=RIGHT, fill=Y) self.picker_frame.vbar.config(command=self.picker.canvas.yview) self.picker.canvas.config(scrollregion=(0, 0, self.picker.canvas_width, self.picker.canvas_height)) self.map_frame.update() # overwriting a property is probably a bad idea self.picker.canvas_height = self.map_frame.winfo_height() self.picker.canvas.config(yscrollcommand=self.picker_frame.vbar.set) self.picker.canvas.pack(side=LEFT, expand=True) self.picker.canvas.bind('<4>', lambda event: self.scroll_picker(event)) self.picker.canvas.bind('<5>', lambda event: self.scroll_picker(event)) self.picker_frame.vbar.bind('<4>', lambda event: self.scroll_picker(event)) self.picker_frame.vbar.bind('<5>', lambda event: self.scroll_picker(event)) self.picker.draw() self.picker.canvas.bind('<Button-1>', self.pick_block) def scroll_picker(self, event): if event.num == 4: self.picker.canvas.yview('scroll', -1, 'units') elif event.num == 5: self.picker.canvas.yview('scroll', 1, 'units') def pick_block(self, event): block_x = int(self.picker.canvas.canvasx( event.x)) / (self.picker.map.tileset.block_width * self.picker.map.tileset.tile_width) block_y = int(self.picker.canvas.canvasy( event.y)) / (self.picker.map.tileset.block_height * self.picker.map.tileset.tile_height) i = block_y * self.picker.map.width + block_x self.paint_tile = self.picker.map.blockdata[i] self.current_tile.map.blockdata = [self.paint_tile] self.current_tile.draw() def paint(self, event): block_x = event.x / (self.map.map.tileset.block_width * self.map.map.tileset.tile_width) block_y = event.y / (self.map.map.tileset.block_height * self.map.map.tileset.tile_height) i = block_y * self.map.map.width + block_x if 0 <= i < len(self.map.map.blockdata): self.map.map.blockdata[i] = self.paint_tile self.map.draw_block(block_x, block_y) def init_map_connections(self): if not self.display_connections: return for direction in self.map.map.connections.keys(): if direction in self.connections.keys(): if hasattr(self.connections[direction], 'canvas'): self.connections[direction].kill_canvas() if self.map.map.connections[direction] == {}: self.connections[direction] = {} continue self.connections[direction] = MapRenderer( self.config, parent=self, name=self.map.map.connections[direction]['map_name']) attrs = self.map.map.connections[direction] if direction in ['north', 'south']: if direction == 'north': x1 = 0 if self.config.version == 'red': y1 = eval(attrs['other_height'], self.config.constants) - 3 elif self.config.version == 'crystal': y1 = eval(attrs['map'] + '_HEIGHT', self.config.constants) - 3 else: # south x1 = 0 y1 = 0 x2 = x1 + eval(attrs['strip_length'], self.config.constants) y2 = y1 + 3 else: if direction == 'east': x1 = 0 y1 = 0 else: # west x1 = -3 y1 = 1 x2 = x1 + 3 y2 = y1 + eval(attrs['strip_length'], self.config.constants) self.connections[direction].init_canvas(self.map_frame) self.connections[direction].canvas.pack(side={ 'north': TOP, 'south': BOTTOM, 'west': LEFT, 'east': RIGHT }[direction]) self.connections[direction].map.crop(x1, y1, x2, y2) self.connections[direction].draw()
class MainWindow(Tk): def __init__(self): Tk.__init__(self) self.title(mainWindowTitle) self.resizable(width=0, height=0) self.__setStyles() self.__initializeComponents() self.__dataController = DataController(); self.mainloop() def __initializeComponents(self): self.imageCanvas = Canvas(master=self, width=imageCanvasWidth, height=windowElementsHeight, bg="white") self.imageCanvas.pack(side=LEFT, padx=(windowPadding, 0), pady=windowPadding, fill=BOTH) self.buttonsFrame = Frame(master=self, width=buttonsFrameWidth, height=windowElementsHeight) self.buttonsFrame.propagate(0) self.loadFileButton = Button(master=self.buttonsFrame, text=loadFileButtonText, command=self.loadFileButtonClick) self.loadFileButton.pack(fill=X, pady=buttonsPadding); self.colorByLabel = Label(self.buttonsFrame, text=colorByLabelText) self.colorByLabel.pack(fill=X) self.colorByCombobox = Combobox(self.buttonsFrame, state=DISABLED, values=colorByComboboxValues) self.colorByCombobox.set(colorByComboboxValues[0]) self.colorByCombobox.bind("<<ComboboxSelected>>", self.__colorByComboboxChange) self.colorByCombobox.pack(fill=X, pady=buttonsPadding) self.rejectedValuesPercentLabel = Label(self.buttonsFrame, text=rejectedMarginLabelText) self.rejectedValuesPercentLabel.pack(fill=X) self.rejectedValuesPercentEntry = Entry(self.buttonsFrame) self.rejectedValuesPercentEntry.insert(0, defaultRejectedValuesPercent) self.rejectedValuesPercentEntry.config(state=DISABLED) self.rejectedValuesPercentEntry.pack(fill=X, pady=buttonsPadding) self.colorsSettingsPanel = Labelframe(self.buttonsFrame, text=visualisationSettingsPanelText) self.colorsTableLengthLabel = Label(self.colorsSettingsPanel, text=colorsTableLengthLabelText) self.colorsTableLengthLabel.pack(fill=X) self.colorsTableLengthEntry = Entry(self.colorsSettingsPanel) self.colorsTableLengthEntry.insert(0, defaultColorsTableLength) self.colorsTableLengthEntry.config(state=DISABLED) self.colorsTableLengthEntry.pack(fill=X) self.scaleTypeLabel = Label(self.colorsSettingsPanel, text=scaleTypeLabelText) self.scaleTypeLabel.pack(fill=X) self.scaleTypeCombobox = Combobox(self.colorsSettingsPanel, state=DISABLED, values=scaleTypesComboboxValues) self.scaleTypeCombobox.set(scaleTypesComboboxValues[0]) self.scaleTypeCombobox.bind("<<ComboboxSelected>>", self.__scaleTypeComboboxChange) self.scaleTypeCombobox.pack(fill=X) self.colorsTableMinLabel = Label(self.colorsSettingsPanel, text=colorsTableMinLabelText) self.colorsTableMinLabel.pack(fill=X) self.colorsTableMinEntry = Entry(self.colorsSettingsPanel) self.colorsTableMinEntry.insert(0, defaultColorsTableMin) self.colorsTableMinEntry.config(state=DISABLED) self.colorsTableMinEntry.pack(fill=X) self.colorsTableMaxLabel = Label(self.colorsSettingsPanel, text=colorsTableMaxLabelText) self.colorsTableMaxLabel.pack(fill=X) self.colorsTableMaxEntry = Entry(self.colorsSettingsPanel) self.colorsTableMaxEntry.insert(0, defaultColorsTableMax) self.colorsTableMaxEntry.config(state=DISABLED) self.colorsTableMaxEntry.pack(fill=X) self.colorsSettingsPanel.pack(fill=X, pady=buttonsPadding) self.redrawButton = Button(master=self.buttonsFrame, text=redrawButtonText, state=DISABLED, command=self.__redrawButtonClick) self.redrawButton.pack(fill=X, pady=buttonsPadding) self.buttonsFrame.pack(side=RIGHT, padx=windowPadding, pady=windowPadding, fill=BOTH) def __setStyles(self): Style().configure("TButton", padding=buttonsTextPadding, font=buttonsFont) def loadFileButtonClick(self): fileName = tkFileDialog.askopenfilename(filetypes=[('Tablet files', '*.mtb'), ('Tablet files', '*.htd')]) if (fileName): if (not self.__getInputParams()): self.__showInvalidInputMessage() return self.lastFileName = fileName; self.title(mainWindowTitle + " " + fileName) self.__draw(fileName) tkMessageBox.showinfo(measureDialogTitle, measureDialogText + str(self.__dataController.getMeasure(fileName))) self.redrawButton.config(state=NORMAL) self.colorByCombobox.config(state="readonly") self.colorsTableLengthEntry.config(state=NORMAL) self.scaleTypeCombobox.config(state="readonly") def __redrawButtonClick(self): if (not self.__getInputParams()): self.__showInvalidInputMessage() return self.__draw(self.lastFileName) def __scaleTypeComboboxChange(self, event): if (self.scaleTypeCombobox.get() == relativeScaleType): self.colorsTableMinEntry.config(state=DISABLED) self.colorsTableMaxEntry.config(state=DISABLED) else: self.colorsTableMinEntry.config(state=NORMAL) self.colorsTableMaxEntry.config(state=NORMAL) def __colorByComboboxChange(self, event): if (self.colorByCombobox.get() == colorByNoneOption): self.rejectedValuesPercentEntry.config(state=DISABLED) else: self.rejectedValuesPercentEntry.config(state=NORMAL) def __draw(self, fileName): self.imageCanvas.delete(ALL) dataForDrawing = self.__dataController.getDataForDrawing( fileName, self.colorByCombobox.get(), self.colorsTableLength, self.scaleTypeCombobox.get(), self.colorsTableMinValue, self.colorsTableMaxValue, self.rejectedValuesPercent) for package in dataForDrawing: x = package[0]; y = package[1]; color = package[2]; self.imageCanvas.create_line(x, y, x + 1, y + 1, fill=color) def __drawColorBySpeed(self, dataPackages, minX, minY, ratio, hsv): allSpeeds = self.__getAllSpeeds(dataPackages) minSpeed = min(allSpeeds) maxSpeed = max(allSpeeds) if (self.scaleTypeCombobox.get() == relativeScaleType): colorsTableMinValue = minSpeed colorsTableMaxValue = maxSpeed else: colorsTableMinValue = self.colorsTableMinValue colorsTableMaxValue = self.colorsTableMaxValue i = 0 for package in dataPackages: x = (package[dataXNumber] - minX) * ratio y = (package[dataYNumber] - minY) * ratio color = hsv.getColorByValue(colorsTableMinValue, colorsTableMaxValue, allSpeeds[i]) tk_rgb = "#%02x%02x%02x" % color self.imageCanvas.create_line(x, y, x + 1, y + 1, fill=tk_rgb) i += 1 def __showInvalidInputMessage(self): tkMessageBox.showinfo(invalidInputMessageTitle, invalidInputMessageText) def __getInputParams(self): try: self.colorsTableLength = int(self.colorsTableLengthEntry.get()) self.colorsTableMinValue = float(self.colorsTableMinEntry.get()) self.colorsTableMaxValue = float(self.colorsTableMaxEntry.get()) self.rejectedValuesPercent = float(self.rejectedValuesPercentEntry.get()) if (self.colorsTableLength < 1 or self.colorsTableMinValue >= self.colorsTableMaxValue or self.rejectedValuesPercent < 0 or self.rejectedValuesPercent >= 100): raise return True except: return False
class Application(Frame): def __init__(self, master=None, config=config): self.config = config self.log = logging.getLogger("{0}.{1}".format(self.__class__.__name__, id(self))) self.display_connections = True Frame.__init__(self, master) self.pack(fill=BOTH, expand=True) Style().configure("TFrame", background="#444") self.paint_tile = 1 self.init_ui() def init_ui(self): self.connections = {} self.button_frame = Frame(self) self.button_frame.grid(row=0, column=0, columnspan=2) self.map_frame = Frame(self) self.map_frame.grid(row=1, column=0, padx=5, pady=5, sticky=N + S + E + W) self.picker_frame = Frame(self) self.picker_frame.grid(row=1, column=1) self.button_new = Button(self.button_frame) self.button_new["text"] = "New" self.button_new["command"] = self.new_map self.button_new.grid(row=0, column=0, padx=2) self.menubar = Menu(self) menu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="File", menu=menu) menu.add_command(label="New") menu.add_command(label="Open") menu.add_command(label="Save") self.open = Button(self.button_frame) self.open["text"] = "Open" self.open["command"] = self.open_map self.open.grid(row=0, column=1, padx=2) self.save = Button(self.button_frame) self.save["text"] = "Save" self.save["command"] = self.save_map self.save.grid(row=0, column=2, padx=2) self.get_map_list() self.map_list.grid(row=0, column=3, padx=2) def get_map_list(self): self.available_maps = sorted(m for m in get_available_maps(config=self.config)) self.map_list = Combobox(self.button_frame, height=24, width=24, values=self.available_maps) if len(self.available_maps): self.map_list.set(self.available_maps[0]) def new_map(self): self.map_name = None self.init_map() self.map.map.blockdata = bytearray([self.paint_tile] * 20 * 20) self.map.map.width = 20 self.map.map.height = 20 self.draw_map() self.init_picker() def open_map(self): self.map_name = self.map_list.get() self.init_map() self.draw_map() self.init_picker() def save_map(self): if hasattr(self, "map"): if self.map.map.blk_path: initial = self.map.map.blk_path else: initial = self.config.path filename = tkFileDialog.asksaveasfilename(initialfile=initial) if filename: with open(filename, "wb") as save: save.write(self.map.map.blockdata) self.log.info("blockdata saved as {}".format(filename)) else: self.log.info("nothing to save") def init_map(self): if hasattr(self, "map"): self.map.kill_canvas() self.map = MapRenderer(self.config, parent=self.map_frame, name=self.map_name) self.init_map_connections() def draw_map(self): self.map.init_canvas(self.map_frame) self.map.canvas.pack() # .grid(row=1,column=1) self.map.draw() self.map.canvas.bind("<Button-1>", self.paint) self.map.canvas.bind("<B1-Motion>", self.paint) def init_picker(self): """This should really be its own class.""" self.current_tile = MapRenderer( self.config, parent=self.button_frame, tileset=Tileset(id=self.map.map.tileset.id) ) self.current_tile.map.blockdata = [self.paint_tile] self.current_tile.map.width = 1 self.current_tile.map.height = 1 self.current_tile.init_canvas() self.current_tile.draw() self.current_tile.canvas.grid(row=0, column=4, padx=4) if hasattr(self, "picker"): self.picker.kill_canvas() self.picker = MapRenderer(self.config, parent=self, tileset=Tileset(id=self.map.map.tileset.id)) self.picker.map.blockdata = range(len(self.picker.map.tileset.blocks)) self.picker.map.width = 4 self.picker.map.height = len(self.picker.map.blockdata) / self.picker.map.width self.picker.init_canvas(self.picker_frame) if hasattr(self.picker_frame, "vbar"): self.picker_frame.vbar.destroy() self.picker_frame.vbar = Scrollbar(self.picker_frame, orient=VERTICAL) self.picker_frame.vbar.pack(side=RIGHT, fill=Y) self.picker_frame.vbar.config(command=self.picker.canvas.yview) self.picker.canvas.config(scrollregion=(0, 0, self.picker.canvas_width, self.picker.canvas_height)) self.map_frame.update() # overwriting a property is probably a bad idea self.picker.canvas_height = self.map_frame.winfo_height() self.picker.canvas.config(yscrollcommand=self.picker_frame.vbar.set) self.picker.canvas.pack(side=LEFT, expand=True) self.picker.canvas.bind("<4>", lambda event: self.scroll_picker(event)) self.picker.canvas.bind("<5>", lambda event: self.scroll_picker(event)) self.picker_frame.vbar.bind("<4>", lambda event: self.scroll_picker(event)) self.picker_frame.vbar.bind("<5>", lambda event: self.scroll_picker(event)) self.picker.draw() self.picker.canvas.bind("<Button-1>", self.pick_block) def scroll_picker(self, event): if event.num == 4: self.picker.canvas.yview("scroll", -1, "units") elif event.num == 5: self.picker.canvas.yview("scroll", 1, "units") def pick_block(self, event): block_x = int(self.picker.canvas.canvasx(event.x)) / ( self.picker.map.tileset.block_width * self.picker.map.tileset.tile_width ) block_y = int(self.picker.canvas.canvasy(event.y)) / ( self.picker.map.tileset.block_height * self.picker.map.tileset.tile_height ) i = block_y * self.picker.map.width + block_x self.paint_tile = self.picker.map.blockdata[i] self.current_tile.map.blockdata = [self.paint_tile] self.current_tile.draw() def paint(self, event): block_x = event.x / (self.map.map.tileset.block_width * self.map.map.tileset.tile_width) block_y = event.y / (self.map.map.tileset.block_height * self.map.map.tileset.tile_height) i = block_y * self.map.map.width + block_x if 0 <= i < len(self.map.map.blockdata): self.map.map.blockdata[i] = self.paint_tile self.map.draw_block(block_x, block_y) def init_map_connections(self): if not self.display_connections: return for direction in self.map.map.connections.keys(): if direction in self.connections.keys(): if hasattr(self.connections[direction], "canvas"): self.connections[direction].kill_canvas() if self.map.map.connections[direction] == {}: self.connections[direction] = {} continue self.connections[direction] = MapRenderer( self.config, parent=self, name=self.map.map.connections[direction]["map_name"] ) attrs = self.map.map.connections[direction] if direction in ["north", "south"]: if direction == "north": x1 = 0 if self.config.version == "red": y1 = eval(attrs["other_height"], self.config.constants) - 3 elif self.config.version == "crystal": y1 = eval(attrs["map"] + "_HEIGHT", self.config.constants) - 3 else: # south x1 = 0 y1 = 0 x2 = x1 + eval(attrs["strip_length"], self.config.constants) y2 = y1 + 3 else: if direction == "east": x1 = 0 y1 = 0 else: # west x1 = -3 y1 = 1 x2 = x1 + 3 y2 = y1 + eval(attrs["strip_length"], self.config.constants) self.connections[direction].init_canvas(self.map_frame) self.connections[direction].canvas.pack( side={"north": TOP, "south": BOTTOM, "west": LEFT, "east": RIGHT}[direction] ) self.connections[direction].map.crop(x1, y1, x2, y2) self.connections[direction].draw()
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
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')