class PasswordDialog(Dialog): def __init__(self, title, prompt, parent): self.prompt = prompt Dialog.__init__(self, parent, title) def body(self, master): from tkinter import Label from tkinter import Entry from tkinter import Checkbutton from tkinter import IntVar from tkinter import W self.checkVar = IntVar() Label(master, text=self.prompt).grid(row=0, sticky=W) self.e1 = Entry(master) self.e1.grid(row=0, column=1) self.cb = Checkbutton(master, text="Save to keychain", variable=self.checkVar) self.cb.pack() self.cb.grid(row=1, columnspan=2, sticky=W) self.e1.configure(show='*') def apply(self): self.result = (self.e1.get(), self.checkVar.get() == 1)
def create_other_buttons(self): f = self.make_frame()[0] btn = Checkbutton(f, anchor="w", variable=self.recvar, text="Recurse down subdirectories") btn.pack(side="top", fill="both") btn.select()
def initUI(self): self.parent.title("Checkbutton") self.pack(fill=BOTH, expand=1) self.var = IntVar() cb = Checkbutton(self, text="Show title", variable=self.var, command=self.onClick) cb.select() cb.place(x=50, y=50)
def openfile(): name = askopenfilename() nam = name.split("/") g=nam[-1].split(".") grup= g[0] print(nam,g) print(grup) fitxer = open(name, mode='r') for linia in fitxer: coordinates = linia.split('\t') N,X,Y,Z,C = coordinates N = coordinates[0] X = coordinates[1] Y = coordinates[2] Z = coordinates[3] C = [coordinates[4]] if len(coordinates)>5: i=5 for c in range(len(coordinates)-5): C.append(coordinates[i]) codis.add(c) i = i+1 codis.add(C[0]) i= 0 r = 2 c = 1 if askyesno('codis...','Vols unir per codis?'): codis_linia.clear() tria = tk.Toplevel() ok = tk.Button(tria, text='ok', width=25, command=tria.destroy) ok.grid(column=0, row=0,columnspan=5) for item in codis: codis_linia[str(item)]= IntVar() chb =Checkbutton(tria,text = str(item), variable = codis_linia[item], onvalue = True, offvalue = False, height=5 ) if c > 5: c = 1 r = r+1 chb.grid(column =c, row=r) c = c+1 label2.config(text= 'Quins codis son linies')
def __init__(self, master): column0_padx = 24 row_pady = 36 #Label 1 lbl_testcase_exec = Label(master, text="Test case execution", wraplength=100, anchor='w', justify='left') lbl_results_cmp = Label(master, text="Results comparison", wraplength=100, justify='left') lbl_tolerance = Label(master, text="Tolerance (5%)", wraplength=100) testcase_exec = Checkbutton(master) results_cmp = Checkbutton(master) tolerance = Entry(master, width=4) lbl_analysis = Label(master, text="Analysis Library") analysis_lib = Entry(master, width=30) lbl_testcase_exec.grid(row=0, column=2, padx=20, pady=12, sticky='w') lbl_results_cmp.grid(row=0, column=3, pady=12, sticky='w') lbl_tolerance.grid(row=0, column=4, padx=20, pady=12, sticky='wn') lbl_analysis.grid(row=1, column=0, sticky='w', padx=column0_padx) analysis_lib.grid(row=1, column=1, sticky='w') testcase_exec.grid(row=1, column=2, padx=20, sticky='w') results_cmp.grid(row=1, column=3, sticky='w') tolerance.grid(row=1, column=4, padx=20, sticky='w') #Label 2 lbl_ref_analysis = Label( master, text="Reference Analysis Libary Version", wraplength=150, justify='left', pady=row_pady) ref_analysis_lib = Entry(master, width=30) lbl_ref_analysis.grid(row=2, column=0, sticky='w', padx=column0_padx) ref_analysis_lib.grid(row=2, column=1, sticky='w') # version lbl_version = Label(master, text="Version under Test") version = Label(master, text="vA.B.C.D") lbl_version.grid(row=3, column=0, sticky='w', padx=column0_padx) version.grid(row=3, column=1, sticky='w') # test all lbl_testall = Label(master, text="Test All") testall = Checkbutton(master) lbl_testall.grid(row=4, column=0, pady=row_pady, padx=column0_padx, sticky='w') testall.grid(row=4, column=1, sticky='w') # buttons bottom_frame = Frame(master) bottom_frame.grid(row=5, column=1, columnspan=3, sticky='w') btn_start = Button(bottom_frame, text = "Go", width=7) btn_start.pack(side='left') btn_commit = Button(bottom_frame, text="Commit", width=7) btn_commit.pack(side='left', padx=80) btn_exit = Button(bottom_frame, text="Exit", width=7) btn_exit.pack(side='left')
class ConfigWindow(Toplevel): '''Represent the configuration window.''' def __init__(self, parent=None): '''Constructor of ConfigWindow.''' Toplevel.__init__(self, parent) self.title('Configuracion') self._states = [IntVar(value=CONFIG['GAME_TRACKING']), IntVar(value=CONFIG['CONFIRM_EXIT'])] self._cbox_gtrack = Checkbutton(self, text='Seguimiento del juego') self._cbox_gtrack.config(variable=self._states[0]) self._cbox_confexit = Checkbutton(self, text='Confirmacion al salir') self._cbox_confexit.config(variable=self._states[1]) self._cbox_gtrack.grid(row=0, column=0, sticky=W) self._cbox_confexit.grid(row=1, column=0, sticky=W) self._button_cancel = Button(self, text='Cancelar', command=self.destroy) self._button_cancel.grid(row=3, column=1, sticky=E) self._button_accept = Button(self, text='Guardar y Salir') self._button_accept.config(command=self.save_config) self._button_accept.grid(row=3, column=0, sticky=E) def save_config(self): pass def get_state_game_tracking(self): return self._states[0].get() def get_state_confirm_exit(self): return self._states[1].get()
def create_option_buttons(self): "Fill frame with Checkbuttons bound to SearchEngine booleanvars." frame = self.make_frame("Options")[0] engine = self.engine options = [(engine.revar, "Regular expression"), (engine.casevar, "Match case"), (engine.wordvar, "Whole word")] if self.needwrapbutton: options.append((engine.wrapvar, "Wrap around")) for var, label in options: btn = Checkbutton(frame, anchor="w", variable=var, text=label) btn.pack(side="left", fill="both") if var.get(): btn.select() return frame, options # for test
def create_option_buttons(self): """Return (filled frame, options) for testing. Options is a list of SearchEngine booleanvar, label pairs. A gridded frame from make_frame is filled with a Checkbutton for each pair, bound to the var, with the corresponding label. """ frame = self.make_frame("Options")[0] engine = self.engine options = [(engine.revar, "Regular expression"), (engine.casevar, "Match case"), (engine.wordvar, "Whole word")] if self.needwrapbutton: options.append((engine.wrapvar, "Wrap around")) for var, label in options: btn = Checkbutton(frame, anchor="w", variable=var, text=label) btn.pack(side="left", fill="both") if var.get(): btn.select() return frame, options
def __init__(self): Tk.__init__(self) self.minsize(200, 250) self.result = None self._model_name = '' self._icon_name = '' self.title("Viewer generator") self.grid_columnconfigure(0, weight=0) self.grid_columnconfigure(1, weight=1) self.grid_rowconfigure(0, weight=0) self.grid_rowconfigure(1, weight=1) self.resizable(True, True) Label(self, text='Model').grid(row=0, column=0, sticky=(N, E)) self.models = ttk.Combobox( self, textvariable=StringVar(), state='readonly') self.models.grid(row=0, column=1, sticky=(N, W, E, S), padx=3, pady=3) mainframe = Frame(self, bd=1, relief=SUNKEN) mainframe.grid( row=1, column=0, columnspan=2, sticky=(N, S, E, W), padx=3, pady=3) current_row = 0 current_col = 0 self.check = [] for value in ('add', 'list', 'edit', 'search', 'modify', 'listing', 'show', 'label', 'delete', 'print'): chkbtn_val = IntVar() chkbtn = Checkbutton(mainframe, text=value, variable=chkbtn_val) chkbtn.grid( row=current_row, column=current_col, sticky=W, padx=3, pady=3) self.check.append((value, chkbtn_val)) current_col += 1 if current_col == 2: current_col = 0 current_row += 1 Label(mainframe, text='Icon').grid( row=(current_row + 1), column=0, columnspan=2, sticky=(N, W, E, S), padx=3) self.icons = ttk.Combobox( mainframe, textvariable=StringVar(), state='readonly') self.icons.grid( row=(current_row + 2), column=0, columnspan=2, sticky=(N, W, E, S), padx=3) btnframe = Frame(self, bd=1) btnframe.grid(row=2, column=0, columnspan=2) Button(btnframe, text="OK", width=10, command=self.cmd_ok).grid( row=1, column=0, sticky=(N, S, E, W), padx=5, pady=3) Button(btnframe, text="Cancel", width=10, command=self.cmd_cancel).grid( row=1, column=1, sticky=(N, S, E, W), padx=5, pady=3)
def _makesetting(setting_window, conf): setting_label = Label(setting_window, text=_('Setting'), font=('courier', 20, 'bold')) setting_label.pack(side=TOP) style_container = Frame(setting_window) style_container.pack(side=TOP) style_label = Label(style_container, text=_('Display wallpaper in style: '), font=('courier', 15, 'bold')) style_label.pack(side=LEFT) style_combobox = Combobox(style_container) available_style = {'3': 'zoom', '2': 'scaled', '1': 'stretched', '0': 'centered', '4': 'wallpaper'} style_combobox['value'] = (_('centered'), _('stretched'), _('scaled'), _('zoom'), _('wallpaper')) style_combobox.state(['readonly']) style_combobox.current(int(conf['style'])) style_combobox.pack(side=LEFT) random_container = Frame(setting_window) random_container.pack(side=TOP) random_label = Label(random_container, text=_('Choose wallpaper randomly? '), font=('courier', 15, 'bold')) random_label.pack(side=LEFT) random_checkbutton = Checkbutton(random_container) random_checkbutton.pack(side=LEFT) if conf['random'] == "1": random_checkbutton.select() interval_container = Frame(setting_window) interval_container.pack(side=TOP) interval_label = Label(interval_container, text=_('Change wallpaper every '), font=('courier', 15, 'bold')) interval_label.pack(side=LEFT) interval_text = Text(interval_container, height=1, width=4) interval_text.insert(END, conf['interval']) interval_text.pack(side=LEFT) minute_label = Label(interval_container, text=_(' minutes.'), font=('courier', 15, 'bold')) minute_label.pack(side=LEFT)
def __init__(self,master=None): Frame.__init__(self,master) #Sides of Dice labelSides=Label(self,text="Sides") labelSides.grid(row=0,column=0) self.sides=StringVar() self.sides.set(20) spinboxSides=Spinbox(self,from_=1,to=20,increment=1,width=4) spinboxSides.config(textvariable=self.sides, font="sans 24", justify="center") spinboxSides.grid(row=0,column=1) #Number of Dices labelNumber=Label(self,text="Number") labelNumber.grid(row=1,column=0) self.number=StringVar() self.number.set(1) spinboxNumber=Spinbox(self,from_=1,to=30,increment=1,width=4) spinboxNumber.config(textvariable=self.number, font="sans 24", justify="center") spinboxNumber.grid(row=1,column=1) #Modifier labelModifier=Label(self,text="Modifier") labelModifier.grid(row=2,column=0) self.modifier=StringVar() self.modifier.set(0) spinboxModifier=Spinbox(self,from_=-5,to=5,increment=1,width=4) spinboxModifier.config(textvariable=self.modifier, font="sans 24", justify="center") spinboxModifier.grid(row=2,column=1) #Hide Checkbox labelHide=Label(self, text="Hide") labelHide.grid(row=2, column=2) self.hide=IntVar() self.hide.set(0) checkbuttonHide=Checkbutton(self,variable=self.hide) checkbuttonHide.grid(row=2,column=3) #Result display self.result=StringVar() self.result.set("") labelResult1=Label(self,text="Result") labelResult1.grid(row=1, column=4) labelResult2=Label(self,text=self.result.get(),relief=SUNKEN,width=4) labelResult2.grid(row=1,column=5) #Button to roll buttonRoll=Button(self,text="Roll!", command=self.roll) buttonRoll.grid(row=2,column=5)
def _init_ui(self): # Label to specify video link lbl_video_url = Label(self, text="Video URL:") lbl_video_url.place(x=20, y=20) # Entry to enter video url entr_video_url = Entry(self, width=50, textvariable=self._video_url) entr_video_url.place(x=100, y=20) # Checkbutton to extract audio cb_extract_audio = Checkbutton(self, var=self._extract_audio, text="Only keep audio") cb_extract_audio.pack() cb_extract_audio.place(x=20, y=60) # Button to browse for location b_folder_choose = Button(self, text="Choose output directory", command=self.ask_directory) b_folder_choose.place(x=150, y=90) # Button to start downloading b_start_download = Button(self, text="Start download", command=self.download) b_start_download.place(x=20, y=90) # Log window to log progress self._logger.place(x=20, y=130)
def makeIgnitionFrame(self): self.fullScreen = Int() self.fram_ignition = Frame(self, bd=4, relief=self.style, width= ignition_frame_width, height= ignition_frame_height) self.butt_generate = Button(self.fram_ignition, text= " -- GENERATE -- ", width=111, command= self.generate) self.butt_draw = Button(self.fram_ignition, text= " -- DRAW -- ", width=100, command= self.drawAll, state= 'disabled') self.butt_print = Button(self.fram_ignition, text= "Save Image", command= self.saveImage, state= 'disabled') self.chek_fullscrn = CheckBox(self.fram_ignition, text= "Fullscreen", variable= self.fullScreen, state= 'disabled') self.fram_ignition.grid(row=1, column=0, columnspan=2) self.butt_generate.grid(row=0, column=0, columnspan=2) self.butt_draw.grid( row=1, column=0) self.butt_print.grid( row=0, column=2, rowspan= 2, sticky='ns') self.chek_fullscrn.grid(row=1, column=1)
def __init__(self, client): # Basic setup super(Preferences, self).__init__() self.client = client # Setup the variables used self.echo_input = BooleanVar() self.echo_input.set(self.client.config['UI'].getboolean('echo_input')) self.echo_input.trace("w", self.echo_handler) self.logging = BooleanVar() self.logging.set(self.client.config['logging'].getboolean('log_session')) self.logging.trace('w', self.logging_handler) self.log_dir = self.client.config['logging']['log_directory'] # Build the actual window and widgets prefs = Toplevel(self) prefs.wm_title("Preferences") echo_input_label = Label(prefs, text="Echo Input:") logging_label = Label(prefs, text='Log to file:') echo_checkbox = Checkbutton(prefs, variable=self.echo_input) logging_checkbox = Checkbutton(prefs, variable=self.logging) logging_button_text = 'Choose file...' if self.log_dir == "" else self.log_dir logging_button = Button(prefs, text=logging_button_text, command=self.logging_pick_location) # Pack 'em in. echo_input_label.grid(row=0, column=0) echo_checkbox.grid(row=0, column=1) logging_label.grid(row=1, column=0) logging_checkbox.grid(row=1, column=1) logging_button.grid(row=1, column=2)
def __init__(self, **kwargs): super().__init__(**kwargs) self._isReady = True self.vsb = Scrollbar(self, orient="vertical") self.text = Text( self, height = 10, yscrollcommand=self.vsb.set, bg = self.master.cget('bg'), wrap = 'word') self.vsb.config(command=self.text.yview) self.vsb.pack(side='right', fill='y') self.text.pack(side='left', fill='both', expand=True) # Create the list of checkboxes self._listOfTypes = [] for currType in dsTypes.__all__: v = BooleanVar(value = 1) cb = Checkbutton(self, text = '%s' % currType, anchor = W, width = 15, variable = v) cb.var = v # Easy access to checkbox's current value e = Entry(self) e.delete(0, END) e.insert(0, '<suffix>.<file_extension>') self._listOfTypes.append((cb, e)) self.text.window_create('end', window=cb) self.text.window_create('end', window=e) self.text.insert('end', '\n') # Forces one checkbox per line # Insert help message self.text.insert('end', self.__doc__) # This MUST follow insertion and positioning of # the checkboxes/entries self.text.config(state = DISABLED)
def __init__(self): self.action = None self.root = root = Tk() root.title('Never gonna fold you up') root.protocol("WM_DELETE_WINDOW", self.close) root.pack_propagate(True) scrollbar = Scrollbar(root, orient=tkinter.VERTICAL) self.problem_list = Listbox(root, exportselection=False, yscrollcommand=scrollbar.set) self.problem_list.pack(expand=True, fill=tkinter.BOTH, side=tkinter.LEFT) scrollbar.config(command=self.problem_list.yview) scrollbar.pack(side=tkinter.LEFT, fill=tkinter.Y) self.problem_list.bind('<<ListboxSelect>>', lambda evt: self.populate_problem_canvas()) self.problem_canvas = Canvas(root, bd=1, relief=tkinter.SUNKEN, width=500, height=500) self.problem_canvas.pack(expand=True, fill=tkinter.BOTH, side=tkinter.LEFT) self.problem_canvas.bind("<Configure>", lambda evt: self.populate_problem_canvas()) button_frame = Frame(root) button_frame.pack(fill=tkinter.Y, side=tkinter.LEFT) # Reposition the figure so it's center of mass is at 0.5, 0.5 v = IntVar() self.center_cb = Checkbutton(button_frame, text="center", variable=v, command=lambda: self.populate_problem_canvas()) self.center_cb.var = v self.center_cb.pack(side=tkinter.TOP) # Use meshes.reconstruct_facets instead of polygon/hole logic. v = IntVar() self.reconstruct_cb = Checkbutton(button_frame, text="reconstruct", variable=v, command=lambda: self.populate_problem_canvas()) self.reconstruct_cb.var = v self.reconstruct_cb.pack(side=tkinter.TOP) self.populate_problems() self.current_problem_name = None self.current_problem = None
def __init__(self, parent, model, index, status_model): Frame.__init__(self, parent) Observable.__init__(self) self.model = model self.index = index self.status_model = status_model self.var = IntVar() self.var.set(model.get_checked()) self.progress_var = IntVar() self.progress_status = ProgressStatus.undefined self.check_button = Checkbutton(self, text=model.get_label, variable=self.var, command=self._check_changed) self.progress_bar = Progressbar(self, orient='horizontal', mode='indeterminate', variable=self.progress_var) self.check_button.pack(side=LEFT, fill="both", expand=True) self.model.add_listener(self._model_changed)
def __init__(self, parent, model): Frame.__init__(self, parent) Observable.__init__(self) self._model = model # Create variables and initialise to zero self._checked_var = IntVar() self._progress_var = IntVar() self._checked_var.set(0) self._progress_var.set(0) self._current_gui_checked_state = CheckStatus.undefined self._current_gui_progress_state = ProgressStatus.undefined self.check_button = Checkbutton(self, text=model.get_label(), variable=self._checked_var, command=self._user_check_changed) self.progress_bar = Progressbar(self, orient='horizontal', mode='indeterminate', variable=self._progress_var) self.check_button.pack(side=LEFT, fill="both", expand=True) self._update() self._model.add_listener(self._model_changed)
def body(self, master): from tkinter import Label from tkinter import Entry from tkinter import Checkbutton from tkinter import IntVar from tkinter import W self.checkVar = IntVar() Label(master, text=self.prompt).grid(row=0, sticky=W) self.e1 = Entry(master) self.e1.grid(row=0, column=1) self.cb = Checkbutton(master, text="Save to keychain", variable=self.checkVar) self.cb.pack() self.cb.grid(row=1, columnspan=2, sticky=W) self.e1.configure(show='*')
class ProgressCheckButton(Frame, Observable): def __init__(self, parent, model, index, status_model): Frame.__init__(self, parent) Observable.__init__(self) self.model = model self.index = index self.status_model = status_model self.var = IntVar() self.var.set(model.get_checked()) self.progress_var = IntVar() self.progress_status = ProgressStatus.undefined self.check_button = Checkbutton(self, text=model.get_label, variable=self.var, command=self._check_changed) self.progress_bar = Progressbar(self, orient='horizontal', mode='indeterminate', variable=self.progress_var) self.check_button.pack(side=LEFT, fill="both", expand=True) self.model.add_listener(self._model_changed) def _model_changed(self, new_status): model_state = self.model.get_checked() gui_state = self.var.get() if model_state is not gui_state: self.model.set_checked(gui_state) def refresh_check(self): if self.status_model.is_checked_force_reload(): self.check_button.select() else: self.check_button.deselect() def is_checked(self): return self.var.get() def _progress_status_changed(self, new_status): self._refresh_progress() def _refresh_progress(self): status = self.status_model.get_status() if not status == self.progress_status: if status == ProgressStatus.in_progress: self.progress_bar.pack(side=RIGHT, fill="both", expand=True) else: self.progress_bar.pack_forget() def _check_changed(self): new_checked = self.var.get() if new_checked is not self.model.get_checked(): self.model.set_checked(new_checked) if new_checked is not self.status_model.is_checked(): self._notify(self.index, new_checked)
class ProgressListBoxItem(Frame, Observable): def __init__(self, parent, model): Frame.__init__(self, parent) Observable.__init__(self) self._model = model # Create variables and initialise to zero self._checked_var = IntVar() self._progress_var = IntVar() self._checked_var.set(0) self._progress_var.set(0) self._current_gui_checked_state = CheckStatus.undefined self._current_gui_progress_state = ProgressStatus.undefined self.check_button = Checkbutton(self, text=model.get_label(), variable=self._checked_var, command=self._user_check_changed) self.progress_bar = Progressbar(self, orient='horizontal', mode='indeterminate', variable=self._progress_var) self.check_button.pack(side=LEFT, fill="both", expand=True) self._update() self._model.add_listener(self._model_changed) def _model_changed(self): self.update() def _update(self): # Update check status model_check_state = self._model.get_check_status() if model_check_state is not self._current_gui_checked_state: self._current_gui_checked_state = model_check_state # if self.status_model.is_checked_force_reload(): if model_check_state: self.check_button.select() else: self.check_button.deselect() # Update progress status model_progress_state = self._model.get_progress_status if not model_progress_state == self._current_gui_progress_state: self._current_gui_progress_state = model_progress_state if model_progress_state == ProgressStatus.in_progress: self.progress_bar.pack(side=RIGHT, fill="both", expand=True) else: self.progress_bar.pack_forget() def _user_check_changed(self): new_checked = self._checked_var.get() if new_checked is not self._model.get_check_status(): self._model.manual_set_checked(new_checked)
def __init__(self,master): self.master = master refresh() frame = Frame(master) frame.pack() # variable to store checkbox value self.keeplogin = IntVar() self.UserLabel = Label(frame, text="Username") self.PassLabel = Label(frame, text="Password") self.HashLabel = Label(frame, text="HashCode") self.UserLabel.grid(row=0,column=0,sticky=W) self.PassLabel.grid(row=1,column=0,sticky=W) self.HashLabel.grid(row=2,column=0,sticky=W) self.UserEntry = Entry(frame) self.PassEntry = Entry(frame,show='*') self.HashEntry = Entry(frame) self.UserEntry.grid(row=0,column=1,columnspan=2) self.PassEntry.grid(row=1,column=1,columnspan=2) self.HashEntry.grid(row=2,column=1,columnspan=2) self.ImgBox = ImageTk.PhotoImage(file='image.png') self.ImgLabel = Label(frame, image=self.ImgBox) self.ImgLabel.image = self.ImgBox self.ImgLabel.grid(row=3,column=0,columnspan=2) self.RefreshBtn = Button(frame, text="Refresh",command=self.refresh) self.RefreshBtn.grid(row=3,column=2,sticky=W+E) self.KeepLoginChkBtn = Checkbutton(frame,text='KeepLogin',variable=self.keeplogin) self.KeepLoginChkBtn.grid(row=4,column=0) self.LoginBtn = Button(frame,text='Login',command=self.login) self.LoginBtn.grid(row=4,column=1,columnspan=2,sticky=W+E)
def create_check_buttons(self): self.cb_frame = LabelFrame(self, text="Global Settings") for cb in CHECK_BUTTONS: label = cb target_parent = self.cb_frame if isinstance(CHECK_BUTTONS[cb], dict) and 'sub_frame' in list(CHECK_BUTTONS[cb].keys()): target_parent = getattr(self, CHECK_BUTTONS[cb]['sub_frame']) setattr(self, cb, IntVar(value=type(CHECK_BUTTONS[cb]) == dict and CHECK_BUTTONS[cb]['val'] or CHECK_BUTTONS[cb])) self.this_cb = Checkbutton(target_parent, text=label, variable=getattr(self, cb)) self.this_cb.bind('<Button-1>', self.check_boxes_handler) self.this_cb.disable = (type(CHECK_BUTTONS[cb]) == dict and 'disable' in list(CHECK_BUTTONS[cb].keys())) self.this_cb.grid(sticky=W, column=0, row=len(target_parent.winfo_children())) self.this_cb.ref = cb for but in GLOBAL_BUTTONS: label = but ele = GLOBAL_BUTTONS[but] this_but = Button(self.cb_frame, text=but) this_but.bind('<ButtonRelease-1>', getattr(self, ele['handler'])) this_but.ref = but this_but.grid(sticky=W, column=0, row=len(self.cb_frame.winfo_children())) self.cb_frame.grid(column=0, row=0, rowspan=10, sticky=N)
if i.get() == 0: result += f'button {all_buttons[all_values.index(i)]},' if result != '' and result[-1] == ',': result = result[0:-1] label['text'] = 'OFF: ' + result if __name__ == '__main__': root = Tk() value1 = IntVar() value2 = IntVar() value3 = IntVar() all_values = [value1, value2, value3] check_button1 = Checkbutton(root, text='1', variable=value1, offvalue=0, onvalue=1) check_button2 = Checkbutton(root, text='2', variable=value2, offvalue=0, onvalue=1) check_button3 = Checkbutton(root, text='3', variable=value3, offvalue=0, onvalue=1) all_buttons = [ check_button1['text'], check_button2['text'], check_button3['text'] ]
def trials_rejection_screen(self): self.data_entries = {} Label(self.getFrame(0,0.1,0,0.3),text='Raw Data & Reject Trials', font=self.medium_font).pack(fill='both',expand=1) Label(self.getFrame(0.1,0.15,0.02,0.08),text='Trigger Number', wraplength=0.05*self.size,font=self.small_font ).pack(fill='both',expand=1) trigger = self.make_option_menu(self.getFrame(0.1,0.15,0.08,0.15), self.data['triggers'].split(',')) Label(self.getFrame(0.15,0.2,0.02,0.08),text='Trigger Delay (ms)', wraplength=0.05*self.size,font=self.small_font ).pack(fill='both',expand=1) delay = Entry(self.getFrame(0.15,0.2,0.08,0.15),font=self.small_font) delay.pack(fill='both',expand=1) delay.focus_set() delay.insert(0,'0') self.data_entries['Delay'] = delay Label(self.getFrame(0.2,0.25,0.02,0.08),text='EOG Threshold', wraplength=0.05*self.size,font=self.small_font ).pack(fill='both',expand=1) EOG_threshold = self.make_option_menu(self.getFrame(0.2,0.25,0.08,0.15), ['70']) self.data_entries['EOG Threshold'] = EOG_threshold Label(self.getFrame(0.1,0.15,0.16,0.22),text='Threshold', wraplength=0.05*self.size,font=self.small_font ).pack(fill='both',expand=1) threshold = self.make_option_menu(self.getFrame(0.1,0.15,0.22,0.3), ['1000']) self.data_entries['Threshold'] = threshold Label(self.getFrame(0.15,0.17,0.16,0.22),text='Baseline', wraplength=0.06*self.size,font=self.small_font ).pack(fill='both',expand=1) Label(self.getFrame(0.15,0.17,0.22,0.26),text='min', wraplength=0.04*self.size,font=self.small_font ).pack(fill='both',expand=1) Label(self.getFrame(0.15,0.17,0.26,0.3),text='max', wraplength=0.04*self.size,font=self.small_font ).pack(fill='both',expand=1) bl_min = Entry(self.getFrame(0.17,0.2,0.22,0.26),font=self.small_font) bl_min.pack(fill='both',expand=1) bl_min.focus_set() bl_min.insert(0,str(int(self.default_bl_tmin*100))) bl_max = Entry(self.getFrame(0.17,0.2,0.26,0.3),font=self.small_font) bl_max.pack(fill='both',expand=1) bl_max.focus_set() bl_max.insert(0,str(int(self.default_bl_tmax*100))) self.data_entries['Baseline Min'] = bl_min self.data_entries['Baseline Max'] = bl_max bl_normalize = IntVar() bl_normalize.set(1) bl_normalize_radio = Checkbutton(self.getFrame(0.18,0.2,0.16,0.22), text='Norm',variable=bl_normalize, command=self.changeNormalize) bl_normalize_radio.pack(fill='both',expand=1) self.data_entries['Baseline Normalize'] = bl_normalize Label(self.getFrame(0.2,0.25,0.16,0.22),text='Interval (ms)', wraplength=0.05*self.size,font=self.small_font ).pack(fill='both',expand=1) Label(self.getFrame(0.2,0.22,0.22,0.26),text='min', wraplength=0.04*self.size,font=self.small_font ).pack(fill='both',expand=1) Label(self.getFrame(0.2,0.22,0.26,0.3),text='max', wraplength=0.04*self.size,font=self.small_font ).pack(fill='both',expand=1) interval_min = Entry(self.getFrame(0.22,0.25,0.22,0.26),font=self.small_font) interval_min.pack(fill='both',expand=1) interval_min.focus_set() interval_min.insert(0,'-600') interval_max = Entry(self.getFrame(0.22,0.25,0.26,0.3),font=self.small_font) interval_max.pack(fill='both',expand=1) interval_max.focus_set() interval_max.insert(0,'600') self.data_entries['Interval Min'] = interval_min self.data_entries['Interval Max'] = interval_max epo = self.buddy._load_epochs('TMS') fig = epo.plot(n_epochs=1) epo_selection = FigureCanvasTkAgg(fig,self.getFrame(0.1,0.9,0.3,0.9)) epo_selection.draw() epo_selection.get_tk_widget().pack(fill='both',expand=1) self.data_entries['Epoch Selection'] = epo_selection
def __init__(self, master, gconf, directory=None): self.master = master self.initialized = False self.master.bind('<Return>', self.infer) self.master.bind('<Escape>', lambda a: self.master.quit()) self.master.protocol('WM_DELETE_WINDOW', self.quit) self.dir = os.path.abspath(ifnone(directory, ifnone(gconf['prev_query_path'], os.getcwd()))) self.frame = Frame(master) self.frame.pack(fill=BOTH, expand=1) self.frame.columnconfigure(1, weight=1) row = 0 # pracmln project options Label(self.frame, text='PRACMLN Project: ').grid(row=row, column=0, sticky='ES') project_container = Frame(self.frame) project_container.grid(row=row, column=1, sticky="NEWS") # new proj file self.btn_newproj = Button(project_container, text='New Project...', command=self.new_project) self.btn_newproj.grid(row=0, column=1, sticky="WS") # open proj file self.btn_openproj = Button(project_container, text='Open Project...', command=self.ask_load_project) self.btn_openproj.grid(row=0, column=2, sticky="WS") # save proj file self.btn_updateproj = Button(project_container, text='Save Project...', command=self.noask_save_project) self.btn_updateproj.grid(row=0, column=3, sticky="WS") # save proj file as... self.btn_saveproj = Button(project_container, text='Save Project as...', command=self.ask_save_project) self.btn_saveproj.grid(row=0, column=4, sticky="WS") # grammar selection row += 1 Label(self.frame, text='Grammar: ').grid(row=row, column=0, sticky='E') grammars = ['StandardGrammar', 'PRACGrammar'] self.selected_grammar = StringVar() self.selected_grammar.trace('w', self.settings_setdirty) l = OptionMenu(*(self.frame, self.selected_grammar) + tuple(grammars)) l.grid(row=row, column=1, sticky='NWE') # logic selection row += 1 Label(self.frame, text='Logic: ').grid(row=row, column=0, sticky='E') logics = ['FirstOrderLogic', 'FuzzyLogic'] self.selected_logic = StringVar() self.selected_logic.trace('w', self.settings_setdirty) l = OptionMenu(*(self.frame, self.selected_logic) + tuple(logics)) l.grid(row=row, column=1, sticky='NWE') # mln section row += 1 Label(self.frame, text="MLN: ").grid(row=row, column=0, sticky='NE') self.mln_container = FileEditBar(self.frame, directory=self.dir, filesettings={'extension': '.mln', 'ftypes': [('MLN files', '.mln')]}, defaultname='*unknown{}', importhook=self.import_mln, deletehook=self.delete_mln, projecthook=self.save_proj, filecontenthook=self.mlnfilecontent, fileslisthook=self.mlnfiles, updatehook=self.update_mln, onchangehook=self.project_setdirty) self.mln_container.editor.bind("<FocusIn>", self._got_focus) self.mln_container.grid(row=row, column=1, sticky="NEWS") self.mln_container.columnconfigure(1, weight=2) self.frame.rowconfigure(row, weight=1) row += 1 self.use_emln = IntVar() self.use_emln.set(0) self.cb_use_emln = Checkbutton(self.frame, text="use model extension", variable=self.use_emln, command=self.onchange_use_emln) self.cb_use_emln.grid(row=row, column=1, sticky="W") # mln extension section row += 1 self.emlncontainerrow = row self.emln_label = Label(self.frame, text="EMLN: ") self.emln_label.grid(row=self.emlncontainerrow, column=0, sticky='NE') self.emln_container = FileEditBar(self.frame, directory=self.dir, filesettings={'extension': '.emln', 'ftypes': [('MLN extension files','.emln')]}, defaultname='*unknown{}', importhook=self.import_emln, deletehook=self.delete_emln, projecthook=self.save_proj, filecontenthook=self.emlnfilecontent, fileslisthook=self.emlnfiles, updatehook=self.update_emln, onchangehook=self.project_setdirty) self.emln_container.grid(row=self.emlncontainerrow, column=1, sticky="NEWS") self.emln_container.editor.bind("<FocusIn>", self._got_focus) self.emln_container.columnconfigure(1, weight=2) self.onchange_use_emln(dirty=False) self.frame.rowconfigure(row, weight=1) # db section row += 1 Label(self.frame, text="Evidence: ").grid(row=row, column=0, sticky='NE') self.db_container = FileEditBar(self.frame, directory=self.dir, filesettings={'extension': '.db', 'ftypes': [('Database files', '.db')]}, defaultname='*unknown{}', importhook=self.import_db, deletehook=self.delete_db, projecthook=self.save_proj, filecontenthook=self.dbfilecontent, fileslisthook=self.dbfiles, updatehook=self.update_db, onchangehook=self.project_setdirty) self.db_container.grid(row=row, column=1, sticky="NEWS") self.db_container.editor.bind("<FocusIn>", self._got_focus) self.db_container.columnconfigure(1, weight=2) self.frame.rowconfigure(row, weight=1) # inference method selection row += 1 self.list_methods_row = row Label(self.frame, text="Method: ").grid(row=row, column=0, sticky=E) self.selected_method = StringVar() self.selected_method.trace('w', self.select_method) methodnames = sorted(InferenceMethods.names()) self.list_methods = OptionMenu(*(self.frame, self.selected_method) + tuple(methodnames)) self.list_methods.grid(row=self.list_methods_row, column=1, sticky="NWE") # options row += 1 option_container = Frame(self.frame) option_container.grid(row=row, column=1, sticky="NEWS") # Multiprocessing self.multicore = IntVar() self.cb_multicore = Checkbutton(option_container, text="Use all CPUs", variable=self.multicore, command=self.settings_setdirty) self.cb_multicore.grid(row=0, column=2, sticky=W) # profiling self.profile = IntVar() self.cb_profile = Checkbutton(option_container, text='Use Profiler', variable=self.profile, command=self.settings_setdirty) self.cb_profile.grid(row=0, column=3, sticky=W) # verbose self.verbose = IntVar() self.cb_verbose = Checkbutton(option_container, text='verbose', variable=self.verbose, command=self.settings_setdirty) self.cb_verbose.grid(row=0, column=4, sticky=W) # options self.ignore_unknown_preds = IntVar() self.cb_ignore_unknown_preds = Checkbutton(option_container, text='ignore unkown predicates', variable=self.ignore_unknown_preds, command=self.settings_setdirty) self.cb_ignore_unknown_preds.grid(row=0, column=5, sticky="W") # queries row += 1 Label(self.frame, text="Queries: ").grid(row=row, column=0, sticky=E) self.query = StringVar() self.query.trace('w', self.settings_setdirty) Entry(self.frame, textvariable=self.query).grid(row=row, column=1, sticky="NEW") # additional parameters row += 1 Label(self.frame, text="Add. params: ").grid(row=row, column=0, sticky="NE") self.params = StringVar() self.params.trace('w', self.settings_setdirty) self.entry_params = Entry(self.frame, textvariable=self.params) self.entry_params.grid(row=row, column=1, sticky="NEW") # closed-world predicates row += 1 Label(self.frame, text="CW preds: ").grid(row=row, column=0, sticky="E") cw_container = Frame(self.frame) cw_container.grid(row=row, column=1, sticky='NEWS') cw_container.columnconfigure(0, weight=1) self.cwPreds = StringVar() self.cwPreds.trace('w', self.settings_setdirty) self.entry_cw = Entry(cw_container, textvariable=self.cwPreds) self.entry_cw.grid(row=0, column=0, sticky="NEWS") self.closed_world = IntVar() self.cb_closed_world = Checkbutton(cw_container, text="CW Assumption", variable=self.closed_world, command=self.onchange_cw) self.cb_closed_world.grid(row=0, column=1, sticky='W') # output filename row += 1 output_cont = Frame(self.frame) output_cont.grid(row=row, column=1, sticky='NEWS') output_cont.columnconfigure(0, weight=1) # - filename Label(self.frame, text="Output: ").grid(row=row, column=0, sticky="NE") self.output_filename = StringVar() self.entry_output_filename = Entry(output_cont, textvariable=self.output_filename) self.entry_output_filename.grid(row=0, column=0, sticky="NEW") # - save option self.save = IntVar() self.cb_save = Checkbutton(output_cont, text="save", variable=self.save) self.cb_save.grid(row=0, column=1, sticky=W) # start button row += 1 start_button = Button(self.frame, text=">> Start Inference <<", command=self.infer) start_button.grid(row=row, column=1, sticky="NEW") self.settings_dirty = IntVar() self.project_dirty = IntVar() self.gconf = gconf self.project = None self.project_dir = os.path.abspath(ifnone(directory, ifnone(gconf['prev_query_path'], os.getcwd()))) if gconf['prev_query_project': self.project_dir] is not None: self.load_project(os.path.join(self.project_dir, gconf['prev_query_project':self.project_dir])) else: self.new_project() self.config = self.project.queryconf self.project.addlistener(self.project_setdirty) self.mln_container.dirty = False self.emln_container.dirty = False self.db_container.dirty = False self.project_setdirty(dirty=False) self.master.geometry(gconf['window_loc_query']) self.initialized = True
class UI(Frame): def __init__(self,parent): Frame.__init__(self,parent) self.window = parent self.ALL = IntVar() self.initUIKit() self.initUI() def initUI(self): self.window.title("MANGA DOWNLOADER") def initUIKit(self): #Label self.searchLabel = Label(self.window,text="Search!!") self.mangaLabel = Label(self.window,text="Manga Name") self.chapLabel = Label(self.window,text="Chapter") #Entry self.searchEntry = Entry(self.window,width=80) #ProgressBar self.progress = Progressbar(self.window,length=80,mode='determinate') #Combobox self.cbMangaName = Combobox(self.window,width=80,state='readonly') self.cbChapList = Combobox(self.window,width=80,state='readonly') #Button self.searchBtn = Button(self.window,text="Search",command=self.SearchManga) self.getChapBtn = Button(self.window,text="Get",command=self.SearchChapter) self.downloadBtn = Button(self.window,text="Download",command=self.Download) #CheckBox self.chkDownloadAll = Checkbutton(self.window,text="Download All Chapter",variable=self.ALL,onvalue =1,offvalue=0) #Init #search self.searchLabel.grid(row=0,column=0) self.searchEntry.grid(row=0,column=1,padx=12,pady=16) self.searchBtn.grid(row=0,column=2) #CB Manga self.mangaLabel.grid(row=1,column=0) self.cbMangaName.grid(row=1,column=1) self.getChapBtn.grid(row=1,column=2) #CB Chapter self.chapLabel.grid(row=3,column=0) self.cbChapList.grid(row=3,column=1) #CheckBox self.chkDownloadAll.grid(row=2,column=1) #Download Button self.downloadBtn.grid(row=4,column=1,pady=16) def SearchManga(self): self.sQuery = self.searchEntry.get() self.searchContent = searchName(self.sQuery) self.cbMangaName['values']= list(self.searchContent.keys()) def SearchChapter(self): if self.ALL.get() == 1: self.cbChapList.config(state='disable') else: self.cbChapList.config(state='readonly') self.keyContent = self.cbMangaName.get() self.sMangaCahpter = searchChap(self.searchContent.get(self.keyContent)) self.cbChapList['values'] = list(self.sMangaCahpter.keys()) def saveFilename(self,name): key = self.chapKey chapName = self.sMangaCahpter.get(key) return re.sub(r'(?u)[^-\w.]', ' ', name) def Download(self): self.chapKey = self.cbChapList.get() self.sChapList = self.sMangaCahpter.get(self.chapKey) if self.ALL.get() == 1: for chap,link in self.sMangaCahpter.items(): singleChapManga(link,self.cbMangaName.get(),self.saveFilename(chap)) messagebox.showinfo('Information','Your download has been complete') else: singleChapManga(self.sChapList,self.cbMangaName.get(),self.saveFilename(self.chapKey)) messagebox.showinfo('Information','Your download has been complete')
class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets() def generate(self): n = int(self.menu_gen.get()) seed = self.inp_seed.get() self.output = Generator.convert(seed, n) if len(self.output) > 0: self.generated = True self.butt_draw.config( state= 'normal') self.chek_fullscrn.config(state= 'normal') self.clearOutput(self.output) def draw(self, n, step=False): p1, p2 = Draw.move(n) self.curr_canvas.create_line(p1[0], p1[1], p2[0], p2[1], fill= self.color, width= self.thick) if step: self.curr_canvas.update_idletasks() def do(self, action, step, rainbow): if len(action) > 1: p = action[1] else: p = 1.0 self.timebuff += step cmd = action[0].lower() if cmd == "draw": if rainbow: self.incColor() if self.incThickYN: self.incThick(self.reverseThick, False) elif self.incThickYN: self.incThick(self.reverseThick, True) if self.timebuff > 1.0: truncate = int(self.timebuff) self.after(truncate, self.draw(float(p), True)) self.timebuff -= truncate else: self.draw(float(p)) elif cmd == "turn": Draw.turn(float(p)) elif cmd == "skip": Draw.skip(float(p)) elif cmd == "back": Draw.back(float(p)) elif cmd == "color": if not rainbow: self.color = Color.getHexString(p) elif cmd == "thick": self.thick = int(p) else: print("Unknown command " + cmd) def drawAll(self, newWindow= True): if self.generated == True: self.butt_print.config(state= 'disabled') self.timebuff = 0.0 self.color = Color.white() self.thick = 2 l = float(self.slid_linesize.get()) a = float(self.slid_angle.get()) Draw.init(self.startingPoint, l, a) if self.fullScreen.get() == 1: if newWindow: self.curr_canvas = dc.BigCanvas(self).canvas self.canvas.delete("all") else: self.curr_canvas = self.canvas self.curr_canvas.delete("all") self.curr_canvas.config(bg= Color.getHexString(self.bgColor.get())) rainbow = self.rainbowCheck.get() == 1 if rainbow or self.incThickYN: self.incStep = 1.0/float(self.getDrawCount(self.output)) self.percent = 0.0 for c in self.output: if c == '[': Draw.push() elif c == ']': Draw.pop() else: for r in Rule.getDrawings(): if c == r[0]: if len(r) > 2: params = (r[1], r[2]) else: params = (r[1],) s = float(self.slid_timer.get()) self.do(params, s, rainbow) break self.butt_print.config(state= 'normal') def incColor(self): self.color = Color.getValueByPercent(self.percent) self.percent += self.incStep def incThick(self, reverse, incYN): maxthick = 5 minthick = 1 diff = maxthick - minthick if reverse: result = maxthick - int(diff * self.percent) else: result = minthick + int(diff * self.percent) self.thick = result if incYN: self.percent += self.incStep def getDrawCount(self, s): draw_commands = [] for r in Rule.getDrawings(): if r[1].lower() == "draw": draw_commands.append(r[0]) draw_count = 0; for c in s: for d in draw_commands: if c == d: draw_count += 1 break return draw_count def clearOutput(self, replacement=None): self.text_output.config(state= 'normal') self.text_output.delete(1.0, END) if replacement: self.text_output.insert(END, replacement) self.text_output.config(state= 'disabled') def formatRules(self, rules): ret = [] for r in rules: entry = r[0] + " | " + r[1] if len(r) > 2: entry += " " + r[2] ret.append(entry) return ret def getRuleFromFormatted(self, s): if s: rule = s.split('|') rule[0] = rule[0].strip() rule[1] = rule[1].strip() prod = rule[1].split(" ") if len(prod) == 1: return (rule[0], prod[0]) else: return (rule[0], prod[0], prod[1]) def RefreshLists(self): self.list_prod.delete(0, END) self.list_draw.delete(0, END) l = self.formatRules(Rule.getProductions()) for p in l: self.list_prod.insert(END, p) l = self.formatRules(Rule.getDrawings()) for d in l: self.list_draw.insert(END, d) def AddProductionRule(self, edit=None): rule = dp.AddProductionRuleDialog(self, edit).result if rule: if edit: Rule.removeProd(edit[0]) Rule.AddProduction(rule) self.RefreshLists() def AddDrawingRule(self, edit=None): rule = dd.AddDrawingRuleDialog(self, edit).result if rule: if edit: Rule.removeDraw(edit[0]) Rule.AddDrawing(rule) self.RefreshLists() def EditProductionRule(self): s = self.list_prod.curselection() if s: idx = s[0] rule = (idx,) + self.getRuleFromFormatted(self.list_prod.get(idx)) if rule: self.AddProductionRule(rule) def EditDrawingRule(self): s = self.list_draw.curselection() if s: idx = s[0] rule = (idx,) + self.getRuleFromFormatted(self.list_draw.get(idx)) if rule: self.AddDrawingRule(rule) def DeleteProductionRule(self): s = self.list_prod.curselection() if s: Rule.removeProd(s[0]) self.RefreshLists() def DeleteDrawingRule(self): s = self.list_draw.curselection() if s: Rule.removeDraw(s[0]) self.RefreshLists() def packOutput(self): ret = "" ret += self.packAxiom() ret += self.packProdRules() ret += self.packDrawRules() return ret def packAxiom(self): return "@" + str(self.inp_seed.get()).strip() def packRules(self, rules): ret = "@" for r in rules: ret += "$" + str(r[0]) + "|" + str(r[1]) if len(r) > 2: ret += ":" + str(r[2]) return ret def packProdRules(self): return self.packRules(Rule.getProductions()) def packDrawRules(self): return self.packRules(Rule.getDrawings()) def parseProdRules(self, raw): rules = raw.split('$') for rule in rules: if rule is not "": r = rule.split('|') Rule.AddProduction((r[0], r[1])) def parseDrawRules(self, raw): rules = raw.split('$') for rule in rules: if rule is not "": r = rule.split('|') p = r[1].split(':') if len(p) == 1: tup = (r[0], p[0]) else: tup = (r[0], p[0], p[1]) Rule.AddDrawing(tup) def parseSaveFile(self, s): Rule.wipe() settings = s.split('@') self.inp_seed.set(str(settings[1])) self.parseProdRules(settings[2]) self.parseDrawRules(settings[3]) self.RefreshLists() def save(self): try: filename = filedialog.asksaveasfilename(**self.file_options['txt']) if filename: f = open(filename, 'w') f.write(self.packOutput()) f.close() except Exception as e: print("File IO error in save\n", e) def load(self): try: filename = filedialog.askopenfilename(**self.file_options['txt']) if filename: f = open(filename, 'r') self.parseSaveFile(f.read()) f.close() self.slid_linesize.set(1.0) self.slid_timer.set(0.0) self.menu_gen.set(1) self.clearOutput() except Exception as e: print("File IO error in load\n" + e) def help(self): help.HelpDialog(self) def saveImage(self): filename = filedialog.asksaveasfilename(**self.file_options['ps']) self.curr_canvas.postscript(file=filename, colormode='color') def click(self, event): self.startingPoint = (event.x, event.y) def clickAndRedraw(self, event): self.click(event) self.drawAll(False) def fileOptions(self): self.file_options = {} txt_options = {} ps_options = {} txt_options['defaultextension'] = '.txt' txt_options['filetypes'] = [('Plaintext', '.txt')] txt_options['initialdir'] = 'Patterns' ps_options['defaultextension'] = '.ps' ps_options['filetypes'] = [('Postscript Image', '.ps')] ps_options['initialdir'] = 'Images' self.file_options['txt'] = txt_options self.file_options['ps'] = ps_options def makeMenuBar(self): self.menubar = Menu(self); self.menubar.add_command(label="Save", command= self.save) self.menubar.add_command(label="Load", command= self.load) self.menubar.add_command(label="Help", command= self.help) root.config(menu= self.menubar) def makeInputFrame(self): self.inp_seed = String() self.bgColor = String() self.gen_value = Int() self.rainbowCheck = Int() self.fram_input = Frame(self, bd= 2, relief= self.style, width= input_frame_width, height= input_frame_height) self.fram_seed = Frame(self.fram_input, bd= 1, relief= self.style) self.fram_prod = Frame(self.fram_input, bd= 1, relief= self.style) self.fram_draw = Frame(self.fram_input, bd= 1, relief= self.style) self.fram_drawParams = Frame(self.fram_input, bd= 1, relief= self.style) self.fram_gen = Frame(self.fram_input, bd= 1, relief= self.style) self.fram_output = Frame(self.fram_input, bd= 1, relief= self.style) self.menu_gen = DropDown(self.fram_gen, textvariable= self.gen_value, state= 'readonly') self.entr_seed = Input(self.fram_seed, textvariable= self.inp_seed) self.text_output = Output(self.fram_output, width= 35, height= 10) self.scrl_output = Scrollbar(self.fram_output) self.list_prod = List(self.fram_prod, selectmode= BROWSE, font= "Courier 8", height= 5) self.list_draw = List(self.fram_draw, selectmode= BROWSE, font= "Courier 8", height= 5) self.slid_linesize = Slider(self.fram_drawParams, from_= 0.1, to= 10.0, orient= HORIZONTAL, resolution= 0.1, length= 180) self.slid_timer = Slider(self.fram_drawParams, from_= 0, to= 2, orient= HORIZONTAL, resolution= 0.02, length= 180) self.slid_angle = Slider(self.fram_drawParams, from_= 0, to= 359, orient= HORIZONTAL, length= 180) self.entr_bgcolor = Input (self.fram_drawParams, textvariable= self.bgColor) self.butt_prodAdd = Button(self.fram_prod, text= "Add", width=8, command= self.AddProductionRule) self.butt_prodEdit = Button(self.fram_prod, text= "Edit", width=8, command= self.EditProductionRule) self.butt_prodDelete = Button(self.fram_prod, text= "Delete", width=8, command= self.DeleteProductionRule) self.butt_drawAdd = Button(self.fram_draw, text= "Add", width=8, command= self.AddDrawingRule) self.butt_drawEdit = Button(self.fram_draw, text= "Edit", width=8, command= self.EditDrawingRule) self.butt_drawDelete = Button(self.fram_draw, text= "Delete", width=8, command= self.DeleteDrawingRule) self.chek_incColor = CheckBox(self.fram_draw, text= "Rainbow", variable= self.rainbowCheck) Label(self.fram_seed, text= "Axiom:", width=8).grid (row=0, column=0) Label(self.fram_prod, text= "Production\nRules:", width=8).grid (row=0, column=0) Label(self.fram_draw, text= "Drawing\nRules:", width=8).grid (row=0, column=0) Label(self.fram_drawParams, text= "Line Size:").grid (row=0, column=0) Label(self.fram_drawParams, text= "Delay (ms):").grid (row=1, column=0) Label(self.fram_drawParams, text= "Starting Angle:").grid (row=2, column=0) Label(self.fram_drawParams, text= "Background Color:").grid (row=3, column=0) Label(self.fram_output, text= "Output:").grid (row=0, column=0) Label(self.fram_gen, text= "Generations:").grid (row=0, column=0) self.gen_value.set(1) self.menu_gen['values'] = tuple(range(1, 13)) self.slid_linesize.set(1.0) self.bgColor.set( Color.default() ) self.text_output.config(state='disabled', yscrollcommand= self.scrl_output.set) self.scrl_output.config(command=self.text_output.yview) self.fram_input.grid (row=0, column=0) self.fram_seed.grid (row=1, column=0, sticky= 'ew') self.fram_prod.grid (row=2, column=0, sticky= 'ew') self.fram_draw.grid (row=3, column=0, sticky= 'ew') self.fram_drawParams.grid (row=4, column=0, sticky= 'ew') self.fram_gen.grid (row=5, column=0, sticky= 'ew') self.fram_output.grid (row=6, column=0, sticky= 'ew') self.entr_seed.grid (row=0, column=1, sticky= 'ew') self.list_prod.grid (row=0, column=1, sticky= 'ew') self.butt_prodAdd.grid (row=1, column=0, sticky= 'ew') self.butt_prodEdit.grid (row=1, column=1, sticky= 'ew') self.butt_prodDelete.grid (row=1, column=2, sticky= 'ew') self.list_draw.grid (row=0, column=1) self.butt_drawAdd.grid (row=1, column=0, sticky= 'ew') self.butt_drawEdit.grid (row=1, column=1, sticky= 'ew') self.butt_drawDelete.grid (row=1, column=2, sticky= 'ew') self.chek_incColor.grid (row=0, column=2) self.slid_linesize.grid (row=0, column=1, sticky= 'ew') self.slid_timer.grid (row=1, column=1, sticky= 'ew') self.slid_angle.grid (row=2, column=1, sticky= 'ew') self.entr_bgcolor.grid (row=3, column=1, sticky= 'ew') self.menu_gen.grid (row=0, column=1, sticky= 'ew') self.text_output.grid (row=1, column=0) self.scrl_output.grid (row=1, column=1, sticky= 'ns') def makeCanvasFrame(self): self.fram_canvas = Frame(self, bd=10, relief=self.style) self.canvas = Canvas(self.fram_canvas, width= canvas_width, height= canvas_height) self.fram_canvas.grid(row=0, column=1, sticky='nesw') self.canvas.grid(sticky='nesw') self.canvas.bind("<Button-1>", self.click) self.curr_canvas = self.canvas def makeIgnitionFrame(self): self.fullScreen = Int() self.fram_ignition = Frame(self, bd=4, relief=self.style, width= ignition_frame_width, height= ignition_frame_height) self.butt_generate = Button(self.fram_ignition, text= " -- GENERATE -- ", width=111, command= self.generate) self.butt_draw = Button(self.fram_ignition, text= " -- DRAW -- ", width=100, command= self.drawAll, state= 'disabled') self.butt_print = Button(self.fram_ignition, text= "Save Image", command= self.saveImage, state= 'disabled') self.chek_fullscrn = CheckBox(self.fram_ignition, text= "Fullscreen", variable= self.fullScreen, state= 'disabled') self.fram_ignition.grid(row=1, column=0, columnspan=2) self.butt_generate.grid(row=0, column=0, columnspan=2) self.butt_draw.grid( row=1, column=0) self.butt_print.grid( row=0, column=2, rowspan= 2, sticky='ns') self.chek_fullscrn.grid(row=1, column=1) def createWidgets(self): self.incThickYN = False self.reverseThick = False self.style = RIDGE self.startingPoint = (20, 20) self.generated = False self.fileOptions() self.makeMenuBar() self.makeInputFrame() self.makeCanvasFrame() self.makeIgnitionFrame()
class ViewMac: main_view = "" current_mac = "" accepted_characters = [ 'a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ':' ] def __init__(self, view, spoofing_status): self.main_view = view self.spoofing_status = spoofing_status self.build_window() self.popup_gen = PopUpWindow() self.set_spoofing_checkbutton() self.root.mainloop() def build_window(self): """ Generates the window. :author: Pablo Sanz Alguacil """ self.root = Toplevel() self.root.protocol("WM_DELETE_WINDOW", self.destroy_window) self.root.geometry('440x490') self.root.resizable(width=False, height=False) self.root.title('WiCC - Mac Changer Tools') # LABELFRAME - INFO self.labelframe_info = LabelFrame(self.root, text="") self.labelframe_info.pack(fill="both", expand="no", pady=15) # LABEL - INFO self.label_info = Label( self.labelframe_info, pady=15, text="In this window you can change your MAC as you want by" "\nusing one this options. A great power comes with a" "\ngreat responsibility") self.label_info.pack(side=TOP) # LABELFRAME - CUSTOM MAC self.labelframe_custom_mac = LabelFrame(self.root, text="Write custom MAC") self.labelframe_custom_mac.pack(fill="both", expand="no", pady=10) # LABEL - CUSTOM MAC self.label_custom_mac = Label(self.labelframe_custom_mac, text="Custom MAC: ") self.label_custom_mac.grid(column=1, row=0, padx=5) # ENTRY - CUSTOM MAC self.entry_custom_mac = ttk.Entry(self.labelframe_custom_mac) self.entry_custom_mac.grid(column=2, row=0, padx=8) self.entry_custom_mac.bind('<Button-3>', rClicker, add='') # BUTTON - CUSTOM MAC self.button_custom_mac = ttk.Button(self.labelframe_custom_mac, text="Set custom MAC", command=self.customize_mac) self.button_custom_mac.grid(column=4, row=0) # LABELFRAME - RANDOM MAC self.labelframe_random_mac = LabelFrame(self.root, text="Randomize MAC") self.labelframe_random_mac.pack(fill="both", expand="no", pady=10) # LABEL - RANDOM MAC self.label_random_mac = Label( self.labelframe_random_mac, text="Changes the current MAC to a completly \nrandom MAC", justify=LEFT) self.label_random_mac.grid(column=1, row=0, rowspan=2, padx=5) # BUTTON - RANDOM MAC self.button_random_mac = ttk.Button(self.labelframe_random_mac, text="Randomize MAC", command=self.randomize_mac) self.button_random_mac.grid(column=3, row=0, padx=5) # LABELFRAME - RESTORE ORIGINAL self.labelframe_restore_original = LabelFrame( self.root, text="Restore original MAC") self.labelframe_restore_original.pack(fill="both", expand="no", pady=10) # LABEL - RESTORE ORIGINAL self.label_restore_original = Label( self.labelframe_restore_original, text="Restores the original selected interface's\nMAC address", justify=LEFT) self.label_restore_original.grid(column=1, row=0, padx=5) # BUTTON - RESTORE ORIGINAL self.button_restore_original = ttk.Button( self.labelframe_restore_original, text="Restore MAC", command=self.restore_mac) self.button_restore_original.grid(column=3, row=0, padx=5) # LABELFRAME - MAC SPOOFING self.labelframe_mac_spoofing = LabelFrame(self.root, text="MAC spoofing") self.labelframe_mac_spoofing.pack(fill="both", expand="no", pady=10) # LABEL - MAC SPOOFING) self.label_mac_spoofing = Label( self.labelframe_mac_spoofing, text="Spoof client's MAC address during attack") self.label_mac_spoofing.grid(column=1, row=0, padx=5) # CHECKBUTTON - MAC SPOOFING self.checkbutton_mac_spoofing = Checkbutton( self.labelframe_mac_spoofing, text="Active", command=self.mac_spoofing) self.checkbutton_mac_spoofing.grid(column=3, row=0, padx=5) # BUTTON - DONE self.button_done = ttk.Button(self.root, text="Done", command=self.destroy_window) self.button_done.pack(padx=15, pady=15) def customize_mac(self): """ Sends an order to the main view to set the MAC address to the sended one. Filters the address before send it (only hexadecimal values). :author: Pablo Sanz Alguacil """ address = self.entry_custom_mac.get().lower() colon_count = 0 address_length = len(self.entry_custom_mac.get()) address_splited = list(address) boolean_fg = True for character in address_splited: if character in self.accepted_characters and address_length == 17: if character == ":": colon_count = colon_count + 1 else: boolean_fg = False if boolean_fg and colon_count == 5: self.notify_view(0, self.entry_custom_mac.get()) else: self.popup_gen.warning("Warning", "Address not valid") def randomize_mac(self): """ Sends an order to the main view to randomize the MAC address. :author: Pablo Sanz Alguacil """ self.notify_view(1, "") def restore_mac(self): """ Sends an order to the main view to restore the original MAC address. :author: Pablo Sanz Alguacil """ self.notify_view(2, "") def set_spoofing_checkbutton(self): """ Selects or deselcts the MAC spoofing checkbutton. :author: Pablo Sanz Alguacil """ if self.spoofing_status: self.checkbutton_mac_spoofing.select() else: self.checkbutton_mac_spoofing.deselect() def mac_spoofing(self): """ Sends an order to the main view to set the MAC spoofing status. Saves the status in a local variable. :author: Pablo Sanz Alguacil """ if self.spoofing_status: self.spoofing_status = False self.notify_view(3, False) else: self.spoofing_status = True self.notify_view(3, True) def notify_view(self, operation, value): """ Operation values (int) [0] Custom mac [1] Random mac [2] Restore mac [3] Mac spoofing Sends and operation and value to the main view. :param self: :param operation: integer :param value: object :author: Pablo Sanz Alguacil """ self.main_view.get_notify_childs(operation, value) def destroy_window(self): """ Enables all buttons in the main window and destroys this window. :author: Pablo Sanz Alguacil """ self.main_view.disable_window(False) self.root.destroy()
def create_option_buttons(self): "Fill frame with Checkbuttons bound to SearchEngine booleanvars." f = self.make_frame("Options") btn = Checkbutton(f, anchor="w", variable=self.engine.revar, text="Regular expression") btn.pack(side="left", fill="both") if self.engine.isre(): btn.select() btn = Checkbutton(f, anchor="w", variable=self.engine.casevar, text="Match case") btn.pack(side="left", fill="both") if self.engine.iscase(): btn.select() btn = Checkbutton(f, anchor="w", variable=self.engine.wordvar, text="Whole word") btn.pack(side="left", fill="both") if self.engine.isword(): btn.select() if self.needwrapbutton: btn = Checkbutton(f, anchor="w", variable=self.engine.wrapvar, text="Wrap around") btn.pack(side="left", fill="both") if self.engine.iswrap(): btn.select()
def pricesWindow(previousWindow): # closes menu and opens prices window pricesSelection = Tk() previousWindow.withdraw() pricesSelection.configure(bg='light cyan') pricesSelection.title('Prices of Items') pricesSelection.geometry('400x310') label = Label(pricesSelection, text='Select item(s):', bd=0, relief='solid', width=15, height=2, bg='light cyan') label.pack() # values of checkbox variables toiletPaperS = BooleanVar(pricesSelection) toiletPaperL = BooleanVar(pricesSelection) handSanitizerS = BooleanVar(pricesSelection) handSanitizerL = BooleanVar(pricesSelection) waterGal = BooleanVar(pricesSelection) waterBot = BooleanVar(pricesSelection) wipesS = BooleanVar(pricesSelection) wipesL = BooleanVar(pricesSelection) # creation of checkboxes Checkbutton(pricesSelection, text='Toilet Paper (Small Pack, 12)', variable=toiletPaperS, onvalue=1, offvalue=0, bg='light cyan').pack() Checkbutton(pricesSelection, text='Toilet Paper (Bulk, 24)', variable=toiletPaperL, onvalue=1, offvalue=0, bg='light cyan').pack() Checkbutton(pricesSelection, text='Hand Sanitizer (travel size, 2 fl. oz.)', variable=handSanitizerS, onvalue=1, offvalue=0, bg='light cyan').pack() Checkbutton(pricesSelection, text='Hand Sanitizer (medium size, 12 fl. oz.)', variable=handSanitizerL, onvalue=1, offvalue=0, bg='light cyan').pack() Checkbutton(pricesSelection, text='Poland Spring Water Jug (1 Gallon)', variable=waterGal, onvalue=1, offvalue=0, bg='light cyan').pack() Checkbutton(pricesSelection, text='Poland Spring Pack (24 Bottles)', variable=waterBot, onvalue=1, offvalue=0, bg='light cyan').pack() Checkbutton(pricesSelection, text='Heavy Duty Wipes (30 ct)', variable=wipesS, onvalue=1, offvalue=0, bg='light cyan').pack() Checkbutton(pricesSelection, text='Heavy Duty Wipes (60 ct)', variable=wipesL, onvalue=1, offvalue=0, bg='light cyan').pack() # button that creates graph graphPrices = Button(pricesSelection, text='Graph Selected', bg='white', command=lambda: pricesData([ toiletPaperS, toiletPaperL, handSanitizerS, handSanitizerL, waterGal, waterBot, wipesS, wipesL ])) graphPrices.place(x=50, y=250) # button that graphs all graphAll = Button(pricesSelection, text='Graph All', bg='white', command=lambda: pricesData()) graphAll.place(x=168, y=250) # return to menu button menuButton = Button(pricesSelection, text='Return to Menu', bg='white', command=lambda: menuWindow(pricesSelection)) menuButton.place(x=250, y=250)
def __init__(self, master=None): """ Main GUI.""" Frame.__init__(self, master) Frame.grid(self, padx=(40, 40), pady=(10, 10)) self.path1 = StringVar() path1_lbl = ttk.Label(self, text='Path:') path1_lbl.grid(column=1, columnspan=4, row=1, sticky=W) path1_entry = ttk.Entry(self, width=30, textvariable=self.path1) path1_entry.grid(column=1, columnspan=4, row=2, sticky=(W, E)) path1_btn = ttk.Button(self, text="Browse", command=self.open1) path1_btn.grid(column=1, row=3, sticky=W, padx=(0, 0)) self.graph1_btn = ttk.Button(self, text="Graph", state=DISABLED, command=lambda: self.graph1(self.C, 1)) self.graph1_btn.grid(column=2, row=3, sticky=W) self.info1_lbl = ttk.Label(self, text='Scan Info/Comments:') self.info1_lbl.grid(column=1, columnspan=4, row=5, sticky=W, pady=(10, 0)) self.info1_Entry = Text(self, width=30, height=12) self.info1_Entry.grid(column=1, columnspan=4, row=6, sticky=(N, W, E)) in_C = StringVar() self.input_entry = ttk.Entry(self, width=10, textvariable=in_C) self.input_entry.grid(column=4, row=3, sticky=(W, E)) self.int_btn = ttk.Button(self, text="Input Array", command=lambda: self.Input_C()) self.int_btn.grid(column=4, row=5, sticky=W) self.int_lbl = ttk.Label(self, text="Inverse Distance " "Weighting Interpolation", font='bold') self.int_lbl.grid(column=1, columnspan=4, row=7, sticky=W, pady=(10, 2)) self.int_btn = ttk.Button(self, text="Interpolate", state=DISABLED, command=lambda: self.interpolation(self.C)) self.int_btn.grid(column=1, row=8, sticky=W) self.NP1 = IntVar() self.NP1.set(5) n_lbl = ttk.Label(self, text='No. pts') n_lbl.grid(column=1, row=9, sticky=(N, W)) self.n_box = Spinbox(self, format='%.0f', from_=0, to=self.NP1.get(), width=5, increment=1) #1E10 self.n_box.grid(column=1, row=10, sticky=(N, W)) self.n_box.insert(1, 5) p_lbl = ttk.Label(self, text='Power') p_lbl.grid(column=2, row=9, sticky=(N, W)) self.p_box = Spinbox(self, format='%.0f', from_=0, to=1E10, width=5, increment=1) self.p_box.grid(column=2, row=10, sticky=(N, W)) self.p_box.insert(1, 2) self.transpose_chk = IntVar() self.trans_btn = Checkbutton(self, text="Tranpose", variable=self.transpose_chk, state=DISABLED, command=lambda: self.check_tr(self.C)) self.trans_btn.grid(column=3, row=10, sticky=(N, W)) self.Refl_x = IntVar() self.Refl_x.set(1) self.Refl_x_btn = Checkbutton(self, text="Reflect_x", variable=self.Refl_x, state=DISABLED, command=lambda: self.check_tr(self.C)) self.Refl_x_btn.grid(column=3, row=9, sticky=(N, W)) self.info1_Entry.insert(END, "Reflect x = %s" % (self.Refl_x.get())) self.N_out_btn = ttk.Button(self, text="Save-Grid", state=DISABLED, command=lambda: self.N_out(self.N)) self.N_out_btn.grid(column=1, row=12, sticky=W) self.M_out_btn = ttk.Button(self, text="Save-xyz", state=DISABLED, command=lambda: self.N_out(self.M)) self.M_out_btn.grid(column=2, row=12, sticky=W) self.plot_btn = ttk.Button(self, text="Plot", state=DISABLED, command=lambda: self.plot(self.C, self.N)) self.plot_btn.grid(column=3, row=12, sticky=(N, W)) # Default values for the interpolated grid self.x01_ = StringVar() self.y01_ = StringVar() self.x01_.set(0.600001) #default self.y01_.set(0.600001) #default self.dx1_ = DoubleVar() # from file self.dy1_ = DoubleVar() # from file self.y02_ = StringVar() self.x02_ = StringVar() self.x02_.set(0.60) #default self.y02_.set(0.60) #default self.dx2_ = StringVar() self.dy2_ = StringVar() self.dx2_.set(0.5) #default self.dy2_.set(0.5) #default self.np_x2_ = StringVar() self.np_y2_ = StringVar() self.np_x2_.set(13) #default self.np_y2_.set(13) #default self.grid2_lbl = ttk.Label(self, text="Interpolated Grid") self.grid2_lbl.grid(column=1, columnspan=4, row=22, sticky=(W, E), pady=(5, 2)) x01_entry = ttk.Entry(self, width=6, textvariable=self.x01_) x01_entry.grid(column=2, row=17, sticky=W) x01_lbl = ttk.Label(self, text='x0') x01_lbl.grid(column=1, row=17, sticky=(N, W), padx=(40, 0)) y01_entry = ttk.Entry(self, width=6, textvariable=self.y01_) y01_entry.grid(column=4, row=17, sticky=W) y01_lbl = ttk.Label(self, text='y0') y01_lbl.grid(column=3, row=17, sticky=(N, W), padx=(40, 0)) dx1_entry = ttk.Entry(self, width=6, textvariable=self.dx1_) dx1_entry.grid(column=2, row=18, sticky=W) dx1_lbl = ttk.Label(self, text='dx1') dx1_lbl.grid(column=1, row=18, sticky=(N, W), padx=(40, 0)) dy1_entry = ttk.Entry(self, width=6, textvariable=self.dy1_) dy1_entry.grid(column=4, row=18, sticky=W) dy1_lbl = ttk.Label(self, text='dy1') dy1_lbl.grid(column=3, row=18, sticky=(N, W), padx=(40, 0)) x02_entry = ttk.Entry(self, width=6, textvariable=self.x02_) x02_entry.grid(column=2, row=23, sticky=W) x02_lbl = ttk.Label(self, text='x0 (Int)') x02_lbl.grid(column=1, row=23, sticky=(N, W), padx=(40, 0)) y02_entry = ttk.Entry(self, width=6, textvariable=self.y02_) y02_entry.grid(column=4, row=23, sticky=W) y02_lbl = ttk.Label(self, text='y0 (Int)') y02_lbl.grid(column=3, row=23, sticky=(N, W), padx=(40, 0)) dx2_entry = ttk.Entry(self, width=6, textvariable=self.dx2_) dx2_entry.grid(column=2, row=24, sticky=W) dx2_lbl = ttk.Label(self, text='dx2') dx2_lbl.grid(column=1, row=24, sticky=(N, W), padx=(40, 0)) dy2_entry = ttk.Entry(self, width=6, textvariable=self.dy2_) dy2_entry.grid(column=4, row=24, sticky=W) dy2_lbl = ttk.Label(self, text='dy2') dy2_lbl.grid(column=3, row=24, sticky=(N, W), padx=(40, 0)) np_x2_entry = ttk.Entry(self, width=6, textvariable=self.np_x2_) np_x2_entry.grid(column=2, row=25, sticky=W) np_x2_lbl = ttk.Label(self, text='np_x2') np_x2_lbl.grid(column=1, row=25, sticky=(N, W), padx=(40, 0)) np_y2_entry = ttk.Entry(self, width=6, textvariable=self.np_y2_) np_y2_entry.grid(column=4, row=25, sticky=W) np_y2_lbl = ttk.Label(self, text='np_y2') np_y2_lbl.grid(column=3, row=25, sticky=(N, W), padx=(40, 0)) self.tipwf = DoubleVar() self.tipwf.set(4220) self.tip = IntVar() self.tip_btn = Checkbutton(self, text="Tip correction (mV)", variable=self.tip, state=DISABLED, command=lambda: self.workfunction(self.C)) self.tip_btn.grid(column=3, columnspan=2, row=26, sticky=(N, W), pady=(15, 0)) self.tip_entry = ttk.Entry(self, width=6, textvariable=self.tipwf) self.tip_entry.grid(column=2, row=26, sticky=E, pady=(15, 0)) minmax_lbl = ttk.Label(self, text='Min and Max x/y') minmax_lbl.grid(column=2, columnspan=3, row=19, sticky=(N, W)) self.xi = IntVar() self.xi.set(0) self.xf = IntVar() self.xf.set(0) xdata_lbl = ttk.Label(self, text='x-data_subset') xdata_lbl.grid(column=1, row=20, sticky=(N, W)) self.xidata_box = Spinbox(self, format='%.0f', from_=0, to=self.xf.get(), width=5, increment=1) self.xidata_box.grid(column=2, row=20, sticky=(N, W), padx=(15, 0)) self.xidata_box.insert(1, 0) self.xfdata_box = Spinbox(self, format='%.0f', from_=0, to=self.xf.get(), width=5, increment=1) self.xfdata_box.grid(column=3, row=20, sticky=(N, W)) self.xfdata_box.insert(1, 0) self.yi = IntVar() self.yi.set(0) self.yf = IntVar() self.yf.set(0) ydata_lbl = ttk.Label(self, text='y-data_subset') ydata_lbl.grid(column=1, row=21, sticky=(N, W)) self.yidata_box = Spinbox(self, format='%.0f', from_=0, to=self.yf.get(), width=5, increment=1) self.yidata_box.grid(column=2, row=21, sticky=(N, W), padx=(15, 0)) self.yidata_box.insert(1, 0) self.yfdata_box = Spinbox(self, format='%.0f', from_=0, to=self.yf.get(), width=5, increment=1) self.yfdata_box.grid(column=3, row=21, sticky=(N, W)) self.yfdata_box.insert(1, 0)
class Application(Frame): def __init__(self, master=None): """ Main GUI.""" Frame.__init__(self, master) Frame.grid(self, padx=(40, 40), pady=(10, 10)) self.path1 = StringVar() path1_lbl = ttk.Label(self, text='Path:') path1_lbl.grid(column=1, columnspan=4, row=1, sticky=W) path1_entry = ttk.Entry(self, width=30, textvariable=self.path1) path1_entry.grid(column=1, columnspan=4, row=2, sticky=(W, E)) path1_btn = ttk.Button(self, text="Browse", command=self.open1) path1_btn.grid(column=1, row=3, sticky=W, padx=(0, 0)) self.graph1_btn = ttk.Button(self, text="Graph", state=DISABLED, command=lambda: self.graph1(self.C, 1)) self.graph1_btn.grid(column=2, row=3, sticky=W) self.info1_lbl = ttk.Label(self, text='Scan Info/Comments:') self.info1_lbl.grid(column=1, columnspan=4, row=5, sticky=W, pady=(10, 0)) self.info1_Entry = Text(self, width=30, height=12) self.info1_Entry.grid(column=1, columnspan=4, row=6, sticky=(N, W, E)) in_C = StringVar() self.input_entry = ttk.Entry(self, width=10, textvariable=in_C) self.input_entry.grid(column=4, row=3, sticky=(W, E)) self.int_btn = ttk.Button(self, text="Input Array", command=lambda: self.Input_C()) self.int_btn.grid(column=4, row=5, sticky=W) self.int_lbl = ttk.Label(self, text="Inverse Distance " "Weighting Interpolation", font='bold') self.int_lbl.grid(column=1, columnspan=4, row=7, sticky=W, pady=(10, 2)) self.int_btn = ttk.Button(self, text="Interpolate", state=DISABLED, command=lambda: self.interpolation(self.C)) self.int_btn.grid(column=1, row=8, sticky=W) self.NP1 = IntVar() self.NP1.set(5) n_lbl = ttk.Label(self, text='No. pts') n_lbl.grid(column=1, row=9, sticky=(N, W)) self.n_box = Spinbox(self, format='%.0f', from_=0, to=self.NP1.get(), width=5, increment=1) #1E10 self.n_box.grid(column=1, row=10, sticky=(N, W)) self.n_box.insert(1, 5) p_lbl = ttk.Label(self, text='Power') p_lbl.grid(column=2, row=9, sticky=(N, W)) self.p_box = Spinbox(self, format='%.0f', from_=0, to=1E10, width=5, increment=1) self.p_box.grid(column=2, row=10, sticky=(N, W)) self.p_box.insert(1, 2) self.transpose_chk = IntVar() self.trans_btn = Checkbutton(self, text="Tranpose", variable=self.transpose_chk, state=DISABLED, command=lambda: self.check_tr(self.C)) self.trans_btn.grid(column=3, row=10, sticky=(N, W)) self.Refl_x = IntVar() self.Refl_x.set(1) self.Refl_x_btn = Checkbutton(self, text="Reflect_x", variable=self.Refl_x, state=DISABLED, command=lambda: self.check_tr(self.C)) self.Refl_x_btn.grid(column=3, row=9, sticky=(N, W)) self.info1_Entry.insert(END, "Reflect x = %s" % (self.Refl_x.get())) self.N_out_btn = ttk.Button(self, text="Save-Grid", state=DISABLED, command=lambda: self.N_out(self.N)) self.N_out_btn.grid(column=1, row=12, sticky=W) self.M_out_btn = ttk.Button(self, text="Save-xyz", state=DISABLED, command=lambda: self.N_out(self.M)) self.M_out_btn.grid(column=2, row=12, sticky=W) self.plot_btn = ttk.Button(self, text="Plot", state=DISABLED, command=lambda: self.plot(self.C, self.N)) self.plot_btn.grid(column=3, row=12, sticky=(N, W)) # Default values for the interpolated grid self.x01_ = StringVar() self.y01_ = StringVar() self.x01_.set(0.600001) #default self.y01_.set(0.600001) #default self.dx1_ = DoubleVar() # from file self.dy1_ = DoubleVar() # from file self.y02_ = StringVar() self.x02_ = StringVar() self.x02_.set(0.60) #default self.y02_.set(0.60) #default self.dx2_ = StringVar() self.dy2_ = StringVar() self.dx2_.set(0.5) #default self.dy2_.set(0.5) #default self.np_x2_ = StringVar() self.np_y2_ = StringVar() self.np_x2_.set(13) #default self.np_y2_.set(13) #default self.grid2_lbl = ttk.Label(self, text="Interpolated Grid") self.grid2_lbl.grid(column=1, columnspan=4, row=22, sticky=(W, E), pady=(5, 2)) x01_entry = ttk.Entry(self, width=6, textvariable=self.x01_) x01_entry.grid(column=2, row=17, sticky=W) x01_lbl = ttk.Label(self, text='x0') x01_lbl.grid(column=1, row=17, sticky=(N, W), padx=(40, 0)) y01_entry = ttk.Entry(self, width=6, textvariable=self.y01_) y01_entry.grid(column=4, row=17, sticky=W) y01_lbl = ttk.Label(self, text='y0') y01_lbl.grid(column=3, row=17, sticky=(N, W), padx=(40, 0)) dx1_entry = ttk.Entry(self, width=6, textvariable=self.dx1_) dx1_entry.grid(column=2, row=18, sticky=W) dx1_lbl = ttk.Label(self, text='dx1') dx1_lbl.grid(column=1, row=18, sticky=(N, W), padx=(40, 0)) dy1_entry = ttk.Entry(self, width=6, textvariable=self.dy1_) dy1_entry.grid(column=4, row=18, sticky=W) dy1_lbl = ttk.Label(self, text='dy1') dy1_lbl.grid(column=3, row=18, sticky=(N, W), padx=(40, 0)) x02_entry = ttk.Entry(self, width=6, textvariable=self.x02_) x02_entry.grid(column=2, row=23, sticky=W) x02_lbl = ttk.Label(self, text='x0 (Int)') x02_lbl.grid(column=1, row=23, sticky=(N, W), padx=(40, 0)) y02_entry = ttk.Entry(self, width=6, textvariable=self.y02_) y02_entry.grid(column=4, row=23, sticky=W) y02_lbl = ttk.Label(self, text='y0 (Int)') y02_lbl.grid(column=3, row=23, sticky=(N, W), padx=(40, 0)) dx2_entry = ttk.Entry(self, width=6, textvariable=self.dx2_) dx2_entry.grid(column=2, row=24, sticky=W) dx2_lbl = ttk.Label(self, text='dx2') dx2_lbl.grid(column=1, row=24, sticky=(N, W), padx=(40, 0)) dy2_entry = ttk.Entry(self, width=6, textvariable=self.dy2_) dy2_entry.grid(column=4, row=24, sticky=W) dy2_lbl = ttk.Label(self, text='dy2') dy2_lbl.grid(column=3, row=24, sticky=(N, W), padx=(40, 0)) np_x2_entry = ttk.Entry(self, width=6, textvariable=self.np_x2_) np_x2_entry.grid(column=2, row=25, sticky=W) np_x2_lbl = ttk.Label(self, text='np_x2') np_x2_lbl.grid(column=1, row=25, sticky=(N, W), padx=(40, 0)) np_y2_entry = ttk.Entry(self, width=6, textvariable=self.np_y2_) np_y2_entry.grid(column=4, row=25, sticky=W) np_y2_lbl = ttk.Label(self, text='np_y2') np_y2_lbl.grid(column=3, row=25, sticky=(N, W), padx=(40, 0)) self.tipwf = DoubleVar() self.tipwf.set(4220) self.tip = IntVar() self.tip_btn = Checkbutton(self, text="Tip correction (mV)", variable=self.tip, state=DISABLED, command=lambda: self.workfunction(self.C)) self.tip_btn.grid(column=3, columnspan=2, row=26, sticky=(N, W), pady=(15, 0)) self.tip_entry = ttk.Entry(self, width=6, textvariable=self.tipwf) self.tip_entry.grid(column=2, row=26, sticky=E, pady=(15, 0)) minmax_lbl = ttk.Label(self, text='Min and Max x/y') minmax_lbl.grid(column=2, columnspan=3, row=19, sticky=(N, W)) self.xi = IntVar() self.xi.set(0) self.xf = IntVar() self.xf.set(0) xdata_lbl = ttk.Label(self, text='x-data_subset') xdata_lbl.grid(column=1, row=20, sticky=(N, W)) self.xidata_box = Spinbox(self, format='%.0f', from_=0, to=self.xf.get(), width=5, increment=1) self.xidata_box.grid(column=2, row=20, sticky=(N, W), padx=(15, 0)) self.xidata_box.insert(1, 0) self.xfdata_box = Spinbox(self, format='%.0f', from_=0, to=self.xf.get(), width=5, increment=1) self.xfdata_box.grid(column=3, row=20, sticky=(N, W)) self.xfdata_box.insert(1, 0) self.yi = IntVar() self.yi.set(0) self.yf = IntVar() self.yf.set(0) ydata_lbl = ttk.Label(self, text='y-data_subset') ydata_lbl.grid(column=1, row=21, sticky=(N, W)) self.yidata_box = Spinbox(self, format='%.0f', from_=0, to=self.yf.get(), width=5, increment=1) self.yidata_box.grid(column=2, row=21, sticky=(N, W), padx=(15, 0)) self.yidata_box.insert(1, 0) self.yfdata_box = Spinbox(self, format='%.0f', from_=0, to=self.yf.get(), width=5, increment=1) self.yfdata_box.grid(column=3, row=21, sticky=(N, W)) self.yfdata_box.insert(1, 0) def enable_btn(self): self.graph1_btn.config(state='ENABLED') self.int_btn.config(state='ENABLED') self.trans_btn.config(state='normal') self.Refl_x_btn.config(state='normal') self.N_out_btn.config(state='ENABLED') self.M_out_btn.config(state='ENABLED') self.tip_btn.config(state='normal') def Input_C(self): """"Loads tab-delimited data from the corresponding text-box""" A = self.input_entry.get() self.info1_Entry.delete(1.0, END) B = [] reader = csv.reader(A.split('\n'), delimiter='\t') for row in reader: row = row[:] B.append(row) B = B[0:len(B) - 1][0:len(B[0])] for i in range(0, len(B)): for j in range(0, len(B[i])): B[i][j] = float(B[i][j]) B = asarray(B) print(B) self.dx1_.set(0.18) self.dy1_.set(0.18) self.NP1.set(len(B[0]) * len(B) - 1) self.n_box.config(to=self.NP1.get()) self.xf.set(len(B[0])) self.xfdata_box.delete(0, "end") self.xfdata_box.insert(1, self.xf.get()) self.xidata_box.config(to=self.xf.get()) self.xfdata_box.config(to=self.xf.get()) self.yf.set(len(B)) self.yfdata_box.delete(0, "end") self.yfdata_box.insert(1, self.yf.get()) self.yidata_box.config(to=self.yf.get()) self.yfdata_box.config(to=self.yf.get()) self.C = B self.enable_btn() self.graph1(B, 1) return self.C def open1(self): """"Loads data from file and displays footer information""" fileName = filedialog.askopenfilename(title="Open CPD file") try: f = open(fileName, 'r') except IOError: pass i = f.readline().strip() if i == "Work Function data": pass else: i = messagebox.askyesno(title="Open file?", message="CPD file header not present!\n" "Proceed to open file?", default='no') if i == 1: pass else: pass self.path1.set(fileName) g = f.read() f.close() # Only CPD data is loaded but there are other measurements Tracking = g.find('Tracking') Grad = g.find('Grad') # Time = g.find('Time') # User = g.find('User') Footer = g.find('/') - 2 # Footer = Footer - 2 CPD_data = g[0:Tracking] # Tracking_data = g[Tracking:Grad] # Grad_data = g[Grad:Time] # Time_data = g[Time:User] # User_data = g[User:Footer] Footer_data = g[Footer:] a = Footer_data.split("\n") Date = a[0] Grad = [int(i) for i in a[-10].split() if i.isdigit()] DAS_Averages = [int(i) for i in a[-18].split() if i.isdigit()] WF_Averages = [int(i) for i in a[-14].split() if i.isdigit()] Xpoints = [int(i) for i in a[-5].split() if i.isdigit()] Ypoints = [int(i) for i in a[-4].split() if i.isdigit()] Xsteps = [int(i) for i in a[-3].split() if i.isdigit()] Ysteps = [int(i) for i in a[-2].split() if i.isdigit()] Xstepscm = Xsteps[0] * 0.0015 #xyscale Ystepscm = Ysteps[0] * 0.0015 # C is the array used for the raw data C = [] reader = csv.reader(CPD_data.split('\n'), delimiter=',') for row in reader: row = row[:-1] C.append(row) C = C[0:len(C) - 1][0:len(C[0])] for i in range(0, len(C)): for j in range(0, len(C[i])): C[i][j] = float(C[i][j]) C = asarray(C) # Clear the textbox before putting in data for new file self.info1_Entry.delete(1.0, END) info_0 = "%s\n%s\n" % (fileName, Date) info_1 = ("Xpoints = %s\nYpoints = %s\nXsteps = %s (%s cm)\n" "Ysteps= %s (%s cm)" \ % (Xpoints[0], Ypoints[0], Xsteps[0], Xstepscm, Ysteps[0], Ystepscm)) info_2 = "\nDAS_Aves = %s\nWF_Averages = %s\nGrad = %s"\ % (DAS_Averages[0],WF_Averages[0],Grad[0]) self.info1_Entry.insert(END, info_0) self.info1_Entry.insert(END, info_1) self.info1_Entry.insert(END, info_2) if self.Refl_x.get() == 1: info_3 = "\nReflect x = %s" % (self.Refl_x.get()) self.info1_Entry.insert(END, info_3) if self.transpose_chk.get() == 1: info_4 = "\nTranspose = %s" % (self.transpose_chk.get()) self.info1_Entry.insert(END, info_4) self.enable_btn() # To prevent divide by 0 issue 1E-8 is added if Xpoints[0] == len(C[0]): self.dx1_.set(Xstepscm + 1E-8) self.dy1_.set(Ystepscm + 1E-8) else: self.dy1_.set(Xstepscm + 1E-8) self.dx1_.set(Ystepscm + 1E-8) self.NP1.set(len(C[0]) * len(C) - 1) self.n_box.config(to=self.NP1.get()) self.xf.set(len(C[0])) self.xfdata_box.delete(0, "end") self.xfdata_box.insert(1, self.xf.get()) self.xidata_box.config(to=self.xf.get()) self.xfdata_box.config(to=self.xf.get()) self.yf.set(len(C)) self.yfdata_box.delete(0, "end") self.yfdata_box.insert(1, self.yf.get()) self.yidata_box.config(to=self.yf.get()) self.yfdata_box.config(to=self.yf.get()) self.tip.set(0) self.C = C self.Cr = C return self.C, self.Cr def graph1(self, data, row_a): """Graphs the raw CPD data""" plt.close() plt.figure(figsize=(3.5, 3.5), dpi=100, frameon=False) im = plt.imshow(data, cmap='jet') plt.colorbar(im, orientation='vertical', fraction=0.046, pad=0.05) plt.tight_layout() plt.savefig(path.join(tmpdir, im_name1), dpi=100, bbox_inches='tight') c = Canvas(self, width=350, height=350, bg='white') c.grid(row=row_a, column=5, columnspan=2, rowspan=50, sticky=(W, N), padx=50) c.background = PhotoImage(file=path.join(tmpdir, im_name1)) c.create_image(1, 20, image=c.background, anchor=NW) def interpolation(self, C): """Performs inverse distance interpolation""" temp = [] for j in range(int(self.yidata_box.get()), int(self.yfdata_box.get())): temp.append([]) for i in range(int(self.xidata_box.get()), int(self.xfdata_box.get())): temp[j - int(self.yidata_box.get())].append(C[j, i]) # Sub-array of raw data defined by the min and max x/y value C = temp C = asarray(C) n = self.n_box.get() n = int(n) p = self.p_box.get() p = int(p) x01 = float(self.x01_.get()) y01 = float(self.y01_.get()) dx1 = float(self.dx1_.get()) dy1 = float(self.dy1_.get()) y02 = float(self.y02_.get()) x02 = float(self.x02_.get()) dx2 = float(self.dx2_.get()) dy2 = float(self.dy2_.get()) np_x2 = int(self.np_x2_.get()) np_y2 = int(self.np_y2_.get()) if self.transpose_chk.get() == 1: C = transpose(C) # Define the dimensions of the raw data grid np_x1 = len(C[0]) np_y1 = len(C) NP1 = np_x1 * np_y1 x1 = ones(np_x1) for i in range(0, np_x1): x1[i] = x01 + dx1 * i y1 = ones(np_y1) for i in range(0, np_y1): y1[i] = y01 + dy1 * i if self.Refl_x.get() == 1: x1_ = ones(np_x1) for i in range(0, len(x1)): x1_[i] = x1[-1 - i] x1 = x1_ data_1d = C.flatten() # Define the dimensions of interpolated data grid NP2 = np_x2 * np_y2 x2 = ones(np_x2) for i in range(0, np_x2): x2[i] = x02 + dx2 * i y2 = ones(np_y2) for i in range(0, np_y2): y2[i] = y02 + dy2 * i # Intperolation calculation k2 = 0 int_data = ones(NP2) dist = [0] * (NP1) index = [0] * (NP1) for j2 in range(0, np_y2): for i2 in range(0, np_x2): dist_2d = [] dist_1d = [] for j in range(0, np_y1): dist_2d.append([]) for i in range(0, np_x1): dist_2d[j].append( sqrt((x2[i2] - x1[i])**2 + (y2[j2] - y1[j])**2)) dist_1d.append( sqrt((x2[i2] - x1[i])**2 + (y2[j2] - y1[j])**2)) index = sorted(range(len(dist_1d)), key=lambda x: dist_1d[x]) dist = sorted(dist_1d) up = min(n, NP1) temp = 0 lamb = ones(up) if dist[0] > 0: for i in range(0, up): lamb[i] = (1/(dist[i]**p))\ /sum(ones(up)/power_(dist[0:up],p)) temp = temp + data_1d[index[i]] * lamb[i] else: temp = data_1d[index[i]] int_data[k2] = temp k2 = k2 + 1 M1 = [] N = [] k2 = 0 for j2 in range(0, np_y2): N.append([]) for i2 in range(0, np_x2): M1.append([x02 + i2 * dx2, y02 + j2 * dy2, int_data[k2]]) N[j2].append(int_data[k2]) k2 = k2 + 1 M1 = asarray(M1) N = asarray(N) # Generate a xyz equivalent array if np_x2 == np_y2: Mt = [] for j2 in range(0, np_y2): for i2 in range(0, np_x2): Mt.append([y02 + j2 * dy2, x02 + i2 * dx2, N[i2, j2]]) k2 = k2 + 1 M = append(Mt, M1, axis=1) else: M = M1 self.N = N self.M1 = M1 self.M = M self.graph1(self.N, 8) self.plot_btn.config(state='ENABLED') return (self.N, self.M1, self.M) def check_tr(self, C): self.info1_Entry.delete(10.0, END) if self.Refl_x.get() == 1: info_3 = "\nReflect x = %s" % (self.Refl_x.get()) self.info1_Entry.insert(END, info_3) if self.transpose_chk.get() == 1: info_4 = "\nTranspose = %s" % (self.transpose_chk.get()) self.info1_Entry.insert(END, info_4) self.interpolation(C) def plot(self, C, N): """Produces images of the raw and interpolated data plots""" plt.close('all') fig_ext = plt.figure(dpi=200) ax1 = fig_ext.add_subplot(121) ax1_im = plt.imshow(C, vmin=amin([amin(C), amin(N)]), vmax=amax([amax(C), amax(N)]), cmap='jet') cbar = plt.colorbar(ax1_im, orientation='vertical', fraction=0.046, pad=0.05) # aspect='auto') if self.tip.get() == 1: cbar.set_label('Work Function (meV)') else: cbar.set_label('CPD (mV)') plt.xlabel('x-axis') plt.ylabel('y-axis') ax2 = fig_ext.add_subplot(122) ax2_im = plt.imshow(N, vmin=amin([amin(C), amin(N)]), vmax=amax([amax(C), amax(N)]), cmap='jet') cbar = plt.colorbar(ax2_im, orientation='vertical', fraction=0.046, pad=0.05) #, aspect='auto') if self.tip.get() == 1: cbar.set_label('Work Function (meV)') else: cbar.set_label('CPD (mV)') plt.xlabel('x-axis') plt.ylabel('y-axis') plt.tight_layout() fig_ext = plt.gcf() plt.show() def N_out(self, N): """Exports the data as a csv file via dialogue box""" file_opt = options = {} options['filetypes'] = [('all files', '.*'), ('CSV (Comma Delimited)', '.csv')] options['initialfile'] = '.csv' options['title'] = 'Save Array as CSV' try: fo1 = filedialog.asksaveasfile(mode='wb', **file_opt) savetxt(fo1, N, delimiter=',', footer=self.info1_Entry.get(1.0, END)) fo1.close() except IOError: messagebox.showinfo(title="Output file", message="Output file issue") def workfunction(self, C): """Applies linear offset to CPD, useful for correcing for the tip's workfunction and converting CPD into workfunction""" if self.tip.get() == 1: self.C = C + float(self.tipwf.get()) self.tip_entry.config(state='disabled') else: self.C = (C - float(self.tipwf.get())) self.tip_entry.config(state="normal") self.graph1(self.C, 1) return self.C
def __init__(self, master, title, x_coor, y_coor, data, variant=False, font_size=11): self.__chb_var = IntVar() self.__state = StringVar() self.__count = StringVar() self.__xObs = StringVar() self.__p_value = StringVar() self.__result = StringVar() self.__results = [] self.__variant = variant checkbox = Checkbutton(master, text=title, variable=self.__chb_var) checkbox.config(font=("Calibri", font_size)) checkbox.place(x=x_coor, y=y_coor) state_label = LabelTag(master, 'State', (x_coor + 60), (y_coor + 30), width=100, font_size=font_size, border=2, relief='groove') if variant: self.__state.set('-1.0') else: self.__state.set('+1') state_option = OptionMenu(master, self.__state, *data) state_option.place(x=(x_coor + 60), y=(y_coor + 60), height=25, width=100) if not variant: xObs_label = LabelTag(master, 'CHI-SQUARED', (x_coor + 165), (y_coor + 30), width=350, font_size=font_size, border=2, relief='groove') xObs_Entry = Entry(master, textvariable=self.__xObs) xObs_Entry.place(x=(x_coor + 165), y=(y_coor + 60), width=350, height=25) else: count_label = LabelTag(master, 'Count', (x_coor + 165), (y_coor + 30), width=350, font_size=font_size, border=2, relief='groove') count_Entry = Entry(master, textvariable=self.__count) count_Entry.place(x=(x_coor + 165), y=(y_coor + 60), width=350, height=25) pass p_value_label = LabelTag(master, 'P-Value', (x_coor + 520), (y_coor + 30), width=350, font_size=font_size, border=2, relief='groove') p_value_Entry = Entry(master, textvariable=self.__p_value) p_value_Entry.place(x=(x_coor + 520), y=(y_coor + 60), width=350, height=25) conclusion_label = LabelTag(master, 'Conclusion', (x_coor + 875), (y_coor + 30), width=150, font_size=font_size, border=2, relief='groove') conclusion_Entry = Entry(master, textvariable=self.__result) conclusion_Entry.place(x=(x_coor + 875), y=(y_coor + 60), width=150, height=25) update_button = Button(master, text='Update', command=self.update) update_button.config(font=("Calibri", 10)) update_button.place(x=(x_coor + 1030), y=(y_coor + 60), width=180, height=25)
""" check buttons, the easy way """ from tkinter import Tk, Checkbutton, IntVar, LEFT root = Tk() states = [] for i in range(10): var = IntVar() chk = Checkbutton(root, text=str(i), variable=var) chk.pack(side=LEFT) states.append(var) root.mainloop() # let tkinter keep track print([var.get() for var in states]) # show all states on exit (or map/lambda) # alternatives # print(list(map(IntVar.get, states))) # print(list(map(lambda var: var.get(), states)))
def recognize_flowchart_window(self): """ Recognize flowchart window. """ window = tk.Toplevel(self.master) header = tk.Frame(window) header.config(width="400", height="50", bg="#857074") header.pack(fill="y") header.pack_propagate(False) title = tk.Label(header, text="Recognize flowchart", font=("Arial", 20), bg="#857074") title.pack(pady=5) window.pack_propagate(False) window.config(width="400", height="470", bg="#943340") # Diferent models to select model_folder_list = os.listdir(self.models_path) model_folder_list.append("Select a folder of training results") model_folder_list.reverse() combobox_model_folder = ttk.Combobox(window, values=model_folder_list, width=27, font=("Arial", 13)) combobox_model_folder.pack(pady=40) combobox_model_folder.current(0) # Button for select image button_image = tk.Button(window, text="Select image", width=18, height=2, font=("Arial", 12), command=self.__select_image) button_image.pack(pady=10) # Use GPU use_gpu_val = IntVar() use_gpu_check = Checkbutton(window, text="Use GPU", variable=use_gpu_val, width=20, height=2, background="#943340") use_gpu_check.pack(pady=10) # Number of RoIs num_rois_lbl = tk.Label(window, text="Optional, default: 32", height=2, width=20, bg="#943340", font=("Arial", 10)) num_rois_lbl.pack() num_rois_input = tk.Entry(window, font=("Arial", 12), width=20) num_rois_input.insert(0, 'Type number of RoIs') num_rois_input.bind('<FocusIn>', lambda args: num_rois_input.delete('0', 'end')) num_rois_input.bind( '<FocusOut>', lambda x: num_rois_input.insert('0', 'Type number of RoIs') if not num_rois_input.get() else 0) num_rois_input.pack(pady=10) # Button for start to predict button_predict = tk.Button( window, text="Predict", width=20, height=2, font=("Arial", 15), background="green", command=lambda: self.predict([ combobox_model_folder.get(), self.selected_image, use_gpu_val.get(), num_rois_input.get() ], window)) button_predict.pack(pady=20)
def train_window(self): """ Train model window. """ window = tk.Toplevel(self.master) window.pack_propagate(False) window.title("Train shape model") window.config(width="700", height="600", bg="#943340") title = tk.Label(window, font=("Arial", 50), text="Train shape model", bg="#943340") title.pack() large_font = ('Arial', 15) text_font = ('Arial', 12) mini_text_font = ('Arial', 7) inputs = tk.Frame(window) inputs.config(bg="#943340") inputs.pack(side=tk.LEFT) # Select folder path of dataset text = tk.StringVar() dataset_path_text = tk.Label(inputs, height=3, width=50, bg="#943340", font=mini_text_font, textvariable=text) dataset_path_text.grid(row=0, column=1) dataset_path_button = tk.Button( inputs, text="* Select dataset", font=("Arial", 9), width=10, command=lambda: self.__select_dataset_path(text)).grid(row=0, column=0) # Pre-trained-model-path text_2 = tk.StringVar() pretrained_model_path_text = tk.Label(inputs, height=3, width=50, bg="#943340", font=mini_text_font, textvariable=text_2) pretrained_model_path_text.grid(row=1, column=1) pretrained_model_path_button = tk.Button( inputs, text="Select trained model", font=("Arial", 9), width=14, command=lambda: self.__select_pretrained_model_path(text_2)).grid( row=1, column=0) # Number of Regions of Interest (RoIs) num_rois_text = tk.Label(inputs, text="# RoIs", height=3, width=15, bg="#943340", font=text_font).grid(row=2) num_rois_input = tk.Entry(inputs, font=large_font) num_rois_input.grid(row=2, column=1) # Number of epochs num_epochs_text = tk.Label(inputs, text="* Epochs", height=3, width=15, bg="#943340", font=text_font).grid(row=3) num_epochs_input = tk.Entry(inputs, font=large_font) num_epochs_input.grid(row=3, column=1) # Learning rate learning_rate_text = tk.Label(inputs, text="* learning rate", height=3, width=15, bg="#943340", font=text_font).grid(row=4) learning_rate_input = tk.Entry(inputs, font=large_font) learning_rate_input.grid(row=4, column=1) # Check - use_gpu use_gpu_text = tk.Label(inputs, text="Use GPU", height=3, width=15, bg="#943340", font=text_font).grid(row=5) use_gpu_val = IntVar() use_gpu_check = Checkbutton(inputs, variable=use_gpu_val) use_gpu_check.grid(row=5, column=1) #start button start_button = tk.Button(inputs, text="Start", font=("Arial", 15), width=10, command=lambda: self.start_train_action([ dataset_path_text.cget("text"), num_rois_input.get(), pretrained_model_path_text.cget("text"), num_epochs_input.get(), learning_rate_input.get(), use_gpu_val.get() ])) start_button.grid(row=6, column=1)
def __init__(self, parent, usu, *args, **kwargs): super().__init__(parent, *args, **kwargs) global linea1 self.parent = parent self.tamagnoletra = ("Arial",10,"bold") self.back1="#525252" #8cabbe self.button1="#59c9b9" self.fore="white" self.foreblack="black" self.configure(bg="#525252") self.registros = vecinos() self.title("Reportes") # Frame Principal self.frm_main = tkr.Frame(self, relief='ridge') self.frm_main.pack(padx=self.PAD, pady=self.PAD, fill="both", expand='yes') sw = self.winfo_screenwidth() sh = self.winfo_screenheight() w = sw * 0.7 h = sh * 0.7 x = (sw - w) / 2 y = (sh - h) / 2 self.geometry("%dx%d+%d+%d" % (w, h, x, y)) self.attributes('-zoomed', True) self.protocol("WM_DELETE_WINDOW", self.volver) self.cuaderno1 = tkrttk.Notebook(self.frm_main) tkrttk.Style().configure("TNotebook", background=self.back1) self.pagina1 = tkr.Frame(self.cuaderno1, background=self.back1) self.cuaderno1.add(self.pagina1, text="Reportes") self.labelframe1=tkr.LabelFrame(self.pagina1) self.labelframe1.configure( background=self.back1) self.labelframe1.grid(column=0, row=0, padx=5, pady=10) self.frameBuscar=Frame(self.labelframe1, bd=1, background=self.back1) self.frametabla=Frame(self.labelframe1, bd=1, background=self.back1) self.frameBuscar.grid(column=0, row=0, padx=5, pady=10) self.frametabla.grid(column=1, row=0, padx=5, pady=10) #Hacer un query para llamar la información de las Tores registros = vecinos() self.ref = registros.combo_add("TORRE",0) #mostrar la lista en checkbox las opciones para filtrar por edificio self.arreglo=[] self.variab=[] self.linea1=0 for int in self.ref: self.variab.append(IntVar()) #command=self.selecc, #########################pendiete self.arreglo.append(Checkbutton(self.frameBuscar, highlightbackground=self.back1, relief="flat", bg=self.back1, fg=self.fore, font=self.tamagnoletra, selectcolor='black', text=int[0],variable=self.variab[self.ref.index(int)])) for mostrar in self.arreglo: self.linea1=self.linea1+1 mostrar.grid(row=self.linea1, column=0, sticky="w") self.linea1=self.linea1+1 #crear el FRame que contendrá los campos de la tabla maestra self.labelframe2=tkr.LabelFrame(self.pagina1) self.labelframe2.configure( background=self.back1, highlightbackground=self.back1) #'height=200' self.labelframe2.grid(column=1, row=0, padx=5, pady=10) linea=0 #Boton para actualizar la información #command=self.updateReg self.button1=tkr.Button(self.labelframe2, command=self.generarRep, text='Generar', highlightbackground=self.back1,bg=self.button1, fg=self.foreblack, font=self.tamagnoletra) self.button1.grid(column=0, row=linea, padx=4, pady=4) #Boton para eliminar datos de la lista de vecinos seleccionado buttonsalir= tkr.Button(self.labelframe2,text='Salir',command=self.volver, highlightbackground=self.back1,bg="#59c9b9", fg=self.foreblack, font=self.tamagnoletra) buttonsalir.grid(column=1, row=linea, padx=4, pady=4) query = "SELECT vec.*, tb1.campo_des, tb2.campo_des FROM vecinos_temporal vec left join tbreferencia tb1 on vec.id_piso = tb1.contador left join tbreferencia tb2 on vec.id_torre = tb2.contador order by id_torre,id_piso,apto,id_miembro" registros = vecinos() self.reg = registros.listarVecinos(query) #llamar para crear el treeview de los registrs de vecinos_temporal treeview_1 = vistas() self.listatree2 = treeview_1.treeview_registros(self.frametabla) """ Hacer TREEVIEW lista """ self.resultado = treeview_1.lista(self.reg,self.listatree2) self.cuaderno1.grid(column=0, row=0, padx=10, pady=10)
def __setup__(self): frame_color = LabelFrame(self._root, text='Color settings') frame_target_apogee = LabelFrame(self._root, text='Target apogee') frame_velocity = LabelFrame(self._root, text='Velocity reference line') frame_color.pack(side="top", fill="both", expand=True, padx=5) frame_target_apogee.pack(side="top", fill="both", expand=True, padx=5) frame_velocity.pack(side="top", fill="both", expand=True, padx=5, pady=5) # ============================================================================================================== # Color settings # ============================================================================================================== label_inner_color = Label(frame_color, text='Inner color') label_outer_color = Label(frame_color, text='Outer color') label_line_color = Label(frame_color, text='Line color') label_rgb = Label(frame_color, text='hex RGB') label_inner_color.grid(row=1, column=0, padx=10) label_outer_color.grid(row=2, column=0, padx=10) label_line_color.grid(row=3, column=0, padx=10, pady=(0, 5)) label_rgb.grid(row=0, column=1, padx=(0, 10)) self.entry_inner_color = Entry(frame_color, width=10) self.entry_inner_color.grid(row=1, column=1, padx=(0, 10)) self.entry_inner_color.delete(0, 'end') self.entry_inner_color.insert(0, self._main.inner_color) self.entry_outer_color = Entry(frame_color, width=10) self.entry_outer_color.grid(row=2, column=1, padx=(0, 10)) self.entry_outer_color.delete(0, 'end') self.entry_outer_color.insert(0, self._main.outer_color) self.entry_line_color = Entry(frame_color, width=10) self.entry_line_color.grid(row=3, column=1, padx=(0, 10), pady=(0, 5)) self.entry_line_color.delete(0, 'end') self.entry_line_color.insert(0, self._main.line_color) # ============================================================================================================== # Target apogee # ============================================================================================================== label_target_apogee = Label(frame_target_apogee, text='Target apogee [m]') label_target_apogee.grid(row=0, column=0, padx=10) label_show_line_apogee = Label(frame_target_apogee, text='Show line') label_show_line_apogee.grid(row=1, column=0, padx=10) self.entry_target_apogee = Entry(frame_target_apogee, width=10) self.entry_target_apogee.grid(row=0, column=1, padx=(0, 10)) self.entry_target_apogee.delete(0, 'end') self.entry_target_apogee.insert(0, self._main.target_apogee) self.show_line_apogee = IntVar(value=self._main.show_line_apogee) show_apogee_button = Checkbutton(frame_target_apogee, variable=self.show_line_apogee, onvalue=True, offvalue=False) show_apogee_button.grid(row=1, column=1) if self.show_line_apogee.get(): show_apogee_button.select() # ============================================================================================================== # Velocity reference line # ============================================================================================================== label_reference_velocity = Label(frame_velocity, text='Reference velocity [m/s]') label_reference_velocity.grid(row=0, column=0) label_show_line_vel = Label(frame_velocity, text='Show line') label_show_line_vel.grid(row=1, column=0, padx=10) self.entry_reference_velocity = Entry(frame_velocity, width=10) self.entry_reference_velocity.grid(row=0, column=1, padx=(0, 10)) self.entry_reference_velocity.delete(0, 'end') self.entry_reference_velocity.insert(0, self._main.reference_velocity) self.show_line_velocity = IntVar(value=self._main.show_line_velocity) show_velocity_button = Checkbutton(frame_velocity, variable=self.show_line_velocity, onvalue=True, offvalue=False) show_velocity_button.grid(row=1, column=1) if self.show_line_velocity.get(): show_velocity_button.select() # Save save_button = Button(self._root, text='Save', command=self.save) save_button.pack()
def __init__(self, parent, fields: SettingsGUIFields): self.frame = Frame(parent.master, bd=2, relief=GROOVE) self.parent = parent self.fields = fields self.dimensionCheckbutton = BooleanVar() self.doNotUseBgCheckbutton = BooleanVar() if self.fields.VAR_PATH_WINDOW_BG_IMAGE == "": self.doNotUseBgCheckbutton.set(True) ROW_BG_SETTINGS = 0 ROW_BG_COLOR = 1 ROW_BG_IMAGE = 2 ROW_SET_DIMENSIONS = 3 ROW_DO_NOT_USE_BG = 4 bgColorFrame = Frame(self.frame) self.LABEL_WINDOW_BG_COLOR = Label( bgColorFrame, textvariable=fields.VAR_LABEL_WINDOW_BG_COLOR_TEXT) Label(self.frame, text="Background Settings").grid(row=ROW_BG_SETTINGS, column=0, sticky=W) self.BUTTON_WINDOW_BG_COLOR = HoverButton( self.frame, text='Background Color:', width=15, command=lambda: self.updateWindowColor(fields)) self.BUTTON_WINDOW_BG_COLOR.grid(row=ROW_BG_COLOR, column=0, sticky=E, padx=4) self.LABEL_WINDOW_BG_COLOR.grid(row=0, column=1, sticky=W) self.LABEL_WINDOW_BG_IMAGE = Label( self.frame, textvariable=fields.VAR_DISPLAY_WINDOW_BG_IMAGE, width=20, anchor=W) self.BUTTON_WINDOW_BG_IMAGE = HoverButton( self.frame, text='Background Image:', width=15, command=lambda: self.selectImageFile(fields)) self.BUTTON_WINDOW_BG_IMAGE.grid(row=ROW_BG_IMAGE, column=0, sticky=E, padx=4, pady=4) self.LABEL_WINDOW_BG_IMAGE.grid(row=ROW_BG_IMAGE, column=1, sticky=W) self.CANVAS_WINDOW_BG_IMAGE = Canvas(bgColorFrame, width=80, height=30) self.RECTANGLE_WINDOW_BG_IMAGE = self.CANVAS_WINDOW_BG_IMAGE.create_rectangle( 80, 4, 0, 30, fill=fields.VAR_LABEL_WINDOW_BG_COLOR_BACKGROUND, outline="") self.fitWindowFrame = Frame(self.frame) self.checkbuttonSetDimensions = Checkbutton( self.fitWindowFrame, text="Fit window to background image", variable=self.dimensionCheckbutton, command=lambda: self.updateWindowDimensions()) self.checkbuttonSetDimensions.grid(row=0, column=0, sticky=W) self.fitWindowFrame.grid(row=ROW_SET_DIMENSIONS, column=0, columnspan=2, padx=4, pady=4, sticky=W) self.buttonClearImage = HoverButton( self.frame, text='Remove Image', width=15, command=lambda: self.updateBackgroundImage()) self.buttonClearImage.grid(row=ROW_DO_NOT_USE_BG, column=0, columnspan=3, sticky=SE, padx=4, pady=(0, 4)) self.CANVAS_WINDOW_BG_IMAGE.grid(row=0, column=0, sticky=W) bgColorFrame.grid(row=ROW_BG_COLOR, column=1, sticky=W)
scrollbar = Scrollbar(bodyframe) scrollbar.config(command=mc.interior.yview, activebackground=btn_colour) scrollbar.grid(row=1, column=7, sticky=N + S) mc.interior.config(yscrollcommand=scrollbar.set) mc.interior.grid(row=1, column=0, columnspan=6, sticky=N + S + E + W) entry = Entry(bodyframe) entry.insert(0, "30") entry.focus_set() mc.table_data = show_within(entry.get()) chkbox1 = Checkbutton(bodyframe, text="Informed", variable=informed, bg=bg_colour) chkbox2 = Checkbutton(bodyframe, text="Inspected", variable=inspected, bg=bg_colour) chkbox3 = Checkbutton(bodyframe, text="Renewed", variable=renewed, bg=bg_colour) def callback(): """ update database with boolean values. currently partially managed by model.py
def pollutionWindow(previousWindow): # closes menu and opens pollution window countrySelection = Tk() previousWindow.withdraw() countrySelection.geometry('400x225') countrySelection.configure(bg='light cyan') # values of checkboxes europe = BooleanVar(countrySelection) china = BooleanVar(countrySelection) unitedStates = BooleanVar(countrySelection) india = BooleanVar(countrySelection) glob = BooleanVar(countrySelection) # creation of checkboxes Checkbutton(countrySelection, text='Europe', variable=europe, onvalue=1, offvalue=0, bg='light cyan').pack() Checkbutton(countrySelection, text='China', variable=china, onvalue=1, offvalue=0, bg='light cyan').pack() Checkbutton(countrySelection, text='United States', variable=unitedStates, onvalue=1, offvalue=0, bg='light cyan').pack() Checkbutton(countrySelection, text='India', variable=india, onvalue=1, offvalue=0, bg='light cyan').pack() Checkbutton(countrySelection, text='Global', variable=glob, onvalue=1, offvalue=0, bg='light cyan').pack() # button that creates graph graphPrices = Button(countrySelection, text='Graph', command=lambda: pollutionData( [europe, china, unitedStates, india, glob]), bg='white') graphPrices.place(x=97, y=150) # button that graphs all graphAll = Button(countrySelection, text='Graph All', command=lambda: pollutionData(), bg='white') graphAll.place(x=150, y=150) # return to menu button menuButton = Button(countrySelection, text='Return to Menu', command=lambda: menuWindow(countrySelection), bg='white') menuButton.place(x=220, y=150)
from tkinter import Tk,Frame,Checkbutton,BooleanVar,BOTH root=Tk() def onClick(): if var.get()==True: root.title("Checkbutton") else: root.title('') var=BooleanVar() cb=Checkbutton(root,text="Show title",variable=var,command=onClick) cb.select() cb.place(x=50,y=50) root.mainloop()
def change(self): if self.windowOpen: return else: self.windowOpen = 1 self.window = Toplevel() self.window.title(_('Change custom menus')) self.window.protocol('WM_DELETE_WINDOW', self.c_cancel) # scrolled list with all submenus, entries self.list = v.ScrolledList(self.window, width=35, font='Courier') self.list.pack() self.current = None self.correspEntry = [[0, '', '', None, None]] self.list.insert('end', '*') self.c_buildList(self.customMenuList, 1) # buttons ... for currently selected entry f = Frame(self.window) self.addEntryB = Button(f, text=_('Add entry'), command=self.c_addEntry) self.addSubmenuB = Button(f, text=_('Add submenu'), command=self.c_addSubmenu) self.deleteB = Button(f, text=_('Delete'), command=self.c_delete) self.addEntryB.pack(side=LEFT, anchor=W) self.addSubmenuB.pack(side=LEFT, anchor=W) self.deleteB.pack(side=LEFT, anchor=W) f.pack(anchor=W) Frame(self.window, background='black', height=1, width=100).pack(expand=YES, fill=X, pady=10) Label(self.window, text=_('Name:')).pack(anchor=W) self.nameCurrent = StringVar() self.nameE = Entry(self.window, width=40, textvariable=self.nameCurrent, takefocus=1) self.nameE.bind('<Return>', self.c_setName) self.nameE.bind('<Tab>', self.c_setName) self.nameE.pack(anchor=W) Frame(self.window, height=15, width=200).pack() Label(self.window, text=_('HTML file:')).pack(anchor=W) f = Frame(self.window) f.pack(anchor=W) self.htmlCurrent = StringVar() self.htmlE = Entry(f, width=35, textvariable=self.htmlCurrent, takefocus=1) self.htmlE.pack(side=LEFT) self.browseB = Button(f, text=_('Browse ...'), command=self.c_browse, height=1) self.browseB.pack(side=RIGHT) Frame(self.window, height=15, width=200).pack() f = Frame(self.window) self.patternB = Button(f, text=_('Add pattern info'), command=self.c_addPattern) self.patternB.pack(side=LEFT) self.giB = Button(f, text=_('Add game info'), command=self.c_addGI) self.giB.pack(side=LEFT) self.resetVar = IntVar() self.resetB = Checkbutton(f, text=_('Reset game list'), highlightthickness=0, variable=self.resetVar) self.resetB.pack(side=LEFT) f.pack(anchor=W) # OK, cancel buttons Frame(self.window, background='black', height=1, width=100).pack(expand=YES, fill=X, pady=10) f = Frame(self.window) f.pack(side=BOTTOM, anchor=E) Button(f, text=_('Cancel'), command=self.c_cancel).pack(side=RIGHT, anchor=E) Button(f, text=_('OK'), command=self.c_OK).pack(side=RIGHT, anchor=E) self.list.list.select_set(0) self.pollList() self.window.update_idletasks() self.window.focus() # self.window.grab_set() self.window.wait_window() del self.window self.windowOpen = 0
def makeInputFrame(self): self.inp_seed = String() self.bgColor = String() self.gen_value = Int() self.rainbowCheck = Int() self.fram_input = Frame(self, bd= 2, relief= self.style, width= input_frame_width, height= input_frame_height) self.fram_seed = Frame(self.fram_input, bd= 1, relief= self.style) self.fram_prod = Frame(self.fram_input, bd= 1, relief= self.style) self.fram_draw = Frame(self.fram_input, bd= 1, relief= self.style) self.fram_drawParams = Frame(self.fram_input, bd= 1, relief= self.style) self.fram_gen = Frame(self.fram_input, bd= 1, relief= self.style) self.fram_output = Frame(self.fram_input, bd= 1, relief= self.style) self.menu_gen = DropDown(self.fram_gen, textvariable= self.gen_value, state= 'readonly') self.entr_seed = Input(self.fram_seed, textvariable= self.inp_seed) self.text_output = Output(self.fram_output, width= 35, height= 10) self.scrl_output = Scrollbar(self.fram_output) self.list_prod = List(self.fram_prod, selectmode= BROWSE, font= "Courier 8", height= 5) self.list_draw = List(self.fram_draw, selectmode= BROWSE, font= "Courier 8", height= 5) self.slid_linesize = Slider(self.fram_drawParams, from_= 0.1, to= 10.0, orient= HORIZONTAL, resolution= 0.1, length= 180) self.slid_timer = Slider(self.fram_drawParams, from_= 0, to= 2, orient= HORIZONTAL, resolution= 0.02, length= 180) self.slid_angle = Slider(self.fram_drawParams, from_= 0, to= 359, orient= HORIZONTAL, length= 180) self.entr_bgcolor = Input (self.fram_drawParams, textvariable= self.bgColor) self.butt_prodAdd = Button(self.fram_prod, text= "Add", width=8, command= self.AddProductionRule) self.butt_prodEdit = Button(self.fram_prod, text= "Edit", width=8, command= self.EditProductionRule) self.butt_prodDelete = Button(self.fram_prod, text= "Delete", width=8, command= self.DeleteProductionRule) self.butt_drawAdd = Button(self.fram_draw, text= "Add", width=8, command= self.AddDrawingRule) self.butt_drawEdit = Button(self.fram_draw, text= "Edit", width=8, command= self.EditDrawingRule) self.butt_drawDelete = Button(self.fram_draw, text= "Delete", width=8, command= self.DeleteDrawingRule) self.chek_incColor = CheckBox(self.fram_draw, text= "Rainbow", variable= self.rainbowCheck) Label(self.fram_seed, text= "Axiom:", width=8).grid (row=0, column=0) Label(self.fram_prod, text= "Production\nRules:", width=8).grid (row=0, column=0) Label(self.fram_draw, text= "Drawing\nRules:", width=8).grid (row=0, column=0) Label(self.fram_drawParams, text= "Line Size:").grid (row=0, column=0) Label(self.fram_drawParams, text= "Delay (ms):").grid (row=1, column=0) Label(self.fram_drawParams, text= "Starting Angle:").grid (row=2, column=0) Label(self.fram_drawParams, text= "Background Color:").grid (row=3, column=0) Label(self.fram_output, text= "Output:").grid (row=0, column=0) Label(self.fram_gen, text= "Generations:").grid (row=0, column=0) self.gen_value.set(1) self.menu_gen['values'] = tuple(range(1, 13)) self.slid_linesize.set(1.0) self.bgColor.set( Color.default() ) self.text_output.config(state='disabled', yscrollcommand= self.scrl_output.set) self.scrl_output.config(command=self.text_output.yview) self.fram_input.grid (row=0, column=0) self.fram_seed.grid (row=1, column=0, sticky= 'ew') self.fram_prod.grid (row=2, column=0, sticky= 'ew') self.fram_draw.grid (row=3, column=0, sticky= 'ew') self.fram_drawParams.grid (row=4, column=0, sticky= 'ew') self.fram_gen.grid (row=5, column=0, sticky= 'ew') self.fram_output.grid (row=6, column=0, sticky= 'ew') self.entr_seed.grid (row=0, column=1, sticky= 'ew') self.list_prod.grid (row=0, column=1, sticky= 'ew') self.butt_prodAdd.grid (row=1, column=0, sticky= 'ew') self.butt_prodEdit.grid (row=1, column=1, sticky= 'ew') self.butt_prodDelete.grid (row=1, column=2, sticky= 'ew') self.list_draw.grid (row=0, column=1) self.butt_drawAdd.grid (row=1, column=0, sticky= 'ew') self.butt_drawEdit.grid (row=1, column=1, sticky= 'ew') self.butt_drawDelete.grid (row=1, column=2, sticky= 'ew') self.chek_incColor.grid (row=0, column=2) self.slid_linesize.grid (row=0, column=1, sticky= 'ew') self.slid_timer.grid (row=1, column=1, sticky= 'ew') self.slid_angle.grid (row=2, column=1, sticky= 'ew') self.entr_bgcolor.grid (row=3, column=1, sticky= 'ew') self.menu_gen.grid (row=0, column=1, sticky= 'ew') self.text_output.grid (row=1, column=0) self.scrl_output.grid (row=1, column=1, sticky= 'ns')
class CustomMenus: def __init__(self, master): self.mainMenu = master.mainMenu self.master = master self.htmlpath = os.curdir self.windowOpen = 0 self.path = v.get_configfile_directory() def buildMenus(self, reload=1, alternativePath=''): """ format of menuList entries: { 'name' : name (which will be displayed in the menu), 'entries': [list of entries] 'subm' : [list of submenus] } format of entry: { 'name' : name which will be displayed in the menu, 'file' : name of a html file which will be displayed upon clicking this entry (or empty), 'gisearch' : parameters of a game info search to be done when this is chosen, 'psearch' : pattern and options for a pattern search } format of submenu: {} as in menuList """ if reload: fallback = b"(lp1\n(dp2\nS'subm'\np3\n(lp4\nsS'name'\np5\nS'Fuseki'\np6\nsS'entries'\np7\n(lp8\n(dp9\nS'gisearch'\np10\n(tsS'reset'\np11\nI1\nsS'psearch'\np12\n(((I0\nI0\ntp13\n(I18\nI18\ntt(dp14\n(I7\nI3\ntp15\nS'.'\ns(I16\nI9\ntp16\nS'.'\ns(I8\nI5\ntp17\nS'.'\ns(I9\nI0\ntp18\nS'.'\ns(I-1\nI14\ntp19\nS'.'\ns(I10\nI7\ntp20\nS'.'\ns(I0\nI17\ntp21\nS'.'\ns(I14\nI1\ntp22\nS'.'\ns(I12\nI17\ntp23\nS'.'\ns(I-1\nI16\ntp24\nS'.'\ns(I15\nI4\ntp25\nS'.'\ns(I3\nI2\ntp26\nS'.'\ns(I4\nI5\ntp27\nS'.'\ns(I2\nI2\ntp28\nS'O'\ns(I16\nI0\ntp29\nS'.'\ns(I17\nI13\ntp30\nS'.'\ns(I8\nI12\ntp31\nS'.'\ns(I16\nI-1\ntp32\nS'.'\ns(I9\nI9\ntp33\nS'.'\ns(I10\nI14\ntp34\nS'.'\ns(I11\nI15\ntp35\nS'.'\ns(I14\nI8\ntp36\nS'.'\ns(I12\nI8\ntp37\nS'.'\ns(I15\nI13\ntp38\nS'.'\ns(I13\nI13\ntp39\nS'.'\ns(I0\nI14\ntp40\nS'.'\ns(I3\nI11\ntp41\nS'.'\ns(I1\nI15\ntp42\nS'.'\ns(I4\nI12\ntp43\nS'.'\ns(I2\nI12\ntp44\nS'.'\ns(I5\nI1\ntp45\nS'.'\ns(I3\nI17\ntp46\nS'.'\ns(I16\nI7\ntp47\nS'.'\ns(I6\nI14\ntp48\nS'.'\ns(I17\nI6\ntp49\nS'.'\ns(I7\nI15\ntp50\nS'.'\ns(I10\nI9\ntp51\nS'.'\ns(I11\nI4\ntp52\nS'.'\ns(I12\nI7\ntp53\nS'.'\ns(I-1\nI2\ntp54\nS'.'\ns(I15\nI10\ntp55\nS'.'\ns(I13\nI6\ntp56\nS'.'\ns(I0\nI5\ntp57\nS'.'\ns(I1\nI0\ntp58\nS'.'\ns(I4\nI11\ntp59\nS'.'\ns(I2\nI7\ntp60\nS'.'\ns(I5\nI10\ntp61\nS'.'\ns(I6\nI1\ntp62\nS'.'\ns(I4\nI17\ntp63\nS'.'\ns(I7\nI4\ntp64\nS'.'\ns(I17\nI17\ntp65\nS'.'\ns(I8\nI0\ntp66\nS'.'\ns(I-1\nI5\ntp67\nS'.'\ns(I1\nI-1\ntp68\nS'.'\ns(I16\nI11\ntp69\nS'.'\ns(I17\nI10\ntp70\nS'.'\ns(I8\nI7\ntp71\nS'.'\ns(I9\nI6\ntp72\nS'.'\ns(I-1\nI12\ntp73\nS'.'\ns(I10\nI5\ntp74\nS'.'\ns(I11\nI8\ntp75\nS'.'\ns(I14\nI7\ntp76\nS'.'\ns(I15\nI6\ntp77\nS'.'\ns(I0\nI9\ntp78\nS'.'\ns(I3\nI4\ntp79\nS'.'\ns(I4\nI7\ntp80\nS'.'\ns(I10\nI-1\ntp81\nS'.'\ns(I5\nI6\ntp82\nS'.'\ns(I16\nI2\ntp83\nS'.'\ns(I17\nI3\ntp84\nS'.'\ns(I7\nI16\ntp85\nS'.'\ns(I8\nI14\ntp86\nS'.'\ns(I9\nI15\ntp87\nS'.'\ns(I10\nI12\ntp88\nS'.'\ns(I11\nI1\ntp89\nS'.'\ns(I9\nI17\ntp90\nS'.'\ns(I14\nI14\ntp91\nS'O'\ns(I12\nI10\ntp92\nS'.'\ns(I15\nI15\ntp93\nS'.'\ns(I13\nI11\ntp94\nS'.'\ns(I2\nI16\ntp95\nS'.'\ns(I0\nI0\ntp96\nS'.'\ns(I3\nI13\ntp97\nS'.'\ns(I1\nI13\ntp98\nS'.'\ns(I4\nI14\ntp99\nS'.'\ns(I2\nI10\ntp100\nS'.'\ns(I5\nI15\ntp101\nS'.'\ns(I9\nI-1\ntp102\nS'.'\ns(I6\nI12\ntp103\nS'.'\ns(I17\nI4\ntp104\nS'.'\ns(I7\nI9\ntp105\nS'.'\ns(I11\nI6\ntp106\nS'.'\ns(I14\nI17\ntp107\nS'.'\ns(I12\nI1\ntp108\nS'.'\ns(I-1\nI0\ntp109\nS'.'\ns(I10\nI17\ntp110\nS'.'\ns(I13\nI4\ntp111\nS'.'\ns(I0\nI7\ntp112\nS'.'\ns(I1\nI6\ntp113\nS'.'\ns(I2\nI5\ntp114\nS'.'\ns(I5\nI8\ntp115\nS'.'\ns(I6\nI7\ntp116\nS'.'\ns(I7\nI6\ntp117\nS'.'\ns(I8\nI2\ntp118\nS'.'\ns(I9\nI3\ntp119\nS'.'\ns(I-1\nI11\ntp120\nS'.'\ns(I14\nI2\ntp121\nS'X'\ns(I3\nI1\ntp122\nS'.'\ns(I16\nI13\ntp123\nS'.'\ns(I6\nI16\ntp124\nS'.'\ns(I17\nI8\ntp125\nS'.'\ns(I17\nI-1\ntp126\nS'.'\ns(I8\nI9\ntp127\nS'.'\ns(I9\nI4\ntp128\nS'.'\ns(I10\nI3\ntp129\nS'.'\ns(I4\nI-1\ntp130\nS'.'\ns(I11\nI10\ntp131\nS'.'\ns(I14\nI5\ntp132\nS'.'\ns(I12\nI13\ntp133\nS'.'\ns(I1\nI16\ntp134\nS'.'\ns(I15\nI0\ntp135\nS'.'\ns(I13\nI16\ntp136\nS'.'\ns(I0\nI11\ntp137\nS'.'\ns(I3\nI6\ntp138\nS'.'\ns(I1\nI10\ntp139\nS'.'\ns(I4\nI1\ntp140\nS'.'\ns(I5\nI4\ntp141\nS'.'\ns(I16\nI4\ntp142\nS'.'\ns(I6\nI11\ntp143\nS'.'\ns(I17\nI1\ntp144\nS'.'\ns(I9\nI13\ntp145\nS'.'\ns(I10\nI10\ntp146\nS'.'\ns(I11\nI3\ntp147\nS'.'\ns(I3\nI-1\ntp148\nS'.'\ns(I14\nI12\ntp149\nS'.'\ns(I12\nI4\ntp150\nS'.'\ns(I15\nI9\ntp151\nS'.'\ns(I13\nI9\ntp152\nS'.'\ns(I0\nI2\ntp153\nS'.'\ns(I3\nI15\ntp154\nS'.'\ns(I1\nI3\ntp155\nS'.'\ns(I4\nI8\ntp156\nS'.'\ns(I2\nI8\ntp157\nS'.'\ns(I5\nI13\ntp158\nS'.'\ns(I6\nI2\ntp159\nS'.'\ns(I7\nI11\ntp160\nS'.'\ns(I16\nI17\ntp161\nS'.'\ns(I12\nI3\ntp162\nS'.'\ns(I-1\nI6\ntp163\nS'.'\ns(I13\nI2\ntp164\nS'.'\ns(I1\nI4\ntp165\nS'.'\ns(I2\nI3\ntp166\nS'.'\ns(I12\nI-1\ntp167\nS'.'\ns(I6\nI5\ntp168\nS'.'\ns(I7\nI0\ntp169\nS'.'\ns(I5\nI16\ntp170\nS'.'\ns(I16\nI8\ntp171\nS'.'\ns(I8\nI4\ntp172\nS'.'\ns(I9\nI1\ntp173\nS'.'\ns(I-1\nI9\ntp174\nS'.'\ns(I10\nI6\ntp175\nS'.'\ns(I0\nI16\ntp176\nS'.'\ns(I14\nI0\ntp177\nS'.'\ns(I12\nI16\ntp178\nS'.'\ns(I15\nI5\ntp179\nS'.'\ns(I3\nI3\ntp180\nS'.'\ns(I11\nI-1\ntp181\nS'.'\ns(I4\nI4\ntp182\nS'.'\ns(I16\nI15\ntp183\nS'.'\ns(I17\nI14\ntp184\nS'.'\ns(I8\nI11\ntp185\nS'.'\ns(I9\nI10\ntp186\nS'.'\ns(I10\nI1\ntp187\nS'.'\ns(I8\nI17\ntp188\nS'.'\ns(I11\nI12\ntp189\nS'.'\ns(I14\nI11\ntp190\nS'.'\ns(I12\nI15\ntp191\nS'.'\ns(I15\nI2\ntp192\nS'.'\ns(I13\nI14\ntp193\nS'.'\ns(I0\nI13\ntp194\nS'.'\ns(I3\nI8\ntp195\nS'.'\ns(I1\nI8\ntp196\nS'.'\ns(I4\nI3\ntp197\nS'.'\ns(I2\nI15\ntp198\nS'.'\ns(I5\nI2\ntp199\nS'.'\ns(I16\nI6\ntp200\nS'.'\ns(I6\nI9\ntp201\nS'.'\ns(I17\nI7\ntp202\nS'.'\ns(I7\nI12\ntp203\nS'.'\ns(I10\nI8\ntp204\nS'.'\ns(I11\nI5\ntp205\nS'.'\ns(I12\nI6\ntp206\nS'.'\ns(I15\nI11\ntp207\nS'.'\ns(I13\nI7\ntp208\nS'.'\ns(I0\nI4\ntp209\nS'.'\ns(I1\nI1\ntp210\nS'.'\ns(I4\nI10\ntp211\nS'.'\ns(I2\nI6\ntp212\nS'.'\ns(I5\nI11\ntp213\nS'.'\ns(I6\nI0\ntp214\nS'.'\ns(I4\nI16\ntp215\nS'.'\ns(I7\nI5\ntp216\nS'.'\ns(I6\nI-1\ntp217\nS'.'\ns(I-1\nI4\ntp218\nS'.'\ns(I15\nI16\ntp219\nS'.'\ns(I13\nI0\ntp220\nS'.'\ns(I11\nI16\ntp221\nS'.'\ns(I2\nI1\ntp222\nS'.'\ns(I7\nI2\ntp223\nS'.'\ns(I16\nI10\ntp224\nS'.'\ns(I17\nI11\ntp225\nS'.'\ns(I8\nI6\ntp226\nS'.'\ns(I9\nI7\ntp227\nS'.'\ns(I5\nI-1\ntp228\nS'.'\ns(I2\nI-1\ntp229\nS'.'\ns(I-1\nI15\ntp230\nS'.'\ns(I10\nI4\ntp231\nS'.'\ns(I11\nI9\ntp232\nS'.'\ns(I14\nI6\ntp233\nS'.'\ns(I-1\nI17\ntp234\nS'.'\ns(I15\nI7\ntp235\nS'.'\ns(I0\nI8\ntp236\nS'.'\ns(I3\nI5\ntp237\nS'.'\ns(I4\nI6\ntp238\nS'.'\ns(I5\nI7\ntp239\nS'.'\ns(I16\nI1\ntp240\nS'.'\ns(I17\nI12\ntp241\nS'.'\ns(I7\nI17\ntp242\nS'.'\ns(I8\nI13\ntp243\nS'.'\ns(I9\nI8\ntp244\nS'.'\ns(I10\nI15\ntp245\nS'.'\ns(I11\nI14\ntp246\nS'.'\ns(I14\nI9\ntp247\nS'.'\ns(I12\nI9\ntp248\nS'.'\ns(I15\nI12\ntp249\nS'.'\ns(I13\nI12\ntp250\nS'.'\ns(I0\nI15\ntp251\nS'.'\ns(I14\nI-1\ntp252\nS'.'\ns(I3\nI10\ntp253\nS'.'\ns(I1\nI14\ntp254\nS'.'\ns(I4\nI13\ntp255\nS'.'\ns(I2\nI13\ntp256\nS'.'\ns(I5\nI0\ntp257\nS'.'\ns(I3\nI16\ntp258\nS'.'\ns(I6\nI15\ntp259\nS'.'\ns(I17\nI5\ntp260\nS'.'\ns(I7\nI14\ntp261\nS'.'\ns(I11\nI7\ntp262\nS'.'\ns(I14\nI16\ntp263\nS'.'\ns(I12\nI0\ntp264\nS'.'\ns(I-1\nI3\ntp265\nS'.'\ns(I10\nI16\ntp266\nS'.'\ns(I13\nI5\ntp267\nS'.'\ns(I0\nI6\ntp268\nS'.'\ns(I1\nI7\ntp269\nS'.'\ns(I13\nI-1\ntp270\nS'.'\ns(I2\nI4\ntp271\nS'.'\ns(I5\nI9\ntp272\nS'.'\ns(I6\nI6\ntp273\nS'.'\ns(I7\nI7\ntp274\nS'.'\ns(I17\nI16\ntp275\nS'.'\ns(I8\nI1\ntp276\nS'.'\ns(I-1\nI10\ntp277\nS'.'\ns(I16\nI12\ntp278\nS'.'\ns(I17\nI9\ntp279\nS'.'\ns(I8\nI8\ntp280\nS'.'\ns(I9\nI5\ntp281\nS'.'\ns(I-1\nI13\ntp282\nS'.'\ns(I10\nI2\ntp283\nS'.'\ns(I11\nI11\ntp284\nS'.'\ns(I14\nI4\ntp285\nS'.'\ns(I12\nI12\ntp286\nS'.'\ns(I1\nI17\ntp287\nS'.'\ns(I15\nI1\ntp288\nS'.'\ns(I13\nI17\ntp289\nS'.'\ns(I0\nI10\ntp290\nS'.'\ns(I3\nI7\ntp291\nS'.'\ns(I1\nI11\ntp292\nS'.'\ns(I4\nI0\ntp293\nS'.'\ns(I5\nI5\ntp294\nS'.'\ns(I16\nI3\ntp295\nS'.'\ns(I6\nI10\ntp296\nS'.'\ns(I17\nI2\ntp297\nS'.'\ns(I8\nI15\ntp298\nS'.'\ns(I9\nI14\ntp299\nS'.'\ns(I10\nI13\ntp300\nS'.'\ns(I11\nI0\ntp301\nS'.'\ns(I9\nI16\ntp302\nS'.'\ns(I14\nI15\ntp303\nS'.'\ns(I12\nI11\ntp304\nS'.'\ns(I15\nI14\ntp305\nS'.'\ns(I13\nI10\ntp306\nS'.'\ns(I2\nI17\ntp307\nS'.'\ns(I0\nI1\ntp308\nS'.'\ns(I3\nI12\ntp309\nS'.'\ns(I1\nI12\ntp310\nS'.'\ns(I4\nI15\ntp311\nS'.'\ns(I2\nI11\ntp312\nS'.'\ns(I5\nI14\ntp313\nS'.'\ns(I6\nI13\ntp314\nS'.'\ns(I7\nI8\ntp315\nS'.'\ns(I16\nI16\ntp316\nS'.'\ns(I7\nI-1\ntp317\nS'.'\ns(I12\nI2\ntp318\nS'.'\ns(I-1\nI1\ntp319\nS'.'\ns(I13\nI3\ntp320\nS'.'\ns(I1\nI5\ntp321\nS'.'\ns(I-1\nI-1\ntp322\nS'.'\ns(I6\nI4\ntp323\nS'.'\ns(I7\nI1\ntp324\nS'.'\ns(I5\nI17\ntp325\nS'.'\ns(I8\nI3\ntp326\nS'.'\ns(I9\nI2\ntp327\nS'.'\ns(I-1\nI8\ntp328\nS'.'\ns(I14\nI3\ntp329\nS'.'\ns(I0\nI-1\ntp330\nS'.'\ns(I3\nI0\ntp331\nS'.'\ns(I16\nI14\ntp332\nS'.'\ns(I6\nI17\ntp333\nS'.'\ns(I17\nI15\ntp334\nS'.'\ns(I8\nI10\ntp335\nS'.'\ns(I9\nI11\ntp336\nS'.'\ns(I10\nI0\ntp337\nS'.'\ns(I8\nI16\ntp338\nS'.'\ns(I11\nI13\ntp339\nS'.'\ns(I14\nI10\ntp340\nS'.'\ns(I12\nI14\ntp341\nS'.'\ns(I15\nI3\ntp342\nS'.'\ns(I15\nI-1\ntp343\nS'.'\ns(I13\nI15\ntp344\nS'.'\ns(I0\nI12\ntp345\nS'.'\ns(I3\nI9\ntp346\nS'.'\ns(I1\nI9\ntp347\nS'.'\ns(I4\nI2\ntp348\nS'.'\ns(I2\nI14\ntp349\nS'X'\ns(I5\nI3\ntp350\nS'.'\ns(I16\nI5\ntp351\nS'.'\ns(I6\nI8\ntp352\nS'.'\ns(I17\nI0\ntp353\nS'.'\ns(I7\nI13\ntp354\nS'.'\ns(I9\nI12\ntp355\nS'.'\ns(I10\nI11\ntp356\nS'.'\ns(I11\nI2\ntp357\nS'.'\ns(I14\nI13\ntp358\nS'.'\ns(I12\nI5\ntp359\nS'.'\ns(I15\nI8\ntp360\nS'.'\ns(I13\nI8\ntp361\nS'.'\ns(I0\nI3\ntp362\nS'.'\ns(I3\nI14\ntp363\nS'.'\ns(I1\nI2\ntp364\nS'.'\ns(I4\nI9\ntp365\nS'.'\ns(I2\nI9\ntp366\nS'.'\ns(I5\nI12\ntp367\nS'.'\ns(I6\nI3\ntp368\nS'.'\ns(I8\nI-1\ntp369\nS'.'\ns(I7\nI10\ntp370\nS'.'\ns(I-1\nI7\ntp371\nS'.'\ns(I15\nI17\ntp372\nS'.'\ns(I13\nI1\ntp373\nS'.'\ns(I11\nI17\ntp374\nS'.'\ns(I2\nI0\ntp375\nS'.'\nsI0\nI1\nI250\nI0\ntp376\nsg5\nS'Diagonal hoshi'\np377\nsS'file'\np378\nS''\nsa(dp379\ng10\n(tsg11\nI1\nsg12\n(((I10\nI0\nt(I18\nI18\nttp380\n(dp381\n(I6\nI9\ntp382\nS'.'\ns(I11\nI11\ntp383\nS'.'\ns(I10\nI17\ntp384\nS'.'\ns(I7\nI12\ntp385\nS'.'\ns(I12\nI12\ntp386\nS'.'\ns(I1\nI17\ntp387\nS'.'\ns(I13\nI17\ntp388\nS'.'\ns(I14\nI17\ntp389\nS'.'\ns(I0\nI10\ntp390\nS'.'\ns(I1\nI11\ntp391\nS'.'\ns(I-1\nI14\ntp392\nS'.'\ns(I6\nI10\ntp393\nS'.'\ns(I0\nI17\ntp394\nS'.'\ns(I15\nI11\ntp395\nS'.'\ns(I12\nI17\ntp396\nS'.'\ns(I-1\nI16\ntp397\nS'.'\ns(I8\nI15\ntp398\nS'.'\ns(I4\nI10\ntp399\nS'.'\ns(I9\nI14\ntp400\nS'.'\ns(I16\nI15\ntp401\nS'.'\ns(I5\nI11\ntp402\nS'.'\ns(I10\nI13\ntp403\nS'.'\ns(I4\nI16\ntp404\nS'.'\ns(I-1\nI11\ntp405\nS'.'\ns(I9\nI16\ntp406\nS'.'\ns(I14\nI15\ntp407\nS'.'\ns(I12\nI11\ntp408\nS'.'\ns(I17\nI13\ntp409\nS'.'\ns(I15\nI14\ntp410\nS'.'\ns(I13\nI10\ntp411\nS'.'\ns(I2\nI17\ntp412\nS'.'\ns(I3\nI12\ntp413\nS'.'\ns(I1\nI12\ntp414\nS'.'\ns(I8\nI12\ntp415\nS'.'\ns(I4\nI15\ntp416\nS'.'\ns(I2\nI11\ntp417\nS'.'\ns(I9\nI9\ntp418\nS'.'\ns(I5\nI14\ntp419\nS'.'\ns(I10\nI14\ntp420\nS'.'\ns(I6\nI13\ntp421\nS'.'\ns(I11\nI15\ntp422\nS'.'\ns(I15\nI16\ntp423\nS'.'\ns(I6\nI16\ntp424\nS'.'\ns(I11\nI16\ntp425\nS'.'\ns(I15\nI13\ntp426\nS'.'\ns(I13\nI13\ntp427\nS'.'\ns(I0\nI14\ntp428\nS'.'\ns(I3\nI11\ntp429\nS'.'\ns(I1\nI15\ntp430\nS'.'\ns(I8\nI9\ntp431\nS'.'\ns(I4\nI12\ntp432\nS'.'\ns(I2\nI12\ntp433\nS'.'\ns(I16\nI14\ntp434\nS'.'\ns(I3\nI17\ntp435\nS'.'\ns(I14\nI9\ntp436\nS'.'\ns(I6\nI14\ntp437\nS'.'\ns(I11\nI10\ntp438\nS'.'\ns(I7\nI15\ntp439\nS'.'\ns(I12\nI13\ntp440\nS'.'\ns(I1\nI16\ntp441\nS'.'\ns(I17\nI11\ntp442\nS'.'\ns(I13\nI16\ntp443\nS'.'\ns(I0\nI11\ntp444\nS'.'\ns(I16\nI9\ntp445\nS'.'\ns(I1\nI10\ntp446\nS'.'\ns(I10\nI9\ntp447\nS'.'\ns(I16\nI17\ntp448\nS'.'\ns(I-1\nI15\ntp449\nS'.'\ns(I6\nI11\ntp450\nS'.'\ns(I5\nI17\ntp451\nS'.'\ns(I11\nI9\ntp452\nS'.'\ns(I15\nI10\ntp453\nS'.'\ns(I-1\nI17\ntp454\nS'.'\ns(I4\nI11\ntp455\nS'.'\ns(I9\nI13\ntp456\nS'.'\ns(I5\nI10\ntp457\nS'.'\ns(I10\nI10\ntp458\nS'.'\ns(I16\nI13\ntp459\nS'.'\ns(I4\nI17\ntp460\nS'.'\ns(I14\nI12\ntp461\nS'.'\ns(I17\nI12\ntp462\nS'.'\ns(I7\nI17\ntp463\nS'.'\ns(I13\nI9\ntp464\nS'.'\ns(I17\nI17\ntp465\nS'.'\ns(I3\nI15\ntp466\nS'.'\ns(I8\nI13\ntp467\nS'.'\ns(I5\nI13\ntp468\nS'.'\ns(I10\nI15\ntp469\nS'.'\ns(I16\nI16\ntp470\nS'.'\ns(I11\nI14\ntp471\nS'.'\ns(I7\nI11\ntp472\nS'.'\ns(I6\nI17\ntp473\nS'.'\ns(I12\nI9\ntp474\nS'.'\ns(I17\nI15\ntp475\nS'.'\ns(I15\nI12\ntp476\nS'.'\ns(I13\nI12\ntp477\nS'.'\ns(I0\nI15\ntp478\nS'.'\ns(I3\nI10\ntp479\nS'.'\ns(I1\nI14\ntp480\nS'.'\ns(I8\nI10\ntp481\nS'.'\ns(I4\nI13\ntp482\nS'.'\ns(I2\nI13\ntp483\nS'.'\ns(I9\nI11\ntp484\nS'.'\ns(I3\nI16\ntp485\nS'.'\ns(I8\nI16\ntp486\nS'.'\ns(I6\nI15\ntp487\nS'.'\ns(I11\nI13\ntp488\nS'.'\ns(I16\nI10\ntp489\nS'.'\ns(I7\nI14\ntp490\nS'.'\ns(I14\nI10\ntp491\nS'.'\ns(I12\nI14\ntp492\nS'.'\ns(I17\nI10\ntp493\nS'.'\ns(I13\nI15\ntp494\nS'.'\ns(I0\nI12\ntp495\nS'.'\ns(I3\nI9\ntp496\nS'.'\ns(I1\nI9\ntp497\nS'.'\ns(I2\nI14\ntp498\nS'X'\ns(I-1\nI12\ntp499\nS'.'\ns(I14\nI16\ntp500\nS'.'\ns(I5\nI16\ntp501\nS'.'\ns(I10\nI16\ntp502\nS'.'\ns(I7\nI13\ntp503\nS'.'\ns(I15\nI17\ntp504\nS'.'\ns(I0\nI9\ntp505\nS'.'\ns(I9\nI12\ntp506\nS'.'\ns(I5\nI9\ntp507\nS'.'\ns(I10\nI11\ntp508\nS'.'\ns(I-1\nI9\ntp509\nS'.'\ns(I16\nI11\ntp510\nS'.'\ns(I14\nI13\ntp511\nS'.'\ns(I0\nI16\ntp512\nS'.'\ns(I7\nI16\ntp513\nS'.'\ns(I12\nI16\ntp514\nS'.'\ns(I17\nI16\ntp515\nS'.'\ns(I3\nI14\ntp516\nS'.'\ns(I8\nI14\ntp517\nS'X'\ns(I4\nI9\ntp518\nS'.'\ns(I2\nI9\ntp519\nS'.'\ns(I9\nI15\ntp520\nS'.'\ns(I5\nI12\ntp521\nS'.'\ns(I10\nI12\ntp522\nS'.'\ns(I-1\nI10\ntp523\nS'.'\ns(I9\nI17\ntp524\nS'.'\ns(I7\nI10\ntp525\nS'.'\ns(I14\nI14\ntp526\nS'X'\ns(I12\nI10\ntp527\nS'.'\ns(I17\nI14\ntp528\nS'.'\ns(I15\nI15\ntp529\nS'.'\ns(I13\nI11\ntp530\nS'.'\ns(I16\nI12\ntp531\nS'.'\ns(I2\nI16\ntp532\nS'.'\ns(I3\nI13\ntp533\nS'.'\ns(I1\nI13\ntp534\nS'.'\ns(I8\nI11\ntp535\nS'.'\ns(I15\nI9\ntp536\nS'.'\ns(I4\nI14\ntp537\nS'.'\ns(I2\nI10\ntp538\nS'.'\ns(I9\nI10\ntp539\nS'.'\ns(I5\nI15\ntp540\nS'.'\ns(I8\nI17\ntp541\nS'.'\ns(I6\nI12\ntp542\nS'.'\ns(I11\nI12\ntp543\nS'.'\ns(I7\nI9\ntp544\nS'.'\ns(I14\nI11\ntp545\nS'.'\ns(I12\nI15\ntp546\nS'.'\ns(I11\nI17\ntp547\nS'.'\ns(I17\nI9\ntp548\nS'.'\ns(I13\nI14\ntp549\nS'.'\ns(I0\nI13\ntp550\nS'.'\ns(I2\nI15\ntp551\nS'.'\ns(I-1\nI13\ntp552\nS'.'\nsI0\nI0\nI250\nI0\ntp553\nsg5\nS'San ren sei'\np554\nsg378\nS''\nsasa(dp555\ng3\n(lp556\nsg5\nS'Players'\np557\nsg7\n(lp558\n(dp559\ng10\n(S''\nS''\nS'Cho U'\nS''\nS''\nS''\nS''\nI0\ntp560\nsg11\nI1\nsg12\n(tsg5\nS'Cho U'\np561\nsg378\nS''\nsa(dp562\ng10\n(S''\nS''\nS'Go Seigen'\nS''\nS''\nS''\nS''\nI0\ntp563\nsg11\nI1\nsg12\n(tsg5\nS'Go Seigen'\np564\nsg378\nS''\nsasa." try: file = open(os.path.join(self.path, 'menus.def'), 'rb') self.customMenuList = pickle.load(file) file.close() except IOError: if alternativePath: try: file = open(os.path.join(alternativePath, 'menus.def'), 'rb') self.customMenuList = pickle.load(file) file.close() except IOError: self.customMenuList = pickle.loads(fallback) else: self.customMenuList = pickle.loads(fallback) self.noOfMenus = len(self.customMenuList) # build menus self.customMenuCommands = [] self.mmIndex = 3 self.customMenuList.sort(key=lambda x: x['name']) for item in self.customMenuList: m = Menu(self.mainMenu) self.mainMenu.insert_cascade(self.mmIndex, menu=m, label=item['name']) self.mmIndex += 1 self.addMenu(item['subm'], m) item['entries'].sort(key=lambda x: x['name']) for e in item['entries']: m.add_command(label=e['name'], command=lambda self=self, i=len( self.customMenuCommands): self.doCommand(i)) self.customMenuCommands.append( (e['file'], e['gisearch'], e['psearch'], e['reset'])) def addMenu(self, menuList, menu): menuList.sort(key=lambda x: x['name']) for item in menuList: m = Menu(menu) menu.add_cascade(label=item['name'], menu=m) self.addMenu(item['subm'], m) for e in item['entries']: m.add_command(label=e['name'], command=lambda self=self, i=len( self.customMenuCommands): self.doCommand(i)) self.customMenuCommands.append( (e['file'], e['gisearch'], e['psearch'], e['reset'])) def removeMenus(self): for i in range(self.noOfMenus): self.mainMenu.delete( 3) # The first custom menu is the 3rd overall menu def doCommand(self, i): if self.customMenuCommands[i][0]: try: webbrowser.open(self.customMenuCommands[i][0], new=1) except: showwarning(_('Error'), _('Failed to open the web browser.')) if self.customMenuCommands[i][3]: # reset game list self.master.reset() if self.customMenuCommands[i][2]: # prepare pattern search self.displayPattern(self.customMenuCommands[i][2]) if self.customMenuCommands[i][1]: # do game info search self.displayGI(self.customMenuCommands[i][1]) self.master.doGISearch() if self.customMenuCommands[i][2]: # do pattern search self.master.search() def displayPattern(self, data): if not data: return if self.master.dataWindow.filelist.list.curselection(): index = int(self.master.dataWindow.filelist.list.curselection()[0]) if self.master.filelist[index][1]: self.master.newFile() else: self.master.newFile() self.master.start() sel = data[0] if sel == ((0, 0), (18, 18)): # TODO boardsize self.master.board.delete('selection') self.master.board.selection = sel else: self.master.board.setSelection(sel[0], sel[1]) self.master.board.changed.set(1) self.master.fixedAnchorVar.set(data[2]) self.master.fixedColorVar.set(data[3]) self.master.moveLimit.set(data[4]) self.master.nextMoveVar.set(data[5]) d = data[1] for ii in range(sel[0][1], sel[1][1] + 1): for jj in range(sel[0][0], sel[1][0] + 1): if d[(ii - 1, jj - 1)] == 'X': nM = 'AB' elif d[(ii - 1, jj - 1)] == 'O': nM = 'AW' elif d[(ii - 1, jj - 1)] in ['x', 'o', '*']: wc_type = d[(ii - 1, jj - 1)] x1, x2, y1, y2 = self.master.board.getPixelCoord((jj, ii), 1) self.master.board.wildcards[(jj, ii)] = ( self.master.board.create_oval(x1 + 4, x2 + 4, y1 - 4, y2 - 4, fill={ '*': 'green', 'x': 'black', 'o': 'white' }[wc_type], tags=('wildcard', 'non-bg')), wc_type) continue else: continue pos = chr(jj + ord('a')) + chr(ii + ord('a')) try: if ('AB' in self.master.cursor.currentNode() or 'AW' in self.master.cursor.currentNode() or 'AE' in self.master.cursor.currentNode()): if not nM in self.master.cursor.currentNode(): self.master.cursor.currentNode()[nM] = [] if not pos in self.master.cursor.currentNode()[nM]: self.master.cursor.currentNode( ).add_property_value(nM, [ pos, ]) color = 'black' if nM == 'AB' else 'white' if not self.master.board.play((jj, ii), color): self.master.board.undostack_append_pass() self.master.board.currentColor = self.master.modeVar.get( ) if nM == 'AB': self.master.capB = self.master.capB + len( self.master.board.undostack_top_captures()) if nM == 'AW': self.master.capW = self.master.capW + len( self.master.board.undostack_top_captures()) self.master.capVar.set( _('Cap - B: {0}, W: {1}').format( self.master.capB, self.master.capW)) else: s = ';' + nM + '[' + pos + ']' self.master.cursor.add(s) c = self.master.cursor.currentNode() self.master.board.delMarks() self.master.board.delLabels() self.master.moveno.set( '%d' % (int(self.master.moveno.get()) + 1)) self.master.displayNode(c) if nM == 'AB': self.master.capB = self.master.capB + len( self.master.board.undostack_top_captures()) if nM == 'AW': self.master.capW = self.master.capW + len( self.master.board.undostack_top_captures()) self.master.capVar.set( _('Cap - B: {0}, W: {1}').format( self.master.capB, self.master.capW)) except SGFError: showwarning(_('Error'), _('SGF Error')) self.master.board.currentColor = self.master.modeVar.get()[:5] def c_buildList(self, menuList, level): for i in range(len(menuList)): item = menuList[i] self.list.insert('end', '-' * level + ' ' + item['name']) self.correspEntry.append([1, item, '-' * level + ' ', menuList, i]) # 1 = submenu self.c_buildList(item['subm'], level + 1) for j in range(len(item['entries'])): entry = item['entries'][j] self.list.insert('end', '-' * level + '* ' + entry['name']) self.correspEntry.append( [2, entry, '-' * level + '* ', item['entries'], j]) # 2 = entry def count(self, i): res = len(i['entries']) + 1 for j in i['subm']: res += self.count(j) return res def displayGI(self, data): if not data: return varList = [ self.master.pwVar, self.master.pbVar, self.master.pVar, self.master.evVar, self.master.frVar, self.master.toVar, self.master.awVar, self.master.referencedVar ] for i in range(len(varList)): varList[i].set(data[i]) def c_addEntry(self): if not self.current: return index = int(self.current[0]) if self.correspEntry[index][0] != 1: return # add entry to currently selected submenu, named 'New' entry = { 'name': _('New'), 'file': '', 'gisearch': (), 'psearch': (), 'reset': 1 } self.correspEntry[index][1]['entries'].append(entry) insertIndex = index + self.count(self.correspEntry[index][1]) - 1 self.correspEntry[insertIndex:insertIndex] = [[ 2, entry, self.correspEntry[index][2][:-1] + '* ', self.correspEntry[index][1]['entries'], len(self.correspEntry[index][1]['entries']) - 1 ]] self.list.insert(insertIndex, self.correspEntry[index][2][:-1] + '* ' + _('New')) self.list.list.select_clear(self.list.list.curselection()) self.list.list.select_set(insertIndex) def c_addSubmenu(self): if not self.current: return index = int(self.current[0]) if self.correspEntry[index][0] == 2: return # add submenu to currently selected submenu, named 'New' submenu = {'name': _('New'), 'entries': [], 'subm': []} if self.correspEntry[index][0] == 0: self.customMenuList.append(submenu) insertIndex = self.list.list.index('end') prefix = '- ' self.correspEntry.append([ 1, submenu, prefix, self.customMenuList, len(self.customMenuList) - 1 ]) else: self.correspEntry[index][1]['subm'].append(submenu) insertIndex = index + self.count( self.correspEntry[index][1]) - len( self.correspEntry[index][1]['entries']) - 1 prefix = self.correspEntry[index][2][:-1] + '- ' self.correspEntry[insertIndex:insertIndex] = [[ 1, submenu, prefix, self.correspEntry[index][1]['subm'], len(self.correspEntry[index][1]['subm']) - 1 ]] self.list.insert(insertIndex, prefix + _('New')) self.list.list.select_clear(self.list.list.curselection()) self.list.list.select_set(insertIndex) def c_delete(self): if not self.current: return index = int(self.current[0]) if self.correspEntry[index][0] == 0: return if self.correspEntry[index][0] == 1: n = self.count(self.correspEntry[index][1]) elif self.correspEntry[index][0] == 2: n = 1 del self.correspEntry[index][3][self.correspEntry[index][4]] del self.correspEntry[index:index + n] self.correspEntry = [[0, '', '', None, None]] self.list.delete(1, 'end') self.c_buildList(self.customMenuList, 1) if self.list.list.index('end') > index: self.list.list.select_set(index) else: self.list.list.select_set('end') self.current = None def c_addPattern(self): if not self.current: return index = int(self.current[0]) if self.correspEntry[index][0] != 2: return d = {} if self.master.board.selection[0][0] > self.master.board.selection[1][ 0] or self.master.board.selection[0][ 1] > self.master.board.selection[1][1]: self.master.board.selection = ((1, 1), (19, 19)) # TODO boardsize sel = self.master.board.selection # copy this because the selection on the board may # be changed by the user although the search is not yet # finished for i in range(sel[0][1], sel[1][1] + 1): for j in range(sel[0][0], sel[1][0] + 1): if self.master.board.getStatus(j, i) == 'W': d[(i - 1, j - 1)] = 'O' elif self.master.board.getStatus(j, i) == 'B': d[(i - 1, j - 1)] = 'X' else: d[(i - 1, j - 1)] = '.' if (j, i) in self.master.board.wildcards: d[(i - 1, j - 1)] = self.master.board.wildcards[(j, i)][1] self.correspEntry[index][1]['psearch'] = ( sel, d, self.master.fixedAnchorVar.get(), self.master.fixedColorVar.get(), self.master.moveLimit.get(), self.master.nextMoveVar.get()) showinfo(_('Add pattern'), _('Successfully stored pattern.')) self.window.lift() def c_addGI(self): if not self.current: return index = int(self.current[0]) if self.correspEntry[index][0] != 2: return self.correspEntry[index][1]['gisearch'] = ( self.master.pwVar.get(), self.master.pbVar.get(), self.master.pVar.get(), self.master.evVar.get(), self.master.frVar.get(), self.master.toVar.get(), self.master.awVar.get(), self.master.referencedVar.get()) showinfo(_('Add game info'), _('Successfully stored game info.')) self.window.lift() def c_OK(self): if self.current: index = int(self.current[0]) if self.correspEntry[index][0] == 1: entry = self.correspEntry[index][1] entry['name'] = self.nameCurrent.get() if self.correspEntry[index][0] == 2: entry = self.correspEntry[index][1] entry['name'] = self.nameCurrent.get() entry['file'] = self.htmlCurrent.get() entry['reset'] = self.resetVar.get() self.removeMenus() self.buildMenus(0) # save menus ... try: file = open(os.path.join(self.path, 'menus.def'), 'wb') pickle.dump(self.customMenuList, file) file.close() except IOError: showwarning(_('I/O Error'), _('Could not save custom menu file.')) self.window.destroy() def c_cancel(self): self.removeMenus() self.buildMenus() self.window.destroy() def c_setName(self, event=None): index = int(self.current[0]) self.list.delete(index) self.correspEntry[index][1]['name'] = self.nameCurrent.get() self.list.insert( index, self.correspEntry[index][2] + self.correspEntry[index][1]['name']) # self.htmlE.focus() # self.list.list.select_set(index) def c_browse(self, event=None): if not self.current: return index = int(self.current[0]) if self.correspEntry[index][0] != 2: return filename = tkFileDialog.askopenfilename(filetypes=[ (_('HTML files'), ('*.html', '*.htm')), (_('All files'), '*') ], initialdir=self.htmlpath) self.window.tkraise() if filename: filename = os.path.normpath(filename) self.htmlpath = os.path.split(filename)[0] self.correspEntry[index][1]['file'] = filename self.htmlCurrent.set(filename) def pollList(self): now = self.list.list.curselection() if not now and self.current: self.list.list.select_set(self.current) elif now != self.current: if self.current: index = int(self.current[0]) if self.correspEntry[index][0] == 1: entry = self.correspEntry[index][1] self.c_setName(None) self.list.list.select_set(now) entry['name'] = self.nameCurrent.get() if self.correspEntry[index][0] == 2: entry = self.correspEntry[index][1] self.c_setName(None) self.list.list.select_set(now) entry['file'] = self.htmlCurrent.get() entry['reset'] = self.resetVar.get() self.nameCurrent.set('') self.htmlCurrent.set('') self.resetVar.set(0) for widget in [ self.addEntryB, self.addSubmenuB, self.deleteB, self.nameE, self.htmlE, self.browseB, self.patternB, self.giB, self.resetB ]: widget.config(state=DISABLED) self.nameE.config(takefocus=0) self.htmlE.config(takefocus=0) if now: self.list.list.see(now) index = int(now[0]) if self.correspEntry[index][0] == 0: for widget in [self.addSubmenuB]: widget.config(state=NORMAL) elif self.correspEntry[index][0] == 1: for widget in [ self.addEntryB, self.addSubmenuB, self.deleteB, self.nameE ]: widget.config(state=NORMAL) self.nameE.config(takefocus=1) self.nameCurrent.set(self.correspEntry[index][1]['name']) elif self.correspEntry[index][0] == 2: for widget in [ self.deleteB, self.nameE, self.htmlE, self.browseB, self.patternB, self.giB, self.resetB ]: widget.config(state=NORMAL) self.nameE.config(takefocus=1) self.htmlE.config(takefocus=1) self.nameCurrent.set(self.correspEntry[index][1]['name']) self.htmlCurrent.set(self.correspEntry[index][1]['file']) self.resetVar.set(self.correspEntry[index][1]['reset']) self.displayPattern(self.correspEntry[index][1]['psearch']) self.displayGI(self.correspEntry[index][1]['gisearch']) self.current = now self.window.after(250, self.pollList) def change(self): if self.windowOpen: return else: self.windowOpen = 1 self.window = Toplevel() self.window.title(_('Change custom menus')) self.window.protocol('WM_DELETE_WINDOW', self.c_cancel) # scrolled list with all submenus, entries self.list = v.ScrolledList(self.window, width=35, font='Courier') self.list.pack() self.current = None self.correspEntry = [[0, '', '', None, None]] self.list.insert('end', '*') self.c_buildList(self.customMenuList, 1) # buttons ... for currently selected entry f = Frame(self.window) self.addEntryB = Button(f, text=_('Add entry'), command=self.c_addEntry) self.addSubmenuB = Button(f, text=_('Add submenu'), command=self.c_addSubmenu) self.deleteB = Button(f, text=_('Delete'), command=self.c_delete) self.addEntryB.pack(side=LEFT, anchor=W) self.addSubmenuB.pack(side=LEFT, anchor=W) self.deleteB.pack(side=LEFT, anchor=W) f.pack(anchor=W) Frame(self.window, background='black', height=1, width=100).pack(expand=YES, fill=X, pady=10) Label(self.window, text=_('Name:')).pack(anchor=W) self.nameCurrent = StringVar() self.nameE = Entry(self.window, width=40, textvariable=self.nameCurrent, takefocus=1) self.nameE.bind('<Return>', self.c_setName) self.nameE.bind('<Tab>', self.c_setName) self.nameE.pack(anchor=W) Frame(self.window, height=15, width=200).pack() Label(self.window, text=_('HTML file:')).pack(anchor=W) f = Frame(self.window) f.pack(anchor=W) self.htmlCurrent = StringVar() self.htmlE = Entry(f, width=35, textvariable=self.htmlCurrent, takefocus=1) self.htmlE.pack(side=LEFT) self.browseB = Button(f, text=_('Browse ...'), command=self.c_browse, height=1) self.browseB.pack(side=RIGHT) Frame(self.window, height=15, width=200).pack() f = Frame(self.window) self.patternB = Button(f, text=_('Add pattern info'), command=self.c_addPattern) self.patternB.pack(side=LEFT) self.giB = Button(f, text=_('Add game info'), command=self.c_addGI) self.giB.pack(side=LEFT) self.resetVar = IntVar() self.resetB = Checkbutton(f, text=_('Reset game list'), highlightthickness=0, variable=self.resetVar) self.resetB.pack(side=LEFT) f.pack(anchor=W) # OK, cancel buttons Frame(self.window, background='black', height=1, width=100).pack(expand=YES, fill=X, pady=10) f = Frame(self.window) f.pack(side=BOTTOM, anchor=E) Button(f, text=_('Cancel'), command=self.c_cancel).pack(side=RIGHT, anchor=E) Button(f, text=_('OK'), command=self.c_OK).pack(side=RIGHT, anchor=E) self.list.list.select_set(0) self.pollList() self.window.update_idletasks() self.window.focus() # self.window.grab_set() self.window.wait_window() del self.window self.windowOpen = 0
class MLNQueryGUI(object): def __init__(self, master, gconf, directory=None): self.master = master self.initialized = False self.master.bind('<Return>', self.infer) self.master.bind('<Escape>', lambda a: self.master.quit()) self.master.protocol('WM_DELETE_WINDOW', self.quit) self.dir = os.path.abspath(ifnone(directory, ifnone(gconf['prev_query_path'], os.getcwd()))) self.frame = Frame(master) self.frame.pack(fill=BOTH, expand=1) self.frame.columnconfigure(1, weight=1) row = 0 # pracmln project options Label(self.frame, text='PRACMLN Project: ').grid(row=row, column=0, sticky='ES') project_container = Frame(self.frame) project_container.grid(row=row, column=1, sticky="NEWS") # new proj file self.btn_newproj = Button(project_container, text='New Project...', command=self.new_project) self.btn_newproj.grid(row=0, column=1, sticky="WS") # open proj file self.btn_openproj = Button(project_container, text='Open Project...', command=self.ask_load_project) self.btn_openproj.grid(row=0, column=2, sticky="WS") # save proj file self.btn_updateproj = Button(project_container, text='Save Project...', command=self.noask_save_project) self.btn_updateproj.grid(row=0, column=3, sticky="WS") # save proj file as... self.btn_saveproj = Button(project_container, text='Save Project as...', command=self.ask_save_project) self.btn_saveproj.grid(row=0, column=4, sticky="WS") # grammar selection row += 1 Label(self.frame, text='Grammar: ').grid(row=row, column=0, sticky='E') grammars = ['StandardGrammar', 'PRACGrammar'] self.selected_grammar = StringVar() self.selected_grammar.trace('w', self.settings_setdirty) l = OptionMenu(*(self.frame, self.selected_grammar) + tuple(grammars)) l.grid(row=row, column=1, sticky='NWE') # logic selection row += 1 Label(self.frame, text='Logic: ').grid(row=row, column=0, sticky='E') logics = ['FirstOrderLogic', 'FuzzyLogic'] self.selected_logic = StringVar() self.selected_logic.trace('w', self.settings_setdirty) l = OptionMenu(*(self.frame, self.selected_logic) + tuple(logics)) l.grid(row=row, column=1, sticky='NWE') # mln section row += 1 Label(self.frame, text="MLN: ").grid(row=row, column=0, sticky='NE') self.mln_container = FileEditBar(self.frame, directory=self.dir, filesettings={'extension': '.mln', 'ftypes': [('MLN files', '.mln')]}, defaultname='*unknown{}', importhook=self.import_mln, deletehook=self.delete_mln, projecthook=self.save_proj, filecontenthook=self.mlnfilecontent, fileslisthook=self.mlnfiles, updatehook=self.update_mln, onchangehook=self.project_setdirty) self.mln_container.editor.bind("<FocusIn>", self._got_focus) self.mln_container.grid(row=row, column=1, sticky="NEWS") self.mln_container.columnconfigure(1, weight=2) self.frame.rowconfigure(row, weight=1) row += 1 self.use_emln = IntVar() self.use_emln.set(0) self.cb_use_emln = Checkbutton(self.frame, text="use model extension", variable=self.use_emln, command=self.onchange_use_emln) self.cb_use_emln.grid(row=row, column=1, sticky="W") # mln extension section row += 1 self.emlncontainerrow = row self.emln_label = Label(self.frame, text="EMLN: ") self.emln_label.grid(row=self.emlncontainerrow, column=0, sticky='NE') self.emln_container = FileEditBar(self.frame, directory=self.dir, filesettings={'extension': '.emln', 'ftypes': [('MLN extension files','.emln')]}, defaultname='*unknown{}', importhook=self.import_emln, deletehook=self.delete_emln, projecthook=self.save_proj, filecontenthook=self.emlnfilecontent, fileslisthook=self.emlnfiles, updatehook=self.update_emln, onchangehook=self.project_setdirty) self.emln_container.grid(row=self.emlncontainerrow, column=1, sticky="NEWS") self.emln_container.editor.bind("<FocusIn>", self._got_focus) self.emln_container.columnconfigure(1, weight=2) self.onchange_use_emln(dirty=False) self.frame.rowconfigure(row, weight=1) # db section row += 1 Label(self.frame, text="Evidence: ").grid(row=row, column=0, sticky='NE') self.db_container = FileEditBar(self.frame, directory=self.dir, filesettings={'extension': '.db', 'ftypes': [('Database files', '.db')]}, defaultname='*unknown{}', importhook=self.import_db, deletehook=self.delete_db, projecthook=self.save_proj, filecontenthook=self.dbfilecontent, fileslisthook=self.dbfiles, updatehook=self.update_db, onchangehook=self.project_setdirty) self.db_container.grid(row=row, column=1, sticky="NEWS") self.db_container.editor.bind("<FocusIn>", self._got_focus) self.db_container.columnconfigure(1, weight=2) self.frame.rowconfigure(row, weight=1) # inference method selection row += 1 self.list_methods_row = row Label(self.frame, text="Method: ").grid(row=row, column=0, sticky=E) self.selected_method = StringVar() self.selected_method.trace('w', self.select_method) methodnames = sorted(InferenceMethods.names()) self.list_methods = OptionMenu(*(self.frame, self.selected_method) + tuple(methodnames)) self.list_methods.grid(row=self.list_methods_row, column=1, sticky="NWE") # options row += 1 option_container = Frame(self.frame) option_container.grid(row=row, column=1, sticky="NEWS") # Multiprocessing self.multicore = IntVar() self.cb_multicore = Checkbutton(option_container, text="Use all CPUs", variable=self.multicore, command=self.settings_setdirty) self.cb_multicore.grid(row=0, column=2, sticky=W) # profiling self.profile = IntVar() self.cb_profile = Checkbutton(option_container, text='Use Profiler', variable=self.profile, command=self.settings_setdirty) self.cb_profile.grid(row=0, column=3, sticky=W) # verbose self.verbose = IntVar() self.cb_verbose = Checkbutton(option_container, text='verbose', variable=self.verbose, command=self.settings_setdirty) self.cb_verbose.grid(row=0, column=4, sticky=W) # options self.ignore_unknown_preds = IntVar() self.cb_ignore_unknown_preds = Checkbutton(option_container, text='ignore unkown predicates', variable=self.ignore_unknown_preds, command=self.settings_setdirty) self.cb_ignore_unknown_preds.grid(row=0, column=5, sticky="W") # queries row += 1 Label(self.frame, text="Queries: ").grid(row=row, column=0, sticky=E) self.query = StringVar() self.query.trace('w', self.settings_setdirty) Entry(self.frame, textvariable=self.query).grid(row=row, column=1, sticky="NEW") # additional parameters row += 1 Label(self.frame, text="Add. params: ").grid(row=row, column=0, sticky="NE") self.params = StringVar() self.params.trace('w', self.settings_setdirty) self.entry_params = Entry(self.frame, textvariable=self.params) self.entry_params.grid(row=row, column=1, sticky="NEW") # closed-world predicates row += 1 Label(self.frame, text="CW preds: ").grid(row=row, column=0, sticky="E") cw_container = Frame(self.frame) cw_container.grid(row=row, column=1, sticky='NEWS') cw_container.columnconfigure(0, weight=1) self.cwPreds = StringVar() self.cwPreds.trace('w', self.settings_setdirty) self.entry_cw = Entry(cw_container, textvariable=self.cwPreds) self.entry_cw.grid(row=0, column=0, sticky="NEWS") self.closed_world = IntVar() self.cb_closed_world = Checkbutton(cw_container, text="CW Assumption", variable=self.closed_world, command=self.onchange_cw) self.cb_closed_world.grid(row=0, column=1, sticky='W') # output filename row += 1 output_cont = Frame(self.frame) output_cont.grid(row=row, column=1, sticky='NEWS') output_cont.columnconfigure(0, weight=1) # - filename Label(self.frame, text="Output: ").grid(row=row, column=0, sticky="NE") self.output_filename = StringVar() self.entry_output_filename = Entry(output_cont, textvariable=self.output_filename) self.entry_output_filename.grid(row=0, column=0, sticky="NEW") # - save option self.save = IntVar() self.cb_save = Checkbutton(output_cont, text="save", variable=self.save) self.cb_save.grid(row=0, column=1, sticky=W) # start button row += 1 start_button = Button(self.frame, text=">> Start Inference <<", command=self.infer) start_button.grid(row=row, column=1, sticky="NEW") self.settings_dirty = IntVar() self.project_dirty = IntVar() self.gconf = gconf self.project = None self.project_dir = os.path.abspath(ifnone(directory, ifnone(gconf['prev_query_path'], os.getcwd()))) if gconf['prev_query_project': self.project_dir] is not None: self.load_project(os.path.join(self.project_dir, gconf['prev_query_project':self.project_dir])) else: self.new_project() self.config = self.project.queryconf self.project.addlistener(self.project_setdirty) self.mln_container.dirty = False self.emln_container.dirty = False self.db_container.dirty = False self.project_setdirty(dirty=False) self.master.geometry(gconf['window_loc_query']) self.initialized = True def _got_focus(self, *_): if self.master.focus_get() == self.mln_container.editor: if not self.project.mlns and not self.mln_container.file_buffer: self.mln_container.new_file() elif self.master.focus_get() == self.db_container.editor: if not self.project.dbs and not self.db_container.file_buffer: self.db_container.new_file() elif self.master.focus_get() == self.emln_container.editor: if not self.project.emlns and not self.emln_container.file_buffer: self.emln_container.new_file() def quit(self): if self.settings_dirty.get() or self.project_dirty.get(): savechanges = messagebox.askyesnocancel("Save changes", "You have unsaved project changes. Do you want to save them before quitting?") if savechanges is None: return elif savechanges: self.noask_save_project() self.master.destroy() else: # write gui settings and destroy self.write_gconfig() self.master.destroy() ####################### PROJECT FUNCTIONS ################################# def new_project(self): self.project = MLNProject() self.project.addlistener(self.project_setdirty) self.project.name = DEFAULTNAME.format('.pracmln') self.reset_gui() self.set_config(self.project.queryconf) self.mln_container.update_file_choices() self.emln_container.update_file_choices() self.db_container.update_file_choices() self.project_setdirty(dirty=True) def project_setdirty(self, dirty=False, *args): self.project_dirty.set(dirty or self.mln_container.dirty or self.db_container.dirty or self.emln_container.dirty) self.changewindowtitle() def settings_setdirty(self, *args): self.settings_dirty.set(1) self.changewindowtitle() def changewindowtitle(self): title = (WINDOWTITLEEDITED if (self.settings_dirty.get() or self.project_dirty.get()) else WINDOWTITLE).format(self.project_dir, self.project.name) self.master.title(title) def ask_load_project(self): filename = askopenfilename(initialdir=self.dir, filetypes=[('PRACMLN project files', '.pracmln')], defaultextension=".pracmln") if filename and os.path.exists(filename): self.load_project(filename) else: logger.info('No file selected.') return def load_project(self, filename): if filename and os.path.exists(filename): projdir, _ = ntpath.split(filename) self.dir = os.path.abspath(projdir) self.project_dir = os.path.abspath(projdir) self.project = MLNProject.open(filename) self.project.addlistener(self.project_setdirty) self.reset_gui() self.set_config(self.project.queryconf.config) self.mln_container.update_file_choices() self.db_container.update_file_choices() if len(self.project.mlns) > 0: self.mln_container.selected_file.set(self.project.queryconf['mln'] or list(self.project.mlns.keys())[0]) self.mln_container.dirty = False if len(self.project.emlns) > 0: self.emln_container.selected_file.set(self.project.queryconf['emln'] or list(self.project.emlns.keys())[0]) self.emln_container.dirty = False if len(self.project.dbs) > 0: self.db_container.selected_file.set(self.project.queryconf['db'] or list(self.project.dbs.keys())[0]) self.db_container.dirty = False self.write_gconfig(savegeometry=False) self.settings_dirty.set(0) self.project_setdirty(dirty=False) self.changewindowtitle() else: logger.error('File {} does not exist. Creating new project...'.format(filename)) self.new_project() def noask_save_project(self): if self.project.name and not self.project.name == DEFAULTNAME.format('.pracmln'): self.save_project(os.path.join(self.project_dir, self.project.name)) else: self.ask_save_project() def ask_save_project(self): fullfilename = asksaveasfilename(initialdir=self.project_dir, confirmoverwrite=True, filetypes=[('PRACMLN project files','.pracmln')], defaultextension=".pracmln") self.save_project(fullfilename) def save_project(self, fullfilename): if fullfilename: fpath, fname = ntpath.split(fullfilename) fname = fname.split('.')[0] self.project.name = fname self.dir = os.path.abspath(fpath) self.project_dir = os.path.abspath(fpath) self.mln_container.save_all_files() self.emln_container.save_all_files() self.db_container.save_all_files() self.update_config() self.project.save(dirpath=self.project_dir) self.write_gconfig() self.load_project(fullfilename) self.settings_dirty.set(0) def save_proj(self): self.project.save(dirpath=self.project_dir) self.write_gconfig() self.project_setdirty(dirty=False) ####################### MLN FUNCTIONS ##################################### def import_mln(self, name, content): self.project.add_mln(name, content) def delete_mln(self, fname): if fname in self.project.mlns: self.project.rm_mln(fname) fnamestr = fname.strip('*') if fnamestr in self.project.mlns: self.project.rm_mln(fnamestr) def update_mln(self, old=None, new=None, content=None, askoverwrite=True): if old is None: old = self.mln_container.selected_file.get() if new is None: new = self.mln_container.selected_file.get().strip('*') if content is None: content = self.mln_container.editor.get("1.0", END).strip() if old == new and askoverwrite: savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new)) if savechanges: self.project.mlns[old] = content else: logger.error('no name specified!') return -1 elif old == new and not askoverwrite: self.project.mlns[old] = content else: if new in self.project.mlns: if askoverwrite: savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new)) if savechanges: self.project.mlns[new] = content else: logger.error('no name specified!') return -1 else: self.project.mlns[new] = content return 1 def mlnfiles(self): return list(self.project.mlns.keys()) def mlnfilecontent(self, filename): return self.project.mlns.get(filename, '').strip() # /MLN FUNCTIONS ##################################### ####################### EMLN FUNCTIONS ##################################### def import_emln(self, name, content): self.project.add_emln(name, content) def delete_emln(self, fname): if fname in self.project.emlns: self.project.rm_emln(fname) fnamestr = fname.strip('*') if fnamestr in self.project.emlns: self.project.rm_emln(fnamestr) def update_emln(self, old=None, new=None, content=None, askoverwrite=True): if old is None: old = self.emln_container.selected_file.get() if new is None: new = self.emln_container.selected_file.get().strip('*') if content is None: content = self.emln_container.editor.get("1.0", END).strip() if old == new and askoverwrite: savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new)) if savechanges: self.project.emlns[old] = content else: logger.error('no name specified!') return -1 elif old == new and not askoverwrite: self.project.emlns[old] = content else: if new in self.project.emlns: if askoverwrite: savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new)) if savechanges: self.project.emlns[new] = content else: logger.error('no name specified!') return -1 else: self.project.emlns[new] = content return 1 def emlnfiles(self): return list(self.project.emlns.keys()) def emlnfilecontent(self, filename): return self.project.emlns.get(filename, '').strip() # /EMLN FUNCTIONS ##################################### # DB FUNCTIONS ##################################### def import_db(self, name, content): self.project.add_db(name, content) def delete_db(self, fname): if fname in self.project.dbs: self.project.rm_db(fname) fnamestr = fname.strip('*') if fnamestr in self.project.dbs: self.project.rm_db(fnamestr) def update_db(self, old=None, new=None, content=None, askoverwrite=True): if old is None: old = self.db_container.selected_file.get() if new is None: new = self.db_container.selected_file.get().strip('*') if content is None: content = self.db_container.editor.get("1.0", END).strip() if old == new and askoverwrite: savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new)) if savechanges: self.project.dbs[old] = content else: logger.error('no name specified!') return -1 elif old == new and not askoverwrite: self.project.dbs[old] = content else: if new in self.project.dbs: if askoverwrite: savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new)) if savechanges: self.project.dbs[new] = content else: logger.error('no name specified!') return -1 else: self.project.dbs[new] = content return 1 def dbfiles(self): return list(self.project.dbs.keys()) def dbfilecontent(self, filename): return self.project.dbs.get(filename, '').strip() # /DB FUNCTIONS ##################################### # GENERAL FUNCTIONS ################################# def select_method(self, *args): self.set_outputfilename() self.settings_setdirty() def onchange_use_emln(self, dirty=True, *args): if not self.use_emln.get(): self.emln_label.grid_forget() self.emln_container.grid_forget() else: self.emln_label.grid(row=self.emlncontainerrow, column=0, sticky="NE") self.emln_container.grid(row=self.emlncontainerrow, column=1, sticky="NWES") if dirty: self.settings_setdirty() def onchange_cw(self, *args): if self.closed_world.get(): self.entry_cw.configure(state=DISABLED) else: self.entry_cw.configure(state=NORMAL) self.settings_setdirty() def reset_gui(self): self.set_config({}) self.db_container.clear() self.emln_container.clear() self.mln_container.clear() def set_config(self, newconf): self.config = newconf self.selected_grammar.set(ifnone(newconf.get('grammar'), 'PRACGrammar')) self.selected_logic.set(ifnone(newconf.get('logic'), 'FirstOrderLogic')) self.mln_container.selected_file.set(ifnone(newconf.get('mln'), '')) if self.use_emln.get(): self.emln_container.selected_file.set(ifnone(newconf.get('mln'), '')) self.db_container.selected_file.set(ifnone(newconf.get('db'), "")) self.selected_method.set(ifnone(newconf.get("method"), InferenceMethods.name('MCSAT'), transform=InferenceMethods.name)) self.multicore.set(ifnone(newconf.get('multicore'), 0)) self.profile.set(ifnone(newconf.get('profile'), 0)) self.params.set(ifnone(newconf.get('params'), '')) self.use_emln.set(ifnone(newconf.get('use_emln'), 0)) self.verbose.set(ifnone(newconf.get('verbose'), 1)) self.ignore_unknown_preds.set(ifnone(newconf.get('ignore_unknown_preds'), 0)) self.output_filename.set(ifnone(newconf.get('output_filename'), '')) self.cwPreds.set(ifnone(newconf.get('cw_preds'), '')) self.closed_world.set(ifnone(newconf.get('cw'), 0)) self.save.set(ifnone(newconf.get('save'), 0)) self.query.set(ifnone(newconf.get('queries'), '')) self.onchange_cw() def set_outputfilename(self): if not hasattr(self, "output_filename") or not hasattr(self, "db_filename") or not hasattr(self, "mln_filename"): return mln = self.mln_container.selected_file.get() db = self.db_container.selected_file.get() if "" in (mln, db): return if self.selected_method.get(): method = InferenceMethods.clazz(self.selected_method.get()) methodid = InferenceMethods.id(method) filename = config.query_output_filename(mln, methodid, db) self.output_filename.set(filename) def update_config(self): self.config = PRACMLNConfig() self.config["use_emln"] = self.use_emln.get() self.config['mln'] = self.mln_container.selected_file.get().strip().lstrip('*') self.config['emln'] = self.emln_container.selected_file.get().strip().lstrip('*') self.config["db"] = self.db_container.selected_file.get().strip().lstrip('*') self.config["method"] = InferenceMethods.id(self.selected_method.get().strip()) self.config["params"] = self.params.get().strip() self.config["queries"] = self.query.get() self.config["output_filename"] = self.output_filename.get().strip() self.config["cw"] = self.closed_world.get() self.config["cw_preds"] = self.cwPreds.get() self.config['profile'] = self.profile.get() self.config['logic'] = self.selected_logic.get() self.config['grammar'] = self.selected_grammar.get() self.config['multicore'] = self.multicore.get() self.config['save'] = self.save.get() self.config['ignore_unknown_preds'] = self.ignore_unknown_preds.get() self.config['verbose'] = self.verbose.get() self.config['window_loc'] = self.master.winfo_geometry() self.config['dir'] = self.dir self.project.queryconf = PRACMLNConfig() self.project.queryconf.update(self.config.config.copy()) def write_gconfig(self, savegeometry=True): self.gconf['prev_query_path'] = self.dir self.gconf['prev_query_project': self.dir] = self.project.name # save geometry if savegeometry: self.gconf['window_loc_query'] = self.master.geometry() self.gconf.dump() def infer(self, savegeometry=True, options={}, *args): mln_content = self.mln_container.editor.get("1.0", END).strip() db_content = self.db_container.editor.get("1.0", END).strip() # create conf from current gui settings self.update_config() # write gui settings self.write_gconfig(savegeometry=savegeometry) # hide gui self.master.withdraw() try: print((headline('PRACMLN QUERY TOOL'))) print() if options.get('mlnarg') is not None: mlnobj = MLN(mlnfile=os.path.abspath(options.get('mlnarg')), logic=self.config.get('logic', 'FirstOrderLogic'), grammar=self.config.get('grammar', 'PRACGrammar')) else: mlnobj = parse_mln(mln_content, searchpaths=[self.dir], projectpath=os.path.join(self.dir, self.project.name), logic=self.config.get('logic', 'FirstOrderLogic'), grammar=self.config.get('grammar', 'PRACGrammar')) if options.get('emlnarg') is not None: emln_content = mlnpath(options.get('emlnarg')).content else: emln_content = self.emln_container.editor.get("1.0", END).strip() if options.get('dbarg') is not None: dbobj = Database.load(mlnobj, dbfiles=[options.get('dbarg')], ignore_unknown_preds=self.config.get('ignore_unknown_preds', True)) else: out(self.config.get('ignore_unknown_preds', True)) dbobj = parse_db(mlnobj, db_content, ignore_unknown_preds=self.config.get('ignore_unknown_preds', True)) if options.get('queryarg') is not None: self.config["queries"] = options.get('queryarg') infer = MLNQuery(config=self.config, mln=mlnobj, db=dbobj, emln=emln_content) result = infer.run() # write to file if run from commandline, otherwise save result to project results if options.get('outputfile') is not None: output = io.StringIO() result.write(output) with open(os.path.abspath(options.get('outputfile')), 'w') as f: f.write(output.getvalue()) logger.info('saved result to {}'.format(os.path.abspath(options.get('outputfile')))) elif self.save.get(): output = io.StringIO() result.write(output) fname = self.output_filename.get() self.project.add_result(fname, output.getvalue()) self.project.save(dirpath=self.dir) logger.info('saved result to file results/{} in project {}'.format(fname, self.project.name)) else: logger.debug('No output file given - results have not been saved.') except: traceback.print_exc() # restore main window sys.stdout.flush() self.master.deiconify()
def __init__(self, master): """Class builds GUI to control Waltz Telescope. Uses Tkinter for GUI functionality. Inherits from lx200commands.Lx200Commands class. This class provides functionality to talk to serial connection using the lx200 protocol. """ super().__init__() self.master = master master.title("Waltz Control Panel") #Store CET and UCT self.CET = '' self.UTC = '' #Store if telescope is waiting for slew to finish self.waiting=True ## Building up GUI Widgets ## #Menubars menubar=Menu(self.master) #Connection menu connectionmenu = Menu(menubar, tearoff=0) connectionmenu.add_command(label="Open Connection", command=self.open_connection_buttonclick) connectionmenu.add_command(label="Close Connection", command=self.close_connection_buttonclick) menubar.add_cascade(label="Connection", menu=connectionmenu) #settings_menu settings_menu=Menu(menubar, tearoff=0) settings_menu.add_command(label="Enable buttons",command=self.stop_waiting) settings_menu.add_command(label="Toggle Precision",command=super().toggle_precision) menubar.add_cascade(label="Settings",menu=settings_menu) #Pointing_stars_menu pointing_stars_menu=Menu(menubar, tearoff=0) pointing_stars_menu.add_command(label="Pointing Star", command=self.save_pointing_star) menubar.add_cascade(label="Save as", menu= pointing_stars_menu) #Special_positions_menu special_positions_menu=Menu(menubar, tearoff=0) special_positions_menu.add_command(label="Slew to Primary Mirror Position",command=self.primary_mirror_pos_buttonclick) special_positions_menu.add_command(label="Slew to Secondary Mirror Position",command=self.secondary_mirror_pos_buttonclick) special_positions_menu.add_command(label="Slew to Park Position",command=self.park_telescope_buttonclick) menubar.add_cascade(label="Special Positions",menu=special_positions_menu) #Show menubar self.master.config(menu=menubar) #Output frame output_frame=Frame(master) output_frame.grid(row=0,columnspan=3) self.LST_label = Label(output_frame, font=('arial', 15, 'bold'), text="LST") self.LST_label.grid(row=0,column=0) self.LST_display = Label(output_frame, font=('arial', 20, 'bold'), bg='light green') self.LST_display.grid(row=0, column=1,padx=10, pady=10) self.local_time_label= Label(output_frame, font=('arial', 15, 'bold'), text='LT') self.local_time_label.grid(row=0, column=3) self.local_time_display = Label(output_frame, font=('arial', 20, 'bold'), bg='light green') self.local_time_display.grid(row=0, column=4,padx=10,pady=10) self.UTC_label= Label(output_frame, font=('arial', 15, 'bold'), text='UTC') self.UTC_label.grid(row=0, column=5) self.UTC_display = Label(output_frame, font=('arial', 20, 'bold'), bg='light green') self.UTC_display.grid(row=0, column=6,padx=10,pady=10) self.RA_label= Label(output_frame, font=('arial', 15, 'bold'), text= "RA") self.RA_label.grid(row=1, column =0) self.RA_display= Label(output_frame, font=('arial', 20, 'bold'), bg='light green') self.RA_display.grid(row=1, column =1) self.DEC_label= Label(output_frame, font=('arial', 15, 'bold'), text= "DEC") self.DEC_label.grid(row=1, column =3) self.DEC_display= Label(output_frame, font=('arial', 20, 'bold'), bg='light green') self.DEC_display.grid(row=1, column =4) self.HA_label= Label(output_frame, font=('arial', 15, 'bold'), text= "HA") self.HA_label.grid(row=1, column =5) self.HA_display= Label(output_frame, font=('arial', 20, 'bold'), bg='light green') self.HA_display.grid(row=1, column=6) #Interchange_frame #To interchange W<->E buttons and N<->S self.interchange_frame=Frame(master) self.interchange_frame.grid(row=1, column=0,pady=10) #Define Variables self.inter_WE=IntVar() self.inter_NS=IntVar() self.inter_NS_checkbox=Checkbutton(self.interchange_frame, text='N <> S', font=('arial', 10, 'bold'), variable=self.inter_NS, command=self.interchange_north_south) self.inter_NS_checkbox.grid(row=0,column=0,sticky='w',pady=5) self.inter_WE_checkbox=Checkbutton(self.interchange_frame, text='W <> E', font=('arial', 10, 'bold'), variable=self.inter_WE, command=self.interchange_west_east) self.inter_WE_checkbox.grid(row=1,column=0,sticky='w',pady=5) #Control frame self.control_frame=Frame(master) self.control_frame.grid(row=1,column=1,pady=10) self.south_button = Button(self.control_frame, text="S", font=('arial', 20, 'bold'), bg='LightGrey', height = 1, width = 2) self.south_button.grid(row=0,column=1) self.west_button = Button(self.control_frame, text="W", font=('arial', 20, 'bold'), bg='LightGrey', height = 1, width = 2) self.west_button.grid(row=1,column=0) self.east_button = Button(self.control_frame, text="E", font=('arial', 20, 'bold'), bg='LightGrey', height = 1, width = 2) self.east_button.grid(row=1,column=2) self.north_button = Button(self.control_frame, text="N", font=('arial', 20, 'bold'), bg='LightGrey', height = 1, width = 2) self.north_button.grid(row=2,column=1) self.stop_button = Button(self.control_frame, text="STOP", font=('arial',20, 'bold'), fg='White', bg='Red', activeforeground='Red', activebackground='White', command=super().stop_at_current_pos) self.stop_button.grid(row=3,column=0, columnspan=3, pady=10) #Radiobutton frame self.radiobutton_frame=Frame(master) self.radiobutton_frame.grid(row=1,column=2,pady=10) radiobutton_parameters=[('Slew',0,self.set_speed_max), ('Find',1, self.set_speed_find), ('Center',2, self.set_speed_center), ('Guide',3, self.set_speed_guide)] self.speed=StringVar() #Initialize speed to guiding speed self.speed.set('Guide') for keyword, position, execute in radiobutton_parameters: self.speed_radiobutton= Radiobutton(self.radiobutton_frame, text=keyword, variable=self.speed, value=keyword, command=execute, font=('arial', 10, 'bold')) self.speed_radiobutton.grid(row=position,column=0,sticky=W) #Options Frame self.options_frame=Frame(master) self.options_frame.grid(row=0,column=3,padx=20) self.sync_button = Button(self.options_frame, text="Synchronize \n with Target", font=('arial', 12, 'bold'), bg='LightGrey', command=self.sync_yes_no, state='disabled') self.sync_button.grid(row=0,column=0,padx=5) #Target Frame self.target_frame=LabelFrame(master, text='Select Target (apparent position)', font=('arial', 15)) self.target_frame.grid(row=1,rowspan=1,column=3,padx=20) self.HIP_label = Label(self.target_frame, font=('arial', 15), text="Hipparcos") self.HIP_label.grid(row=0,column=0) self.HIP_entry= Entry(self.target_frame, font=('arial', 15)) self.HIP_entry.grid(row=0, column=1,pady=10) self.target_ra_label = Label(self.target_frame, font=('arial', 15), text="RA \n [hh mm ss]") self.target_ra_label.grid(row=1,column=0) self.target_ra_entry= Entry(self.target_frame, font=('arial', 15)) self.target_ra_entry.grid(row=1, column=1,pady=10) self.target_dec_label = Label(self.target_frame, font=('arial', 15), text="""DEC \n [°° mm ss]""") self.target_dec_label.grid(row=2,column=0) self.target_dec_entry= Entry(self.target_frame, font=('arial', 15)) self.target_dec_entry.grid(row=2, column=1,pady=10) self.target_time_label= Label(self.target_frame, font=('arial', 15), text=" Obs \n Time") self.target_time_label.grid(row=0,column=2,padx=10) self.target_time_display=Label(self.target_frame, font=('arial', 15), bg='red', width=10) self.target_time_display.grid(row=0,column=3,pady=10) self.target_alt_label = Label(self.target_frame, font=('arial', 15), text="ALT") self.target_alt_label.grid(row=1,column=2,padx=10) self.target_alt_display= Label(self.target_frame, font=('arial', 15), bg='red', width=10) self.target_alt_display.grid(row=1, column=3,pady=10) self.target_az_label = Label(self.target_frame, font=('arial', 15), text="AZ") self.target_az_label.grid(row=2,column=2,padx=10) self.target_az_display= Label(self.target_frame, font=('arial', 15), bg='red', width=10) self.target_az_display.grid(row=2, column=3,pady=10) self.slew_target_button = Button(self.target_frame, text="Slew to Target", font=('arial', 15), bg='LightGrey', state='disabled', command=self.slew_to_target_buttonclick) self.slew_target_button.grid(row=3,columnspan=4) #Plot Frame self.plot_frame=Frame(master) self.plot_frame.grid(row=2,columnspan=4) #Add instance variables to store the plot and the different axes, #and positions globally self.canvas=False self.ax1=False self.star_plot=False self.traj_plot=False self.pos_plot=False self.ax2=False #At first check if serial connection is open (also contains initial commands) self._respond_to_connection_state() #Message box for Warning caution=("CAUTION: THIS IS A FIRST ATTEMPT TO CONTROL THE WALTZ TELESCOPE.\n"+ "BAD INPUTS OR CRASHES OF THE PROGRAM COULD BE HARMFUL TO THE TELESCOPE.\n"+ "DO NOT USE THIS PROGRAM ALONE AND ALWAYS PREPARE FOR STOPING MOVEMENTS "+ "OF THE TELESCOPE VIA THE EMERGENCY STOPS IN THE DOME!") messagebox.showwarning("Warning",message=caution,parent=master)
class ProblemBrowser(object): def __init__(self): self.action = None self.root = root = Tk() root.title('Never gonna fold you up') root.protocol("WM_DELETE_WINDOW", self.close) root.pack_propagate(True) scrollbar = Scrollbar(root, orient=tkinter.VERTICAL) self.problem_list = Listbox(root, exportselection=False, yscrollcommand=scrollbar.set) self.problem_list.pack(expand=True, fill=tkinter.BOTH, side=tkinter.LEFT) scrollbar.config(command=self.problem_list.yview) scrollbar.pack(side=tkinter.LEFT, fill=tkinter.Y) self.problem_list.bind('<<ListboxSelect>>', lambda evt: self.populate_problem_canvas()) self.problem_canvas = Canvas(root, bd=1, relief=tkinter.SUNKEN, width=500, height=500) self.problem_canvas.pack(expand=True, fill=tkinter.BOTH, side=tkinter.LEFT) self.problem_canvas.bind("<Configure>", lambda evt: self.populate_problem_canvas()) button_frame = Frame(root) button_frame.pack(fill=tkinter.Y, side=tkinter.LEFT) # Reposition the figure so it's center of mass is at 0.5, 0.5 v = IntVar() self.center_cb = Checkbutton(button_frame, text="center", variable=v, command=lambda: self.populate_problem_canvas()) self.center_cb.var = v self.center_cb.pack(side=tkinter.TOP) # Use meshes.reconstruct_facets instead of polygon/hole logic. v = IntVar() self.reconstruct_cb = Checkbutton(button_frame, text="reconstruct", variable=v, command=lambda: self.populate_problem_canvas()) self.reconstruct_cb.var = v self.reconstruct_cb.pack(side=tkinter.TOP) self.populate_problems() self.current_problem_name = None self.current_problem = None def populate_problems(self): self.problem_list.delete(0, tkinter.END) for file in sorted((get_root() / 'problems').iterdir()): self.problem_list.insert(tkinter.END, file.stem) def populate_problem_canvas(self): sel = self.problem_list.curselection() if not sel: return assert len(sel) == 1 name = self.problem_list.get(sel[0]) if name != self.current_problem_name: self.current_problem_name = name self.current_problem = load_problem(name) if self.current_problem: p = self.current_problem if self.center_cb.var.get(): p = center_problem(p) if self.reconstruct_cb.var.get(): facets = meshes.reconstruct_facets(p) facets = meshes.keep_real_facets(facets, p) skeleton = [e for f in facets for e in edges_of_a_facet(f)] p = Problem(facets, skeleton) draw_problem(self.problem_canvas, p) def run(self): self.root.mainloop() def close(self): if self.root: self.root.destroy() self.root = None
class WaltzGUI(lx.Lx200Commands): def __init__(self, master): """Class builds GUI to control Waltz Telescope. Uses Tkinter for GUI functionality. Inherits from lx200commands.Lx200Commands class. This class provides functionality to talk to serial connection using the lx200 protocol. """ super().__init__() self.master = master master.title("Waltz Control Panel") #Store CET and UCT self.CET = '' self.UTC = '' #Store if telescope is waiting for slew to finish self.waiting=True ## Building up GUI Widgets ## #Menubars menubar=Menu(self.master) #Connection menu connectionmenu = Menu(menubar, tearoff=0) connectionmenu.add_command(label="Open Connection", command=self.open_connection_buttonclick) connectionmenu.add_command(label="Close Connection", command=self.close_connection_buttonclick) menubar.add_cascade(label="Connection", menu=connectionmenu) #settings_menu settings_menu=Menu(menubar, tearoff=0) settings_menu.add_command(label="Enable buttons",command=self.stop_waiting) settings_menu.add_command(label="Toggle Precision",command=super().toggle_precision) menubar.add_cascade(label="Settings",menu=settings_menu) #Pointing_stars_menu pointing_stars_menu=Menu(menubar, tearoff=0) pointing_stars_menu.add_command(label="Pointing Star", command=self.save_pointing_star) menubar.add_cascade(label="Save as", menu= pointing_stars_menu) #Special_positions_menu special_positions_menu=Menu(menubar, tearoff=0) special_positions_menu.add_command(label="Slew to Primary Mirror Position",command=self.primary_mirror_pos_buttonclick) special_positions_menu.add_command(label="Slew to Secondary Mirror Position",command=self.secondary_mirror_pos_buttonclick) special_positions_menu.add_command(label="Slew to Park Position",command=self.park_telescope_buttonclick) menubar.add_cascade(label="Special Positions",menu=special_positions_menu) #Show menubar self.master.config(menu=menubar) #Output frame output_frame=Frame(master) output_frame.grid(row=0,columnspan=3) self.LST_label = Label(output_frame, font=('arial', 15, 'bold'), text="LST") self.LST_label.grid(row=0,column=0) self.LST_display = Label(output_frame, font=('arial', 20, 'bold'), bg='light green') self.LST_display.grid(row=0, column=1,padx=10, pady=10) self.local_time_label= Label(output_frame, font=('arial', 15, 'bold'), text='LT') self.local_time_label.grid(row=0, column=3) self.local_time_display = Label(output_frame, font=('arial', 20, 'bold'), bg='light green') self.local_time_display.grid(row=0, column=4,padx=10,pady=10) self.UTC_label= Label(output_frame, font=('arial', 15, 'bold'), text='UTC') self.UTC_label.grid(row=0, column=5) self.UTC_display = Label(output_frame, font=('arial', 20, 'bold'), bg='light green') self.UTC_display.grid(row=0, column=6,padx=10,pady=10) self.RA_label= Label(output_frame, font=('arial', 15, 'bold'), text= "RA") self.RA_label.grid(row=1, column =0) self.RA_display= Label(output_frame, font=('arial', 20, 'bold'), bg='light green') self.RA_display.grid(row=1, column =1) self.DEC_label= Label(output_frame, font=('arial', 15, 'bold'), text= "DEC") self.DEC_label.grid(row=1, column =3) self.DEC_display= Label(output_frame, font=('arial', 20, 'bold'), bg='light green') self.DEC_display.grid(row=1, column =4) self.HA_label= Label(output_frame, font=('arial', 15, 'bold'), text= "HA") self.HA_label.grid(row=1, column =5) self.HA_display= Label(output_frame, font=('arial', 20, 'bold'), bg='light green') self.HA_display.grid(row=1, column=6) #Interchange_frame #To interchange W<->E buttons and N<->S self.interchange_frame=Frame(master) self.interchange_frame.grid(row=1, column=0,pady=10) #Define Variables self.inter_WE=IntVar() self.inter_NS=IntVar() self.inter_NS_checkbox=Checkbutton(self.interchange_frame, text='N <> S', font=('arial', 10, 'bold'), variable=self.inter_NS, command=self.interchange_north_south) self.inter_NS_checkbox.grid(row=0,column=0,sticky='w',pady=5) self.inter_WE_checkbox=Checkbutton(self.interchange_frame, text='W <> E', font=('arial', 10, 'bold'), variable=self.inter_WE, command=self.interchange_west_east) self.inter_WE_checkbox.grid(row=1,column=0,sticky='w',pady=5) #Control frame self.control_frame=Frame(master) self.control_frame.grid(row=1,column=1,pady=10) self.south_button = Button(self.control_frame, text="S", font=('arial', 20, 'bold'), bg='LightGrey', height = 1, width = 2) self.south_button.grid(row=0,column=1) self.west_button = Button(self.control_frame, text="W", font=('arial', 20, 'bold'), bg='LightGrey', height = 1, width = 2) self.west_button.grid(row=1,column=0) self.east_button = Button(self.control_frame, text="E", font=('arial', 20, 'bold'), bg='LightGrey', height = 1, width = 2) self.east_button.grid(row=1,column=2) self.north_button = Button(self.control_frame, text="N", font=('arial', 20, 'bold'), bg='LightGrey', height = 1, width = 2) self.north_button.grid(row=2,column=1) self.stop_button = Button(self.control_frame, text="STOP", font=('arial',20, 'bold'), fg='White', bg='Red', activeforeground='Red', activebackground='White', command=super().stop_at_current_pos) self.stop_button.grid(row=3,column=0, columnspan=3, pady=10) #Radiobutton frame self.radiobutton_frame=Frame(master) self.radiobutton_frame.grid(row=1,column=2,pady=10) radiobutton_parameters=[('Slew',0,self.set_speed_max), ('Find',1, self.set_speed_find), ('Center',2, self.set_speed_center), ('Guide',3, self.set_speed_guide)] self.speed=StringVar() #Initialize speed to guiding speed self.speed.set('Guide') for keyword, position, execute in radiobutton_parameters: self.speed_radiobutton= Radiobutton(self.radiobutton_frame, text=keyword, variable=self.speed, value=keyword, command=execute, font=('arial', 10, 'bold')) self.speed_radiobutton.grid(row=position,column=0,sticky=W) #Options Frame self.options_frame=Frame(master) self.options_frame.grid(row=0,column=3,padx=20) self.sync_button = Button(self.options_frame, text="Synchronize \n with Target", font=('arial', 12, 'bold'), bg='LightGrey', command=self.sync_yes_no, state='disabled') self.sync_button.grid(row=0,column=0,padx=5) #Target Frame self.target_frame=LabelFrame(master, text='Select Target (apparent position)', font=('arial', 15)) self.target_frame.grid(row=1,rowspan=1,column=3,padx=20) self.HIP_label = Label(self.target_frame, font=('arial', 15), text="Hipparcos") self.HIP_label.grid(row=0,column=0) self.HIP_entry= Entry(self.target_frame, font=('arial', 15)) self.HIP_entry.grid(row=0, column=1,pady=10) self.target_ra_label = Label(self.target_frame, font=('arial', 15), text="RA \n [hh mm ss]") self.target_ra_label.grid(row=1,column=0) self.target_ra_entry= Entry(self.target_frame, font=('arial', 15)) self.target_ra_entry.grid(row=1, column=1,pady=10) self.target_dec_label = Label(self.target_frame, font=('arial', 15), text="""DEC \n [°° mm ss]""") self.target_dec_label.grid(row=2,column=0) self.target_dec_entry= Entry(self.target_frame, font=('arial', 15)) self.target_dec_entry.grid(row=2, column=1,pady=10) self.target_time_label= Label(self.target_frame, font=('arial', 15), text=" Obs \n Time") self.target_time_label.grid(row=0,column=2,padx=10) self.target_time_display=Label(self.target_frame, font=('arial', 15), bg='red', width=10) self.target_time_display.grid(row=0,column=3,pady=10) self.target_alt_label = Label(self.target_frame, font=('arial', 15), text="ALT") self.target_alt_label.grid(row=1,column=2,padx=10) self.target_alt_display= Label(self.target_frame, font=('arial', 15), bg='red', width=10) self.target_alt_display.grid(row=1, column=3,pady=10) self.target_az_label = Label(self.target_frame, font=('arial', 15), text="AZ") self.target_az_label.grid(row=2,column=2,padx=10) self.target_az_display= Label(self.target_frame, font=('arial', 15), bg='red', width=10) self.target_az_display.grid(row=2, column=3,pady=10) self.slew_target_button = Button(self.target_frame, text="Slew to Target", font=('arial', 15), bg='LightGrey', state='disabled', command=self.slew_to_target_buttonclick) self.slew_target_button.grid(row=3,columnspan=4) #Plot Frame self.plot_frame=Frame(master) self.plot_frame.grid(row=2,columnspan=4) #Add instance variables to store the plot and the different axes, #and positions globally self.canvas=False self.ax1=False self.star_plot=False self.traj_plot=False self.pos_plot=False self.ax2=False #At first check if serial connection is open (also contains initial commands) self._respond_to_connection_state() #Message box for Warning caution=("CAUTION: THIS IS A FIRST ATTEMPT TO CONTROL THE WALTZ TELESCOPE.\n"+ "BAD INPUTS OR CRASHES OF THE PROGRAM COULD BE HARMFUL TO THE TELESCOPE.\n"+ "DO NOT USE THIS PROGRAM ALONE AND ALWAYS PREPARE FOR STOPING MOVEMENTS "+ "OF THE TELESCOPE VIA THE EMERGENCY STOPS IN THE DOME!") messagebox.showwarning("Warning",message=caution,parent=master) def close_connection_buttonclick(self): """ Closes the connection to serial and responds properly to it """ #First check the connection state if self.connected==False: print('Connection already closed') return 0 #Close serial connection super().close_connection() #Check if connection is realy closed #this will set self.connected=False #Respond to closed connection self._respond_to_connection_state() def open_connection_buttonclick(self): """ Closes the connection to serial and responds properly to it """ #First check the connection state if self.connected==True: print('Connection already open') return 0 #Open serial connection super().open_connection() #Respond to open connection self._respond_to_connection_state() def _start_commands(self): """ Contains all functions to be executed at start of program. """ #Commands to be executed even without connection self.refresh_times() self.initialize_plot() #If connection is not open close program if not self.connected: return 0 #Commands for initial settings self.set_speed_guide() #This is the StringVar defining which initial setting the speed Radiobuttons have self.speed.set('Guide') #Commands to be executed all the time (if connection is open) self.display_coordinates() self.refresh_target_alt_az_ha() #Check for format of coordinates and toggle automatically #We always want format DEC=dd mm ss if len(self.dec)==7: super().toggle_precision() def _respond_to_connection_state(self): """ Checks connection to serial port. Print Warning if not and closes program. Enables and binds all buttons if connection is set. """ #If connection to Waltz is closed if not self.connected: #Disable all buttons self.disable_all_buttons() self.stop_button.config(state='disabled') #Message box if serial connection is not open caution=("Warning: No Connection to Waltz") messagebox.showwarning("Warning",message=caution,parent=self.master) #Start Commands #(it will take care that only the ones that do not use the serial connection are executed) self._start_commands() if self.connected: #Enable all buttons self.enable_all_buttons() #Start Commands self._start_commands() def refresh_times(self): """ Refreshs all times (LST, LT, UTC) Introduced to have only one function call in the background. Better to syn clocks """ #Refresh individual times self.refresh_LST() self.refresh_local_time() self.refresh_UTC() #Also refresh hour_angle synced to times because it will change in the same pace super().calculate_hour_angle() self.HA_display.config(text=self.ha) #Calls itself all 200 ms self.master.after(200, self.refresh_times) def refresh_local_time(self): """ Displays the current Central Eruopean Time on CET_display. Calls itself all 200ms to refresh time. """ # get the current local time from the PC local_time_now = time.strftime('%H:%M:%S') # if time string has changed, update it if local_time_now != self.CET: self.local_time = local_time_now self.local_time_display.config(text=self.local_time) def refresh_LST(self): """ Displays the current Local Sidereal Time on LST_display. Calls itself all 200ms to refresh time. """ super().get_LST() self.LST_display.config(text=self.LST) def refresh_UTC(self): """ Displays the current Coordinated Universal Time on UTC_display. Calls itself all 200 ms to refresh time. """ #Get current UTC from datetime UTC_now= datetime.datetime.utcnow() UTC_now=UTC_now.strftime("%H:%M:%S") #Check if UTC has changed since last call if UTC_now != self.UTC: #Save current UTC in self.UTC self.UTC = UTC_now #Display UTC self.UTC_display.config(text=self.UTC) def initialize_plot(self): """Refreshs Plot. """ #Close all plots for safety reasons #plt.close('all') (fig, self.ax1) = plot_traj_limits_altaz_GUI(False,False,False,False) self.canvas = FigureCanvasTkAgg(fig, master = self.plot_frame) self.canvas._tkcanvas.grid(row=0,column=0) self.plot_current_pos() def plot_current_pos(self): """Overplots current position. Plot needs to already exist. """ #First remove existing pos_plot (if it exists) if self.pos_plot: self.pos_plot.pop(0).remove() #Now add new pos_plot self.pos_plot=add_current_pos(self.ax1,self.ha_float,self.dec_float) self.canvas.draw() self.master.after(1000,self.plot_current_pos) def plot_star_and_traj(self): """Overplots star position and trajectory. Plot need to already exist. Will be called periodically with refresh_target_alt_az_ha. """ #First remove existing star_plot/traj_plot (if they exists) if self.star_plot: self.star_plot.pop(0).remove() self.traj_plot.pop(0).remove() self.ax2.remove() if not self.target_ra_float or not self.target_dec_float: return 0 #Now add new_star_plot (self.star_plot, self.traj_plot, self.ax2)=add_star_and_traj(self.ax1, self.target_ha_float, self.target_dec_float) self.canvas.draw() def display_coordinates(self): """ Displays Right ascension and Declination. Hour angle will be displayed synced to times. It should change at the same rate as LST. Look at refresh_times() """ #If connection is not open close program if not self.connected: return 0 self.get_coordinates() self.RA_display.config(text=self.ra) self.DEC_display.config(text=self.dec) if not self.connected: self._respond_to_connection_state() self.master.after(500,self.display_coordinates) def refresh_target_alt_az_ha(self,call_itself=True): """ Executes Lx200Commands.calculate_target_alt_az_ha every 500 ms. """ #Calculate target alt and az and obs time super().calculate_target_alt_az_ha() #Display alt, az and obs time self.target_alt_display.config(text=self.target_alt) self.target_az_display.config(text=self.target_az) self.target_time_display.config(text=self.target_obs_time) #Check coordinates to reply with correct colors if check_coordinates(self.target_alt_float, self.target_az_float): self.display_alt_az('light green') else: self.display_alt_az('red') #Update the plot self.plot_star_and_traj() #Optionally call itself if call_itself: self.master.after(5000,self.refresh_target_alt_az_ha) def interchange_west_east(self): """Interchanges West and East Buttons. """ #self.inter_WE.get() will return 1 if box is checked and 0 if not if self.inter_WE.get(): #Grid Positions if checkbutton is checked self.west_button.grid(row=1,column=2) self.east_button.grid(row=1,column=0) if not self.inter_WE.get(): #Grid Position in default state self.west_button.grid(row=1,column=0) self.east_button.grid(row=1,column=2) def interchange_north_south(self): """Interchanges North and South Buttons. """ #self.inter_WE.get() will return 1 if box is checked and 0 if not if self.inter_NS.get(): #Grid Positions if checkbutton is checked self.south_button.grid(row=2,column=1) self.north_button.grid(row=0,column=1) if not self.inter_NS.get(): #Grid Position in default state self.south_button.grid(row=0,column=1) self.north_button.grid(row=2,column=1) def start_move_west_buttonclick(self, event): """ Sends move west LX200 command to serial connection """ super().start_move_west() def stop_move_west_buttonclick(self, event): """ Sends stop move west LX200 command to serial connection """ super().stop_move_west() def start_move_north_buttonclick(self, event): super().start_move_north() def stop_move_north_buttonclick(self, event): super().stop_move_north() def start_move_south_buttonclick(self, event): super().start_move_south() def stop_move_south_buttonclick(self, event): super().stop_move_south() def start_move_east_buttonclick(self, event): super().start_move_east() def stop_move_east_buttonclick(self, event): super().stop_move_east() def slew_to_target_buttonclick(self): """Slews to target. Target must be set before via set_target_dec_from_string and set_target_ra_from_string """ super().set_target_coordinates() #Slew to target and wait for slew to finish super().slew_to_target() self.wait_for_slew_finish() #After slewing (and if something went wrong): #Set all valid_target entries to 0 (controller won't let you slew to #the same coordinates twice self.valid_target=[0,0] self.slew_target_button.config(state='disabled') #def continue_slew(self,initial_target_ra, initial_target_dec): """ Continues slewing after possible initial slew to medium position. Performs slewing if no slew to medium position is necessary. """ #Check if slew is finished. Default Value of slew_done=True, #so it will also be True if no slew to medium position was necessary.) #if self.slew_done: #Set the initial target coordinates as normal target coordinates again #super().set_target_ra_from_string(initial_target_ra) #super().set_target_dec_from_string(initial_target_dec) #Slew to target #super().slew_to_target() #Wait for the slew to finish (disables all buttons etc.) #self.wait_for_slew_finish() #else: #If previous slew is not finished the funcion will call itself every second. #self.master.after(1000, self.continue_slew, initial_target_ra, initial_target_dec) def park_telescope_buttonclick(self,counter=1,park=True): """Parks telescope and waits for slew to finish. counter counts if parking is executed the first or second time. park specifies if controller gets a parking command or if the function just waits until first slew has finished. """ #We need to call park telescope twice #because the tracking will change RA while DEC is still adjusting #Park telescope for the first time if counter==1: #If parking is activated if park: print('Slew to Park Position the first time') #Slew telescope to parking position super().park_telescope() self.refresh_target_alt_az_ha(call_itself=False) #Start waiting: Call wait_for_slew_finish with call_itself=False #So the funtion will just check if slew has finished if not self.wait_for_slew_finish(call_itself=False): #If slew has not yet finished print('Waiting for First Parking to finish') #Call the park funtion after 1 sec with counter=1 and slew=False #So it will be in counter=1 loop but will not send #a park command to the controller self.master.after(1000,self.park_telescope_buttonclick, 1,False) return 0 else: #If slewing has finished #Disable all buttons (need because it will otherwise wait #for one second until it disables again) self.disable_all_buttons() print('Finished First Parking') #Call park function again after 1 second but enter counter=2 loop #Also activate parking again with park=True #Useful to wait one second as safetiy that slewing has stopped self.master.after(1000,self.park_telescope_buttonclick, 2,True) return 0 #Second Parking loop if counter==2: if park: #If parking is activated print('Slew to Park Position the second time') #Slew telescope to parking position super().park_telescope() self.refresh_target_alt_az_ha(call_itself=False) #Wait again as above. But call counter=2 fpr second parking loop if not self.wait_for_slew_finish(call_itself=False): print('Waiting for Second Parking to finish') self.master.after(1000,self.park_telescope_buttonclick, 2,False) return 0 else: #When slewing is done print('Finished Second Parking') #Show message box to tell user to shut off the controller message=("Turn off the telescope controller to stop tracking"+ " and remain in park position!") messagebox.showinfo("Information",message=message,parent=self.master) return 0 def primary_mirror_pos_buttonclick(self): """Slew Telescope to Primary Mirror Cover Position. Uses LX200Commands primary_mirror_pos. """ super().primary_mirror_pos() self.refresh_target_alt_az_ha(call_itself=False) self.wait_for_slew_finish() def secondary_mirror_pos_buttonclick(self): """Slew Telescope to Secondary Mirror Cover Position. Uses LX200Commands secondary_mirror_pos. """ super().secondary_mirror_pos() self.refresh_target_alt_az_ha(call_itself=False) self.wait_for_slew_finish() def set_target_coordinates_gui(self): """ Calls set_target_coordinates() of Lx200Commands. Defines GUIs reaction to target_coordinates. """ #Call set_target_coordinates if not self.set_target_coordinates(): self.slew_target_button.config(state='disabled') self.display_alt_az('red') #Also plot target coordinates self.plot_star_and_traj() return 0 else: #Display target_alt and az self.slew_target_button.config(state='normal') self.display_alt_az('light green') #Also plot target coordinates self.plot_star_and_traj() def display_alt_az(self,color): """Displays alt and az with given color. Convenience function. """ self.target_alt_display.config(text=self.target_alt) self.target_alt_display.config(bg=color) self.target_az_display.config(text=self.target_az) self.target_az_display.config(bg=color) self.target_time_display.config(text=self.target_obs_time) self.target_time_display.config(bg=color) def set_hip_target_from_entry(self, event): """ Gets a HIP number from the HIP_entry widget and calculates the coordinates. Sets these coordinates as target_ra and target_dec and displays them in the corresponding entry widgets. """ hip_nr=self.HIP_entry.get() super().set_hip_target(hip_nr) self.target_ra_entry.delete(0, END) self.target_ra_entry.insert(0, self.target_ra) self.target_dec_entry.delete(0, END) self.target_dec_entry.insert(0, self.target_dec) self.set_target_coordinates_gui() def set_target_ra_from_entry(self, event): """ Gets a ra input from the target_ra_entry widget and sets it as target_ra. Accepted formats include hh mm ss and hh mm.t. Also tries to set set target dec from entry. Clears text of HIP_entry widget. """ #Delete hip entry self.HIP_entry.delete(0, END) #Get ra input and set as target_ra ra_input=self.target_ra_entry.get() super().set_target_ra_from_string(ra_input) self.target_ra_entry.delete(0, END) self.target_ra_entry.insert(0, self.target_ra) #Try to get dec entry also dec_input=self.target_dec_entry.get() #If dec entry is empty do not try to set target_dec if not dec_input=='': super().set_target_dec_from_string(dec_input) self.target_dec_entry.delete(0, END) self.target_dec_entry.insert(0, self.target_dec) self.set_target_coordinates_gui() def set_target_dec_from_entry(self, event): """ Gets a dec input from the target_dec_entry widget and sets it as target_ra. Accepted formats include dd mm ss and dd mm. Clears text of HIP_entry widget. """ #Delete hip entry #Get dec input and set as target_dec self.HIP_entry.delete(0, END) dec_input=self.target_dec_entry.get() super().set_target_dec_from_string(dec_input) self.target_dec_entry.delete(0, END) self.target_dec_entry.insert(0, self.target_dec) #Try to get ra entry also ra_input=self.target_ra_entry.get() #If ra entry is empty do not try to set target_ra if not ra_input=='': super().set_target_ra_from_string(ra_input) self.target_ra_entry.delete(0, END) self.target_ra_entry.insert(0, self.target_ra) self.set_target_coordinates_gui() def sync_yes_no(self): """Displays yes/no message if sync_button is clicked on. """ result=messagebox.askyesno("Synchroniziation", "Do you really want to synchronize coordinates with target coordinates?") if result: self.sync_on_target_buttonclick() def sync_on_target_buttonclick(self): """Gets target coordinates from entries. Synchronizes coordinates with target coordinates. In Case of Hipparcos target it will recalculate target coordinates at time of synchronization. """ hip_nr=self.HIP_entry.get() if hip_nr!='': super().sync_on_hip(hip_nr) self.target_ra_entry.delete(0, END) self.target_ra_entry.insert(0, self.target_ra) self.target_dec_entry.delete(0, END) self.target_dec_entry.insert(0, self.target_dec) else: #If no Hip target_ get coordinates from entries #Calling one entry is enough since always both entries are checked #None refers to no event (such as Return) self.set_target_ra_from_entry(None) if hip_nr=='' and self.target_ra and self.target_dec: super().sync_on_coordinates() else: print('No valid coordinates set. Synchronisation stopped') #After sync (and if something went wrong): #Set all valid_target entries to 0 (controller won't let you slew to #the same coordinates twice self.valid_target=[0,0] self.slew_target_button.config(state='disabled') def wait_for_slew_finish(self,call_itself=True): """Waits until coordinates equal target coordinates within tolerance. Disables all (except STOP) buttons until target coordinates are reached. call_itself determines if funtion will call itself after 1 second. This is very useful to set to False if you want to call waiting from different function that should pause until waiting is over. Can be stopped by stop_waiting. """ #Disable all buttons self.disable_all_buttons() #Check if slew has finished or self.stop_waiting parameter=True #Enable buttons if so. #self.stop_waiting parameter can be set by button in menubar #Then break the loop if super().slew_finished(): #Enable all buttons again self.enable_all_buttons() return True else: #If variable call_itself is true #Calls itself after 1 second. #After call is asigned to global variable waiting #to stop it via stop_waiting. if call_itself: global waiting waiting=self.master.after(1000,self.wait_for_slew_finish) return False def stop_waiting(self): """Stops Waiting for slew to finish and enables all buttons. Can be called in the menu. """ #First disable all buttons to avoid binding events more than once. self.disable_all_buttons() #Enable all buttons self.enable_all_buttons() #And try to stop waiting if waiting is going on. try: self.master.after_cancel(waiting) except NameError: return 0 def delete_entries(self,event): """ Deletes entries of target_ra and target_dec. Used when entering new Hipparcos Number. """ self.target_ra_entry.delete(0,END) self.target_dec_entry.delete(0,END) def disable_all_buttons(self): """ Disables all buttons and unbinds all bindings. Except of Stop Button """ #Disable all buttons #We also need to unbind the buttons which are called by events instead of commands for child in self.control_frame.winfo_children(): child.config(state='disabled') child.unbind("<ButtonPress-1>") child.unbind("<ButtonRelease-1>") #Enable Stop Button again. It should always be enabled. self.stop_button.config(state='normal') #Disable and unbind entry widgets in target_frame for child in self.target_frame.winfo_children(): child.config(state='disabled') child.unbind("<Return>") child.unbind("<Tab>") self.sync_button.config(state='disabled') #Radiobuttons for child in self.radiobutton_frame.winfo_children(): child.config(state='disabled') def enable_all_buttons(self): """ Enables all buttons and binds all bindings. Except of Stop Button. All bindings are defined here, except of commands of buttons. """ #Disable all buttons #We also need to bind the buttons which are called by events instead of commands for child in self.control_frame.winfo_children(): child.config(state='normal') #Add the bindings manually self.north_button.bind("<ButtonPress-1>",self.start_move_north_buttonclick) self.north_button.bind("<ButtonRelease-1>",self.stop_move_north_buttonclick) self.west_button.bind("<ButtonPress-1>",self.start_move_west_buttonclick) self.west_button.bind("<ButtonRelease-1>",self.stop_move_west_buttonclick) self.south_button.bind("<ButtonPress-1>",self.start_move_south_buttonclick) self.south_button.bind("<ButtonRelease-1>",self.stop_move_south_buttonclick) self.east_button.bind("<ButtonPress-1>",self.start_move_east_buttonclick) self.east_button.bind("<ButtonRelease-1>",self.stop_move_east_buttonclick) self.sync_button.config(state='normal') #Enable and bind entry widgets in target_frame for child in self.target_frame.winfo_children(): child.config(state='normal') #Do not enable slew button self.slew_target_button.config(state='disabled') #Add the bindings manually #When entering any new number or char (also when deleting), #the entries of target_ra and target_dec should be deleted #Important to bind Return and Tab after this first binding to override this functionality #Otherwise it would also just delete the entries self.HIP_entry.bind("<Key>", self.delete_entries,add='+') self.HIP_entry.bind("<Return>", self.set_hip_target_from_entry, add="+") self.HIP_entry.bind("<Tab>", self.set_hip_target_from_entry, add="+") self.target_ra_entry.bind("<Return>", self.set_target_ra_from_entry, add="+") self.target_ra_entry.bind("<Tab>", self.set_target_ra_from_entry,add="+") self.target_dec_entry.bind("<Return>", self.set_target_dec_from_entry, add="+") self.target_dec_entry.bind("<Tab>", self.set_target_dec_from_entry, add="+") #Radiobuttons for child in self.radiobutton_frame.winfo_children(): child.config(state='normal') def save_pointing_star(self): """ Saves Pointings Stars Information to file. Takes Hipparcos Number, RA, DEC LST and Date and saves to file. Also Saves Hipparcos Number, RA, DEC, HA, target_ra, target_dec, LST, UTC and Date to second file. This could lead to potentially new system of pointing_star data. This could be easier to handle. Not done yet. """ ### Traditional File ### try: hipparcos=self.HIP_entry.get() #Need integer to catch errors and for formatting hipparcos=int(hipparcos) #Format Hipparcos Number to 000123 hip_pointing="{:06d}".format(hipparcos) except ValueError: print('Invalid Hiparcos number') return 0 #Format RA to hh mm ss (RA_hours,h,rest)=self.ra.partition('h') (RA_min,m,rest)=rest.partition('m') (RA_sec,s,rest)=rest.partition('s') RA_pointing="{} {} {}".format(RA_hours, RA_min, RA_sec) #Format DEC to +dd mm ss (DEC_deg,grad,rest)=self.dec.partition('°') (DEC_min,m,rest)=rest.partition("'") (DEC_sec,s,rest)=rest.partition('"') DEC_pointing="{} {} {}".format(DEC_deg, DEC_min, DEC_sec) #Format LST to hh mm ss (LST_hours,h,rest)=self.LST.partition(':') (LST_min,m,rest)=rest.partition(':') (LST_sec,s,rest)=rest.partition(':') LST_pointing="{} {} {}".format(LST_hours, LST_min, LST_sec) #Get Date in Format dd.mm.yyyy (using locale module) today = datetime.date.today() Date_pointing=today.strftime('%d.%m.%Y') line="{} {} {} {} {}\n".format(hip_pointing, RA_pointing, DEC_pointing, LST_pointing, Date_pointing) #Filename and path using pathlib module #File is in parrent_directory/pointing_stars/pointings_stars.txt current_path=pathlib.Path.cwd() parrent_path=current_path.parent file_path=parrent_path / 'pointing_stars' / 'pointing_stars.txt' #With automatically closes the file in the end with open(str(file_path), 'a') as ps_file: print('Saving pointing star to (old format) file') ps_file.write(line) ### New Format File ### #Format HA to hh mm ss (HA_hours,h,rest)=self.ha.partition('h') (HA_min,m,rest)=rest.partition('m') (HA_sec,s,rest)=rest.partition('s') HA_pointing="{} {} {}".format(HA_hours, HA_min, HA_sec) line=("{} {} {} {} {} {} {} {} {}" " {} {} {} {} {} {}\n") line=line.format(hip_pointing, RA_pointing, self.ra_float, DEC_pointing, self.dec_float, HA_pointing, self.ha_float, self.target_ra, self.target_ra_float, self.target_dec, self.target_dec_float, self.target_ha_float, self.LST, self.UTC, Date_pointing) #Filename and path using pathlib module #File is in parrent_directory/pointing_stars/pointings_stars_new_format.txt current_path=pathlib.Path.cwd() parrent_path=current_path.parent file_path=parrent_path / 'pointing_stars' / 'pointing_stars_new_format.txt' #With automatically closes the file in the end with open(str(file_path), 'a') as ps_file: print('Saving pointing star to (new format) file') ps_file.write(line)
def closeAndStartUmineko(): rootWindow.withdraw() mainUmineko() installFinishedMessage = "Install Finished. Temporary install files have been displayed - please delete the " \ "temporary files after checking the mod has installed correctly." print(installFinishedMessage) messagebox.showinfo("Install Completed", installFinishedMessage) rootWindow.destroy() # Add an 'OK' button. When pressed, the dialog is closed defaultPadding = {"padx": 20, "pady": 10} b = tkinter.Button(rootWindow, text="Install Higurashi Mods", command=closeAndStartHigurashi) b.pack(**defaultPadding) b = tkinter.Button(rootWindow, text="Install Umineko Mods", command=closeAndStartUmineko) b.pack(**defaultPadding) tkinter.Label(rootWindow, text="Advanced Settings").pack() # Add a checkbox to enable/disable IPV6. IPV6 is disabled by default due to some # installations failing when IPV6 is used due to misconfigured routers/other problems. use_ipv6_var = IntVar() def onIPV6CheckboxToggled(): GLOBAL_SETTINGS.USE_IPV6 = use_ipv6_var.get() c = Checkbutton(rootWindow, text="Enable IPv6", var=use_ipv6_var, command=onIPV6CheckboxToggled) c.pack() rootWindow.mainloop()
calDateReached.pack() frame3.pack() # ---------------------------------------------------------------------------------- frame4 = Frame(window) DDLbl = Label(frame4, text="Date Date Reached") calDateToday = Calendar(frame4, font="Arial 14", selectmode='day', locale='en_US', cursor="hand1", year=LTD.year, month=LTD.month, day=LTD.day) CheckVar1 = IntVar() C1 = Checkbutton(frame4, text="Today", variable=CheckVar1, onvalue=1, offvalue=0) DDLbl.pack(side=LEFT, padx=45, pady=30) calDateToday.pack(pady=30) C1.pack() frame4.pack() # ---------------------------------------------------------------------------------- frame5 = Frame(window) inputLastEpisodePlaceLbl = Label(frame5, text="Last Episode Place")
class DistanceFuncFrame(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.isCalcDistanceMode = BooleanVar() self.isCriticalShortest = BooleanVar() self.cbCalcDistance = Checkbutton( self, variable=self.isCalcDistanceMode, text="calculate distance mode", command=self.on_calc_distance_mode_clicked) self.cbCriticalShortest = Checkbutton(self, variable=self.isCriticalShortest, text="critical") self.cbCalcDistance.deselect() self.cbCriticalShortest.deselect() self.lblStartPos = Label(self) self.lblEndPos = Label(self) self.lblDistance = Label(self) self.firstPosRow = INVALID_ROW self.firstPosCol = INVALID_COL Label(self).pack(expand=1) Label(self).pack(expand=1) self.cbCalcDistance.pack(expand=1) self.cbCriticalShortest.pack(expand=1) self.lblStartPos.pack(expand=1) self.lblEndPos.pack(expand=1) self.lblDistance.pack(expand=1) evtDispatcher.register(EvtIds.EVT_FIRST_POSITION_SELECTED, self.handle_first_position_selected) evtDispatcher.register(EvtIds.EVT_SECOND_POSITION_SELECTED, self.handle_second_position_selected) evtDispatcher.register(EvtIds.EVT_SHORTEST_DISTANCE_CALCULATED, self.handle_shortest_distance_calculated) def handle_first_position_selected(self, content): if content is None or content["row"] is None or content["col"] is None: return self.lblEndPos.config(text="") self.lblDistance.config(text="") self.lblStartPos.config(text="POS1: (%d, %d)" % (content["col"], content["row"])) self.firstPosRow = content["row"] self.firstPosCol = content["col"] def handle_second_position_selected(self, content): if content is None or content["row"] is None or content["col"] is None: return self.lblEndPos.config(text="POS2: (%d, %d)" % (content["col"], content["row"])) self.lblDistance.config(text="calculating...") self.update() evtDispatcher.dispatch( EvtIds.EVT_INFORM_CALC_DISTANCE, { "row1": self.firstPosRow, "col1": self.firstPosCol, "row2": content["row"], "col2": content["col"], "isCriticalShortest": self.isCriticalShortest.get() }) def handle_shortest_distance_calculated(self, content): if content is None or content["distance"] is None: return if content["distance"] == UNREACH_DISTANCE: self.lblDistance.config(text="UNREACHABLE") return res = "Shortest Distance: %d" % content["distance"] if not self.isCriticalShortest.get(): res = "Possible Shortest Distance: %d" % content["distance"] self.lblDistance.config(text=res) def on_calc_distance_mode_clicked(self): if not self.isCalcDistanceMode.get(): self.clean() self.cbCriticalShortest.deselect() evtDispatcher.dispatch(EvtIds.EVT_SET_CALC_DISTANCE_MODE, {"mode": self.isCalcDistanceMode.get()}) def clean(self): self.lblStartPos.config(text="") self.lblEndPos.config(text="") self.lblDistance.config(text="")
name = StringVar() name.set('随机滚动:') last_name = StringVar() last_name.set('被点名:') # 滚动文本 round_text = Label(gui, height=1, textvariable=name, font=('SimHei', 15), fg='#000000') round_text.pack() # 最终显示文本 name_text = Label(gui, height=1, textvariable=last_name, font=('SimHei', 15), fg='#FF7F00') name_text.pack() # 按钮 btn1 = Button(gui, text='开始点名', bg='#32CD32', fg='#ffffff', font=('SimHei', 15), command=run) btn1.pack() # 复选框 CheckVar1 = IntVar() label_again = Checkbutton(gui, text='重复点名', onvalue=1, offvalue=0, variable=CheckVar1, font=('SimHei', 15)) label_again.pack() # 背景图 bgImage = ImageTk.PhotoImage((Image.open('./background.jpg')).resize((240, 180))) img = Label(gui, image=bgImage) img.pack() mainloop()
def __init__(self, root): self.root = root self.root.title("Registeration Window") self.root.geometry("1357x700+0+0") self.root.config(bg="white") # ===BG Image=== self.bg = ImageTk.PhotoImage(file="images/862206.jpg") bg = Label(self.root, image=self.bg).place(x=0, y=0, relwidth=1, relheight=1) # ===Left Image=== self.left = ImageTk.PhotoImage(file="images/harvey.jpg") left = Label(self.root, image=self.left).place(x=30, y=95, relwidth=0.33, relheight=0.73) # ====Register Frame==== frame1: Frame = Frame(self.root, bg="white") frame1.place(x=480, y=100, width=700, height=500) title = Label(frame1, text="Register Here", font=("Arial", 20, "bold"), bg="white", fg="blue").place(x=50, y=30) # --------------Row1 f_name = Label(frame1, text="First Name", font=("Arial", 15, "bold"), bg="white", fg="grey").place(x=50, y=100) self.txt_fname = Entry(frame1, font=("times new roman", 15), bg="lightgray") self.txt_fname.place(x=50, y=130, width=250) l_name = Label(frame1, text="Last Name", font=("Arial", 15, "bold"), bg="white", fg="grey").place(x=370, y=100) self.txt_lname = Entry(frame1, font=("times new roman", 15), bg="lightgray") self.txt_lname.place(x=370, y=130, width=250) #--------------Row2 contact = Label(frame1, text="Contact", font=("Arial", 15, "bold"), bg="white", fg="grey").place(x=50, y=155) self.txt_contact = Entry(frame1, font=("times new roman", 15), bg="lightgray") self.txt_contact.place(x=50, y=185, width=250) email = Label(frame1, text="Email", font=("Arial", 15, "bold"), bg="white", fg="grey").place(x=370, y=155) self.txt_email = Entry(frame1, font=("times new roman", 15), bg="lightgray") self.txt_email.place(x=370, y=185, width=250) # --------------Row3 question = Label(frame1, text="Security Question", font=("Arial", 15, "bold"), bg="white", fg="grey").place(x=50, y=220) self.cmb_question = ttk.Combobox(frame1, font=("times new roman", 13), state='readonly') self.cmb_question['values'] = ("select", "Your pet name", "your birth place", "your birth date") self.cmb_question.place(x=50, y=245, width=250) self.cmb_question.current(0) answer = Label(frame1, text="Answer", font=("Arial", 15, "bold"), bg="white", fg="grey").place(x=370, y=220) self.txt_answer = Entry(frame1, font=("times new roman", 15), bg="lightgray") self.txt_answer.place(x=370, y=245, width=250) # --------------Row4 password = Label(frame1, text="Password", font=("Arial", 15, "bold"), bg="white", fg="grey").place(x=50, y=275) self.txt_password = Entry(frame1, font=("times new roman", 15), bg="lightgray") self.txt_password.place(x=50, y=300, width=250) cpassword = Label(frame1, text="Confirm Password", font=("Arial", 15, "bold"), bg="white", fg="grey").place(x=370, y=275) self.txt_cpassword = Entry(frame1, font=("times new roman", 15), bg="lightgray") self.txt_cpassword.place(x=370, y=300, width=250) #------terms-------- self.var_chk = IntVar() chk = Checkbutton(frame1, text="I agree The terms and conditions", variable=self.var_chk, onvalue=1, offvalue=0, bg="white").place(x=50, y=340, width=250) self.btn_img = ImageTk.PhotoImage(file="images/regyy.jpg") btn_register = Button(frame1, image=self.btn_img, bd=0, cursor="hand2", command=self.register_data).place(x=50, y=420, relwidth=0.8, relheight=0.1) btn_2 = Button(self.root, text="Sing In", font=("arial", 20), bd=0, cursor="hand2", command=self.login_window).place(x=130, y=500, relwidth=0.2, relheight=0.05)
scale = Scale(from_=0, to=100, command=scale_used) scale.pack() # Checkbutton def checkbutton_used(): # Prints 1 if On button checked, otherwise 0. print(checked_state.get()) # variable to hold on to checked state, 0 is off, 1 is on. checked_state = IntVar() checkbutton = Checkbutton( text="Is On?", variable=checked_state, command=checkbutton_used ) checked_state.get() checkbutton.pack() # Radiobutton def radio_used(): print(radio_state.get()) # Variable to hold on to which radio button value is checked. radio_state = IntVar() radiobutton1 = Radiobutton( text="Option1", value=1, variable=radio_state, command=radio_used )
def guiMain(settings=None): frames = {} mainWindow = Tk() mainWindow.wm_title("OoT Randomizer %s" % ESVersion) mainWindow.resizable(False, False) set_icon(mainWindow) notebook = ttk.Notebook(mainWindow) frames['rom_tab'] = ttk.Frame(notebook) frames['rules_tab'] = ttk.Frame(notebook) frames['logic_tab'] = ttk.Frame(notebook) frames['other_tab'] = ttk.Frame(notebook) frames['aesthetic_tab'] = ttk.Frame(notebook) frames['aesthetic_tab_left'] = Frame(frames['aesthetic_tab']) frames['aesthetic_tab_right'] = Frame(frames['aesthetic_tab']) adjustWindow = ttk.Frame(notebook) customWindow = ttk.Frame(notebook) notebook.add(frames['rom_tab'], text='ROM Options') notebook.add(frames['rules_tab'], text='Main Rules') notebook.add(frames['logic_tab'], text='Detailed Logic') notebook.add(frames['other_tab'], text='Other') notebook.add(frames['aesthetic_tab'], text='Cosmetics') ####################### # randomizer controls # ####################### # hold the results of the user's decisions here guivars = {} # hierarchy ############ #Rules Tab frames['open'] = LabelFrame(frames['rules_tab'], text='Open', labelanchor=NW) frames['world'] = LabelFrame(frames['rules_tab'], text='World', labelanchor=NW) frames['logic'] = LabelFrame(frames['rules_tab'], text='Shuffle', labelanchor=NW) # Logic tab frames['rewards'] = LabelFrame(frames['logic_tab'], text='Remove Specific Locations', labelanchor=NW) frames['tricks'] = LabelFrame(frames['logic_tab'], text='Specific expected tricks', labelanchor=NW) #Other Tab frames['convenience'] = LabelFrame(frames['other_tab'], text='Speed Ups', labelanchor=NW) frames['other'] = LabelFrame(frames['other_tab'], text='Misc', labelanchor=NW) #Aesthetics tab frames['cosmetics'] = LabelFrame(frames['aesthetic_tab'], text='General', labelanchor=NW) frames['tuniccolor'] = LabelFrame(frames['aesthetic_tab_left'], text='Tunic Color', labelanchor=NW) frames['navicolor'] = LabelFrame(frames['aesthetic_tab_right'], text='Navi Color', labelanchor=NW) frames['lowhp'] = LabelFrame(frames['aesthetic_tab_left'], text='Low HP SFX', labelanchor=NW) frames['navihint'] = LabelFrame(frames['aesthetic_tab_right'], text='Navi SFX', labelanchor=NW) # shared settingsFrame = Frame(mainWindow) settings_string_var = StringVar() settingsEntry = Entry(settingsFrame, textvariable=settings_string_var, width=25) def show_settings(event=None): settings = guivars_to_settings(guivars) settings_string_var.set(settings.get_settings_string()) # Update any dependencies for info in setting_infos: if info.gui_params and 'dependency' in info.gui_params: dep_met = info.gui_params['dependency'](guivars) if widgets[info.name].winfo_class() == 'Frame': for child in widgets[info.name].winfo_children(): if child.winfo_class() == 'TCombobox': child.configure( state='readonly' if dep_met else 'disabled') else: child.configure( state='normal' if dep_met else 'disabled') if child.winfo_class() == 'Scale': child.configure(fg='Black' if dep_met else 'Grey') else: if widgets[info.name].winfo_class() == 'TCombobox': widgets[info.name].configure( state='readonly' if dep_met else 'disabled') else: widgets[info.name].configure( state='normal' if dep_met else 'disabled') if widgets[info.name].winfo_class() == 'Scale': widgets[info.name].configure( fg='Black' if dep_met else 'Grey') if info.name in guivars and guivars[ info.name].get() == 'Custom Color': color = askcolor() if color == (None, None): color = ((0, 0, 0), '#000000') guivars[info.name].set('Custom (' + color[1] + ')') def show_settings_special(event=None): if guivars['logic_tricks'].get(): widgets['logic_man_on_roof'].select() widgets['logic_child_deadhand'].select() widgets['logic_dc_jump'].select() widgets['logic_windmill_poh'].select() widgets['logic_crater_bean_poh_with_hovers'].select() widgets['logic_zora_with_cucco'].select() widgets['logic_fewer_tunic_requirements'].select() else: widgets['logic_man_on_roof'].deselect() widgets['logic_child_deadhand'].deselect() widgets['logic_dc_jump'].deselect() widgets['logic_windmill_poh'].deselect() widgets['logic_crater_bean_poh_with_hovers'].deselect() widgets['logic_zora_with_cucco'].deselect() widgets['logic_fewer_tunic_requirements'].deselect() settings = guivars_to_settings(guivars) settings_string_var.set(settings.get_settings_string()) def import_settings(event=None): try: settings = guivars_to_settings(guivars) text = settings_string_var.get().upper() settings.seed = guivars['seed'].get() settings.update_with_settings_string(text) settings_to_guivars(settings, guivars) except Exception as e: messagebox.showerror(title="Error", message="Invalid settings string") label = Label(settingsFrame, text="Settings String") importSettingsButton = Button(settingsFrame, text='Import Settings String', command=import_settings) label.pack(side=LEFT, anchor=W, padx=5) settingsEntry.pack(side=LEFT, anchor=W) importSettingsButton.pack(side=LEFT, anchor=W, padx=5) fileDialogFrame = Frame(frames['rom_tab']) romDialogFrame = Frame(fileDialogFrame) baseRomLabel = Label(romDialogFrame, text='Base ROM') guivars['rom'] = StringVar(value='ZOOTDEC.z64') romEntry = Entry(romDialogFrame, textvariable=guivars['rom'], width=40) def RomSelect(): rom = filedialog.askopenfilename( filetypes=[("ROM Files", (".z64", ".n64")), ("All Files", "*")]) if rom != '': guivars['rom'].set(rom) romSelectButton = Button(romDialogFrame, text='Select ROM', command=RomSelect, width=10) baseRomLabel.pack(side=LEFT, padx=(38, 0)) romEntry.pack(side=LEFT, padx=3) romSelectButton.pack(side=LEFT) romDialogFrame.pack() fileDialogFrame.pack(side=TOP, anchor=W, padx=5, pady=(5, 1)) def open_output(): open_file(output_path('')) def output_dir_select(): rom = filedialog.askdirectory( initialdir=default_output_path(guivars['output_dir'].get())) if rom != '': guivars['output_dir'].set(rom) outputDialogFrame = Frame(frames['rom_tab']) outputDirLabel = Label(outputDialogFrame, text='Output Directory') guivars['output_dir'] = StringVar(value='') outputDirEntry = Entry(outputDialogFrame, textvariable=guivars['output_dir'], width=40) outputDirButton = Button(outputDialogFrame, text='Select Dir', command=output_dir_select, width=10) outputDirLabel.pack(side=LEFT, padx=(3, 0)) outputDirEntry.pack(side=LEFT, padx=3) outputDirButton.pack(side=LEFT) outputDialogFrame.pack(side=TOP, anchor=W, padx=5, pady=(5, 1)) if os.path.exists(local_path('README.html')): def open_readme(): open_file(local_path('README.html')) openReadmeButton = Button(outputDialogFrame, text='Open Documentation', command=open_readme) openReadmeButton.pack(side=LEFT, padx=5) outputDialogFrame.pack(side=TOP, anchor=W, pady=3) countDialogFrame = Frame(frames['rom_tab']) countLabel = Label(countDialogFrame, text='Generation Count') guivars['count'] = StringVar() countSpinbox = Spinbox(countDialogFrame, from_=1, to=100, textvariable=guivars['count'], width=3) countLabel.pack(side=LEFT) countSpinbox.pack(side=LEFT, padx=2) countDialogFrame.pack(side=TOP, anchor=W, padx=5, pady=(1, 1)) # build gui ############ widgets = {} for info in setting_infos: if info.gui_params: if info.gui_params['widget'] == 'Checkbutton': # determine the initial value of the checkbox default_value = 1 if info.gui_params[ 'default'] == "checked" else 0 # create a variable to access the box's state guivars[info.name] = IntVar(value=default_value) # create the checkbox widgets[info.name] = Checkbutton( frames[info.gui_params['group']], text=info.gui_params['text'], variable=guivars[info.name], justify=LEFT, wraplength=190, command=show_settings) widgets[info.name].pack(expand=False, anchor=W) if info.gui_params['widget'] == 'SpecialCheckbutton': # determine the initial value of the checkbox default_value = 1 if info.gui_params[ 'default'] == "checked" else 0 # create a variable to access the box's state guivars[info.name] = IntVar(value=default_value) # create the checkbox widgets[info.name] = Checkbutton( frames[info.gui_params['group']], text=info.gui_params['text'], variable=guivars[info.name], justify=LEFT, wraplength=190, command=show_settings_special) widgets[info.name].pack(expand=False, anchor=W) elif info.gui_params['widget'] == 'Combobox': # create the variable to store the user's decision guivars[info.name] = StringVar( value=info.gui_params['default']) # create the option menu widgets[info.name] = Frame(frames[info.gui_params['group']]) # dropdown = OptionMenu(widgets[info.name], guivars[info.name], *(info['options'])) if isinstance(info.gui_params['options'], list): info.gui_params['options'] = dict( zip(info.gui_params['options'], info.gui_params['options'])) dropdown = ttk.Combobox(widgets[info.name], textvariable=guivars[info.name], values=list( info.gui_params['options'].keys()), state='readonly', width=30) dropdown.bind("<<ComboboxSelected>>", show_settings) dropdown.pack(side=BOTTOM, anchor=W) # label the option if 'text' in info.gui_params: label = Label(widgets[info.name], text=info.gui_params['text']) label.pack(side=LEFT, anchor=W, padx=5) # pack the frame widgets[info.name].pack(expand=False, side=TOP, anchor=W, padx=3, pady=3) elif info.gui_params['widget'] == 'Radiobutton': # create the variable to store the user's decision guivars[info.name] = StringVar( value=info.gui_params['default']) # create the option menu widgets[info.name] = LabelFrame( frames[info.gui_params['group']], text=info.gui_params['text'] if 'text' in info.gui_params else info["name"], labelanchor=NW) if isinstance(info.gui_params['options'], list): info.gui_params['options'] = dict( zip(info.gui_params['options'], info.gui_params['options'])) # setup orientation side = TOP anchor = W if "horizontal" in info.gui_params and info.gui_params[ "horizontal"]: side = LEFT anchor = N # add the radio buttons for option in info.gui_params["options"]: radio_button = Radiobutton(widgets[info.name], text=option, value=option, variable=guivars[info.name], justify=LEFT, wraplength=190, indicatoron=False, command=show_settings) radio_button.pack(expand=True, side=side, anchor=anchor) # pack the frame widgets[info.name].pack(expand=False, side=TOP, anchor=W, padx=3, pady=3) elif info.gui_params['widget'] == 'Scale': # create the variable to store the user's decision guivars[info.name] = IntVar(value=info.gui_params['default']) # create the option menu widgets[info.name] = Frame(frames[info.gui_params['group']]) # dropdown = OptionMenu(widgets[info.name], guivars[info.name], *(info['options'])) minval = 'min' in info.gui_params and info.gui_params[ 'min'] or 0 maxval = 'max' in info.gui_params and info.gui_params[ 'max'] or 100 stepval = 'step' in info.gui_params and info.gui_params[ 'step'] or 1 scale = Scale(widgets[info.name], variable=guivars[info.name], from_=minval, to=maxval, tickinterval=stepval, resolution=stepval, showvalue=0, orient=HORIZONTAL, sliderlength=15, length=200, command=show_settings) scale.pack(side=BOTTOM, anchor=W) # label the option if 'text' in info.gui_params: label = Label(widgets[info.name], text=info.gui_params['text']) label.pack(side=LEFT, anchor=W, padx=5) # pack the frame widgets[info.name].pack(expand=False, side=TOP, anchor=W, padx=3, pady=3) elif info.gui_params['widget'] == 'Entry': # create the variable to store the user's decision guivars[info.name] = StringVar( value=info.gui_params['default']) # create the option menu widgets[info.name] = Frame(frames[info.gui_params['group']]) entry = Entry(widgets[info.name], textvariable=guivars[info.name], width=30) entry.pack(side=BOTTOM, anchor=W) # label the option if 'text' in info.gui_params: label = Label(widgets[info.name], text=info.gui_params['text']) label.pack(side=LEFT, anchor=W, padx=5) # pack the frame widgets[info.name].pack(expand=False, side=TOP, anchor=W, padx=3, pady=3) if 'tooltip' in info.gui_params: ToolTips.register(widgets[info.name], info.gui_params['tooltip']) # pack the hierarchy frames['logic'].pack(fill=BOTH, expand=True, anchor=N, side=RIGHT, pady=(5, 1)) frames['open'].pack(fill=BOTH, expand=True, anchor=W, side=TOP, pady=(5, 1)) frames['world'].pack(fill=BOTH, expand=True, anchor=W, side=BOTTOM, pady=(5, 1)) # Logic tab frames['rewards'].pack(fill=BOTH, expand=True, anchor=N, side=LEFT, pady=(5, 1)) frames['tricks'].pack(fill=BOTH, expand=True, anchor=N, side=LEFT, pady=(5, 1)) #Other Tab frames['convenience'].pack(fill=BOTH, expand=True, anchor=N, side=LEFT, pady=(5, 1)) frames['other'].pack(fill=BOTH, expand=True, anchor=N, side=LEFT, pady=(5, 1)) #Aesthetics tab frames['cosmetics'].pack(fill=BOTH, expand=True, anchor=W, side=TOP) frames['aesthetic_tab_left'].pack(fill=BOTH, expand=True, anchor=W, side=LEFT) frames['aesthetic_tab_right'].pack(fill=BOTH, expand=True, anchor=W, side=RIGHT) #Aesthetics tab - Left Side frames['tuniccolor'].pack(fill=BOTH, expand=True, anchor=W, side=TOP, pady=(5, 1)) frames['lowhp'].pack(fill=BOTH, expand=True, anchor=W, side=TOP, pady=(5, 1)) #Aesthetics tab - Right Side frames['navicolor'].pack(fill=BOTH, expand=True, anchor=W, side=TOP, pady=(5, 1)) frames['navihint'].pack(fill=BOTH, expand=True, anchor=W, side=TOP, pady=(5, 1)) notebook.pack(fill=BOTH, expand=True, padx=5, pady=5) multiworldFrame = LabelFrame(frames['rom_tab'], text='Multi-World Generation') countLabel = Label( multiworldFrame, wraplength=350, justify=LEFT, text= 'This is used for co-op generations. Increasing Player Count will drastically increase the generation time. For more information see:' ) hyperLabel = Label(multiworldFrame, wraplength=350, justify=LEFT, text='https://github.com/TestRunnerSRL/bizhawk-co-op', fg='blue', cursor='hand2') hyperLabel.bind( "<Button-1>", lambda event: webbrowser.open_new( r"https://github.com/TestRunnerSRL/bizhawk-co-op")) countLabel.pack(side=TOP, anchor=W, padx=5, pady=0) hyperLabel.pack(side=TOP, anchor=W, padx=5, pady=0) worldCountFrame = Frame(multiworldFrame) countLabel = Label(worldCountFrame, text='Player Count') guivars['world_count'] = StringVar() countSpinbox = Spinbox(worldCountFrame, from_=1, to=100, textvariable=guivars['world_count'], width=3) countLabel.pack(side=LEFT) countSpinbox.pack(side=LEFT, padx=2) worldCountFrame.pack(side=LEFT, anchor=N, padx=10, pady=(1, 5)) playerNumFrame = Frame(multiworldFrame) countLabel = Label(playerNumFrame, text='Player ID') guivars['player_num'] = StringVar() countSpinbox = Spinbox(playerNumFrame, from_=1, to=100, textvariable=guivars['player_num'], width=3) countLabel.pack(side=LEFT) countSpinbox.pack(side=LEFT, padx=2) playerNumFrame.pack(side=LEFT, anchor=N, padx=10, pady=(1, 5)) multiworldFrame.pack(side=TOP, anchor=W, padx=5, pady=(1, 1)) # didn't refactor the rest, sorry # create the option menu settingsFrame.pack(fill=BOTH, anchor=W, padx=5, pady=(10, 0)) def multiple_run(settings, window): orig_seed = settings.seed for i in range(settings.count): settings.update_seed(orig_seed + '-' + str(i)) window.update_title("Generating Seed...%d/%d" % (i + 1, settings.count)) main(settings, window) def generateRom(): settings = guivars_to_settings(guivars) if settings.count is not None: BackgroundTaskProgress(mainWindow, "Generating Seed...", multiple_run, settings) else: BackgroundTaskProgress(mainWindow, "Generating Seed...", main, settings) generateSeedFrame = Frame(mainWindow) generateButton = Button(generateSeedFrame, text='Generate Patched Rom', command=generateRom) seedLabel = Label(generateSeedFrame, text='Seed') guivars['seed'] = StringVar() seedEntry = Entry(generateSeedFrame, textvariable=guivars['seed'], width=25) seedLabel.pack(side=LEFT, padx=(55, 5)) seedEntry.pack(side=LEFT) generateButton.pack(side=LEFT, padx=(5, 0)) generateSeedFrame.pack(side=BOTTOM, anchor=W, padx=5, pady=10) guivars['checked_version'] = StringVar() if settings is not None: # load values from commandline args settings_to_guivars(settings, guivars) else: # try to load saved settings try: settingsFile = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'settings.sav') with open(settingsFile) as f: settings = Settings(json.load(f)) settings.update_seed("") settings_to_guivars(settings, guivars) except: pass show_settings() def gui_check_version(): task = BackgroundTask(mainWindow, check_version, guivars['checked_version'].get()) while task.running: mainWindow.update() if task.status: dialog = Dialog(mainWindow, title="Version Error", question=task.status, oktext='Don\'t show again', canceltext='OK') if dialog.result: guivars['checked_version'].set(ESVersion) mainWindow.after(1000, gui_check_version) mainWindow.mainloop() # save settings on close with open('settings.sav', 'w') as outfile: settings = guivars_to_settings(guivars) json.dump(settings.__dict__, outfile)
def build_window(self): """ Generates the window. :author: Pablo Sanz Alguacil """ self.root = Toplevel() self.root.protocol("WM_DELETE_WINDOW", self.destroy_window) self.root.geometry('440x490') self.root.resizable(width=False, height=False) self.root.title('WiCC - Mac Changer Tools') # LABELFRAME - INFO self.labelframe_info = LabelFrame(self.root, text="") self.labelframe_info.pack(fill="both", expand="no", pady=15) # LABEL - INFO self.label_info = Label( self.labelframe_info, pady=15, text="In this window you can change your MAC as you want by" "\nusing one this options. A great power comes with a" "\ngreat responsibility") self.label_info.pack(side=TOP) # LABELFRAME - CUSTOM MAC self.labelframe_custom_mac = LabelFrame(self.root, text="Write custom MAC") self.labelframe_custom_mac.pack(fill="both", expand="no", pady=10) # LABEL - CUSTOM MAC self.label_custom_mac = Label(self.labelframe_custom_mac, text="Custom MAC: ") self.label_custom_mac.grid(column=1, row=0, padx=5) # ENTRY - CUSTOM MAC self.entry_custom_mac = ttk.Entry(self.labelframe_custom_mac) self.entry_custom_mac.grid(column=2, row=0, padx=8) self.entry_custom_mac.bind('<Button-3>', rClicker, add='') # BUTTON - CUSTOM MAC self.button_custom_mac = ttk.Button(self.labelframe_custom_mac, text="Set custom MAC", command=self.customize_mac) self.button_custom_mac.grid(column=4, row=0) # LABELFRAME - RANDOM MAC self.labelframe_random_mac = LabelFrame(self.root, text="Randomize MAC") self.labelframe_random_mac.pack(fill="both", expand="no", pady=10) # LABEL - RANDOM MAC self.label_random_mac = Label( self.labelframe_random_mac, text="Changes the current MAC to a completly \nrandom MAC", justify=LEFT) self.label_random_mac.grid(column=1, row=0, rowspan=2, padx=5) # BUTTON - RANDOM MAC self.button_random_mac = ttk.Button(self.labelframe_random_mac, text="Randomize MAC", command=self.randomize_mac) self.button_random_mac.grid(column=3, row=0, padx=5) # LABELFRAME - RESTORE ORIGINAL self.labelframe_restore_original = LabelFrame( self.root, text="Restore original MAC") self.labelframe_restore_original.pack(fill="both", expand="no", pady=10) # LABEL - RESTORE ORIGINAL self.label_restore_original = Label( self.labelframe_restore_original, text="Restores the original selected interface's\nMAC address", justify=LEFT) self.label_restore_original.grid(column=1, row=0, padx=5) # BUTTON - RESTORE ORIGINAL self.button_restore_original = ttk.Button( self.labelframe_restore_original, text="Restore MAC", command=self.restore_mac) self.button_restore_original.grid(column=3, row=0, padx=5) # LABELFRAME - MAC SPOOFING self.labelframe_mac_spoofing = LabelFrame(self.root, text="MAC spoofing") self.labelframe_mac_spoofing.pack(fill="both", expand="no", pady=10) # LABEL - MAC SPOOFING) self.label_mac_spoofing = Label( self.labelframe_mac_spoofing, text="Spoof client's MAC address during attack") self.label_mac_spoofing.grid(column=1, row=0, padx=5) # CHECKBUTTON - MAC SPOOFING self.checkbutton_mac_spoofing = Checkbutton( self.labelframe_mac_spoofing, text="Active", command=self.mac_spoofing) self.checkbutton_mac_spoofing.grid(column=3, row=0, padx=5) # BUTTON - DONE self.button_done = ttk.Button(self.root, text="Done", command=self.destroy_window) self.button_done.pack(padx=15, pady=15)
class SettingsBackgroundFrame: def __init__(self, parent, fields: SettingsGUIFields): self.frame = Frame(parent.master, bd=2, relief=GROOVE) self.parent = parent self.fields = fields self.dimensionCheckbutton = BooleanVar() self.doNotUseBgCheckbutton = BooleanVar() if self.fields.VAR_PATH_WINDOW_BG_IMAGE == "": self.doNotUseBgCheckbutton.set(True) ROW_BG_SETTINGS = 0 ROW_BG_COLOR = 1 ROW_BG_IMAGE = 2 ROW_SET_DIMENSIONS = 3 ROW_DO_NOT_USE_BG = 4 bgColorFrame = Frame(self.frame) self.LABEL_WINDOW_BG_COLOR = Label( bgColorFrame, textvariable=fields.VAR_LABEL_WINDOW_BG_COLOR_TEXT) Label(self.frame, text="Background Settings").grid(row=ROW_BG_SETTINGS, column=0, sticky=W) self.BUTTON_WINDOW_BG_COLOR = HoverButton( self.frame, text='Background Color:', width=15, command=lambda: self.updateWindowColor(fields)) self.BUTTON_WINDOW_BG_COLOR.grid(row=ROW_BG_COLOR, column=0, sticky=E, padx=4) self.LABEL_WINDOW_BG_COLOR.grid(row=0, column=1, sticky=W) self.LABEL_WINDOW_BG_IMAGE = Label( self.frame, textvariable=fields.VAR_DISPLAY_WINDOW_BG_IMAGE, width=20, anchor=W) self.BUTTON_WINDOW_BG_IMAGE = HoverButton( self.frame, text='Background Image:', width=15, command=lambda: self.selectImageFile(fields)) self.BUTTON_WINDOW_BG_IMAGE.grid(row=ROW_BG_IMAGE, column=0, sticky=E, padx=4, pady=4) self.LABEL_WINDOW_BG_IMAGE.grid(row=ROW_BG_IMAGE, column=1, sticky=W) self.CANVAS_WINDOW_BG_IMAGE = Canvas(bgColorFrame, width=80, height=30) self.RECTANGLE_WINDOW_BG_IMAGE = self.CANVAS_WINDOW_BG_IMAGE.create_rectangle( 80, 4, 0, 30, fill=fields.VAR_LABEL_WINDOW_BG_COLOR_BACKGROUND, outline="") self.fitWindowFrame = Frame(self.frame) self.checkbuttonSetDimensions = Checkbutton( self.fitWindowFrame, text="Fit window to background image", variable=self.dimensionCheckbutton, command=lambda: self.updateWindowDimensions()) self.checkbuttonSetDimensions.grid(row=0, column=0, sticky=W) self.fitWindowFrame.grid(row=ROW_SET_DIMENSIONS, column=0, columnspan=2, padx=4, pady=4, sticky=W) self.buttonClearImage = HoverButton( self.frame, text='Remove Image', width=15, command=lambda: self.updateBackgroundImage()) self.buttonClearImage.grid(row=ROW_DO_NOT_USE_BG, column=0, columnspan=3, sticky=SE, padx=4, pady=(0, 4)) self.CANVAS_WINDOW_BG_IMAGE.grid(row=0, column=0, sticky=W) bgColorFrame.grid(row=ROW_BG_COLOR, column=1, sticky=W) def updateBackgroundImage(self): self.fields.VAR_DISPLAY_WINDOW_BG_IMAGE.set("") self.fields.VAR_PATH_WINDOW_BG_IMAGE.set("") def updateWindowDimensions(self): if self.dimensionCheckbutton.get(): try: filename = self.fields.VAR_PATH_WINDOW_BG_IMAGE.get() img = Image.open(filename) self.fields.VAR_WINDOW_WIDTH.set(img.size[0]) self.fields.VAR_WINDOW_HEIGHT.set(img.size[1]) except Exception: self.fields.VAR_WINDOW_WIDTH.set(0) self.fields.VAR_WINDOW_HEIGHT.set(0) self.parent.sFrame.ENTRY_WINDOW_WIDTH.configure(state=DISABLED) self.parent.sFrame.ENTRY_WINDOW_HEIGHT.configure(state=DISABLED) else: self.parent.sFrame.ENTRY_WINDOW_WIDTH.configure(state=NORMAL) self.parent.sFrame.ENTRY_WINDOW_HEIGHT.configure(state=NORMAL) def updateWindowColor(self, fields): color = colorchooser.askcolor(title="Select color") if color[1]: fields.VAR_LABEL_WINDOW_BG_COLOR_TEXT.set(color[1]) fields.VAR_LABEL_WINDOW_BG_COLOR_BACKGROUND = color[1] self.CANVAS_WINDOW_BG_IMAGE.itemconfig( self.RECTANGLE_WINDOW_BG_IMAGE, fill=fields.VAR_LABEL_WINDOW_BG_COLOR_BACKGROUND) def selectImageFile(self, fields): filename = filedialog.askopenfilename( initialdir=os.getcwd() + "/imagefiles", title="Select image file", filetypes=[("PNG", "*.png"), ("JPEG", "*.jpg; *.jpeg; *.jpe; *.jfif")]) if filename: fields.VAR_DISPLAY_WINDOW_BG_IMAGE.set( helperMethods.getFileNameFromPath(filename)) fields.VAR_PATH_WINDOW_BG_IMAGE.set(filename) self.updateWindowDimensions()
def __init__(self, master=None): super().__init__(master) self.pack() # First row f1 = LabelFrame(self, text='NAND file with No$GBA footer', padx=10, pady=10) # NAND Button self.nand_mode = False nand_icon = PhotoImage( data=('R0lGODlhEAAQAIMAAAAAADMzM2ZmZpmZmczMzP///wAAAAAAAAA' 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAMAAAYALAAAAAAQAB' 'AAAARG0MhJaxU4Y2sECAEgikE1CAFRhGMwSMJwBsU6frIgnR/bv' 'hTPrWUSDnGw3JGU2xmHrsvyU5xGO8ql6+S0AifPW8kCKpcpEQA7')) self.nand_button = Button(f1, image=nand_icon, command=self.change_mode, state=DISABLED) self.nand_button.image = nand_icon self.nand_button.pack(side='left') self.nand_file = StringVar() Entry(f1, textvariable=self.nand_file, state='readonly', width=40).pack(side='left') Button(f1, text='...', command=self.choose_nand).pack(side='left') f1.pack(padx=10, pady=10, fill=X) # Second row f2 = Frame(self) # Check boxes self.checks_frame = Frame(f2) # Install TWiLight check self.twilight = IntVar() self.twilight.set(1) twl_chk = Checkbutton( self.checks_frame, text='Install latest TWiLight Menu++ on custom firmware', variable=self.twilight) twl_chk.pack(padx=10, anchor=W) # Clean files check self.clean_downloaded = IntVar() self.clean_downloaded.set(1) clean_chk = Checkbutton(self.checks_frame, text='Clean downloaded files after completion', variable=self.clean_downloaded) clean_chk.pack(padx=10, anchor=W) self.checks_frame.pack(fill=X) # NAND operation frame self.nand_frame = LabelFrame(f2, text='NAND operation', padx=10, pady=10) self.nand_operation = IntVar() self.nand_operation.set(0) Radiobutton(self.nand_frame, text='Remove No$GBA footer', variable=self.nand_operation, value=0, command=lambda: self.enable_entries(False)).pack(anchor=W) Radiobutton(self.nand_frame, text='Add No$GBA footer', variable=self.nand_operation, value=1, command=lambda: self.enable_entries(True)).pack(anchor=W) fl = Frame(self.nand_frame) self.cid_label = Label(fl, text='eMMC CID', state=DISABLED) self.cid_label.pack(anchor=W, padx=(24, 0)) self.cid = StringVar() self.cid_entry = Entry(fl, textvariable=self.cid, width=20, state=DISABLED) self.cid_entry.pack(anchor=W, padx=(24, 0)) fl.pack(side='left') fr = Frame(self.nand_frame) self.console_id_label = Label(fr, text='Console ID', state=DISABLED) self.console_id_label.pack(anchor=W) self.console_id = StringVar() self.console_id_entry = Entry(fr, textvariable=self.console_id, width=20, state=DISABLED) self.console_id_entry.pack(anchor=W) fr.pack(side='right') f2.pack(fill=X) # Third row f3 = Frame(self) self.start_button = Button(f3, text='Start', width=16, command=self.hiya, state=DISABLED) self.start_button.pack(side='left', padx=(0, 5)) Button(f3, text='Quit', command=root.destroy, width=16).pack(side='left', padx=(5, 0)) f3.pack(pady=(10, 20)) self.folders = [] self.files = []