def __init__(self, parent): self.serialStatus = False #create variables self.startmotor = BooleanVar() self.logstate = BooleanVar() self.loggedData = [] self.throttlevar = StringVar() self.throttleval = IntVar() #default values self.throttlevar.set("0%") self.throttleval.set(0) #base frame init Frame.__init__(self, parent) self.parent = parent self.initUI() self.centerWindow() self.PERIOD_LENGTH_Log = 100 #milliseconds self.PERIOD_LENGTH_Scan = 1000 #milliseconds self.PERIOD_LENGTH_Refresh = 300 #milliseconds self.parent.after(0, self.runScan) self.parent.after(0, self.runLog) self.parent.after(0, self.runRefresh)
class MenuItem(object): def __init__(self, menu, title, **kwargs): self._menu = menu if kwargs.get('checkbox'): # Checkbox menu item self._checkvar = BooleanVar() self._checkvar.set(kwargs.get('checked', False)) self._menu._ctrl.add_checkbutton(label=title, command=self._on_check, variable=self._checkvar) else: # NOTE: For whatever reason, lambdas do not work in this case... self._menu._ctrl.add_command(label=title, command=self._on_click) if kwargs.get('on_click'): self.on_click = kwargs['on_click'] def _on_check(self): """Handler for keeping on_click virtual with checkbox option""" self.on_click(self._checkvar.get()) def _on_click(self): """Handler for keeping on_click virtual""" self.on_click() def on_click(self): pass def __exit__(self, *args): pass def __enter__(self, *args): return self
def initialize(self): self.grid() #ENTRY CELL self.entryVariable = StringVar() self.entry = Tkinter.Entry(self,textvariable=self.entryVariable) self.entry.grid(column=0,row=0,sticky='EW') self.entry.bind("<Return>", self.OnPressEnter) self.entryVariable.set(u"Enter text here.") #CLICK BUTTON button = Tkinter.Button(self,text=u"Click me !",command=self.OnButtonClick) button.grid(column=1,row=0) #CHECK BOX self.var = BooleanVar() cb = Tkinter.Checkbutton(self, text="Show title",variable=self.var, command=self.onClick) cb.select() cb.grid(column=0,row=5,sticky='W') ## #COMBO BOX ## self.combo = StringVar() ## self.box = ttk.Combobox(self.parent, textvariable=self.box) ## self.box['values'] = ('X', 'Y', 'Z') ## self.box.current(0) ## self.box.grid(column=0, row=4,sticky='W') #LABEL self.labelVariable = Tkinter.StringVar() label = Tkinter.Label(self,textvariable=self.labelVariable,anchor="w",fg="white",bg="blue") label.grid(column=0,row=1,columnspan=2,sticky='EW') self.labelVariable.set(u"Hello !") # MENU menubar = Tkinter.Menu(self.parent) # level0: -- menubar-- self.config(menu=menubar) fileMenu = Tkinter.Menu(menubar) #level1: filemenu menubar.add_cascade(label="File", menu=fileMenu) # add to menubar submenu = Tkinter.Menu(menubar) #level2: submenu fileMenu.add_cascade(label='Import', menu=submenu) # add to filemenu submenu.add_command(label="test1",command=self.test1)# level3: add under submenu submenu.add_command(label="test2",command=self.test2) fileMenu.add_separator() fileMenu.add_command(label="Exit", command=self.destroy)# level2: under filemenu self.grid_columnconfigure(0,weight=1) # just formatting self.resizable(True,False) self.update() self.geometry(self.geometry()) self.entry.focus_set() self.entry.selection_range(0, Tkinter.END) #QUIT quitButton = Tkinter.Button(self, text="Quit",command=self.destroy) quitButton.grid(column=1,row=5,sticky='E')
def __init__(self, parent, question_text, ans1_text, ans2_text, ans3_text, ans4_text, exp1_text, exp2_text, exp3_text, exp4_text, correct_ans): # assigning parameters to attributes self.parent = parent self.qtext = str(question_text) self.text1 = str(ans1_text) self.text2 = str(ans2_text) self.text3 = str(ans3_text) self.text4 = str(ans4_text) self.exp1 = str(exp1_text) self.exp2 = str(exp2_text) self.exp3 = str(exp3_text) self.exp4 = str(exp4_text) self.ans = int(correct_ans) # creating Tkinter variables self.ans_input = IntVar() self.is_correct = BooleanVar() self.efbg = StringVar() self.is_correct_text = StringVar() self.exp_text = StringVar() # developer mode if dev: self.ans_input.set(self.ans) # questionwide bgcolor, fgcolor self.bgcolor = GrayScale(80) self.fgcolor = GrayScale(20) # creating parent frame self.parent_frame() self.question_frame()
def CreateOldSeparatorMenu(self): self.oldSeparatorMenu = Menu(self.optionsMenu, tearoff=0) self.oldSpacesButton = BooleanVar() self.oldUnderscoresButton = BooleanVar() self.oldCamelcaseButton = BooleanVar() self.oldPeriodButton = BooleanVar() self.oldSeparatorMenu.add_checkbutton(label="Spaces", onvalue=True, offvalue=False, variable=self.oldSpacesButton) self.oldSpacesButton.set(True) self.oldSeparatorMenu.add_checkbutton(label="Underscores", onvalue=True, offvalue=False, variable=self.oldUnderscoresButton) self.oldUnderscoresButton.set(True) #self.oldSeparatorMenu.add_command(label="Custom Separator", command=self.customSeparatorFrame) self.oldSeparatorMenu.add_checkbutton(label="CamelCase", onvalue=True, offvalue=False, variable=self.oldCamelcaseButton) self.oldSeparatorMenu.add_checkbutton(label="Period", onvalue=True, offvalue=False, variable=self.oldPeriodButton) self.optionsMenu.add_cascade(label="Old Separator", menu=self.oldSeparatorMenu)
def __init__(self, container, frame, label='', text='', row=0, column=0): self.container = container self.is_b0 = BooleanVar(container.parent) self.is_dw = BooleanVar(container.parent) self.column = column self.direction = StringVar(container.parent) self.label_from = Label(frame, text='from') self.text_from = Entry(frame) self.text_from.insert(0, text) self.button_file_from = Button(frame, text='...', command=lambda:filenameDialog_text(self.text_from)) self.button_rm = Button(frame, text='remove', command=self.click_remove) self.radio_ap = Radiobutton(frame, text='AP', variable=self.direction, value='AP', command=self.set_direction) self.radio_pa = Radiobutton(frame, text='PA', variable=self.direction, value='PA', command=self.set_direction) self.label_to = Label(frame, text='to') self.text_to = Entry(frame) #self.text_to.insert(0, text) self.button_file_to = Button(frame, text='Gen', command=self.set_filename_to) self.check_b0 = Checkbutton(frame, text='B0', variable=self.is_b0) self.check_dw = Checkbutton(frame, text='DWI', variable=self.is_dw) self.button_up = Button(frame, text='up', width=3, command=self.click_up) self.button_dn = Button(frame, text='down', width=3, command=self.click_dn) self.row = -1 self.change_row(row) if text != '': self.set_appa() self.set_filename_to()
def test_invalid_value_domain(self): v = BooleanVar(self.root, name="name") self.root.globalsetvar("name", "value") with self.assertRaises(TclError): v.get() self.root.globalsetvar("name", "1.0") with self.assertRaises(TclError): v.get()
def test_invalid_value_domain(self): v = BooleanVar(self.root, name='name') self.root.globalsetvar('name', 'value') with self.assertRaises(TclError): v.get() self.root.globalsetvar('name', '1.0') with self.assertRaises(TclError): v.get()
def __init__(self, root): self.root = root self.patvar = StringVar(root, '') self.revar = BooleanVar(root, False) self.casevar = BooleanVar(root, False) self.wordvar = BooleanVar(root, False) self.wrapvar = BooleanVar(root, True) self.backvar = BooleanVar(root, False)
def __init__(self): """Construct a Studio window.""" Frame.__init__(self) # make the window resizable top = self.master.winfo_toplevel() for row in range(2, GRID_ROWS + 2): for col in range(0, GRID_COLS): top.rowconfigure(row, weight=1) top.columnconfigure(col, weight=1) self.rowconfigure(row, weight=1) self.columnconfigure(col, weight=1) # initialize the title title = Label(self.master, font=FONT_TITLE, text=TEXT_TITLE) title.grid(row=0, column=0, columnspan=GRID_COLS) # initialize the meter self._meter = Meter(self.master, METER_WIDTH, self._get_meter_data) self._meter.grid(row=1, column=0, columnspan=GRID_COLS) # initialize the cart grid self._grid = Grid(self, GRID_ROWS, GRID_COLS, True, self._cart_start, self._cart_stop, self._cart_end, self.add_cart) # initialize the dual box self._dual_box = DualBox(self) self._dual_box.grid(row=GRID_ROWS + 2, column=0, columnspan=4) # intialize the auto-queue control self._auto_queue = BooleanVar() self._auto_queue.set(False) control = Frame(self.master, bd=2, relief=Tkinter.SUNKEN) Checkbutton(control, text=TEXT_AUTOSLOT, variable=self._auto_queue, onvalue=True, offvalue=False).pack(anchor=Tkinter.NW) control.grid(row=GRID_ROWS + 2, column=4, columnspan=GRID_COLS - 4) # initialize the search box, button Label(control, font=FONT, text=TEXT_SEARCHBOX).pack(anchor=Tkinter.NW) self._entry = Entry(control, takefocus=True, width=45) self._entry.bind("<Return>", self.search) # self._entry.grid(row=GRID_ROWS + 3, column=0, columnspan=5) self._entry.pack(anchor=Tkinter.NW) self._entry.focus_set() button = Button(control, text=TEXT_SEARCH, command=self.search) # button.grid(row=GRID_ROWS + 3, column=5) button.pack(anchor=Tkinter.S) # begin the event loop self.master.protocol("WM_DELETE_WINDOW", self.master.destroy) self.master.title(TEXT_TITLE) self.master.mainloop()
def addSubCheckbuttons(self): self.affectSubfolders = BooleanVar() self.cleanFolderNames = BooleanVar() self.optionsMenu.add_checkbutton(label="Affect Subfolders", onvalue=True, offvalue=False, variable=self.affectSubfolders) self.optionsMenu.add_checkbutton(label="Clean Folder Names", onvalue=True, offvalue=False, variable=self.cleanFolderNames) self.affectSubfolders.set(True) self.cleanFolderNames.set(True)
def __init__(self, root): self.root = root # State shared by search, replace, and grep; # the search dialogs bind these to UI elements. self.patvar = StringVar(root) # search pattern self.revar = BooleanVar(root) # regular expression? self.casevar = BooleanVar(root) # match case? self.wordvar = BooleanVar(root) # match whole word? self.wrapvar = BooleanVar(root) # wrap around buffer? self.wrapvar.set(1) # (on by default) self.backvar = BooleanVar(root) # search backwards?
def initUI(self): self.parent.title("Checkbutton") self.pack(fill=BOTH, expand=True) self.var = BooleanVar() cb = Checkbutton(self, text="Show title", variable=self.var, command=self.onClick) cb.select() cb.place(x=50, y=50)
def cs_checkbox(root, r, c, label, boolval, box_conf={}, grid_conf={}): entrybl = BooleanVar() entrybl.set(boolval) checkbox = Checkbutton(master=root, text=label, onvalue=True, offvalue=False, variable=entrybl, **box_conf) checkbox.grid(row=r, column=c, **grid_conf) return entrybl
def __init__(self, root): """Initialize Variables that save search state. The dialogs bind these to the UI elements present in the dialogs. """ self.root = root self.patvar = StringVar(root, '') self.revar = BooleanVar(root, False) self.casevar = BooleanVar(root, False) self.wordvar = BooleanVar(root, False) self.wrapvar = BooleanVar(root, True) self.backvar = BooleanVar(root, False)
def __init__(self, root): '''Initialize Variables that save search state. The dialogs bind these to the UI elements present in the dialogs. ''' self.root = root # need for report_error() self.patvar = StringVar(root, '') # search pattern self.revar = BooleanVar(root, False) # regular expression? self.casevar = BooleanVar(root, False) # match case? self.wordvar = BooleanVar(root, False) # match whole word? self.wrapvar = BooleanVar(root, True) # wrap around buffer? self.backvar = BooleanVar(root, False) # search backwards?
def login_gui(username, password): def get_login(evt=None): temp_username = username_holder.get() temp_password = password_holder.get() if remember_login_holder.get(): logon_file = open("dep.dat", "w") logon_file.write(encodestring(temp_username+" "+temp_password)) logon_file.close() elif os.path.isfile("dep.dat"): os.remove("dep.dat") login_tk.destroy() wrap.login(temp_username, temp_password) overview_gui() return def on_checkbox_flip(): if remember_login_holder.get(): logon_file = open("dep.dat", "w") logon_file.write(encodestring(username_holder.get()+" "+password_holder.get())) logon_file.close() else: if os.path.isfile("dep.dat"): os.remove("dep.dat") return login_tk = Tk() login_tk.title("Login Window") Label(login_tk, text="Login to GradeSpeed").pack(padx=50, pady=(10, 5)) Label(login_tk, text="Username:"******"<Key-Return>", get_login) Label(login_tk, text="Password:"******"*") password_field.pack(padx=50, pady=(0, 5)) password_field.bind("<Key-Return>", get_login) remember_login_holder = BooleanVar() remember_login_holder.set(len(username) > 0) login_frame = Frame(login_tk) Checkbutton(login_frame, text="Remember Logon", var=remember_login_holder, command=on_checkbox_flip).pack() login_frame.pack(pady=5) Button(text="Login", command=get_login).pack(padx=50, pady=(5, 10)) center_gui(login_tk) login_tk.mainloop()
def CreateCheckList(self, frame, labels, values=None, colors=None): all_widgetes = [w for w in frame.winfo_children() if w.winfo_class() == 'Checkbutton'] for w in all_widgetes: w.destroy() all_widgetes = [w for w in frame.winfo_children() if w.winfo_class() == 'Label'] for w in all_widgetes[1:]: w.destroy() var = [] if values is not None: add_text = ["%5.1f" % (values[i]) +'%' for i in range(len(values))] for i in range(len(labels)): var.append(BooleanVar()) fgc = "black" if colors is not None: mycolor = '#%02x%02x%02x' % (colors[i,0], colors[i,1], colors[i,2]) if (colors[i,0]+colors[i,1]+colors[i,2])/3/255<=0.5: fgc = "#FFFFFF" else: mycolor = frame.cget('bg') cb = Checkbutton(frame, text=labels[i], state=DISABLED, variable=var[i], bg=mycolor, disabledforeground=fgc, anchor=W) # cb.pack(anchor=W, fill=X, padx=2) cb.grid(row=i+2,column=0,sticky=W+E) if values is not None: cb = Label(frame, text=add_text[i], bg=mycolor, fg=fgc, anchor=E) cb.grid(row=i+2,column=1,sticky=W+E+N+S) frame.grid_rowconfigure(i+2, weight=0) return var
def createNewSeparatorMenu(self): self.newSeparatorMenu = Menu(self.optionsMenu, tearoff=0) self.spacesButton = BooleanVar() self.underscoresButton = BooleanVar() self.camelcaseButton = BooleanVar() self.periodButton = BooleanVar() self.newSeparatorMenu.add_checkbutton(label="Spaces", onvalue=True, offvalue=False, variable=self.spacesButton, command=self.ToggleNonSpacesOff) self.spacesButton.set(True) self.newSeparatorMenu.add_checkbutton(label="Underscores", onvalue=True, offvalue=False, variable=self.underscoresButton, command=self.ToggleNonUnderscoresOff) self.newSeparatorMenu.add_command(label="Custom Separator", command=self.customSeparatorFrame) self.newSeparatorMenu.add_checkbutton(label="CamelCase", onvalue=True, offvalue=False, variable=self.camelcaseButton, command=self.ToggleNonCamelCaseOff) self.newSeparatorMenu.add_checkbutton(label="Period", onvalue=True, offvalue=False, variable=self.periodButton, command=self.ToggleNonPeriodOff) self.optionsMenu.add_cascade(label="New Separator", menu=self.newSeparatorMenu)
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Checkbutton") self.pack(fill=BOTH, expand=True) self.var = BooleanVar() cb = Checkbutton(self, text="Show title", variable=self.var, command=self.onClick) cb.select() cb.place(x=50, y=50) def onClick(self): if self.var.get() == True: self.master.title("Checkbutton") else: self.master.title("")
def make_checkbox_all(self, frame, width=4, ncol=20): self.lst_checkbox_slices_values = [] self.lst_checkbox_slices = [] ii = 0 for z in range(self.shape[2]): self.lst_checkbox_slices_values.append( [BooleanVar() for f in range(self.shape[3])]) boxes = [ Checkbutton(frame, text=str('%s' % f), variable=self.lst_checkbox_slices_values[z][f], width=width) for f in range(self.shape[3]) ] jj = 0 for f in range(self.shape[3]): btn = boxes[f] btn.grid(row=z, column=f) jj += 1 if ncol is not None and ncol <= jj: ii += 1 jj = 0 self.lst_checkbox_slices.append(boxes) if jj > 0: ii += 1
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Checkbutton") self.pack(fill=BOTH, expand=True) self.var = BooleanVar() cb = Checkbutton(self, text="Show title", variable=self.var, command=self.onClick) cb.select() cb.place(x=50, y=30) def onClick(self): if self.var.get() == True: self.master.title("Checkbutton") else: self.master.title("")
class MeasureFrame(LabelFrame): def __init__(self, master, tracker, text="Measuring", *args, **kwargs): LabelFrame.__init__(self, master, text=text, *args, **kwargs) self.tracker = tracker self.config_frame = NamedEntryFrame(self, (OBS_INTERVAL, NUM_SAMPLES, NUM_OBSS), parsers={OBS_INTERVAL: float, NUM_SAMPLES: int, NUM_OBSS: int}) self.config_frame.grid() self.save_frame = LabelFrame(self, text="Saving") self.dest_selector = FileSelectionFrame(self.save_frame, ask_mode="save") self.dest_selector.grid(row=0, column=0, columnspan=2) self.save_button = Button(self.save_frame, text="Save", command=bg_caller(self.save)) self.save_button.grid(row=1, column=0) self.appending_var = BooleanVar() self.append_checkbutton = Checkbutton(self.save_frame, text="Append", variable=self.appending_var) self.append_checkbutton.grid(row=1, column=1) self.save_frame.grid() def measure(self, only_accurate=True): try: interval = self.config_frame.get(OBS_INTERVAL) samples = self.config_frame.get(NUM_SAMPLES) num_obss = self.config_frame.get(NUM_OBSS) except ValueError: logger.error("Could not parse input fields.") data = self.tracker.measure(observation_interval=interval, samples_per_observation=samples, number_of_observations=num_obss) if only_accurate: accurate_data = [point for point in data if point.status == point.DATA_ACCURATE] num_invalid = len(data) - len(accurate_data) if num_invalid > 0: logger.warning("Hiding {} inaccurate data points." .format(num_invalid)) return accurate_data else: return data def save(self, only_accurate=True): dest = self.dest_selector.path_var.get() if not dest: logger.error("Must select a destination file.") return data = self.measure(only_accurate=only_accurate) w = csv.writer(open(dest, 'a' if self.appending_var.get() else 'w')) for point in data: w.writerow((point.time, point.position.r, point.position.theta, point.position.phi)) logger.info("Saved measurements into {!r}".format(dest))
def __init__(self, wname='guippy', master=None): Tkinter.Frame.__init__(self, master) self.master.title(wname) self.radio_value = IntVar() self.radio_values = { 'test1': 0, 'test2': 1, 'test3': 2, } self.check_values = { 'test1': BooleanVar(), 'test2': BooleanVar(), 'test3': BooleanVar(), } self.option_value = StringVar() self.entry_value = StringVar() self.result_value = StringVar() self.radio_entry = StringVar() self.check_entry = StringVar() # widgets kwds = {'padx': 3, 'pady': 3, 'side': Tkinter.LEFT} ff = Frame(self) ff.pack(side=Tkinter.TOP, anchor='w') Button(ff, text='apply ', command=self.apply).pack(**kwds) Button(ff, text='reapply').pack(**kwds) ff = Frame(self) ff.pack(side=Tkinter.TOP, anchor='w') for key, val in sorted(self.radio_values.items()): _r = Radiobutton(ff, text=key, variable=self.radio_value, value=val) _r.pack(**kwds) Entry(ff, textvariable=self.radio_entry).pack(**kwds) ff = Frame(self) ff.pack(side=Tkinter.TOP, anchor='c') for key, val in sorted(self.check_values.items()): _w = Checkbutton(ff, text=key, variable=val) _w.pack(**kwds) Entry(ff, textvariable=self.check_entry).pack(**kwds)
def __init__( self, parent, defaultfont=None, showstyles=None ): self._family = StringVar( value='Century Schoolbook L') self._sizeString = StringVar( value='20' ) self._weight = StringVar( value=tkFont.NORMAL ) self._slant = StringVar( value=tkFont.ROMAN ) self._isUnderline = BooleanVar( value=False ) self._isOverstrike = BooleanVar( value=False ) if defaultfont: self._initialize( defaultfont ) self._currentFont = tkFont.Font( font=self.getFontTuple() ) self._showStyles = showstyles self.sampleText = None tkSimpleDialog.Dialog.__init__( self, parent, 'Font Chooser' )
def createBreakUpByMenu(self): self.delimitersMenu = Menu(self.optionsMenu, tearoff=0) self.breakUpByBraces = BooleanVar() self.breakUpByParens = BooleanVar() self.breakUpByBrackets = BooleanVar() self.breakUpByCamelCase = BooleanVar() self.breakUpByParens.set(True) self.breakUpByBrackets.set(True) self.delimitersMenu.add_checkbutton(label="Braces", onvalue=True, offvalue=False, variable=self.breakUpByBraces) self.delimitersMenu.add_checkbutton(label="Parentheses", onvalue=True, offvalue=False, variable=self.breakUpByParens) self.delimitersMenu.add_checkbutton(label="Brackets", onvalue=True, offvalue=False, variable=self.breakUpByBrackets) self.delimitersMenu.add_checkbutton(label="CamelCase", onvalue=True, offvalue=False, variable=self.breakUpByCamelCase) self.optionsMenu.add_cascade(label="Delimiters", menu=self.delimitersMenu)
def __init__(self, master): Frame.__init__(self, master) self.serial_num = StringVar() self.gpioPin = StringVar() self.serial_num_smt = StringVar() self.master = master self.results = StringVar() self.debug_mode = BooleanVar() self.__initUi()
def test_get(self): v = BooleanVar(self.root, True, "name") self.assertIs(v.get(), True) self.root.globalsetvar("name", "0") self.assertIs(v.get(), False) self.root.globalsetvar("name", 42 if self.root.wantobjects() else 1) self.assertIs(v.get(), True) self.root.globalsetvar("name", 0) self.assertIs(v.get(), False) self.root.globalsetvar("name", 42L if self.root.wantobjects() else 1L) self.assertIs(v.get(), True) self.root.globalsetvar("name", 0L) self.assertIs(v.get(), False) self.root.globalsetvar("name", "on") self.assertIs(v.get(), True) self.root.globalsetvar("name", u"0") self.assertIs(v.get(), False) self.root.globalsetvar("name", u"on") self.assertIs(v.get(), True)
def test_invalid_value_domain(self): false = 0 if self.root.wantobjects() else "0" v = BooleanVar(self.root, name="name") with self.assertRaises(TclError): v.set("value") self.assertEqual(self.root.globalgetvar("name"), false) self.root.globalsetvar("name", "value") with self.assertRaises(TclError): v.get() self.root.globalsetvar("name", "1.0") with self.assertRaises(TclError): v.get()
def initUI(self): self.parent.title("CheckButton") self.pack(fill=BOTH,expand=True) self.var = BooleanVar() self.var.set(False) chbt = Checkbutton(self,text="Show Title", variable=self.var,command=self.onClick) #chbt.select() chbt.place(x=50,y=50)
def __init__(self, root): self.in_file_name = '' self.root = root self.root.title('Tappy (Tidal Analysis Package)') #gets the tappy_filter method methods = [('None', 'none'), ('Transform', 'transform'), ('USGS', 'usgs'), ('Demerliac', 'demerliac')] self.methodvar = StringVar() self.methodvar.set('none') Tk.Label(root, text='Filter:').pack(anchor=W,pady=2, padx=15) for name, kwarg in methods: Tk.Radiobutton(root, text=name, variable=self.methodvar, value=kwarg).pack(anchor=W,pady=2, padx=15) Tk.Label(root, text='Options:').pack(anchor=W,pady=2, padx=15) #choose linear trend self.linearTrend = BooleanVar() Tk.Checkbutton(root, text="Linear Trend", variable = self.linearTrend) \ .pack(anchor=W,pady= 2,padx=15) self.rayleigh = BooleanVar() Tk.Checkbutton(root, text="Rayleigh", variable = self.rayleigh) \ .pack(anchor=W,pady= 2,padx=15) #reads the input file name chosen in file upload self.in_file_name = StringVar() self.make_fileselect(root,"Tide File:",self.in_file_name,"tide_fname") #chooses output file directory and begins the analysis of the input file c3 = lambda: self.select_output_file(root) self.b1 = Tk.Button(self.root, text='Export File', state = DISABLED, command=c3) self.b1.pack(anchor=W,pady=2, padx=15)
def initUI(self): self.parent.title("Checkbutton") self.pack(fill=BOTH, expand=True) self.var = BooleanVar() cb = Checkbutton(self, text="Show title", variable=self.var, command=self.onClick) cb.select() cb.place(x=50, y=30)
def insert_checkbutton(self, text, frame_name, side, varname, stick=None, default=None, callback=None): """Inserts a check button widget in the specified frame. ARGS: * var: a TKinter supported variable, such as IntVar(), StrVar(), and etc.""" # create a variable for this task var = BooleanVar() if default is not None: var.set(default) # create the widget frame = self.frames[frame_name] check = Checkbutton(frame, text=text, variable=var, command=callback) check.pack(side=self.TkSide[side], anchor=stick) # save data regarding the widget if self.checkbuttons.get(frame_name, None) == None: self.checkbuttons[frame_name] = {} self.checkbuttons[frame_name][varname] = {'button':check, 'var':var}
def __init__(self, parent, draftgame): self.current_opponent_id = 0 self.user_pick_made = BooleanVar() self.user_pick_made.set(False) self.game = draftgame self.parent = parent Frame.__init__(self, parent) self.grid() self.__MainUI() self.draft_logic()
def __init__(self): # UI stuff self.ui_root = Tk() self.ui_main = None # Checkboxes self.input_only = Item(BooleanVar(), Types.Checkbox, position=0) self.logs = Item(BooleanVar(), Types.Checkbox, position=1) # Text fields self.user = Item(StringVar(), Types.String, 'user', 0) self.user_password = Item(StringVar(), Types.String, 'user_password', 1) self.local_password = Item(StringVar(), Types.String, 'local_password', 2) self.log_name = Item(StringVar(), Types.String, position=3) # Combo boxes self.text_entry = Item(StringVar(), Types.Combo, 'text', 0) self._text_history = [] self.app = Item(StringVar(), Types.File) self.defaults = self._load_defaults() self.current_sdk = None
def __init__(self, menu, title, **kwargs): self._menu = menu if kwargs.get('checkbox'): # Checkbox menu item self._checkvar = BooleanVar() self._checkvar.set(kwargs.get('checked', False)) self._menu._ctrl.add_checkbutton(label=title, command=self._on_check, variable=self._checkvar) else: # NOTE: For whatever reason, lambdas do not work in this case... self._menu._ctrl.add_command(label=title, command=self._on_click) if kwargs.get('on_click'): self.on_click = kwargs['on_click']
def reinit(self): self.arret = 0 self.compt = self.init_compt self.lbl.config(text='Saisissez les coordonnées:', bg="blue", fg="white", width=20) self.lbl.grid(column=0, row=0) self.txt1Lbl = Label(self.window) self.txt1 = Entry(self.window, width=3) self.txt2 = Entry(self.window, width=3) self.txt3 = Entry(self.window, width=3) self.txt1Lbl.config(text='X', bg="red", fg="white", width=3) self.txt1Lbl.grid(column=0, row=1) #self.lbl.pack() #self.txt1Lbl.pack() self.txt1.grid(column=1, row=1) self.txt2.grid(column=1, row=2) self.txt3.grid(column=1, row=3) self.NETWORK = BooleanVar() self.chk_state1 = BooleanVar() self.NETWORK.set(False) self.chk_state1.set(False) #set check state self.chk0 = Checkbutton(self.window, text='Load previous network', var=self.NETWORK) self.chk1 = Checkbutton(self.window, text='Learn', var=self.chk_state1) self.chk0.grid(column=2, row=1) self.chk1.grid(column=2, row=2) self.btn.config(text='Lancer', command=self.start) self.btn.grid(column=0, row=4)
def __init__(self, text): self.text = text self.constraints = { 0: anarchy(), 1: communism(), 2: democracy(), 3: dictatorship() } self.leader = None self.constraint_id = None self.rule = lambda *args: True self.using = {n: BooleanVar() for n in self.constraints} self.set_constraint(0)
def checkbutton_component(self, s, r, c, init_val=False, mode=NORMAL, onvalue=-1, offvalue=-1): '''adds a checkbutton, and its associated variable''' if onvalue == -1: var = BooleanVar() var.set(init_val) btn = Checkbutton(self,text=s, variable=var) else: var = StringVar() var.set(init_val) btn = Checkbutton(self,text=s, variable=var, onvalue=onvalue, offvalue=offvalue) btn.grid(row=r, column=c, columnspan=2, sticky=W) btn.config(state=mode) return var
def __init__(self, fig): self._scope = None self.fig = fig self.plt = fig.add_subplot(111) self.ch1, self.ch2 = self.plt.plot([], [], [], []) self.pool = ThreadPool() self.ch1b = BooleanVar() self.ch1b.set(True) self.ch2b = BooleanVar() self.ch2b.set(True) self._fft = BooleanVar() self._fft.set(False) self._xy = BooleanVar() self._xy.set(False) self._USB_voltage = None
def redraw(self): # Even though there are never more than three widgets per row, # we have four columns, to allow the taskname label and the # input widget to stretch. self.grid_columnconfigure(2, weight=1) row = 0 # Add a new row of widgets for each task. for rec in sorted(self.table.query(), key=lambda rec: rec.get('created')): # Extract the fields we need. completed = rec.get('completed') taskname = rec.get('taskname') # Create a button with an 'X' in it, to delete the task. close_btn = Button(self, text='X', command=lambda rec=rec: self.delete_rec(rec)) close_btn.grid(row=row, column=0) # Create a checkbox, to mark it completed (or not). var = BooleanVar(self, value=completed) completed_btn = Checkbutton( self, variable=var, command=lambda rec=rec, var=var: self.toggle_rec(rec, var)) completed_btn.grid(row=row, column=1) # Create a label showing the task name. taskname_lbl = Label(self, text=taskname, anchor=W) taskname_lbl.grid(row=row, column=2, columnspan=2, sticky=W) row += 1 # Bump row index. # Add a final row with the input and button to add new tasks. self.input = Entry(self) self.input.bind('<Return>', self.add_rec) self.input.grid(row=row, column=0, columnspan=3, sticky=W + E) add_btn = Button(self, text='Add Task', command=self.add_rec) add_btn.grid(row=row, column=3) # Add save button. (Auto-save is left as an exercise.) save_btn = Button(self, text='Save local snapshot', command=self.save) save_btn.grid(row=row + 1, column=0, columnspan=3, sticky=W)
def __init__(self, master, tracker, text="Measuring", *args, **kwargs): LabelFrame.__init__(self, master, text=text, *args, **kwargs) self.tracker = tracker self.config_frame = NamedEntryFrame(self, (OBS_INTERVAL, NUM_SAMPLES, NUM_OBSS), parsers={OBS_INTERVAL: float, NUM_SAMPLES: int, NUM_OBSS: int}) self.config_frame.grid() self.save_frame = LabelFrame(self, text="Saving") self.dest_selector = FileSelectionFrame(self.save_frame, ask_mode="save") self.dest_selector.grid(row=0, column=0, columnspan=2) self.save_button = Button(self.save_frame, text="Save", command=bg_caller(self.save)) self.save_button.grid(row=1, column=0) self.appending_var = BooleanVar() self.append_checkbutton = Checkbutton(self.save_frame, text="Append", variable=self.appending_var) self.append_checkbutton.grid(row=1, column=1) self.save_frame.grid()
def checkbutton_component(self, s, r, c, init_val=False, mode=NORMAL, onvalue=-1, offvalue=-1): '''adds a checkbutton, and its associated variable''' if onvalue == -1: var = BooleanVar() var.set(init_val) btn = Checkbutton(self, text=s, variable=var) else: var = StringVar() var.set(init_val) btn = Checkbutton(self, text=s, variable=var, onvalue=onvalue, offvalue=offvalue) btn.grid(row=r, column=c, columnspan=2, sticky=W) btn.config(state=mode) return var
class SearchEngine: """Handles searching a text widget for Find, Replace, and Grep.""" def __init__(self, root): """Initialize Variables that save search state. The dialogs bind these to the UI elements present in the dialogs. """ self.root = root self.patvar = StringVar(root, '') self.revar = BooleanVar(root, False) self.casevar = BooleanVar(root, False) self.wordvar = BooleanVar(root, False) self.wrapvar = BooleanVar(root, True) self.backvar = BooleanVar(root, False) def getpat(self): return self.patvar.get() def setpat(self, pat): self.patvar.set(pat) def isre(self): return self.revar.get() def iscase(self): return self.casevar.get() def isword(self): return self.wordvar.get() def iswrap(self): return self.wrapvar.get() def isback(self): return self.backvar.get() def setcookedpat(self, pat): """Set pattern after escaping if re.""" if self.isre(): pat = re.escape(pat) self.setpat(pat) def getcookedpat(self): pat = self.getpat() if not self.isre(): pat = re.escape(pat) if self.isword(): pat = '\\b%s\\b' % pat return pat def getprog(self): """Return compiled cooked search pattern.""" pat = self.getpat() if not pat: self.report_error(pat, 'Empty regular expression') return None else: pat = self.getcookedpat() flags = 0 if not self.iscase(): flags = flags | re.IGNORECASE try: prog = re.compile(pat, flags) except re.error as what: args = what.args msg = args[0] col = arg[1] if len(args) >= 2 else -1 self.report_error(pat, msg, col) return None return prog def report_error(self, pat, msg, col=-1): msg = 'Error: ' + str(msg) if pat: msg = msg + '\nPattern: ' + str(pat) if col >= 0: msg = msg + '\nOffset: ' + str(col) tkMessageBox.showerror('Regular expression error', msg, master=self.root) def search_text(self, text, prog=None, ok=0): """Return (lineno, matchobj) or None for forward/backward search. This function calls the right function with the right arguments. It directly return the result of that call. Text is a text widget. Prog is a precompiled pattern. The ok parameteris a bit complicated as it has two effects. If there is a selection, the search begin at either end, depending on the direction setting and ok, with ok meaning that the search starts with the selection. Otherwise, search begins at the insert mark. To aid progress, the search functions do not return an empty match at the starting position unless ok is True. """ if not prog: prog = self.getprog() if not prog: return None wrap = self.wrapvar.get() first, last = get_selection(text) if self.isback(): if ok: start = last else: start = first line, col = get_line_col(start) res = self.search_backward(text, prog, line, col, wrap, ok) else: if ok: start = first else: start = last line, col = get_line_col(start) res = self.search_forward(text, prog, line, col, wrap, ok) return res def search_forward(self, text, prog, line, col, wrap, ok=0): wrapped = 0 startline = line chars = text.get('%d.0' % line, '%d.0' % (line + 1)) while chars: m = prog.search(chars[:-1], col) if m: if ok or m.end() > col: return (line, m) line = line + 1 if wrapped and line > startline: break col = 0 ok = 1 chars = text.get('%d.0' % line, '%d.0' % (line + 1)) if not chars and wrap: wrapped = 1 wrap = 0 line = 1 chars = text.get('1.0', '2.0') return None def search_backward(self, text, prog, line, col, wrap, ok=0): wrapped = 0 startline = line chars = text.get('%d.0' % line, '%d.0' % (line + 1)) while 1: m = search_reverse(prog, chars[:-1], col) if m: if ok or m.start() < col: return (line, m) line = line - 1 if wrapped and line < startline: break ok = 1 if line <= 0: if not wrap: break wrapped = 1 wrap = 0 pos = text.index('end-1c') line, col = map(int, pos.split('.')) chars = text.get('%d.0' % line, '%d.0' % (line + 1)) col = len(chars) - 1 return None
def __init__(self, root, engine, flist): SearchDialogBase.__init__(self, root, engine) self.flist = flist self.globvar = StringVar(root) self.recvar = BooleanVar(root)
class GrepDialog(SearchDialogBase): title = "Find in Files Dialog" icon = "Grep" needwrapbutton = 0 def __init__(self, root, engine, flist): SearchDialogBase.__init__(self, root, engine) self.flist = flist self.globvar = StringVar(root) self.recvar = BooleanVar(root) def open(self, text, searchphrase, io=None): SearchDialogBase.open(self, text, searchphrase) if io: path = io.filename or "" else: path = "" dir, base = os.path.split(path) head, tail = os.path.splitext(base) if not tail: tail = ".py" self.globvar.set(os.path.join(dir, "*" + tail)) def create_entries(self): SearchDialogBase.create_entries(self) self.globent = self.make_entry("In files:", self.globvar)[0] 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 create_command_buttons(self): SearchDialogBase.create_command_buttons(self) self.make_button("Search Files", self.default_command, 1) def default_command(self, event=None): prog = self.engine.getprog() if not prog: return path = self.globvar.get() if not path: self.top.bell() return from idlelib.OutputWindow import OutputWindow # leave here! save = sys.stdout try: sys.stdout = OutputWindow(self.flist) self.grep_it(prog, path) finally: sys.stdout = save def grep_it(self, prog, path): dir, base = os.path.split(path) list = self.findfiles(dir, base, self.recvar.get()) list.sort() self.close() pat = self.engine.getpat() print("Searching %r in %s ..." % (pat, path)) hits = 0 try: for fn in list: try: with open(fn) as f: for lineno, line in enumerate(f, 1): if line[-1:] == '\n': line = line[:-1] if prog.search(line): sys.stdout.write("%s: %s: %s\n" % (fn, lineno, line)) hits += 1 except IOError as msg: print(msg) print(("Hits found: %s\n" "(Hint: right-click to open locations.)" % hits) if hits else "No hits.") except AttributeError: # Tk window has been closed, OutputWindow.text = None, # so in OW.write, OW.text.insert fails. pass def findfiles(self, dir, base, rec): try: names = os.listdir(dir or os.curdir) except os.error as msg: print(msg) return [] list = [] subdirs = [] for name in names: fn = os.path.join(dir, name) if os.path.isdir(fn): subdirs.append(fn) else: if fnmatch.fnmatch(name, base): list.append(fn) if rec: for subdir in subdirs: list.extend(self.findfiles(subdir, base, rec)) return list def close(self, event=None): if self.top: self.top.grab_release() self.top.withdraw()
class SearchEngine: """Handles searching a text widget for Find, Replace, and Grep.""" def __init__(self, root): '''Initialize Variables that save search state. The dialogs bind these to the UI elements present in the dialogs. ''' self.root = root # need for report_error() self.patvar = StringVar(root, '') # search pattern self.revar = BooleanVar(root, False) # regular expression? self.casevar = BooleanVar(root, False) # match case? self.wordvar = BooleanVar(root, False) # match whole word? self.wrapvar = BooleanVar(root, True) # wrap around buffer? self.backvar = BooleanVar(root, False) # search backwards? # Access methods def getpat(self): return self.patvar.get() def setpat(self, pat): self.patvar.set(pat) def isre(self): return self.revar.get() def iscase(self): return self.casevar.get() def isword(self): return self.wordvar.get() def iswrap(self): return self.wrapvar.get() def isback(self): return self.backvar.get() # Higher level access methods def setcookedpat(self, pat): "Set pattern after escaping if re." # called only in SearchDialog.py: 66 if self.isre(): pat = re.escape(pat) self.setpat(pat) def getcookedpat(self): pat = self.getpat() if not self.isre(): # if True, see setcookedpat pat = re.escape(pat) if self.isword(): pat = r"\b%s\b" % pat return pat def getprog(self): "Return compiled cooked search pattern." pat = self.getpat() if not pat: self.report_error(pat, "Empty regular expression") return None pat = self.getcookedpat() flags = 0 if not self.iscase(): flags = flags | re.IGNORECASE try: prog = re.compile(pat, flags) except re.error as what: args = what.args msg = args[0] col = arg[1] if len(args) >= 2 else -1 self.report_error(pat, msg, col) return None return prog def report_error(self, pat, msg, col=-1): # Derived class could override this with something fancier msg = "Error: " + str(msg) if pat: msg = msg + "\nPattern: " + str(pat) if col >= 0: msg = msg + "\nOffset: " + str(col) tkMessageBox.showerror("Regular expression error", msg, master=self.root) def search_text(self, text, prog=None, ok=0): '''Return (lineno, matchobj) or None for forward/backward search. This function calls the right function with the right arguments. It directly return the result of that call. Text is a text widget. Prog is a precompiled pattern. The ok parameteris a bit complicated as it has two effects. If there is a selection, the search begin at either end, depending on the direction setting and ok, with ok meaning that the search starts with the selection. Otherwise, search begins at the insert mark. To aid progress, the search functions do not return an empty match at the starting position unless ok is True. ''' if not prog: prog = self.getprog() if not prog: return None # Compilation failed -- stop wrap = self.wrapvar.get() first, last = get_selection(text) if self.isback(): if ok: start = last else: start = first line, col = get_line_col(start) res = self.search_backward(text, prog, line, col, wrap, ok) else: if ok: start = first else: start = last line, col = get_line_col(start) res = self.search_forward(text, prog, line, col, wrap, ok) return res def search_forward(self, text, prog, line, col, wrap, ok=0): wrapped = 0 startline = line chars = text.get("%d.0" % line, "%d.0" % (line+1)) while chars: m = prog.search(chars[:-1], col) if m: if ok or m.end() > col: return line, m line = line + 1 if wrapped and line > startline: break col = 0 ok = 1 chars = text.get("%d.0" % line, "%d.0" % (line+1)) if not chars and wrap: wrapped = 1 wrap = 0 line = 1 chars = text.get("1.0", "2.0") return None def search_backward(self, text, prog, line, col, wrap, ok=0): wrapped = 0 startline = line chars = text.get("%d.0" % line, "%d.0" % (line+1)) while 1: m = search_reverse(prog, chars[:-1], col) if m: if ok or m.start() < col: return line, m line = line - 1 if wrapped and line < startline: break ok = 1 if line <= 0: if not wrap: break wrapped = 1 wrap = 0 pos = text.index("end-1c") line, col = map(int, pos.split(".")) chars = text.get("%d.0" % line, "%d.0" % (line+1)) col = len(chars) - 1 return None
class SearchEngine: def __init__(self, root): self.root = root # State shared by search, replace, and grep; # the search dialogs bind these to UI elements. self.patvar = StringVar(root) # search pattern self.revar = BooleanVar(root) # regular expression? self.casevar = BooleanVar(root) # match case? self.wordvar = BooleanVar(root) # match whole word? self.wrapvar = BooleanVar(root) # wrap around buffer? self.wrapvar.set(1) # (on by default) self.backvar = BooleanVar(root) # search backwards? # Access methods def getpat(self): return self.patvar.get() def setpat(self, pat): self.patvar.set(pat) def isre(self): return self.revar.get() def iscase(self): return self.casevar.get() def isword(self): return self.wordvar.get() def iswrap(self): return self.wrapvar.get() def isback(self): return self.backvar.get() # Higher level access methods def getcookedpat(self): pat = self.getpat() if not self.isre(): pat = re.escape(pat) if self.isword(): pat = r"\b%s\b" % pat return pat def getprog(self): pat = self.getpat() if not pat: self.report_error(pat, "Empty regular expression") return None pat = self.getcookedpat() flags = 0 if not self.iscase(): flags = flags | re.IGNORECASE try: prog = re.compile(pat, flags) except re.error, what: try: msg, col = what except: msg = str(what) col = -1 self.report_error(pat, msg, col) return None return prog
class FileNamePurifierGUI(Frame): appWidth = 480 appHeight = 360 """ TODO: add "old separators" menu (possibly including camelCase and custom) if(camelCase or custom): add logic in Parser add "preserve text" box to prevent wiping of '.' from names when needed add logic to make the separators exclusive add logic to allow the use of camelCase as a separator """ #important instance variables: """ Separators: self.spacesButton self.underscoresButton self.camelcaseButton self.finalCustomSeparator self.periodButton """ """ break up by: self.breakUpByBraces self.breakUpByParens self.breakUpByBrackets self.breakUpByCamelCase """ """ append to: self.finalAppendToFrontText self.finalAppendToEndText """ """ misc: self.affectSubfolders self.cleanFolderNames self.finalRemoveFirstInstanceText """ """ #newSeparator is a string because self.finalCustomSeparator is a string newSeparator = " " if(self.underscoresButton.get()): newSeparator = "_" elif(self.camelcaseButton.get()): pass elif(len(self.finalCustomSeparator) > 0): newSeparator = self.finalCustomSeparator elif(self.periodButton.get()): newSeparator = "." parser = Parser(self.finalAppendToFrontText, self.finalAppendToEndText, [self.finalRemoveFirstInstanceText], [], [], [' ', '_', '.'], newSeparator, self.breakUpByBraces, self.breakUpByParens, self.breakUpByBrackets, self.breakUpByCamelCase, ) """ def __init__(self, parent, width, height): Frame.__init__(self, parent) self.appWidth = width self.appHeight = height self.parent = parent self.initUI() self.centerWindow() self.dir_opt = {} self.finalAppendToEndText = "" self.finalAppendToFrontText = "" self.finalRemoveFirstInstanceText = "" def askDirectory(self): self.addDirectoryText(askdirectory(**self.dir_opt).rstrip('\r\n')) def addDirectoryText(self, stringToAdd): self.directoryText.config(state = NORMAL) self.directoryText.delete("0.0", END) self.directoryText.insert("0.0", stringToAdd.rstrip('\r\n')) self.directoryText.config(state = DISABLED) def GetNewSeparator(self): newSeparator = "" if(self.spacesButton.get()): newSeparator = " "; elif(self.underscoresButton.get()): newSeparator = "_"; elif(self.camelcaseButton.get()): #TODO: implement seperate by camelcase pass elif(self.periodButton.get()): newSeparator = "." elif(len(self.finalCustomSeparator) > 0): newSeparator = self.finalCustomSeparator return newSeparator def ReadOldSeparatorList(self): oldSeparatorList = [] if(self.oldSpacesButton.get()): oldSeparatorList.append(" ") if(self.oldUnderscoresButton.get()): oldSeparatorList.append("_") if(self.oldPeriodButton.get()): oldSeparatorList.append(".") return oldSeparatorList def CreatePurifierForOptions(self): purifier = FileNamePurifier(self.finalAppendToFrontText, self.finalAppendToEndText, [self.finalRemoveFirstInstanceText], [], [], self.ReadOldSeparatorList(), self.GetNewSeparator(), self.breakUpByBraces.get(), self.breakUpByParens.get(), self.breakUpByBrackets.get(), self.breakUpByCamelCase.get(), self.oldCamelcaseButton.get(), self.camelcaseButton.get()) return purifier def purifyFiles(self): if(len(self.directoryText.get("0.0", END)) > 0): selectorAndPurifier = FileSelectorAndPurifier(self.affectSubfolders.get(), self.cleanFolderNames.get(), self.directoryText.get("0.0", END), self.CreatePurifierForOptions()) tkMessageBox.showinfo("FileNamePurifier", "Purifying FileNames. Please Wait.") selectorAndPurifier.PurifyFileNames() tkMessageBox.showinfo("FileNamePurifier", "FileName Purification Complete!") def CreateOldSeparatorMenu(self): self.oldSeparatorMenu = Menu(self.optionsMenu, tearoff=0) self.oldSpacesButton = BooleanVar() self.oldUnderscoresButton = BooleanVar() self.oldCamelcaseButton = BooleanVar() self.oldPeriodButton = BooleanVar() self.oldSeparatorMenu.add_checkbutton(label="Spaces", onvalue=True, offvalue=False, variable=self.oldSpacesButton) self.oldSpacesButton.set(True) self.oldSeparatorMenu.add_checkbutton(label="Underscores", onvalue=True, offvalue=False, variable=self.oldUnderscoresButton) self.oldUnderscoresButton.set(True) #self.oldSeparatorMenu.add_command(label="Custom Separator", command=self.customSeparatorFrame) self.oldSeparatorMenu.add_checkbutton(label="CamelCase", onvalue=True, offvalue=False, variable=self.oldCamelcaseButton) self.oldSeparatorMenu.add_checkbutton(label="Period", onvalue=True, offvalue=False, variable=self.oldPeriodButton) self.optionsMenu.add_cascade(label="Old Separator", menu=self.oldSeparatorMenu) def addSubMenus(self): self.CreateOldSeparatorMenu() self.createNewSeparatorMenu() self.addSubCheckbuttons() self.createBreakUpByMenu() self.createAppendTextMenu() self.optionsMenu.add_command(label="Remove First Instance Of", command=self.removeFirstInstanceFrame) def submitRemoveFirstInstanceText(self): self.finalRemoveFirstInstanceText = self.removeFirstInstanceText.get("0.0", END) def removeFirstInstanceFrame(self): root = Tk() removeFirstInstanceFrame = Frame(root) removeFirstInstanceFrame.pack(fill=BOTH, expand=1) self.removeFirstInstanceText = Text(removeFirstInstanceFrame) self.removeFirstInstanceText.config(width = 80, height = 1) self.removeFirstInstanceText.pack() removeFirstButton = Button(removeFirstInstanceFrame, text="Submit", command=self.submitRemoveFirstInstanceText) removeFirstButton.pack() root.title("Enter text to remove the first instance of: ") root.mainloop() def submitAppendToFrontText(self): self.finalAppendToFrontText = self.appendToFrontText.get("0.0", END) def appendToFrontFrame(self): root = Tk() frame= Frame(root) frame.pack(fill=BOTH, expand=1) self.appendToFrontText = Text(frame) self.appendToFrontText.config(width = 80, height = 1) self.appendToFrontText.pack() submitButton = Button(frame, text="Submit", command=self.submitAppendToFrontText) submitButton.pack() root.title("Enter text to append to the front: ") root.mainloop() def submitAppendToEndText(self): self.finalAppendToEndText = self.appendToEndText.get("0.0", END) def appendToEndFrame(self): root = Tk() frame= Frame(root) frame.pack(fill=BOTH, expand=1) self.appendToEndText = Text(frame) self.appendToEndText.config(width = 80, height = 1) self.appendToEndText.pack() submitButton = Button(frame, text="Submit", command=self.submitAppendToEndText) submitButton.pack() root.title("Enter text to append to the end: ") root.mainloop() def createAppendTextMenu(self): self.appendText = Menu(self.optionsMenu, tearoff=0) self.appendText.add_command(label="Append To Front", command=self.appendToFrontFrame) self.appendText.add_command(label="Append To End", command=self.appendToEndFrame) self.optionsMenu.add_cascade(label="Append Text", menu=self.appendText) def createBreakUpByMenu(self): self.delimitersMenu = Menu(self.optionsMenu, tearoff=0) self.breakUpByBraces = BooleanVar() self.breakUpByParens = BooleanVar() self.breakUpByBrackets = BooleanVar() self.breakUpByCamelCase = BooleanVar() self.breakUpByParens.set(True) self.breakUpByBrackets.set(True) self.delimitersMenu.add_checkbutton(label="Braces", onvalue=True, offvalue=False, variable=self.breakUpByBraces) self.delimitersMenu.add_checkbutton(label="Parentheses", onvalue=True, offvalue=False, variable=self.breakUpByParens) self.delimitersMenu.add_checkbutton(label="Brackets", onvalue=True, offvalue=False, variable=self.breakUpByBrackets) self.delimitersMenu.add_checkbutton(label="CamelCase", onvalue=True, offvalue=False, variable=self.breakUpByCamelCase) self.optionsMenu.add_cascade(label="Delimiters", menu=self.delimitersMenu) def submitCustomSeparator(self): self.finalCustomSeparator = self.customSeparator.get("0.0", END) def customSeparatorFrame(self): root = Tk() frame= Frame(root) frame.pack(fill=BOTH, expand=1) self.customSeparator = Text(frame) self.customSeparator.config(width = 80, height = 1) self.customSeparator.pack() submitButton = Button(frame, text="Submit", command=self.submitCustomSeparator) submitButton.pack() root.title("Enter a custom separator:") root.mainloop() def ToggleNonUnderscoresOff(self): self.spacesButton.set(False) self.camelcaseButton.set(False) self.periodButton.set(False) def ToggleNonSpacesOff(self): self.underscoresButton.set(False) self.camelcaseButton.set(False) self.periodButton.set(False) def ToggleNonCamelCaseOff(self): self.spacesButton.set(False) self.underscoresButton.set(False) self.periodButton.set(False) def ToggleNonPeriodOff(self): self.spacesButton.set(False) self.camelcaseButton.set(False) self.underscoresButton.set(False) def createNewSeparatorMenu(self): self.newSeparatorMenu = Menu(self.optionsMenu, tearoff=0) self.spacesButton = BooleanVar() self.underscoresButton = BooleanVar() self.camelcaseButton = BooleanVar() self.periodButton = BooleanVar() self.newSeparatorMenu.add_checkbutton(label="Spaces", onvalue=True, offvalue=False, variable=self.spacesButton, command=self.ToggleNonSpacesOff) self.spacesButton.set(True) self.newSeparatorMenu.add_checkbutton(label="Underscores", onvalue=True, offvalue=False, variable=self.underscoresButton, command=self.ToggleNonUnderscoresOff) self.newSeparatorMenu.add_command(label="Custom Separator", command=self.customSeparatorFrame) self.newSeparatorMenu.add_checkbutton(label="CamelCase", onvalue=True, offvalue=False, variable=self.camelcaseButton, command=self.ToggleNonCamelCaseOff) self.newSeparatorMenu.add_checkbutton(label="Period", onvalue=True, offvalue=False, variable=self.periodButton, command=self.ToggleNonPeriodOff) self.optionsMenu.add_cascade(label="New Separator", menu=self.newSeparatorMenu) def addSubCheckbuttons(self): self.affectSubfolders = BooleanVar() self.cleanFolderNames = BooleanVar() self.optionsMenu.add_checkbutton(label="Affect Subfolders", onvalue=True, offvalue=False, variable=self.affectSubfolders) self.optionsMenu.add_checkbutton(label="Clean Folder Names", onvalue=True, offvalue=False, variable=self.cleanFolderNames) self.affectSubfolders.set(True) self.cleanFolderNames.set(True) def initUI(self): self.parent.title("Filename Purifier") self.pack(fill=BOTH, expand=1) self.directoryButton = Button(self, text="Choose Directory", command=self.askDirectory) self.directoryButton.place(x = self.appWidth/3, y = 70) self.directoryText = Text() self.directoryText.config(width = 40, height = 1) self.directoryText.config(state = DISABLED) self.directoryText.place(x = 100, y = 120) self.purifyButton = Button(self, text="Purify Files", command=self.purifyFiles) self.purifyButton.place(x = self.appWidth/3 + 25, y = 170) self.menubar = Menu(self) self.optionsMenu = Menu(self.menubar, tearoff=0) self.addSubMenus() self.menubar.add_cascade(label="Options", menu=self.optionsMenu) self.parent.config(menu=self.menubar) def centerWindow(self): screenWidth = self.parent.winfo_screenwidth() screenHeight = self.parent.winfo_screenheight() x = (screenWidth - self.appWidth)/2 y = (screenHeight - self.appHeight)/2 self.parent.geometry('%dx%d+%d+%d' % (self.appWidth, self.appHeight, x, y))