def AppendMenu(mbar, text, menu_list): button = Menubutton(mbar, text = text) button.pack(side = LEFT) menu = UpdatedMenu(button, menu_list) button.menu = menu button['menu'] = menu.menu return menu
def __init__(self, parent=None): Frame.__init__(self, borderwidth=2) mButtonFile = Menubutton(self, text="Fichier") mButtonFile.pack() menuFile = Menu(mButtonFile) menuFile.add_command(label="Quitter", command=parent.quit) menuFile.add_command(label="Sauvegarder", command=parent.save) mButtonFile.configure(menu=menuFile)
def create_mnu_edit(): """ Создаёт меню "Правка". """ self.btn_edit = Menubutton(self.pnl_menu, text=LANG_RU['mnu_edit'], border=3, relief='groove') self.mnu_edit = Menu(self.btn_edit) self.btn_edit.config(menu=self.mnu_edit) self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Undo'], accelerator='Ctrl+Z') self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Redo']) self.mnu_edit.add_separator() self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Copy'], accelerator='Ctrl+C') self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Cut'], accelerator='Ctrl+X') self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Paste'], accelerator='Ctrl+V') self.mnu_edit.add_separator() self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Find'], accelerator='Ctrl+F') self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Replace'], accelerator='Ctrl+R') self.btn_edit.pack(side='left')
def __init__(self,parent=None, width = 800, height = 50): """ Initialise / crée le menu """ Frame.__init__(self,borderwidth=2) #Vars self.parent = parent self.fileOpened = None mbuttonFile = Menubutton(self,text='Fichier') #mbuttonFile.grid(row=0, column=0) mbuttonFile.pack(side=LEFT) menuFile=Menu(mbuttonFile) menuFile.add_command(label='Nouveau',command=self.new) menuFile.add_separator() menuFile.add_command(label='Sauvegarder',command=self.save) menuFile.add_command(label='Sauvegarder sous...',command=self.saveAs) menuFile.add_command(label='Charger...',command=self.load) menuFile.add_separator() #Search for an exit function on the parent, or take the default one from MenuBar class if not found try: menuFile.add_command(label='Quitter',command=self.parent.exit) except AttributeError: menuFile.add_command(label='Quitter',command=self.exit) mbuttonFile.configure(menu=menuFile) mbuttonHelp = Menubutton(self,text='Aide') #mbuttonHelp.grid(row=0, column=1) mbuttonHelp.pack(side=RIGHT) menuHelp = Menu(mbuttonHelp) menuHelp.add_command(label='Aide',command=self.infos) menuHelp.add_command(label='A propos',command=self.aPropos) mbuttonHelp.configure(menu=menuHelp) # define options for opening or saving a file self.file_opt = options = {} options['defaultextension'] = '.txt' options['filetypes'] = [('text files', '.txt'),('all files', '.*')] options['initialdir'] = 'C:\\' options['initialfile'] = 'save.txt' options['parent'] = parent options['title'] = 'Choissisez le fichier'
def create_mnu_file(): """ Создание меню "Файл". :return: """ # добавление менюхи файл self.mbt_file = Menubutton(self.frm_menu, text='File', relief='raised', border=3) self.mbt_file.pack(side='left')
def create_mnu_edit(): """ Создание меню "Правка". :return: """ # добавление менюхи правка self.mbt_edit = Menubutton(self.frm_menu, text='Edit', relief='raised', border=3) self.mbt_edit.pack(side='left')
def toc_menu(self, text): "Create table of contents as drop-down menu." toc = Menubutton(self, text='TOC') drop = Menu(toc, tearoff=False) for lbl, dex in text.parser.toc: drop.add_command(label=lbl, command=lambda dex=dex: text.yview(dex)) toc['menu'] = drop return toc
def AppendMenu(mbar, text, menu_list, underline): theme = app.uimanager.currentColorTheme # button = TMenubutton(mbar, text = text, underline=underline, style='RootMenuButton') button = Menubutton(mbar, text=text, underline=underline) button['background'] = theme.bg button['foreground'] = theme.foreground button['activebackground'] = theme.menuselectbackground button['activeforeground'] = theme.selectforeground button['relief'] = 'flat' button['highlightbackground'] = theme.menuselectbackground button['highlightcolor'] = theme.menuselectforeground button['highlightthickness'] = 0 button['bd'] = 0 button.pack(side=LEFT, padx=2, pady=0) menu = UpdatedMenu(button, menu_list) button.menu = menu button['menu'] = menu.menu return menu
def displayForTeacher(self, course): self.course = course rows = 24 columns = 3 for row in range(rows): for column in range(columns): empty = Label(self) empty.grid(row=row, column=column, padx=1, pady=1, sticky="nsew") label = Label(self, text=course) label.grid(row=0, column=0, columnspan=3, padx=1, pady=1, sticky="nsew") self.sections = courseSections[course].keys() self.noSection = IntVar() mb = Menubutton(self, text="Change Section") mb.menu = Menu(mb) mb["menu"] = mb.menu mb.menu.add_radiobutton(label=self.sections[0], value=0, variable=self.noSection, command=self.displaySection) mb.menu.add_radiobutton(label=self.sections[1], value=1, variable=self.noSection, command=self.displaySection) mb.grid(row=2, column=0, columnspan=3, padx=1, pady=1, sticky="nsew") self.displaySection()
def __init__(self, parent=None): Frame.__init__(self, borderwidth=2) mbuttonFile = Menubutton(self, text="Fichier") mbuttonFile.pack(side="left") menuFile = Menu(mbuttonFile) menuFile.add_command(label="Sauvegarder", command=parent.save) menuFile.add_command(label="Charger", command=parent.load) menuFile.add_command(label="Quitter", command=parent.quitter) mbuttonFile.configure(menu=menuFile) mbuttonFileBis = Menubutton(self, text="?") menuFileBis = Menu(mbuttonFileBis) menuFileBis.add_command(label="A propos", command=parent.about) mbuttonFileBis.configure(menu = menuFileBis) mbuttonFileBis.pack(side="left")
def create_mnu_help(): """ Создаёт меню "Справка". """ self.btn_help = Menubutton(self.pnl_menu, text='mnu_help', border=3, relief='groove') self.mnu_help = Menu(self.btn_help) self.btn_help.config(menu=self.mnu_help) self.mnu_help.add_command(label='Type files', accelerator='Ctrl+D') self.mnu_help.add_command(label='--1') self.mnu_custom.add_separator() self.btn_help.pack(side='left')
def __init__(self, parent=None): Frame.__init__(self, borderwidth=2) button_file = Menubutton(self, text="File") menu_file = Menu(button_file) menu_file.add_command(label="New", command=parent.new) menu_file.add_command(label="Save", command=parent.save) menu_file.add_command(label="Exit", command=parent.exit) button_file.configure(menu=menu_file) button_file.pack()
def create_mnu_custom(): """ Создаёт меню нстроек. """ self.btn_custom = Menubutton(self.pnl_menu, text='mnu_custom', border=3, relief='groove') self.mnu_custom = Menu(self.btn_custom) self.btn_custom.config(menu=self.mnu_custom) self.mnu_custom.add_command(label='Type files', accelerator='Ctrl+D') self.mnu_custom.add_command(label='--1') self.mnu_custom.add_separator() self.mnu_custom.add_command(label='--2', accelerator='---') self.mnu_custom.add_command(label='--3', accelerator='---') self.mnu_custom.add_command(label='--4', accelerator='---') self.mnu_custom.add_separator() self.btn_custom.pack(side='left')
def __init__(self, master=None): Frame.__init__(self, borderwidth=2) self.master = master button_file = Menubutton(self, text="Fichier", bg="white") button_file.pack(side="left") menu_file = Menu(button_file) menu_file.add_command(label='Effacer', underline=0, command=self.master.delete_circle) menu_file.add_command(label='Afficher', underline=0, command=self.master.create_circle) menu_file.add_command(label='Terminer', underline=0, command=self.master.quit) button_file.configure(menu=menu_file)
def create_mnu_custom(): """ Создание меню "Настройки". :return: """ # добавление менюхи настройка self.mbt_custom = Menubutton(self.frm_menu, text='Custom', relief='raised', border=3) self.mbt_custom.pack(side='left') self.mnu_custom = Menu(self.mbt_custom) self.mnu_custom.add_command( label=self.lang['win_main_mbt_edit_bp'], accelerator='F11', command=self.__root.control.show_win_edit_bp) self.mnu_custom.add_separator() self.mnu_custom.add_command( label=self.lang['win_main_mbt_edit_disk'], accelerator='F12', command=self.__root.control.show_win_idc) self.mbt_custom.config(menu=self.mnu_custom)
def create_mnu_help(): """ Создание меню "Помощь". :return: """ # добавление менюхи справка self.btm_help = Menubutton(self.frm_menu, text=self.lang[ 'win_main_mbt_help_name'], relief='raised', border=3) self.btm_help.pack(side='right') self.mnu_help = Menu(self.btm_help) self.mnu_help.add_command( label=self.lang['win_main_mbt_help_help'], accelerator='F1') self.mnu_help.add_separator() self.mnu_help.add_command( label=self.lang['win_main_mbt_help_about'], accelerator='Ctrl-F1', command=self.__root.control.about) self.btm_help.config(menu=self.mnu_help)
def create_mnu_file(): """ Создаёт меню файл. """ self.btn_file = Menubutton(self.pnl_menu, text=LANG_RU['mnu_file'], border=3, relief='groove') self.mnu_file = Menu(self.btn_file) self.btn_file.config(menu=self.mnu_file) self.mnu_file.add_command(label=LANG_RU['mnuFile_New'], accelerator='Ctrl+N') self.mnu_file.add_command(label=LANG_RU['mnuFile_Open'], accelerator='Ctrl+O') self.mnu_file.add_separator() self.mnu_file.add_command(label=LANG_RU['mnuFile_Save'], accelerator='Ctrl+S') self.mnu_file.add_command(label=LANG_RU['mnuFile_SaveAs']) self.mnu_file.add_separator() self.mnu_file.add_command(label=LANG_RU['mnuFile_Print'], accelerator='Ctrl+P') self.mnu_file.add_separator() self.mnu_file.add_command(label=LANG_RU['mnuFile_Exit'], accelerator='Ctrl+Q') self.btn_file.pack(side='left')
def createWidgets(self): ''' #==================================================# :TOPBAR: #==================================================# ''' self.fileButton = Menubutton(self, text='File', relief='flat') self.fileButton.grid(row=0, column=0) self.fileButton.menu = Menu(self.fileButton, tearoff=0) self.fileButton["menu"] = self.fileButton.menu self.fileButton.menu.add_command(label="New", command=self.NewFile) self.fileButton.menu.add_command(label="Exit", command=self.quit) self.eButton = Menubutton(self, text="Enrollment", relief='flat') self.eButton.grid(row=0, column=1) self.eButton.menu = Menu(self.eButton, tearoff=0) self.eButton["menu"] = self.eButton.menu self.eButton.menu.add_command(label="Add Enrollment", command=self.add_Enroll) self.statButton = Menubutton(self, text="Statistics", relief='flat') self.statButton.grid(row=0, column=2) self.statButton.menu = Menu(self.statButton, tearoff=0) self.statButton["menu"] = self.statButton.menu self.discMenu = Menu(tearoff=0) self.discMenu.add_command(label="Sort by name", command=self.StudentEnrollA) self.discMenu.add_command(label="Sort by grade", command=self.StudentEnrollB) self.statButton.menu.add_cascade( label="Students Enrolled at disicpline", menu=self.discMenu) self.statButton.menu.add_command(label="Failing Students", command=self.FailingStudents) self.statButton.menu.add_command(label="Best Students", command=self.BestStudents) self.statButton.menu.add_command(label="Discipline Averages", command=self.DisciplineH) self.searchButton = Menubutton(self, text="Search", relief='flat') self.searchButton.grid(row=0, column=3) self.searchButton.menu = Menu(self.searchButton, tearoff=0) self.searchButton["menu"] = self.searchButton.menu self.searchButton.menu.add_command(label="Search", command=self.SearchALL) self.editButton = Menubutton(self, text="Edit", relief='flat') self.editButton.grid(row=0, column=4) self.editButton.menu = Menu(self.editButton, tearoff=0) self.editButton["menu"] = self.editButton.menu self.editButton.menu.add_command(label="Undo", command=self.undo) self.editButton.menu.add_command(label="Redo", command=self.redo) self.root.bind('<Control-z>', self.undo) self.root.bind('<Control-y>', self.redo) ''' #===================================================# :Student: #===================================================# ''' self.sbar = Label(self, text='Student list', fg='white', bg='#3B9C9C', width=49) self.sbar.grid(row=1, column=0, columnspan=16) self.sList = Listbox(self, exportselection=0) for index in self._studentControl.getCurentRepo().getStudents(): self.sList.insert(END, index) self.sList.grid(row=2, column=0, columnspan=16) self.sList.config(width=57, height=40) self.sMenu = Menu(self, tearoff=0) self.sMenu.add_command(label="Add Student", command=self.add_Student) self.sMenu.add_command(label="Remove Student", command=self.remove_Student) self.sMenu.add_command(label='Update Student ID', command=self.update_StudentID) self.sMenu.add_command(label='Update Student name', command=self.update_StudentName) self.sMenu.add_command(label='Refresh', command=self.Srefresh) self.sList.bind("<Button-3>", self.sPopup) ''' #===================================================# :Discipline: #===================================================# ''' self.dbar = Label(self, text='Discipline list', fg='white', bg='#3B9C9C', width=49) self.dbar.grid(row=1, column=16, columnspan=16) self.dList = Listbox(self, exportselection=0) for index in self._disciplineControl.getCurentRepo().getDisciplines(): self.dList.insert(END, index) self.dList.grid(row=2, column=16, columnspan=16) self.dList.config(width=57, height=40) self.dMenu = Menu(self, tearoff=0) self.dMenu.add_command(label="Add Discipline", command=self.add_Discipline) self.dMenu.add_command(label="Remove Discipline", command=self.remove_Discipline) self.dMenu.add_command(label='Update Discipline ID', command=self.update_DisciplineID) self.dMenu.add_command(label='Update Discipline name', command=self.update_DisciplineName) self.dMenu.add_command(label='Refresh', command=self.Drefresh) self.dList.bind("<Button-3>", self.dPopup) ''' #===================================================# :Enroll: #===================================================# ''' self.ebar = Label(self, text='Enroll list', fg='white', bg='#3B9C9C', width=49) self.ebar.grid(row=1, column=32, columnspan=16) self.eList = Listbox(self, exportselection=0) for index in self._enrolControl.getCurentRepo().getEnroll(): self.eList.insert(END, '\n' + str(index)) self.eList.grid(row=2, column=32, columnspan=16) self.eList.config(width=57, height=40) self.eMenu = Menu(self, tearoff=0) self.eMenu.add_command(label="Remove Enrollment", command=self.remove_Enroll) self.eMenu.add_command(label="Grade Student", command=self.add_EnrollGrade) self.eMenu.add_command(label='Refresh', command=self.Erefresh) self.eList.bind("<Button-3>", self.ePopup) ''' #===================================================# :Grade: #===================================================# ''' self.gbar = Label(self, text='Grade list', fg='white', bg='#3B9C9C', width=49) self.gbar.grid(row=1, column=48, columnspan=16) self.gList = Listbox(self, exportselection=0) for index in self._gradeControl.getCurentRepo().getGrades(): self.gList.insert(END, '\n' + str(index)) self.gList.grid(row=2, column=48, columnspan=16) self.gList.config(width=57, height=40) self.gMenu = Menu(self, tearoff=0) self.gMenu.add_command(label="Grade Student", command=self.add_Grade) self.gMenu.add_command(label='Refresh', command=self.Grefresh) self.gList.bind("<Button-3>", self.gPopup)
class Application(Frame): def compress(self, sCTRL, dCTRL, eCTRL, gCTRL): allCTRL = { 'Student': sCTRL, 'Discipline': dCTRL, 'Enroll': eCTRL, 'Grade': gCTRL } pickle.dump(allCTRL, open("save.p", "wb")) def compare(self): if self.oCont >= self.Max: self.Max = self.oCont return def reader(self, Input, InputNumber): try: Input.getvar((str(InputNumber))) except TclError as tcl: s = str(tcl) return s.split("\"")[1] def clearText(self): self.textFrame.delete('1.0', END) def Srefresh(self): controller = self._studentControl.getCurentRepo().getStudents() curList = self.sList curList.delete(0, END) controller.sort() for index in controller: curList.insert(END, index) def Drefresh(self): controller = self._disciplineControl.getCurentRepo().getDisciplines() curList = self.dList curList.delete(0, END) controller.sort() for index in controller: curList.insert(END, index) def Erefresh(self): controller = self._enrolControl.getCurentRepo().getEnroll() curList = self.eList curList.delete(0, END) controller.sort() for index in controller: curList.insert(END, index) def Grefresh(self): controller = self._gradeControl.getCurentRepo().getGrades() curList = self.gList curList.delete(0, END) controller.sort() for index in controller: curList.insert(END, index) def refreshALL(self): self.Srefresh() self.Drefresh() self.Erefresh() self.Grefresh() def SreadID(self, string): return string[11:string.index('|') - 1] def DreadID(self, string): return string[15:string.index('|') - 1] def EreadID(self, string): return [ string[12:string.index('|') - 1], string[string.index('|') + 15:-2] ] def sPopup(self, event): self.sMenu.post(event.x_root, event.y_root) def dPopup(self, event): self.dMenu.post(event.x_root, event.y_root) def ePopup(self, event): self.eMenu.post(event.x_root, event.y_root) def gPopup(self, event): self.gMenu.post(event.x_root, event.y_root) def displayError(self, msg): tkMessageBox.showerror('Error', msg) def NewFile(self): self._studentControl.setRepo(deepcopy(student(1, ''))) self._disciplineControl.setRepo(deepcopy(discipline(1, ''))) self._enrolControl.setRepo(deepcopy(enroll(1, 1))) self._gradeControl.setRepo(deepcopy(grade(1, 1))) self.refreshALL() ''' #============================================# :STUDENT: #============================================# ''' def add_Student(self): try: top = tk.Toplevel() top.title('Input') Input = Window2('Enter student ID: ', 'Enter student Name: ', top) Input.mainloop() top.destroy() if not Input.getvar(str( Input.Input1)) == None and not Input.getvar( str(Input.Input2)) == None: studentID = Input.getvar(str(Input.Input1)) name = Input.getvar(str(Input.Input2)) print studentID print name Valid().ID(studentID) Valid().name(name) self._studentControl.getCurentRepo().addStudent( student(int(studentID), name)) self._studentControl.create(int(studentID), name) self.refreshALL() except ValueError: self.displayError('Invalid Input') except NameError: self.displayError('Invalid Name') except idError: self.displayError('Invalid ID') def remove_Student(self): try: index = self.sList.curselection() studentID = self.SreadID(self.sList.get(index)) studentID = int(studentID) name = '' eList = [] gList = [] for Student in self._studentControl.getCurentRepo().getStudents(): if int(Student.getId()) == studentID: name = Student.getName() for enroll in self._enrolControl.getCurentRepo().getEnroll(): if enroll.get_student_id() == studentID: eList.append(enroll) for grade in self._gradeControl.getCurentRepo().getGrades(): if int(grade.getStudentID()) == studentID: gList.append(grade) try: self._studentControl.removeStudent(studentID) except classException: pass try: self._enrolControl.removeEnrollStudent(studentID) except classException: pass try: self._gradeControl.removeGradeStudent(studentID) except classException: pass self._studentControl.delete(studentID, eList, gList, name) self.refreshALL() except ValueError: self.displayError('Invalid Input') except NameError: self.displayError('Invalid Name') except TclError: self.displayError('No item selected') def update_StudentID(self): try: top = tk.Toplevel() top.title('Input') Input = WindowRemove('New ID', top) Input.mainloop() top.destroy() index = self.sList.curselection() studentID = self.SreadID(self.sList.get(index)) studentID = int(studentID) if not Input.getvar(str(Input.Input1)) == None: newID = Input.getvar(str(Input.Input1)) newID = int(newID) self._studentControl.getCurentRepo().updateStudentID( studentID, newID) self._enrolControl.getCurentRepo().updateStudentID( studentID, newID) self._gradeControl.getCurentRepo().updateGradeStudentID( int(studentID), newID) self._studentControl.updateID(studentID, newID) self.refreshALL() except ValueError: self.displayError('Invalid Input') except NameError: self.displayError('Invalid Name') except TclError: self.displayError('No item selected') def update_StudentName(self): try: top = tk.Toplevel() top.title('Input') Input = WindowRemove('New name', top) Input.mainloop() top.destroy() index = self.sList.curselection() studentID = self.SreadID(self.sList.get(index)) studentID = int(studentID) oldName = self.sList.get(index)[self.sList.get(index).index('|') + 9:-2] if not Input.getvar(str(Input.Input1)) == None: newName = Input.getvar(str(Input.Input1)) Valid().name(newName) self._studentControl.getCurentRepo().updateStudentName( studentID, newName) self._studentControl.updateName(studentID, oldName, newName) self.refreshALL() except ValueError: self.displayError('Invalid Input') except NameError: self.displayError('Invalid Name') except TclError: self.displayError('No item selected') ''' #=============================================# :DISCIPLINE: #=============================================# ''' def add_Discipline(self): try: top = tk.Toplevel() top.title('Input') Input = Window2('Enter discipline ID: ', 'Enter discipline Name: ', top) Input.mainloop() top.destroy() if not Input.getvar(str(Input.Input1)) == None or not Input.getvar( str(Input.Input2)) == None: disciplineID = Input.getvar(str(Input.Input1)) name = Input.getvar(str(Input.Input2)) Valid().name(name) Valid().ID(disciplineID) self._disciplineControl.getCurentRepo().addDiscipline( discipline(int(disciplineID), name)) self._disciplineControl.create(int(disciplineID), name) self.refreshALL() except ValueError: self.displayError('Invalid Input') except NameError: self.displayError('Invalid Name') except TclError: self.displayError('No item selected') except idError: self.displayError('Invalid ID') def remove_Discipline(self): try: index = self.dList.curselection() disciplineID = self.DreadID(self.dList.get(index)) disciplineID = int(disciplineID) name = '' eList = [] gList = [] for Discipline in self._disciplineControl.getCurentRepo( ).getDisciplines(): if int(Discipline.getId()) == disciplineID: name = Discipline.getName() for enroll in self._enrolControl.getCurentRepo().getEnroll(): if enroll.get_discipline_id() == disciplineID: eList.append(enroll) for grade in self._gradeControl.getCurentRepo().getGrades(): if grade.getDisciplineID() == disciplineID: gList.append(grade) try: self._disciplineControl.removeDiscipline(disciplineID) except classException: pass try: self._gradeControl.removeGradeDiscipline(disciplineID) except classException: pass try: self._enrolControl.removeEnrollDiscipline(disciplineID) except classException: pass try: self._disciplineControl.delete(disciplineID, eList, gList, name) except classException: pass self.refreshALL() except ValueError: self.displayError('Invalid Input') except NameError: self.displayError('Invalid Name') except TclError: self.displayError('No item selected') def update_DisciplineID(self): try: top = tk.Toplevel() top.title('Input') Input = WindowRemove('New ID', top) Input.mainloop() top.destroy() index = self.dList.curselection() disciplineID = self.DreadID(self.dList.get(index)) disciplineID = int(disciplineID) if not Input.getvar(str(Input.Input1)) == None: newID = Input.getvar(str(Input.Input1)) newID = int(newID) self._disciplineControl.getCurentRepo().updateDisciplineID( disciplineID, newID) self._enrolControl.getCurentRepo().updateDisciplineID( disciplineID, newID) self._gradeControl.getCurentRepo().updateGradeDisciplineID( disciplineID, newID) self._disciplineControl.updateID(disciplineID, newID) self.refreshALL() except ValueError: self.displayError('Invalid Input') except NameError: self.displayError('Invalid Name') except TclError: self.displayError('No item selected') def update_DisciplineName(self): try: top = tk.Toplevel() top.title('Input') Input = WindowRemove('New name', top) Input.mainloop() top.destroy() index = self.dList.curselection() disciplineID = self.DreadID(self.dList.get(index)) disciplineID = int(disciplineID) oldName = self.dList.get(index)[self.dList.get(index).index('|') + 8:-2] if not Input.getvar(str(Input.Input1)) == None: newName = Input.getvar(str(Input.Input1)) Valid().name(newName) self._disciplineControl.getCurentRepo().updateDisciplineName( disciplineID, newName) self._disciplineControl.updateName(disciplineID, oldName, newName) self.refreshALL() except ValueError: self.displayError('Invalid Input') except NameError: self.displayError('Invalid Name') except TclError: self.displayError('No item selected') ''' #===================================================# :ENROLL: #===================================================# ''' def remove_Enroll(self): try: index = self.eList.curselection() IDs = self.EreadID(self.eList.get(index)) studentID = int(IDs[0]) disicplineID = int(IDs[1]) self.eList.delete(ANCHOR) self._gradeControl.removeGrade(enroll(studentID, disicplineID)) self._enrolControl.removeEnroll(enroll(studentID, disicplineID)) self.Erefresh() self.Grefresh() self.refreshALL() except ValueError: self.displayError('Invalid Input') except NameError: self.displayError('Invalid Name') except TclError: self.displayError('No item selected') def add_Enroll(self): try: index = self.sList.curselection() studentID = self.SreadID(self.sList.get(index)) studentID = int(studentID) index = self.dList.curselection() disciplineID = self.DreadID(self.dList.get(index)) disciplineID = int(disciplineID) #try: self._enrolControl.addEnroll(enroll(studentID, disciplineID)) #except ValueError: #self.displayError('Enrollment allready exists') self._enrolControl.create(enroll(studentID, disciplineID)) self.refreshALL() except ValueError: self.displayError('Invalid Input') except NameError: self.displayError('Invalid Name') except TclError: self.displayError('No item selected') def add_EnrollGrade(self): try: top = tk.Toplevel() top.title('Input') Input = WindowRemove('Grade: ', top) Input.mainloop() top.destroy() index = self.eList.curselection() IDs = self.EreadID(self.eList.get(index)) studentID = int(IDs[0]) disciplineID = int(IDs[1]) if not Input.getvar(str(Input.Input1)) == None: gradeValue = Input.getvar(str(Input.Input1)) gradeValue = float(gradeValue) Valid().grade(gradeValue) self._gradeControl.addGrade(grade(disciplineID, studentID), gradeValue) self.Grefresh() self.refreshALL() except ValueError: self.displayError('Invalid Input') except NameError: self.displayError('Invalid Name') except TclError: self.displayError('No item selected') ''' #=======================================================# :GRADE: #=======================================================# ''' def add_Grade(self): try: top = tk.Toplevel() top.title('Input') Input = WindowRemove('Grade: ', top) Input.mainloop() top.destroy() index = self.gList.curselection() IDs = self.EreadID(self.eList.get(index)) studentID = int(IDs[0]) disciplineID = int(IDs[1]) if not Input.getvar(str(Input.Input1)) == None: gradeValue = Input.getvar(str(Input.Input1)) gradeValue = float(gradeValue) Valid().grade(gradeValue) self._gradeControl.addGrade(grade(disciplineID, studentID), gradeValue) self._gradeControl.create(grade(disciplineID, studentID), gradeValue) self.refreshALL() except ValueError: self.displayError('Invalid Input') except NameError: self.displayError('Invalid Name') except TclError: self.displayError('No item selected') ''' #================================================# :SEARCH: #================================================# ''' def SearchALL(self): top = tk.Toplevel() top.title('Input') Input = WindowRemove('Search: ', top) Input.mainloop() top.destroy() searchString = Input.getvar(str(Input.Input1)) top = tk.Toplevel() top.title('Serch Results') top.text = Listbox(top) top.text.grid(row=0, column=0) top.text.config(width=50) top.text.insert(END, 'Disciplines:') for discipline in self._disciplineControl.getCurentRepo( ).getDisciplines(): if searchString.lower() in str(discipline.getId()).lower() or str( discipline.getId()).lower() in searchString.lower( ) or searchString.lower() in discipline.getName().lower( ) or discipline.getName().lower() in searchString.lower(): top.text.insert(END, discipline) top.text.insert(END, 'Students:') for student in self._studentControl.getCurentRepo().getStudents(): if searchString.lower() in str(student.getId()).lower() or str( student.getId()).lower() in searchString.lower( ) or searchString.lower() in student.getName().lower( ) or student.getName().lower() in searchString.lower(): top.text.insert(END, student) ''' #===============================================# :STATISCTICS: #===============================================# ''' def StudentEnrollA(self): try: top = tk.Toplevel() top.title('Enrollment List') top.text = Listbox(top) top.text.grid(row=0, column=0) index = self.dList.curselection() disciplineID = self.DreadID(self.dList.get(index)) disciplineID = int(disciplineID) SList = self._enrolControl.studentEnrollA(disciplineID) for index in SList: top.text.insert(END, index) del SList[:] except TclError: top.destroy() self.displayError('No disicpline Selected') def StudentEnrollB(self): try: top = tk.Toplevel() top.title('Enrollment List') top.text = Listbox(top) top.text.grid(row=0, column=0) index = self.dList.curselection() disciplineID = self.DreadID(self.dList.get(index)) disciplineID = int(disciplineID) SList = [[' ', -1]] for grade in self._gradeControl.getCurentRepo().getGrades(): if grade.getDisciplineID() == disciplineID: for student in self._studentControl.getCurentRepo( ).getStudents(): if student.getId() == grade.getStudentID(): if grade.getGrade() != []: gradeAvg = self.listAvg( grade.getGrade(), grade.getGradeSize()) SList.append([student.getName(), gradeAvg]) SList.sort(key=itemgetter(1), reverse=True) del SList[-1] for index in SList: top.text.insert(END, index) del SList[:] except TclError: top.destroy() self.displayError('No disicpline Selected') def FailingStudents(self): top = tk.Toplevel() top.title('Enrollment List') top.text = Listbox(top) top.text.grid(row=0, column=0) top.text.config(width=50) sList = [['', '']] for grade in self._gradeControl.getCurentRepo().getGrades(): for student in self._studentControl.getCurentRepo().getStudents(): for discipline in self._disciplineControl.getCurentRepo( ).getDisciplines(): if grade.getStudentID() == student.getId(): if grade.getDisciplineID() == discipline.getId(): if grade.getGrade() != []: gradeAvg = self.listAvg( grade.getGrade(), grade.getGradeSize()) if gradeAvg < 5: sList.append([ student.getName(), discipline.getName() ]) for index in sList: top.text.insert(END, '\n' + index[0] + ' - ' + index[1]) del sList[:] def BestStudents(self): top = tk.Toplevel() top.title('Enrollment List') top.text = Listbox(top) top.text.grid(row=0, column=0) top.text.config(width=50) sList = [['', '']] gList = [] sName = '' for student in self._studentControl.getCurentRepo().getStudents(): for grade in self._gradeControl.getCurentRepo().getGrades(): if student.getId() == grade.getStudentID(): if (grade.getGrade() != []): gAvg = self.listAvg(grade.getGrade(), grade.getGradeSize()) gList.append(gAvg) sName = student.getName() if gList != []: sAvg = self.listAvg(gList, len(gList)) sList.append([sName, round(sAvg, 2)]) sList.sort(key=itemgetter(1), reverse=True) for index in range(1, len(sList)): top.text.insert( END, str(sList[index][0] + ' - ' + str(sList[index][1]))) del sList[:] def DisciplineH(self): top = tk.Toplevel() top.title('Enrollment List') top.text = Listbox(top) top.text.grid(row=0, column=0) top.text.config(width=50) sList = [['', '']] gList = [] dName = '' for discipline in self._disciplineControl.getCurentRepo( ).getDisciplines(): for grade in self._gradeControl.getCurentRepo().getGrades(): if discipline.getId() == grade.getDisciplineID(): if (grade.getGrade() != []): gAvg = self.listAvg(grade.getGrade(), grade.getGradeSize()) gList.append(gAvg) dName = discipline.getName() if gList != []: sAvg = self.listAvg(gList, len(gList)) sList.append([dName, round(sAvg, 2)]) sList.sort(key=itemgetter(1), reverse=True) for index in range(1, len(sList)): top.text.insert( END, '\n' + str(sList[index][0]) + ' - ' + str(sList[index][1])) del sList[:] ''' #======================================# :EDIT: #======================================# ''' def undo(self, event): self._undoControl.undo() self.refreshALL() def redo(self, event): self._undoControl.redo() self.refreshALL() ''' #===========================================================================================# :Widgets: #===========================================================================================# ''' def createWidgets(self): ''' #==================================================# :TOPBAR: #==================================================# ''' self.fileButton = Menubutton(self, text='File', relief='flat') self.fileButton.grid(row=0, column=0) self.fileButton.menu = Menu(self.fileButton, tearoff=0) self.fileButton["menu"] = self.fileButton.menu self.fileButton.menu.add_command(label="New", command=self.NewFile) self.fileButton.menu.add_command(label="Exit", command=self.quit) self.eButton = Menubutton(self, text="Enrollment", relief='flat') self.eButton.grid(row=0, column=1) self.eButton.menu = Menu(self.eButton, tearoff=0) self.eButton["menu"] = self.eButton.menu self.eButton.menu.add_command(label="Add Enrollment", command=self.add_Enroll) self.statButton = Menubutton(self, text="Statistics", relief='flat') self.statButton.grid(row=0, column=2) self.statButton.menu = Menu(self.statButton, tearoff=0) self.statButton["menu"] = self.statButton.menu self.discMenu = Menu(tearoff=0) self.discMenu.add_command(label="Sort by name", command=self.StudentEnrollA) self.discMenu.add_command(label="Sort by grade", command=self.StudentEnrollB) self.statButton.menu.add_cascade( label="Students Enrolled at disicpline", menu=self.discMenu) self.statButton.menu.add_command(label="Failing Students", command=self.FailingStudents) self.statButton.menu.add_command(label="Best Students", command=self.BestStudents) self.statButton.menu.add_command(label="Discipline Averages", command=self.DisciplineH) self.searchButton = Menubutton(self, text="Search", relief='flat') self.searchButton.grid(row=0, column=3) self.searchButton.menu = Menu(self.searchButton, tearoff=0) self.searchButton["menu"] = self.searchButton.menu self.searchButton.menu.add_command(label="Search", command=self.SearchALL) self.editButton = Menubutton(self, text="Edit", relief='flat') self.editButton.grid(row=0, column=4) self.editButton.menu = Menu(self.editButton, tearoff=0) self.editButton["menu"] = self.editButton.menu self.editButton.menu.add_command(label="Undo", command=self.undo) self.editButton.menu.add_command(label="Redo", command=self.redo) self.root.bind('<Control-z>', self.undo) self.root.bind('<Control-y>', self.redo) ''' #===================================================# :Student: #===================================================# ''' self.sbar = Label(self, text='Student list', fg='white', bg='#3B9C9C', width=49) self.sbar.grid(row=1, column=0, columnspan=16) self.sList = Listbox(self, exportselection=0) for index in self._studentControl.getCurentRepo().getStudents(): self.sList.insert(END, index) self.sList.grid(row=2, column=0, columnspan=16) self.sList.config(width=57, height=40) self.sMenu = Menu(self, tearoff=0) self.sMenu.add_command(label="Add Student", command=self.add_Student) self.sMenu.add_command(label="Remove Student", command=self.remove_Student) self.sMenu.add_command(label='Update Student ID', command=self.update_StudentID) self.sMenu.add_command(label='Update Student name', command=self.update_StudentName) self.sMenu.add_command(label='Refresh', command=self.Srefresh) self.sList.bind("<Button-3>", self.sPopup) ''' #===================================================# :Discipline: #===================================================# ''' self.dbar = Label(self, text='Discipline list', fg='white', bg='#3B9C9C', width=49) self.dbar.grid(row=1, column=16, columnspan=16) self.dList = Listbox(self, exportselection=0) for index in self._disciplineControl.getCurentRepo().getDisciplines(): self.dList.insert(END, index) self.dList.grid(row=2, column=16, columnspan=16) self.dList.config(width=57, height=40) self.dMenu = Menu(self, tearoff=0) self.dMenu.add_command(label="Add Discipline", command=self.add_Discipline) self.dMenu.add_command(label="Remove Discipline", command=self.remove_Discipline) self.dMenu.add_command(label='Update Discipline ID', command=self.update_DisciplineID) self.dMenu.add_command(label='Update Discipline name', command=self.update_DisciplineName) self.dMenu.add_command(label='Refresh', command=self.Drefresh) self.dList.bind("<Button-3>", self.dPopup) ''' #===================================================# :Enroll: #===================================================# ''' self.ebar = Label(self, text='Enroll list', fg='white', bg='#3B9C9C', width=49) self.ebar.grid(row=1, column=32, columnspan=16) self.eList = Listbox(self, exportselection=0) for index in self._enrolControl.getCurentRepo().getEnroll(): self.eList.insert(END, '\n' + str(index)) self.eList.grid(row=2, column=32, columnspan=16) self.eList.config(width=57, height=40) self.eMenu = Menu(self, tearoff=0) self.eMenu.add_command(label="Remove Enrollment", command=self.remove_Enroll) self.eMenu.add_command(label="Grade Student", command=self.add_EnrollGrade) self.eMenu.add_command(label='Refresh', command=self.Erefresh) self.eList.bind("<Button-3>", self.ePopup) ''' #===================================================# :Grade: #===================================================# ''' self.gbar = Label(self, text='Grade list', fg='white', bg='#3B9C9C', width=49) self.gbar.grid(row=1, column=48, columnspan=16) self.gList = Listbox(self, exportselection=0) for index in self._gradeControl.getCurentRepo().getGrades(): self.gList.insert(END, '\n' + str(index)) self.gList.grid(row=2, column=48, columnspan=16) self.gList.config(width=57, height=40) self.gMenu = Menu(self, tearoff=0) self.gMenu.add_command(label="Grade Student", command=self.add_Grade) self.gMenu.add_command(label='Refresh', command=self.Grefresh) self.gList.bind("<Button-3>", self.gPopup) def __init__(self, studentControl, disciplineControl, gradeControl, enrolControl, U1, master=None): Frame.__init__(self, master) self.pack() self.grid() self.Max = 0 self.oCont = 0 self.root = master self._studentControl = studentControl self._disciplineControl = disciplineControl self._gradeControl = gradeControl self._enrolControl = enrolControl self._undoControl = U1 self.createWidgets() @staticmethod def listAvg(myList, size): s = 0.0 for index in range(size): s += myList[index] s /= size return s
def data(self): global textPath textPath = StringVar() global text0a text0a = StringVar() global text0b text0b = StringVar() global text2a text2a = StringVar() global text3 text3 = StringVar() global alphaVar alphaVar = IntVar() global betaVar betaVar = IntVar() global allVar allVar = IntVar() global text6a text6a = "0" global filterVar filterVar = IntVar() global text6b text6b = StringVar() global t1x t1x = "" global t2x t2x = "" global t3x t3x = "" global t4x t4x = "" global text8_0 text8_0 = StringVar() global text8_1 text8_1 = StringVar() Label(self.frame,text="Path ? ").grid(row=0, column=0) Entry(self.frame,textvariable=textPath).grid(row=1, column=0) Button(self.frame, text="Valider et afficher", command = affiche_recap).grid(row=1, column=1) Label(self.frame, text="Green function database information file\n (for a certain depth only for the instance) ?").grid(row=3) Entry(self.frame, textvariable=text0a).grid(row=4) Label(self.frame, text="Output directory (parentdir) ?").grid(row=5) Entry(self.frame, textvariable=text0b).grid(row=6) Label(self.frame, text="Phase name ?").grid(row=9) Entry(self.frame, textvariable=text3).grid(row=10) def afficheAlpha(): seismicPara["text"]="alpha" betaVar.set(0) allVar.set(0) def afficheBeta(): seismicPara["text"]="beta" alphaVar.set(0) allVar.set(0) def afficheAll(): seismicPara["text"]="all" alphaVar.set(0) betaVar.set(0) seismicPara = Menubutton(self.frame, text="Seismic Parameter", relief=RAISED) seismicPara.grid(row=0) seismicPara.menu = Menu(seismicPara, tearoff = 0) seismicPara["menu"] = seismicPara.menu seismicPara.menu.add_checkbutton(label="alpha", variable = alphaVar, command = afficheAlpha) seismicPara.menu.add_checkbutton(label="beta", variable = betaVar, command = afficheBeta) seismicPara.menu.add_checkbutton(label="all", variable = allVar, command = afficheAll) seismicPara.grid(row=11) Label(self.frame, text="Filter name ?").grid(row=12) Entry(self.frame, textvariable=text6b).grid(row=13) Label(self.frame, text="time window t1 ?").grid(row=14) Labelt1 = Label(self.frame, text="-->").grid(row=15) Button(self.frame, text="time 1", command=self.time1).grid(row=15, column=1) Label(self.frame, text="time window t2 ?").grid(row=16) Labelt1 = Label(self.frame, text="-->").grid(row=17) Button(self.frame, text="time 2", command=self.time2).grid(row=17, column=1) ''' Label(self.frame, text="time window t3 ?").grid(row=18) Labelt1 = Label(self.frame, text="-->").grid(row=19) Button(self.frame, text="time 3", command=self.time3).grid(row=19, column=1) Label(self.frame, text="time window t4 ?").grid(row=20) Labelt1 = Label(self.frame, text="-->").grid(row=21) Button(self.frame, text="time 4", command=self.time4).grid(row=21, column=1) ''' def affiche0(): convertPara["text"]="No conversion" text8_1.set(0) def affiche1(): convertPara["text"]="Conversion" text8_0.set(0) convertPara = Menubutton(self.frame, text="Geodetic latitude to geocentric latitude conversion", relief=RAISED) convertPara.grid(row=0) convertPara.menu = Menu(convertPara, tearoff = 0) convertPara["menu"] = convertPara.menu convertPara.menu.add_checkbutton(label="No conversion", variable = text8_0, command = affiche0) convertPara.menu.add_checkbutton(label="Conversion", variable = text8_1, command = affiche1) convertPara.grid(row=22) b = Checkbutton(self.frame, text = "apply filter", variable = filterVar) b.grid(row=23, column = 0) Button(self.frame, text="continue", command=self.quitter).grid(row=23, column=1)
def destroy(self): WidgetWithCommand.clean_up(self) Menubutton.destroy(self) self.__menu = None
def __init__(self, parent=None): Frame.__init__(self, borderwidth=2) mbuttonFile = Menubutton(self, text="Fichier") mbuttonFile.pack(side="left") menuFile = Menu(mbuttonFile) menuFile.add_command(label="Sauvegarder", command=parent.save) menuFile.add_command(label="Charger", command=parent.load) menuFile.add_command(label="Quitter", command=parent.quitter) mbuttonFile.configure(menu=menuFile) mbuttonFileBis = Menubutton(self, text="?") menuFileBis = Menu(mbuttonFileBis) menuFileBis.add_command(label="A propos", command=parent.about) mbuttonFileBis.configure(menu=menuFileBis) mbuttonFileBis.pack(side="left")
def __init__(self, parent): Frame.__init__(self, borderwidth=2) self.parent = parent # File Button Menu button_file = Menubutton(self, text="Fichier") menu_file = Menu(button_file) menu_file.add_command(label="Nouveau", command=self.parent.new) menu_file.add_command(label="Ouvrir", command=self.parent.open) menu_file.add_command(label="Sauvegarder", command=self.parent.save) menu_file.add_command(label="Quitter", command=self.parent.exit) button_file.configure(menu=menu_file) button_file.pack(side=LEFT, fill="x") # Help Button Menu button_file = Menubutton(self, text="Aide") menu_help = Menu(button_file) menu_help.add_command(label="A propos de nous", command=self.parent.help) button_file.configure(menu=menu_help) button_file.pack(side=LEFT)
def __init__(self, parent=None): Frame.__init__(self, borderwidth=2) self.parent = parent mbuttonFile = Menubutton(self, text="Fichier") mbuttonPlus = Menubutton(self, text="Plus") mbuttonQuit = Menubutton(self, text="Quitter") mbuttonFile.pack(side="left") mbuttonPlus.pack(side="left") mbuttonQuit.pack(side="left") menuFile = Menu(mbuttonFile) menuFile.add_command(label="Enregistrer Default", command=self.defaultSave) menuFile.add_command(label="Enregistrer", command=self.save) menuFile.add_command(label="Charger Default", command=self.defaultLoad) menuFile.add_command(label="Charger Choix", command=self.load) menuPlus = Menu(mbuttonPlus) menuPlus.add_command(label="Infos", command=self.showInfos) menuQuit = Menu(mbuttonQuit) menuQuit.add_command(label="Quitter", command=parent.quit) menuQuit.add_command(label="Quitter avec confirmation", command=self.confirmQuit) mbuttonFile.configure(menu=menuFile) mbuttonPlus.configure(menu=menuPlus) mbuttonQuit.configure(menu=menuQuit)
class lightingPanel(AppShell): ################################################################# # lightingPanel(AppShell) # This will create a window to let user # create any kinds of lighting into the scene ################################################################# # Override class variables appname = 'Lighting Panel' frameWidth = 400 frameHeight = 400 currentLight = None def __init__(self, lightList, parent = None, **kw): self.lightList = lightList self.lightColor = [0.3*255,0.3*255,0.3*255] self.type = '' INITOPT = Pmw.INITOPT optiondefs = ( ('title', self.appname, None), ) self.defineoptions(kw, optiondefs) # Initialize the superclass AppShell.__init__(self) # Execute option callbacks self.initialiseoptions(lightingPanel) self.parent.resizable(False,False) ## Disable the ability to resize for this Window. def createInterface(self): # Handle to the toplevels interior interior = self.interior() menuBar = self.menuBar self.menuBar.destroy() # Create a frame to hold all stuff mainFrame = Frame(interior) self.listZone = Pmw.Group(mainFrame,tag_pyclass = None) self.listZone.pack(expand=0, fill=Tkinter.X,padx=3,pady=3) listFrame = self.listZone.interior() self.lightEntry = self.createcomponent( 'Lights List', (), None, Pmw.ComboBox, (listFrame,),label_text='Light :', labelpos = Tkinter.W, entry_width = 25, selectioncommand = self.selectLight, scrolledlist_items = self.lightList) self.lightEntry.pack(side=Tkinter.LEFT) self.renameButton = self.createcomponent( 'Rename Light', (), None, Button, (listFrame,), text = ' Rename ', command = self.renameLight) self.renameButton.pack(side=Tkinter.LEFT) self.addLighZone = Pmw.Group(listFrame,tag_pyclass = None) self.addLighZone.pack(side=Tkinter.LEFT) insideFrame = self.addLighZone.interior() self.lightsButton = Menubutton(insideFrame, text = 'Add light',borderwidth = 3, activebackground = '#909090') lightsMenu = Menu(self.lightsButton) lightsMenu.add_command(label = 'Add Ambient Light', command = self.addAmbient) lightsMenu.add_command(label = 'Add Directional Light', command = self.addDirectional) lightsMenu.add_command(label = 'Add Point Light', command = self.addPoint) lightsMenu.add_command(label = 'Add Spotlight', command = self.addSpot) self.lightsButton.pack(expand=0) self.lightsButton['menu'] = lightsMenu self.deleteButton = self.createcomponent( 'delete Light', (), None, Button, (listFrame,), text = ' Delete ', command = self.deleteLight) self.deleteButton.pack(side=Tkinter.LEFT) self.lightColor = seColorEntry( mainFrame, text = 'Light Color', value=self.lightColor) self.lightColor['command'] = self.setLightingColorVec self.lightColor['resetValue'] = [0.3*255,0.3*255,0.3*255,0] self.lightColor.pack(fill=Tkinter.X,expand=0) self.bind(self.lightColor, 'Set light color') # Notebook pages for light specific controls self.lightNotebook = Pmw.NoteBook(mainFrame, tabpos = None, borderwidth = 0) ambientPage = self.lightNotebook.add('Ambient') directionalPage = self.lightNotebook.add('Directional') pointPage = self.lightNotebook.add('Point') spotPage = self.lightNotebook.add('Spot') # Put this here so it isn't called right away self.lightNotebook['raisecommand'] = self.updateLightInfo # Directional light controls self.dSpecularColor = seColorEntry( directionalPage, text = 'Specular Color') self.dSpecularColor['command'] = self.setSpecularColor self.dSpecularColor.pack(fill = Tkinter.X, expand = 0) self.bind(self.dSpecularColor, 'Set directional light specular color') self.dPosition = Vector3Entry( directionalPage, text = 'Position') self.dPosition['command'] = self.setPosition self.dPosition['resetValue'] = [0,0,0,0] self.dPosition.pack(fill = Tkinter.X, expand = 0) self.bind(self.dPosition, 'Set directional light position') self.dOrientation = Vector3Entry( directionalPage, text = 'Orientation') self.dOrientation['command'] = self.setOrientation self.dOrientation['resetValue'] = [0,0,0,0] self.dOrientation.pack(fill = Tkinter.X, expand = 0) self.bind(self.dOrientation, 'Set directional light orientation') # Point light controls self.pSpecularColor = seColorEntry( pointPage, text = 'Specular Color') self.pSpecularColor['command'] = self.setSpecularColor self.pSpecularColor.pack(fill = Tkinter.X, expand = 0) self.bind(self.pSpecularColor, 'Set point light specular color') self.pPosition = Vector3Entry( pointPage, text = 'Position') self.pPosition['command'] = self.setPosition self.pPosition['resetValue'] = [0,0,0,0] self.pPosition.pack(fill = Tkinter.X, expand = 0) self.bind(self.pPosition, 'Set point light position') self.pConstantAttenuation = Slider( pointPage, text = 'Constant Attenuation', max = 1.0, resolution = 0.01, value = 1.0) self.pConstantAttenuation['command'] = self.setConstantAttenuation self.pConstantAttenuation.pack(fill = Tkinter.X, expand = 0) self.bind(self.pConstantAttenuation, 'Set point light constant attenuation') self.pLinearAttenuation = Slider( pointPage, text = 'Linear Attenuation', max = 1.0, resolution = 0.01, value = 0.0) self.pLinearAttenuation['command'] = self.setLinearAttenuation self.pLinearAttenuation.pack(fill = Tkinter.X, expand = 0) self.bind(self.pLinearAttenuation, 'Set point light linear attenuation') self.pQuadraticAttenuation = Slider( pointPage, text = 'Quadratic Attenuation', max = 1.0, resolution = 0.01, value = 0.0) self.pQuadraticAttenuation['command'] = self.setQuadraticAttenuation self.pQuadraticAttenuation.pack(fill = Tkinter.X, expand = 0) self.bind(self.pQuadraticAttenuation, 'Set point light quadratic attenuation') # Spot light controls self.sSpecularColor = seColorEntry( spotPage, text = 'Specular Color') self.sSpecularColor['command'] = self.setSpecularColor self.sSpecularColor.pack(fill = Tkinter.X, expand = 0) self.bind(self.sSpecularColor, 'Set spot light specular color') self.sConstantAttenuation = Slider( spotPage, text = 'Constant Attenuation', max = 1.0, resolution = 0.01, value = 1.0) self.sConstantAttenuation['command'] = self.setConstantAttenuation self.sConstantAttenuation.pack(fill = Tkinter.X, expand = 0) self.bind(self.sConstantAttenuation, 'Set spot light constant attenuation') self.sLinearAttenuation = Slider( spotPage, text = 'Linear Attenuation', max = 1.0, resolution = 0.01, value = 0.0) self.sLinearAttenuation['command'] = self.setLinearAttenuation self.sLinearAttenuation.pack(fill = Tkinter.X, expand = 0) self.bind(self.sLinearAttenuation, 'Set spot light linear attenuation') self.sQuadraticAttenuation = Slider( spotPage, text = 'Quadratic Attenuation', max = 1.0, resolution = 0.01, value = 0.0) self.sQuadraticAttenuation['command'] = self.setQuadraticAttenuation self.sQuadraticAttenuation.pack(fill = Tkinter.X, expand = 0) self.bind(self.sQuadraticAttenuation, 'Set spot light quadratic attenuation') self.sExponent = Slider( spotPage, text = 'Exponent', max = 1.0, resolution = 0.01, value = 0.0) self.sExponent['command'] = self.setExponent self.sExponent.pack(fill = Tkinter.X, expand = 0) self.bind(self.sExponent, 'Set spot light exponent') # MRM: Add frustum controls self.lightNotebook.setnaturalsize() self.lightNotebook.pack(expand = 1, fill = Tkinter.BOTH) mainFrame.pack(expand=1, fill = Tkinter.BOTH) def onDestroy(self, event): messenger.send('LP_close') ''' If you have open any thing, please rewrite here! ''' pass def renameLight(self): ################################################################# # renameLight(self) # Call Back function # This function will be called when user push # the "Rename" button on the panel. # # Then, this function will collect data and send out them with a message # "LP_rename" # Which will be caught by sceneEditor and pass to dataHolder to # complete the renaming. # ################################################################# oName = self.currentLight nName = self.lightEntry.get() messenger.send('LP_rename',[oName,nName]) return def deleteLight(self): ################################################################# # deleteLight(self) # Call Back Function. # This function will be called when user click on # the "Delete" button on the panel. # # Then, this function will send out a message with current seleted light # "LP_removeLight" # Which will be caught by sceneEditor and pass to dataHolder to # complete the delete process. # ################################################################# messenger.send('LP_removeLight',[self.currentLight]) return def updateList(self, list, node=None): ################################################################# # updataList(self, list, node = None) # This function will take a list object which contains names of lights in the scene. # Also, if user has put node as a parameter, # this function will automatically select that node as the current working target. ################################################################# self.lightList = list self.lightEntry.setlist(list) if node!=None: self.lightEntry.selectitem(index=node.getName(), setentry=True ) self.updateDisplay(node) elif len(list)>0: self.lightEntry.selectitem(index=0, setentry=True ) self.selectLight(list[0]) else: self.lightEntry.clear() return def selectLight(self, lightName): ################################################################# # selectLight(self, lightName) # This function will be called each time when # user select a light from the list on the panel. # Then, this function will send out the message, # 'LP_selectLight' to sceneEditorand get the current light information from dataHolder. ################################################################# if lightName in self.lightList: messenger.send('LP_selectLight',[lightName]) return def updateDisplay(self, lightNode): ################################################################# # updateDisplay(self, lightNode) # This function will update the information showing on the panel. # For example, give a lightNode which is a Point Light. # This function will switch the page to specify the type. # Also, new node is the same type with the previous one, # then this is function won't do the page switching, # but will call other function to refresh the data to target node. ################################################################# self.currentLight = lightNode if self.currentLight != None: color = lightNode.getLightColor() self.lightColor.set([255*color.getX(),255*color.getY(),255*color.getZ()]) oldType = self.type self.type = lightNode.getType() else: self.lightColor.set([255*0.3,255*0.3,255*0.3]) oldType = self.type self.type = 'ambient' if self.type=='ambient': self.lightNotebook.selectpage('Ambient') elif self.type =='directional': self.lightNotebook.selectpage('Directional') elif self.type =='point': self.lightNotebook.selectpage('Point') elif self.type =='spot': self.lightNotebook.selectpage('Spot') if oldType == self.type: # The same type with previous one, call updateLightInfo to refresh the values. self.updateLightInfo() return def updateLightInfo(self, page=None): ################################################################# # updateLightInfo(self, page=None) # This function will refresh the data we user have done any selection. ################################################################# if self.currentLight != None: light = self.currentLight.getLight() if self.type != 'ambient': specColor = light.getSpecularColor() if self.type =='directional': point = self.currentLight.getPosition() dir = self.currentLight.getOrientation() self.dSpecularColor.set([specColor.getX()*255,specColor.getY()*255,specColor.getZ()*255]) self.dPosition.set([point.getX(),point.getY(),point.getZ()]) self.dOrientation.set([dir.getX(),dir.getY(),dir.getZ()]) elif self.type =='point': point = self.currentLight.getPosition() attenuation = light.getAttenuation() self.pSpecularColor.set([specColor.getX()*255,specColor.getY()*255,specColor.getZ()*255]) self.pPosition.set([point.getX(),point.getY(),point.getZ()]) self.pConstantAttenuation.set(attenuation.getX()) self.pLinearAttenuation.set(attenuation.getY()) self.pQuadraticAttenuation.set(attenuation.getZ()) elif self.type =='spot': attenuation = light.getAttenuation() expo = light.getExponent() self.sSpecularColor.set([specColor.getX()*255,specColor.getY()*255,specColor.getZ()*255]) self.sConstantAttenuation.set(attenuation.getX()) self.sLinearAttenuation.set(attenuation.getY()) self.sQuadraticAttenuation.set(attenuation.getZ()) self.sExponent.set(expo) return def addAmbient(self): ################################################################# # addAmbient(self) # This function will send out a message to # ask dataHolder to create a default ambient light ################################################################# messenger.send('LP_addLight',['ambient']) return def addDirectional(self): ################################################################# # addDirectional(self) # This function will send out a message to # sk dataHolder to create a default Directional light ################################################################# messenger.send('LP_addLight',['directional']) return def addPoint(self): ################################################################# # addPoint(self) # This function will send out a message to # ask dataHolder to create a default Point light ################################################################# messenger.send('LP_addLight',['point']) return def addSpot(self): ################################################################# # addSpot(self) # This function will send out a message to # ask dataHolder to create a default Spot light ################################################################# messenger.send('LP_addLight',['spot']) return def setLightingColorVec(self,color): ################################################################# # setLightingColorVec(self,color) # Call Back function. This will be called # when user try to change the color of light. ################################################################# if self.currentLight==None: return self.currentLight.setColor(VBase4((color[0]/255),(color[1]/255),(color[2]/255),1)) return def setSpecularColor(self,color): ################################################################# # setSpecularColor(self,color) # Call Back function. This will be called # when user try to change the Specular color of light. ################################################################# if self.currentLight==None: return self.currentLight.setSpecColor(VBase4((color[0]/255),(color[1]/255),(color[2]/255),1)) return def setPosition(self,position): ################################################################# # setPosition(self,position) # Call Back function. This will be called # when user try to change the position of light. ################################################################# if self.currentLight==None: return self.currentLight.setPosition(Point3(position[0],position[1],position[2])) return def setOrientation(self, orient): ################################################################# # setOrientation(self, orient) # Call Back function. This will be called # when user try to change the orientation of light. ################################################################# if self.currentLight==None: return self.currentLight.setOrientation(Vec3(orient[0],orient[1],orient[2])) return def setConstantAttenuation(self, value): ################################################################# # setConstantAttenuation(self, value) # Call Back function. This will be called # when user try to change the Constant Attenuation of light. ################################################################# self.currentLight.setConstantAttenuation(value) return def setLinearAttenuation(self, value): ################################################################# # setLinearAttenuation(self, value) # Call Back function. This will be called # when user try to change the Linear Attenuation of light. ################################################################# self.currentLight.setLinearAttenuation(value) return def setQuadraticAttenuation(self, value): ################################################################# # setQuadraticAttenuation(self, value) # Call Back function. This will be called # when user try to change the Quadratic Attenuation of light. ################################################################# self.currentLight.setQuadraticAttenuation(value) return def setExponent(self, value): ################################################################# # setExponent(self, value) # Call Back function. This will be called # when user try to change Exponent value of light. ################################################################# self.currentLight.setExponent(value) return
class ClsGUI(Tk): """ Попытка создать ГУИ для репортера. """ def __init__(self): """ Создаёт интерфейс пользователя для репортера. """ def bind_win(): """ Привязка событий к окнам. """ def quit_reporter(event=''): """ Выходит из репортера. :param event: """ import sys sys.exit() def save_reporter(event=''): """ Сохраняет отчёт. :param event: """ print '===report===' _reporter = ClsSmallReporter() self.txt_report.insert('1.0', _reporter.html_data) def generate_report(event=''): """ Генерирует отчёт. :param event: """ print '===report===' reporter = ClsSmallReporter() self.txt_report.insert('1.0', reporter.html_data) self.bind('<Control-Q>', quit_reporter) self.bind('<Control-q>', quit_reporter) self.bind('<Control-S>', save_reporter) self.bind('<Control-s>', save_reporter) self.bind('<Control-G>', generate_report) self.bind('<Control-g>', generate_report) Tk.__init__(self) self.frm_up = Frame(self) self.mnu_file = None self.mnu_custom = None self.btn_exit = None self.mnu_help = None self.mnu_edit = None self.txt_report = None self.btn_edit = None self.btn_save = None self.pnl_menu = None self.btn_custom = None self.btn_generate = None self.btn_file = None self.btn_help = None self.frm_midle = None self.frm_down = None self.title(LANG_RU['win_main']) self.minsize(GEOMETRY['winMain_minSizeX'], GEOMETRY['winMain_minSizeY']) self.maxsize(GEOMETRY['winMain_maxSizeX'], GEOMETRY['winMain_maxSizeY']) self.create_up_frame() self.create_frm_middle() self.create_frm_down() bind_win() self.mainloop() def create_up_frame(self): """ Создаёт верхний фрейм. :type self: object """ self.create_menu_bar() self.frm_up.pack(side='top', fill='x') def create_frm_middle(self): """ Создаёт средний фрейм для отображения. """ self.frm_midle = Frame(self, border=2, relief='raised') self.frm_midle.pack(side='top', expand=1, fill='both') self.txt_report = Text(self.frm_midle, font='Consolas 9 normal') self.txt_report.pack(side='top', fill='both', expand=1) def create_frm_down(self): """ Создаёт нижний фрейм репортера. """ def btn_generate_click(event=''): """ Обработчик нижатия кнопки генератора отчёта. :param event: """ print '===report===' _reporter = ClsSmallReporter() self.txt_report.insert('1.0', _reporter.html_data) def create_btn_exit(): """ Создаёт кнопки выхода из программы. """ def report_exit(event=''): """ Обработчик нажатия кнопки выхода из программы. :param event: """ import sys sys.exit() self.btn_exit = Button(self.frm_down, text=LANG_RU['btn_exit'], command=report_exit, bg='red') self.btn_exit.pack(side='left', expand=1, fill='x') def create_btn_save(): """ Создаёт кнопку для сохранения отчёта. """ self.btn_save = Button(self.frm_down, text=LANG_RU['btn_save']) self.btn_save.pack(side='left', expand=1, fill='x') def create_btn_generate(): """ Создаёт кнопку для генерации отчёта """ self.btn_generate = Button(self.frm_down, text=LANG_RU['btn_generate'], command=btn_generate_click) self.btn_generate.pack(side='left', expand=1, fill='x') self.frm_down = Frame(self) create_btn_generate() create_btn_save() create_btn_exit() self.frm_down.pack(side='bottom', fill='x') def create_menu_bar(self): """ Создаёт линейку для меню программы. """ def create_mnu_file(): """ Создаёт меню файл. """ self.btn_file = Menubutton(self.pnl_menu, text=LANG_RU['mnu_file'], border=3, relief='groove') self.mnu_file = Menu(self.btn_file) self.btn_file.config(menu=self.mnu_file) self.mnu_file.add_command(label=LANG_RU['mnuFile_New'], accelerator='Ctrl+N') self.mnu_file.add_command(label=LANG_RU['mnuFile_Open'], accelerator='Ctrl+O') self.mnu_file.add_separator() self.mnu_file.add_command(label=LANG_RU['mnuFile_Save'], accelerator='Ctrl+S') self.mnu_file.add_command(label=LANG_RU['mnuFile_SaveAs']) self.mnu_file.add_separator() self.mnu_file.add_command(label=LANG_RU['mnuFile_Print'], accelerator='Ctrl+P') self.mnu_file.add_separator() self.mnu_file.add_command(label=LANG_RU['mnuFile_Exit'], accelerator='Ctrl+Q') self.btn_file.pack(side='left') def create_mnu_edit(): """ Создаёт меню "Правка". """ self.btn_edit = Menubutton(self.pnl_menu, text=LANG_RU['mnu_edit'], border=3, relief='groove') self.mnu_edit = Menu(self.btn_edit) self.btn_edit.config(menu=self.mnu_edit) self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Undo'], accelerator='Ctrl+Z') self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Redo']) self.mnu_edit.add_separator() self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Copy'], accelerator='Ctrl+C') self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Cut'], accelerator='Ctrl+X') self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Paste'], accelerator='Ctrl+V') self.mnu_edit.add_separator() self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Find'], accelerator='Ctrl+F') self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Replace'], accelerator='Ctrl+R') self.btn_edit.pack(side='left') def create_mnu_custom(): """ Создаёт меню нстроек. """ self.btn_custom = Menubutton(self.pnl_menu, text='mnu_custom', border=3, relief='groove') self.mnu_custom = Menu(self.btn_custom) self.btn_custom.config(menu=self.mnu_custom) self.mnu_custom.add_command(label='Type files', accelerator='Ctrl+D') self.mnu_custom.add_command(label='--1') self.mnu_custom.add_separator() self.mnu_custom.add_command(label='--2', accelerator='---') self.mnu_custom.add_command(label='--3', accelerator='---') self.mnu_custom.add_command(label='--4', accelerator='---') self.mnu_custom.add_separator() self.btn_custom.pack(side='left') def create_mnu_help(): """ Создаёт меню "Справка". """ self.btn_help = Menubutton(self.pnl_menu, text='mnu_help', border=3, relief='groove') self.mnu_help = Menu(self.btn_help) self.btn_help.config(menu=self.mnu_help) self.mnu_help.add_command(label='Type files', accelerator='Ctrl+D') self.mnu_help.add_command(label='--1') self.mnu_custom.add_separator() self.btn_help.pack(side='left') self.pnl_menu = PanedWindow(self.frm_up, border=2, relief='raised') create_mnu_file() create_mnu_edit() create_mnu_custom() create_mnu_help() self.pnl_menu.pack(side='left', expand=1, fill='x')
def initUI(self): self.parent.title("Booru") self.pack(fill=Y, expand=0, side=LEFT) myicon = ImageTk.PhotoImage(file="sbooru.ico") self.current_booru_var = StringVar() self.mb = Menubutton(self, textvariable=self.current_booru_var, relief=RAISED, image=myicon, compound=LEFT) self.mb.image = myicon self.mb.pack(side=TOP) self.mb.menu = Menu(self.mb, tearoff=0) self.mb["menu"] = self.mb.menu self.current_booru_var.set("Safebooru") def change_booru(booru): self.current_booru = booru if self.current_booru == 0: self.current_booru_var.set("Danbooru") if self.current_booru == 1: self.current_booru_var.set("Safebooru") self.mb.menu.add_command(label="Danbooru", command=lambda: change_booru(0)) self.mb.menu.add_command(label="Safebooru", command=lambda: change_booru(1)) self.mb.pack() image = Image.open( get_image_from_internet_binary( u"%s%s" % (main_url, self.posts[0][u"preview_file_url"]))) photo = ImageTk.PhotoImage(image) self.label = Label(self, image=photo) self.label.image = photo self.label.pack(fill=Y, expand=0, side=TOP) self.lb = Listbox(self) for i in self.posts: self.lb.insert(END, i["id"]) self.lb.bind("<<ListboxSelect>>", self.onSelect) self.lb.pack(pady=15, fill=Y, expand=0, side=LEFT) self.description = Labelframe(self, text="Description", height=350, width=350) self.description.pack(pady=15, expand=0) #artist self.artist_v = StringVar() self.artist = Label(self.description, textvariable=self.artist_v, justify=LEFT, wraplength=350, anchor=W) self.artist.pack() #md5 self.md5_v = StringVar() self.md5 = Label(self.description, textvariable=self.md5_v, justify=LEFT, wraplength=350, anchor=W) self.md5.pack() #source self.source_v = StringVar() self.source = Label(self.description, textvariable=self.source_v, justify=LEFT, wraplength=350, anchor=W) self.source.pack() #wxh self.wxh_v = StringVar() self.wxh = Label(self.description, textvariable=self.wxh_v, justify=LEFT, wraplength=350, anchor=W) self.wxh.pack() #tags (for now all) self.tags_v = StringVar() self.tags = Label(self.description, textvariable=self.tags_v, justify=LEFT, wraplength=350, anchor=W) self.tags.pack() #uploader self.uploader_v = StringVar() self.uploader = Label(self.description, textvariable=self.uploader_v, justify=LEFT, wraplength=350, anchor=W) self.uploader.pack() idx = (0, 0) try: self.artist_v.set(u"Artist:\t%s" % self.posts[idx[0]][u"tag_string_artist"]) except KeyError: self.artist_v.set(u"Artist:\t") try: self.md5_v.set(u"MD5:\t%s" % self.posts[idx[0]][u"md5"]) except KeyError: self.md5_v.set(u"MD5:\t") try: self.source_v.set(u"Source:\t%s" % self.posts[idx[0]][u"source"]) except KeyError: self.source_v.set(u"Source:\t") try: self.wxh_v.set(u"Size:\t%sx%s" % (self.posts[idx[0]][u"image_width"], self.posts[idx[0]][u"image_height"])) except KeyError: self.wxh_v.set(u"Size:\t") try: self.tags_v.set(u"Tags:\t%s" % self.posts[idx[0]][u"tag_string"]) except KeyError: self.tags_v.set(u"Tags:\t") try: self.uploader_v.set(u"Uploader:\t%s" % self.posts[idx[0]][u"uploader_name"]) except KeyError: self.uploader_v.set(u"Uploader:\t") self.button_frame = Frame(self.description) self.button_frame.pack(fill=Y, expand=0, side=LEFT) def download_image_current(): def download(): urllib.urlretrieve( "%s%s" % (main_url, self.current_image[u"file_url"]), "%s_%s.%s" % (self.current_image[u"id"], self.current_image[u"md5"], self.current_image[u"file_ext"])) t1 = Thread(target=download, args=()) t1.start() self.download_button = Button(self.button_frame, text="Download", command=download_image_current) self.download_button.pack(side=LEFT) def bigger_preview(): image = Image.open( get_image_from_internet_binary( u"%s%s" % (main_url, self.current_image[u"file_url"]))) photo = ImageTk.PhotoImage(image) self.bigpreview = Toplevel(self) labelu = Label(self.bigpreview, image=photo) labelu.image = photo labelu.pack(fill=Y, expand=0, side=LEFT) self.preview_button = Button(self.button_frame, text="Preview", command=bigger_preview) self.preview_button.pack(side=RIGHT) def onRefresh(): def method(): query_args["page"] = self.current_page.get() self.posts = get_posts("posts.json", query_args) self.lb.delete(0, END) for i in self.posts: self.lb.insert(END, i["id"]) t1 = Thread(target=method, args=()) t1.start() self.refresh = Button(self.button_frame, text="Refresh posts", command=onRefresh) self.refresh.pack(side=LEFT) page_control = Frame(self) page_control.pack(pady=15, side=BOTTOM) self.current_page = IntVar() self.current_page.set(1) def forward_f(): self.current_page.set(self.current_page.get() + 1) onRefresh() forward = Button(page_control, text=">>", command=forward_f) forward.pack(side=RIGHT) def backward_f(): self.current_page.set((self.current_page.get() - 1) if ( self.current_page.get() - 1 > 0) else self.current_page.get()) onRefresh() backward = Button(page_control, text="<<", command=backward_f) backward.pack(side=LEFT) curpaglabl = Label(page_control, textvariable=self.current_page, background="orange") curpaglabl.pack(pady=15, side=BOTTOM)
def __init__(self,master,start_dir=expanduser("~"),filetypes=[],title="Select a music file.",color_1="#000000",color_2="#00c0c0",highlight_color_items="#c9c9c9") : ''' master == root_window == Tk() use color_1 and color_2 and bg_items and fg_items and highlight_color_items for colors personalisation. filetypes must "Strictly" be a list of extension beginning with an asterix followed by a point and the extension (in lowercase) or an empty list for no filtering. filetypes=["*.mp3","*.wav"] per example. Or insert an, item '*' for all filetype in combination with defined filetypes. for borderwidth and relief settings look at the code ''' # Constrcut GUI for the file selection toplevel. self.toplevel=Toplevel(master,bg=color_1,borderwidth=1,relief="sunken") self.toplevel.resizable(width=False, height=False) self.toplevel.title(title) self.dir_selection_frame=Frame(self.toplevel,bg=color_1,borderwidth=8/2,relief="groove") # Frame container for directory fields. self.dir_name_entry=Entry(self.toplevel,justify="center",width=50,bg=color_2,fg=color_1) # This will contains the current directory relative dirname self.dir_name_separator=Button(self.toplevel,width=1,relief="sunken",bg=color_1,fg=color_2) # An separator self.dir_back_button=Button(self.toplevel,width=6,relief="raised",bg=color_2,fg=color_1,text="Back",command=self.folder_go_back) # Change directory back button. self.canvas_frame=Frame(self.toplevel,borderwidth=8,relief="groove") # Frame for the file selection window canvas and his scrollbar. self.canvas=Canvas(self.canvas_frame,height=20*9,width=18*28,bg=color_2) # File selection window. self.canvas_scrollbar=Scrollbar(self.canvas_frame,orient=HORIZONTAL, bg=color_2,troughcolor=color_1,command=self.canvas.xview) # File selection window scrollbar. self.canvas.configure(xscrollcommand=self.canvas_scrollbar.set) self.file_selection_frame=Frame(self.toplevel,bg=color_1,borderwidth=8/2,relief="groove") # Frame container for filename fields. self.file_name_entry=Entry(self.toplevel,justify="center",width=50,bg=color_2,fg=color_1) # This will contains the basename (relative) of the selected file. self.file_name_separator=Button(self.toplevel,width=1,relief="sunken",bg=color_1,fg=color_2) # An separator. self.file_filter_menubutton = Menubutton(self.file_selection_frame, text='',relief="groove",width=8,bg=color_2,fg=color_1) # Menubutton for filetype filter. self.file_filter_extension="" if filetypes : self.file_filter_menu= Menu(self.file_filter_menubutton,borderwidth=3,relief="groove") # We use a menu for the filetypes filtering. i=0 self.file_filter_var=StringVar(master=None, value=filetypes[i], name=None) # Control varaible for current filetype and initialize with the first filetype item. self.file_filter_menubutton.config(text=filetypes[i]) self.file_filter_extension=filetypes[i][1::] while i < len(filetypes) : # Creating radiobutton to change the filetype filter. self.file_filter_menu.add_radiobutton(label=filetypes[i], variable=self.file_filter_var,value=filetypes[i],background=color_2,command=self.set_filetype_filter ) i += 1 self.file_filter_menubutton.configure(menu= self.file_filter_menu) self.buttons_frame=Frame(self.toplevel,bg=color_2,borderwidth=8,relief="groove",height=50,width=18*3) # Frame container for the buttons. self.button_cancel=Button(self.buttons_frame,bg=color_2,fg=color_1,text="Quit",borderwidth=8/2,relief="groove",width=8,command=self.item_selection_quit) self.button_home=Button(self.buttons_frame,bg=color_2,fg=color_1,text="Home",borderwidth=8/2,relief="groove",width=8,command=self.item_selection_home) self.button_ok=Button(self.buttons_frame,bg=color_2,fg=color_1,text=" OK ",borderwidth=8/2,relief="groove",width=8,command=self.item_selection_ok) self.start_dir=start_dir # Start folder. self.curdir=start_dir # Current folder. self.last_dir=[] # Container for the precedent folders we visit. self.last_dir.append(start_dir) # Append start folder. self.select_filepath="" # Value to return by file selection. self.dir_name_entry.insert(0,"../"+basename(self.curdir)) if not color_2 : self.items_bg="#D9D9D9" else : self.items_bg=color_2 self.items_fg=color_1 self.highlight_color_items=highlight_color_items self.init_icons() self.ls_dir() self.update_canvas() self.dir_selection_frame.grid(row=0,column=0,sticky="WE") self.dir_name_entry.grid(row=0,column=0,in_=self.dir_selection_frame,sticky="NSEW") self.dir_name_separator.grid(row=0,column=1,in_=self.dir_selection_frame,sticky="EW") self.dir_back_button.grid(row=0,column=2,in_=self.dir_selection_frame,sticky="EW") self.canvas_frame.grid(row=1,column=0,sticky="WE") self.canvas.grid(row=0,column=0,in_=self.canvas_frame) self.canvas_scrollbar.grid(row=1,column=0,in_=self.canvas_frame,sticky="WE") self.file_selection_frame.grid(row=2,column=0,sticky="WE") self.file_name_entry.grid(row=0,column=0,in_=self.file_selection_frame,sticky="NSEW") self.file_name_separator.grid(row=0,column=1,in_=self.file_selection_frame,sticky="EW") self.file_filter_menubutton.grid(row=0,column=2,in_=self.file_selection_frame,sticky="NS") self.buttons_frame.grid(row=3,column=0,sticky="NSEW") self.button_cancel.grid(row=0,column=2,padx=32+3,pady=4,in_=self.buttons_frame) self.button_home.grid(row=0,column=4,padx=32+3,pady=4,in_=self.buttons_frame) self.button_ok.grid(row=0,column=6,padx=34+3,pady=4,in_=self.buttons_frame) self.toplevel.wait_window()
def createInterface(self): # Handle to the toplevels interior interior = self.interior() menuBar = self.menuBar self.menuBar.destroy() # Create a frame to hold all stuff mainFrame = Frame(interior) self.listZone = Pmw.Group(mainFrame,tag_pyclass = None) self.listZone.pack(expand=0, fill=Tkinter.X,padx=3,pady=3) listFrame = self.listZone.interior() self.lightEntry = self.createcomponent( 'Lights List', (), None, Pmw.ComboBox, (listFrame,),label_text='Light :', labelpos = Tkinter.W, entry_width = 25, selectioncommand = self.selectLight, scrolledlist_items = self.lightList) self.lightEntry.pack(side=Tkinter.LEFT) self.renameButton = self.createcomponent( 'Rename Light', (), None, Button, (listFrame,), text = ' Rename ', command = self.renameLight) self.renameButton.pack(side=Tkinter.LEFT) self.addLighZone = Pmw.Group(listFrame,tag_pyclass = None) self.addLighZone.pack(side=Tkinter.LEFT) insideFrame = self.addLighZone.interior() self.lightsButton = Menubutton(insideFrame, text = 'Add light',borderwidth = 3, activebackground = '#909090') lightsMenu = Menu(self.lightsButton) lightsMenu.add_command(label = 'Add Ambient Light', command = self.addAmbient) lightsMenu.add_command(label = 'Add Directional Light', command = self.addDirectional) lightsMenu.add_command(label = 'Add Point Light', command = self.addPoint) lightsMenu.add_command(label = 'Add Spotlight', command = self.addSpot) self.lightsButton.pack(expand=0) self.lightsButton['menu'] = lightsMenu self.deleteButton = self.createcomponent( 'delete Light', (), None, Button, (listFrame,), text = ' Delete ', command = self.deleteLight) self.deleteButton.pack(side=Tkinter.LEFT) self.lightColor = seColorEntry( mainFrame, text = 'Light Color', value=self.lightColor) self.lightColor['command'] = self.setLightingColorVec self.lightColor['resetValue'] = [0.3*255,0.3*255,0.3*255,0] self.lightColor.pack(fill=Tkinter.X,expand=0) self.bind(self.lightColor, 'Set light color') # Notebook pages for light specific controls self.lightNotebook = Pmw.NoteBook(mainFrame, tabpos = None, borderwidth = 0) ambientPage = self.lightNotebook.add('Ambient') directionalPage = self.lightNotebook.add('Directional') pointPage = self.lightNotebook.add('Point') spotPage = self.lightNotebook.add('Spot') # Put this here so it isn't called right away self.lightNotebook['raisecommand'] = self.updateLightInfo # Directional light controls self.dSpecularColor = seColorEntry( directionalPage, text = 'Specular Color') self.dSpecularColor['command'] = self.setSpecularColor self.dSpecularColor.pack(fill = Tkinter.X, expand = 0) self.bind(self.dSpecularColor, 'Set directional light specular color') self.dPosition = Vector3Entry( directionalPage, text = 'Position') self.dPosition['command'] = self.setPosition self.dPosition['resetValue'] = [0,0,0,0] self.dPosition.pack(fill = Tkinter.X, expand = 0) self.bind(self.dPosition, 'Set directional light position') self.dOrientation = Vector3Entry( directionalPage, text = 'Orientation') self.dOrientation['command'] = self.setOrientation self.dOrientation['resetValue'] = [0,0,0,0] self.dOrientation.pack(fill = Tkinter.X, expand = 0) self.bind(self.dOrientation, 'Set directional light orientation') # Point light controls self.pSpecularColor = seColorEntry( pointPage, text = 'Specular Color') self.pSpecularColor['command'] = self.setSpecularColor self.pSpecularColor.pack(fill = Tkinter.X, expand = 0) self.bind(self.pSpecularColor, 'Set point light specular color') self.pPosition = Vector3Entry( pointPage, text = 'Position') self.pPosition['command'] = self.setPosition self.pPosition['resetValue'] = [0,0,0,0] self.pPosition.pack(fill = Tkinter.X, expand = 0) self.bind(self.pPosition, 'Set point light position') self.pConstantAttenuation = Slider( pointPage, text = 'Constant Attenuation', max = 1.0, resolution = 0.01, value = 1.0) self.pConstantAttenuation['command'] = self.setConstantAttenuation self.pConstantAttenuation.pack(fill = Tkinter.X, expand = 0) self.bind(self.pConstantAttenuation, 'Set point light constant attenuation') self.pLinearAttenuation = Slider( pointPage, text = 'Linear Attenuation', max = 1.0, resolution = 0.01, value = 0.0) self.pLinearAttenuation['command'] = self.setLinearAttenuation self.pLinearAttenuation.pack(fill = Tkinter.X, expand = 0) self.bind(self.pLinearAttenuation, 'Set point light linear attenuation') self.pQuadraticAttenuation = Slider( pointPage, text = 'Quadratic Attenuation', max = 1.0, resolution = 0.01, value = 0.0) self.pQuadraticAttenuation['command'] = self.setQuadraticAttenuation self.pQuadraticAttenuation.pack(fill = Tkinter.X, expand = 0) self.bind(self.pQuadraticAttenuation, 'Set point light quadratic attenuation') # Spot light controls self.sSpecularColor = seColorEntry( spotPage, text = 'Specular Color') self.sSpecularColor['command'] = self.setSpecularColor self.sSpecularColor.pack(fill = Tkinter.X, expand = 0) self.bind(self.sSpecularColor, 'Set spot light specular color') self.sConstantAttenuation = Slider( spotPage, text = 'Constant Attenuation', max = 1.0, resolution = 0.01, value = 1.0) self.sConstantAttenuation['command'] = self.setConstantAttenuation self.sConstantAttenuation.pack(fill = Tkinter.X, expand = 0) self.bind(self.sConstantAttenuation, 'Set spot light constant attenuation') self.sLinearAttenuation = Slider( spotPage, text = 'Linear Attenuation', max = 1.0, resolution = 0.01, value = 0.0) self.sLinearAttenuation['command'] = self.setLinearAttenuation self.sLinearAttenuation.pack(fill = Tkinter.X, expand = 0) self.bind(self.sLinearAttenuation, 'Set spot light linear attenuation') self.sQuadraticAttenuation = Slider( spotPage, text = 'Quadratic Attenuation', max = 1.0, resolution = 0.01, value = 0.0) self.sQuadraticAttenuation['command'] = self.setQuadraticAttenuation self.sQuadraticAttenuation.pack(fill = Tkinter.X, expand = 0) self.bind(self.sQuadraticAttenuation, 'Set spot light quadratic attenuation') self.sExponent = Slider( spotPage, text = 'Exponent', max = 1.0, resolution = 0.01, value = 0.0) self.sExponent['command'] = self.setExponent self.sExponent.pack(fill = Tkinter.X, expand = 0) self.bind(self.sExponent, 'Set spot light exponent') # MRM: Add frustum controls self.lightNotebook.setnaturalsize() self.lightNotebook.pack(expand = 1, fill = Tkinter.BOTH) mainFrame.pack(expand=1, fill = Tkinter.BOTH)
def __init__(self, root): self.root = root # Radio action buttons self.action = None self.sgmap_single_btn, self.krn_lib_btn, self.multi_map_btn = None, None, None self.file_log_var = StringVar() self.csv_file_var = StringVar() self.krn_folder_var = StringVar() self.output_folder_var = StringVar() self.sgmap_folder_var = StringVar() self.krn_ent_var = StringVar() self.krn_var, self.hem_var = IntVar(), IntVar() self.img, self.cdiag = None, None self.lat_lbl, self.lat_entry = None, None self.k_lbl, self.k_entry = None, None self.zen_lbl, self.zen_entry = None, None self.azi_lbl, self.azi_entry = None, None self.krn_lvl, self.krn_entry, self.krn_btn = None, None, None self.txt_redir, self.prg_log = None, None self.map_btn, self.gen_krn_btn = None, None # Sets window title, size, and icon on screen. self.root.title("Skyglow Estimation Toolbox (SET)") self.root.geometry('%dx%d+%d+%d' % (constants.SW * 0.75, constants.SH * 0.75, 25, 25)) self.root.iconbitmap(os.path.join(os.getcwd(), constants.ICO)) self.root.resizable(False, False) self.root.update_idletasks() # Creates three paned windows for the main screen. base = PanedWindow() base.pack(fill=BOTH, expand=1) sub1 = PanedWindow(base, orient=VERTICAL, height=self.root.winfo_height() * 3 / 4) base.add(sub1) sub2 = PanedWindow(sub1, orient=HORIZONTAL, height=self.root.winfo_height() / 5) sub1.add(sub2) # Creates frame for holding inputs. self.input_frame = Frame(sub2) sub2.add(self.input_frame) # Creates frame for bottom half of main screen. self.img_frame = Frame(sub1, bd=2, bg='white', relief="sunken") sub1.add(self.img_frame) # Creates canvas for displaying images. self.img_canvas = Canvas(self.img_frame, bd=2, relief="groove", width=constants.SW * 0.6, height=self.root.winfo_height() * 3 / 4 * 0.9) self.img_canvas.place(relx=.5, rely=.5, anchor=CENTER) # Creates help button for link to documentation, instructions, and about. self.help_btn = Menubutton(self.input_frame, text="Help", relief="raised", bd=2, width=8, pady=1) #self.help_btn.place(relx=1, rely=0, anchor=NE) self.help_btn.grid(column=4, columnspan=1, row=0) self.help_btn_menu = Menu(self.help_btn, tearoff=0) doc = 'https://github.com/NASA-DEVELOP' self.help_btn_menu.add_command(label="Documentation", command=lambda: self.open_url(doc)) self.help_btn_menu.add_command(label="Instructions", command=self.instructions) self.help_btn_menu.add_separator() self.help_btn_menu.add_command(label="About", command=self.about) self.help_btn["menu"] = self.help_btn_menu
def createInterface(self): # Handle to the toplevels interior interior = self.interior() menuBar = self.menuBar self.menuBar.destroy() # Create a frame to hold all stuff mainFrame = Frame(interior) self.listZone = Pmw.Group(mainFrame, tag_pyclass=None) self.listZone.pack(expand=0, fill=Tkinter.X, padx=3, pady=3) listFrame = self.listZone.interior() self.lightEntry = self.createcomponent( 'Lights List', (), None, Pmw.ComboBox, (listFrame, ), label_text='Light :', labelpos=Tkinter.W, entry_width=25, selectioncommand=self.selectLight, scrolledlist_items=self.lightList) self.lightEntry.pack(side=Tkinter.LEFT) self.renameButton = self.createcomponent('Rename Light', (), None, Button, (listFrame, ), text=' Rename ', command=self.renameLight) self.renameButton.pack(side=Tkinter.LEFT) self.addLighZone = Pmw.Group(listFrame, tag_pyclass=None) self.addLighZone.pack(side=Tkinter.LEFT) insideFrame = self.addLighZone.interior() self.lightsButton = Menubutton(insideFrame, text='Add light', borderwidth=3, activebackground='#909090') lightsMenu = Menu(self.lightsButton) lightsMenu.add_command(label='Add Ambient Light', command=self.addAmbient) lightsMenu.add_command(label='Add Directional Light', command=self.addDirectional) lightsMenu.add_command(label='Add Point Light', command=self.addPoint) lightsMenu.add_command(label='Add Spotlight', command=self.addSpot) self.lightsButton.pack(expand=0) self.lightsButton['menu'] = lightsMenu self.deleteButton = self.createcomponent('delete Light', (), None, Button, (listFrame, ), text=' Delete ', command=self.deleteLight) self.deleteButton.pack(side=Tkinter.LEFT) self.lightColor = seColorEntry(mainFrame, text='Light Color', value=self.lightColor) self.lightColor['command'] = self.setLightingColorVec self.lightColor['resetValue'] = [0.3 * 255, 0.3 * 255, 0.3 * 255, 0] self.lightColor.pack(fill=Tkinter.X, expand=0) self.bind(self.lightColor, 'Set light color') # Notebook pages for light specific controls self.lightNotebook = Pmw.NoteBook(mainFrame, tabpos=None, borderwidth=0) ambientPage = self.lightNotebook.add('Ambient') directionalPage = self.lightNotebook.add('Directional') pointPage = self.lightNotebook.add('Point') spotPage = self.lightNotebook.add('Spot') # Put this here so it isn't called right away self.lightNotebook['raisecommand'] = self.updateLightInfo # Directional light controls self.dSpecularColor = seColorEntry(directionalPage, text='Specular Color') self.dSpecularColor['command'] = self.setSpecularColor self.dSpecularColor.pack(fill=Tkinter.X, expand=0) self.bind(self.dSpecularColor, 'Set directional light specular color') self.dPosition = Vector3Entry(directionalPage, text='Position') self.dPosition['command'] = self.setPosition self.dPosition['resetValue'] = [0, 0, 0, 0] self.dPosition.pack(fill=Tkinter.X, expand=0) self.bind(self.dPosition, 'Set directional light position') self.dOrientation = Vector3Entry(directionalPage, text='Orientation') self.dOrientation['command'] = self.setOrientation self.dOrientation['resetValue'] = [0, 0, 0, 0] self.dOrientation.pack(fill=Tkinter.X, expand=0) self.bind(self.dOrientation, 'Set directional light orientation') # Point light controls self.pSpecularColor = seColorEntry(pointPage, text='Specular Color') self.pSpecularColor['command'] = self.setSpecularColor self.pSpecularColor.pack(fill=Tkinter.X, expand=0) self.bind(self.pSpecularColor, 'Set point light specular color') self.pPosition = Vector3Entry(pointPage, text='Position') self.pPosition['command'] = self.setPosition self.pPosition['resetValue'] = [0, 0, 0, 0] self.pPosition.pack(fill=Tkinter.X, expand=0) self.bind(self.pPosition, 'Set point light position') self.pConstantAttenuation = Slider(pointPage, text='Constant Attenuation', max=1.0, resolution=0.01, value=1.0) self.pConstantAttenuation['command'] = self.setConstantAttenuation self.pConstantAttenuation.pack(fill=Tkinter.X, expand=0) self.bind(self.pConstantAttenuation, 'Set point light constant attenuation') self.pLinearAttenuation = Slider(pointPage, text='Linear Attenuation', max=1.0, resolution=0.01, value=0.0) self.pLinearAttenuation['command'] = self.setLinearAttenuation self.pLinearAttenuation.pack(fill=Tkinter.X, expand=0) self.bind(self.pLinearAttenuation, 'Set point light linear attenuation') self.pQuadraticAttenuation = Slider(pointPage, text='Quadratic Attenuation', max=1.0, resolution=0.01, value=0.0) self.pQuadraticAttenuation['command'] = self.setQuadraticAttenuation self.pQuadraticAttenuation.pack(fill=Tkinter.X, expand=0) self.bind(self.pQuadraticAttenuation, 'Set point light quadratic attenuation') # Spot light controls self.sSpecularColor = seColorEntry(spotPage, text='Specular Color') self.sSpecularColor['command'] = self.setSpecularColor self.sSpecularColor.pack(fill=Tkinter.X, expand=0) self.bind(self.sSpecularColor, 'Set spot light specular color') self.sConstantAttenuation = Slider(spotPage, text='Constant Attenuation', max=1.0, resolution=0.01, value=1.0) self.sConstantAttenuation['command'] = self.setConstantAttenuation self.sConstantAttenuation.pack(fill=Tkinter.X, expand=0) self.bind(self.sConstantAttenuation, 'Set spot light constant attenuation') self.sLinearAttenuation = Slider(spotPage, text='Linear Attenuation', max=1.0, resolution=0.01, value=0.0) self.sLinearAttenuation['command'] = self.setLinearAttenuation self.sLinearAttenuation.pack(fill=Tkinter.X, expand=0) self.bind(self.sLinearAttenuation, 'Set spot light linear attenuation') self.sQuadraticAttenuation = Slider(spotPage, text='Quadratic Attenuation', max=1.0, resolution=0.01, value=0.0) self.sQuadraticAttenuation['command'] = self.setQuadraticAttenuation self.sQuadraticAttenuation.pack(fill=Tkinter.X, expand=0) self.bind(self.sQuadraticAttenuation, 'Set spot light quadratic attenuation') self.sExponent = Slider(spotPage, text='Exponent', max=1.0, resolution=0.01, value=0.0) self.sExponent['command'] = self.setExponent self.sExponent.pack(fill=Tkinter.X, expand=0) self.bind(self.sExponent, 'Set spot light exponent') # MRM: Add frustum controls self.lightNotebook.setnaturalsize() self.lightNotebook.pack(expand=1, fill=Tkinter.BOTH) mainFrame.pack(expand=1, fill=Tkinter.BOTH)
class SkyglowEstimationToolbox: """Main class that establishes GUI.""" def __init__(self, root): self.root = root # Radio action buttons self.action = None self.sgmap_single_btn, self.krn_lib_btn, self.multi_map_btn = None, None, None self.file_log_var = StringVar() self.csv_file_var = StringVar() self.krn_folder_var = StringVar() self.output_folder_var = StringVar() self.sgmap_folder_var = StringVar() self.krn_ent_var = StringVar() self.krn_var, self.hem_var = IntVar(), IntVar() self.img, self.cdiag = None, None self.lat_lbl, self.lat_entry = None, None self.k_lbl, self.k_entry = None, None self.zen_lbl, self.zen_entry = None, None self.azi_lbl, self.azi_entry = None, None self.krn_lvl, self.krn_entry, self.krn_btn = None, None, None self.txt_redir, self.prg_log = None, None self.map_btn, self.gen_krn_btn = None, None # Sets window title, size, and icon on screen. self.root.title("Skyglow Estimation Toolbox (SET)") self.root.geometry('%dx%d+%d+%d' % (constants.SW * 0.75, constants.SH * 0.75, 25, 25)) self.root.iconbitmap(os.path.join(os.getcwd(), constants.ICO)) self.root.resizable(False, False) self.root.update_idletasks() # Creates three paned windows for the main screen. base = PanedWindow() base.pack(fill=BOTH, expand=1) sub1 = PanedWindow(base, orient=VERTICAL, height=self.root.winfo_height() * 3 / 4) base.add(sub1) sub2 = PanedWindow(sub1, orient=HORIZONTAL, height=self.root.winfo_height() / 5) sub1.add(sub2) # Creates frame for holding inputs. self.input_frame = Frame(sub2) sub2.add(self.input_frame) # Creates frame for bottom half of main screen. self.img_frame = Frame(sub1, bd=2, bg='white', relief="sunken") sub1.add(self.img_frame) # Creates canvas for displaying images. self.img_canvas = Canvas(self.img_frame, bd=2, relief="groove", width=constants.SW * 0.6, height=self.root.winfo_height() * 3 / 4 * 0.9) self.img_canvas.place(relx=.5, rely=.5, anchor=CENTER) # Creates help button for link to documentation, instructions, and about. self.help_btn = Menubutton(self.input_frame, text="Help", relief="raised", bd=2, width=8, pady=1) #self.help_btn.place(relx=1, rely=0, anchor=NE) self.help_btn.grid(column=4, columnspan=1, row=0) self.help_btn_menu = Menu(self.help_btn, tearoff=0) doc = 'https://github.com/NASA-DEVELOP' self.help_btn_menu.add_command(label="Documentation", command=lambda: self.open_url(doc)) self.help_btn_menu.add_command(label="Instructions", command=self.instructions) self.help_btn_menu.add_separator() self.help_btn_menu.add_command(label="About", command=self.about) self.help_btn["menu"] = self.help_btn_menu def main_screen(self): """Set up input GUI and image display screen.""" self.action = IntVar() btn_width = int(constants.SW / 60) file_width = int(constants.SW / 18) lbl_width = int(constants.SW / 60) gen_width = int(constants.SW / 42) radio_font = Font(family='TkDefaultFont', size=12) self.sgmap_single_btn = Radiobutton( self.input_frame, text="Generate Artificial Skyglow Map", font=radio_font, width=btn_width, variable=self.action, value='sng', command=self.sng_popup) self.krn_lib_btn = Radiobutton(self.input_frame, text="Generate Kernel Library", font=radio_font, width=btn_width, variable=self.action, value='krn', command=self.krn_popup) self.multi_map_btn = Radiobutton( self.input_frame, text="Generate Maps from Multiple Kernels", font=radio_font, width=btn_width, variable=self.action, value='mul', command=self.mul_popup) self.hem_map_btn = Radiobutton( self.input_frame, text="Generate Hemispherical Visualization", font=radio_font, width=btn_width, variable=self.action, value='hem', command=self.hem_popup) #Place widget self.sgmap_single_btn.grid(column=0, columnspan=1, row=0) self.krn_lib_btn.grid(column=1, columnspan=1, row=0) self.multi_map_btn.grid(column=2, columnspan=1, row=0) self.hem_map_btn.grid(column=3, columnspan=1, row=0) # VIIRS Image Reference File self.file_lbl = Label(self.input_frame, text="Image File:", width=lbl_width, anchor=E) self.file_log = Entry(self.input_frame, width=file_width, bd=2, relief="sunken", textvariable=self.file_log_var) self.browse_btn = Button(self.input_frame, text="Browse", command=self.import_viirs) # Angles CSV File self.csv_file_lbl = Label(self.input_frame, text="Angles CSV File:", width=lbl_width, anchor=E) self.csv_file_log = Entry(self.input_frame, width=file_width, bd=2, relief="sunken", textvariable=self.csv_file_var) self.csv_browse_btn = Button(self.input_frame, text="Browse", command=self.import_csv) # Multiple Maps form Kernel library self.mul_file_lbl = Label(self.input_frame, text="Kernel Folder:", width=lbl_width, anchor=E) self.mul_file_log = Entry(self.input_frame, width=file_width, bd=2, relief="sunken", textvariable=self.krn_folder_var) self.mul_browse_btn = Button(self.input_frame, text="Browse", command=self.import_krn_folder) # MultiKrn Map Output Location self.output_lbl = Label(self.input_frame, text="Output Location:", width=lbl_width, anchor=E) self.output_log = Entry(self.input_frame, width=file_width, bd=2, relief="sunken", textvariable=self.output_folder_var) self.output_btn = Button(self.input_frame, text="Browse", command=self.import_out_folder) # Hemisphere Output Location self.sgmap_folder_lbl = Label(self.input_frame, text="Skyglow Map Location:", width=lbl_width, anchor=E) self.sgmap_folder_log = Entry(self.input_frame, width=file_width, bd=2, relief="sunken", textvariable=self.sgmap_folder_var) self.sgmap_folder_btn = Button(self.input_frame, text="Browse", command=self.import_sgmap_folder) # Import Kernel Checkbutton self.check_lbl = Label(self.input_frame, text="Import Kernel:", width=lbl_width, anchor=E) self.krn_chk = Checkbutton(self.input_frame, anchor=W, variable=self.krn_var, command=self.checkbtn_val) self.hem_chk_lbl = Label(self.input_frame, text="Generate kernels for hemisphere:", width=lbl_width, anchor=E) self.hem_chk = Checkbutton(self.input_frame, anchor=W, variable=self.hem_var) # Region Latitude (deg), Grand Teton National park = 43.7904 degrees N self.lat_lbl = Label(self.input_frame, text="Latitude (deg):", width=lbl_width, anchor=E) self.lat_entry = Entry(self.input_frame, width=btn_width, bd=2, relief="sunken") self.lon_lbl = Label(self.input_frame, text="Longitude (deg):", width=lbl_width, anchor=E) self.lon_entry = Entry(self.input_frame, width=btn_width, bd=2, relief="sunken") # Atmospheric Clarity Parameter, REF 2, Eq. 12, p. 645 self.k_lbl = Label(self.input_frame, text="Atmospheric Clarity Parameter:", width=btn_width, anchor=E) self.k_entry = Entry(self.input_frame, width=btn_width, bd=2, relief="sunken") # Zenith angle (deg), z, REF 2, Fig. 6, p.648 self.zen_lbl = Label(self.input_frame, text="Zenith Angle (deg):", width=lbl_width, anchor=E) self.zen_entry = Entry(self.input_frame, width=btn_width, bd=2, relief="sunken") # Azimuth angle (deg) self.azi_lbl = Label(self.input_frame, text="Azimuth Angle (deg):", width=lbl_width, anchor=E) self.azi_entry = Entry(self.input_frame, width=btn_width, bd=2, relief="sunken") self.krn_lbl = Label(self.input_frame, text="Kernel File:", width=lbl_width, anchor=E) self.krn_ent = Entry(self.input_frame, width=file_width, bd=2, relief="sunken", textvariable=self.krn_ent_var) self.krn_btn = Button(self.input_frame, text="Browse", command=self.import_krn) # Generate Artificial Skyglow Map Button self.map_btn = Button(self.input_frame, text="Generate Artificial Skyglow Map", width=gen_width, command=self.generate_map) # Generate Kernal library button for SET self.gen_krn_btn = Button(self.input_frame, text="Generate Kernel Library", width=gen_width, command=self.generate_krn) # Generate Map of Multiple Kernals(word better later on) self.mul_map_btn = Button(self.input_frame, text="Generate Maps from Multiple Kernels", width=gen_width, command=self.generate_mmap) # Generate Hemispherical Visualization Display of Skyglow self.hem_gen_btn = Button(self.input_frame, text="Generate Hemisphere", width=gen_width, command=self.generate_hem) def import_viirs(self): """Import a VIIRS DNB file.""" # Allows user to search through his directory for VIIRS Image file. file_types = [('TIFF Files', '*.tif'), ('All files', '*')] file_name = filedialog.askopenfilename(initialdir='/', title="Select file", filetypes=file_types) self.file_log_var.set(file_name) # Checks to see if file is empty. If not, displays image on canvas. if file_name != '': pilimg = Image.open(file_name) pilimg_width, pilimg_height = pilimg.size pilimg.tile = [ t for t in pilimg.tile if t[1][2] < pilimg_width and t[1][3] < pilimg_height ] canvas_size = (self.img_canvas.winfo_width(), self.img_canvas.winfo_height()) pilimg_r = pilimg.resize(canvas_size, Image.ANTIALIAS) pilimg_col = ImageOps.colorize(ImageOps.grayscale(pilimg_r), (0, 0, 0), (255, 255, 255)) pilimg_cont = ImageOps.autocontrast(pilimg_col, cutoff=.4, ignore=None) self.img = ImageTk.PhotoImage(pilimg_cont) self.img_canvas.create_image(canvas_size[0] / 2, canvas_size[1] / 2, image=self.img) else: print('File is empty.') def import_csv(self): """Import CSV file.""" file_types = [('CSV Files', '*.csv'), ('All files', '*')] file_name = filedialog.askopenfilename(initialdir='/', title="Select file", filetypes=file_types) self.csv_file_var.set(file_name) if file_name is '': print('File is empty.') def import_krn_folder(self): """Import kernel folder.""" krn_dir = filedialog.askdirectory(initialdir='/', title="Select kernel folder") self.krn_folder_var.set(krn_dir) if krn_dir is '': print('Directory is empty.') def import_out_folder(self): """Import skyglow output folder.""" output_dir = filedialog.askdirectory(initialdir='/', title="Select output folder") self.output_folder_var.set(output_dir) if output_dir is '': print('Directory is empty.') def import_krn(self): """Import existing kernel tif.""" file_types = [('TIFF Files', '*.tif'), ('All files', '*')] file_name = filedialog.askopenfilename(initialdir='/', title="Select file", filetypes=file_types) self.krn_ent_var.set(file_name) def import_sgmap_folder(self): """Import skyglow map folder for hemisphere building.""" sgmap_dir = filedialog.askdirectory(initialdir='/', title="Select skyglow map folder") self.sgmap_folder_var.set(sgmap_dir) if sgmap_dir is '': print('Directory is empty.') def sng_popup(self): """Single map tab.""" self.remove_all() self.check_lbl.grid(column=0, row=2) self.krn_chk.place(relx=.22, rely=.41, anchor=CENTER) self.file_lbl.grid(column=0, row=1) self.file_log.grid(column=1, columnspan=3, row=1) self.browse_btn.grid(column=4, row=1, sticky=W, padx=3) self.lat_lbl.grid(column=0, row=3) self.lat_entry.grid(column=1, row=3) self.k_lbl.grid(column=2, row=3) self.k_entry.grid(column=3, row=3) self.zen_lbl.grid(column=0, row=4) self.zen_entry.grid(column=1, row=4) self.azi_lbl.grid(column=2, row=4) self.azi_entry.grid(column=3, row=4) self.map_btn.grid(column=1, columnspan=3, row=5, sticky=N + S + E + W) def krn_popup(self): """Kernel lib tab.""" self.remove_all() # latitude self.lat_lbl.grid(column=0, row=3) self.lat_entry.grid(column=1, row=3) # atmospheric clarity self.k_lbl.grid(column=2, row=3) self.k_entry.grid(column=3, row=3) # angles file self.csv_file_lbl.grid(column=0, row=1) self.csv_file_log.grid(column=1, columnspan=3, row=1) self.csv_browse_btn.grid(column=4, row=1, sticky=W, padx=3) # input VIIRS image self.file_lbl.grid(column=0, row=2) self.file_log.grid(column=1, columnspan=3, row=2) self.browse_btn.grid(column=4, row=2, sticky=W, padx=3) self.hem_chk_lbl.grid(column=0, row=4) self.hem_chk.place(relx=.21, rely=.69) self.gen_krn_btn.grid(column=1, columnspan=3, row=5, sticky=N + S + E + W) def mul_popup(self): """Multiple maps tab.""" self.remove_all() # Kernel folder location self.mul_file_lbl.grid(column=0, row=1) self.mul_file_log.grid(column=1, columnspan=3, row=1) self.mul_browse_btn.grid(column=4, row=1, sticky=W, padx=3) # input VIIRS image self.file_lbl.grid(column=0, row=2) self.file_log.grid(column=1, columnspan=3, row=2) self.browse_btn.grid(column=4, row=2, sticky=W, padx=3) # Choose output location self.output_lbl.grid(column=0, row=3) self.output_log.grid(column=1, columnspan=3, row=3) self.output_btn.grid(column=4, row=3, sticky=W, padx=3) # Generate map from kernel folder self.mul_map_btn.grid(column=1, columnspan=3, row=4, sticky=N + S + E + W) def hem_popup(self): """Hemisphere tab.""" self.remove_all() # Skyglow Map Folder self.sgmap_folder_lbl.grid(column=0, row=1) self.sgmap_folder_log.grid(column=1, columnspan=3, row=1) self.sgmap_folder_btn.grid(column=4, row=1, sticky=W, padx=3) # Latitude entry self.lat_lbl.grid(column=0, row=3) self.lat_entry.grid(column=1, row=3) # Longitude entry self.lon_lbl.grid(column=2, row=3) self.lon_entry.grid(column=3, row=3) # Generate Hemispherical Visualization button self.hem_gen_btn.grid(column=1, columnspan=3, row=4, sticky=N + S + E + W) def remove_all(self): """Remove all existing GUI elements before opening new tab.""" self.check_lbl.grid_remove() self.krn_chk.place_forget() self.hem_chk.place_forget() self.hem_chk_lbl.grid_remove() self.file_lbl.grid_remove() self.file_log.grid_remove() self.browse_btn.grid_remove() self.krn_lbl.grid_remove() self.krn_ent.grid_remove() self.krn_btn.grid_remove() self.lat_lbl.grid_remove() self.lat_entry.grid_remove() self.k_lbl.grid_remove() self.k_entry.grid_remove() self.zen_lbl.grid_remove() self.zen_entry.grid_remove() self.azi_lbl.grid_remove() self.azi_entry.grid_remove() self.map_btn.grid_remove() self.gen_krn_btn.grid_remove() self.mul_map_btn.grid_remove() self.csv_file_lbl.grid_remove() self.csv_file_log.grid_remove() self.csv_browse_btn.grid_remove() self.mul_file_lbl.grid_remove() self.mul_file_log.grid_remove() self.mul_browse_btn.grid_remove() self.output_lbl.grid_remove() self.output_log.grid_remove() self.output_btn.grid_remove() self.hem_gen_btn.grid_remove() self.lat_lbl.grid_remove() self.lat_entry.grid_remove() self.lon_lbl.grid_remove() self.lon_entry.grid_remove() self.sgmap_folder_lbl.grid_remove() self.sgmap_folder_log.grid_remove() self.sgmap_folder_btn.grid_remove() def checkbtn_val(self): """Change interface based on if Import Kernel button is checked.""" # Import Kernel File widgets when Kernel Checkbutton is marked. if self.krn_var.get(): self.lat_lbl.grid_remove() self.lat_entry.grid_remove() self.k_lbl.grid_remove() self.k_entry.grid_remove() self.zen_lbl.grid_remove() self.zen_entry.grid_remove() self.azi_lbl.grid_remove() self.azi_entry.grid_remove() self.krn_lbl.grid(column=0, row=2) self.krn_ent.grid(column=1, columnspan=3, row=2) self.krn_btn.grid(column=4, row=2, sticky=W, padx=3) self.krn_chk.place_forget() self.krn_chk.place(relx=0.19, rely=.5) # Input parameter widgets when Kernel Checkbuttton is unmarked else: self.krn_lbl.grid_remove() self.krn_ent.grid_remove() self.krn_btn.grid_remove() self.lat_lbl.grid(column=0, row=3) self.lat_entry.grid(column=1, row=3) self.k_lbl.grid(column=2, row=3) self.k_entry.grid(column=3, row=3) self.zen_lbl.grid(column=0, row=4) self.zen_entry.grid(column=1, row=4) self.azi_lbl.grid(column=2, row=4) self.azi_entry.grid(column=3, row=4) self.krn_chk.place_forget() self.krn_chk.place(relx=0.22, rely=.41, anchor=CENTER) @staticmethod def open_url(url): """"Open a url""" webbrowser.open_new(url) def instructions(self): """Open instructions window.""" # Instantiates separate Toplevel instruction window. instr_window = Toplevel(self.root) instr_window.geometry('550x575+25+25') instr_window.title('Instructions') instr_window.wm_iconbitmap(constants.ICO) instr_window.resizable(False, False) # Creatse Scrollbar and Frame for containing other widgets. instr_scroll = Scrollbar(instr_window) instr_scroll.pack(fill=Y, side="right") instr_frame = Frame(instr_window, bg='white') instr_frame.pack(fill=BOTH, side="left") # Adds instruction text from constants and adds image of Cinzano's diagram. instr = Text(instr_frame, width=65, height=40, padx=10, pady=5, bd=0, wrap="word") instr.insert("end", constants.INSTR) cdiagram_file = Image.open("./static/cinzano_diagram.PNG") cdiagram_file = cdiagram_file.resize((500, 450), Image.ANTIALIAS) self.cdiag = ImageTk.PhotoImage(cdiagram_file) instr.image_create("end", image=self.cdiag) instr.tag_add("top", "1.0", "4.10") instr.tag_config("top", font='Times 12 bold') instr.tag_add("body", "5.0", "19.20") instr.tag_config("body", font='Times 12') instr.insert("end", constants.CDIAG) instr.pack() instr_scroll.config(command=instr.yview) def about(self): """Open an about window. Window gives authors, SET version number, and icon credit. """ # Instantiates a new Toplevel about window. about_window = Toplevel(self.root) about_window.geometry('350x335+25+25') about_window.title('About') about_window.wm_iconbitmap(constants.ICO) about_window.resizable(False, False) # Adds text to about window. about = Text(about_window, width=50, height=30, padx=10, pady=3) about.insert("end", constants.ABOUT) about.tag_add("abt", "1.0", "21.30") about.tag_config("abt", font='Times 10 bold', justify=CENTER) about.pack() def progress(self): """Construct a progress window to monitor darksky.""" # Instantiates a new Toplevel window and frame for progress bar and loading log. self.prg_window = Toplevel(self.root) self.prg_window.geometry('650x325+250+250') self.prg_window.title('Generating Artificial Skyglow Map...') self.prg_window.iconbitmap(constants.ICO) self.prg_window.resizable(False, False) prg_frame = Frame(self.prg_window) prg_frame.pack(fill=BOTH) # Creates Scrollbar, Progressbar, and Label for checking progress.. prg_scroll = Scrollbar(prg_frame) prg_scroll.pack(fill=Y, side="right") self.prg_bar = ttk.Progressbar(prg_frame, orient=HORIZONTAL, length=750, mode='indeterminate') self.prg_bar.pack() self.prg_bar.start() prg_lbl_txt = StringVar() prg_lbl = Label(prg_frame, textvariable=prg_lbl_txt) prg_lbl.pack() # Displays message log that prints from log file and starts darkskypy. self.prg_log = Text(prg_frame, width=90, padx=5, pady=5, relief="sunken") self.prg_log.pack() self.prg_log.insert( "end", "*****Progress Log*****\n=======================\n") self.prg_log.tag_add("abt", "1.0", "3.0") self.prg_log.tag_config("abt", font='Courier 12 bold', justify=CENTER) self.txt_redir = LogRedirector(self.prg_log) logger.addHandler(self.txt_redir) sys.stderr = StderrRedirector(self.prg_log) prg_lbl_txt.set("Start time: " + str(time.asctime())) self.no_progress = 0 def update_progress(self): """Update progress window to prevent it from freezing.""" self.prg_log.update() # if only one thread exists, stop progress bar and close window if len(threading.enumerate()) == 1: self.prg_bar.stop() self.no_progress += 1 if self.no_progress == 3: self.prg_window.withdraw() else: self.prg_bar.start() self.root.after(1000, self.update_progress) def generate_map(self): """Call darksky.sgmapper in background thread.""" # Acquires input arguments. lat_in, k_in, zen_in, azi_in, file_in, krn_file_in = 0, 0, 0, 0, '', '' if self.krn_var.get(): krn_file_in = self.krn_ent_var.get() else: lat_in = float(self.lat_entry.get()) k_in = float(self.k_entry.get()) zen_in = float(self.zen_entry.get()) azi_in = float(self.azi_entry.get()) file_in = self.file_log_var.get() self.progress() # Create new threads to run light propagation model simultaneously. p_thread = threading.Thread(target=self.update_progress()) t_thread = threading.Thread(target=darksky.sgmapper, args=(lat_in, k_in, zen_in, azi_in, file_in, krn_file_in)) t_thread.setDaemon(True) p_thread.start() t_thread.start() def generate_krn(self): """Start kernel generation in background threads.""" # Acquires input arguments csv_in, file_in, lat_in, k_in, hem = '', '', 0, 0, False csv_in = self.csv_file_var.get() file_in = self.file_log_var.get() lat_in = float(self.lat_entry.get()) k_in = float(self.k_entry.get()) hem = self.hem_var.get() self.progress() # Create new threads to run light propagation model simultaneously. p_thread = threading.Thread(target=self.update_progress()) with open(csv_in, "rb") as f: angle_list = loadtxt(f, delimiter=",", skiprows=1) p_thread.start() for angle_set in angle_list: t_thread = threading.Thread(target=darksky.generate_krn, args=(lat_in, k_in, angle_set[0], angle_set[1], file_in, hem)) t_thread.setDaemon(True) t_thread.start() def generate_mmap(self): """Start brightness map creation from kernels.""" # Acquires input arguments krn_folder_in, file_in, output_in, = '', '', '' krn_folder_in = self.krn_folder_var.get() file_in = self.file_log_var.get() output_in = self.output_folder_var.get() self.progress() # Create new threads to run light propagation model simultaneously. p_thread = threading.Thread(target=self.update_progress()) t_thread = threading.Thread(target=darksky.multisgmapper, args=(file_in, krn_folder_in, output_in)) t_thread.setDaemon(True) p_thread.start() t_thread.start() def generate_hem(self): """Generate hemisphere.""" sgmap_folder_in, lat_in, lon_in, = '', 0, 0 sgmap_folder_in = self.sgmap_folder_var.get() lat_in = float(self.lat_entry.get()) lon_in = float(self.lon_entry.get()) darksky.generate_hem(lat_in, lon_in, sgmap_folder_in)
class lightingPanel(AppShell): ################################################################# # lightingPanel(AppShell) # This will create a window to let user # create any kinds of lighting into the scene ################################################################# # Override class variables appname = 'Lighting Panel' frameWidth = 400 frameHeight = 400 currentLight = None def __init__(self, lightList, parent=None, **kw): self.lightList = lightList self.lightColor = [0.3 * 255, 0.3 * 255, 0.3 * 255] self.type = '' INITOPT = Pmw.INITOPT optiondefs = (('title', self.appname, None), ) self.defineoptions(kw, optiondefs) # Initialize the superclass AppShell.__init__(self) # Execute option callbacks self.initialiseoptions(lightingPanel) self.parent.resizable( False, False) ## Disable the ability to resize for this Window. def createInterface(self): # Handle to the toplevels interior interior = self.interior() menuBar = self.menuBar self.menuBar.destroy() # Create a frame to hold all stuff mainFrame = Frame(interior) self.listZone = Pmw.Group(mainFrame, tag_pyclass=None) self.listZone.pack(expand=0, fill=Tkinter.X, padx=3, pady=3) listFrame = self.listZone.interior() self.lightEntry = self.createcomponent( 'Lights List', (), None, Pmw.ComboBox, (listFrame, ), label_text='Light :', labelpos=Tkinter.W, entry_width=25, selectioncommand=self.selectLight, scrolledlist_items=self.lightList) self.lightEntry.pack(side=Tkinter.LEFT) self.renameButton = self.createcomponent('Rename Light', (), None, Button, (listFrame, ), text=' Rename ', command=self.renameLight) self.renameButton.pack(side=Tkinter.LEFT) self.addLighZone = Pmw.Group(listFrame, tag_pyclass=None) self.addLighZone.pack(side=Tkinter.LEFT) insideFrame = self.addLighZone.interior() self.lightsButton = Menubutton(insideFrame, text='Add light', borderwidth=3, activebackground='#909090') lightsMenu = Menu(self.lightsButton) lightsMenu.add_command(label='Add Ambient Light', command=self.addAmbient) lightsMenu.add_command(label='Add Directional Light', command=self.addDirectional) lightsMenu.add_command(label='Add Point Light', command=self.addPoint) lightsMenu.add_command(label='Add Spotlight', command=self.addSpot) self.lightsButton.pack(expand=0) self.lightsButton['menu'] = lightsMenu self.deleteButton = self.createcomponent('delete Light', (), None, Button, (listFrame, ), text=' Delete ', command=self.deleteLight) self.deleteButton.pack(side=Tkinter.LEFT) self.lightColor = seColorEntry(mainFrame, text='Light Color', value=self.lightColor) self.lightColor['command'] = self.setLightingColorVec self.lightColor['resetValue'] = [0.3 * 255, 0.3 * 255, 0.3 * 255, 0] self.lightColor.pack(fill=Tkinter.X, expand=0) self.bind(self.lightColor, 'Set light color') # Notebook pages for light specific controls self.lightNotebook = Pmw.NoteBook(mainFrame, tabpos=None, borderwidth=0) ambientPage = self.lightNotebook.add('Ambient') directionalPage = self.lightNotebook.add('Directional') pointPage = self.lightNotebook.add('Point') spotPage = self.lightNotebook.add('Spot') # Put this here so it isn't called right away self.lightNotebook['raisecommand'] = self.updateLightInfo # Directional light controls self.dSpecularColor = seColorEntry(directionalPage, text='Specular Color') self.dSpecularColor['command'] = self.setSpecularColor self.dSpecularColor.pack(fill=Tkinter.X, expand=0) self.bind(self.dSpecularColor, 'Set directional light specular color') self.dPosition = Vector3Entry(directionalPage, text='Position') self.dPosition['command'] = self.setPosition self.dPosition['resetValue'] = [0, 0, 0, 0] self.dPosition.pack(fill=Tkinter.X, expand=0) self.bind(self.dPosition, 'Set directional light position') self.dOrientation = Vector3Entry(directionalPage, text='Orientation') self.dOrientation['command'] = self.setOrientation self.dOrientation['resetValue'] = [0, 0, 0, 0] self.dOrientation.pack(fill=Tkinter.X, expand=0) self.bind(self.dOrientation, 'Set directional light orientation') # Point light controls self.pSpecularColor = seColorEntry(pointPage, text='Specular Color') self.pSpecularColor['command'] = self.setSpecularColor self.pSpecularColor.pack(fill=Tkinter.X, expand=0) self.bind(self.pSpecularColor, 'Set point light specular color') self.pPosition = Vector3Entry(pointPage, text='Position') self.pPosition['command'] = self.setPosition self.pPosition['resetValue'] = [0, 0, 0, 0] self.pPosition.pack(fill=Tkinter.X, expand=0) self.bind(self.pPosition, 'Set point light position') self.pConstantAttenuation = Slider(pointPage, text='Constant Attenuation', max=1.0, resolution=0.01, value=1.0) self.pConstantAttenuation['command'] = self.setConstantAttenuation self.pConstantAttenuation.pack(fill=Tkinter.X, expand=0) self.bind(self.pConstantAttenuation, 'Set point light constant attenuation') self.pLinearAttenuation = Slider(pointPage, text='Linear Attenuation', max=1.0, resolution=0.01, value=0.0) self.pLinearAttenuation['command'] = self.setLinearAttenuation self.pLinearAttenuation.pack(fill=Tkinter.X, expand=0) self.bind(self.pLinearAttenuation, 'Set point light linear attenuation') self.pQuadraticAttenuation = Slider(pointPage, text='Quadratic Attenuation', max=1.0, resolution=0.01, value=0.0) self.pQuadraticAttenuation['command'] = self.setQuadraticAttenuation self.pQuadraticAttenuation.pack(fill=Tkinter.X, expand=0) self.bind(self.pQuadraticAttenuation, 'Set point light quadratic attenuation') # Spot light controls self.sSpecularColor = seColorEntry(spotPage, text='Specular Color') self.sSpecularColor['command'] = self.setSpecularColor self.sSpecularColor.pack(fill=Tkinter.X, expand=0) self.bind(self.sSpecularColor, 'Set spot light specular color') self.sConstantAttenuation = Slider(spotPage, text='Constant Attenuation', max=1.0, resolution=0.01, value=1.0) self.sConstantAttenuation['command'] = self.setConstantAttenuation self.sConstantAttenuation.pack(fill=Tkinter.X, expand=0) self.bind(self.sConstantAttenuation, 'Set spot light constant attenuation') self.sLinearAttenuation = Slider(spotPage, text='Linear Attenuation', max=1.0, resolution=0.01, value=0.0) self.sLinearAttenuation['command'] = self.setLinearAttenuation self.sLinearAttenuation.pack(fill=Tkinter.X, expand=0) self.bind(self.sLinearAttenuation, 'Set spot light linear attenuation') self.sQuadraticAttenuation = Slider(spotPage, text='Quadratic Attenuation', max=1.0, resolution=0.01, value=0.0) self.sQuadraticAttenuation['command'] = self.setQuadraticAttenuation self.sQuadraticAttenuation.pack(fill=Tkinter.X, expand=0) self.bind(self.sQuadraticAttenuation, 'Set spot light quadratic attenuation') self.sExponent = Slider(spotPage, text='Exponent', max=1.0, resolution=0.01, value=0.0) self.sExponent['command'] = self.setExponent self.sExponent.pack(fill=Tkinter.X, expand=0) self.bind(self.sExponent, 'Set spot light exponent') # MRM: Add frustum controls self.lightNotebook.setnaturalsize() self.lightNotebook.pack(expand=1, fill=Tkinter.BOTH) mainFrame.pack(expand=1, fill=Tkinter.BOTH) def onDestroy(self, event): messenger.send('LP_close') ''' If you have open any thing, please rewrite here! ''' pass def renameLight(self): ################################################################# # renameLight(self) # Call Back function # This function will be called when user push # the "Rename" button on the panel. # # Then, this function will collect data and send out them with a message # "LP_rename" # Which will be caught by sceneEditor and pass to dataHolder to # complete the renaming. # ################################################################# oName = self.currentLight nName = self.lightEntry.get() messenger.send('LP_rename', [oName, nName]) return def deleteLight(self): ################################################################# # deleteLight(self) # Call Back Function. # This function will be called when user click on # the "Delete" button on the panel. # # Then, this function will send out a message with current seleted light # "LP_removeLight" # Which will be caught by sceneEditor and pass to dataHolder to # complete the delete process. # ################################################################# messenger.send('LP_removeLight', [self.currentLight]) return def updateList(self, list, node=None): ################################################################# # updataList(self, list, node = None) # This function will take a list object which contains names of lights in the scene. # Also, if user has put node as a parameter, # this function will automatically select that node as the current working target. ################################################################# self.lightList = list self.lightEntry.setlist(list) if node != None: self.lightEntry.selectitem(index=node.getName(), setentry=True) self.updateDisplay(node) elif len(list) > 0: self.lightEntry.selectitem(index=0, setentry=True) self.selectLight(list[0]) else: self.lightEntry.clear() return def selectLight(self, lightName): ################################################################# # selectLight(self, lightName) # This function will be called each time when # user select a light from the list on the panel. # Then, this function will send out the message, # 'LP_selectLight' to sceneEditorand get the current light information from dataHolder. ################################################################# if lightName in self.lightList: messenger.send('LP_selectLight', [lightName]) return def updateDisplay(self, lightNode): ################################################################# # updateDisplay(self, lightNode) # This function will update the information showing on the panel. # For example, give a lightNode which is a Point Light. # This function will switch the page to specify the type. # Also, new node is the same type with the previous one, # then this is function won't do the page switching, # but will call other function to refresh the data to target node. ################################################################# self.currentLight = lightNode if self.currentLight != None: color = lightNode.getLightColor() self.lightColor.set( [255 * color.getX(), 255 * color.getY(), 255 * color.getZ()]) oldType = self.type self.type = lightNode.getType() else: self.lightColor.set([255 * 0.3, 255 * 0.3, 255 * 0.3]) oldType = self.type self.type = 'ambient' if self.type == 'ambient': self.lightNotebook.selectpage('Ambient') elif self.type == 'directional': self.lightNotebook.selectpage('Directional') elif self.type == 'point': self.lightNotebook.selectpage('Point') elif self.type == 'spot': self.lightNotebook.selectpage('Spot') if oldType == self.type: # The same type with previous one, call updateLightInfo to refresh the values. self.updateLightInfo() return def updateLightInfo(self, page=None): ################################################################# # updateLightInfo(self, page=None) # This function will refresh the data we user have done any selection. ################################################################# if self.currentLight != None: light = self.currentLight.getLight() if self.type != 'ambient': specColor = light.getSpecularColor() if self.type == 'directional': point = self.currentLight.getPosition() dir = self.currentLight.getOrientation() self.dSpecularColor.set([ specColor.getX() * 255, specColor.getY() * 255, specColor.getZ() * 255 ]) self.dPosition.set([point.getX(), point.getY(), point.getZ()]) self.dOrientation.set([dir.getX(), dir.getY(), dir.getZ()]) elif self.type == 'point': point = self.currentLight.getPosition() attenuation = light.getAttenuation() self.pSpecularColor.set([ specColor.getX() * 255, specColor.getY() * 255, specColor.getZ() * 255 ]) self.pPosition.set([point.getX(), point.getY(), point.getZ()]) self.pConstantAttenuation.set(attenuation.getX()) self.pLinearAttenuation.set(attenuation.getY()) self.pQuadraticAttenuation.set(attenuation.getZ()) elif self.type == 'spot': attenuation = light.getAttenuation() expo = light.getExponent() self.sSpecularColor.set([ specColor.getX() * 255, specColor.getY() * 255, specColor.getZ() * 255 ]) self.sConstantAttenuation.set(attenuation.getX()) self.sLinearAttenuation.set(attenuation.getY()) self.sQuadraticAttenuation.set(attenuation.getZ()) self.sExponent.set(expo) return def addAmbient(self): ################################################################# # addAmbient(self) # This function will send out a message to # ask dataHolder to create a default ambient light ################################################################# messenger.send('LP_addLight', ['ambient']) return def addDirectional(self): ################################################################# # addDirectional(self) # This function will send out a message to # sk dataHolder to create a default Directional light ################################################################# messenger.send('LP_addLight', ['directional']) return def addPoint(self): ################################################################# # addPoint(self) # This function will send out a message to # ask dataHolder to create a default Point light ################################################################# messenger.send('LP_addLight', ['point']) return def addSpot(self): ################################################################# # addSpot(self) # This function will send out a message to # ask dataHolder to create a default Spot light ################################################################# messenger.send('LP_addLight', ['spot']) return def setLightingColorVec(self, color): ################################################################# # setLightingColorVec(self,color) # Call Back function. This will be called # when user try to change the color of light. ################################################################# if self.currentLight == None: return self.currentLight.setColor( VBase4((color[0] / 255), (color[1] / 255), (color[2] / 255), 1)) return def setSpecularColor(self, color): ################################################################# # setSpecularColor(self,color) # Call Back function. This will be called # when user try to change the Specular color of light. ################################################################# if self.currentLight == None: return self.currentLight.setSpecColor( VBase4((color[0] / 255), (color[1] / 255), (color[2] / 255), 1)) return def setPosition(self, position): ################################################################# # setPosition(self,position) # Call Back function. This will be called # when user try to change the position of light. ################################################################# if self.currentLight == None: return self.currentLight.setPosition( Point3(position[0], position[1], position[2])) return def setOrientation(self, orient): ################################################################# # setOrientation(self, orient) # Call Back function. This will be called # when user try to change the orientation of light. ################################################################# if self.currentLight == None: return self.currentLight.setOrientation(Vec3(orient[0], orient[1], orient[2])) return def setConstantAttenuation(self, value): ################################################################# # setConstantAttenuation(self, value) # Call Back function. This will be called # when user try to change the Constant Attenuation of light. ################################################################# self.currentLight.setConstantAttenuation(value) return def setLinearAttenuation(self, value): ################################################################# # setLinearAttenuation(self, value) # Call Back function. This will be called # when user try to change the Linear Attenuation of light. ################################################################# self.currentLight.setLinearAttenuation(value) return def setQuadraticAttenuation(self, value): ################################################################# # setQuadraticAttenuation(self, value) # Call Back function. This will be called # when user try to change the Quadratic Attenuation of light. ################################################################# self.currentLight.setQuadraticAttenuation(value) return def setExponent(self, value): ################################################################# # setExponent(self, value) # Call Back function. This will be called # when user try to change Exponent value of light. ################################################################# self.currentLight.setExponent(value) return
class ClsWinMain(Tk): """ Главное окно программы. """ def __init__(self, root=None): """ Создание главного окна прогарммы. :param root: :return: """ def create_self(): """ Создание самого окна. :return: """ def create_frm_btn(): """ Создание кнопок на главном окне. :return: """ # укорочение ссылки control = self.__root.control # нижний фрейм главного окна self.frm_btn = Frame(self, border=3, relief='sunken') self.frm_btn.pack(side='bottom', fil='x') # кнопка "шаг" главного окна self.btn_step = Button(self.frm_btn, text='Step >', command=control.win_main_step_cpu) self.btn_step.pack(side='left') # кнопка "Отлдака" главного окна self.btn_debug = Button(self.frm_btn, text='Debug >>', command=control.win_main_debug) self.btn_debug.pack(side='left') # кнопка "выход" главного окна self.btn_exit = Button(self.frm_btn, text='Exit [X]', command=control.exit) self.btn_exit.pack(side='right') # кнопка для показа экрана виртуального компьютера self.btn_show_screen = Button(self.frm_btn, text='PC Screen', command=control.show_screen) self.btn_show_screen.pack(side='left') # кнопка для сброса виртуального компьютера self.btn_reset = Button(self.frm_btn, text='Reset (x)', command=control.reset_pc) self.btn_reset.pack(side='left') def create_menu(): """ Создание менб для главного окна. :return: """ def create_mnu_file(): """ Создание меню "Файл". :return: """ # добавление менюхи файл self.mbt_file = Menubutton(self.frm_menu, text='File', relief='raised', border=3) self.mbt_file.pack(side='left') def create_mnu_edit(): """ Создание меню "Правка". :return: """ # добавление менюхи правка self.mbt_edit = Menubutton(self.frm_menu, text='Edit', relief='raised', border=3) self.mbt_edit.pack(side='left') def create_mnu_custom(): """ Создание меню "Настройки". :return: """ # добавление менюхи настройка self.mbt_custom = Menubutton(self.frm_menu, text='Custom', relief='raised', border=3) self.mbt_custom.pack(side='left') self.mnu_custom = Menu(self.mbt_custom) self.mnu_custom.add_command( label=self.lang['win_main_mbt_edit_bp'], accelerator='F11', command=self.__root.control.show_win_edit_bp) self.mnu_custom.add_separator() self.mnu_custom.add_command( label=self.lang['win_main_mbt_edit_disk'], accelerator='F12', command=self.__root.control.show_win_idc) self.mbt_custom.config(menu=self.mnu_custom) def create_mnu_help(): """ Создание меню "Помощь". :return: """ # добавление менюхи справка self.btm_help = Menubutton(self.frm_menu, text=self.lang[ 'win_main_mbt_help_name'], relief='raised', border=3) self.btm_help.pack(side='right') self.mnu_help = Menu(self.btm_help) self.mnu_help.add_command( label=self.lang['win_main_mbt_help_help'], accelerator='F1') self.mnu_help.add_separator() self.mnu_help.add_command( label=self.lang['win_main_mbt_help_about'], accelerator='Ctrl-F1', command=self.__root.control.about) self.btm_help.config(menu=self.mnu_help) # фрейм меню (в верхней части) self.frm_menu = Frame(self, border=3, relief='sunken') self.frm_menu.pack(side='top', fil='x') create_mnu_file() create_mnu_edit() create_mnu_custom() create_mnu_help() def create_frm_cpu(): """ Создание ырема для отображения состояния ЦП. :return: """ self.frm_cpu = ClsFrmCPU(root=self) Tk.__init__(self) self.minsize(320, 400) self.after(100, self.win_update) create_frm_btn() create_menu() create_frm_cpu() self.__root = root self.lang = root.res.lang_str.lang_dict self.btn_debug = None self.frm_cpu = None self.btn_reset = None self.mbt_edit = None self.btm_help = None self.mbt_file = None self.btn_step = None self.mnu_custom = None self.frm_menu = None self.btn_show_screen = None self.frm_button = None self.btn_exit = None self.mbt_custom = None self.frm_btn = None self.mnu_help = None create_self() def win_update(self): """ Обновление окна по таймеру. :return: """ self.__root.logic.update_monitor() self.after(100, self.win_update) def begin(self): """ В целях ухода от конфликтов имён пришлось назвать вот так ))). """ self.mainloop() def win_exit(self): """ При закрытии главного окна -- завершается всё приложение. :return: """ self.destroy()
def data(self): global textPath textPath = StringVar() global text0a text0a = StringVar() global text0b text0b = StringVar() global text2a text2a = StringVar() global text3 text3 = StringVar() global alphaVar alphaVar = IntVar() global betaVar betaVar = IntVar() global allVar allVar = IntVar() global text6a0 text6a0 = IntVar() global text6a1 text6a1 = IntVar() global text6b text6b = StringVar() global text6c1 text6c1 = StringVar() global text6c2 text6c2 = StringVar() global text6c3 text6c3 = StringVar() global text7_1 text7_1 = StringVar() global text7_2 text7_2 = StringVar() global text7_3 text7_3 = StringVar() global text7_4 text7_4 = StringVar() global text8 text8 = StringVar() Label(self.frame,text="Path ? ").grid(row=0, column=0) Entry(self.frame,textvariable=textPath).grid(row=1, column=0) Button(self.frame, text="Valider et afficher", command = affiche_recap).grid(row=1, column=1) Label(self.frame, text="Green function database information file\n (for a certain depth only for the instance) ?").grid(row=3) Entry(self.frame, textvariable=text0a).grid(row=4) Label(self.frame, text="Output directory (parentdir) ?").grid(row=5) Entry(self.frame, textvariable=text0b).grid(row=6) Label(self.frame, text="Phase name ?").grid(row=9) Entry(self.frame, textvariable=text3).grid(row=10) def afficheAlpha(): seismicPara["text"]="alpha" betaVar.set(0) allVar.set(0) def afficheBeta(): seismicPara["text"]="beta" alphaVar.set(0) allVar.set(0) def afficheAll(): seismicPara["text"]="all" alphaVar.set(0) betaVar.set(0) seismicPara = Menubutton(self.frame, text="Seismic Parameter", relief=RAISED) seismicPara.grid(row=0) seismicPara.menu = Menu(seismicPara, tearoff = 0) seismicPara["menu"] = seismicPara.menu seismicPara.menu.add_checkbutton(label="alpha", variable = alphaVar, command = afficheAlpha) seismicPara.menu.add_checkbutton(label="beta", variable = betaVar, command = afficheBeta) seismicPara.menu.add_checkbutton(label="all", variable = allVar, command = afficheAll) seismicPara.grid(row=11) def affiche0(): filterPara["text"]="Filter Off" text6a1.set(0) def affiche1(): filterPara["text"]="Filter On" text6a0.set(0) filterPara = Menubutton(self.frame, text="Butterworth filter ", relief=RAISED) filterPara.grid(row=0) filterPara.menu = Menu(filterPara, tearoff = 0) filterPara["menu"] = filterPara.menu filterPara.menu.add_checkbutton(label="Filter Off", variable = text6a0, command = affiche0) filterPara.menu.add_checkbutton(label="Filter On", variable = text6a1, command = affiche1) filterPara.grid(row=12) Label(self.frame, text="Filter name ?").grid(row=15) Entry(self.frame, textvariable=text6b).grid(row=16) Label(self.frame, text="\nIf butterworth = 0; \n just comment out those 3 parameters").grid(row=17) Label(self.frame, text="lowest frequency ?").grid(row=18,column=1) Entry(self.frame, textvariable=text6c1).grid(row=19, column=1) Label(self.frame, text="highest frequency ?").grid(row=20, column=1) Entry(self.frame, textvariable=text6c2).grid(row=21, column=1) Label(self.frame, text="number of poles ?").grid(row=22, column=1) Entry(self.frame, textvariable=text6c3).grid(row=23, column =1) Label(self.frame, text="time window t1 ?").grid(row=24) Entry(self.frame, textvariable=text7_1).grid(row=25) Label(self.frame, text="time window t2 ?").grid(row=26) Entry(self.frame, textvariable=text7_2).grid(row=27) Label(self.frame, text="time window t3 ?").grid(row=28) Entry(self.frame, textvariable=text7_3).grid(row=29) Label(self.frame, text="time window t4 ?").grid(row=30) Entry(self.frame, textvariable=text7_4).grid(row=31) Label(self.frame, text="itranslat (1 if you convert geodetic latitude to geocentric latitude) ?").grid(row=32) Entry(self.frame, textvariable=text8).grid(row=33) Button(self.frame, text="continue", command=writingFile).grid(row=34)
class tkFileSelector() : def __init__(self,master,start_dir=expanduser("~"),filetypes=[],title="Select a music file.",color_1="#000000",color_2="#00c0c0",highlight_color_items="#c9c9c9") : ''' master == root_window == Tk() use color_1 and color_2 and bg_items and fg_items and highlight_color_items for colors personalisation. filetypes must "Strictly" be a list of extension beginning with an asterix followed by a point and the extension (in lowercase) or an empty list for no filtering. filetypes=["*.mp3","*.wav"] per example. Or insert an, item '*' for all filetype in combination with defined filetypes. for borderwidth and relief settings look at the code ''' # Constrcut GUI for the file selection toplevel. self.toplevel=Toplevel(master,bg=color_1,borderwidth=1,relief="sunken") self.toplevel.resizable(width=False, height=False) self.toplevel.title(title) self.dir_selection_frame=Frame(self.toplevel,bg=color_1,borderwidth=8/2,relief="groove") # Frame container for directory fields. self.dir_name_entry=Entry(self.toplevel,justify="center",width=50,bg=color_2,fg=color_1) # This will contains the current directory relative dirname self.dir_name_separator=Button(self.toplevel,width=1,relief="sunken",bg=color_1,fg=color_2) # An separator self.dir_back_button=Button(self.toplevel,width=6,relief="raised",bg=color_2,fg=color_1,text="Back",command=self.folder_go_back) # Change directory back button. self.canvas_frame=Frame(self.toplevel,borderwidth=8,relief="groove") # Frame for the file selection window canvas and his scrollbar. self.canvas=Canvas(self.canvas_frame,height=20*9,width=18*28,bg=color_2) # File selection window. self.canvas_scrollbar=Scrollbar(self.canvas_frame,orient=HORIZONTAL, bg=color_2,troughcolor=color_1,command=self.canvas.xview) # File selection window scrollbar. self.canvas.configure(xscrollcommand=self.canvas_scrollbar.set) self.file_selection_frame=Frame(self.toplevel,bg=color_1,borderwidth=8/2,relief="groove") # Frame container for filename fields. self.file_name_entry=Entry(self.toplevel,justify="center",width=50,bg=color_2,fg=color_1) # This will contains the basename (relative) of the selected file. self.file_name_separator=Button(self.toplevel,width=1,relief="sunken",bg=color_1,fg=color_2) # An separator. self.file_filter_menubutton = Menubutton(self.file_selection_frame, text='',relief="groove",width=8,bg=color_2,fg=color_1) # Menubutton for filetype filter. self.file_filter_extension="" if filetypes : self.file_filter_menu= Menu(self.file_filter_menubutton,borderwidth=3,relief="groove") # We use a menu for the filetypes filtering. i=0 self.file_filter_var=StringVar(master=None, value=filetypes[i], name=None) # Control varaible for current filetype and initialize with the first filetype item. self.file_filter_menubutton.config(text=filetypes[i]) self.file_filter_extension=filetypes[i][1::] while i < len(filetypes) : # Creating radiobutton to change the filetype filter. self.file_filter_menu.add_radiobutton(label=filetypes[i], variable=self.file_filter_var,value=filetypes[i],background=color_2,command=self.set_filetype_filter ) i += 1 self.file_filter_menubutton.configure(menu= self.file_filter_menu) self.buttons_frame=Frame(self.toplevel,bg=color_2,borderwidth=8,relief="groove",height=50,width=18*3) # Frame container for the buttons. self.button_cancel=Button(self.buttons_frame,bg=color_2,fg=color_1,text="Quit",borderwidth=8/2,relief="groove",width=8,command=self.item_selection_quit) self.button_home=Button(self.buttons_frame,bg=color_2,fg=color_1,text="Home",borderwidth=8/2,relief="groove",width=8,command=self.item_selection_home) self.button_ok=Button(self.buttons_frame,bg=color_2,fg=color_1,text=" OK ",borderwidth=8/2,relief="groove",width=8,command=self.item_selection_ok) self.start_dir=start_dir # Start folder. self.curdir=start_dir # Current folder. self.last_dir=[] # Container for the precedent folders we visit. self.last_dir.append(start_dir) # Append start folder. self.select_filepath="" # Value to return by file selection. self.dir_name_entry.insert(0,"../"+basename(self.curdir)) if not color_2 : self.items_bg="#D9D9D9" else : self.items_bg=color_2 self.items_fg=color_1 self.highlight_color_items=highlight_color_items self.init_icons() self.ls_dir() self.update_canvas() self.dir_selection_frame.grid(row=0,column=0,sticky="WE") self.dir_name_entry.grid(row=0,column=0,in_=self.dir_selection_frame,sticky="NSEW") self.dir_name_separator.grid(row=0,column=1,in_=self.dir_selection_frame,sticky="EW") self.dir_back_button.grid(row=0,column=2,in_=self.dir_selection_frame,sticky="EW") self.canvas_frame.grid(row=1,column=0,sticky="WE") self.canvas.grid(row=0,column=0,in_=self.canvas_frame) self.canvas_scrollbar.grid(row=1,column=0,in_=self.canvas_frame,sticky="WE") self.file_selection_frame.grid(row=2,column=0,sticky="WE") self.file_name_entry.grid(row=0,column=0,in_=self.file_selection_frame,sticky="NSEW") self.file_name_separator.grid(row=0,column=1,in_=self.file_selection_frame,sticky="EW") self.file_filter_menubutton.grid(row=0,column=2,in_=self.file_selection_frame,sticky="NS") self.buttons_frame.grid(row=3,column=0,sticky="NSEW") self.button_cancel.grid(row=0,column=2,padx=32+3,pady=4,in_=self.buttons_frame) self.button_home.grid(row=0,column=4,padx=32+3,pady=4,in_=self.buttons_frame) self.button_ok.grid(row=0,column=6,padx=34+3,pady=4,in_=self.buttons_frame) self.toplevel.wait_window() def init_icons(self) : # Folder and file icons, design by me. self.image_folder=Image.open("/usr/share/ScreenLocker/Images/file_selector/folder_icon.png") self.imagetk_folder=ImageTk.PhotoImage(image=self.image_folder) self.image_file=Image.open("/usr/share/ScreenLocker/Images/file_selector/file_icon.png") self.imagetk_file=ImageTk.PhotoImage(image=self.image_file) def ls_dir(self) : ''' List an directory and split the result in folders and files containers. Finally sort the 2 containers.''' folder_content=listdir(self.curdir) self.cur_folder_entries=len(folder_content) self.cur_folder_list=[] self.cur_files_list=[] folder_content.sort() for v in folder_content : if isdir(self.curdir+"/"+v) : self.cur_folder_list.append(unicode(v,encoding='utf-8')) elif isfile(self.curdir+"/"+v) : self.cur_files_list.append(unicode(v,encoding='utf-8')) self.cur_folder_list.sort() self.cur_files_list.sort() def update_canvas(self) : ''' Generating the content from the File selection window (an canvas)''' self.clear_canvas() i=0 # global folder and file iterator. pos_x=0 # Coordinates for the rows. pos_y=0 # Coordinates in the columns. max_len=0 # Column max folder|filename length. max_len_save=0 # Saved value for filling empty canvas scrollregion. while i < len(self.cur_folder_list) : # Generating the folder items of the current folder exec(u"folder_icon_{0}=Label(self.canvas,text='{1}',image=self.imagetk_folder,relief='flat',width=17,height=17,bg=self.items_bg)".format(str(i),self.cur_folder_list[i].replace("'","\\'"))) exec(u"folder_name_{0}=Label(self.canvas,text='{1}',relief='flat',width={2},font='Monospace 9 bold',justify='left',bg=self.items_bg,fg=self.items_fg)".format(str(i),self.cur_folder_list[i].replace("'","\\'"),int(len(" "+self.cur_folder_list[i])))) if int(len(" "+self.cur_folder_list[i])) > max_len : # Update longest folder name in this column. max_len=int(len(" "+self.cur_folder_list[i])) # Storing the value for max length of the longest folder name in this column. max_len_save=max_len # Value to save for filling if the generating content take minus place as the canvas scrollregion. exec("folder_icon_{0}.bind('<Double-1>',self.select_folder)".format(str(i))) exec("folder_name_{0}.bind('<Double-1>',self.select_folder)".format(str(i))) exec("folder_name_{0}.bind('<Enter>',self.highlight_item_enter)".format(str(i))) exec("folder_name_{0}.bind('<Leave>',self.highlight_item_leave)".format(str(i))) exec("folder_icon_{0}.pack(side='left',fill=BOTH)".format(str(i))) exec("folder_name_{0}.pack(side='right',fill=BOTH)".format(str(i))) exec("self.canvas.create_window(({1},{2}),anchor='nw',window=folder_icon_{0})".format(str(i),pos_x,pos_y)) exec("self.canvas.create_window(({1}+17+1,{2}),anchor='nw',window=folder_name_{0})".format(str(i),pos_x,pos_y)) pos_y += 20 # column increment 17 height of an items + 3 pixels padding. if ( i % 9 == 0) and not i == 0 : # An column can contains 9 items and we change column. pos_y=0 # Column position updating. pos_x += 17 + (max_len*9) # Update the x coordinates according the maximal length of foldername in this column ( (9 pixels == font size) (17 pixels for the folder item icon) ) . max_len=0 i += 1 # Go to the next item. ii=0 # Files iterator. while ii < len(self.cur_files_list) : # Generating the files items of the current folder. if (self.file_filter_extension and self.cur_files_list[ii].lower().endswith(self.file_filter_extension)) or not self.file_filter_extension : # applying filter of no filetype filering. exec(u"file_icon_{0}=Label(self.canvas,text='{1}',image=self.imagetk_file,relief='flat',width=17,height=17,bg=self.items_bg)".format(str(i),self.cur_files_list[ii].replace("'","\\'"))) exec(u"file_name_{0}=Label(self.canvas,text='{1}',relief='flat',width={2},font='Monospace 9 normal',justify='left',bg=self.items_bg,fg=self.items_fg)".format(str(i),self.cur_files_list[ii].replace("'","\\'"),int(len(" "+self.cur_files_list[ii])))) if int(len(" "+self.cur_files_list[ii])) > max_len : # Update longest filename in this column. max_len=int(len(" "+self.cur_files_list[ii])) # Storing the value for max length of the longest filename in this column. max_len_save=max_len # Value to save for filling if the generating content take minus place as the canvas scrollregion. exec("file_icon_{0}.bind('<Double-1>',self.select_file)".format(str(i))) exec("file_name_{0}.bind('<Double-1>',self.select_file)".format(str(i))) exec("file_name_{0}.bind('<Enter>',self.highlight_item_enter)".format(str(i))) exec("file_name_{0}.bind('<Leave>',self.highlight_item_leave)".format(str(i))) exec("file_icon_{0}.pack(side='left',fill=BOTH)".format(str(i))) exec("file_name_{0}.pack(side='right',fill=BOTH)".format(str(i))) exec("self.canvas.create_window(({1},{2}),anchor='nw',window=file_icon_{0})".format(str(i),pos_x,pos_y)) exec("self.canvas.create_window(({1}+17+1,{2}),anchor='nw',window=file_name_{0})".format(str(i),pos_x,pos_y)) pos_y += 20 # column increment 17 height of an items + 3 pixels padding. if ( i % 9 == 0) and not i == 0 : # An column can contains 9 items and we change column. # Note: we check the common file & folder iterator. pos_y=0 # Column position updating. pos_x += 17 + (max_len*9) # Update the x coordinates according the maximal length of filename in this column ( (9 pixels == font size) (17 pixels for the file item icon) ). max_len=0 i += 1 ii += 1 if not pos_x+(max_len_save*9)+17 < 18*28 : # items collection greater than the canvas scrollregion. self.canvas.config(scrollregion=(0,0,pos_x+(max_len_save*9)+17,0)) else : # items collection littler than the canvas scrollregion. self.canvas.config(scrollregion=(0,0,18*28,0)) def clear_canvas(self) : for child in self.canvas.children.values() : child.destroy() def highlight_item_enter(self,event) : event.widget.config(bg=self.highlight_color_items) def highlight_item_leave(self,event) : event.widget.config(bg=self.items_bg) def select_folder(self,event) : if isdir(self.curdir+"/"+event.widget.cget("text").lstrip()) : # event.widget.cget("text") return the selected folder. sea the update_canvas() method. self.select_filepath="" self.file_name_entry.delete(0,END) if self.curdir.startswith('//') : # Bugfix. self.curdir=self.curdir[1::] self.last_dir.append(self.curdir) else : self.last_dir.append(self.curdir) for v in self.last_dir : # Bigfix if self.last_dir.count(v) > 1 : self.last_dir.remove(v) try : # in case of access right this will fail immediatelly listdir(self.curdir+"/"+event.widget.cget("text")) self.curdir=self.curdir+"/"+event.widget.cget("text") self.dir_name_entry.delete(0,END) self.dir_name_entry.insert(0,"../"+event.widget.cget("text")) self.ls_dir() self.update_canvas() except : pass def select_file(self,event) : if isfile(self.curdir+"/"+event.widget.cget("text")) : # Set the value to return and fill the file selection field. self.select_filepath=self.curdir+"/"+event.widget.cget("text") self.file_name_entry.delete(0,END) self.file_name_entry.insert(0,event.widget.cget("text")) def folder_go_back(self) : if len(self.last_dir) > 1 : self.curdir=self.last_dir.pop(-1) # pop the last value from the visited folder folders else : # In case we have yet only 1 folder in the visited folder container. if self.last_dir[0].rfind("/") : # The value of the container is not the root folder ( / ) but not the /home/username folder who can be only visited folder. self.last_dir[0]=self.last_dir[0][0:self.last_dir[0].rfind("/")] self.curdir=self.last_dir[0] elif self.last_dir[0].rfind("/") == 0 : # The value of the container is the root folder. self.last_dir[0]="/" self.curdir=self.last_dir[0] else : # The value is the /home/username directory self.curdir=self.last_dir[0] self.file_name_entry.delete(0,END) self.select_filepath="" self.dir_name_entry.delete(0,END) self.dir_name_entry.insert(0,"../"+basename(self.curdir)) self.ls_dir() self.update_canvas() def set_filetype_filter(self) : '''Change filetype filter.''' self.file_filter_menubutton.config(text=self.file_filter_var.get()) self.file_filter_extension=self.file_filter_var.get()[1::] # Contains the selected filetype ( in form '.'+filetype ). self.file_name_entry.delete(0,END) self.select_filepath="" self.ls_dir() self.update_canvas() def item_selection_ok(self) : '''Return the selected filepath or empty string and destroy File_selector instance''' if self.select_filepath : self.toplevel.destroy() return True def item_selection_quit(self) : '''destroy File_selector instance''' self.toplevel.destroy() return False def item_selection_home(self) : '''Change current directory to the /home/username folder''' self.curdir=expanduser("~") self.select_filepath="" self.file_name_entry.delete(0,END) self.last_dir=[] self.last_dir.append(expanduser("~")) self.dir_name_entry.delete(0,END) self.dir_name_entry.insert(0,"../"+basename(self.curdir)) self.ls_dir() self.update_canvas()
def __init__(self, parent=None): Frame.__init__(self, bg='green', borderwidth=2) file_button = Menubutton(self, text="File") file_button.pack(side="left") file_menu = Menu(file_button) file_button.configure(menu=file_menu) file_menu.add_command(label='Save', underline=0, command=parent.file_save) # file_menu.add_command(label='Quit', underline=0, # command=parent.destroy) file_menu.add_command(label='Quit', underline=0, command=parent.file_quit) edit_button = Menubutton(self, text="Edit") edit_button.pack(side="left") edit_menu = Menu(edit_button) edit_button.configure(menu=edit_menu) edit_menu.add_command(label='Hide', underline=0, command=parent.delete_circle) edit_menu.add_command(label='Show', underline=0, command=parent.create_circle) help_button = Menubutton(self, text="Help") help_button.pack(side="right") help_menu = Menu(help_button) help_button.configure(menu=help_menu) help_menu.add_command(label='About Us', underline=0, command=parent.help_us) help_menu.add_command(label='About TkInter', underline=0, command=parent.help_tkinter)