class ScrolledList(Frame): def __init__(self, master, d_list, a_function): Frame.__init__(self, master) scrl_bar = Scrollbar(self) self.listbox = Listbox(self) scrl_bar.config(command=self.listbox.yview) scrl_bar.pack(side=RIGHT, fill=Y) self.listbox.config(yscrollcommand=scrl_bar.set) self.listbox.pack(side=LEFT, expand=YES, fill=BOTH) #load the listbox idx = 0 for item in d_list: fparts = item.split('.') # DEBUG print fparts if fparts[-1] == 'csv': self.listbox.insert(idx, item) idx += 1 # link double click to the processList self.listbox.bind('<Double-1>', self.processList) # attach a function passed form the master # not this si done as passd function so it could be anything self.passed_function = a_function # get the index of the double clicked itenm and pass the item to # the passed function def processList(self, event): index = self.listbox.curselection() label = self.listbox.get(index) self.passed_function((index, label))
def set_listTop(Listbox,sMap): try: index=Listbox.curselection()[0] #Check if there is an existing entry in the listbox except IndexError: index=END for i,listbox_entry in enumerate(Listbox.get(0, END)): if listbox_entry == sMap: tkMessageBox.showinfo("Entry", "There is already an entry for this transition.") return Listbox.insert(index, sMap)
class SelectionDialog(_TkDialog): def __init__(self, message, values): _TkDialog.__init__(self, message, values) def _create_selector(self, parent, values): self._listbox = Listbox(parent) for item in values: self._listbox.insert(END, item) return self._listbox def _validate_value(self): return bool(self._listbox.curselection()) def _get_value(self): return self._listbox.get(self._listbox.curselection())
class MultipleSelectionDialog(_TkDialog): def __init__(self, message, values): _TkDialog.__init__(self, message, values) def _create_selector(self, parent, values): self._listbox = Listbox(parent, selectmode='multiple') for item in values: self._listbox.insert(END, item) self._listbox.config(width=0) return self._listbox def _get_value(self): selected_values = [self._listbox.get(i) for i in self._listbox.curselection()] return selected_values
class MultipleSelectionDialog(_TkDialog): def __init__(self, message, values): _TkDialog.__init__(self, message, values) def _create_selector(self, parent, values): self._listbox = Listbox(parent, selectmode='multiple') for item in values: self._listbox.insert(END, item) self._listbox.config(width=0) return self._listbox def _get_value(self): selected_values = [ self._listbox.get(i) for i in self._listbox.curselection() ] return selected_values
class ScrolledList(Frame): def __init__(self, master,a_function): Frame.__init__(self,master) scrl_bar = Scrollbar(self) self.listbox = Listbox(self) scrl_bar.config(command=self.listbox.yview) scrl_bar.pack(side=RIGHT, fill=Y) self.listbox.config(yscrollcommand=scrl_bar.set) self.listbox.pack(side=LEFT, expand=YES, fill=BOTH) # link double click to the processList self.listbox.bind('<Double-1>', self.processList) # attach a function passed form the master # not this si done as passd function so it could be anything self.passed_function = a_function # get the index of the double clicked itenm and pass the item to # the passed function def processList(self, event): index = self.listbox.curselection() label = self.listbox.get(index) self.passed_function((index,label)) def load_data(self,d_list): #load the listbox idx = 0 for item in d_list: fparts = item.split('.') # DEBUG print fparts if fparts[-1] == 'csv': # only display thoes files that have not been processed if not(item.startswith("done-")): self.listbox.insert(idx, item) idx += 1 def remove_item(self,idx): self.listbox.delete(idx)
class SelectionDialog(_AbstractTkDialog): _left_button = 'OK' _right_button = 'Cancel' def __init__(self, message, values): self._message = message self._values = values _AbstractTkDialog.__init__(self, "Select one option") def create_components(self, parent): Label(parent, text=self._message).pack(fill=BOTH) self._listbox = Listbox(parent) self._listbox.pack(fill=BOTH) for item in self._values: self._listbox.insert(END, item) return self._listbox def validate(self): return bool(self._listbox.curselection()) def apply(self): self.result = self._listbox.get(self._listbox.curselection())
class GUIListbox: def __init__(self, parent, items=None, **kwargs): self.listbox = Listbox(parent, **kwargs) if items: self.setItems(items) def setItems(self, items): self.listbox.delete(0, END) for item in items: self.listbox.insert(END, item) def getSelected(self): return self.listbox.get(ACTIVE) def bindDoubleClick(self, func): self.listbox.bind("<Double-Button-1>", func) def grid(self, **kwargs): self.listbox.grid(kwargs) def pack(self, **kwargs): self.listbox.pack(kwargs)
class Downloader(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Book downloader") self.style = Style() self.style.theme_use("default") framesearch = Frame(self) framesearch.pack(fill=BOTH) search_label = Label(framesearch, text="Filter books:", padx=5, pady=5, width=15) search_label.pack(side=LEFT) self.search_entry = Entry(framesearch) self.search_entry.pack(side=RIGHT, fill=X) self.search_entry.bind("<Return>", self.searchHandler) #self.search_entry.bind("<Key>", self.searchHandler) framelist = Frame(self, relief=RAISED, borderwidth=1) framelist.pack(fill=BOTH, expand=True) self.lb = Listbox(framelist, height=30) scrollbar = Scrollbar(framelist) scrollbar.pack(side=RIGHT, fill=Y) self.lb.config(yscrollcommand=scrollbar.set) scrollbar.config(command=self.lb.yview) self.loadLibrary() for b in self.book_list: self.lb.insert(END, b[0]) self.lb.pack(fill=BOTH) self.pack(fill=BOTH, expand=True) DownButton = Button(self, text="Download", command=self.downloadAction) DownButton.pack(side=RIGHT) def downloadAction(self): bookUrls = [] selected = self.lb.curselection() if len(selected)<1: tkMessageBox.showerror("Select books to Download", "You have to select the books you want to download") return for b in selected: item = self.lb.get(b) for b2 in self.book_list: if item==b2[0]: bookUrls.append(b2[1]) self.lb.delete(b) break for burl in bookUrls: print("Starting thread for %s" % burl) retriver = Retriver() retriver.setUrl(burl) retriver.start() def searchHandler(self, event): filterStr = self.search_entry.get() self.lb.delete(0, END) if filterStr=="": for b in self.book_list: self.lb.insert(END, b[0]) else: for b in self.book_list: if b[0].lower().find(filterStr.lower())>-1: self.lb.insert(END, b[0]) def getPageHTML(self, page_num=1): pageurl = "http://www.allitebooks.com/page/" + str(page_num) fh = urllib.urlopen(pageurl) if fh.getcode()==200: txt= fh.read() fh.close() return txt else: return '' def loadBooksInPage(self, page_num=1): html = self.getPageHTML(page_num) if len(html)==0: return False soup = BeautifulSoup(html, "lxml") for h2 in soup.find_all('h2','entry-title'): alink = h2.a if alink != None: aurl = alink['href'] atxt = alink.text self.book_list.append ( [atxt, aurl] ) print("%i: %s" % (self.books, atxt)) self.books += 1 return True def loadLibrary(self): self.book_list = [] self.books = 0 print("Getting the list of books") p = 1 while(self.loadBooksInPage(p) ): p=p+1 self.book_list.sort() if len(self.book_list)<1: sys.exit("Couldn't find books online, please check your internet access")
class GraphAnalyzer(Frame): def __init__(self, root): Frame.__init__(self, root) self.__root = root self.__data_manager = DataManager() self.__check_button_type = namedtuple('CheckButtonType', 'widget var') self.__natures = [ "Single Carriageway", "Traffic Island Link", "Dual Carriageway", "Roundabout", "Traffic Island Link At Junction", "Slip Road" ] self.__roads = [ "M3","M40","M4","A1(M)","M11","M23","M20","M25","M1","HIGH STREET", "LONDON ROAD","HIGH ROAD","UXBRIDGE ROAD","STATION ROAD", "BRIGHTON ROAD","GREEN LANES","FINCHLEY ROAD","HARROW ROAD", "NORTH CIRCULAR ROAD","KINGSTON ROAD","PORTSMOUTH ROAD","HERTFORD ROAD", "STAINES ROAD","CROYDON ROAD","MAIN ROAD","CHURCH ROAD","PARK ROAD" ] self.__motorways = ["M3","M40","M4","A1(M)","M11","M23","M20","M25","M1"] self.__init_grid() self.__draw_grid() def __init_grid(self): # Road list self.__roads_list_box = Listbox(self.__root, selectmode=MULTIPLE, height=27, exportselection=0) for road in self.__roads: self.__roads_list_box.insert('end', road) # Nature list self.__natures_list_box = Listbox(self.__root, selectmode=MULTIPLE, height=6, width=22, exportselection=0) for nature in self.__natures: self.__natures_list_box.insert('end', nature) # Start with all natures selected self.__natures_list_box.select_set(0, END)\ # Days list self.__days_list_box = Listbox(self.__root, selectmode=MULTIPLE, height=8, width=22, exportselection=0) for day in ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']: self.__days_list_box.insert('end', day) # Hours list self.__hours_list_box = Listbox(self.__root, selectmode=MULTIPLE, height=24, width=7, exportselection=0) for hour in range(24): self.__hours_list_box.insert('end', hour) # Check button draw overall self.__draw_overall_var = IntVar() self.__draw_overall_check_box = \ Checkbutton(self.__root, text = "Draw Overall Curve?", variable = self.__draw_overall_var, onvalue = 1, offvalue = 0, height=2, width = 20) # Check button draw nature self.__draw_nature_var = IntVar() self.__draw_nature_check_box = \ Checkbutton(self.__root, text = "Draw Curve Per Nature?", variable = self.__draw_nature_var, onvalue = 1, offvalue = 0, height=2, width = 20) # Check button show data self.__show_data_var = IntVar() self.__show_data_var.set(1) self.__show_data_check_box = \ Checkbutton(self.__root, text = "Show data?", variable = self.__show_data_var, onvalue = 1, offvalue = 0, height=2, width = 20) # Go button self.__go_button = Button(self.__root, text='GO', command = lambda: self.__generate_graph()) # Errors text box self.__error_text_box = Text(self.__root, height=28, width=18, fg="red") self.__error_text_box.tag_config('justified', justify=CENTER) def __draw_grid(self): # Roads label and list box Label(self.__root, text="Roads", justify=CENTER).grid(row=0, column=0) self.__roads_list_box.grid(row=1, column=0, rowspan=27) # Natures label and list box Label(self.__root, text="Natures", justify=CENTER).grid(row=0, column=1) self.__natures_list_box.grid(row=1, column=1, rowspan=6) # Days label and list box Label(self.__root, text="Days", justify=CENTER).grid(row=7, column=1) self.__days_list_box.grid(row=8, column=1, rowspan=8) # Hours label and list box Label(self.__root, text="Hours", justify=CENTER).grid(row=0, column=3) self.__hours_list_box.grid(row=1, column=3, rowspan=24) # Check boxes Label(self.__root, text="Drawing Options", justify=CENTER).grid(row=0, column=4) self.__draw_overall_check_box.grid(row=1, column=4, rowspan=2) self.__draw_nature_check_box.grid(row=3, column=4, rowspan=2) self.__show_data_check_box.grid(row=5, column=4, rowspan=2) # Go button self.__go_button.grid(row=10, column=4) # Error Column Label(self.__root, text="Error Report", height=1, width=18, justify=CENTER).grid(row=0, column=5) self.__error_text_box.grid(row=1, column=5, rowspan=28) def __generate_graph(self): # Get parameters roads = tuple(self.__roads_list_box.get(road_index) for road_index in self.__roads_list_box.curselection()) roads = [ ("classification" if road in self.__motorways else "street", road) for road in roads] natures = tuple(self.__natures_list_box.get(nature_index) for nature_index in self.__natures_list_box.curselection()) days = self.__days_list_box.curselection() hours = self.__hours_list_box.curselection() errors = self.__error_check(roads, natures, days, hours) if len(errors): self.__error_text_box.delete("1.0",END) for e in errors: self.__error_text_box.insert(END, e + '\n', 'justified') else: data = self.__data_manager.get_data("traffic", "rainfall", roads, natures, hours, days) self.__plot_data(data) def __error_check(self, roads, natures, hours, days): errors = [] if not len(roads): errors.append("No roads selected") if not len(natures): errors.append("No natures selected") if not len(hours): errors.append("No hours selected") if not len(days): errors.append("No days selected") if not (self.__show_data_var.get() or self.__draw_nature_var.get() or self.__draw_overall_var.get()): errors.append("Nothing to draw") return errors def __plot_data(self, data): max_depth = data.depth.max() max_speed = data.speed.max() dfs_to_plot = [] if self.__show_data_var.get(): dfs_to_plot.append(data) if self.__draw_overall_var.get(): dfs_to_plot.append(self.__get_best_fit_curve(data, max_depth, max_speed, "Best fit curve")) if self.__draw_nature_var.get(): for nature, nature_df in data.groupby(['nature']): dfs_to_plot.append(self.__get_best_fit_curve(nature_df, max_depth, max_speed, nature)) data = pd.concat(dfs_to_plot, ignore_index=True) fg = sns.FacetGrid(data=data, hue='nature', aspect=1.9, legend_out=False, size=8) fg.map(plt.scatter, 'depth', 'speed', s=20).add_legend(None, "Legend") axes = fg.axes ylim = 120 if max_speed > 200 else max_speed xlim = 1.0 if max_depth < 1.0 else 2.0 axes[0,0].set_ylim(0,ylim) axes[0,0].set_xlim(0,xlim) sns.plt.show() def __get_best_fit_curve(self, data, max_depth, max_speed, nature_str): try: popt, pcov = curve_fit(self.curve_func, data.depth, data.speed) except RuntimeError: return pd.DataFrame({'depth':[], 'speed':[], 'nature':[], 'identifier':[]}) a = popt[0] b = popt[1] c = popt[2] depths = list(np.arange(0, max_depth, max_depth/10000.0)) speeds = map(lambda x: self.curve_func(x, a, b, c), depths) if max(speeds) > max_speed: speeds = [s for s in speeds if s <= max_speed] depths = depths[0:len(speeds)] natures = [nature_str] * len(depths) identifiers = [''] * len(depths) return pd.DataFrame({'depth':depths, 'speed':speeds, 'nature':natures, 'identifier':identifiers}) def curve_func(self, x, a, b, c): return a * np.exp(-b * x) + c
class SelectPaths(MyFrame): def __init__(self, topframe=None): MyFrame.__init__(self, topframe=topframe) style = Style() style.theme_use('clam') self.patient_foler_path = "" self.patients = [] self.set_title('Brain segmentation GUI') self.add_ui_components() def add_ui_components(self): # Creating the frames. self.sub_frame1 = Frame(self) self.sub_frame1.grid(column=0, row=0) sub_frame2 = Frame(self) sub_frame2.grid(column=0, row=1) sub_frame3 = Frame(self) sub_frame3.grid(column=0, row=2) sub_frame21 = Frame(sub_frame2) sub_frame21.grid(column=0, row=0) sub_frame22 = Frame(sub_frame2) sub_frame22.grid(padx=20, column=1, row=0) sub_frame221 = Frame(sub_frame22) sub_frame221.grid(row=1, column=0) # Creating the top-menu buttons. self.visualise_button = Button(self.sub_frame1, text="Visualise", command=self.start_visualisation) self.visualise_button.grid(row=0, column=1) self.help_button = Button(self.sub_frame1, text="Help", command=self.open_help) self.help_button.grid(row=0, column=2) # Creating the select modality path. self.modality_label = Label(sub_frame21, text="Path to patient folders", relief=FLAT) self.modality_label.grid(row=1, column=1) self.modality_path_entry = Entry(sub_frame21) self.modality_path_entry.grid(row=2, column=1) #self.modality_path_entry.set(self.patient_folder_path) self.modality_path_button = Button( sub_frame21, text="Choose", command=self.choose_directory_and_import) self.modality_path_button.grid(row=2, column=2) # Creating the patients listbox. self.label_patients = Label(sub_frame22, text="Patients") self.label_patients.grid(row=0, column=0) self.listbox_patients = Listbox(sub_frame221, selectmode='multiple', width=50, height=10) self.listbox_patients.pack(side=LEFT, fill=Y) #self.listbox_patients.grid(row=1, column=0) self.listbox_patients.bind("<Button-1>", self.listbox_changed) self.scrollbar = Scrollbar(sub_frame221) self.scrollbar.pack(side=RIGHT, fill=Y) # attach listbox to scrollbar self.listbox_patients.config(yscrollcommand=self.scrollbar.set) self.scrollbar.config(command=self.listbox_patients.yview) # Creating the status console. self.status_text = Text(sub_frame3, height=5) self.status_text.grid(column=0, row=0) self.status_text.tag_configure('title', justify='center', font="Arial 10 bold") self.status_text.tag_configure('entry', justify='left', font="Arial 9") self.status_text.insert(END, 'Status Console', 'title') self.status_text_entry_number = 1 self.status_text.configure(state='disabled') # ***** EVENTS - START******************************** def start_visualisation(self): """ Launch visualisation module. Linked to self.visualise_button (Button). """ patient_path = os.path.join(self.patient_folder_path, 'processed_' + self.patients[0]) segmentation_path = os.path.join( patient_path, SEGM_PREFIX + '_' + self.patients[0] + '.nii.gz') supervoxel_path = os.path.join( patient_path, SUPERVOXEL_PREFIX + '_' + self.patients[0] + '.nii.gz') # check if the supervoxels and the segmentation exist if not os.path.exists(supervoxel_path): supervoxel_path = None if not os.path.exists(segmentation_path): segmentation_path = None mod_paths = [] for mod in MODALITY_PREFIXES: mod_paths.append(\ os.path.join(patient_path, mod+'_'+self.patients[0]+'.nii.gz')) vis = vv.VisualVolumes(image_paths=mod_paths, segm_path=segmentation_path, supervoxel_id_path=supervoxel_path, topframe=self.master) vis.tkraise() def listbox_changed(self, event): """ Add a patient upon selection in the listbox. Linked to self.listbox_patients (Listbox). """ indices = list(self.listbox_patients.curselection()) selected_idx = self.listbox_patients.nearest(event.y) if selected_idx == -1: return # remove or add a patient index if selected_idx not in indices: indices.append(selected_idx) else: indices.remove(selected_idx) # set self.patients based on the new patient indices and enable visualisation if only one is selected. self.patients = [] for idx in indices: self.patients.append(self.listbox_patients.get(idx).split(' ')[0]) if len(self.patients) == 1: self.visualise_button['state'] = 'enabled' else: self.visualise_button['state'] = 'disabled' def choose_directory_and_import(self): """ Allow the user to select an import path. Linked to self.modality_path_button (Button), and sets self.modality_path_entry (Entry). """ initialdir = DATA_PATH msg = 'Select directory containing patients' path = askdirectory(title=msg, initialdir=initialdir) # update the text box. self.modality_path_entry.delete(0, END) self.modality_path_entry.insert(0, str(path)) # Adding the modality paths after the folder is selected. self.patient_folder_path = self.modality_path_entry.get() if os.path.exists(self.patient_folder_path): patients_validation = os.listdir(self.patient_folder_path) # Checking if the patient has the right modalities and importing the patient. for i, patient in enumerate(patients_validation): # Checking if the patient was already processed. if patient.startswith('processed_') or os.path.exists( os.path.join(self.patient_folder_path, 'processed_' + patient)): print("The files of the patient " + patient + " are already copied") continue # If everything is fine, then it continues to makign folders and copying files # Copying the files into the new folder. valid = self._convert_and_copy_files(patient) if not valid: patients_validation[i] = None # We make a list of patients with only ids for the listbox. valid_patients = [p for p in patients_validation if p is not None] self.list_existing_patients(valid_patients) def _convert_and_copy_files(self, patient): """ Check if all valid files exist for this patient and return True if so. """ # Getting the list of modalities for every patient. patient_path = os.path.join(self.patient_folder_path, patient) modalities = os.listdir(patient_path) # Look for paths valid_paths = {} prefices = [SEGM_PREFIX, SUPERVOXEL_PREFIX] + MODALITY_PREFIXES for prefix in prefices: candidates = [modality \ for modality in modalities \ if modality.startswith(prefix+'.')] if len(candidates) != 1: err = '%s file not identified. Look for ambiguities in %s.' \ % (prefix, patient_path) print(err) return False modality = candidates[0] if not any([ modality.endswith(ext) for ext in ['.mha', '.nii', '.nii.gz'] ]): err = "Image format not recognized: %s. In %s" \ % (modality, patient_path) print(err) return False valid_paths[prefix] = modality # Creating a processed patient folder. os.mkdir(os.path.join(self.patient_folder_path, 'processed_' + patient)) for prefix, basename in valid_paths.iteritems(): shutil.copyfile( os.path.join(self.patient_folder_path, patient, basename), os.path.join(self.patient_folder_path, 'processed_' + patient, prefix + '_' + patient + '.nii.gz')) return True def open_help(self): self.help_window = help_window.HelpWindow() self.help_window.tkraise() # ***** EVENTS - END*************************** def list_existing_patients(self, patients=None): print("Importing existing patients") # We make a list of patients with only ids for the listbox. if patients is None: patients = os.listdir(self.patient_folder_path) self.patients = [] for patient in patients: if not patient.startswith('processed_'): self.patients.append(patient) self.patients.sort() self.populate_patient_listbox(self.patients) if self.listbox_patients.size() > 0: self.listbox_patients.selection_set(0) self.status_text.configure(state='normal') self.status_text.insert( END, '\n' + str(self.status_text_entry_number) + '- Patients are imported.', 'entry') self.status_text_entry_number += 1 self.status_text.insert( END, '\n' + str(self.status_text_entry_number) + '- Please select a patient to proceed', 'entry') self.status_text_entry_number += 1 self.status_text.configure(state='disabled') def populate_patient_listbox(self, patients): self.listbox_patients.delete(0, END) for patient in patients: patient_path = os.path.join(self.patient_folder_path, 'processed_' + patient) #check if a given patient has a label if os.path.exists( os.path.join( patient_path, 'corrected_' + SEGM_PREFIX + '_' + patient + '.nii.gz')): patient = patient + ' - segmentation corrected' self.listbox_patients.insert(END, patient)
class Combobox_Autocomplete(Entry, object): def __init__(self, master, list_of_items=None, autocomplete_function=None, listbox_width=None, listbox_height=7, ignorecase_match=False, startswith_match=True, vscrollbar=True, hscrollbar=True, **kwargs): if hasattr(self, "autocomplete_function"): if autocomplete_function is not None: raise ValueError("Combobox_Autocomplete subclass has 'autocomplete_function' implemented") else: if autocomplete_function is not None: self.autocomplete_function = autocomplete_function else: if list_of_items is None: raise ValueError("If not guiven complete function, list_of_items can't be 'None'") if ignorecase_match: if startswith_match: def matches_function(entry_data, item): return item.startswith(entry_data) else: def matches_function(entry_data, item): return item in entry_data self.autocomplete_function = lambda entry_data: [item for item in self.list_of_items if matches_function(entry_data, item)] else: if startswith_match: def matches_function(escaped_entry_data, item): if re.match(escaped_entry_data, item, re.IGNORECASE): return True else: return False else: def matches_function(escaped_entry_data, item): if re.search(escaped_entry_data, item, re.IGNORECASE): return True else: return False def autocomplete_function(entry_data): escaped_entry_data = re.escape(entry_data) return [item for item in self.list_of_items if matches_function(escaped_entry_data, item)] self.autocomplete_function = autocomplete_function self._listbox_height = int(listbox_height) self._listbox_width = listbox_width self.list_of_items = list_of_items self._use_vscrollbar = vscrollbar self._use_hscrollbar = hscrollbar kwargs.setdefault("background", "white") if "textvariable" in kwargs: self._entry_var = kwargs["textvariable"] else: self._entry_var = kwargs["textvariable"] = StringVar() Entry.__init__(self, master, **kwargs) self._trace_id = self._entry_var.trace('w', self._on_change_entry_var) self._listbox = None self.bind("<Tab>", self._on_tab) self.bind("<Up>", self._previous) self.bind("<Down>", self._next) self.bind('<Control-n>', self._next) self.bind('<Control-p>', self._previous) self.bind("<Return>", self._update_entry_from_listbox) self.bind("<Escape>", lambda event: self.unpost_listbox()) #self.bind("<FocusOut>", lambda event: self.unpost_listbox()) def _on_tab(self, event): #self.post_listbox() self.unpost_listbox() #frmbill.cbouom.focus() #self._update_entry_from_listbox() #self.unpost_listbox() # if self._listbox is not None: # self._listbox.master.destroy() # self._listbox = None return "break" def _on_change_entry_var(self, name, index, mode): entry_data = self._entry_var.get() if entry_data == '': #print('test111') self.unpost_listbox() self.focus() else: if len(entry_data) < 3: return True values = finditem(entry_data) #kk #self.autocomplete_function(entry_data) if values: if self._listbox is None: self._build_listbox(values) else: self._listbox.delete(0, END) height = min(self._listbox_height, len(values)) self._listbox.configure(height=height) for item in values: self._listbox.insert(END, item) else: self.unpost_listbox() self.focus() def _build_listbox(self, values): listbox_frame = Frame() self._listbox = Listbox(listbox_frame, background="white", selectmode=SINGLE, activestyle="none", exportselection=False) self._listbox.grid(row=0, column=0,sticky = N+E+W+S) self._listbox.bind("<ButtonRelease-1>", self._update_entry_from_listbox) self._listbox.bind("<Return>", self._update_entry_from_listbox) self._listbox.bind("<Escape>", lambda event: self.unpost_listbox()) self._listbox.bind('<Control-n>', self._next) self._listbox.bind('<Control-p>', self._previous) if self._use_vscrollbar: vbar = Scrollbar(listbox_frame, orient=VERTICAL, command= self._listbox.yview) vbar.grid(row=0, column=1, sticky=N+S) self._listbox.configure(yscrollcommand= lambda f, l: autoscroll(vbar, f, l)) if self._use_hscrollbar: hbar = Scrollbar(listbox_frame, orient=HORIZONTAL, command= self._listbox.xview) hbar.grid(row=1, column=0, sticky=E+W) self._listbox.configure(xscrollcommand= lambda f, l: autoscroll(hbar, f, l)) listbox_frame.grid_columnconfigure(0, weight= 1) listbox_frame.grid_rowconfigure(0, weight= 1) x = -self.cget("borderwidth") - self.cget("highlightthickness") y = self.winfo_height()-self.cget("borderwidth") - self.cget("highlightthickness") if self._listbox_width: width = self._listbox_width else: width=self.winfo_width() listbox_frame.place(in_=self, x=x, y=y, width=width) height = min(self._listbox_height, len(values)) self._listbox.configure(height=height) for item in values: self._listbox.insert(END, item) def post_listbox(self): if self._listbox is not None: return entry_data = self._entry_var.get() if entry_data == '': return values = self.autocomplete_function(entry_data) if values: self._build_listbox(values) def unpost_listbox(self): if self._listbox is not None: self._listbox.master.destroy() self._listbox = None def get_value(self): return self._entry_var.get() def set_value(self, text, close_dialog=False): self._set_var(text) if close_dialog: self.unpost_listbox() self.icursor(END) self.xview_moveto(1.0) def _set_var(self, text): self._entry_var.trace_vdelete("w", self._trace_id) self._entry_var.set(text) self._trace_id = self._entry_var.trace('w', self._on_change_entry_var) if len(text) > 0: find_price(text) #kk def _update_entry_from_listbox(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if current_selection: text = self._listbox.get(current_selection) self._set_var(text) self._listbox.master.destroy() self._listbox = None self.focus() self.icursor(END) self.xview_moveto(1.0) return "break" def _previous(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if len(current_selection)==0: self._listbox.selection_set(0) self._listbox.activate(0) else: index = int(current_selection[0]) self._listbox.selection_clear(index) if index == 0: index = END else: index -= 1 self._listbox.see(index) self._listbox.selection_set(first=index) self._listbox.activate(index) return "break" def _next(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if len(current_selection)==0: self._listbox.selection_set(0) self._listbox.activate(0) else: index = int(current_selection[0]) self._listbox.selection_clear(index) if index == self._listbox.size() - 1: index = 0 else: index +=1 self._listbox.see(index) self._listbox.selection_set(index) self._listbox.activate(index) return "break" # if __name__ == '__main__': # try: # from Tkinter import Tk # except ImportError: # from tkinter import Tk # list_of_items = ["Cordell Cannata", "Lacey Naples", "Zachery Manigault", "Regan Brunt", "Mario Hilgefort", "Austin Phong", "Moises Saum", "Willy Neill", "Rosendo Sokoloff", "Salley Christenberry", "Toby Schneller", "Angel Buchwald", "Nestor Criger", "Arie Jozwiak", "Nita Montelongo", "Clemencia Okane", "Alison Scaggs", "Von Petrella", "Glennie Gurley", "Jamar Callender", "Titus Wenrich", "Chadwick Liedtke", "Sharlene Yochum", "Leonida Mutchler", "Duane Pickett", "Morton Brackins", "Ervin Trundy", "Antony Orwig", "Audrea Yutzy", "Michal Hepp", "Annelle Hoadley", "Hank Wyman", "Mika Fernandez", "Elisa Legendre", "Sade Nicolson", "Jessie Yi", "Forrest Mooneyhan", "Alvin Widell", "Lizette Ruppe", "Marguerita Pilarski", "Merna Argento", "Jess Daquila", "Breann Bevans", "Melvin Guidry", "Jacelyn Vanleer", "Jerome Riendeau", "Iraida Nyquist", "Micah Glantz", "Dorene Waldrip", "Fidel Garey", "Vertie Deady", "Rosalinda Odegaard", "Chong Hayner", "Candida Palazzolo", "Bennie Faison", "Nova Bunkley", "Francis Buckwalter", "Georgianne Espinal", "Karleen Dockins", "Hertha Lucus", "Ike Alberty", "Deangelo Revelle", "Juli Gallup", "Wendie Eisner", "Khalilah Travers", "Rex Outman", "Anabel King", "Lorelei Tardiff", "Pablo Berkey", "Mariel Tutino", "Leigh Marciano", "Ok Nadeau", "Zachary Antrim", "Chun Matthew", "Golden Keniston", "Anthony Johson", "Rossana Ahlstrom", "Amado Schluter", "Delila Lovelady", "Josef Belle", "Leif Negrete", "Alec Doss", "Darryl Stryker", "Michael Cagley", "Sabina Alejo", "Delana Mewborn", "Aurelio Crouch", "Ashlie Shulman", "Danielle Conlan", "Randal Donnell", "Rheba Anzalone", "Lilian Truax", "Weston Quarterman", "Britt Brunt", "Leonie Corbett", "Monika Gamet", "Ingeborg Bello", "Angelique Zhang", "Santiago Thibeau", "Eliseo Helmuth"] # root = Tk() # root.geometry("300x200") # combobox_autocomplete = Combobox_Autocomplete(root, list_of_items, highlightthickness=1) # combobox_autocomplete.pack() # combobox_autocomplete.focus() # root.mainloop()
class SelectionListbox(Toplevel): def __init__(self, parent, objectList): Toplevel.__init__(self, parent) self.protocol('WM_DELETE_WINDOW', self.destroy) self._objectList = objectList self._lb = Listbox(self, selectmode = SINGLE) self._lb.pack() self._buttons = PanedWindow(self) for i in objectList.getKeysInOrder(): self._lb.insert(END, i) addButton = Button(self._buttons, text="Add", command=self.onAdd) addButton.pack(side=LEFT) modifyButton = Button(self._buttons, text="Modify", command=self.onModify) modifyButton.pack(side=LEFT) deleteButton = Button(self._buttons, text="Delete", command=self.onDelete) deleteButton.pack(side=LEFT) cancelButton = Button(self._buttons, text="Cancel", command=self.onCancel) cancelButton.pack(side=RIGHT) self._buttons.pack(side=BOTTOM) def onAdd(self): self._inputPanel = InputPanel(self, self._objectList.getElementKeys(), self.addCallBack) def onModify(self): ctr = self._lb.curselection() key = self._lb.get(ctr) print key print self._objectList self._inputPanel = InputPanel(self, self._objectList.getElementKeys(), self.modifyCallBack, key, self._objectList._resources[key]) def onDelete(self): idx = self._lb.curselection() self.deleteCallBack(idx) def onCancel(self): self.destroy() def destroy(self): Toplevel.destroy(self) def addCallBack(self, cdict, key): print "Add new element" key = self._objectList.addFromDict(cdict) self._lb.insert(END, key) self._lb.update() # self._inputPanel.destroy() def modifyCallBack(self, cdict, key): print "Modify Existing Element" print cdict print key self._objectList.modifyElement(cdict, key) print self._objectList._resources[key] self._lb.update() # self._inputPanel.destroy() def deleteCallBack(self, idx): print "Delete" print idx key = self._lb.get(idx) self._objectList.deleteElement(key) self._lb.delete(idx) self._lb.update()
class IniGenGui(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUIGlobals() def initUIGlobals(self): self.parent.title("Ini Generator") Style().configure("TButton", padding=(0, 0, 0, 0), font='serif 10') f1 = Frame(self) f1.grid(row=0, column=0, padx=10, sticky=N + S + E + W) f11 = LabelFrame(f1, text="Algorithms to Run") f11.grid(row=0, column=0) row = 0 self.check_algs_value_list = [] self.check_algs_map = {} for alg in algorithms: if alg == 'clean': continue check_alg_value = IntVar() check_alg = Checkbutton(f11, text=alg, variable=check_alg_value, justify=LEFT, width=25) check_alg.grid(row=row, column=0, sticky=W + E) self.check_algs_value_list.append(check_alg_value) self.check_algs_map[alg] = check_alg_value row += 1 f111 = Frame(f11) f111.grid(row=row, column=0) button_checkall = Button(f111, text="All", command=self.checkall) button_checkall.grid(row=0, column=0, sticky=W + E) button_uncheckall = Button(f111, text="None", command=self.uncheckall) button_uncheckall.grid(row=0, column=1, sticky=W + E) row = 0 f12 = Frame(f1) f12.grid(row=1, column=0, pady=20, sticky=S + W + E) f121 = LabelFrame(f12, text='Location of uPMU') f121.grid(row=0, column=0) self.radio_loc_string = StringVar() locations.append('Other Location') for loc in locations: radio_loc = Radiobutton(f121, text=loc, variable=self.radio_loc_string, value=loc, command=self.set_loc, justify=LEFT, width=25) radio_loc.grid(row=row, column=0, sticky=W + E) row += 1 self.entry_otherloc = Entry(f121) f2 = Frame(self) f2.grid(row=0, column=1, padx=10, sticky=N + S + E + W) f21 = LabelFrame(f2, text='Name of uPMU (raw)') f21.grid(row=0) row = 0 f211 = Frame(f21) f211.grid(row=row) row += 1 self.entry_namesearch = Entry(f211) self.entry_namesearch.grid(row=0, column=0, sticky=E + W) button_namesearch = Button(f211, text="Search", command=self.namesearch) button_namesearch.grid(row=0, column=1, sticky=W + E) self.lstbx_namelist = Listbox(f21) self.lstbx_namelist.bind("<Double-Button-1>", self.namelist_select) self.lstbx_namelist.grid(row=row, sticky=W + E) row += 1 f212 = Frame(f21) f212.grid(row=row) row += 1 label_nameselected = Label(f212, text="Selected:") label_nameselected.grid(row=0, column=0) self.entry_nameselected = Entry(f212, state=DISABLED) self.entry_nameselected.grid(row=0, column=1, sticky=W + E) f22 = LabelFrame(f2, text="Name of uPMU (abbr)") f22.grid(row=1, sticky=W + E, pady=10) self.entry_name = Entry(f22, width=30) self.entry_name.grid(row=0, column=0, sticky=E + W) f23 = LabelFrame(f2, text="Name of Reference uPMU (clean)") f23.grid(row=2, pady=10) row = 0 f231 = Frame(f23) f231.grid(row=row) row += 1 self.entry_refnamesearch = Entry(f231) self.entry_refnamesearch.grid(row=0, column=0, sticky=E + W) button_refnamesearch = Button(f231, text="Search", command=self.refnamesearch) button_refnamesearch.grid(row=0, column=1, sticky=W + E) self.lstbx_refnamelist = Listbox(f23) self.lstbx_refnamelist.bind("<Double-Button-1>", self.refnamelist_select) self.lstbx_refnamelist.grid(row=row, sticky=W + E) row += 1 f232 = Frame(f23) f232.grid(row=row) row += 1 label_refnameselected = Label(f232, text="Selected:") label_refnameselected.grid(row=0, column=0) self.entry_refnameselected = Entry(f232, state=DISABLED) self.entry_refnameselected.grid(row=0, column=1, sticky=W + E) button_gen = Button(self, text="Generate Files", command=self.generate_files) button_gen.grid(row=1, column=0, columnspan=2, sticky=W + E) self.pack() def generate_files(self): algs = [] for alg in self.check_algs_map: if self.check_algs_map[alg].get() == 1: algs.append(alg) if self.radio_loc_string.get() == "Other Location": location = self.entry_otherloc.get() else: location = self.radio_loc_string.get() name_raw = self.entry_nameselected.get() name = self.entry_name.get() ref_name = self.entry_refnameselected.get() uuid_map = self.get_uuid_map(name_raw) reference_uuid_map = self.get_ref_uuid_map(ref_name) IniGenAutomation(location, name_raw, name, uuid_map, ref_name, reference_uuid_map, algs) def namesearch(self): searchterm = self.entry_namesearch.get() if searchterm.contains("/"): loc = searchterm.split('/') searchphrase = '/upmu/%{0}%/%{1}%/%'.format(loc[0], loc[1]) else: searchphrase = '/upmu/%{0}%/%'.format(searchterm) search_results = self.search(searchterm, searchphrase) self.lstbx_namelist.delete(0, END) if len(search_results) == 0: tkMessageBox.showwarning( 'Search Error', 'No matches from search for \'{0}\''.format(searchterm)) else: for result in search_results: self.lstbx_namelist.insert(END, result) def refnamesearch(self): searchterm = self.entry_refnamesearch.get() searchphrase = '/Clean/%{0}%/%'.format(searchterm) search_results = self.search(searchterm, searchphrase) self.lstbx_refnamelist.delete(0, END) if len(search_results) == 0: tkMessageBox.showwarning( 'Search Error', 'No matches from search for \'{0}\''.format(searchterm)) else: for result in search_results: self.lstbx_refnamelist.insert(END, result) def search(self, searchterm, searchphrase): connection = _mysql.connect(host="128.32.37.231", port=3306, user="******", passwd="moresecuredataftw", db='upmu') connection.query( "SELECT * FROM uuidpathmap WHERE path LIKE '{0}'".format( searchphrase)) results = connection.store_result() queried_data = {} result = results.fetch_row() while result != tuple(): queried_data[result[0][0]] = result[0][1] result = results.fetch_row() search_results = set() for path in queried_data: dirs = path.split('/') if searchterm in dirs[2]: search_results.add(dirs[2]) return search_results def set_loc(self): if self.radio_loc_string.get() == "Other Location": self.entry_otherloc.grid(sticky=W + E) else: self.entry_otherloc.grid_forget() def checkall(self): for check in self.check_algs_value_list: check.set(1) def uncheckall(self): for check in self.check_algs_value_list: check.set(0) def namelist_select(self, event): selected_index = self.lstbx_namelist.curselection() selected = self.lstbx_namelist.get(selected_index) self.entry_nameselected.configure(state=NORMAL) self.entry_nameselected.delete(0, END) self.entry_nameselected.insert(0, selected) self.entry_nameselected.configure(state=DISABLED) def refnamelist_select(self, event): selected_index = self.lstbx_refnamelist.curselection() selected = self.lstbx_refnamelist.get(selected_index) self.entry_refnameselected.configure(state=NORMAL) self.entry_refnameselected.delete(0, END) self.entry_refnameselected.insert(0, selected) self.entry_refnameselected.configure(state=DISABLED) def get_uuid_map(self, name): uuid_map = {} connection = _mysql.connect(host="128.32.37.231", port=3306, user="******", passwd="moresecuredataftw", db='upmu') connection.query( "SELECT * FROM uuidpathmap WHERE path LIKE '/upmu/{0}/%'".format( name)) results = connection.store_result() result = results.fetch_row() while result != tuple(): path = result[0][0].split('/') uuid_map[path[-1]] = result[0][1] result = results.fetch_row() return uuid_map def get_ref_uuid_map(self, name): uuid_map = {} connection = _mysql.connect(host="128.32.37.231", port=3306, user="******", passwd="moresecuredataftw", db='upmu') connection.query( "SELECT * FROM uuidpathmap WHERE path LIKE '/Clean/{0}/%'".format( name)) results = connection.store_result() result = results.fetch_row() while result != tuple(): path = result[0][0].split('/') uuid_map[path[-2]] = result[0][1] result = results.fetch_row() return uuid_map
class Gamelist(): def __init__(self, drive, platform): GameListData.game_list_data_json = GameListData().get_game_list() self.json_game_list_data = GameListData.game_list_data_json if drive == 'USB(*)': self.drive_to_show = '/dev_' + drive.lower().replace('(*)', '') else: self.drive_to_show = '/dev_' + drive.lower() + '/' self.platform_to_show = platform + '_games' self.WCM_BASE_PATH = AppPaths.wcm_gui self.last_selection = (None, 0) self.list_of_items = [] self.selected_title_id = None self.selected_title = None self.selected_path = None self.selected_filename = None self.drive_system_path_array = None self.is_cleared = False def create_main_frame(self, entry_field_title_id, entry_field_title, entry_field_filename, entry_field_iso_path, entry_field_platform, drive_system_array): self.entry_field_title_id = entry_field_title_id self.entry_field_title = entry_field_title self.entry_field_filename = entry_field_filename self.entry_field_iso_path = entry_field_iso_path self.entry_field_platform = entry_field_platform self.drive_system_path_array = drive_system_array self.corrected_index = [] self.main_frame = Frame() self.popup_menu = Menu(self.main_frame, tearoff=0) self.popup_menu.add_command(label="Delete", command=self.delete_selected) self.popup_menu.add_command(label="Rename", command=self.rename_selected) # self.popup_menu.add_command(label="Refetch", # command=self.refetch) # self.popup_menu.add_command(label="Select All", # command=self.select_all) s = Scrollbar(self.main_frame) self._listbox = Listbox(self.main_frame, width=465) self._listbox.bind('<Enter>', self._bound_to_mousewheel) self._listbox.bind('<Leave>', self._unbound_to_mousewheel) self._listbox.bind("<Button-3>", self.popup) # Button-2 on Aqua s.pack(side=RIGHT, fill=Y) self._listbox.pack(side=LEFT, fill=Y) s['command'] = self._listbox.yview self._listbox['yscrollcommand'] = s.set # default filters if 'ALL_games' == self.platform_to_show: # iterate all platforms for platform in self.json_game_list_data: for list_game in self.json_game_list_data[platform]: # titles in the list has been designed to be unique if '/dev_all/' == self.drive_to_show or self.drive_to_show in list_game['path']: self.add_item(list_game['title']) else: for list_game in self.json_game_list_data[self.platform_to_show]: if '/dev_all/' == self.drive_to_show or self.drive_to_show in list_game['path']: self.add_item(list_game['title']) for x in range(19 - self._listbox.size()): self.add_item('') # adding shade to every other row of the list for x in range(0, self._listbox.size()): if x % 2 == 0: self._listbox.itemconfig(x, {'fg': 'white'}, background='#001738') else: self._listbox.itemconfig(x, {'fg': 'white'}, background='#001F4C') self.label = Label(self.main_frame) self.selection_poller() return self.main_frame def selection_poller(self): self.label.after(200, self.selection_poller) self.new_selection = self._listbox.curselection() # cursor har been initiated if self._listbox.curselection() is not (): if self.new_selection[0] is not self.last_selection[0] or self.is_cleared: self.entry_fields_update(self.new_selection) self.is_cleared = False self.last_selection = self.new_selection def entry_fields_update(self, new_selection): for platform in self.json_game_list_data: for list_game in self.json_game_list_data[platform]: self.selected_title = self._listbox.get(new_selection[0]) tmp_title = list_game['title'] match = self.selected_title == str(tmp_title) if match: self.selected_title_id = str(list_game['title_id']).replace('-', '') self.selected_title = str(list_game['title']) self.selected_path = str(list_game['path']) self.selected_filename = str(list_game['filename']) self.selected_platform = str(list_game['platform']) # parse drive and system from json data path_array = filter(None, self.selected_path.split('/')) self.drive_system_path_array[0] = path_array[0] self.drive_system_path_array[1] = path_array[1] self.drive_system_path_array[2] = '/'.join(path_array[2:len(path_array)]).replace('//', '') self.entry_field_title_id.delete(0, len(self.entry_field_title_id.get())-1) self.entry_field_title_id.delete(0, END) self.entry_field_title_id.insert(0, self.selected_title_id) self.entry_field_title.delete(0, END) self.entry_field_title.insert(0, self.selected_title) self.entry_field_filename.delete(0, END) self.entry_field_filename.insert(0, self.selected_filename) self.entry_field_platform.delete(0, END) self.entry_field_platform.insert(0, self.selected_platform) return True def get_selected_path(self): return self.current_iso_path def get_listbox(self): return self._listbox def get_ascending_index(self, list_of_items, item, ignore_case=True): lo = 0 hi = len(list_of_items) if ignore_case: item = item.lower() while lo < hi: mid = (lo + hi) // 2 if item < list_of_items[mid].lower(): hi = mid else: lo = mid + 1 else: while lo < hi: mid = (lo + hi) // 2 if item < list_of_items[mid]: hi = mid else: lo = mid + 1 return lo def add_item(self, item): if item != '': self.list_of_items = self._listbox.get(0, END) # getting ascending index in order to sort alphabetically index = self.get_ascending_index(self.list_of_items, item) self._listbox.insert(index, item) else: self._listbox.insert(END, item) def get_items(self): return self.list_of_items def _bound_to_mousewheel(self, event): self._listbox.bind_all("<MouseWheel>", self._on_mousewheel) def _unbound_to_mousewheel(self, event): self._listbox.unbind_all("<MouseWheel>") def _on_mousewheel(self, event): self._listbox.yview_scroll(int(-1*(event.delta/30)), "units") def popup(self, event): try: self._listbox.selection_clear(0, END) self._listbox.selection_set(self._listbox.nearest(event.y)) self._listbox.activate(self._listbox.nearest(event.y)) finally: if self._listbox.get(self._listbox.curselection()[0]) is not '': self.popup_menu.tk_popup(event.x_root + 43, event.y_root + 12, 0) self.popup_menu.grab_release() self.popup_menu.focus_set() def delete_selected(self): import tkMessageBox game_folder_path = os.path.join(AppPaths.game_work_dir, '..') response = tkMessageBox.askyesno('Delete game folder', 'Delete \'' + self.entry_field_title.get() + '\'?\n\nFolder path: ' + os.path.realpath(game_folder_path)) # yes if response: # remove game from visual game list for i in self._listbox.curselection()[::-1]: self._listbox.delete(i) removed_index = i # remove game from json game list platform_key = self.entry_field_platform.get() + '_games' self.json_game_list_data[platform_key] = [x for x in self.json_game_list_data[platform_key] if x['title'] != self.selected_title] # update the json game list file with open(GameListData.GAME_LIST_DATA_PATH, 'w') as newFile: json_text = json.dumps(self.json_game_list_data, indent=4, separators=(",", ":")) newFile.write(json_text) # remove the game build folder too if AppPaths.game_work_dir != os.path.join(AppPaths.wcm_gui, 'work_dir'): if os.path.isdir(game_folder_path): if 'webman-classics-maker' in game_folder_path: shutil.rmtree(game_folder_path) # clear entry_fields self.clear_entries_and_path() # set cursor self._listbox.select_set(removed_index) #This only sets focus on the first item. def rename_selected(self): self.entry_field_title.selection_range(0, END) self.entry_field_title.focus_set() def select_all(self): self._listbox.selection_set(0, 'end') def clear_entries_and_path(self): self.entry_field_title_id.delete(0, len(self.entry_field_title_id.get())-1) self.entry_field_title_id.delete(0, END) self.entry_field_title.delete(0, END) self.entry_field_platform.delete(0, END) self.entry_field_filename.delete(0, END) self.is_cleared = True def get_selected_build_dir_path(self): self.build_dir_path = '' if self.selected_filename not in {'', None}: filename = self.selected_filename title_id = self.selected_title_id.replace('-', '') build_base_path = AppPaths.builds tmp_filename = filename # removes the file extension from tmp_filename for file_ext in GlobalVar.file_extensions: if filename.upper().endswith(file_ext): tmp_filename = filename[0:len(filename)-len(file_ext)] break game_folder_name = tmp_filename.replace(' ', '_') + '_(' + title_id.replace('-', '') + ')' self.build_dir_path = os.path.join(build_base_path, game_folder_name) return self.build_dir_path
class Window(Frame): RENDER_PROCESSES = 2 def __init__(self, width, height, scene, tracer, calculate=None): Frame.__init__(self, master=None) if calculate is None: calculate = [0, 0] self.d = calculate self.scene = scene self.after_id = 0 self.tracer = tracer self.width = width self.height = height self.__init_window(height, width) self.master.mainloop() def __init_window(self, height, width): self.master.title = "Ray Py" canvas = Canvas(self.master, width=width, height=height) canvas.pack(side=TOP) self.img = PhotoImage(width=width, height=height) canvas.create_image((width / 2, height / 2), image=self.img, state="normal") self.startButton = Button(self.master, text="Render", command=lambda: self.__onStartPressed()) self.startButton.pack(side=RIGHT) self.resetButton = Button(self.master, text="Reset", command=lambda: self.__onResetPressed()) self.resetButton.config(state="disabled") self.resetButton.pack(side=RIGHT) self.listbox = Listbox(self.master, height=5) self.listbox.bind('<<ListboxSelect>>', self.__selectTracer) self.listbox.insert(END, "Simple", "Shadow", "ShadingShadow", "Recursive", "PathTracer") self.listbox.pack(side=LEFT) self.listbox.selection_set(0) self.listbox.activate(0) self.listbox.focus_set() def __selectTracer(self, evt): value = self.listbox.get(self.listbox.curselection()) if value == "Simple": self.tracer = SimpleRayTracer() elif value == "Shadow": self.tracer = SimpleShadowRayTracer() elif value == "ShadingShadow": self.tracer = ShadingShadowRayTracer(self.scene.eye) elif value == "Recursive": self.tracer = RecursiveRayTracer(self.scene.eye) elif value == "PathTracer": self.tracer = PathTracer(self.scene.eye) def __onStartPressed(self): self.startButton.config(state="disabled") self.listbox.config(state="disabled") self.__draw() def __update(self): if self.finishedQueue.qsize() >= self.RENDER_PROCESSES: self.finishedThreads = self.RENDER_PROCESSES while not self.finishedQueue.empty(): self.finishedQueue.get() if not self.dataQueue.empty(): item = self.dataQueue.get() self.img.put(item[1], item[0]) self.master.update() elif self.finishedThreads == self.RENDER_PROCESSES: for t in self.threads: t.join() self.master.after_cancel(self.after_id) self.resetButton.config(state="active") return self.after_id = self.master.after(0, self.__update) def __draw(self): from processes import BlockProcess from multiprocessing import Queue self.finishedQueue = Queue() self.dataQueue = Queue() self.finishedThreads = 0 self.threads = BlockProcess.forCount(self.RENDER_PROCESSES, self.width, self.height, self.tracer, self.scene, self.dataQueue, self.finishedQueue) for t in self.threads: t.start() self.__update() self.after_id = self.master.after(0, self.__update) def __onResetPressed(self): self.img.blank() self.d = [0, 0] self.resetButton.config(state="disabled") self.startButton.config(state="active") self.listbox.config(state="normal")
class exo(Frame): """The base class for the exo_convert GUI""" # This is the constructor for the GUI def __init__(self,master=None): Frame.__init__(self,master) self.grid() for i in range(2): self.columnconfigure(i,minsize=10) self.rowconfigure(i,minsize=10) self.defineUnits() self.createWidgets() # Bind choice of variable (distance,mass,time) # Highlights variable selection and presents unit options self.inputlist.bind("<Button-1>",self.__varChoice) # Bind choice of unit (highlights unit selection) self.unitlist.bind("<Button-1>",self.__unitChoice) # Bind Entry of variable value to calculation self.inputfield.bind("<Return>",self.__calcConversion) # This function creates and defines the units def defineUnits(self): # Tuples which represent the various units allowed by each option # Distances self.distunits = ('pc','AU','Solar Radii','Jupiter Radii', 'Saturn Radii','Neptune Radii ','Earth Radii','Mars Radii', 'Moon Radii','cm') # All values in cm self.distvalues = (3.08568025e18, 1.496e13, 6.995e10,7.1492e9,6.0268e9,2.4764e9,6.371e8,3.396e8,1.73814e8,1.0) # Masses self.massunits = ('Solar Masses', 'Jupiter Masses','Saturn Masses', 'Neptune Masses', 'Earth Masses', 'Mars Masses', 'Moon Masses', 'kg','g') # All values in g self.massvalues = (1.988920e33,1.8986e30,5.6834e29, 1.0243e29, 5.9736e27,6.4185e26, 7.3477e25, 1000.0,1.0) # Time self.timeunits = ('seconds','minutes' ,'hours', 'days','Martian sols','weeks', 'years', 'Mars years', 'Jupiter years') # All values in seconds self.timevalues = (1.0,60.0,3600.0, 86400.0,88775.244, 604800.0,31556926.0,59354294.4 , 374335776.0) # Keep the unit values in dictionaries, and use the above strings as keys self.distdict = {} self.createUnitDict(self.distdict,self.distunits,self.distvalues) self.massdict = {} self.createUnitDict(self.massdict,self.massunits,self.massvalues) self.timedict = {} self.createUnitDict(self.timedict, self.timeunits, self.timevalues) self.myunits = self.timeunits self.myvalues = self.timevalues self.mydict = self.timedict # This function creates a unit dictionary, with keys and unit values in cgs def createUnitDict(self,mydict,mykeys,myvalues): for i in range(len(myvalues)): mydict[mykeys[i]] = myvalues[i] # This function creates and adds all widgets to the GUI def createWidgets(self): # Create Widgets in order of appearance # This is not necessary, but makes code easier to read # Start with text telling user what to do self.varlabel = Text(self,height=1, width=20) self.varlabel.insert(END,"Which Variable?") # Place widget on the Frame according to a grid self.varlabel.grid(row=0,column=0,sticky=W) # Second text label asking user which units are being used self.unitlabel = Text(self,height=2,width=20) self.unitlabel.insert(END,"Which Units are you \nworking in?") self.unitlabel.grid(row=0,column=1,sticky=W) # Third text label asking user for numerical value self.numlabel = Text(self,height=1, width=20) self.numlabel.insert(END,"Enter Variable Value") self.numlabel.grid(row=0,column=2,sticky=W) # This creates a list of options for the user to select self.inputlist = Listbox(self, height=3, selectmode=SINGLE) # Tuple of choices we're going to put in this list paramlist = ('Distance', 'Time', 'Mass') # Add each item separately for item in paramlist: self.inputlist.insert(END,item) # Add it to the grid self.inputlist.grid(row=1, sticky=W) # Add a unit list which produces a set of unit choices dependent on inputlist self.unitlist = Listbox(self, height=10,selectmode=SINGLE) self.unitlist.grid(row=1,column=1, sticky=W) # Number Entry Box self.inputfield = Entry(self) self.inputfield.insert(END, "0") self.inputfield.grid(row =1, column=2,sticky=W) # Text Output Box self.outputtext = Text(self, height=10) self.outputtext.grid(row=2,column=0,columnspan=3,sticky=W) self.outputtext.insert(END, "WAITING: ") # Create the Quit Button self.quitButton=Button(self,text='Quit',command=self.quit) self.quitButton.grid(row =3, column=0, sticky=W) # Event handler functions begin here # This handler defines the choice of units available to the user, # depending on selected variable def __varChoice(self, event): self.unitlist.delete(first=0,last=len(self.myvalues)) num = 0 try: num = self.inputlist.curselection()[0] choice = int(num) except: choice = 0 return # Highlight current choice in red self.inputlist.itemconfig(choice, selectbackground='red') if choice==0: #print 'Distance chosen' self.mydict=self.distdict self.myunits= self.distunits self.myvalues = self.distvalues elif choice==1: # print 'Time chosen' self.mydict=self.timedict self.myunits= self.timeunits self.myvalues = self.timevalues elif choice==2: # print 'Mass chosen' self.mydict=self.massdict self.myunits= self.massunits self.myvalues = self.massvalues # Add the units to the unitlist for item in self.myunits: self.unitlist.insert(END,item) del num def __unitChoice(self,event): num = 0 try: num = self.unitlist.curselection()[0] choice = int(num) except: choice = 0 return # Highlight current choice in red self.unitlist.itemconfig(choice, selectbackground='red') # Handler takes current state of GUI, and calculates results def __calcConversion(self,event): num = 0 # What units are being used? try: num = self.unitlist.curselection()[0] choice = int(num) except: choice = 0 return self.outputtext.delete("1.0",index2=END) # Highlight current choice in red self.unitlist.itemconfig(choice, selectbackground='red') # What is the value in the entry field? value = self.inputfield.get() value = float(value) # Now perform calculation using dictionary var = self.unitlist.get(choice) # Convert value to cgs value = value*self.mydict[var] # Create a new list of output answers output=[] self.outputtext.insert(END,"OUTPUT: \n\n") # Calculate and output it to the GUI for i in range(len(self.myvalues)): output.append(value/self.myvalues[i]) self.outputtext.insert(END,self.myunits[i] + ": "+str(output[i])+"\n")
class ListPage(BasePage): def __init__(self, parent, controller): BasePage.__init__(self, parent, controller) self.target_keep_profile_var = IntVar() self.mutex = Lock() def prepare(self): self.enable_device_list() self.enable_bid_input() self.setData(self.controller.data) self.setDeviceList(self.data.keys()) self.controller.setDefault(self, self.controller.loadOptions()) self.deviceList.focus_force() def printErr(self, message): self.errLog.config(text=message) def setData(self, data): self.data = data def setupView(self, title="Select your flash", data=None): if(data): self.setData(data) Label(self, text="Status:").grid(row=4, column=0, columnspan=1, sticky="SW") self.errLog = Label(self, text="", width="90") self.errLog.grid(row=5, column=0, columnspan=4, sticky="NW") self.desc = Label(self, text=title, font=TITLE_FONT) self.desc.grid(row=0, column=0, columnspan=2) self.ok = Button(self, text='Flash', command=lambda: self.confirm()) self.ok.grid(row=4, column=3, sticky="E") # bind self.target_keep_profile_var (IntVar) to keepProfileCheckbutton, 1 is True, 0 is Flase self.keepProfileCheckbutton = Checkbutton(self, text="Keep User Profile (BETA)", variable=self.target_keep_profile_var) self.keepProfileCheckbutton.grid(row=7, column=0, columnspan=4, sticky="W") self.deviceLabel = Label(self, text="Device", font=TITLE_FONT) self.deviceLabel.grid(row=1, column=0) self.deviceList = Listbox(self, exportselection=0) self.deviceList.grid(row=2, column=0) self.versionLabel = Label(self, text="Branch", font=TITLE_FONT) self.versionLabel.grid(row=1, column=1) self.versionList = Listbox(self, exportselection=0) self.versionList.grid(row=2, column=1) self.engLabel = Label(self, text="Build Type", font=TITLE_FONT) self.engLabel.grid(row=1, column=2) self.engList = Listbox(self, exportselection=0) self.engList.grid(row=2, column=2) self.packageLabel = Label(self, text="Gecko/Gaia/Full", font=TITLE_FONT) self.packageLabel.grid(row=1, column=3) self.packageList = Listbox(self, exportselection=0) self.packageList.grid(row=2, column=3) self.bidVar = StringVar() Label(self, text="Build ID").grid(row=3, column=0, sticky='E') self.bidInput = Entry(self, textvariable=self.bidVar, width="30") self.bidInput.grid(row=3, column=1, columnspan=2, sticky="W") self.bidVar.set('latest') self.progress = ttk.Progressbar(self, orient='horizontal', length=120, mode='indeterminate') self.progress.grid(row=3, column=3) self.disable_device_list() self.disable_version_list() self.disable_eng_list() self.disable_package_list() self.disable_bid_input() self.disable_ok_button() def enable_device_list(self): target = self.deviceList target.bind('<<ListboxSelect>>', self.deviceOnSelect) target.bind('<Return>', self.pressReturnKey) target.config(state="normal") def disable_device_list(self): target = self.deviceList target.unbind('<<ListboxSelect>>') target.unbind('<Return>') target.config(state="disabled") def enable_version_list(self): target = self.versionList target.bind('<<ListboxSelect>>', self.versionOnSelect) target.bind('<Return>', self.pressReturnKey) target.config(state="normal") def disable_version_list(self): target = self.versionList target.unbind('<<ListboxSelect>>') target.unbind('<Return>') target.config(state="disabled") def enable_eng_list(self): target = self.engList target.bind('<<ListboxSelect>>', self.engOnSelect) target.bind('<Return>', self.pressReturnKey) target.config(state="normal") def disable_eng_list(self): target = self.engList target.unbind('<<ListboxSelect>>') target.unbind('<Return>') target.config(state="disabled") def enable_package_list(self): target = self.packageList target.bind('<<ListboxSelect>>', self.packageOnSelect) target.bind('<Return>', self.pressReturnKey) target.config(state="normal") def disable_package_list(self): target = self.packageList target.unbind('<<ListboxSelect>>') target.unbind('<Return>') target.config(state="disabled") def enable_ok_button(self): target = self.ok target.bind('<Return>', self.pressReturnKey) target.config(state="normal") def disable_ok_button(self): target = self.ok target.unbind('<Return>') target.config(state="disabled") def enable_bid_input(self): target = self.bidInput # binding unfocus for build id field target.bind('<FocusOut>', self.updateBuildId) target.bind('<Return>', self.pressReturnKey) target.config(state="normal") def disable_bid_input(self): target = self.bidInput target.unbind('<FocusOut>') target.unbind('<Return>') target.config(state="disabled") def selection_all_checked(self): result = False if len(self.deviceList.curselection()) == 0: self.logger.log('Please select device.', status_callback=self.printErr) self.disable_ok_button() self.deviceList.focus_set() elif len(self.versionList.curselection()) == 0: self.logger.log('Please select branch.', status_callback=self.printErr) self.disable_ok_button() self.versionList.focus_set() elif len(self.engList.curselection()) == 0: self.logger.log('Please select user or engineer build.', status_callback=self.printErr) self.disable_ok_button() self.engList.focus_set() elif len(self.packageList.curselection()) == 0: self.logger.log('Please select package to flash.', status_callback=self.printErr) self.disable_ok_button() self.packageList.focus_set() elif len(self.bidVar.get()) != 14 and self.bidVar.get() != 'latest': self.logger.log('Please enter build ID to flash or use "latest" to get the newest', status_callback=self.printErr) self.logger.log(self.bidVar.get() + ' is invalid: ' + str(len(self.bidVar.get()))) self.bidVar.set('latest') else: result = True return result def updateBuildId(self, event=None): # if the value is '' or 'latest', the set the build_id option as ''. buildId = self.bidVar.get() if buildId == 'latest': buildId = '' elif len(buildId) != 14: self.printErr("Invalid build ID: " + buildId + ", reset to latest") buildId = '' self.bidVar.set('latest') else: if len(self.engList.curselection()) != 0: refresh_package_list_thread = threading.Thread(target=self.refreshPackageList) refresh_package_list_thread.start() def pressReturnKey(self, event=None): if self.selection_all_checked(): self.disable_ok_button() self.confirm() def deviceOnSelect(self, evt): self.setVersionList() def versionOnSelect(self, evt): self.setEngList() def engOnSelect(self, evt): refresh_package_list_thread = threading.Thread(target=self.refreshPackageList) refresh_package_list_thread.start() def packageOnSelect(self, evt): self.enable_ok_button() def confirm(self): self.mutex.acquire() try: if self.selection_all_checked(): self.disable_ok_button() params = [] package = self.packageList.get(self.packageList.curselection()[0]) self.logger.log('Start to flash [' + package + '].', status_callback=self.printErr) if(PathParser._IMAGES in package): params.append(PathParser._IMAGES) else: if(PathParser._GAIA in package): params.append(PathParser._GAIA) if(PathParser._GECKO in package): params.append(PathParser._GECKO) keep_profile = (self.target_keep_profile_var.get() == 1) run_flash_thread = threading.Thread(target=self.run_flash, args=(params, keep_profile)) run_flash_thread.start() self.controller.transition(self) finally: self.mutex.release() def run_flash(self, params, keep_profile): self.progress.start(10) self.disable_device_list() self.disable_version_list() self.disable_eng_list() self.disable_package_list() self.disable_bid_input() self.disable_ok_button() archives = self.controller.do_download(params) self.controller.do_flash(params, archives, keep_profile=keep_profile) self.enable_device_list() self.enable_version_list() self.enable_eng_list() self.enable_package_list() self.enable_bid_input() self.enable_ok_button() self.progress.stop() def setDeviceList(self, device=[]): self.deviceList.delete(0, END) for li in device: self.deviceList.insert(END, li) def setVersionList(self, version=[]): if len(version) == 0: version = self.data[self.deviceList.get(self.deviceList.curselection())] self.enable_version_list() self.disable_eng_list() self.disable_package_list() self.disable_ok_button() self.versionList.delete(0, END) for li in version: self.versionList.insert(END, li) def setEngList(self, eng=[]): if len(eng) == 0: device = self.deviceList.get(self.deviceList.curselection()) version = self.versionList.get(self.versionList.curselection()) eng = self.data[device][version] self.enable_eng_list() self.disable_package_list() self.disable_ok_button() self.engList.delete(0, END) for li in eng: self.engList.insert(END, li) def refreshPackageList(self): self.mutex.acquire() self.progress.start(10) try: self.disable_device_list() self.disable_version_list() self.disable_eng_list() self.disable_bid_input() self.enable_package_list() #self.packageList.config(state="normal") self.packageList.delete(0, END) device = self.deviceList.get(self.deviceList.curselection()) version = self.versionList.get(self.versionList.curselection()) eng = self.engList.get(self.engList.curselection()) buildId = '' if (len(self.bidVar.get()) == 0 or self.bidVar.get() == 'latest') else self.bidVar.get() package = self.controller.getPackages(self.data[device][version][eng]['src'], build_id=buildId) if len(package) == 0: self.logger.log('Invalid build ID: ' + buildId + ', reset to latest', status_callback=self.printErr) buildId = '' self.bidVar.set('latest') package = self.controller.getPackages(self.data[device][version][eng]['src'], build_id=buildId) for li in package: self.packageList.insert(END, li) finally: self.enable_device_list() self.enable_version_list() self.enable_eng_list() self.enable_bid_input() #self.ok.config(state="normal") self.progress.stop() self.mutex.release()
class ListFrame(LabelFrame): """ A Frame representing one of the search term lists (e.g. Hashtags, Excluded Users). Displays all the items in the list, and allows the user to add or remove items. Methods should not be called directly; instead they should be bound as event handlers. """ def __init__(self, name, add_handler, remove_handler, master=None): """ Creates a ListFrame with the given name as its title. add_handler and remove_handler are functions to be called when items are added or removed, and should relay the information back to the Searcher (or whatever object actually uses the list). """ LabelFrame.__init__(self, master) self['text'] = name self.add_handler = add_handler self.remove_handler = remove_handler self.list = Listbox(self) self.list.grid(row=0, columnspan=2) # Tkinter does not automatically close the right-click menu for us, # so we must close it when the user clicks away from the menu. self.list.bind("<Button-1>", lambda event: self.context_menu.unpost()) self.list.bind("<Button-3>", self.open_menu) self.context_menu = Menu(self, tearoff=0) self.context_menu.add_command(label="Remove", command=self.remove) self.input = Entry(self) self.input.bind("<Return>", lambda event: self.add()) self.input.grid(row=1, columnspan=2) self.add_button = Button(self) self.add_button['text'] = "Add" self.add_button['command'] = self.add self.add_button.grid(row=2, column=0, sticky=W + E) self.remove_button = Button(self) self.remove_button['text'] = "Remove" self.remove_button['command'] = self.remove self.remove_button.grid(row=2, column=1, sticky=W + E) def add(self): """ Add the item in the input line to the list. """ self.list.insert(END, self.input.get()) self.add_handler(self.input.get()) self.input.delete(0, END) def remove(self): """ Remove the active (highlighted) item from the list. """ deleted = self.list.get(ACTIVE) self.list.delete(ACTIVE) self.remove_handler(deleted) def open_menu(self, event): """ Opens a right-click menu for the selected item. Currently the menu only has an option for removing the item. """ index = self.list.index("@" + str(event.x) + "," + str(event.y)) if index < 0: return self.context_menu.post(event.x_root, event.y_root) self.list.activate(index) self.list.selection_clear(0, END) self.list.selection_set(ACTIVE)
class AttributesDialog(Toplevel): """ Dialog window for creating and assigning attributes to objects :param root: The parent frame :param shape: The ShapeManager being edited """ def __init__(self, root, shape): """ Initialize root tkinter window and master GUI window """ Toplevel.__init__(self, root, width=200, height=200) self.__shape = shape if shape is False: self.close() return self.title('Edit Attributes') # copies TAGS to avoid aliasing self.__available_attributes = TAGS[:] self.container = Frame(self) self.container.pack(side=TOP, fill=BOTH, expand=True) self.top_frame = None self.bottom_frame = None self.note_text = None self.attributes_list = None self.selected_list = None self.transient(root) logger.info('Creating top frame') self.create_top_frame() logger.info('Creating bottom frame') self.create_bottom_frame() def create_top_frame(self): """ Initializes the top half of the window """ self.top_frame = Frame(self.container) self.top_frame.pack(side=TOP, fill=X, expand=False) attributes_string = StringVar() attributes_string.set('Attributes:') attributes_label = Label(self.top_frame, textvariable=attributes_string) attributes_label.grid(row=0, column=0) selected_string = StringVar() selected_string.set('Selected:') selected_label = Label(self.top_frame, textvariable=selected_string) selected_label.grid(row=0, column=3) self.attributes_list = Listbox(self.top_frame, width=30, height=15, selectmode=EXTENDED) self.attributes_list.grid(row=1, column=0, padx=6) self.selected_list = Listbox(self.top_frame, width=30, height=15, selectmode=EXTENDED) self.selected_list.grid(row=1, column=3, padx=6) logger.info('Loading attributes') for tag in self.__available_attributes: if self.__shape.is_attribute(tag): self.selected_list.insert(END, tag) else: self.attributes_list.insert(END, tag) remove_button = Button(self.top_frame, width=3, height=2, text='<--', command=self.remove_attribute) remove_button.grid(row=1, column=1) move_button = Button(self.top_frame, width=3, height=2, text='-->', command=self.move_attribute) move_button.grid(row=1, column=2) def create_bottom_frame(self): """ Initializes the bottom half of the window """ self.bottom_frame = Frame(self.container) self.bottom_frame.pack(side=BOTTOM, fill=X, expand=False) note_string = StringVar() note_string.set('Notes:') note_label = Label(self.bottom_frame, textvariable=note_string) note_label.grid(row=0, column=1) self.note_text = Text(self.bottom_frame, width=55, height=10) self.note_text.grid(row=1, column=1, padx=6) self.note_text.insert(END, self.__shape.get_notes()) button_frame = Frame(self.container) button_frame.pack(side=BOTTOM, fill=X, expand=False) accept_button = Button(button_frame, text='Save', width=9, command=self.save) accept_button.pack(side=LEFT, pady=5, padx=2) cancel_button = Button(button_frame, text='Clear Note', width=9, command=self.clear) cancel_button.pack(side=LEFT, pady=5, padx=2) # closeButton = Button(buttonFrame, text='Close', command=self.close) # closeButton.grid(row=3, column=2) def move_attribute(self): """ Saves the attributes that the user has selected """ selection = self.attributes_list.curselection() if len(selection) == 0: return for item in selection: string = self.attributes_list.get(item) logger.info('Adding attribute \'%s\' to shape' % string) self.__shape.add_attribute(string) self.selected_list.insert(END, string) for item in reversed(selection): self.attributes_list.delete(item) def remove_attribute(self): """ Deletes the attributes that the user has selected """ selection = self.selected_list.curselection() if len(selection) == 0: return for item in selection: string = self.selected_list.get(item) logger.info('Deleting attribute \'%s\' from shape' % string) self.__shape.remove_attribute(string) self.attributes_list.insert(END, string) for item in reversed(selection): self.selected_list.delete(item) def save(self): """ Saves the note """ logger.info('Saving note') note = self.note_text.get('1.0', 'end-1c') self.__shape.set_notes(note) self.close() def clear(self): """ Deletes the note """ logger.info('Deleting note') self.note_text.delete(1.0, END) self.__shape.set_notes('') def close(self): """ Closes window """ logger.info('Closing window') self.destroy()
class AutocompleteEntry(Entry): def __init__(self, autocompleteList, *args, **kwargs): # Listbox length self.listboxLength = kwargs.pop('listboxLength', 12) self.listboxFontSize = tkFont.Font(size=18) # Custom matches function if 'matchesFunction' in kwargs: self.matchesFunction = kwargs['matchesFunction'] del kwargs['matchesFunction'] else: def matches(fieldValue, acListEntry): pattern = re.compile('.*' + re.escape(fieldValue) + '.*', re.IGNORECASE) return re.match(pattern, acListEntry) self.matchesFunction = matches Entry.__init__(self, *args, **kwargs) self.focus() self.autocompleteList = autocompleteList self.var = self["textvariable"] if self.var == '': self.var = self["textvariable"] = StringVar() self.var.trace('w', self.changed) self.bind("<Return>", self.selection) self.bind("<Up>", self.moveUp) self.bind("<Down>", self.moveDown) self.listboxUp = False def update_content_text(self, event): w = event.widget try: index = int(w.curselection()[0]) except IndexError: return value = w.get(index) clipboard_content = autocompleteList.get(value)[0] content['text'] = clipboard_content def changed(self, name, index, mode): if self.var.get() == '': if self.listboxUp: content['text'] = '' self.listbox.destroy() self.listboxUp = False else: words = self.comparison() if words: if not self.listboxUp: self.listbox = Listbox(width=self["width"], height=self.listboxLength, font=self.listboxFontSize) self.listbox.bind('<<ListboxSelect>>', self.update_content_text) self.listbox.bind("<Return>", self.selection) self.listbox.place(x=self.winfo_x(), y=self.winfo_y() + self.winfo_height()) self.listboxUp = True self.listbox.delete(0, END) for w in words: self.listbox.insert(END, w) self.listbox.see(0) # Scroll! self.listbox.selection_set(first=0) value = self.listbox.get(ACTIVE) clipboard_content = autocompleteList.get(value)[0] content['text'] = clipboard_content else: if self.listboxUp: content['text'] = '' self.listbox.destroy() self.listboxUp = False def selection(self, event): if self.listboxUp: self.var.set(self.listbox.get(ACTIVE)) value = self.listbox.get(ACTIVE) data = autocompleteList.get(value) content = data[0] is_command = data[1] is_website = data[2] if is_command == '1': self.execute(content) elif is_website == '1': self.open_website(content) self.listbox.destroy() self.listboxUp = False self.icursor(END) self.copy_value(content) self.quit() def open_website(self, url): webbrowser.open(url) def execute(self, command): p = subprocess.Popen(command, bufsize=2048, shell=True, stdin=subprocess.PIPE) (output, err) = p.communicate() p_status = p.wait() def copy_value(self, value): clipboard.copy(value) def moveUp(self, event): if self.listboxUp: if self.listbox.curselection() == (): index = '0' else: index = self.listbox.curselection()[0] if index != '0': self.listbox.selection_clear(first=index) index = str(int(index) - 1) self.listbox.see(index) # Scroll! self.listbox.selection_set(first=index) self.listbox.activate(index) self.listbox.event_generate("<<ListboxSelect>>", when="tail") def moveDown(self, event): if self.listboxUp: if self.listbox.curselection() == (): index = '0' else: index = self.listbox.curselection()[0] if index != END: self.listbox.selection_clear(first=index) index = str(int(index) + 1) self.listbox.see(index) self.listbox.selection_set(first=index) self.listbox.activate(index) self.listbox.event_generate("<<ListboxSelect>>", when="tail") def quit(self): root.quit() def comparison(self): return [ w for w in self.autocompleteList if self.matchesFunction(self.var.get(), w) ]
class FoodGUI(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Food List Editor") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) self.columnconfigure(1, weight=1) self.columnconfigure(3, pad=7) self.rowconfigure(4, weight=1) self.rowconfigure(5, pad=7) lbl = Label(self, text="Food List") lbl.grid(sticky=W, pady=4, padx=5) abtn = Button(self, text="Add Food", command=self.sequence) abtn.grid(row=1, column=3) dbtn = Button(self, text="Delete Food", command=self.delete_food) dbtn.grid(row=2, column=3, pady=4) upbtn = Button(self, text="Refresh", command=self.update_list) upbtn.grid(row=3, column=3) cbtn = Button(self, text="Close", command=self.close_program) cbtn.grid(row=5, column=3) scrollbar = Scrollbar(self, orient="vertical") self.lb = Listbox(self, width=50, height=20,\ yscrollcommand=scrollbar.set) scrollbar.config(command=self.lb.yview) self.make_list() def make_list(self): while self.lb.size(): self.lb.delete(0) try: acts1 = open("food_list.txt") acts = acts1.readlines() acts1.close() except IOError: new_list = open("food_list.txt", 'w') new_list.close() acts1 = open("food_list.txt") acts = acts1.readlines() acts1.close() for i in acts: self.lb.insert(END, i) self.lb.bind("<<ListboxSelect>>") self.lb.place(x=5, y=25) def sequence(self): self.add_food() self.update_list() def update_list(self): del_list = open('food_list.txt') del_list2 = del_list.readlines() del_list.close() new_food_list = open('food_list.txt', 'w') for line in del_list2: if line != "\n": new_food_list.writelines(line) new_food_list.close() self.make_list() def add_food(self): if __name__ == '__main__': root2 = Tk() root2.geometry("500x200+500+300") app2 = AddFood(root2, self) root2.mainloop() def delete_food(self): del_f = self.lb.get(ACTIVE) del_list = open('food_list.txt') del_list2 = del_list.readlines() del_list.close() new_food_list = open('food_list.txt', 'w') for line in del_list2: if line != del_f: new_food_list.writelines(line) new_food_list.close() self.update_list() def close_program(self): exit(0)
class MainWindow: cam_1 = None cam_2 = None cam_3 = None gps_sensor_1 = None humansensor = None #humansensor=pexpect.spawn("echo online")#nc -v 192.168.0.2 4444") proc_server = None def __init__(self, master): self.master = master self.master.geometry("700x500") master.title("DVEM") self.label_Webcams = Label(text="Configuration of webcams", fg="#E0E0E0", bg="#18384e", font="Verdana 15 bold").grid( row=row_default, column=1, columnspan=6, sticky=Tkinter.W) List_Cams = identify_Cam.identify_Cam() #Wieder einkommentieren #List_Cams=[0] self.label_found_Webcams = Label( master, justify=LEFT, text=str(len(List_Cams)) + " webcams have been found.\nWebcam input channel (see below).") self.label_found_Webcams.grid(row=row_default + 1, column=1, columnspan=3, sticky=Tkinter.W) self.listbox_webcam = Listbox(master, width=10, height=5, exportselection=1) for item in List_Cams: self.listbox_webcam.insert(END, item) self.Fahrer = Label(text=" Fahrerkamera: ", fg="black", font="Verdana 10 bold") self.Fahrer.grid(row=row_default + 1, column=4, sticky=Tkinter.W) self.listbox_Fahrer = Listbox(master, exportselection=False, width=12, height=4) for item in List_Cams: self.listbox_Fahrer.insert(END, item) self.listbox_Fahrer.grid(row=row_default + 2, column=4, rowspan=4, sticky=Tkinter.W) self.Front = Label(text="Frontkamera: ", fg="black", font="Verdana 10 bold") self.Front.grid(row=row_default + 1, column=5, sticky=Tkinter.W) self.listbox_Front = Listbox(master, exportselection=False, width=10, height=4) for item in List_Cams: self.listbox_Front.insert(END, item) self.listbox_Front.grid(row=row_default + 2, column=5, rowspan=4, sticky=Tkinter.W) self.Heck = Label(text="Heckkamera: ", fg="black", font="Verdana 10 bold") self.Heck.grid(row=row_default + 1, column=6, sticky=Tkinter.W) self.listbox_Heck = Listbox(master, exportselection=False, width=10, height=4) for item in List_Cams: self.listbox_Heck.insert(END, item) self.listbox_Heck.grid(row=row_default + 2, column=6, rowspan=4, sticky=Tkinter.W) self.listbox_webcam.grid(row=row_default + 2, column=1, rowspan=4, sticky=Tkinter.W) self.showWebcam = Button(master, text="ShowWebcam", command=self.show_Webcam).grid( row=row_default + 6, column=1, sticky=Tkinter.W) self.label_Recording = Label(text="Start recording", fg="#E0E0E0", bg="#18384e", font="Verdana 15 bold").grid( row=row_default + 7, column=1) self.Label_Status_Web = Label(text="Status Webcams: ", font="Verdana 10 bold").grid( row=row_default + 8, column=1, sticky=Tkinter.W) self.Label_Status_Web_2 = Label(text=with_lamp, bg="snow4").grid(row=row_default + 8, column=2, sticky=Tkinter.W) self.Label_Status_GPS = Label(text="Status GPS: ", font="Verdana 10 bold").grid( row=row_default + 9, column=1, sticky=Tkinter.W) self.Label_Status_GPS_2 = Label(text=with_lamp, bg="snow4").grid(row=row_default + 9, column=2, sticky=Tkinter.W) self.Label_Status_OBD = Label(text="Status OBDBlueth: ", font="Verdana 10 bold").grid( row=row_default + 10, column=1, sticky=Tkinter.W) self.Label_Status_OBD_2 = Label(text=with_lamp, bg="snow4").grid(row=row_default + 10, column=2, sticky=Tkinter.W) self.Label_Status_Human_Sensors = Label(text="Status Human_Sensors: ", font="Verdana 10 bold").grid( row=row_default + 11, column=1, sticky=Tkinter.W) self.Label_Status_Human_Sensors_2 = Label( text=with_lamp, bg="snow4", ).grid(row=row_default + 11, column=2, sticky=Tkinter.W) self.button_Start_WEBCAMS_GPS_OBD = Button( master, bg="#356312", fg="white", text="Start: Webcams, GPS", command=self.StartWEBCAMSGPSOBD).grid(row=row_default + 12, column=1, sticky=Tkinter.W) self.kill_webcam_gps_button = Button( master, text="Terminate_Webcam_GPS_sensor", command=self.determinate_webcam_gps_sensor).grid(row=row_default + 13, column=1, sticky=Tkinter.W) self.button_Start_Human_Sensors = Button( master, bg="#356312", fg="white", text="Start: Human_Sensors,OBD", command=self.StartHumanSensor).grid(row=row_default + 15, column=1, sticky=Tkinter.W) self.kill_humansensor_button = Button( master, text="Terminate_Human_sensor", command=self.determinate_human_sensor).grid(row=row_default + 16, column=1, sticky=Tkinter.W) self.close_button = Button(master, text="Close", command=self.close_window).grid( row=row_default + 17, column=1, sticky=Tkinter.W) self.label_Recording = Label(text="Information", fg="#E0E0E0", bg="#18384e", font="Verdana 15 bold").grid( row=row_default + 18, column=1, sticky=Tkinter.W) self.gps_data = Button(master, text="Show_GPS_Data", command=self.gps_data).grid(row=row_default + 19, column=1, sticky=Tkinter.W) #Nachfolgende Button noch einbauen # self.close_button = Button(master, text="Close", command=self.close_window).grid(row=3, column=2) # self.textbox=Text(root, height=2, width=30).grid(row=2, column=1) def show_Webcam(self): try: self.label_Webcams = Label(text="Please select item", fg="snow2", bg="snow2", font="Verdana 15 bold").grid( row=row_default + 1, column=2, sticky=Tkinter.W) selected_input_channel = self.listbox_webcam.get( self.listbox_webcam.curselection() ) #Somit bekomt man das Iteam das gerade ausgewählt ist in der Listbox showWebcam.showWebcam(selected_input_channel) except: self.label_Webcams = Label(text="Please select item", fg="red", font="Verdana 15 bold").grid( row=row_default + 1, column=2, sticky=Tkinter.W) #showWebcam.showWebcam() def close_window(self): root.destroy() def determinate_human_sensor(self): print "hallochen" self.proc_server.terminate() i = 0 humansensor2 = pexpect.spawn('nc -v 192.168.0.2 4445') humansensor2.sendline("killall mate-terminal") self.Label_Status_Human_Sensors_2 = Label( text=with_lamp, bg="snow4", ).grid(row=row_default + 11, column=2, sticky=Tkinter.W) def determinate_webcam_gps_sensor(self): self.cam_1.terminate() self.cam_2.terminate() self.cam_3.terminate() self.gps_sensor_1.terminate() #Change lamp color self.Label_Status_Human_Sensors_2 = Label( text=with_lamp, bg="snow4", ).grid(row=row_default + 10, column=2, sticky=Tkinter.W) self.Label_Status_Web_2 = Label(text=with_lamp, bg="snow4").grid(row=row_default + 7, column=2, sticky=Tkinter.W) self.Label_Status_GPS_2 = Label(text=with_lamp, bg="snow4").grid(row=row_default + 8, column=2, sticky=Tkinter.W) self.Label_Status_OBD_2 = Label(text=with_lamp, bg="snow4").grid(row=row_default + 9, column=2, sticky=Tkinter.W) def StartWEBCAMSGPSOBD(self): try: self.label_Webcams = Label(text="Please select item", fg="snow2", bg="snow2", font="Verdana 15 bold").grid( row=row_default + 1, column=2, sticky=Tkinter.W) self.Label_Status_Human_Sensors_2 = Label( text=with_lamp, bg="green", ).grid(row=row_default + 10, column=2, sticky=Tkinter.W) self.Label_Status_Web_2 = Label(text=with_lamp, bg="green").grid( row=row_default + 7, column=2, sticky=Tkinter.W) self.Label_Status_GPS_2 = Label(text=with_lamp, bg="green").grid( row=row_default + 8, column=2, sticky=Tkinter.W) self.Label_Status_OBD_2 = Label(text=with_lamp, bg="green").grid( row=row_default + 9, column=2, sticky=Tkinter.W) selected_listbox_Fahrer = self.listbox_Fahrer.get( self.listbox_Fahrer.curselection()) selected_listbox_Front = self.listbox_Front.get( self.listbox_Front.curselection()) selected_listbox_Heck = self.listbox_Heck.get( self.listbox_Heck.curselection()) dir_path = os.path.dirname(os.path.realpath(__file__)) self.gps_sensor_1 = Process(target=gps_sensor.gps_signal, args=(dir_path, )) self.gps_sensor_1.start() self.cam_1 = Process(target=video.videoaufzeichnung, args=(320, 240, selected_listbox_Fahrer, 4000000, 20)) #Fahrer self.cam_1.start() self.cam_2 = Process(target=video.videoaufzeichnung, args=(960, 544, selected_listbox_Front, 4000000, 80)) #Front self.cam_2.start() self.cam_3 = Process(target=video.videoaufzeichnung, args=(432, 240, selected_listbox_Heck, 4000000, 20)) #Heck self.cam_3.start() except: self.cam_1.terminate() self.cam_2.terminate() self.cam_3.terminate() self.gps_sensor_1.terminate() print "everything is dead" def gps_data(self): gps_data_map = pexpect.spawn("chromium-browser map1.html") def StartHumanSensor(self): self.Label_Status_Human_Sensors_2 = Label( text=with_lamp, bg="green", ).grid(row=row_default + 11, column=2, sticky=Tkinter.W) parameter = "gustav" self.humansensor = pexpect.spawn('nc -v 192.168.0.2 4444') self.humansensor.sendline('cd //home') self.humansensor.sendline( 'cd //home//odroid//Desktop//DVEM_Human_Odroid//maesurement') self.humansensor.sendline(str('python HumanSensorData.py ')) self.proc_server = Process(target=server.server, args=('192.168.0.1', 55606)) self.proc_server.start() time.sleep(1)
class IniGenGui(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUIGlobals() def initUIGlobals(self): self.parent.title("Ini Generator") Style().configure("TButton", padding=(0, 0, 0, 0), font='serif 10') f1 = Frame(self) f1.grid(row=0, column=0, padx=10, sticky=N+S+E+W) f11 = LabelFrame(f1, text="Algorithms to Run") f11.grid(row=0, column=0) row = 0 self.check_algs_value_list = [] self.check_algs_map = {} for alg in algorithms: if alg == 'clean': continue check_alg_value = IntVar() check_alg = Checkbutton(f11, text=alg, variable=check_alg_value, justify=LEFT, width=25) check_alg.grid(row=row, column=0, sticky=W+E) self.check_algs_value_list.append(check_alg_value) self.check_algs_map[alg] = check_alg_value row += 1 f111 = Frame(f11) f111.grid(row=row, column=0) button_checkall = Button(f111, text="All", command=self.checkall) button_checkall.grid(row=0, column=0, sticky=W+E) button_uncheckall = Button(f111, text="None", command=self.uncheckall) button_uncheckall.grid(row=0, column=1, sticky=W+E) row = 0 f12 = Frame(f1) f12.grid(row=1, column=0, pady=20, sticky=S+W+E) f121 = LabelFrame(f12, text='Location of uPMU') f121.grid(row=0, column=0) self.radio_loc_string = StringVar() locations.append('Other Location') for loc in locations: radio_loc = Radiobutton(f121, text=loc, variable=self.radio_loc_string, value=loc, command=self.set_loc, justify=LEFT, width=25) radio_loc.grid(row=row, column=0, sticky=W+E) row += 1 self.entry_otherloc = Entry(f121) f2 = Frame(self) f2.grid(row=0, column=1, padx=10, sticky=N+S+E+W) f21 = LabelFrame(f2, text='Name of uPMU (raw)') f21.grid(row=0) row = 0 f211 = Frame(f21) f211.grid(row=row) row += 1 self.entry_namesearch = Entry(f211) self.entry_namesearch.grid(row=0, column=0, sticky=E+W) button_namesearch = Button(f211, text="Search", command=self.namesearch) button_namesearch.grid(row=0, column=1, sticky=W+E) self.lstbx_namelist = Listbox(f21) self.lstbx_namelist.bind("<Double-Button-1>", self.namelist_select) self.lstbx_namelist.grid(row=row, sticky=W+E) row += 1 f212 = Frame(f21) f212.grid(row=row) row += 1 label_nameselected = Label(f212, text="Selected:") label_nameselected.grid(row=0, column=0) self.entry_nameselected = Entry(f212, state=DISABLED) self.entry_nameselected.grid(row=0, column=1, sticky=W+E) f22 = LabelFrame(f2, text="Name of uPMU (abbr)") f22.grid(row=1, sticky=W+E, pady=10) self.entry_name = Entry(f22, width=30) self.entry_name.grid(row=0, column=0, sticky=E+W) f23 = LabelFrame(f2, text="Name of Reference uPMU (clean)") f23.grid(row=2, pady=10) row = 0 f231 = Frame(f23) f231.grid(row=row) row += 1 self.entry_refnamesearch = Entry(f231) self.entry_refnamesearch.grid(row=0, column=0, sticky=E+W) button_refnamesearch = Button(f231, text="Search", command=self.refnamesearch) button_refnamesearch.grid(row=0, column=1, sticky=W+E) self.lstbx_refnamelist = Listbox(f23) self.lstbx_refnamelist.bind("<Double-Button-1>", self.refnamelist_select) self.lstbx_refnamelist.grid(row=row, sticky=W+E) row += 1 f232 = Frame(f23) f232.grid(row=row) row += 1 label_refnameselected = Label(f232, text="Selected:") label_refnameselected.grid(row=0, column=0) self.entry_refnameselected = Entry(f232, state=DISABLED) self.entry_refnameselected.grid(row=0, column=1, sticky=W+E) button_gen = Button(self, text="Generate Files", command=self.generate_files) button_gen.grid(row=1, column=0, columnspan=2, sticky=W+E) self.pack() def generate_files(self): algs = [] for alg in self.check_algs_map: if self.check_algs_map[alg].get() == 1: algs.append(alg) if self.radio_loc_string.get() == "Other Location": location = self.entry_otherloc.get() else: location = self.radio_loc_string.get() name_raw = self.entry_nameselected.get() name = self.entry_name.get() ref_name = self.entry_refnameselected.get() uuid_map = self.get_uuid_map(name_raw) reference_uuid_map = self.get_ref_uuid_map(ref_name) IniGenAutomation(location, name_raw, name, uuid_map, ref_name, reference_uuid_map, algs) def namesearch(self): searchterm = self.entry_namesearch.get() searchphrase = '/upmu/%{0}%/%'.format(searchterm) search_results = self.search(searchterm, searchphrase) self.lstbx_namelist.delete(0, END) if len(search_results) == 0: tkMessageBox.showwarning('Search Error', 'No matches from search for \'{0}\''.format(searchterm)) else: for result in search_results: self.lstbx_namelist.insert(END, result) def refnamesearch(self): searchterm = self.entry_refnamesearch.get() searchphrase = '/Clean/%{0}%/%'.format(searchterm) search_results = self.search(searchterm, searchphrase, ref=True) self.lstbx_refnamelist.delete(0, END) if len(search_results) == 0: tkMessageBox.showwarning('Search Error', 'No matches from search for \'{0}\''.format(searchterm)) else: for result in search_results: self.lstbx_refnamelist.insert(END, result) def search(self, searchterm, searchphrase, ref=False): connection = _mysql.connect(host="128.32.37.231", port=3306, user="******", passwd="moresecuredataftw", db='upmu') connection.query("SELECT * FROM uuidpathmap WHERE path LIKE '{0}'".format(searchphrase)) results = connection.store_result() queried_data = {} result = results.fetch_row() while result != tuple(): queried_data[result[0][0]] = result[0][1] result = results.fetch_row() search_results = set() for path in queried_data: dirs = path.split('/') if ref: if searchterm in '/'.join(dirs[2:-2]): search_results.add('/'.join(dirs[2:-2])) else: if searchterm in '/'.join(dirs[2:-1]): search_results.add('/'.join(dirs[2:-1])) return search_results def set_loc(self): if self.radio_loc_string.get() == "Other Location": self.entry_otherloc.grid(sticky=W+E) else: self.entry_otherloc.grid_forget() def checkall(self): for check in self.check_algs_value_list: check.set(1) def uncheckall(self): for check in self.check_algs_value_list: check.set(0) def namelist_select(self, event): selected_index = self.lstbx_namelist.curselection() selected = self.lstbx_namelist.get(selected_index) self.entry_nameselected.configure(state=NORMAL) self.entry_nameselected.delete(0, END) self.entry_nameselected.insert(0, selected) self.entry_nameselected.configure(state=DISABLED) def refnamelist_select(self, event): selected_index = self.lstbx_refnamelist.curselection() selected = self.lstbx_refnamelist.get(selected_index) self.entry_refnameselected.configure(state=NORMAL) self.entry_refnameselected.delete(0, END) self.entry_refnameselected.insert(0, selected) self.entry_refnameselected.configure(state=DISABLED) def get_uuid_map(self, name): uuid_map = {} connection = _mysql.connect(host="128.32.37.231", port=3306, user="******", passwd="moresecuredataftw", db='upmu') connection.query("SELECT * FROM uuidpathmap WHERE path LIKE '/upmu/{0}/%'".format(name)) results = connection.store_result() result = results.fetch_row() while result != tuple(): path = result[0][0].split('/') uuid_map[path[-1]] = result[0][1] result = results.fetch_row() return uuid_map def get_ref_uuid_map(self, name): uuid_map = {} connection = _mysql.connect(host="128.32.37.231", port=3306, user="******", passwd="moresecuredataftw", db='upmu') connection.query("SELECT * FROM uuidpathmap WHERE path LIKE '/Clean/{0}/%'".format(name)) results = connection.store_result() result = results.fetch_row() while result != tuple(): path = result[0][0].split('/') uuid_map[path[-2]] = result[0][1] result = results.fetch_row() return uuid_map
class ChatMainForm(Template): ''' Class for graphic presentation of chat client. Main form with chat, list of created games, button for creating game. If you created game button becomes start game. ChatMainForm form with textbox, entry, listbox and button. ''' def __init__(self, parent,name): ''' Initialize all gui components... parent represents root of tk window name is name that client entered Creates instance of client class and starts thread for receiving messages ''' Template.__init__(self, parent) self.client = ChatClient.ChatClient() #where to put try block here or in connect method self.client.connect_to_server() self.end = False #for stopping receiving thread self.name = name #start new thread self.thread=thread.start_new_thread( self.receive_server_messages, (1,) )#!!!doesn't work without second argument #send first message with name self.client.send_message(self.name) self.parent = parent self.initUI() def initUI(self): ''' Initialize all gui components ''' self.nameText = Label(self, text="Chat") self.nameText.place(x=270, y=10) self.nameText3 = Label(self, text="Players in game") self.nameText3.place(x=50,y=10) self.nameText2 = Label(self, text="Game list ")# **********Popravi ovo!!!!!!******** self.nameText2.place(x=50,y=10) #display chat messages self.messageDispley = Text(self,font=tkFont.Font(family="Calibri",size=10),width=28,height=13) self.messageDispley.place(x=270, y=40) self.messageDispley.insert(END,"Welcome...\n") #write text messages self.message = StringVar() self.messageText =Entry(self, textvariable=self.message, width=28) self.messageText.place(x=270, y=275) #send chat massage self.nameButton = Button(self, text="Send", width=26, command=self.send_chat_message) self.nameButton.place(x=270, y=300) #lists players in specific game self.playersList = Listbox(self) self.playersList.place(x=50, y=30) #lists all games self.gameList = Listbox(self) self.gameList.place(x=50, y=30) #join created game self.joinGameButton = Button(self,text="Join game",width=15, command=self.send_join_message) self.joinGameButton.place(x=50, y=230) #start created game self.startGameButton = Button(self,text="Start game",width=15, command=self.send_game_start_message) self.startGameButton.place(x=50, y=270) #create new game self.createGameButton = Button(self,text="Create new game",width=15, command=self.create_new_game) self.createGameButton.place(x=50, y=270) def send_game_start_message(self): ''' Sends signal to server that game is starting ''' self.startGameButton.config(state=DISABLED) self.client.send_message("Start game") def send_join_message(self): ''' Hides 'create new game' and 'Join game' buttons and shows 'Players list' listbox. Send message with selected game to server ''' #first we think you can join self.canJoin = True items = self.gameList.curselection() #if nothing is selected if items == tuple(): return # creating xml document to be send root2 = etree.Element("JoinGame") ge = etree.SubElement(root2, "game").text = self.gameList.get(items[0]) self.client.send_message(etree.tostring(root2)) #join massage send self.joinEvent.clear() #first receive_server_messages thread needs to finish processing message from server self.joinEvent.wait() print "BUHA" #if we don't receive message from server we hide fields if self.canJoin: self.joinGameButton.place_forget() self.createGameButton.place_forget() self.gameList.place_forget() self.nameText2.place_forget() self.startGameButton.place_forget() def create_new_game(self): ''' Hides 'create new game' and 'Join game' buttons and shows 'Start game' button and 'Players list' listbox. ''' self.joinGameButton.place_forget() self.createGameButton.place_forget() self.gameList.place_forget() self.nameText2.place_forget() self.startGameButton.place(x=50, y=270) #can't start until somebody joins self.startGameButton.config(state=DISABLED) self.client.send_message("Create game") def send_chat_message(self): ''' sends chat message to server if message is 'Bye' ends program**to be changed** ''' # creating xml document to be send root2 = etree.Element("ChatMessage") etree.SubElement(root2, "message").text = self.message.get() self.client.send_message(etree.tostring(root2)) if self.message.get() =='Bye': print 'sss' self.client.comSocket.close self.end = True self.parent.destroy() self.message.set('') def find_next_player_index(self,currentPlayerIndex): ''' finds index of next player on turn in playersList ''' index = currentPlayerIndex + 1 if index == len(self.game.playersList): index = 0 while index != currentPlayerIndex: #print self.game.playersList[index].isOut #print type(self.game.playersList[index].isOut) if index == len(self.game.playersList): index = 0 if str(self.game.playersList[index].isOut) == 'false': #print 'aaaaaaaaa' break else: index += 1; #print index return index def start_game(self,id): try: white = (255, 255, 255) # Call this function so the Pygame library can initialize itself pygame.init() # Create an 800x600 sized screen self.screen = pygame.display.set_mode([800, 600]) # This sets the name of the window pygame.display.set_caption('Fingers game') clock = pygame.time.Clock() done = False firstClick = True secondClick = False # waits until process_message finish with game object self.gameStateEvent.wait() currentPlayer = self.game.playersList[self.game.ourIndex]; ourField = currentPlayer.field nextField = None hitting = None hitted = None print "AAAAAAAAAAA" while done == False: clock.tick(10) nextIndex = self.find_next_player_index(self.game.ourIndex) nextPlayer = self.game.playersList[nextIndex] nextField = nextPlayer.field for event in pygame.event.get(): if event.type == pygame.QUIT: #enable all filed for choosing game self.createGameButton.place(x=50, y=270) self.joinGameButton.place(x=50, y=230) self.nameText2.place(x=50,y=10) self.gameList.place(x=50, y=30) self.initialGameState = True self.game = None self.client.send_message("QUIT") pygame.quit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos # if game is over we can't play if self.game.gameOver == 'false': if self.client.comSocket.getsockname()[1] == self.game.playerTurn: if firstClick: # check if left hand picture is clicked if ourField.image1.get_rect(center=ourField.get_centers()[0]).collidepoint(x, y): hitting = 'left' firstClick = False secondClick = True # check if right hand picture is clicked elif ourField.image2.get_rect(center=ourField.get_centers()[1]).collidepoint(x, y): hitting = 'right' firstClick = False secondClick = True elif secondClick: # check if left hand picture is clicked if nextField.image1.get_rect(center=nextField.get_centers()[0]).collidepoint(x, y) and nextPlayer.fingersLeft != 0: hitted = 'left' secondClick = False #this turn over reset firstClick and secondClick firstClick = True secondClick = False self.send_move_message(hitting, hitted) # check if right hand picture is clicked elif nextField.image2.get_rect(center=nextField.get_centers()[1]).collidepoint(x, y) and nextPlayer.fingersRight != 0: hitted = 'right' secondClick = False #this turn over reset firstClick and secondClick firstClick = True secondClick = False self.send_move_message(hitting, hitted) #check if second hand is from same player and if separation is possible elif ourField.image1.get_rect(center=ourField.get_centers()[0]).collidepoint(x, y): if currentPlayer.fingersRight == 0 and (currentPlayer.fingersLeft == 2 or currentPlayer.fingersLeft == 4): hitted = 'separation' secondClick = False print "SANJA" #this turn over reset firstClick and secondClick firstClick = True secondClick = False self.send_move_message(hitting, hitted) else: firstClick = True elif ourField.image2.get_rect(center=ourField.get_centers()[1]).collidepoint(x, y): print "BUHA1" print currentPlayer.fingersLeft if currentPlayer.fingersLeft == 0 and (currentPlayer.fingersRight== 2 or currentPlayer.fingersRight == 4): print "SANJA" hitted = 'separation' secondClick = False #this turn over reset firstClick and secondClick firstClick = True secondClick = False self.send_move_message(hitting, hitted) else: firstClick = True #write text on screen myfont = pygame.font.SysFont("Comic Sans MS", 20) winnerFont = pygame.font.SysFont("Comic Sans MS", 36) #refresh screen self.screen.fill((0, 0, 0)) if self.game.gameOver == 'true': if not self.all_out(): labelWinner = winnerFont.render("**** Game over ****", 1, white) labelWinner2 = winnerFont.render("**** somebody left :( *****", 1, white) else: labelWinner = winnerFont.render("*****Winner is " + self.return_winner_name() + " *****", 1, white) labelWinner2 = winnerFont.render(" ", 1, white) self.screen.blit(labelWinner, (180, 220)) self.screen.blit(labelWinner2, (180, 250)) label1 = myfont.render("You: " + self.game.playersList[self.game.ourIndex].playerName, 1, white) label2 = myfont.render("Players turn: " + self.game.playersList[self.game.find_index(self.game.playerTurn)].playerName, 1, white) #add text self.screen.blit(label1, (40, 450)) self.screen.blit(label2, (40, 480)) #draw hands self.game.draw_state(self.screen) pygame.display.flip() except: traceback.print_exc() def all_out(self): ''' checks if only one player is left in game ''' return len([x for x in self.game.playersList if x.isOut == 'false']) == 1 def return_winner_name(self): ''' returns winers name ''' return next(x.playerName for x in self.game.playersList if x.isOut == 'false') def send_move_message(self,hitting,hitted): ''' creates and sends move message based on hitting and hitted hands ''' xmlroot = etree.Element("Move") etree.SubElement(xmlroot, "playerPlayed").text = str(self.game.playerTurn) etree.SubElement(xmlroot, "hittingHand").text = hitting etree.SubElement(xmlroot, "hittedHand").text = hitted print etree.tostring(xmlroot) self.client.send_message(etree.tostring(xmlroot)) def process_message(self): ''' Recieve xml data as parameter and calls appropriate methods for specific type of messges ''' messageType = self.root.tag if messageType == "ChatMessage": self.messageDispley.insert(END,self.root[0].text+'\n') # if game is full we receive message and set shared object canJoin to false if self.root[0].text.startswith('Unable to join'): print "SANJA" self.canJoin = False #unable to join massage processed so enable joinEvent, self.joinEvent.set() #trying to start game ****TO BE CHANGED*** if self.root[0].text.startswith('Start game'): self.game = None self.gameThread = thread.start_new_thread(self.start_game, (2,)) elif messageType == "ListOfGames": #****Mora posebna metoda koja nema parametre jedino tako radi*** self.list_all_games(self.gameList) elif messageType == "ListOfPlayers": self.list_all_games(self.playersList) #if there is more then tow players in game enable startGameButton if len(self.playersList.get(0, END)) > 1: self.startGameButton.config(state=NORMAL) elif messageType == "GameState": if self.initialGameState: self.gameStateEvent.clear() self.game = GameState(self.root,self.client.comSocket.getsockname()[1]) self.gameStateEvent.set() self.initialGameState = False else: self.game.changeGameState(self.root) print str(self.game.playersList[self.game.ourIndex].fingersRight) + '->' + self.game.playersList[self.game.ourIndex].playerName else: print "Error while processing massages" def list_all_games(self,listBox): ''' Reads all <game> elements from xml and shows them in gameList listbox ''' #******Ovov nekad radi nekad ne********* lis = [] print self.root[0] for el in iter(self.root[0]): lis.append(el.text) listBox.delete(0, END) for e in lis: #t = e.text listBox.insert(END,e) def receive_server_messages(self,id): ''' receives messages while main thread is running ''' #event must be defined here because in process_message we # create another event for every message, no good. self.gameStateEvent = threading.Event() #creating event for disabling thread while event is not set self.joinEvent = threading.Event() self.initialGameState = True while not self.end: try: mes = self.client.comSocket.recv(1024) # http://lxml.de/tutorial.html print mes + '*****' self.root = etree.fromstring(mes) self.gameStateEvent.clear() self.process_message() #massage processed so enable joinEvent, self.joinEvent.set() except: traceback.print_exc()
class ChooseNameUI(Frame): def __init__(self, parent,names=["1","2","3"]): Frame.__init__(self, parent) self.parent = parent self.names = names self.initUI() self.centerWindow() def initUI(self): self.parent.title("选择角色名字") self.pack(fill=BOTH, expand=1) "source list" self.lb = Listbox(self) for i in self.names: self.lb.insert(END, i) self.lb.bind("<<ListboxSelect>>", self.onSelect) self.lb.place(x=80, y=20) "right list" self.lbRight = Listbox(self) #self.lbRight.bind("<<ListboxSelect>>", self.onSelect) self.lbRight.place(x=150, y=240) "left list" self.lbLeft = Listbox(self) #self.lbLeft.bind("<<ListboxSelect>>", self.onSelect) self.lbLeft.place(x=20, y=240) "label" self.var = StringVar() self.label = Label(self, text=0, textvariable=self.var) self.label.place(x=120, y=400) "left button" leftButton = Button(self, text="增加到自己的名字", command=self.leftClick) leftButton.place(x=20,y=180) "left add all button" leftAddAllBtn = Button(self, text="添加剩下的名字到自己", command=self.leftAddAllClick) leftAddAllBtn.place(x=20,y=210) "right button" rightButton = Button(self, text="增加到对方的名字", command=self.rightClick) rightButton.place(x = 150, y = 180) "right add all button" rightAddAllBtn = Button(self, text="添加剩下的名字到对方", command=self.rightAddAllClick) rightAddAllBtn.place(x=150,y=210) "move to right button" left2RightBtn = Button(self, text="移动到自己", command=self.move2Left) left2RightBtn.place(x=150,y=380) "move to left button" left2RightBtn = Button(self, text="移动到对方", command=self.move2Right) left2RightBtn.place(x=20,y=380) "finish button" self.finishBtn = Button(self, text="选择完毕", command = self.finishClick) self.finishBtn.place(x = 120 , y = 420) def onSelect(self, val): sender = val.widget idx = sender.curselection() if idx: value = sender.get(idx) self.var.set(value) def leftClick(self): str = self.var.get() if str is not None and str != "": self.lbLeft.insert(END,str) self.removeSelection() def rightClick(self): str = self.var.get() if str is not None and str != "": self.lbRight.insert(END,str) self.removeSelection() def removeSelection(self): index = self.lb.curselection() self.lb.delete(index,index) self.var.set("") "if select all data finish" if not self.lb.get(0): self.finishClick() def finishClick(self): if self.lb.get(0): box.showerror("错误", "还有名字没加入") else: if not self.lbLeft.get(0): box.showerror("错误", "没有自己的名字,请选择") elif not self.lbRight.get(0): box.showerror("错误", "没有对方的名字,请选择") else: "get the two list and generate json" myList = [self.lbLeft.get(i) for i in xrange(self.lbLeft.size())] herList = [self.lbRight.get(i) for i in xrange(self.lbRight.size())] #conversationtool.generateJSON(myList,herList) t = conversationtool.generateThread(myList,herList) t.start() t.join() def rightAddAllClick(self): while self.lb.get(0): value = self.lb.get(0) self.lb.delete(0) self.lbRight.insert(END , value) self.var.set("") def leftAddAllClick(self): while self.lb.get(0): value = self.lb.get(0) self.lb.delete(0) self.lbLeft.insert(END,value) self.var.set("") def move2Right(self): index = self.lbLeft.curselection() if index: value = self.lbLeft.get(index) self.lbLeft.delete(index) self.lbRight.insert(END, value) else: box.showerror("错误", "请选择自己的名字") def move2Left(self): index = self.lbRight.curselection() if index: value = self.lbRight.get(index) self.lbRight.delete(index) self.lbLeft.insert(END , value) else: box.showerror("错误", "请选择对方的名字") def centerWindow(self): w = 300 h = 450 sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() x = (sw - w)/2 y = (sh - h)/2 self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
class AutocompleteEntry(Entry): def __init__(self, *args, **kwargs): Entry.__init__(self, width=100, *args, **kwargs) self.focus_set() self.pack() self.var = self["textvariable"] if self.var == '': self.var = self["textvariable"] = StringVar() self.var.trace('w', self.changed) self.bind("<Right>", self.selection) self.bind("<Up>", self.up) self.bind("<Down>", self.down) self.bind("<Return>", self.enter) self.lb_up = False self.lb = None def enter(self, event): print event def changed(self, name, index, mode): if self.var.get() == '': if self.lb: self.lb.destroy() self.lb_up = False else: words = self.comparison() if words: if not self.lb_up: self.lb = Listbox(master=root, width=100) self.lb.bind("<Double-Button-1>", self.selection) self.lb.bind("<Right>", self.selection) self.lb.place(x=self.winfo_x(), y=self.winfo_y()+self.winfo_height()) self.lb_up = True self.lb.delete(0, END) for w in words: self.lb.insert(END,w) else: if self.lb_up: self.lb.destroy() self.lb_up = False def selection(self, _): if self.lb_up: self.var.set(self.lb.get(ACTIVE)) self.lb.destroy() self.lb_up = False self.icursor(END) def up(self, _): if self.lb_up: if self.lb.curselection() == (): index = '0' else: index = self.lb.curselection()[0] if index != '0': self.lb.selection_clear(first=index) index = str(int(index)-1) self.lb.selection_set(first=index) self.lb.activate(index) def down(self, _): if self.lb_up: if self.lb.curselection() == (): index = '0' else: index = self.lb.curselection()[0] if index != END: self.lb.selection_clear(first=index) index = str(int(index)+1) self.lb.selection_set(first=index) self.lb.activate(index) def comparison(self): q = self.var.get() q = unicode(q.decode('utf8')) for hit in searcher.search(qp.parse(q), limit=50): if hit['author']: yield '%s. "%s"' % (hit['author'], hit['title']) else: yield hit['title']
class Ordered_Listbox(Frame): def __init__(self, master, data=None, ascending_order = True, ignore_case=False, autoscroll=False, vscrollbar=True, hscrollbar=False, scrollbar_background=None, scrollbar_troughcolor=None, **kwargs): Frame.__init__(self, master) self._ignore_case = ignore_case self._ascending_order = ascending_order master.grid_rowconfigure(0, weight=1) master.grid_columnconfigure(0, weight=1) self._listbox = Listbox(self, *kwargs) self._listbox.grid(row=0, column=0, sticky= N+E+W+S) scrollbar_kwargs = {} if scrollbar_background is not None: scrollbar_kwargs["background"] = scrollbar_background if scrollbar_troughcolor is not None: scrollbar_kwargs["throughcolor"] = scrollbar_troughcolor if vscrollbar: self._vbar=Scrollbar(self,takefocus=0, command=self._listbox.yview, **scrollbar_kwargs) self._vbar.grid(row=0, column=1, sticky= N+S) if autoscroll: self._listbox.config(yscrollcommand=lambda f, l: make_autoscroll(self._vbar, f, l)) else: self._listbox.config(yscrollcommand=self._vbar.set) if hscrollbar: self._hbar=Scrollbar(self,takefocus=0, command=self._listbox.xview, **scrollbar_kwargs) self._hbar.grid(row=0, column=1, sticky= E+W) if autoscroll: self._listbox.config(xscrollcommand=lambda f, l: make_autoscroll(self._hbar, f, l)) else: self._listbox.config(xscrollcommand=self._hbar.set) if data is not None: for item in data: self.add_item(item) def add_item(self, item): list_of_items = self._listbox.get(0, END) index = bisect(list_of_items, item, ignore_case=self._ignore_case, ascending_order=self._ascending_order) self._listbox.insert(index, item) def delete_item(self, item): list_of_items = self._listbox.get(0, END) index = bisect(list_of_items, item, ignore_case=self._ignore_case, ascending_order=self._ascending_order) self._listbox.delete(index-1) def selected_items(self): list_of_items = [] for index in self._listbox.curselection(): list_of_items.append(self._listbox.get(index)) return list_of_items def selected_item(self): return self._listbox.curselection()[0] def deselect_all(self): self._listbox.selection_clear(0, END) def select(self, item): index = self.index(item) if index is None: return self._listbox.selection_set(index) def deselect(self, item): index = self.index(item) if index is None: return self._listbox.selection_clear(index) def index(self, item): list_of_items = self._listbox.get(0, END) try: index = list_of_items.index(item) except ValueError: return None return index def bind(self, event, handler): self._listbox.bind(event, handler) def clear(self): self._listbox.delete(1,END) def __iter__(self): return self.items @property def items(self): return self._listbox.get(0, END)
class GetKeysDialog(Toplevel): def __init__(self,parent,title,action,currentKeySequences,_htest=False): """ action - string, the name of the virtual event these keys will be mapped to currentKeys - list, a list of all key sequence lists currently mapped to virtual events, for overlap checking _htest - bool, change box location when running htest """ Toplevel.__init__(self, parent) self.configure(borderwidth=5) self.resizable(height=FALSE,width=FALSE) self.title(title) self.transient(parent) self.grab_set() self.protocol("WM_DELETE_WINDOW", self.Cancel) self.parent = parent self.action=action self.currentKeySequences=currentKeySequences self.result='' self.keyString=StringVar(self) self.keyString.set('') self.SetModifiersForPlatform() # set self.modifiers, self.modifier_label self.modifier_vars = [] for modifier in self.modifiers: variable = StringVar(self) variable.set('') self.modifier_vars.append(variable) self.advanced = False self.CreateWidgets() self.LoadFinalKeyList() self.withdraw() #hide while setting geometry self.update_idletasks() self.geometry( "+%d+%d" % ( parent.winfo_rootx() + (parent.winfo_width()/2 - self.winfo_reqwidth()/2), parent.winfo_rooty() + ((parent.winfo_height()/2 - self.winfo_reqheight()/2) if not _htest else 150) ) ) #centre dialog over parent (or below htest box) self.deiconify() #geometry set, unhide self.wait_window() def CreateWidgets(self): frameMain = Frame(self,borderwidth=2,relief=SUNKEN) frameMain.pack(side=TOP,expand=TRUE,fill=BOTH) frameButtons=Frame(self) frameButtons.pack(side=BOTTOM,fill=X) self.buttonOK = Button(frameButtons,text='OK', width=8,command=self.OK) self.buttonOK.grid(row=0,column=0,padx=5,pady=5) self.buttonCancel = Button(frameButtons,text='Cancel', width=8,command=self.Cancel) self.buttonCancel.grid(row=0,column=1,padx=5,pady=5) self.frameKeySeqBasic = Frame(frameMain) self.frameKeySeqAdvanced = Frame(frameMain) self.frameControlsBasic = Frame(frameMain) self.frameHelpAdvanced = Frame(frameMain) self.frameKeySeqAdvanced.grid(row=0,column=0,sticky=NSEW,padx=5,pady=5) self.frameKeySeqBasic.grid(row=0,column=0,sticky=NSEW,padx=5,pady=5) self.frameKeySeqBasic.lift() self.frameHelpAdvanced.grid(row=1,column=0,sticky=NSEW,padx=5) self.frameControlsBasic.grid(row=1,column=0,sticky=NSEW,padx=5) self.frameControlsBasic.lift() self.buttonLevel = Button(frameMain,command=self.ToggleLevel, text='Advanced Key Binding Entry >>') self.buttonLevel.grid(row=2,column=0,stick=EW,padx=5,pady=5) labelTitleBasic = Label(self.frameKeySeqBasic, text="New keys for '"+self.action+"' :") labelTitleBasic.pack(anchor=W) labelKeysBasic = Label(self.frameKeySeqBasic,justify=LEFT, textvariable=self.keyString,relief=GROOVE,borderwidth=2) labelKeysBasic.pack(ipadx=5,ipady=5,fill=X) self.modifier_checkbuttons = {} column = 0 for modifier, variable in zip(self.modifiers, self.modifier_vars): label = self.modifier_label.get(modifier, modifier) check=Checkbutton(self.frameControlsBasic, command=self.BuildKeyString, text=label,variable=variable,onvalue=modifier,offvalue='') check.grid(row=0,column=column,padx=2,sticky=W) self.modifier_checkbuttons[modifier] = check column += 1 labelFnAdvice=Label(self.frameControlsBasic,justify=LEFT, text=\ "Select the desired modifier keys\n"+ "above, and the final key from the\n"+ "list on the right.\n\n" + "Use upper case Symbols when using\n" + "the Shift modifier. (Letters will be\n" + "converted automatically.)") labelFnAdvice.grid(row=1,column=0,columnspan=4,padx=2,sticky=W) self.listKeysFinal=Listbox(self.frameControlsBasic,width=15,height=10, selectmode=SINGLE) self.listKeysFinal.bind('<ButtonRelease-1>',self.FinalKeySelected) self.listKeysFinal.grid(row=0,column=4,rowspan=4,sticky=NS) scrollKeysFinal=Scrollbar(self.frameControlsBasic,orient=VERTICAL, command=self.listKeysFinal.yview) self.listKeysFinal.config(yscrollcommand=scrollKeysFinal.set) scrollKeysFinal.grid(row=0,column=5,rowspan=4,sticky=NS) self.buttonClear=Button(self.frameControlsBasic, text='Clear Keys',command=self.ClearKeySeq) self.buttonClear.grid(row=2,column=0,columnspan=4) labelTitleAdvanced = Label(self.frameKeySeqAdvanced,justify=LEFT, text="Enter new binding(s) for '"+self.action+"' :\n"+ "(These bindings will not be checked for validity!)") labelTitleAdvanced.pack(anchor=W) self.entryKeysAdvanced=Entry(self.frameKeySeqAdvanced, textvariable=self.keyString) self.entryKeysAdvanced.pack(fill=X) labelHelpAdvanced=Label(self.frameHelpAdvanced,justify=LEFT, text="Key bindings are specified using Tkinter keysyms as\n"+ "in these samples: <Control-f>, <Shift-F2>, <F12>,\n" "<Control-space>, <Meta-less>, <Control-Alt-Shift-X>.\n" "Upper case is used when the Shift modifier is present!\n\n" + "'Emacs style' multi-keystroke bindings are specified as\n" + "follows: <Control-x><Control-y>, where the first key\n" + "is the 'do-nothing' keybinding.\n\n" + "Multiple separate bindings for one action should be\n"+ "separated by a space, eg., <Alt-v> <Meta-v>." ) labelHelpAdvanced.grid(row=0,column=0,sticky=NSEW) def SetModifiersForPlatform(self): """Determine list of names of key modifiers for this platform. The names are used to build Tk bindings -- it doesn't matter if the keyboard has these keys, it matters if Tk understands them. The order is also important: key binding equality depends on it, so config-keys.def must use the same ordering. """ if sys.platform == "darwin": self.modifiers = ['Shift', 'Control', 'Option', 'Command'] else: self.modifiers = ['Control', 'Alt', 'Shift'] self.modifier_label = {'Control': 'Ctrl'} # short name def ToggleLevel(self): if self.buttonLevel.cget('text')[:8]=='Advanced': self.ClearKeySeq() self.buttonLevel.config(text='<< Basic Key Binding Entry') self.frameKeySeqAdvanced.lift() self.frameHelpAdvanced.lift() self.entryKeysAdvanced.focus_set() self.advanced = True else: self.ClearKeySeq() self.buttonLevel.config(text='Advanced Key Binding Entry >>') self.frameKeySeqBasic.lift() self.frameControlsBasic.lift() self.advanced = False def FinalKeySelected(self,event): self.BuildKeyString() def BuildKeyString(self): keyList = modifiers = self.GetModifiers() finalKey = self.listKeysFinal.get(ANCHOR) if finalKey: finalKey = self.TranslateKey(finalKey, modifiers) keyList.append(finalKey) self.keyString.set('<' + string.join(keyList,'-') + '>') def GetModifiers(self): modList = [variable.get() for variable in self.modifier_vars] return [mod for mod in modList if mod] def ClearKeySeq(self): self.listKeysFinal.select_clear(0,END) self.listKeysFinal.yview(MOVETO, '0.0') for variable in self.modifier_vars: variable.set('') self.keyString.set('') def LoadFinalKeyList(self): #these tuples are also available for use in validity checks self.functionKeys=('F1','F2','F2','F4','F5','F6','F7','F8','F9', 'F10','F11','F12') self.alphanumKeys=tuple(string.ascii_lowercase+string.digits) self.punctuationKeys=tuple('~!@#%^&*()_-+={}[]|;:,.<>/?') self.whitespaceKeys=('Tab','Space','Return') self.editKeys=('BackSpace','Delete','Insert') self.moveKeys=('Home','End','Page Up','Page Down','Left Arrow', 'Right Arrow','Up Arrow','Down Arrow') #make a tuple of most of the useful common 'final' keys keys=(self.alphanumKeys+self.punctuationKeys+self.functionKeys+ self.whitespaceKeys+self.editKeys+self.moveKeys) self.listKeysFinal.insert(END, *keys) def TranslateKey(self, key, modifiers): "Translate from keycap symbol to the Tkinter keysym" translateDict = {'Space':'space', '~':'asciitilde','!':'exclam','@':'at','#':'numbersign', '%':'percent','^':'asciicircum','&':'ampersand','*':'asterisk', '(':'parenleft',')':'parenright','_':'underscore','-':'minus', '+':'plus','=':'equal','{':'braceleft','}':'braceright', '[':'bracketleft',']':'bracketright','|':'bar',';':'semicolon', ':':'colon',',':'comma','.':'period','<':'less','>':'greater', '/':'slash','?':'question','Page Up':'Prior','Page Down':'Next', 'Left Arrow':'Left','Right Arrow':'Right','Up Arrow':'Up', 'Down Arrow': 'Down', 'Tab':'Tab'} if key in translateDict.keys(): key = translateDict[key] if 'Shift' in modifiers and key in string.ascii_lowercase: key = key.upper() key = 'Key-' + key return key def OK(self, event=None): if self.advanced or self.KeysOK(): # doesn't check advanced string yet self.result=self.keyString.get() self.destroy() def Cancel(self, event=None): self.result='' self.destroy() def KeysOK(self): '''Validity check on user's 'basic' keybinding selection. Doesn't check the string produced by the advanced dialog because 'modifiers' isn't set. ''' keys = self.keyString.get() keys.strip() finalKey = self.listKeysFinal.get(ANCHOR) modifiers = self.GetModifiers() # create a key sequence list for overlap check: keySequence = keys.split() keysOK = False title = 'Key Sequence Error' if not keys: tkMessageBox.showerror(title=title, parent=self, message='No keys specified.') elif not keys.endswith('>'): tkMessageBox.showerror(title=title, parent=self, message='Missing the final Key') elif (not modifiers and finalKey not in self.functionKeys + self.moveKeys): tkMessageBox.showerror(title=title, parent=self, message='No modifier key(s) specified.') elif (modifiers == ['Shift']) \ and (finalKey not in self.functionKeys + self.moveKeys + ('Tab', 'Space')): msg = 'The shift modifier by itself may not be used with'\ ' this key symbol.' tkMessageBox.showerror(title=title, parent=self, message=msg) elif keySequence in self.currentKeySequences: msg = 'This key combination is already in use.' tkMessageBox.showerror(title=title, parent=self, message=msg) else: keysOK = True return keysOK
class GetKeysDialog(Toplevel): def __init__(self, parent, title, action, currentKeySequences, _htest=False): """ action - string, the name of the virtual event these keys will be mapped to currentKeys - list, a list of all key sequence lists currently mapped to virtual events, for overlap checking _htest - bool, change box location when running htest """ Toplevel.__init__(self, parent) self.configure(borderwidth=5) self.resizable(height=FALSE, width=FALSE) self.title(title) self.transient(parent) self.grab_set() self.protocol("WM_DELETE_WINDOW", self.Cancel) self.parent = parent self.action = action self.currentKeySequences = currentKeySequences self.result = '' self.keyString = StringVar(self) self.keyString.set('') self.SetModifiersForPlatform( ) # set self.modifiers, self.modifier_label self.modifier_vars = [] for modifier in self.modifiers: variable = StringVar(self) variable.set('') self.modifier_vars.append(variable) self.advanced = False self.CreateWidgets() self.LoadFinalKeyList() self.withdraw() #hide while setting geometry self.update_idletasks() self.geometry("+%d+%d" % (parent.winfo_rootx() + (parent.winfo_width() / 2 - self.winfo_reqwidth() / 2), parent.winfo_rooty() + ((parent.winfo_height() / 2 - self.winfo_reqheight() / 2) if not _htest else 150)) ) #centre dialog over parent (or below htest box) self.deiconify() #geometry set, unhide self.wait_window() def CreateWidgets(self): frameMain = Frame(self, borderwidth=2, relief=SUNKEN) frameMain.pack(side=TOP, expand=TRUE, fill=BOTH) frameButtons = Frame(self) frameButtons.pack(side=BOTTOM, fill=X) self.buttonOK = Button(frameButtons, text='OK', width=8, command=self.OK) self.buttonOK.grid(row=0, column=0, padx=5, pady=5) self.buttonCancel = Button(frameButtons, text='Cancel', width=8, command=self.Cancel) self.buttonCancel.grid(row=0, column=1, padx=5, pady=5) self.frameKeySeqBasic = Frame(frameMain) self.frameKeySeqAdvanced = Frame(frameMain) self.frameControlsBasic = Frame(frameMain) self.frameHelpAdvanced = Frame(frameMain) self.frameKeySeqAdvanced.grid(row=0, column=0, sticky=NSEW, padx=5, pady=5) self.frameKeySeqBasic.grid(row=0, column=0, sticky=NSEW, padx=5, pady=5) self.frameKeySeqBasic.lift() self.frameHelpAdvanced.grid(row=1, column=0, sticky=NSEW, padx=5) self.frameControlsBasic.grid(row=1, column=0, sticky=NSEW, padx=5) self.frameControlsBasic.lift() self.buttonLevel = Button(frameMain, command=self.ToggleLevel, text='Advanced Key Binding Entry >>') self.buttonLevel.grid(row=2, column=0, stick=EW, padx=5, pady=5) labelTitleBasic = Label(self.frameKeySeqBasic, text="New keys for '" + self.action + "' :") labelTitleBasic.pack(anchor=W) labelKeysBasic = Label(self.frameKeySeqBasic, justify=LEFT, textvariable=self.keyString, relief=GROOVE, borderwidth=2) labelKeysBasic.pack(ipadx=5, ipady=5, fill=X) self.modifier_checkbuttons = {} column = 0 for modifier, variable in zip(self.modifiers, self.modifier_vars): label = self.modifier_label.get(modifier, modifier) check = Checkbutton(self.frameControlsBasic, command=self.BuildKeyString, text=label, variable=variable, onvalue=modifier, offvalue='') check.grid(row=0, column=column, padx=2, sticky=W) self.modifier_checkbuttons[modifier] = check column += 1 labelFnAdvice=Label(self.frameControlsBasic,justify=LEFT, text=\ "Select the desired modifier keys\n"+ "above, and the final key from the\n"+ "list on the right.\n\n" + "Use upper case Symbols when using\n" + "the Shift modifier. (Letters will be\n" + "converted automatically.)") labelFnAdvice.grid(row=1, column=0, columnspan=4, padx=2, sticky=W) self.listKeysFinal = Listbox(self.frameControlsBasic, width=15, height=10, selectmode=SINGLE) self.listKeysFinal.bind('<ButtonRelease-1>', self.FinalKeySelected) self.listKeysFinal.grid(row=0, column=4, rowspan=4, sticky=NS) scrollKeysFinal = Scrollbar(self.frameControlsBasic, orient=VERTICAL, command=self.listKeysFinal.yview) self.listKeysFinal.config(yscrollcommand=scrollKeysFinal.set) scrollKeysFinal.grid(row=0, column=5, rowspan=4, sticky=NS) self.buttonClear = Button(self.frameControlsBasic, text='Clear Keys', command=self.ClearKeySeq) self.buttonClear.grid(row=2, column=0, columnspan=4) labelTitleAdvanced = Label( self.frameKeySeqAdvanced, justify=LEFT, text="Enter new binding(s) for '" + self.action + "' :\n" + "(These bindings will not be checked for validity!)") labelTitleAdvanced.pack(anchor=W) self.entryKeysAdvanced = Entry(self.frameKeySeqAdvanced, textvariable=self.keyString) self.entryKeysAdvanced.pack(fill=X) labelHelpAdvanced = Label( self.frameHelpAdvanced, justify=LEFT, text="Key bindings are specified using Tkinter keysyms as\n" + "in these samples: <Control-f>, <Shift-F2>, <F12>,\n" "<Control-space>, <Meta-less>, <Control-Alt-Shift-X>.\n" "Upper case is used when the Shift modifier is present!\n\n" + "'Emacs style' multi-keystroke bindings are specified as\n" + "follows: <Control-x><Control-y>, where the first key\n" + "is the 'do-nothing' keybinding.\n\n" + "Multiple separate bindings for one action should be\n" + "separated by a space, eg., <Alt-v> <Meta-v>.") labelHelpAdvanced.grid(row=0, column=0, sticky=NSEW) def SetModifiersForPlatform(self): """Determine list of names of key modifiers for this platform. The names are used to build Tk bindings -- it doesn't matter if the keyboard has these keys, it matters if Tk understands them. The order is also important: key binding equality depends on it, so config-keys.def must use the same ordering. """ if sys.platform == "darwin": self.modifiers = ['Shift', 'Control', 'Option', 'Command'] else: self.modifiers = ['Control', 'Alt', 'Shift'] self.modifier_label = {'Control': 'Ctrl'} # short name def ToggleLevel(self): if self.buttonLevel.cget('text')[:8] == 'Advanced': self.ClearKeySeq() self.buttonLevel.config(text='<< Basic Key Binding Entry') self.frameKeySeqAdvanced.lift() self.frameHelpAdvanced.lift() self.entryKeysAdvanced.focus_set() self.advanced = True else: self.ClearKeySeq() self.buttonLevel.config(text='Advanced Key Binding Entry >>') self.frameKeySeqBasic.lift() self.frameControlsBasic.lift() self.advanced = False def FinalKeySelected(self, event): self.BuildKeyString() def BuildKeyString(self): keyList = modifiers = self.GetModifiers() finalKey = self.listKeysFinal.get(ANCHOR) if finalKey: finalKey = self.TranslateKey(finalKey, modifiers) keyList.append(finalKey) self.keyString.set('<' + string.join(keyList, '-') + '>') def GetModifiers(self): modList = [variable.get() for variable in self.modifier_vars] return [mod for mod in modList if mod] def ClearKeySeq(self): self.listKeysFinal.select_clear(0, END) self.listKeysFinal.yview(MOVETO, '0.0') for variable in self.modifier_vars: variable.set('') self.keyString.set('') def LoadFinalKeyList(self): #these tuples are also available for use in validity checks self.functionKeys = ('F1', 'F2', 'F2', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12') self.alphanumKeys = tuple(string.ascii_lowercase + string.digits) self.punctuationKeys = tuple('~!@#%^&*()_-+={}[]|;:,.<>/?') self.whitespaceKeys = ('Tab', 'Space', 'Return') self.editKeys = ('BackSpace', 'Delete', 'Insert') self.moveKeys = ('Home', 'End', 'Page Up', 'Page Down', 'Left Arrow', 'Right Arrow', 'Up Arrow', 'Down Arrow') #make a tuple of most of the useful common 'final' keys keys = (self.alphanumKeys + self.punctuationKeys + self.functionKeys + self.whitespaceKeys + self.editKeys + self.moveKeys) self.listKeysFinal.insert(END, *keys) def TranslateKey(self, key, modifiers): "Translate from keycap symbol to the Tkinter keysym" translateDict = { 'Space': 'space', '~': 'asciitilde', '!': 'exclam', '@': 'at', '#': 'numbersign', '%': 'percent', '^': 'asciicircum', '&': 'ampersand', '*': 'asterisk', '(': 'parenleft', ')': 'parenright', '_': 'underscore', '-': 'minus', '+': 'plus', '=': 'equal', '{': 'braceleft', '}': 'braceright', '[': 'bracketleft', ']': 'bracketright', '|': 'bar', ';': 'semicolon', ':': 'colon', ',': 'comma', '.': 'period', '<': 'less', '>': 'greater', '/': 'slash', '?': 'question', 'Page Up': 'Prior', 'Page Down': 'Next', 'Left Arrow': 'Left', 'Right Arrow': 'Right', 'Up Arrow': 'Up', 'Down Arrow': 'Down', 'Tab': 'Tab' } if key in translateDict.keys(): key = translateDict[key] if 'Shift' in modifiers and key in string.ascii_lowercase: key = key.upper() key = 'Key-' + key return key def OK(self, event=None): if self.advanced or self.KeysOK(): # doesn't check advanced string yet self.result = self.keyString.get() self.destroy() def Cancel(self, event=None): self.result = '' self.destroy() def KeysOK(self): '''Validity check on user's 'basic' keybinding selection. Doesn't check the string produced by the advanced dialog because 'modifiers' isn't set. ''' keys = self.keyString.get() keys.strip() finalKey = self.listKeysFinal.get(ANCHOR) modifiers = self.GetModifiers() # create a key sequence list for overlap check: keySequence = keys.split() keysOK = False title = 'Key Sequence Error' if not keys: tkMessageBox.showerror(title=title, parent=self, message='No keys specified.') elif not keys.endswith('>'): tkMessageBox.showerror(title=title, parent=self, message='Missing the final Key') elif (not modifiers and finalKey not in self.functionKeys + self.moveKeys): tkMessageBox.showerror(title=title, parent=self, message='No modifier key(s) specified.') elif (modifiers == ['Shift']) \ and (finalKey not in self.functionKeys + self.moveKeys + ('Tab', 'Space')): msg = 'The shift modifier by itself may not be used with'\ ' this key symbol.' tkMessageBox.showerror(title=title, parent=self, message=msg) elif keySequence in self.currentKeySequences: msg = 'This key combination is already in use.' tkMessageBox.showerror(title=title, parent=self, message=msg) else: keysOK = True return keysOK
class ListPage(BasePage): def __init__(self, parent, controller): BasePage.__init__(self, parent, controller) self.mutex = Lock() def prepare(self): self.deviceList.config(state='normal') self.versionList.config(state='disabled') self.engList.config(state='disabled') self.packageList.config(state='disabled') self.ok.config(state='disabled') self.setData(self.controller.data) self.setDeviceList(self.data.keys()) self.controller.setDefault(self, self.controller.loadOptions()) self.deviceList.focus_force() def printErr(self, message): self.errLog.config(text=message) def setData(self, data): self.data = data def setupView(self, title="Select your flash", data=None): if(data): self.setData(data) self.errLog = Label(self, text="") self.errLog.grid(row=4, column=1, columnspan=3, sticky="NWSE") self.desc = Label(self, text=title, font=TITLE_FONT) self.desc.grid(row=0, column=0, columnspan=2) self.ok = Button(self, text='Next', command=lambda: self. confirm()) self.ok.grid(row=4, column=3, sticky="E") self.ok.config(state="disabled") self.deviceLabel = Label(self, text="Device", font=TITLE_FONT) self.deviceLabel.grid(row=1, column=0) self.deviceList = Listbox(self, exportselection=0) self.deviceList.grid(row=2, column=0) self.deviceList.bind('<<ListboxSelect>>', self.deviceOnSelect) self.deviceList.config(state="disabled") self.versionLabel = Label(self, text="Branch", font=TITLE_FONT) self.versionLabel.grid(row=1, column=1) self.versionList = Listbox(self, exportselection=0) self.versionList.grid(row=2, column=1) self.versionList.bind('<<ListboxSelect>>', self.versionOnSelect) self.versionList.config(state="disabled") self.engLabel = Label(self, text="Build Type", font=TITLE_FONT) self.engLabel.grid(row=1, column=2) self.engList = Listbox(self, exportselection=0) self.engList.grid(row=2, column=2) self.engList.bind('<<ListboxSelect>>', self.engOnSelect) self.engList.config(state="disabled") self.packageLabel = Label( self, text="Gecko/Gaia/Full", font=TITLE_FONT) self.packageLabel.grid(row=1, column=3) self.packageList = Listbox(self, exportselection=0) self.packageList.grid(row=2, column=3) self.packageList.bind('<<ListboxSelect>>', self.packageOnSelect) self.packageList.config(state="disabled") self.bidVar = StringVar() Label(self, text="Build ID").grid(row=3, column=0, sticky='E') self.bidInput = Entry( self, textvariable=self.bidVar, width="30") self.bidInput.grid( row=3, column=1, columnspan=2, sticky="W") self.bidVar.set('latest') # binding unfocus for build id field self.bidInput.bind('<FocusOut>', self.updateBuildId) # binding the Return Key to each componments self.deviceList.bind('<Return>', self.pressReturnKey) self.versionList.bind('<Return>', self.pressReturnKey) self.engList.bind('<Return>', self.pressReturnKey) self.packageList.bind('<Return>', self.pressReturnKey) self.bidInput.bind('<Return>', self.pressReturnKey) self.ok.bind('<Return>', self.pressReturnKey) def selection_all_checked(self): result = False if len(self.deviceList.curselection()) == 0: self.logger.log('Please select device.', status_callback=self.printErr) self.ok.config(state="disabled") self.deviceList.focus_set() elif len(self.versionList.curselection()) == 0: self.logger.log('Please select branch.', status_callback=self.printErr) self.ok.config(state="disabled") self.versionList.focus_set() elif len(self.engList.curselection()) == 0: self.logger.log('Please select user or engineer build.', status_callback=self.printErr) self.ok.config(state="disabled") self.engList.focus_set() elif len(self.packageList.curselection()) == 0: self.logger.log('Please select package to flash.', status_callback=self.printErr) self.ok.config(state="disabled") self.packageList.focus_set() elif len(self.bidVar.get()) == 0: self.logger.log('Please enter build ID to flash or use "latest" to get the newest', status_callback=self.printErr) self.bidVar.set('latest') else: result = True return result def updateBuildId(self, event=None): if len(self.engList.curselection()) != 0: self.refreshPackageList() def pressReturnKey(self, event=None): if self.selection_all_checked(): self.ok.config(state="disabled") self.confirm() def deviceOnSelect(self, evt): self.setVersionList() def versionOnSelect(self, evt): self.setEngList() def engOnSelect(self, evt): self.refreshPackageList() # hard coded right now def packageOnSelect(self, evt): self.ok.config(state="normal") def confirm(self): self.mutex.acquire() try: if self.selection_all_checked(): self.ok.config(state="disabled") params = [] package = self.packageList.get(self.packageList.curselection()[0]) self.logger.log('Start to flash [' + package + '].', status_callback=self.printErr) if(PathParser._IMAGES in package): params.append(PathParser._IMAGES) else: if(PathParser._GAIA in package): params.append(PathParser._GAIA) if(PathParser._GECKO in package): params.append(PathParser._GECKO) self.controller.doFlash(params) self.packageList.select_clear(0, END) self.controller.transition(self) finally: self.mutex.release() def setDeviceList(self, device=[]): self.deviceList.delete(0, END) for li in device: self.deviceList.insert(END, li) def setVersionList(self, version=[]): if len(version) == 0: version = self.data[ self.deviceList.get(self.deviceList.curselection()) ] self.versionList.config(state="normal") self.engList.config(state="disabled") self.packageList.config(state="disabled") self.ok.config(state="disabled") self.versionList.delete(0, END) for li in version: self.versionList.insert(END, li) def setEngList(self, eng=[]): if len(eng) == 0: device = self.deviceList.get(self.deviceList.curselection()) version = self.versionList.get(self.versionList.curselection()) eng = self.data[device][version] self.engList.config(state="normal") self.packageList.config(state="disabled") self.ok.config(state="disabled") self.engList.delete(0, END) for li in eng: self.engList.insert(END, li) def refreshPackageList(self): self.mutex.acquire() try: self.packageList.config(state="normal") self.ok.config(state="normal") self.packageList.delete(0, END) device = self.deviceList.get(self.deviceList.curselection()) version = self.versionList.get(self.versionList.curselection()) eng = self.engList.get(self.engList.curselection()) # if the value is '' or 'latest', the set the build_id option as ''. buildId = '' if (len(self.bidVar.get()) == 0 or self.bidVar.get() == 'latest') else self.bidVar.get() package = self.controller.getPackages(self.data[device][version][eng]['src'], build_id=buildId) if len(package) == 0: package = [PathParser._GAIA_GECKO, PathParser._GAIA, PathParser._GECKO, PathParser._IMAGES] for li in package: self.packageList.insert(END, li) finally: self.mutex.release()
class StatePopup(object): def __init__(self, master, default_value, state_probs): top = self.top = Toplevel(master.canvas) self.master = master self.l = Label(top, text="New State") self.l.grid(row=0, column=0, columnspan=2) self.lb = Listbox( top ) # OptionMenu(top, Tkinter.StringVar().set(self.states[-1]), *self.states) self.lb.insert("end", "0") for i, (state, color) in enumerate(self.master.trail.colorlist.items()): str = ",".join(["{:x}".format(x) for x in state]) self.lb.insert("end", str) self.lb.itemconfig(i + 1, {"bg": color}) self.lb.grid(row=1, column=1, padx=MARGIN_LR / 2, pady=MARGIN_TB) self.lb.config(height=5, width=8) self.lb.bind( "<Double-Button-1>", lambda x: self.set_text(self.lb.get(self.lb.curselection()))) self.e = Entry(top) self.e.insert(0, default_value) self.e.bind("<Control-KeyRelease-a>", lambda x: self.select_all()) self.e.grid(row=1, column=0, sticky=N, padx=MARGIN_LR / 2, pady=MARGIN_TB) self.e.select_range(0, 'end') self.e.icursor('end') self.e.focus() self.b = Button(top, text='Ok', command=self.check_cleanup) self.top.protocol("WM_DELETE_WINDOW", self.close) self.b.grid(row=3, column=0, columnspan=2) self.l2 = Label(top, text="Probabilities") self.l2.grid(row=4, column=0, columnspan=2) for i, x in enumerate(state_probs): # if x > 0: # l = Label(top, text=hex(i)[2:] + ":" + str(x)) # l.pack() pass self.top.bind("<Return>", lambda x: self.check_cleanup()) self.top.bind("<Escape>", lambda x: self.close()) self.value = None self.top.wait_visibility() # stop interaction in other gui self.top.grab_set() def set_text(self, text): self.e.delete(0, 'end') self.e.insert(0, text) def select_all(event): event.e.select_range(0, 'end') # move cursor to the end event.e.icursor('end') return 'break' def check_cleanup(self): newstate = self.e.get() if newstate == "": self.value = range( 0, 2**(self.master.trail.statebitsize / self.master.trail.statesize)) elif newstate == "*": self.value = range( 1, 2**(self.master.trail.statebitsize / self.master.trail.statesize)) else: try: state = [] for x in newstate.split(","): x = x.strip() x = int(x, 16) assert x < 2**(self.master.trail.statebitsize / self.master.trail.statesize) state.append(x) assert len(state) > 0 self.value = state except Exception as e: print "Exception: " + str(e) self.value = None return self.close() def close(self): self.top.grab_release() self.top.destroy()
class ConditionalsEditor: def __init__(self, my_window, conditionals, close_callback): #Tk.__init__(self) self.my_window = my_window self.my_window.title("Condition Editor") self.close_callback = close_callback self.conditionals = conditionals shared_pad_x = 3 shared_pad_y = 3 main_frame = Frame(self.my_window) main_frame.grid(column=0, row=0, sticky=(N, W, E, S)) image_path = "images" image_files = [ f for f in os.listdir(image_path) if os.path.isfile(os.path.join(image_path, f)) and f.endswith(".png") ] self.icons = {} for image_file in image_files: self.icons[os.path.splitext( os.path.basename(image_file))[0]] = PhotoImage( file=os.path.join(image_path, image_file)) up_down_button_frame = Frame(main_frame) self.up_button = Button(up_down_button_frame, state="disabled", text="Move up", image=self.icons["gtk-go-up"], command=self.up_pressed) self.up_button.grid(column=0, row=0, sticky=(E)) self.down_button = Button(up_down_button_frame, state="disabled", text="Move down", image=self.icons["gtk-go-down"], command=self.down_pressed) self.down_button.grid(column=0, row=1, sticky=(E)) up_down_button_frame.grid(column=0, row=0, sticky=(E)) condition_list = Frame(main_frame, relief=SUNKEN, borderwidth=1) condition_list.grid(column=1, row=0, sticky=(N, S, E, W), padx=shared_pad_x, pady=shared_pad_y, columnspan=1) self.condition_list_scrollbar = Scrollbar(condition_list) self.state_listbox = Listbox(condition_list, relief=FLAT, exportselection=False, borderwidth=0, highlightthickness=0, yscrollcommand=self.state_listbox_scroll, activestyle="none") self.state_listbox.grid(column=0, row=0, padx=0, sticky=(N, S)) self.state_listbox.bind("<<ListboxSelect>>", self.state_listbox_selected) self.condition_listbox = Listbox( condition_list, relief=FLAT, exportselection=False, borderwidth=0, highlightthickness=0, yscrollcommand=self.condition_listbox_scroll, activestyle="none") self.condition_listbox.grid(column=1, row=0, sticky=(N, S, E, W), padx=0) self.condition_listbox.bind("<<ListboxSelect>>", self.condition_listbox_selected) self.execution_target_listbox = Listbox( condition_list, relief=FLAT, exportselection=False, borderwidth=0, highlightthickness=0, yscrollcommand=self.execution_target_listbox_scroll, activestyle="none") self.execution_target_listbox.grid(column=2, row=0, padx=0, sticky=(N, S)) self.execution_target_listbox.bind( "<<ListboxSelect>>", self.execution_target_listbox_selected) self.condition_list_scrollbar.grid(column=3, row=0, sticky=(N, S)) self.condition_list_scrollbar.config( command=self.condition_list_scrollbar_callback) condition_list.grid_rowconfigure(0, weight=1) for conditional in self.conditionals: self.state_listbox.insert(END, conditional[0]) self.condition_listbox.insert(END, conditional[1]) self.execution_target_listbox.insert(END, conditional[2]) #for i in range(5): # self.state_listbox.insert(END, "Foo %d"%i) # self.condition_listbox.insert(END, "Bar %d"%i) # self.execution_target_listbox.insert(END, "Baz %d"%i) if_label = Label(main_frame, text="If:", padx=10) if_label.grid(column=0, row=1, sticky=(N, E)) self.if_text_variable = StringVar() if_entry = Entry(main_frame, textvariable=self.if_text_variable) if_entry.grid( column=1, row=1, sticky=(E, W), padx=shared_pad_x, pady=shared_pad_y, ) then_label = Label(main_frame, text="Then:", padx=10) then_label.grid(column=0, row=2, sticky=(N, E)) self.then_entry = Text(main_frame) self.then_entry.grid( column=1, row=2, sticky=(N, S, E, W), padx=shared_pad_x, rowspan=2, ) option_frame = Frame(main_frame) execution_target_label = Label(option_frame, text="Execution target:") execution_target_label.grid(column=0, row=0, sticky=(N, W), pady=(10, shared_pad_y)) self.execution_target = StringVar() self.execution_target.set("Debugger") debugger_radiobutton = Radiobutton(option_frame, text="Debugger", variable=self.execution_target, value="Debugger") debugger_radiobutton.grid(column=0, row=1, sticky=(N, W)) python_radiobutton = Radiobutton(option_frame, text="Python", variable=self.execution_target, value="Python") python_radiobutton.grid(column=0, row=2, sticky=(N, W)) state_label = Label(option_frame, text="State") state_label.grid(column=0, row=3, sticky=(N, W), pady=(10, shared_pad_y)) self.active_checkbutton = StringVar() self.active_checkbutton.set("Enabled") active_checkbutton = Checkbutton(option_frame, text="Enabled", variable=self.active_checkbutton, onvalue="Enabled", offvalue="Disabled") active_checkbutton.grid(column=0, row=4, sticky=(N, W)) option_frame.grid(column=0, row=3, sticky=(N, S, E, W), pady=5) button_frame = Frame(main_frame) self.add_button = Button(button_frame, state="disabled", text="Add", image=self.icons["gtk-add"], compound=LEFT) self.add_button.grid(column=0, row=0, sticky=(E)) self.update_button = Button(button_frame, state="disabled", text="Update", image=self.icons["gtk-edit"], compound=LEFT) self.update_button.grid(column=1, row=0, sticky=(E)) self.delete_button = Button(button_frame, state="disabled", text="Delete", image=self.icons["gtk-remove"], compound=LEFT) self.delete_button.grid(column=2, row=0, sticky=(E)) button_frame.grid(column=0, row=4, columnspan=2, sticky=(E), padx=shared_pad_x, pady=shared_pad_y) close_frame = Frame(main_frame) close_button = Button(close_frame, text="Close", image=self.icons["gtk-close"], compound=LEFT, command=self.on_closing) close_button.grid(column=0, row=0, sticky=(S, E)) close_frame.grid(column=0, row=5, columnspan=2, sticky=(S, E), padx=shared_pad_x, pady=(15, shared_pad_y)) self.my_window.grid_columnconfigure(0, weight=1) self.my_window.grid_rowconfigure(0, weight=1) main_frame.grid_columnconfigure(1, weight=1) main_frame.grid_rowconfigure(0, weight=1) main_frame.grid_rowconfigure(2, weight=0) main_frame.grid_rowconfigure(3, weight=1) main_frame.grid_rowconfigure(4, weight=1) main_frame.grid_rowconfigure(5, weight=1) condition_list.grid_columnconfigure(1, weight=1) button_frame.grid_rowconfigure(0, weight=1) self.my_window.protocol("WM_DELETE_WINDOW", self.on_closing) def on_closing(self): if self.close_callback is not None: self.close_callback() self.my_window.destroy() def up_pressed(self): index = self.state_listbox.curselection()[0] state_current = self.state_listbox.get(index) condition_current = self.condition_listbox.get(index) execution_target_current = self.execution_target_listbox.get(index) self.state_listbox.delete(index) self.condition_listbox.delete(index) self.execution_target_listbox.delete(index) self.state_listbox.insert(index - 1, state_current) self.condition_listbox.insert(index - 1, condition_current) self.execution_target_listbox.insert(index - 1, execution_target_current) self.conditionals.insert(index - 1, self.conditionals.pop(index)) self.state_listbox.selection_set(index - 1) self.condition_listbox.selection_set(index - 1) self.execution_target_listbox.selection_set(index - 1) self.state_listbox.see(index - 1) if index - 1 == 0: self.up_button.config(state="disabled") self.down_button.config(state="normal") def down_pressed(self): index = self.state_listbox.curselection()[0] state_current = self.state_listbox.get(index) condition_current = self.condition_listbox.get(index) execution_target_current = self.execution_target_listbox.get(index) self.state_listbox.delete(index) self.condition_listbox.delete(index) self.execution_target_listbox.delete(index) self.state_listbox.insert(index + 1, state_current) self.condition_listbox.insert(index + 1, condition_current) self.execution_target_listbox.insert(index + 1, execution_target_current) self.conditionals.insert(index + 1, self.conditionals.pop(index)) self.state_listbox.selection_set(index + 1) self.condition_listbox.selection_set(index + 1) self.execution_target_listbox.selection_set(index + 1) self.state_listbox.see(index + 1) if index + 1 == self.state_listbox.size() - 1: self.down_button.config(state="disabled") self.up_button.config(state="normal") def condition_list_scrollbar_callback(self, *args): self.state_listbox.yview(*args) self.condition_listbox.yview(*args) self.execution_target_listbox.yview(*args) def state_listbox_scroll(self, *args): self.condition_listbox.yview_moveto(args[0]) self.execution_target_listbox.yview_moveto(args[0]) self.condition_list_scrollbar.set(*args) def condition_listbox_scroll(self, *args): self.state_listbox.yview_moveto(args[0]) self.execution_target_listbox.yview_moveto(args[0]) def execution_target_listbox_scroll(self, *args): self.state_listbox.yview_moveto(args[0]) self.condition_listbox.yview_moveto(args[0]) def any_listbox_selected(self): self.up_button.config(state="normal") self.down_button.config(state="normal") if self.state_listbox.curselection( )[0] == self.state_listbox.size() - 1: self.down_button.config(state="disabled") if self.state_listbox.curselection()[0] == 0: self.up_button.config(state="disabled") self.delete_button.config(state="normal") self.then_entry.delete("1.0", END) self.then_entry.insert( END, self.conditionals[self.state_listbox.curselection()[0]][3]) self.if_text_variable.set( self.conditionals[self.state_listbox.curselection()[0]][1]) self.execution_target.set( self.conditionals[self.state_listbox.curselection()[0]][2]) self.active_checkbutton.set( self.conditionals[self.state_listbox.curselection()[0]][0]) def state_listbox_selected(self, event): index = self.state_listbox.curselection()[0] try: self.condition_listbox.selection_clear( self.condition_listbox.curselection()[0]) except IndexError: pass self.condition_listbox.selection_set(index) try: self.execution_target_listbox.selection_clear( self.execution_target_listbox.curselection()[0]) except IndexError: pass self.execution_target_listbox.selection_set(index) self.any_listbox_selected() def condition_listbox_selected(self, event): index = self.condition_listbox.curselection()[0] try: self.state_listbox.selection_clear( self.state_listbox.curselection()[0]) except IndexError: pass self.state_listbox.selection_set(index) try: self.execution_target_listbox.selection_clear( self.execution_target_listbox.curselection()[0]) except IndexError: pass self.execution_target_listbox.selection_set(index) self.any_listbox_selected() def execution_target_listbox_selected(self, event): index = self.execution_target_listbox.curselection()[0] try: self.state_listbox.selection_clear( self.state_listbox.curselection()[0]) except IndexError: pass self.state_listbox.selection_set(index) try: self.condition_listbox.selection_clear( self.condition_listbox.curselection()[0]) except IndexError: pass self.condition_listbox.selection_set(index) self.any_listbox_selected()
def main(argv): if len(argv) == 1: root = Tk() root.title("Randominions 4") mapfilevar = StringVar() outfilevar = StringVar() outfilevar.set("newrandommap.map") modfilevar = StringVar() lvl1thronevar = IntVar() lvl1thronevar.set(0) lvl2thronevar = IntVar() lvl2thronevar.set(0) lvl3thronevar = IntVar() lvl3thronevar.set(0) landstartvar = IntVar() landstartvar.set(0) waterstartvar = IntVar() waterstartvar.set(0) coaststartvar = IntVar() coaststartvar.set(0) foreststartvar = IntVar() foreststartvar.set(0) swampstartvar = IntVar() swampstartvar.set(0) cavestartvar = IntVar() cavestartvar.set(0) indystrengthvar = IntVar() indystrengthvar.set(100) rarechancevar = IntVar() rarechancevar.set(10) magepowervar = IntVar() magepowervar.set(2) allowsacred = BooleanVar() allowsacred.set(False) Label(root, text="Map:").grid(row=0, sticky=E) Entry(root, width=50, textvariable=mapfilevar).grid(row=0, column=1) Label(root, text="Output map:").grid(row=4, sticky=E) Entry(root, width=50, textvariable=outfilevar).grid(row=4, column=1) Label(root, text="Nation mod file:").grid(row=5, sticky=E) Entry(root, width=50, textvariable=modfilevar).grid(row=5, column=1) Label(root, text="Rare indy chance(%):").grid(row=6, sticky=E) Entry(root, width=5, textvariable=rarechancevar).grid(row=6, column=1, sticky=W) Label(root, text="Indy strength(%):").grid(row=7, sticky=E) Entry(root, width=5, textvariable=indystrengthvar).grid(row=7, column=1, sticky=W) Label(root, text="Max nation mage power:").grid(row=8, sticky=E) Entry(root, width=5, textvariable=magepowervar).grid(row=8, column=1, sticky=W) Label(root, text="Allow sacred units:").grid(row=9, sticky=E) Checkbutton(root, variable=allowsacred).grid(row=9, column=1, sticky=W) Label(root, text="Level 1 thrones:").grid(row=0, column=3, sticky=E) Entry(root, width=3, textvariable=lvl1thronevar).grid(row=0, column=4) Label(root, text="Level 2 thrones:").grid(row=1, column=3, sticky=E) Entry(root, width=3, textvariable=lvl2thronevar).grid(row=1, column=4) Label(root, text="Level 3 thrones:").grid(row=2, column=3, sticky=E) Entry(root, width=3, textvariable=lvl3thronevar).grid(row=2, column=4) Label(root, text="Land nations:").grid(row=3, column=3, sticky=E) Entry(root, width=3, textvariable=landstartvar).grid(row=3, column=4) Label(root, text="Water nations:").grid(row=4, column=3, sticky=E) Entry(root, width=3, textvariable=waterstartvar).grid(row=4, column=4) Label(root, text="Coastal starts:").grid(row=5, column=3, sticky=E) Entry(root, width=3, textvariable=coaststartvar).grid(row=5, column=4) Label(root, text="Forest starts:").grid(row=6, column=3, sticky=E) Entry(root, width=3, textvariable=foreststartvar).grid(row=6, column=4) Label(root, text="Swamp starts:").grid(row=7, column=3, sticky=E) Entry(root, width=3, textvariable=swampstartvar).grid(row=7, column=4) Label(root, text="Cave starts:").grid(row=8, column=3, sticky=E) Entry(root, width=3, textvariable=cavestartvar).grid(row=8, column=4) Label(root, text="Indies:").grid(row=1, sticky=E) indylist = Listbox(root, width=50, height=4) indylist.grid(row=1, column=1, rowspan=3) Button(root, width=13, text="Choose Map", command=lambda : mapfilevar.set(askopenfilename(filetypes=[('Dominions 4 map files', '.map')]))).grid(row=0, column=2, sticky=W) Button(root, width=13, text="Choose Mod", command=lambda : modfilevar.set(askopenfilename(filetypes=[('Dominions 4 mod file', '.dm')]))).grid(row=5, column=2, sticky=W) Button(root, width=13, text="Add indies", command=lambda : indylist.insert(END,askopenfilename(filetypes=[('JSON files', '.json'), ('Domions 4 mod files', '.dm')]))).grid(row=1, column=2, sticky=W) Button(root, width=13, text="Remove selected", command=lambda : indylist.delete(ANCHOR)).grid(row=2, column=2, sticky=W) Button(root, width=10, text="Quit", command=root.destroy).grid(row=10, column=0) Button(root, width=10, text="Generate!", \ command=lambda : runGenerator(mapfilevar.get(), indylist.get(0, END), outfilevar.get(), landstartvar.get(), waterstartvar.get(), \ coaststartvar.get(), foreststartvar.get(), swampstartvar.get(), cavestartvar.get(), lvl1thronevar.get(), \ lvl2thronevar.get(), lvl3thronevar.get(), rarechancevar.get(), indystrengthvar.get(), modfilevar.get(), magepowervar.get(), allowsacred.get())).grid(row=10, column=3) root.mainloop() elif len(argv) < 15: print "Usage: randominions4 mapfile targetmapfile indydefinition landnations waternations coaststarts foreststarts swampstarts cavestarts lvl1thrones lvl2thrones lvl3thrones rarechance indystrength" else: mapfile = argv[1] indyfile = argv[3] targetfile = argv[2] landcount = int(argv[4]) watercount = int(argv[5]) coaststarts = int(argv[6]) foreststarts = int(argv[7]) swampstarts = int(argv[8]) cavestarts = int(argv[9]) lvl1thrones = int(argv[10]) lvl2thrones = int(argv[11]) lvl3thrones = int(argv[12]) rarechance = int(argv[13]) strength = int(argv[14]) runGenerator(mapfile, [indyfile], targetfile, landcount, watercount, coaststarts, foreststarts, swampstarts, cavestarts, lvl1thrones, lvl2thrones, lvl3thrones, rarechance, strength, None, None, None)
class ListFrame(LabelFrame): """ A Frame representing one of the search term lists (e.g. Hashtags, Excluded Users). Displays all the items in the list, and allows the user to add or remove items. Methods should not be called directly; instead they should be bound as event handlers. """ def __init__(self, name, add_handler, remove_handler, master=None): """ Creates a ListFrame with the given name as its title. add_handler and remove_handler are functions to be called when items are added or removed, and should relay the information back to the Searcher (or whatever object actually uses the list). """ LabelFrame.__init__(self, master) self['text'] = name self.add_handler = add_handler self.remove_handler = remove_handler self.list = Listbox(self) self.list.grid(row=0, columnspan=2) # Tkinter does not automatically close the right-click menu for us, # so we must close it when the user clicks away from the menu. self.list.bind("<Button-1>", lambda event: self.context_menu.unpost()) self.list.bind("<Button-3>", self.open_menu) self.context_menu = Menu(self, tearoff=0) self.context_menu.add_command(label="Remove", command=self.remove) self.input = Entry(self) self.input.bind("<Return>", lambda event: self.add()) self.input.grid(row=1, columnspan=2) self.add_button = Button(self) self.add_button['text'] = "Add" self.add_button['command'] = self.add self.add_button.grid(row=2, column=0, sticky=W+E) self.remove_button = Button(self) self.remove_button['text'] = "Remove" self.remove_button['command'] = self.remove self.remove_button.grid(row=2, column=1, sticky=W+E) def add(self): """ Add the item in the input line to the list. """ self.list.insert(END, self.input.get()) self.add_handler(self.input.get()) self.input.delete(0, END) def remove(self): """ Remove the active (highlighted) item from the list. """ deleted = self.list.get(ACTIVE) self.list.delete(ACTIVE) self.remove_handler(deleted) def open_menu(self, event): """ Opens a right-click menu for the selected item. Currently the menu only has an option for removing the item. """ index = self.list.index("@" + str(event.x) + "," + str(event.y)) if index < 0: return self.context_menu.post(event.x_root, event.y_root) self.list.activate(index) self.list.selection_clear(0, END) self.list.selection_set(ACTIVE)
class ListPane(Frame): """A ListPane is a widget for holding a list of words, incorporating a scrollbar""" def __init__(self, parent, height=35, width=40): Frame.__init__(self, parent) #Create a scrollbar so that list can be of arbitrary length scrollbar = Scrollbar(self) #Create a listbox to hold/display the word list self.listbox = Listbox(self, height = height, width = width, yscrollcommand = scrollbar.set) scrollbar.config(command = self.listbox.yview) self.listbox.pack(side=LEFT, fill = BOTH) scrollbar.pack(side=RIGHT, fill = Y) #Allow the widget to react to single or double clicks self.listbox.bind("<Double-Button-1>", self.doubleclicked) self.listbox.bind("<Button-1>", self.singleclicked) def remove(self, itemindex): """Removes the word at the given index of the list""" self.listbox.delete(itemindex, itemindex) def get(self, index=None): """Get the currently selected word""" try: if index!=None: return self.listbox.get(index) else: return self.get(self.listbox.curselection()) except TclError: return None def getDisplayed(self): """Get a list of all words currently contained in the ListPane""" return self.listbox.get(0,END) def insert(self, item): """Insert a word into the list""" self.listbox.insert(END, item) def display(self, itemlist): """Pass a list to this method and the contents will be displayed in the ListPane""" self.listbox.delete(0, END) for item in itemlist: self.listbox.insert(END, item) def doubleclicked(self, event): """Called when widget is double-clicked. Template method that calls doubleClickFunc""" try: itemindex = self.listbox.curselection() self.doubleClickFunc(itemindex) except TclError: pass def doubleClickFunc(self, itemindex): """This method should be replaced on specific instances of ListPane. Defines the behaviour of widget when double-clicked""" pass def singleclicked(self, event): """Called when widget is single-clicked. Template method that calls singleClickFunc""" self.singleClickFunc(self.listbox.index("@%d,%d" % (event.x, event.y))) def singleClickFunc(self, itemindex): """This method should be replaced on specific instances of ListPane Defines the behaviour of widget when single-clicked""" pass
class Ordered_Listbox(Frame): def __init__(self, master, data=None, ascending_order=True, ignore_case=False, autoscroll=False, vscrollbar=True, hscrollbar=False, scrollbar_background=None, scrollbar_troughcolor=None, **kwargs): Frame.__init__(self, master) self._ignore_case = ignore_case self._ascending_order = ascending_order master.grid_rowconfigure(0, weight=1) master.grid_columnconfigure(0, weight=1) self._listbox = Listbox(self, *kwargs) self._listbox.grid(row=0, column=0, sticky=N + E + W + S) scrollbar_kwargs = {} if scrollbar_background is not None: scrollbar_kwargs["background"] = scrollbar_background if scrollbar_troughcolor is not None: scrollbar_kwargs["throughcolor"] = scrollbar_troughcolor if vscrollbar: self._vbar = Scrollbar(self, takefocus=0, command=self._listbox.yview, **scrollbar_kwargs) self._vbar.grid(row=0, column=1, sticky=N + S) if autoscroll: self._listbox.config(yscrollcommand=lambda f, l: make_autoscroll(self._vbar, f, l)) else: self._listbox.config(yscrollcommand=self._vbar.set) if hscrollbar: self._hbar = Scrollbar(self, takefocus=0, command=self._listbox.xview, **scrollbar_kwargs) self._hbar.grid(row=0, column=1, sticky=E + W) if autoscroll: self._listbox.config(xscrollcommand=lambda f, l: make_autoscroll(self._hbar, f, l)) else: self._listbox.config(xscrollcommand=self._hbar.set) if data is not None: for item in data: self.add_item(item) def add_item(self, item): list_of_items = self._listbox.get(0, END) index = bisect(list_of_items, item, ignore_case=self._ignore_case, ascending_order=self._ascending_order) self._listbox.insert(index, item) def delete_item(self, item): list_of_items = self._listbox.get(0, END) index = bisect(list_of_items, item, ignore_case=self._ignore_case, ascending_order=self._ascending_order) self._listbox.delete(index - 1) def selected_items(self): list_of_items = [] for index in self._listbox.curselection(): list_of_items.append(self._listbox.get(index)) return list_of_items def selected_item(self): return self._listbox.curselection()[0] def deselect_all(self): self._listbox.selection_clear(0, END) def select(self, item): index = self.index(item) if index is None: return self._listbox.selection_set(index) def deselect(self, item): index = self.index(item) if index is None: return self._listbox.selection_clear(index) def index(self, item): list_of_items = self._listbox.get(0, END) try: index = list_of_items.index(item) except ValueError: return None return index def bind(self, event, handler): self._listbox.bind(event, handler) def clear(self): self._listbox.delete(1, END) def __iter__(self): return self.items @property def items(self): return self._listbox.get(0, END)
class WikinewsExplorer: def __init__(self, master): self.currentFileName = "" self.entDir = "/dev/shm/wikinews/entities/" self.llDir= "/dev/shm/wikinews/lang_links/" self.boolFileLoad = False self.entFiles = [] self.llFiles = [] self.wikinewsBaseURL = "http://en.wikinews.org/?curid=" frame = Frame(master) frame.pack() frame.columnconfigure(1, weight=1) frame.columnconfigure(3, pad=7) frame.rowconfigure(3, weight=1) frame.rowconfigure(5, pad=7) self.lbEntFile = Label(frame, text="entities dir: ") self.lbEntFile.grid(row=0, column=0) self.lbLLFile = Label(frame, text="lang links dir: ") self.lbLLFile.grid(row=1, column=0) self.txtEntFile =Text(frame, height=1, width=40) self.txtEntFile.insert(INSERT, self.entDir) self.txtEntFile.grid(row=0, column=1) self.txtLLFile =Text(frame, height=1, width=40) self.txtLLFile.insert(INSERT, self.llDir) self.txtLLFile.grid(row=1, column=1) self.butLoad= Button(frame, text ="Load", command = self.readInputFiles) self.butLoad.grid(row=0, column=2, rowspan=2) self.scrollbar = Scrollbar(frame) self.lstArticles = Listbox(frame, yscrollcommand = self.scrollbar.set, width=50, height=20) self.lstArticles.grid( row=2, column=0, columnspan=2, sticky=W) self.lstArticles.bind("<<ListboxSelect>>", self.onArticleSelect) self.scrollbar.grid(row=2, column=3, sticky=W) self.scrollbar.config( command = self.lstArticles.yview ) self.butOpenBrowser = Button(frame, text="View article in browser", command=self.openInFirefox) self.butOpenBrowser.grid(row=3, column=0) self.lblSearchTitle = Label(frame, text="search article ID: ") self.lblSearchTitle.grid(row=4, column=0, sticky=E) self.txtSearchTitle = Text(frame, height=1, width=30) self.txtSearchTitle.grid(row=4, column=1) self.butSearchTitle = Button(frame, text="Go", command=self.searchTitle) self.butSearchTitle.grid(row=4, column=2, sticky=W) self.scrollbar2 = Scrollbar(frame) self.lstContent = Listbox(frame, yscrollcommand=self.scrollbar2.set, width=100, height=20) self.lstContent.grid(row=0, column=3, rowspan=5) self.lstContent.bind("<<ListboxSelect>>", self.onEntitySelect) self.scrollbar2.grid(row=0, column=3, sticky=W) self.scrollbar2.config( command = self.lstContent.yview ) self.scrollbar3 = Scrollbar(frame) self.lstWikiLinks = Listbox(frame, yscrollcommand=self.scrollbar3.set, width=70, height=13) self.lstWikiLinks.grid(row=5, column=3, sticky=W) self.scrollbar3.grid(row=5, column=3, sticky=W) self.scrollbar3.config( command = self.lstWikiLinks.yview ) def onEntitySelect(self, event): """ fetch entity info directly from wikipedia """ # enpty content box self.lstWikiLinks.delete(0, END) widg = event.widget index = int(widg.curselection()[0]) entityString = widg.get(index) print 'selected entity %d: "%s"' % (index, entityString) entityName = extractEntityName(entityString) self.lstWikiLinks.insert(END, "en.wikipedia.org/wiki/" + entityName) self.lstWikiLinks.insert(END, "======= links to the following wiki entities: ========================") url = "http://en.wikipedia.org/w/api.php?format=xml&action=query&titles=" + entityName +"&prop=links" print "HTTP request: ", url xmlResponseTree = None try: response = urllib2.urlopen(url).read() xmlResponseTree = ET.fromstring(response) except: print " \n ERROR: ", str(sys.exc_info()[0]) if xmlResponseTree != None: for link in xmlResponseTree.iter("pl"): # item = "en.wikipedia.org/wiki/" + self.lstWikiLinks.insert(END, link.attrib.get("title")) else: print " xml response tree empty " def onArticleSelect(self, event): # enpty content boxes self.lstContent.delete(0, END) self.lstWikiLinks.delete(0,END) widg = event.widget index = int(widg.curselection()[0]) fileName = widg.get(index) self.currentFileName = fileName print 'selected item %d: "%s"' % (index, fileName) # load the entity and lang-link files and display in the content box entFile = self.entDir + fileName llFile = self.llDir + fileName ents = open(entFile) lls = open(llFile) self.lstContent.insert(END, "===== contained Entities =================================") for ent in ents: self.lstContent.insert(END, ent.strip()) self.lstContent.insert(END, " ") self.lstContent.insert(END, "===== contained Language Links ===========================") for ll in lls: self.lstContent.insert(END, ll.strip()) ents.close() lls.close() def openInFirefox(self): wikinewsBase = self.wikinewsBaseURL articleID = self.lstArticles.get(ACTIVE).split("-")[0] """ commandLinux = "firefox " + wikinewsBase + articleID + " &" commandMacOS = "open -a firefox -g " + wikinewsBase + articleID commandWindows = 'firefox.exe \"' + wikinewsBase + articleID + '\"' if os.uname()[0] == "Linux": print "Linux: starting firefox" os.system(commandLinux) elif os.uname()[0] == "Mac": print "Mac: starting firefox" os.system(commandMacOS) elif os.name == "Windows": print "Windows: starting firefox" os.system(commandWindows) else: tkMessageBox.showinfo("Wikinews Explorer", "Strange OS detected: " + os.uname()[0] + "\n can't start Firefox") """ if not webbrowser.open_new(wikinewsBase + articleID): tkMessageBox.showinfo("Wikinews Explorer", "start browser") return def searchTitle(self): print "search: files loaded?", self.boolFileLoad targetString = self.txtSearchTitle.get(1.0, END).strip() if self.boolFileLoad: i = 0 for fileName in self.entFiles: if targetString.lower() in fileName.lower(): # focus first result and exit self.lstArticles.selection_set(i, i) self.lstArticles.see(i) print "--- found: ", i, " ", fileName break i += 1 else: tkMessageBox.showinfo("Wikinews Explorer", "Input files not loaded") def readInputFiles(self): self.entDir = self.txtEntFile.get(1.0, END).strip() self.llDir = self.txtLLFile.get(1.0, END).strip() if not os.path.exists(self.entDir): tkMessageBox.showinfo( "Wikinews Explorer", self.entDir + "\ndoes not exist") self.boolFileLoad = False return if not os.path.exists(self.llDir): self.boolFileLoad = False tkMessageBox.showinfo( "Wikinews Explorer", self.llDir + "\ndoes not exist") return # no return until here, it's fine self.entFiles = os.listdir(self.entDir) self.llFiles = os.listdir(self.llDir) if len(self.entFiles) != len(self.llFiles): tkMessageBox.showinfo("Wikinews Explorer", "something's wrong: \n article number mismatch: " + len(self.entFiles) + " != " + len(self.llFiles)) self.boolFileLoad = False return else: print "files count ok: ", str(len(self.entFiles)), " == ", str(len(self.llFiles)) for fileName in self.entFiles: self.lstArticles.insert(END, fileName) self.boolFileLoad = True # file loading ok print "files loaded?", self.boolFileLoad
class Combobox_Autocomplete(Entry, object): def __init__(self, master, list_of_items=None, autocomplete_function=None, listbox_width=None, listbox_height=7, ignorecase_match=False, startswith_match=True, vscrollbar=True, hscrollbar=True, **kwargs): if hasattr(self, "autocomplete_function"): if autocomplete_function is not None: raise ValueError("Combobox_Autocomplete subclass has 'autocomplete_function' implemented") else: if autocomplete_function is not None: self.autocomplete_function = autocomplete_function else: if list_of_items is None: raise ValueError("If not guiven complete function, list_of_items can't be 'None'") if ignorecase_match: if startswith_match: def matches_function(entry_data, item): return item.startswith(entry_data) else: def matches_function(entry_data, item): return item in entry_data self.autocomplete_function = lambda entry_data: [item for item in self.list_of_items if matches_function(entry_data, item)] else: if startswith_match: def matches_function(escaped_entry_data, item): if re.match(escaped_entry_data, item, re.IGNORECASE): return True else: return False else: def matches_function(escaped_entry_data, item): if re.search(escaped_entry_data, item, re.IGNORECASE): return True else: return False def autocomplete_function(entry_data): escaped_entry_data = re.escape(entry_data) return [item for item in self.list_of_items if matches_function(escaped_entry_data, item)] self.autocomplete_function = autocomplete_function self._listbox_height = int(listbox_height) self._listbox_width = listbox_width self.list_of_items = list_of_items self._use_vscrollbar = vscrollbar self._use_hscrollbar = hscrollbar kwargs.setdefault("background", "white") if "textvariable" in kwargs: self._entry_var = kwargs["textvariable"] else: self._entry_var = kwargs["textvariable"] = StringVar() Entry.__init__(self, master, **kwargs) self._trace_id = self._entry_var.trace('w', self._on_change_entry_var) self._listbox = None self.bind("<Tab>", self._on_tab) self.bind("<Up>", self._previous) self.bind("<Down>", self._next) self.bind('<Control-n>', self._next) self.bind('<Control-p>', self._previous) self.bind("<Return>", self._update_entry_from_listbox) self.bind("<Escape>", lambda event: self.unpost_listbox()) def _on_tab(self, event): self.post_listbox() return "break" def _on_change_entry_var(self, name, index, mode): entry_data = self._entry_var.get() if entry_data == '': self.unpost_listbox() self.focus() else: values = self.autocomplete_function(entry_data) if values: if self._listbox is None: self._build_listbox(values) else: self._listbox.delete(0, END) height = min(self._listbox_height, len(values)) self._listbox.configure(height=height) for item in values: self._listbox.insert(END, item) else: self.unpost_listbox() self.focus() def _build_listbox(self, values): listbox_frame = Frame() self._listbox = Listbox(listbox_frame, background="white", selectmode=SINGLE, activestyle="none", exportselection=False) self._listbox.grid(row=0, column=0,sticky = N+E+W+S) self._listbox.bind("<ButtonRelease-1>", self._update_entry_from_listbox) self._listbox.bind("<Return>", self._update_entry_from_listbox) self._listbox.bind("<Escape>", lambda event: self.unpost_listbox()) self._listbox.bind('<Control-n>', self._next) self._listbox.bind('<Control-p>', self._previous) if self._use_vscrollbar: vbar = Scrollbar(listbox_frame, orient=VERTICAL, command= self._listbox.yview) vbar.grid(row=0, column=1, sticky=N+S) self._listbox.configure(yscrollcommand= lambda f, l: autoscroll(vbar, f, l)) if self._use_hscrollbar: hbar = Scrollbar(listbox_frame, orient=HORIZONTAL, command= self._listbox.xview) hbar.grid(row=1, column=0, sticky=E+W) self._listbox.configure(xscrollcommand= lambda f, l: autoscroll(hbar, f, l)) listbox_frame.grid_columnconfigure(0, weight= 1) listbox_frame.grid_rowconfigure(0, weight= 1) x = -self.cget("borderwidth") - self.cget("highlightthickness") y = self.winfo_height()-self.cget("borderwidth") - self.cget("highlightthickness") if self._listbox_width: width = self._listbox_width else: width=self.winfo_width() listbox_frame.place(in_=self, x=x, y=y, width=width) height = min(self._listbox_height, len(values)) self._listbox.configure(height=height) for item in values: self._listbox.insert(END, item) def post_listbox(self): if self._listbox is not None: return entry_data = self._entry_var.get() if entry_data == '': return values = self.autocomplete_function(entry_data) if values: self._build_listbox(values) def unpost_listbox(self): if self._listbox is not None: self._listbox.master.destroy() self._listbox = None def get_value(self): return self._entry_var.get() def set_value(self, text, close_dialog=False): self._set_var(text) if close_dialog: self.unpost_listbox() self.icursor(END) self.xview_moveto(1.0) def _set_var(self, text): self._entry_var.trace_vdelete("w", self._trace_id) self._entry_var.set(text) self._trace_id = self._entry_var.trace('w', self._on_change_entry_var) def _update_entry_from_listbox(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if current_selection: text = self._listbox.get(current_selection) self._set_var(text) self._listbox.master.destroy() self._listbox = None self.focus() self.icursor(END) self.xview_moveto(1.0) return "break" def _previous(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if len(current_selection)==0: self._listbox.selection_set(0) self._listbox.activate(0) else: index = int(current_selection[0]) self._listbox.selection_clear(index) if index == 0: index = END else: index -= 1 self._listbox.see(index) self._listbox.selection_set(first=index) self._listbox.activate(index) return "break" def _next(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if len(current_selection)==0: self._listbox.selection_set(0) self._listbox.activate(0) else: index = int(current_selection[0]) self._listbox.selection_clear(index) if index == self._listbox.size() - 1: index = 0 else: index +=1 self._listbox.see(index) self._listbox.selection_set(index) self._listbox.activate(index) return "break"
class Combobox_Autocomplete(Entry, object): def __init__(self, master, list_of_items=None, autocomplete_function=None, listbox_width=None, listbox_height=7, ignorecase_match=False, startswith_match=True, vscrollbar=True, hscrollbar=True, **kwargs): if hasattr(self, "autocomplete_function"): if autocomplete_function is not None: raise ValueError( "Combobox_Autocomplete subclass has 'autocomplete_function' implemented" ) else: if autocomplete_function is not None: self.autocomplete_function = autocomplete_function else: if list_of_items is None: raise ValueError( "If not guiven complete function, list_of_items can't be 'None'" ) if ignorecase_match: if startswith_match: def matches_function(entry_data, item): return item.startswith(entry_data) else: def matches_function(entry_data, item): return item in entry_data self.autocomplete_function = lambda entry_data: [ item for item in self.list_of_items if matches_function(entry_data, item) ] else: if startswith_match: def matches_function(escaped_entry_data, item): if re.match(escaped_entry_data, item, re.IGNORECASE): return True else: return False else: def matches_function(escaped_entry_data, item): if re.search(escaped_entry_data, item, re.IGNORECASE): return True else: return False def autocomplete_function(entry_data): escaped_entry_data = re.escape(entry_data) return [ item for item in self.list_of_items if matches_function(escaped_entry_data, item) ] self.autocomplete_function = autocomplete_function self._listbox_height = int(listbox_height) self._listbox_width = listbox_width self.list_of_items = list_of_items self._use_vscrollbar = vscrollbar self._use_hscrollbar = hscrollbar kwargs.setdefault("background", "white") if "textvariable" in kwargs: self._entry_var = kwargs["textvariable"] else: self._entry_var = kwargs["textvariable"] = StringVar() Entry.__init__(self, master, **kwargs) self._trace_id = self._entry_var.trace('w', self._on_change_entry_var) self._listbox = None self.bind("<Tab>", self._on_tab) self.bind("<Up>", self._previous) self.bind("<Down>", self._next) self.bind('<Control-n>', self._next) self.bind('<Control-p>', self._previous) self.bind("<Return>", self._update_entry_from_listbox) self.bind("<Escape>", lambda event: self.unpost_listbox()) def _on_tab(self, event): self.post_listbox() return "break" def _on_change_entry_var(self, name, index, mode): entry_data = self._entry_var.get() if entry_data == '': self.unpost_listbox() self.focus() else: values = self.autocomplete_function(entry_data) if values: if self._listbox is None: self._build_listbox(values) else: self._listbox.delete(0, END) height = min(self._listbox_height, len(values)) self._listbox.configure(height=height) for item in values: self._listbox.insert(END, item) else: self.unpost_listbox() self.focus() def _build_listbox(self, values): listbox_frame = Frame() self._listbox = Listbox(listbox_frame, background="white", selectmode=SINGLE, activestyle="none", exportselection=False) self._listbox.grid(row=0, column=0, sticky=N + E + W + S) self._listbox.bind("<ButtonRelease-1>", self._update_entry_from_listbox) self._listbox.bind("<Return>", self._update_entry_from_listbox) self._listbox.bind("<Escape>", lambda event: self.unpost_listbox()) self._listbox.bind('<Control-n>', self._next) self._listbox.bind('<Control-p>', self._previous) if self._use_vscrollbar: vbar = Scrollbar(listbox_frame, orient=VERTICAL, command=self._listbox.yview) vbar.grid(row=0, column=1, sticky=N + S) self._listbox.configure( yscrollcommand=lambda f, l: autoscroll(vbar, f, l)) if self._use_hscrollbar: hbar = Scrollbar(listbox_frame, orient=HORIZONTAL, command=self._listbox.xview) hbar.grid(row=1, column=0, sticky=E + W) self._listbox.configure( xscrollcommand=lambda f, l: autoscroll(hbar, f, l)) listbox_frame.grid_columnconfigure(0, weight=1) listbox_frame.grid_rowconfigure(0, weight=1) x = -self.cget("borderwidth") - self.cget("highlightthickness") y = self.winfo_height() - self.cget("borderwidth") - self.cget( "highlightthickness") if self._listbox_width: width = self._listbox_width else: width = self.winfo_width() listbox_frame.place(in_=self, x=x, y=y, width=width) height = min(self._listbox_height, len(values)) self._listbox.configure(height=height) for item in values: self._listbox.insert(END, item) def post_listbox(self): if self._listbox is not None: return entry_data = self._entry_var.get() if entry_data == '': return values = self.autocomplete_function(entry_data) if values: self._build_listbox(values) def unpost_listbox(self): if self._listbox is not None: self._listbox.master.destroy() self._listbox = None def get_value(self): return self._entry_var.get() def set_value(self, text, close_dialog=False): self._set_var(text) if close_dialog: self.unpost_listbox() self.icursor(END) self.xview_moveto(1.0) def _set_var(self, text): self._entry_var.trace_vdelete("w", self._trace_id) self._entry_var.set(text) self._trace_id = self._entry_var.trace('w', self._on_change_entry_var) def _update_entry_from_listbox(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if current_selection: text = self._listbox.get(current_selection) self._set_var(text) self._listbox.master.destroy() self._listbox = None self.focus() self.icursor(END) self.xview_moveto(1.0) return "break" def _previous(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if len(current_selection) == 0: self._listbox.selection_set(0) self._listbox.activate(0) else: index = int(current_selection[0]) self._listbox.selection_clear(index) if index == 0: index = END else: index -= 1 self._listbox.see(index) self._listbox.selection_set(first=index) self._listbox.activate(index) return "break" def _next(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if len(current_selection) == 0: self._listbox.selection_set(0) self._listbox.activate(0) else: index = int(current_selection[0]) self._listbox.selection_clear(index) if index == self._listbox.size() - 1: index = 0 else: index += 1 self._listbox.see(index) self._listbox.selection_set(index) self._listbox.activate(index) return "break"
class photGUI(Frame): """The base class for the phot_calc GUI""" # This is the constructor for the GUI def __init__(self,master=None): # We begin by calling the base class's constructor first Frame.__init__(self,master) # We now have an empty window! # This command sets up a grid structure in the window self.grid() # This loop generates rows and columns in the grid for i in range(13): self.rowconfigure(i,minsize=10) for i in range(3): self.columnconfigure(i,minsize=30) # These are methods which appear below the constructor self.defineUnits() # this sets up the units I'll be using in the converter self.createWidgets() # this places the elements (or widgets) in the grid # This command "binds" the user's click to a method (varChoice) # This method will determine which variable the user wants (Distance, Mass, Time) self.inputlist.bind("<Button-1>",self.__varChoice) # This is a similar command for the selection of unit self.unitlist.bind("<Button-1>",self.__unitChoice) # Finally, this bind reads in whatever value is in the text box when the user hits return # and carries out the unit conversion self.inputfield.bind("<Return>",self.__calcConversion) # This function creates and defines the units def defineUnits(self): '''Method defines tuples that carry the various units stored by the converter''' self.speed = 2.997924580000019e10 self.h = 6.6260755e-27 # Wavelengths self.wavunits = ('nm','um', 'cm','m') self.wavvalues = (1.0e-7, 1.0e-4,1.0,1.0e2) self.frequnits = ('Hz','MHz','GHz','THz') self.freqvalues = (1.0, 1.0e6, 1.0e9, 1.0e12) self.energunits = ('eV','keV','MeV','GeV','erg') self.energvalues = (1.0,1.0e3,1.0e6,1.0e9,1.6e-12) # Keep the unit values in dictionaries, and use the above strings as keys self.wavdict = {} self.createUnitDict(self.wavdict,self.wavunits,self.wavvalues) # this method is shown below self.freqdict = {} self.createUnitDict(self.freqdict,self.frequnits,self.freqvalues) self.energdict = {} self.createUnitDict(self.energdict, self.energunits, self.energvalues) self.myunits = self.wavunits self.myvalues = self.wavvalues self.mydict = self.wavdict def createUnitDict(self,mydict,mykeys,myvalues): '''This method takes a set of units and values, and creates a dictionary to store them in''' for i in range(len(myvalues)): mydict[mykeys[i]] = myvalues[i] def createWidgets(self): '''This method creates all widgets and adds them to the GUI''' # Create Widgets in order of appearance # This is not necessary, but makes code easier to read # Start with text telling user what to do self.varlabel = Text(self,height=1, width=20) self.varlabel.insert(END,"Which Variable?") # Place widget on the Frame according to a grid self.varlabel.grid(row=0,column=0,sticky=W) # Second text label asking user which units are being used self.unitlabel = Text(self,height=1,width=20) self.unitlabel.insert(END,"Which Units?") self.unitlabel.grid(row=0,column=1,sticky=W) # Third text label asking user for numerical value self.numlabel = Text(self,height=1, width=20) self.numlabel.insert(END,"Enter Variable Values") self.numlabel.grid(row=0,column=2,sticky=W) # This creates a list of options for the user to select self.inputlist = Listbox(self, height=4, selectmode=SINGLE) # Tuple of choices we're going to put in this list self.paramlist = ('Frequency', 'Wavelength', 'Energy') # Add each item separately for item in self.paramlist: self.inputlist.insert(END,item) # Add it to the grid self.inputlist.grid(row=1, column=0,rowspan=4,sticky=W) # Add a unit list (several combinations of units allowed) self.unitlist = Listbox(self, height=4,selectmode=SINGLE) self.unitlist.grid(row=1,column=1,rowspan=4, sticky=W) # Number Entry Boxes (and Text Labels) self.inputlabel = Text(self,height=1,width=20) self.inputlabel.insert(END,"Waiting Selection") self.inputlabel.grid(row=1,column=2,sticky=W) self.inputfield = Entry(self) self.inputfield.grid(row=2,column=2,sticky=W) # Text Output Boxes self.wavoutput = Text(self, height=5, width=20) self.wavoutput.grid(row=7,column=0,rowspan=5,sticky=W) self.wavoutput.insert(END, "Wavelength: \n") self.freqoutput = Text(self, height=5, width=20) self.freqoutput.grid(row=7,column=1,rowspan=5,sticky=W) self.freqoutput.insert(END, "Frequency: \n") self.energoutput = Text(self, height=5, width=20) self.energoutput.grid(row=7,column=2,rowspan=5,sticky=W) self.energoutput.insert(END, "Energy: \n") # Create the Quit Button self.quitButton=Button(self,text='Quit',command=self.quit) self.quitButton.grid(row =13, column=0, sticky=W) # Event handler functions begin here # This handler defines the choice of units available to the user, # depending on selected variable def __varChoice(self, event): '''Handles the selection of variable: updates the list of units''' # Firstly, delete anything already in the units column self.unitlist.delete(first=0,last=len(self.myvalues)) num = 0 # Identify which option was clicked on try: num = self.inputlist.curselection()[0] self.varchoice = int(num) except: self.varchoice = 0 return # Get the string associated with this choice selection= self.inputlist.get(self.varchoice) print selection, " chosen" # Highlight current choice in red self.inputlist.itemconfig(self.varchoice, selectbackground='red') # If statement defines units being used if selection =='Wavelength': self.myunits = self.wavunits self.myvalues = self.wavvalues self.mydict = self.wavdict elif selection == 'Frequency': self.myunits = self.frequnits self.myvalues = self.freqvalues self.mydict = self.freqdict elif selection == 'Energy': self.myunits = self.energunits self.myvalues = self.energvalues self.mydict = self.energdict self.inputlabel.delete("1.0",index2=END) self.inputlabel.insert(END,selection) for i in range(len(self.myunits)): self.unitlist.insert(END,self.myunits[i]) def __unitChoice(self,event): '''Handles the selection of units''' num = 0 # Find which number is selected try: num = self.unitlist.curselection()[0] self.unitchoice = int(num) except: self.unitchoice = 0 return # Get the string (i.e. which unit is selected) selection= self.unitlist.get(self.unitchoice) print selection, " chosen" # Highlight current choice in red self.unitlist.itemconfig(self.unitchoice, selectbackground='red') # Handler takes current state of GUI, and calculates results def __calcConversion(self,event): '''This method takes the current state of all GUI variables, calculates one of four equations''' # Which variable has been selected for calculation? # This decides what equation to use a = self.inputfield.get() var = self.unitlist.get(self.unitchoice) a=float(a) freq = 0.0 wav = 0.0 energy = 0.0 if self.varchoice==0: freq = a freq = freq*self.mydict[var] wav = self.speed/freq energy = self.h*freq/self.energdict['erg'] elif self.varchoice==1: wav = a wav = wav*self.mydict[var] freq = self.speed/wav energy = self.speed*self.h/wav elif self.varchoice==2: energy = a energy=energy*self.energdict["erg"] freq = energy/self.h wav = self.speed*self.h/energy energy = energy*self.mydict[var]/self.energdict["erg"] # Remove all text in the output boxes self.wavoutput.delete("1.0",index2=END) self.freqoutput.delete("1.0",index2=END) self.energoutput.delete("1.0",index2=END) self.wavoutput.insert(END, "Wavelength: \n") self.freqoutput.insert(END, "Frequency: \n") self.energoutput.insert(END, "Energy: \n") # Calculate each conversion and output it to the GUI for i in range(len(self.wavvalues)): # As all units stored in cgs values, conversion is simple output = wav/self.wavvalues[i] # Express output in # Add to the output list self.wavoutput.insert(END,self.wavunits[i] + ": %.4e" % output+"\n") for i in range(len(self.freqvalues)): # As all units stored in cgs values, conversion is simple output = freq/self.freqvalues[i] # Add to the output list self.freqoutput.insert(END,self.frequnits[i] + ": %.4e" % output+"\n") for i in range(len(self.energvalues)): # As all units stored in cgs values, conversion is simple output = energy/self.energvalues[i] # Add to the output list self.energoutput.insert(END,self.energunits[i] + ": %.4e" % output+"\n")
class LintGui: """Build and control a window to interact with pylint""" def __init__(self, root=None): """init""" self.root = root or Tk() self.root.title('Pylint') #reporter self.reporter = None #message queue for output from reporter self.msg_queue = Queue.Queue() self.msgs = [] self.filenames = [] self.rating = StringVar() self.tabs = {} self.report_stream = BasicStream(self) #gui objects self.lbMessages = None self.showhistory = None self.results = None self.btnRun = None self.information_box = None self.convention_box = None self.refactor_box = None self.warning_box = None self.error_box = None self.fatal_box = None self.txtModule = None self.status = None self.msg_type_dict = None self.init_gui() def init_gui(self): """init helper""" #setting up frames top_frame = Frame(self.root) mid_frame = Frame(self.root) radio_frame = Frame(self.root) res_frame = Frame(self.root) msg_frame = Frame(self.root) check_frame = Frame(self.root) history_frame = Frame(self.root) btn_frame = Frame(self.root) rating_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) mid_frame.pack(side=TOP, fill=X) history_frame.pack(side=TOP, fill=BOTH, expand=True) radio_frame.pack(side=TOP, fill=BOTH, expand=True) rating_frame.pack(side=TOP, fill=BOTH, expand=True) res_frame.pack(side=TOP, fill=BOTH, expand=True) check_frame.pack(side=TOP, fill=BOTH, expand=True) msg_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) #Message ListBox rightscrollbar = Scrollbar(msg_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.lbMessages = Listbox(msg_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white") self.lbMessages.pack(expand=True, fill=BOTH) rightscrollbar.config(command=self.lbMessages.yview) bottomscrollbar.config(command=self.lbMessages.xview) #History ListBoxes rightscrollbar2 = Scrollbar(history_frame) rightscrollbar2.pack(side=RIGHT, fill=Y) bottomscrollbar2 = Scrollbar(history_frame, orient=HORIZONTAL) bottomscrollbar2.pack(side=BOTTOM, fill=X) self.showhistory = Listbox(history_frame, yscrollcommand=rightscrollbar2.set, xscrollcommand=bottomscrollbar2.set, bg="white") self.showhistory.pack(expand=True, fill=BOTH) rightscrollbar2.config(command=self.showhistory.yview) bottomscrollbar2.config(command=self.showhistory.xview) self.showhistory.bind('<Double-Button-1>', self.select_recent_file) self.set_history_window() #status bar self.status = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W) self.status.pack(side=BOTTOM, fill=X) #labels self.lblRatingLabel = Label(rating_frame, text='Rating:') self.lblRatingLabel.pack(side=LEFT) self.lblRating = Label(rating_frame, textvariable=self.rating) self.lblRating.pack(side=LEFT) Label(mid_frame, text='Recently Used:').pack(side=LEFT) Label(top_frame, text='Module or package').pack(side=LEFT) #file textbox self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) #results box rightscrollbar = Scrollbar(res_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(res_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.results = Listbox(res_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white", font="Courier") self.results.pack(expand=True, fill=BOTH, side=BOTTOM) rightscrollbar.config(command=self.results.yview) bottomscrollbar.config(command=self.results.xview) #buttons Button(top_frame, text='Open', command=self.file_open).pack(side=LEFT) Button(top_frame, text='Open Package', command=(lambda : self.file_open(package=True))).pack(side=LEFT) self.btnRun = Button(top_frame, text='Run', command=self.run_lint) self.btnRun.pack(side=LEFT) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #radio buttons self.information_box = IntVar() self.convention_box = IntVar() self.refactor_box = IntVar() self.warning_box = IntVar() self.error_box = IntVar() self.fatal_box = IntVar() i = Checkbutton(check_frame, text="Information", fg=COLORS['(I)'], variable=self.information_box, command=self.refresh_msg_window) c = Checkbutton(check_frame, text="Convention", fg=COLORS['(C)'], variable=self.convention_box, command=self.refresh_msg_window) r = Checkbutton(check_frame, text="Refactor", fg=COLORS['(R)'], variable=self.refactor_box, command=self.refresh_msg_window) w = Checkbutton(check_frame, text="Warning", fg=COLORS['(W)'], variable=self.warning_box, command=self.refresh_msg_window) e = Checkbutton(check_frame, text="Error", fg=COLORS['(E)'], variable=self.error_box, command=self.refresh_msg_window) f = Checkbutton(check_frame, text="Fatal", fg=COLORS['(F)'], variable=self.fatal_box, command=self.refresh_msg_window) i.select() c.select() r.select() w.select() e.select() f.select() i.pack(side=LEFT) c.pack(side=LEFT) r.pack(side=LEFT) w.pack(side=LEFT) e.pack(side=LEFT) f.pack(side=LEFT) #check boxes self.box = StringVar() # XXX should be generated report = Radiobutton(radio_frame, text="Report", variable=self.box, value="Report", command=self.refresh_results_window) rawMet = Radiobutton(radio_frame, text="Raw metrics", variable=self.box, value="Raw metrics", command=self.refresh_results_window) dup = Radiobutton(radio_frame, text="Duplication", variable=self.box, value="Duplication", command=self.refresh_results_window) ext = Radiobutton(radio_frame, text="External dependencies", variable=self.box, value="External dependencies", command=self.refresh_results_window) stat = Radiobutton(radio_frame, text="Statistics by type", variable=self.box, value="Statistics by type", command=self.refresh_results_window) msgCat = Radiobutton(radio_frame, text="Messages by category", variable=self.box, value="Messages by category", command=self.refresh_results_window) msg = Radiobutton(radio_frame, text="Messages", variable=self.box, value="Messages", command=self.refresh_results_window) report.select() report.grid(column=0, row=0, sticky=W) rawMet.grid(column=1, row=0, sticky=W) dup.grid(column=2, row=0, sticky=W) msg.grid(column=3, row=0, sticky=E) stat.grid(column=0, row=1, sticky=W) msgCat.grid(column=1, row=1, sticky=W) ext.grid(column=2, row=1, columnspan=2, sticky=W) #dictionary for check boxes and associated error term self.msg_type_dict = { 'I' : lambda : self.information_box.get() == 1, 'C' : lambda : self.convention_box.get() == 1, 'R' : lambda : self.refactor_box.get() == 1, 'E' : lambda : self.error_box.get() == 1, 'W' : lambda : self.warning_box.get() == 1, 'F' : lambda : self.fatal_box.get() == 1 } self.txtModule.focus_set() def select_recent_file(self, event): """adds the selected file in the history listbox to the Module box""" if not self.showhistory.size(): return selected = self.showhistory.curselection() item = self.showhistory.get(selected) #update module self.txtModule.delete(0, END) self.txtModule.insert(0, item) def refresh_msg_window(self): """refresh the message window with current output""" #clear the window self.lbMessages.delete(0, END) for msg in self.msgs: if (self.msg_type_dict.get(msg[0])()): msg_str = self.convert_to_string(msg) self.lbMessages.insert(END, msg_str) fg_color = COLORS.get(msg_str[:3], 'black') self.lbMessages.itemconfigure(END, fg=fg_color) def refresh_results_window(self): """refresh the results window with current output""" #clear the window self.results.delete(0, END) try: for res in self.tabs[self.box.get()]: self.results.insert(END, res) except: pass def convert_to_string(self, msg): """make a string representation of a message""" if (msg[2] != ""): return "(" + msg[0] + ") " + msg[1] + "." + msg[2] + " [" + msg[3] + "]: " + msg[4] else: return "(" + msg[0] + ") " + msg[1] + " [" + msg[3] + "]: " + msg[4] def process_incoming(self): """process the incoming messages from running pylint""" while self.msg_queue.qsize(): try: msg = self.msg_queue.get(0) if msg == "DONE": self.report_stream.output_contents() return False #adding message to list of msgs self.msgs.append(msg) #displaying msg if message type is selected in check box if (self.msg_type_dict.get(msg[0])()): msg_str = self.convert_to_string(msg) self.lbMessages.insert(END, msg_str) fg_color = COLORS.get(msg_str[:3], 'black') self.lbMessages.itemconfigure(END, fg=fg_color) except Queue.Empty: pass return True def periodic_call(self): """determine when to unlock the run button""" if self.process_incoming(): self.root.after(100, self.periodic_call) else: #enabling button so it can be run again self.btnRun.config(state=NORMAL) def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def halt(self): """program halt placeholder""" return def file_open(self, package=False, _=None): """launch a file browser""" if not package: filename = askopenfilename(parent=self.root, filetypes=[('pythonfiles', '*.py'), ('allfiles', '*')], title='Select Module') else: filename = askdirectory(title="Select A Folder", mustexist=1) if filename == (): return self.txtModule.delete(0, END) self.txtModule.insert(0, filename) def update_filenames(self): """update the list of recent filenames""" filename = self.txtModule.get() if not filename: filename = os.getcwd() if filename+'\n' in self.filenames: index = self.filenames.index(filename+'\n') self.filenames.pop(index) #ensure only 10 most recent are stored if len(self.filenames) == 10: self.filenames.pop() self.filenames.insert(0, filename+'\n') def set_history_window(self): """update the history window with info from the history file""" #clear the window self.showhistory.delete(0, END) # keep the last 10 most recent files try: view_history = open(HOME+HISTORY, 'r') for hist in view_history.readlines(): if not hist in self.filenames: self.filenames.append(hist) self.showhistory.insert(END, hist.split('\n')[0]) view_history.close() except IOError: # do nothing since history file will be created later return def run_lint(self, _=None): """launches pylint""" self.update_filenames() self.root.configure(cursor='watch') self.reporter = GUIReporter(self, output=self.report_stream) module = self.txtModule.get() if not module: module = os.getcwd() #cleaning up msgs and windows self.msgs = [] self.lbMessages.delete(0, END) self.tabs = {} self.results.delete(0, END) self.btnRun.config(state=DISABLED) #setting up a worker thread to run pylint worker = Thread(target=lint_thread, args=(module, self.reporter, self,)) self.periodic_call() worker.start() # Overwrite the .pylint-gui-history file with all the new recently added files # in order from filenames but only save last 10 files write_history = open(HOME+HISTORY, 'w') write_history.writelines(self.filenames) write_history.close() self.set_history_window() self.root.configure(cursor='')
class hillGUI(Frame): """The base class for the hill_calc GUI""" # This is the constructor for the GUI def __init__(self,master=None): # We begin by calling the base class's constructor first Frame.__init__(self,master) # We now have an empty window! # This command sets up a grid structure in the window self.grid() # This loop generates rows and columns in the grid for i in range(10): self.rowconfigure(i,minsize=10) for i in range(3): self.columnconfigure(i,minsize=10) # These are methods which appear below the constructor #self.defineUnits() # this sets up the units I'll be using in the converter self.createWidgets() # this places the elements (or widgets) in the grid # This command "binds" the user's click to a method (varChoice) # This method will determine which variable the user wants (Distance, Mass, Time) self.inputlist.bind("<Button-1>",self.__varChoice) # This is a similar command for the selection of unit self.unitlist.bind("<Button-1>",self.__unitChoice) # Finally, this bind reads in whatever value is in the text box when the user hits return # and carries out the unit conversion for i in range(len(self.inputfield)): self.inputfield[i].bind("<Return>",self.__calcConversion) def createUnitDict(self,mydict,mykeys,myvalues): '''This method takes a set of units and values, and creates a dictionary to store them in''' for i in range(len(myvalues)): mydict[mykeys[i]] = myvalues[i] def createWidgets(self): '''This method creates all widgets and adds them to the GUI''' # Create Widgets in order of appearance # This is not necessary, but makes code easier to read # Start with text telling user what to do self.varlabel = Text(self,height=1, width=20) self.varlabel.insert(END,"Which Variable?") # Place widget on the Frame according to a grid self.varlabel.grid(row=0,column=0,sticky=W) # Second text label asking user which units are being used self.unitlabel = Text(self,height=2,width=20) self.unitlabel.insert(END,"Planet Mass Units?\n (a=AU, Ms=Msol)") self.unitlabel.grid(row=0,column=1,sticky=W) # Third text label asking user for numerical value self.numlabel = Text(self,height=1, width=20) self.numlabel.insert(END,"Enter Variable Values") self.numlabel.grid(row=0,column=2,sticky=W) # This creates a list of options for the user to select self.inputlist = Listbox(self, height=4, selectmode=SINGLE) # Tuple of choices we're going to put in this list self.paramlist = ('Semi Major Axis', 'Planet Mass', 'Star Mass','Hill Radius') # Add each item separately for item in self.paramlist: self.inputlist.insert(END,item) # Add it to the grid self.inputlist.grid(row=1, column=0,rowspan=4,sticky=W) # Add a unit list (several combinations of units allowed) self.unitlist = Listbox(self, height=4,selectmode=SINGLE) self.unitlist.grid(row=1,column=1,rowspan=4, sticky=W) self.massunits = ('Earth Masses','Neptune Masses', 'Jupiter Masses', 'Solar Masses') self.massvalues = ( 3.00343905235e-06, 5.1500311727e-5, 0.000954588419846,1.0) self.massdict = {} self.createUnitDict(self.massdict, self.massunits,self.massvalues) for item in self.massunits: self.unitlist.insert(END,item) # Number Entry Boxes (and Text Labels) self.inputfield = [] self.inputlabels = [] irow = 0 for i in range(len(self.paramlist)): irow = irow+1 self.inputlabels.append(Text(self,height=1,width=20)) self.inputlabels[i].insert(END,self.paramlist[i]) self.inputlabels[i].grid(row=irow,column=2,sticky='N') irow = irow+1 self.inputfield.append(Entry(self)) self.inputfield[i].insert(END, "1.0") self.inputfield[i].grid(row =irow, column=2,sticky='N') # Text Output Box self.outputtext = Text(self, height=1, width=40) self.outputtext.grid(row=7,column=0,columnspan=2,sticky=W) self.outputtext.insert(END, "WAITING: ") # Create the Quit Button self.quitButton=Button(self,text='Quit',command=self.quit) self.quitButton.grid(row =8, column=0, sticky=W) # Event handler functions begin here # This handler defines the choice of units available to the user, # depending on selected variable def __varChoice(self, event): '''Handles the selection of variable: updates the list of units''' # Firstly, delete anything already in the units column # self.unitlist.delete(first=0,last=len(self.myvalues)) num = 0 # Identify which option was clicked on try: num = self.inputlist.curselection()[0] self.varchoice = int(num) except: self.varchoice = 0 return # Get the string associated with this choice selection= self.inputlist.get(self.varchoice) print selection, " chosen" # Highlight current choice in red self.inputlist.itemconfig(self.varchoice, selectbackground='red') def __unitChoice(self,event): '''Handles the selection of units''' num = 0 # Find which number is selected try: num = self.unitlist.curselection()[0] self.unitchoice = int(num) except: self.unitchoice = 0 return # Get the string (i.e. which unit is selected) selection= self.unitlist.get(self.unitchoice) print selection, " chosen" # Highlight current choice in red self.unitlist.itemconfig(self.unitchoice, selectbackground='red') # If statement defines units being used self.massconvert = self.massdict[selection] # Remove all text in the output box, and tell user to define units self.outputtext.delete("1.0",index2=END) self.outputtext.insert(END, "Now Enter Values") # Handler takes current state of GUI, and calculates results def __calcConversion(self,event): '''This method takes the current state of all GUI variables, calculates one of four equations''' print 'Calculating' # Which variable has been selected for calculation? # This decides what equation to use a = self.inputfield[0].get() a=float(a) mp = self.inputfield[1].get() mp=float(mp)*self.massconvert ms = self.inputfield[2].get() ms = float(ms) rh = self.inputfield[3].get() rh = float(rh) if self.varchoice==0: a = rh*(3*ms/mp)*0.3333 value = a elif self.varchoice==1: mp = 3*ms*rh**3/a**3 value = mp elif self.varchoice==2: ms = mp*a**3/(3*rh**3) value = ms elif self.varchoice==3: rh = a *(mp/(3*ms))**0.3333 value = rh # Remove all text in the output box and insert new stuff self.outputtext.delete("1.0",index2=END) self.outputtext.insert(END,str(self.paramlist[self.varchoice])+": "+str(value))
class GraphAnalyzer(Frame): def __init__(self, root): Frame.__init__(self, root) self.__root = root self.__data_manager = DataManager() self.__check_button_type = namedtuple('CheckButtonType', 'widget var') self.__natures = [ "Single Carriageway", "Traffic Island Link", "Dual Carriageway", "Roundabout", "Traffic Island Link At Junction", "Slip Road" ] self.__roads = [ "M3", "M40", "M4", "A1(M)", "M11", "M23", "M20", "M25", "M1", "HIGH STREET", "LONDON ROAD", "HIGH ROAD", "UXBRIDGE ROAD", "STATION ROAD", "BRIGHTON ROAD", "GREEN LANES", "FINCHLEY ROAD", "HARROW ROAD", "NORTH CIRCULAR ROAD", "KINGSTON ROAD", "PORTSMOUTH ROAD", "HERTFORD ROAD", "STAINES ROAD", "CROYDON ROAD", "MAIN ROAD", "CHURCH ROAD", "PARK ROAD" ] self.__motorways = [ "M3", "M40", "M4", "A1(M)", "M11", "M23", "M20", "M25", "M1" ] self.__init_grid() self.__draw_grid() def __init_grid(self): # Road list self.__roads_list_box = Listbox(self.__root, selectmode=MULTIPLE, height=27, exportselection=0) for road in self.__roads: self.__roads_list_box.insert('end', road) # Nature list self.__natures_list_box = Listbox(self.__root, selectmode=MULTIPLE, height=6, width=22, exportselection=0) for nature in self.__natures: self.__natures_list_box.insert('end', nature) # Start with all natures selected self.__natures_list_box.select_set(0, END)\ # Days list self.__days_list_box = Listbox(self.__root, selectmode=MULTIPLE, height=8, width=22, exportselection=0) for day in [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ]: self.__days_list_box.insert('end', day) # Hours list self.__hours_list_box = Listbox(self.__root, selectmode=MULTIPLE, height=24, width=7, exportselection=0) for hour in range(24): self.__hours_list_box.insert('end', hour) # Check button draw overall self.__draw_overall_var = IntVar() self.__draw_overall_check_box = \ Checkbutton(self.__root, text = "Draw Overall Curve?", variable = self.__draw_overall_var, onvalue = 1, offvalue = 0, height=2, width = 20) # Check button draw nature self.__draw_nature_var = IntVar() self.__draw_nature_check_box = \ Checkbutton(self.__root, text = "Draw Curve Per Nature?", variable = self.__draw_nature_var, onvalue = 1, offvalue = 0, height=2, width = 20) # Check button show data self.__show_data_var = IntVar() self.__show_data_var.set(1) self.__show_data_check_box = \ Checkbutton(self.__root, text = "Show data?", variable = self.__show_data_var, onvalue = 1, offvalue = 0, height=2, width = 20) # Go button self.__go_button = Button(self.__root, text='GO', command=lambda: self.__generate_graph()) # Errors text box self.__error_text_box = Text(self.__root, height=28, width=18, fg="red") self.__error_text_box.tag_config('justified', justify=CENTER) def __draw_grid(self): # Roads label and list box Label(self.__root, text="Roads", justify=CENTER).grid(row=0, column=0) self.__roads_list_box.grid(row=1, column=0, rowspan=27) # Natures label and list box Label(self.__root, text="Natures", justify=CENTER).grid(row=0, column=1) self.__natures_list_box.grid(row=1, column=1, rowspan=6) # Days label and list box Label(self.__root, text="Days", justify=CENTER).grid(row=7, column=1) self.__days_list_box.grid(row=8, column=1, rowspan=8) # Hours label and list box Label(self.__root, text="Hours", justify=CENTER).grid(row=0, column=3) self.__hours_list_box.grid(row=1, column=3, rowspan=24) # Check boxes Label(self.__root, text="Drawing Options", justify=CENTER).grid(row=0, column=4) self.__draw_overall_check_box.grid(row=1, column=4, rowspan=2) self.__draw_nature_check_box.grid(row=3, column=4, rowspan=2) self.__show_data_check_box.grid(row=5, column=4, rowspan=2) # Go button self.__go_button.grid(row=10, column=4) # Error Column Label(self.__root, text="Error Report", height=1, width=18, justify=CENTER).grid(row=0, column=5) self.__error_text_box.grid(row=1, column=5, rowspan=28) def __generate_graph(self): # Get parameters roads = tuple( self.__roads_list_box.get(road_index) for road_index in self.__roads_list_box.curselection()) roads = [("classification" if road in self.__motorways else "street", road) for road in roads] natures = tuple( self.__natures_list_box.get(nature_index) for nature_index in self.__natures_list_box.curselection()) days = self.__days_list_box.curselection() hours = self.__hours_list_box.curselection() errors = self.__error_check(roads, natures, days, hours) if len(errors): self.__error_text_box.delete("1.0", END) for e in errors: self.__error_text_box.insert(END, e + '\n', 'justified') else: data = self.__data_manager.get_data("traffic", "rainfall", roads, natures, hours, days) self.__plot_data(data) def __error_check(self, roads, natures, hours, days): errors = [] if not len(roads): errors.append("No roads selected") if not len(natures): errors.append("No natures selected") if not len(hours): errors.append("No hours selected") if not len(days): errors.append("No days selected") if not (self.__show_data_var.get() or self.__draw_nature_var.get() or self.__draw_overall_var.get()): errors.append("Nothing to draw") return errors def __plot_data(self, data): max_depth = data.depth.max() max_speed = data.speed.max() dfs_to_plot = [] if self.__show_data_var.get(): dfs_to_plot.append(data) if self.__draw_overall_var.get(): dfs_to_plot.append( self.__get_best_fit_curve(data, max_depth, max_speed, "Best fit curve")) if self.__draw_nature_var.get(): for nature, nature_df in data.groupby(['nature']): dfs_to_plot.append( self.__get_best_fit_curve(nature_df, max_depth, max_speed, nature)) data = pd.concat(dfs_to_plot, ignore_index=True) fg = sns.FacetGrid(data=data, hue='nature', aspect=1.9, legend_out=False, size=8) fg.map(plt.scatter, 'depth', 'speed', s=20).add_legend(None, "Legend") axes = fg.axes ylim = 120 if max_speed > 200 else max_speed xlim = 1.0 if max_depth < 1.0 else 2.0 axes[0, 0].set_ylim(0, ylim) axes[0, 0].set_xlim(0, xlim) sns.plt.show() def __get_best_fit_curve(self, data, max_depth, max_speed, nature_str): try: popt, pcov = curve_fit(self.curve_func, data.depth, data.speed) except RuntimeError: return pd.DataFrame({ 'depth': [], 'speed': [], 'nature': [], 'identifier': [] }) a = popt[0] b = popt[1] c = popt[2] depths = list(np.arange(0, max_depth, max_depth / 10000.0)) speeds = map(lambda x: self.curve_func(x, a, b, c), depths) if max(speeds) > max_speed: speeds = [s for s in speeds if s <= max_speed] depths = depths[0:len(speeds)] natures = [nature_str] * len(depths) identifiers = [''] * len(depths) return pd.DataFrame({ 'depth': depths, 'speed': speeds, 'nature': natures, 'identifier': identifiers }) def curve_func(self, x, a, b, c): return a * np.exp(-b * x) + c
class JobList(Frame): # NOTE: job_params contains information about a Job in the Joblist # NOTE: plot_args contains information about plotting information, which occurs after the jobs have been and the data files have been created def __init__(self, parent=None, **kwargs): Frame.__init__(self, parent) self.parent = parent self.job_list_yscroll = Scrollbar(self, orient=Tkinter.VERTICAL) self.job_list_xscroll = Scrollbar(self, orient=Tkinter.HORIZONTAL) self.job_list = Listbox(self, xscrollcommand=self.job_list_xscroll, yscrollcommand=self.job_list_yscroll) self.job_list_xscroll['command'] = self.job_list.xview self.job_list_yscroll['command'] = self.job_list.yview self.new_job_frame = Frame(self) add_icon_filename = kwargs['add_icon_filename'] if 'add_icon_filename' in kwargs else None if add_icon_filename == None: self.add_job_button = Button(self.new_job_frame, text='Add Job', command=self.on_add) else: add_icon = PhotoImage(file=add_icon_filename) self.add_job_button = Button(self.new_job_frame, text='Add Job', compound='bottom', image=add_icon, command=self.on_add) self.remove_job_button = Button(self.new_job_frame, text='Remove Job', command=self.on_remove) self.progress_frame = Frame(self) self.progress_value = Tkinter.IntVar() self.progress_bar = Progressbar(self.progress_frame, variable=self.progress_value) self.button_frame = Frame(self) self.process_button = ProcessButton(parent=self.button_frame, start_jobs=self.start_jobs) self.quit_button = QuitButton(parent=self.button_frame, close_other_windows=self.close_top_level_windows) self.run_job = kwargs['run_job'] if 'run_job' in kwargs else None self.create_plots = kwargs['create_plots'] if 'create_plots' in kwargs else None self.log_filename = kwargs['log_filename'] if 'log_filename' in kwargs else None self.bind('<<AskToClearJobs>>', self.ask_to_clear_jobs) self.bind('<<AskToPlotGraphs>>', self.ask_to_plot_graphs) self.bind('<<CreatePlotGUI>>', self.create_plot_gui) self.parent.bind('<ButtonPress>', self.on_press) self.parent.bind('<Configure>', self.on_resize) self.reinit_variables() self.top_level_windows = list() # NOTE: Because there seems to be an issue resizing child widgets when the top level (Tk) widget is being resized, # the resize option will be disabled for this window self.parent.resizable(width=False, height=False) self.lift() def reinit_variables(self): self.job_params = dict() self.last_job_id = -1 self.job_outcomes = list() self.plot_args = list() self.on_button = False def add_job_params(self, input_args): self.job_params = input_args # Add each element to the job list for job in self.job_params: self.add_job(job) def add_job(self, job): try: index_end = job['input_directory'].rindex('/') index_start = job['input_directory'].rindex('/', 0, index_end) input_directory_text = job['input_directory'] list_text = 'Job ' + str(job['job_id']) + ' \'' + input_directory_text + '\'' if job['start'] != None: list_text += ' ' + str(job['start']) if job['end'] != None: list_text += ' to' if job['end'] != None: list_text += ' ' + str(job['end']) if job['job_id'] > self.last_job_id: self.last_job_id = job['job_id'] self.job_list.insert(Tkinter.END, list_text) # Add the list text to the job params as an optional parameter to read later to display in a future Graph GUI (or for any other useful purpose) job['list_text'] = list_text # The line number is used wrt the GUI to indicate which job in the job list is being currently executed. job['line_number'] = self.job_list.size() - 1 #print str(job['line_number']) self.job_params[job['job_id']] = job except KeyError as ke: # Should show some error message indicating that there is a problem. pass #print str(self.job_params) #print 'Added Job ' + str(job['job_id']) def ask_to_clear_jobs(self, event): for job in self.job_params.itervalues(): line_number = job['line_number'] self.job_list.itemconfig(line_number, foreground='black') # Update parent to refresh widget appearance self.parent.update() # Reactivate process button self.process_button.config(state = Tkinter.NORMAL) # Note: Display a pop-up that tells the user that the job is done and asks if the job list should be cleared. clearList = msg.askyesno(title='Jobs Finished', message='All jobs have been completed. Would you like to clear the job list?', master=self) if clearList: self.clear_list() def ask_to_plot_graphs(self, event): # TODO: Add a dialog that also asks to create a graph of the 'Other Type Of Plot' plotGraphs = msg.askyesno(title='Plot Graphs', message='Create plots of data?', master=self) if not plotGraphs: return # TODO: Iterate through the jobs to display to the user an interface that asks if they want to graphs of the outputs if self.create_plots != None: output_files_list = list() for job_outcome in self.job_outcomes: for output_outcomes in job_outcome[2]: (station, output_directory, output_files) = output_outcomes for output_files_tuple in output_files: for output_file_tuple in output_files_tuple: (output_file, output_file_success) = output_file_tuple if output_file_success: # If there is a list text variable (the 4th (or 3rd by 0 based index) variable), then add it to our output list if len(job_outcome) == 4: output_files_list.append([output_file, job_outcome[3]]) else: output_files_list.append([output_file]) plots_thread = PlotsThread(self.create_plots, output_files_list, self) plots_thread.start() def add_plot(self, args=dict()): self.plot_args.append(args) def finished_adding_plots(self): self.event_generate('<<CreatePlotGUI>>', when='tail') def create_plot_gui(self, event): # TODO: This should be replaced with a new window that allows the user to drag and drop the icons from one frame to another graph_names = list() for args in self.plot_args: graph_name = args['output_file'] graph_names.append(graph_name) dnd_graphs_frame = Dnd.createFrame(self, 'Drag and Drop Output Plots', graph_names, self.finish_creating_plot_gui) # This is the entry point for the def finish_creating_plot_gui(self, plot_labels): graph_count = 1 for plot_label in plot_labels: for args in self.plot_args: #print 'Looking in ' + args['plot_title'] + ' for ' + plot_label #print 'The plot label is: ' + plot_label #print 'The output file is: ' + args['output_file'] if plot_label == args['output_file']: #print 'Creating graph ' + str(graph_count) graph_count += 1 graph_window = ModelRunnerGraphGUI.GraphWindow(parent=self, title=args['window_title'], df=args['df'], plot=args['plot'], plot_title=args['plot_title'], y_label=args['y_label'], log_filename=self.log_filename) graph_window.set_grid() self.top_level_windows.append(graph_window) #print 'Creating plot GUI # Have to clear out list here instead of clear_list because clear_list() removes plot_args before this method has a chance to read # them and create the appropriate plot graph windows self.reinit_variables() # Clear all the elements in the list def clear_list(self): # Save plot args because they are need later in this run plot_args = self.plot_args self.reinit_variables() # Restore the plot args self.plot_args = plot_args self.job_list.delete(0, self.job_list.size()) self.progress_value.set(0) # Update parent to refresh widget appearance self.parent.update() def on_add(self): single_job = JobParameters(parent=self.parent, beginning_year=1950, ending_year=2100, job_id=self.last_job_id + 1, entry=self) single_job.set_grid() def on_remove(self): selection = self.job_list.curselection() for line_number in selection: line_text = self.job_list.get(line_number) job_id = int(line_text[4:line_text.index(' ', 4)]) job = self.job_params.pop(job_id) self.job_list.delete(line_number) print 'Removed Job ' + str(job['job_id']) # Fix line number for line_number in range(self.job_list.size()): line_text = self.job_list.get(line_number) job_id = int(line_text[4:line_text.index(' ', 4)]) #print 'Job ' + str(job_id) + ' is now on line ' + str(line_number) self.job_params[job_id]['line_number'] = line_number def set_grid(self): self.grid(sticky=Tkinter.N + Tkinter.S + Tkinter.W + Tkinter.E, padx=4, pady=4) self.columnconfigure(0, minsize=600) self.rowconfigure(0, minsize=300) self.job_list.grid(row=0, column=0, sticky=Tkinter.N + Tkinter.S + Tkinter.E + Tkinter.W) self.job_list_yscroll.grid(row=0, column=1, sticky=Tkinter.N + Tkinter.S + Tkinter.W) self.job_list_xscroll.grid(row=1, column=0, sticky=Tkinter.E + Tkinter.W + Tkinter.N) self.new_job_frame.grid(row=2, column=0, pady=3, sticky=Tkinter.W) self.remove_job_button.grid(row=0, column=0) self.add_job_button.grid(row=0, column=1) self.progress_frame.grid(row=3, column=0, pady=3) self.progress_frame.columnconfigure(0, minsize=600) self.progress_bar.grid(row=0, column=0, sticky=Tkinter.E + Tkinter.W + Tkinter.N + Tkinter.S) self.button_frame.grid(row=4, column=0, sticky=Tkinter.E + Tkinter.W + Tkinter.N + Tkinter.S) self.button_frame.columnconfigure(0, minsize=300) self.button_frame.columnconfigure(1, minsize=300) self.process_button.pack(side=Tkinter.RIGHT) self.quit_button.pack(side=Tkinter.RIGHT) def start_jobs(self): # If there are no queued jobs then simply return if len(self.job_params) == 0 or len(self.job_list.get(0)) == 0: return # Deactivate the process button self.process_button.config(state = Tkinter.DISABLED) # Initialize the progress bar self.progress_value.set(0) # Update parent to refresh widget appearance self.parent.update() # Start process thread jobs_thread = JobsThread(self.job_params, self.run_job, self.on_update, self.on_resume) jobs_thread.start() self['cursor'] = 'wait' def on_update(self, status, line_number, step): if status == 'init': self.job_list.itemconfig(line_number, foreground='green') self.job_list.activate(line_number) elif status == 'success': self.job_list.itemconfig(line_number, foreground='blue') elif status == 'fail': self.job_list.itemconfig(line_number, foreground='red') self.progress_value.set(step) # Update parent to refresh widget appearance self.parent.update() def on_resume(self, job_outcomes=list()): self.progress_value.set(100) self.job_outcomes = job_outcomes self.event_generate('<<AskToClearJobs>>', when='tail') self.event_generate('<<AskToPlotGraphs>>', when='tail') self['cursor'] = 'arrow' def close_top_level_windows(self): #print 'Closing other top level windows' for top_level_window in self.top_level_windows: if top_level_window: top_level_window.withdraw() top_level_window.destroy() def notify_of_close(self, top_level_window): if top_level_window in self.top_level_windows: #print 'Removing top level window' self.top_level_windows.remove(top_level_window) def on_press(self, event): self.on_button = True self.release_pattern = "<B%d-ButtonRelease-%d>" % (event.num, event.num) self.parent.bind(self.release_pattern, self.on_release) def on_release(self, event): self.on_button = False def on_resize(self, event): self.parent.lift() if self.on_button: self.set_grid() def on_close(self): self.plot_args = list() self.withdraw() self.destroy()
class GUI(Frame): # In intialize the object, taking in the parent as in input parameter def __init__(self, parent): Frame.__init__(self, parent) # Initialize the api self.api = API() # Set the ip and port to communicate with the master server self.SERVER_IP = config.masterip self.SERVER_PORT = config.port # Set the initial server status to 0, will change to 1 if server is active # self.serverStatus = 0 # Declare a list which will hold the files that have been flagged for deletion self.toDelete = [] self.parent = parent # Initialize the GUI self.initUI() # Function to initialize UI def initUI(self): # Set the name of the UI window self.parent.title("Bennington File System Client") # Set the style using the default theme self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) # Set the "Open File" options self.file_opt = options = {} # Allow for any file to be choosable options["defaultextension"] = "" options["filetypes"] = "" # Set the directory window will open up to initially options["initialdir"] = "C:\\" options["parent"] = self # Create a label object which holds the text labeling the listbox lbl = Label(self, text="Bennington File System Files List", foreground="black") # Place the text in the top left lbl.grid(column=0, row=0, pady=4, padx=5) # Create the listbox, which will contain a list of all the files on the system self.area = Listbox(self, height=20) # Place the lisbox in the UI frame self.area.grid(row=1, column=0, columnspan=1, rowspan=10, padx=5, sticky=N + W + E + S) # Ask the master server which files it has, then populate the listbox with the response self.getFiles() # Create a button labeled 'Upload', and bind the uploadFile() function to it uploadbtn = Button(self, text="Upload", command=self.uploadFile) # Place the button in the UI frame uploadbtn.grid(row=1, column=3) # Create a button labeled 'Download', and bind the downloadFile() function to it dwnbtn = Button(self, text="Download", command=self.downloadFile) # Place the button in the UI frame dwnbtn.grid(row=2, column=3) # Create a button labeled 'Delete', and bind the deleteFile() function to it delbtn = Button(self, text="Delete", command=self.deleteFile) # Place the button in the UI frame delbtn.grid(row=3, column=3) # Create a button labeled 'Undelete', and bind the undeleteFile() function to it undelbtn = Button(self, text="Undelete", command=self.undeleteFile) # Place the button in the UI frame undelbtn.grid(row=4, column=3) # Create a button labeled 'Refresh List', and bind the getFiles() function to it refbtn = Button(self, text="Refresh List", command=self.getFiles) # Place the button in the UI frame refbtn.grid(row=5, column=3) # Create a button labeled 'Quit', and bind the exitProgram() function to it quitButton = Button(self, text="Quit", command=self.exitProgram) # Place the button in the UI frame quitButton.grid(sticky=W, padx=5, pady=4) # Downloads the active selection in the listbox def downloadFile(self): # Get the filename from the active listbox item fileName = self.currentSelectionFileName() # Call the API read function to get all the data associated with that file self.api.read(fileName, 0, -1, fileName) # Get the file name of the active selection in the listbox def currentSelectionFileName(self): # Get the index of the active selection index = self.currentSelectionIndex() # From the listbox object, pass in the index to get the filename fileName = self.area.get(index) return fileName # Get the index of the active selection in the listbox def currentSelectionIndex(self): # Get the index of the active selection index = self.area.curselection()[0] return index # Mark the active selection in the listbox for deletion def deleteFile(self): # Get the index of the current active selection index = self.currentSelectionIndex() # Get the filename of the current active selection filename = self.area.get(index) # Call the API function to mark file for deletion self.api.delete(filename) # Change the background color of the selection to denote it has been marked for deletion self.area.itemconfig(index, {"bg": "salmon"}) # Append the filename to the toDelete list self.toDelete.append(filename) # Unmarks the active selection in the listbox for deletion def undeleteFile(self): # Get the index of the current active selection index = self.currentSelectionIndex() # Get the filename of the current active selection filename = self.area.get(index) # See if the file has been marked for deletion if filename in self.toDelete: # Call the API function to unmark file for deletion self.api.undelete(filename) # Change the background color of the selection to denote it is no longer marked for deletion self.area.itemconfig(index, {"bg": "white"}) # Remove the filename from the toDelete list self.toDelete.remove(filename) # Upload a file from local machine to the distributed file system def uploadFile(self): # Get the file name and file path of the file the user wants to upload fileinfo = self.openFile() # Create a file with the filename provided self.api.create(fileinfo[0]) # Append the file data from the file at the given file path self.api.append(fileinfo[0], fileinfo[1], 1) # Once that is complete, refresh the file list in the listbox self.getFiles() # Prompt the user to select a file def openFile(self): # Prompt the user to select a file, and store the returned file path filepath = tkFileDialog.askopenfilename(**self.file_opt) # Parse the filepath, and store the last element of the split as the file name filename = filepath.split("/")[-1] # Return a list containing the file name and file path return [filename, filepath] # Get the list of existing files from the master server def getFiles(self): try: # Get the file data using the API's fileList() function # At this stage, the data has lots of extra things in it, so it needs to be cleaned up data = self.api.fileList() # Split the string at every * character data = re.split("\*", data) # Declare an empty array which will hold the file names found from the parsing fileNames = [] for item in data: # Split the element at every ^ character tempitem = re.split("\^", item) for thing in tempitem: # If the element has a | in it, but is not just a |, then it is the filename if "|" in thing and not thing == "|": # Append the filename (with the | stripped out) to the fileNames list fileNames.append(thing.strip("|")) # If the file is marked for deletion and still in the fileNames list # keep the file in the toDelete list temp = [] for item in self.toDelete: if item in fileNames: temp.append(item) # Update the toDelete list self.toDelete = temp # Remove all entries in the listbox self.area.delete(0, END) # Populate the listbox with the file names returned from the master for item in fileNames: self.area.insert(END, item) self.checkIfMarked(item) except Exception as e: raise e # Check to see if the provided file name exists in the toDelete list def checkIfMarked(self, fileName): # If the file name is in the toDelete list if fileName in self.toDelete: # Change the background color of the element to denote that it has been marked for deletion self.area.itemconfig(END, {"bg": "salmon"}) # An exit function that quits the UI (any additional clean up pre-close should go in here) def exitProgram(self): self.quit()
class ListPage(BasePage): def __init__(self, parent, controller): BasePage.__init__(self, parent, controller) self.target_keep_profile_var = IntVar() self.mutex = Lock() def prepare(self): self.deviceList.config(state='normal') self.versionList.config(state='disabled') self.engList.config(state='disabled') self.packageList.config(state='disabled') self.ok.config(state='disabled') self.setData(self.controller.data) self.setDeviceList(self.data.keys()) self.controller.setDefault(self, self.controller.loadOptions()) self.deviceList.focus_force() def printErr(self, message): self.errLog.config(text=message) def setData(self, data): self.data = data def setupView(self, title="Select your flash", data=None): if (data): self.setData(data) self.errLog = Label(self, text="") self.errLog.grid(row=4, column=1, columnspan=3, sticky="NWSE") self.desc = Label(self, text=title, font=TITLE_FONT) self.desc.grid(row=0, column=0, columnspan=2) self.ok = Button(self, text='Next', command=lambda: self.confirm()) self.ok.grid(row=4, column=3, sticky="E") self.ok.config(state="disabled") # bind self.target_keep_profile_var (IntVar) to keepProfileCheckbutton, 1 is True, 0 is Flase self.keepProfileCheckbutton = Checkbutton( self, text="Keep User Profile (BETA)", variable=self.target_keep_profile_var) self.keepProfileCheckbutton.grid(row=5, column=0, columnspan=4, sticky="W") self.deviceLabel = Label(self, text="Device", font=TITLE_FONT) self.deviceLabel.grid(row=1, column=0) self.deviceList = Listbox(self, exportselection=0) self.deviceList.grid(row=2, column=0) self.deviceList.bind('<<ListboxSelect>>', self.deviceOnSelect) self.deviceList.config(state="disabled") self.versionLabel = Label(self, text="Branch", font=TITLE_FONT) self.versionLabel.grid(row=1, column=1) self.versionList = Listbox(self, exportselection=0) self.versionList.grid(row=2, column=1) self.versionList.bind('<<ListboxSelect>>', self.versionOnSelect) self.versionList.config(state="disabled") self.engLabel = Label(self, text="Build Type", font=TITLE_FONT) self.engLabel.grid(row=1, column=2) self.engList = Listbox(self, exportselection=0) self.engList.grid(row=2, column=2) self.engList.bind('<<ListboxSelect>>', self.engOnSelect) self.engList.config(state="disabled") self.packageLabel = Label(self, text="Gecko/Gaia/Full", font=TITLE_FONT) self.packageLabel.grid(row=1, column=3) self.packageList = Listbox(self, exportselection=0) self.packageList.grid(row=2, column=3) self.packageList.bind('<<ListboxSelect>>', self.packageOnSelect) self.packageList.config(state="disabled") self.bidVar = StringVar() Label(self, text="Build ID").grid(row=3, column=0, sticky='E') self.bidInput = Entry(self, textvariable=self.bidVar, width="30") self.bidInput.grid(row=3, column=1, columnspan=2, sticky="W") self.bidVar.set('latest') # binding unfocus for build id field self.bidInput.bind('<FocusOut>', self.updateBuildId) # binding the Return Key to each componments self.deviceList.bind('<Return>', self.pressReturnKey) self.versionList.bind('<Return>', self.pressReturnKey) self.engList.bind('<Return>', self.pressReturnKey) self.packageList.bind('<Return>', self.pressReturnKey) self.bidInput.bind('<Return>', self.pressReturnKey) self.ok.bind('<Return>', self.pressReturnKey) def selection_all_checked(self): result = False if len(self.deviceList.curselection()) == 0: self.logger.log('Please select device.', status_callback=self.printErr) self.ok.config(state="disabled") self.deviceList.focus_set() elif len(self.versionList.curselection()) == 0: self.logger.log('Please select branch.', status_callback=self.printErr) self.ok.config(state="disabled") self.versionList.focus_set() elif len(self.engList.curselection()) == 0: self.logger.log('Please select user or engineer build.', status_callback=self.printErr) self.ok.config(state="disabled") self.engList.focus_set() elif len(self.packageList.curselection()) == 0: self.logger.log('Please select package to flash.', status_callback=self.printErr) self.ok.config(state="disabled") self.packageList.focus_set() elif len(self.bidVar.get()) != 14 and self.bidVar.get() != 'latest': self.logger.log( 'Please enter build ID to flash or use "latest" to get the newest', status_callback=self.printErr) self.logger.log(self.bidVar.get() + ' is invalid: ' + str(len(self.bidVar.get()))) self.bidVar.set('latest') else: result = True return result def updateBuildId(self, event=None): # if the value is '' or 'latest', the set the build_id option as ''. buildId = self.bidVar.get() if buildId == 'latest': buildId = '' elif len(buildId) != 14: self.printErr("Invalid build ID: " + buildId + ", reset to latest") buildId = '' self.bidVar.set('latest') else: if len(self.engList.curselection()) != 0: self.refreshPackageList() def pressReturnKey(self, event=None): if self.selection_all_checked(): self.ok.config(state="disabled") self.confirm() def deviceOnSelect(self, evt): self.setVersionList() def versionOnSelect(self, evt): self.setEngList() def engOnSelect(self, evt): self.refreshPackageList() # hard coded right now def packageOnSelect(self, evt): self.ok.config(state="normal") def confirm(self): self.mutex.acquire() try: if self.selection_all_checked(): self.ok.config(state="disabled") params = [] package = self.packageList.get( self.packageList.curselection()[0]) self.logger.log('Start to flash [' + package + '].', status_callback=self.printErr) if (PathParser._IMAGES in package): params.append(PathParser._IMAGES) else: if (PathParser._GAIA in package): params.append(PathParser._GAIA) if (PathParser._GECKO in package): params.append(PathParser._GECKO) keep_profile = (self.target_keep_profile_var.get() == 1) archives = self.controller.do_download(params) self.controller.do_flash(params, archives, keep_profile=keep_profile) self.packageList.select_clear(0, END) self.controller.transition(self) finally: self.mutex.release() def setDeviceList(self, device=[]): self.deviceList.delete(0, END) for li in device: self.deviceList.insert(END, li) def setVersionList(self, version=[]): if len(version) == 0: version = self.data[self.deviceList.get( self.deviceList.curselection())] self.versionList.config(state="normal") self.engList.config(state="disabled") self.packageList.config(state="disabled") self.ok.config(state="disabled") self.versionList.delete(0, END) for li in version: self.versionList.insert(END, li) def setEngList(self, eng=[]): if len(eng) == 0: device = self.deviceList.get(self.deviceList.curselection()) version = self.versionList.get(self.versionList.curselection()) eng = self.data[device][version] self.engList.config(state="normal") self.packageList.config(state="disabled") self.ok.config(state="disabled") self.engList.delete(0, END) for li in eng: self.engList.insert(END, li) def refreshPackageList(self): self.mutex.acquire() try: self.packageList.config(state="normal") self.ok.config(state="normal") self.packageList.delete(0, END) device = self.deviceList.get(self.deviceList.curselection()) version = self.versionList.get(self.versionList.curselection()) eng = self.engList.get(self.engList.curselection()) buildId = '' if (len(self.bidVar.get()) == 0 or self.bidVar.get() == 'latest') else self.bidVar.get() package = self.controller.getPackages( self.data[device][version][eng]['src'], build_id=buildId) if len(package) == 0: self.logger.log('Invalid build ID: ' + buildId + ', reset to latest', status_callback=self.printErr) buildId = '' self.bidVar.set('latest') package = self.controller.getPackages( self.data[device][version][eng]['src'], build_id=buildId) for li in package: self.packageList.insert(END, li) finally: self.mutex.release()
class PraiseTexGUI(object): """Graphical interface for selecting songs and compiling them""" def __init__(self, songdir="songs"): # data self.songs = [] self.praisetex = PraiseTex(songdir) self.root = Tk() button_width = 6 button_padx = "2m" button_pady = "1m" frame_padx = "3m" frame_pady = "2m" label_padx = "3m" label_pady = "2m" listbox_width = 30 listbox_height = 20 frame_title_font = ("TkDefaultFont", 14) text_font = ("TkDefaultFont", 12) menu_font = ("TkDefaultFont", 12) button_font = ("TkDefaultFont", 12) # window properties self.root.title("praisetex") self.root.option_add("*Font", ("TkDefaultFont", 12)) # menu menubar = Menu(self.root) menubar.tk.call('tk', 'scaling', 2.5) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Open Directory", command=self.openDirectory) filemenu.add_command(label="Exit", command=self.root.quit) menubar.add_cascade(label="File", menu=filemenu) self.root.config(menu=menubar) # left section self.availableSongsTitle = Label(self.root, text="Available Songs", font=frame_title_font, padx=label_padx, pady=label_pady) self.availableSongsTitle.grid(row=0, column=0) self.availableSongsFrame = Frame(self.root) self.availableSongsFrame.grid(row=1, column=0, padx=frame_padx, pady=frame_pady) self.availableSongsScroll = Scrollbar(self.availableSongsFrame, orient=VERTICAL) self.availableSongs = Listbox(self.availableSongsFrame, width=listbox_width, height=listbox_height, selectmode=EXTENDED, yscrollcommand=self.availableSongsScroll.set, exportselection=0) self.availableSongsScroll.config(command=self.availableSongs.yview) self.availableSongsScroll.pack(side=RIGHT, fill=Y) self.availableSongs.pack() self.button = Button(self.root, text="Refresh", command=self.refreshSongList) self.button.grid(row=2, column=0) # middle section self.addRemoveButtonFrame = Frame(self.root) self.addRemoveButtonFrame.grid(row=1, column=1) self.addSongButton = Button(self.addRemoveButtonFrame, text="Add", command=self.addSong) self.addSongButton.pack(side=TOP, padx=button_padx, pady=button_pady) self.removeSongButton = Button(self.addRemoveButtonFrame, text="Remove", command=self.removeSong) self.removeSongButton.pack(side=BOTTOM) # right section self.songsToCompileTitle = Label(self.root, text="Songs to Compile", font=frame_title_font, padx=label_padx, pady=label_pady) self.songsToCompileTitle.grid(row=0, column=2) self.songsToCompileFrame = Frame(self.root) self.songsToCompileFrame.grid(row=1, column=2, padx=frame_padx, pady=frame_pady) self.songsToCompileScroll = Scrollbar(self.songsToCompileFrame, orient=VERTICAL) self.songsToCompile = Listbox(self.songsToCompileFrame, width=listbox_width, height=listbox_height, selectmode=EXTENDED, yscrollcommand=self.songsToCompileScroll.set, exportselection=0, font=text_font) self.songsToCompileScroll.config(command=self.songsToCompile.yview) self.songsToCompileScroll.pack(side=RIGHT, fill=Y) self.songsToCompile.pack() self.compileButtonFrame = Frame(self.root) self.compileButtonFrame.grid(row=2, column=2) self.chordsButton = Button(self.compileButtonFrame, text="Chords", command=self.compileChords) self.chordsButton.pack(side=LEFT, padx=button_padx, pady=button_pady) self.slidesButton = Button(self.compileButtonFrame, text="Slides", command=self.compileSlides) self.slidesButton.pack(side=RIGHT, padx=button_padx, pady=button_pady) # status bar self.status = Label(self.root, text="Ready", padx="1m") self.status.grid(row=3, column=0, columnspan=3, sticky=W) self.refreshSongList() def run(self): """Start event loop of GUI""" self.root.mainloop() def refreshSongList(self): """Sync up the filenames in songlist with files in directory""" # clear song list self.availableSongs.delete(0, END) # add song files self.songs = self.praisetex.refreshSongList() for song in self.songs: self.availableSongs.insert(END, song) self.updateStatus("{0} songs found in directory {1}".format(len(self.songs), self.praisetex.getSongDirectory())) def openDirectory(self): """Selects directory for songs""" dirname = filedialog.askdirectory(parent=self.root, initialdir=self.praisetex.getSongDirectory(), title='Please select a directory') if len(dirname) > 0: self.praisetex.setSongDirectory(dirname) self.updateStatus("Song directory set to {0}".format(dirname)) def addSong(self): """Add song to compile list""" selectedSongs = self.availableSongs.curselection() # get index of where to insert selected songs insertIndex = self.songsToCompile.curselection() if len(insertIndex) > 0: insertIndex = int(insertIndex[0]) # convert to integer else: insertIndex = -1 # song should be appended if len(selectedSongs) == 0: # do nothing pass elif len(selectedSongs) == 1: # insert the one song song = selectedSongs[0] songtitle = self.availableSongs.get(song) if insertIndex == -1: end = len(self.praisetex.compile) self.praisetex.addSong(end, songtitle) self.songsToCompile.insert(END, songtitle) else: self.praisetex.addSong(insertIndex+1, songtitle) self.songsToCompile.insert(insertIndex+1, songtitle) else: # more than one song songList = [self.availableSongs.get(song) for song in selectedSongs] if insertIndex != -1: songList.reverse() for songtitle in songList: self.praisetex.addSong(insertIndex+1, songtitle) self.songsToCompile.insert(insertIndex+1, songtitle) else: # add songs to the end for songtitle in songList: end = len(self.praisetex.compile) self.praisetex.addSong(end, songtitle) self.songsToCompile.insert(END, songtitle) self.updateStatus("{0} songs added".format(len(selectedSongs))) def removeSong(self): """Remove song from compile list""" songindexes = list(self.songsToCompile.curselection()) songindexes.reverse() for index in songindexes: self.praisetex.removeSong(index) self.songsToCompile.delete(index) self.updateStatus("{0} songs removed".format(len(songindexes))) def compileChords(self): """Compile a chord sheet from selected songs""" self.updateStatus("Compiling Songs") error = self.praisetex.compileChords() if error: self.updateStatus("pdflatex has failed") else: self.updateStatus("Compiled chords.pdf") def compileSlides(self): """Compile slides from selected songs""" self.updateStatus("Compiling Songs") error = self.praisetex.compileSlides() if error: self.updateStatus("pdflatex has failed") else: self.updateStatus("Compiled slides.pdf") def updateStatus(self, message): """Update the status bar""" self.status.config(text=message)
class LintGui(object): """Build and control a window to interact with pylint""" def __init__(self, root=None): """init""" self.root = root or Tk() self.root.title('Pylint') #reporter self.reporter = None #message queue for output from reporter self.msg_queue = Queue.Queue() self.msgs = [] self.visible_msgs = [] self.filenames = [] self.rating = StringVar() self.tabs = {} self.report_stream = BasicStream(self) self.differ = differ.Differ() #gui objects self.lbMessages = None self.showhistory = None self.results = None self.btnRun = None self.information_box = None self.convention_box = None self.refactor_box = None self.warning_box = None self.error_box = None self.fatal_box = None self.txtModule = None self.status = None self.msg_type_dict = None self.init_gui() def init_gui(self): """init helper""" #setting up frames top_frame = Frame(self.root) mid_frame = Frame(self.root) radio_frame = Frame(self.root) res_frame = Frame(self.root) msg_frame = Frame(self.root) check_frame = Frame(self.root) history_frame = Frame(self.root) btn_frame = Frame(self.root) rating_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) mid_frame.pack(side=TOP, fill=X) history_frame.pack(side=TOP, fill=BOTH, expand=True) radio_frame.pack(side=TOP, fill=BOTH, expand=True) rating_frame.pack(side=TOP, fill=BOTH, expand=True) res_frame.pack(side=TOP, fill=BOTH, expand=True) check_frame.pack(side=TOP, fill=BOTH, expand=True) msg_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) # Binding F5 application-wide to run lint self.root.bind('<F5>', self.run_lint) #Message ListBox rightscrollbar = Scrollbar(msg_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.lbMessages = Listbox(msg_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white") self.lbMessages.bind("<Double-Button-1>", self.show_sourcefile) self.lbMessages.pack(expand=True, fill=BOTH) rightscrollbar.config(command=self.lbMessages.yview) bottomscrollbar.config(command=self.lbMessages.xview) #Message context menu self.mnMessages = Menu(self.lbMessages, tearoff=0) self.mnMessages.add_command(label="View in sourcefile", command=self.show_sourcefile) self.mnMessages.add_command(label="Add to ignore patchfile", command=self.add_to_ignore_patchfile) self.lbMessages.bind("<Button-3>", self.show_messages_context) #History ListBoxes rightscrollbar2 = Scrollbar(history_frame) rightscrollbar2.pack(side=RIGHT, fill=Y) bottomscrollbar2 = Scrollbar(history_frame, orient=HORIZONTAL) bottomscrollbar2.pack(side=BOTTOM, fill=X) self.showhistory = Listbox(history_frame, yscrollcommand=rightscrollbar2.set, xscrollcommand=bottomscrollbar2.set, bg="white") self.showhistory.pack(expand=True, fill=BOTH) rightscrollbar2.config(command=self.showhistory.yview) bottomscrollbar2.config(command=self.showhistory.xview) self.showhistory.bind('<Double-Button-1>', self.select_recent_file) self.set_history_window() #status bar self.status = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W) self.status.pack(side=BOTTOM, fill=X) #labels self.lblRatingLabel = Label(rating_frame, text='Rating:') self.lblRatingLabel.pack(side=LEFT) self.lblRating = Label(rating_frame, textvariable=self.rating) self.lblRating.pack(side=LEFT) Label(mid_frame, text='Recently Used:').pack(side=LEFT) Label(top_frame, text='Module or package').pack(side=LEFT) #file textbox self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) #results box rightscrollbar = Scrollbar(res_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(res_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.results = Listbox(res_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white", font="Courier") self.results.pack(expand=True, fill=BOTH, side=BOTTOM) rightscrollbar.config(command=self.results.yview) bottomscrollbar.config(command=self.results.xview) #buttons Button(top_frame, text='Open', command=self.file_open).pack(side=LEFT) Button(top_frame, text='Open Package', command=(lambda: self.file_open(package=True))).pack(side=LEFT) self.btnRun = Button(top_frame, text='Run', command=self.run_lint) self.btnRun.pack(side=LEFT) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #radio buttons self.information_box = IntVar() self.convention_box = IntVar() self.refactor_box = IntVar() self.warning_box = IntVar() self.error_box = IntVar() self.fatal_box = IntVar() i = Checkbutton(check_frame, text="Information", fg=COLORS['(I)'], variable=self.information_box, command=self.refresh_msg_window) c = Checkbutton(check_frame, text="Convention", fg=COLORS['(C)'], variable=self.convention_box, command=self.refresh_msg_window) r = Checkbutton(check_frame, text="Refactor", fg=COLORS['(R)'], variable=self.refactor_box, command=self.refresh_msg_window) w = Checkbutton(check_frame, text="Warning", fg=COLORS['(W)'], variable=self.warning_box, command=self.refresh_msg_window) e = Checkbutton(check_frame, text="Error", fg=COLORS['(E)'], variable=self.error_box, command=self.refresh_msg_window) f = Checkbutton(check_frame, text="Fatal", fg=COLORS['(F)'], variable=self.fatal_box, command=self.refresh_msg_window) i.select() c.select() r.select() w.select() e.select() f.select() i.pack(side=LEFT) c.pack(side=LEFT) r.pack(side=LEFT) w.pack(side=LEFT) e.pack(side=LEFT) f.pack(side=LEFT) #check boxes self.box = StringVar() # XXX should be generated report = Radiobutton(radio_frame, text="Report", variable=self.box, value="Report", command=self.refresh_results_window) rawMet = Radiobutton(radio_frame, text="Raw metrics", variable=self.box, value="Raw metrics", command=self.refresh_results_window) dup = Radiobutton(radio_frame, text="Duplication", variable=self.box, value="Duplication", command=self.refresh_results_window) ext = Radiobutton(radio_frame, text="External dependencies", variable=self.box, value="External dependencies", command=self.refresh_results_window) stat = Radiobutton(radio_frame, text="Statistics by type", variable=self.box, value="Statistics by type", command=self.refresh_results_window) msgCat = Radiobutton(radio_frame, text="Messages by category", variable=self.box, value="Messages by category", command=self.refresh_results_window) msg = Radiobutton(radio_frame, text="Messages", variable=self.box, value="Messages", command=self.refresh_results_window) sourceFile = Radiobutton(radio_frame, text="Source File", variable=self.box, value="Source File", command=self.refresh_results_window) report.select() report.grid(column=0, row=0, sticky=W) rawMet.grid(column=1, row=0, sticky=W) dup.grid(column=2, row=0, sticky=W) msg.grid(column=3, row=0, sticky=W) stat.grid(column=0, row=1, sticky=W) msgCat.grid(column=1, row=1, sticky=W) ext.grid(column=2, row=1, sticky=W) sourceFile.grid(column=3, row=1, sticky=W) #dictionary for check boxes and associated error term self.msg_type_dict = { 'I': lambda: self.information_box.get() == 1, 'C': lambda: self.convention_box.get() == 1, 'R': lambda: self.refactor_box.get() == 1, 'E': lambda: self.error_box.get() == 1, 'W': lambda: self.warning_box.get() == 1, 'F': lambda: self.fatal_box.get() == 1 } self.txtModule.focus_set() def select_recent_file(self, event): """adds the selected file in the history listbox to the Module box""" if not self.showhistory.size(): return selected = self.showhistory.curselection() item = self.showhistory.get(selected) #update module self.txtModule.delete(0, END) self.txtModule.insert(0, item) def refresh_msg_window(self): """refresh the message window with current output""" #clear the window self.lbMessages.delete(0, END) self.visible_msgs = [] for msg in self.msgs: if (self.msg_type_dict.get(msg.C)()): self.visible_msgs.append(msg) msg_str = convert_to_string(msg) self.lbMessages.insert(END, msg_str) fg_color = COLORS.get(msg_str[:3], 'black') self.lbMessages.itemconfigure(END, fg=fg_color) def refresh_results_window(self): """refresh the results window with current output""" #clear the window self.results.delete(0, END) try: for res in self.tabs[self.box.get()]: self.results.insert(END, res) except: pass def process_incoming(self): """process the incoming messages from running pylint""" while self.msg_queue.qsize(): try: msg = self.msg_queue.get(0) if msg == "DONE": self.report_stream.output_contents() return False #adding message to list of msgs self.msgs.append(msg) #displaying msg if message type is selected in check box if (self.msg_type_dict.get(msg.C)()): self.visible_msgs.append(msg) msg_str = convert_to_string(msg) self.lbMessages.insert(END, msg_str) fg_color = COLORS.get(msg_str[:3], 'black') self.lbMessages.itemconfigure(END, fg=fg_color) except Queue.Empty: pass return True def periodic_call(self): """determine when to unlock the run button""" if self.process_incoming(): self.root.after(100, self.periodic_call) else: #enabling button so it can be run again self.btnRun.config(state=NORMAL) def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def halt(self): """program halt placeholder""" return def file_open(self, package=False, _=None): """launch a file browser""" if not package: filename = askopenfilename(parent=self.root, filetypes=[('pythonfiles', '*.py'), ('allfiles', '*')], title='Select Module') else: filename = askdirectory(title="Select A Folder", mustexist=1) if filename == (): return self.txtModule.delete(0, END) self.txtModule.insert(0, filename) def update_filenames(self): """update the list of recent filenames""" filename = self.txtModule.get() if not filename: filename = os.getcwd() if filename + '\n' in self.filenames: index = self.filenames.index(filename + '\n') self.filenames.pop(index) #ensure only 10 most recent are stored if len(self.filenames) == 10: self.filenames.pop() self.filenames.insert(0, filename + '\n') def set_history_window(self): """update the history window with info from the history file""" #clear the window self.showhistory.delete(0, END) # keep the last 10 most recent files try: view_history = open(HOME + HISTORY, 'r') for hist in view_history.readlines(): if not hist in self.filenames: self.filenames.append(hist) self.showhistory.insert(END, hist.split('\n')[0]) view_history.close() except IOError: # do nothing since history file will be created later return def run_lint(self, _=None): """launches pylint""" self.update_filenames() self.root.configure(cursor='watch') self.reporter = GUIReporter(self, output=self.report_stream) module = self.txtModule.get() if not module: module = os.getcwd() #cleaning up msgs and windows self.msgs = [] self.visible_msgs = [] self.lbMessages.delete(0, END) self.tabs = {} self.results.delete(0, END) self.btnRun.config(state=DISABLED) #setting up a worker thread to run pylint worker = Thread(target=lint_thread, args=( module, self.reporter, self, )) self.periodic_call() worker.start() # Overwrite the .pylint-gui-history file with all the new recently added files # in order from filenames but only save last 10 files write_history = open(HOME + HISTORY, 'w') write_history.writelines(self.filenames) write_history.close() self.set_history_window() self.root.configure(cursor='') def show_sourcefile(self, event=None): selected = self.lbMessages.curselection() if not selected: return msg = self.visible_msgs[int(selected[0])] scroll = msg.line - 3 if scroll < 0: scroll = 0 self.tabs["Source File"] = open(msg.abspath, "r").readlines() self.box.set("Source File") self.refresh_results_window() self.results.yview(scroll) self.results.select_set(msg.line - 1) def show_messages_context(self, event): """Show the message listbox's context menu""" # Select the item that was clicked index = self.lbMessages.nearest(event.y) self.lbMessages.selection_clear(0, END) self.lbMessages.selection_set(index) self.lbMessages.activate(index) self.mnMessages.tk_popup(event.x_root, event.y_root) def add_to_ignore_patchfile(self, event=None): """ Add the selected message to the ignore patchfile. This means that this message will now be ignored by pylint-patcher. """ selected = self.lbMessages.curselection() if not selected: return selected_index = int(selected[0]) msg = self.visible_msgs[selected_index] self.differ.add_disable_pragma(msg.abspath, msg.line, msg.symbol) self.differ.diff() del self.msgs[self.msgs.index(msg)] del self.visible_msgs[selected_index] self.lbMessages.delete(selected_index)
class DirList(object): def __init__(self, initdir=None): self.top = Tk() self.label = Label( self.top, text='用户管理 v0.8', font=('Helvetica', 12, 'bold'), ) self.label.pack() self.cwd = StringVar(self.top) self.dirl = Label(self.top, fg='blue', font=('Helvetica', 12, 'bold')) self.dirl.pack() self.dirfm = Frame(self.top) self.dirsb = Scrollbar(self.dirfm) self.dirsb.pack(side=RIGHT, fill=Y) self.dirs = Listbox(self.dirfm, height=15, width=50, yscrollcommand=self.dirsb.set) self.dirs.bind('<Double-1>', self.setdirandgo) self.dirsb.config(command=self.dirs.yview) self.dirs.pack(side=LEFT, fill=BOTH) self.dirfm.pack() self.dirn = Entry(self.top, width=50, textvariable=self.cwd) self.dirn.bind('<Return>', self.dols) self.dirn.pack() self.bfm = Frame(self.top) self.clr = Button(self.bfm, text='Clear', command=self.clrdir, activeforeground='white', activebackground='blue') self.ls = Button(self.bfm, text='List Directory', command=self.dols, activeforeground='white', activebackground='green') self.quit = Button(self.bfm, text='Quit', command=self.top.quit, activeforeground='white', activebackground='red') self.clr.pack(side=LEFT) self.ls.pack(side=LEFT) self.quit.pack(side=LEFT) self.bfm.pack() if initdir: self.cwd.set(os.curdir) self.dols() def clrdir(self, ev=None): self.cwd.set('') def setdirandgo(self, ev=None): self.last = self.cwd.get() self.dirs.config(selectbackground='red') check = self.dirs.get(self.dirs.curselection()) if not check: check = os.curdir self.cwd.set(check) self.dols() def dols(self, ev=None): error = '' tdir = self.cwd.get() if not tdir: tdir = os.curdir if not os.path.exists(tdir): error = tdir + ': no such file' elif not os.path.isdir(tdir): error = tdir + ': not a directory' if error: self.cwd.set(error) self.top.update() sleep(2) if not (hasattr(self, 'last') and self.last): self.last = os.curdir self.cwd.set(self.last) self.dirs.config( selectbackground='LightSkyBlue') self.top.update() return self.cwd.set( 'FETCHING DIRECTORY CONTENTS...') self.top.update() dirlist = os.listdir(tdir) dirlist.sort() os.chdir(tdir) self.dirl.config(text=os.getcwd()) self.dirs.delete(0, END) self.dirs.insert(END, os.curdir) self.dirs.insert(END, os.pardir) for eachFile in dirlist: self.dirs.insert(END, eachFile) self.cwd.set(os.curdir) self.dirs.config( selectbackground='LightSkyBlue')