def __init__(self, app, font): self.app = app self.frame = LabelFrame( app.frame, text='LEDs and Switches', font=font, ) self.LEDs = [] self.switches = [] for column in range(8): LED_var = IntVar(self.frame) LED = Checkbutton( self.frame, indicatoron=0, selectcolor='#8080ff', text=str(column), variable=LED_var, ) LED.bind('<Button-1>', lambda _: 'break') # Output only. LED.grid(row=0, column=7 - column) switch_var = IntVar(self.frame) switch = Checkbutton( self.frame, command=(lambda i=column: self._set_switch(i)), variable=switch_var, ) switch.grid(row=1, column=7 - column) self.LEDs.append(LED_var) self.switches.append(switch_var) self._monkey_patch_LED_write(self.app.cpu)
def __init__(self, parentwin, kvgrouppairs, flyoverfn, baserow=6): # CSV Generation options check button self.master = parentwin self.kvgrouppairs = kvgrouppairs self.flyoverfn = flyoverfn # the checkbox gui items to enable / disable various optional activities self.delbutton = Checkbutton(parentwin, text="Delete\nselected", variable=self.kvgrouppairs['DeleteCheck'], onvalue=True, offvalue=False).grid(row=baserow + 15, column=4, columnspan=1, sticky=W) self.copycheckbutton = Checkbutton( parentwin, text="Copy\nselected", variable=self.kvgrouppairs['CopyCheck'], onvalue=True, offvalue=False).grid(row=baserow + 15, column=3, columnspan=1, sticky=W) self.printcheckbutton = Checkbutton( parentwin, text="Print CSV recs", variable=self.kvgrouppairs['PrintCheck'], onvalue=True, offvalue=False).grid(row=baserow + 15, column=2, columnspan=1, sticky=W) self.dupcheckbutton = Checkbutton( parentwin, text="Dup checking", variable=self.kvgrouppairs['DupCheck'], onvalue=True, offvalue=False).grid(row=baserow + 15, column=1, columnspan=1, sticky=W) # note that we don't need to keep the handle to the check buttons so they are not instance self.xx variables timercheckbutton = Checkbutton( parentwin, text="Timer enable", variable=self.kvgrouppairs['TimerCheck'], onvalue=True, offvalue=False) timercheckbutton.grid(row=baserow + 15, column=0, columnspan=1, sticky=W) timercheckbutton.bind( "<Enter>", lambda event: self.flyoverfn( "You can turn the timer off so that timer won't monitor insertion/removal automatically\n\n\n" )) timercheckbutton.bind("<Leave>", self.flyoverfn(None))
def create_checkbutton(self): P0, widget_dims, board_dims = self.board.get_geometry() x, y = P0 width, height = widget_dims board_width, board_height = board_dims x, y = x / board_width, y / board_height width, height = width / board_width, height / board_height button = Checkbutton(self.board) button.place(relx=x, rely=y, relheight=height, relwidth=width, anchor="nw") self.board.delete("line") items = [item for item in button.keys() if len(item) > 2] button.bind("<Enter>", lambda event: self.get_widget_info(button)) button.bind("<Leave>", lambda event: self.focus_out()) button.bind("<Button-3>", lambda event: self.modify(button, items)) self.manager.switch(button, items)
def queryDatesAndTimes(allConts, malport): dates=[] returnDates = [] dateButtons = [] dateValues=[] returnTimes = [] timeButtons = [] timeValues=[] today = datetime.now() daysForward = "" if today.weekday()<2: daysForward = 3 else: daysForward = 5 for i in range(daysForward+1): thisDay = getDaysForward(i, True) if thisDay: dates.append(thisDay) bgC = "lavender" top = Tk() top.config(bg = bgC) L1 = Label(top, text="Please select the acceptable dates/times\nfor the new RVs\n(Hold shift to select all since last selection)", bg = bgC, padx = 20) L1.config(font=("serif", 16)) L1.grid(row=0, column=0, sticky=constants.W+constants.E, columnspan = 2) start = [0] i=1 def selectstart(start, chkbuttons, event): start[0]= chkbuttons.index(event.widget) def selectrange(start, chkbuttons, event): startLocal = start[0] end = chkbuttons.index(event.widget) sl = slice(min(startLocal, end)+1, max(startLocal, end)) for cb in chkbuttons[sl]: cb.toggle() start[0] = startLocal for date in dates: check = BooleanVar() checkButton = Checkbutton(top, text=date, variable=check, bg="royal blue", font=("serif", 12)) checkButton.grid(row=i, column=0, sticky=constants.W+constants.E, pady=0) # if malport: # checkButton.grid(columnspan=2) if i>1 and allConts: check.set(True) i+=1 checkButton.bind("<Button-1>", lambda event: selectstart(start, dateButtons, event)) checkButton.bind("<Shift-Button-1>", lambda event: selectrange(start, dateButtons, event)) dateButtons.append(checkButton) dateValues.append((check, date)) if not malport: time_Order = ["04", "05","06","07","08","09","10","11","12","13","14","16","18","19","20", "00"] else: # time_Order = ["06","11","14","16","18", "00"] # f=open(r"C:\Automation\CNPort.txt", 'r') time_Order=[] # f=open(r"J:\LOCAL DEPARTMENT\Automation - DO NOT MOVE\Malport Hours.txt", 'r') f=open(r"C:\Automation\Malport Hours.txt", 'r') # read = f.readline() # m = re.search("username: *", read) # username = read[m.end():].rstrip() read = f.readline() while read != "": if read == "\n": continue else: read = read.strip() if len(read)==1: read = "0"+read if len(read)==2: read+=":00" if len(read)==4 and not ":" in read: read=read[:2]+":"+read[2:] elif len(read)==4: read = "0"+read time_Order.append(read) read = f.readline() f.close() # time_Order = ["06","08","10","12","14","16","18","20", "00"] for i in range(len(time_Order)): check=BooleanVar() if len(time_Order[i])==2: cb = Checkbutton(text=time_Order[i]+":00",padx=0,pady=0,bd=0, variable=check, bg="dark violet", font=("serif", 12)) else: cb = Checkbutton(text=time_Order[i],padx=0,pady=0,bd=0, variable=check, bg="dark violet", font=("serif", 12)) cb.grid(row = i+1, column = 1, sticky=constants.W+constants.E+constants.N+constants.S) cb.bind("<Button-1>", lambda event: selectstart(start, timeButtons, event)) cb.bind("<Shift-Button-1>", lambda event: selectrange(start, timeButtons, event)) timeValues.append((check, time_Order[i])) timeButtons.append(cb) def callbackDates(): for button, date in dateValues: if button.get(): returnDates.append(date) if len(returnDates)<1: popUpOKLeft("Please select target dates for the new RV(s)") for button, time in timeValues: if button.get(): returnTimes.append(time) top.destroy() MyButton = Button(top, text="OK", command=callbackDates) MyButton.grid(row=i+2, column=0, sticky=constants.W+constants.E, padx = 20, pady = (0,20), columnspan = 2) MyButton.config(font=("serif", 30), bg="green") top.update() w = top.winfo_width() # width for the Tk root h = top.winfo_height() # height for the Tk root ws = top.winfo_screenwidth() # width of the screen hs = top.winfo_screenheight() # height of the screen x = (ws/2) - (w/2) y = (hs/2) - (h/2) top.geometry('%dx%d+%d+%d' % (w, h, x, y)) top.update() top.lift() top.attributes('-topmost',True) top.after_idle(top.attributes,'-topmost',False) if not malport: moveTo(MyButton.winfo_width()/2 + MyButton.winfo_rootx(), MyButton.winfo_height()/2 + MyButton.winfo_rooty()) top.mainloop() # if not malport: if len(returnTimes)<1: returnTimes = ["04", "05","06","07","08","09","10","11","12","13","14","16"] # else: # if len(returnTimes)<1: # returnTimes = ["06","08","10","12","14","16"] # else: # returnTimes = ["00"] return returnDates, returnTimes
class MainWindow: def __init__(self, master): self.FORMAT = {0: '.pdf', 1: '.jpg'} self.SETTINGS_DPI = {0: 72, 1: 100, 2: 150} self.SETTINGS_COLOR = {0: '1', 1: 'RGB'} self.list_files = '' self.filename = '' self.lenght_list_files = '' #################################################################################################### # A1 # 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9 # 10 # # A2 # BUTTON # TEXT # TEXT # TEXT # TEXT # TEXT # TEXT # TEXT # VSCROLL # 10 # # A3 # BUTTON # TEXT # TEXT # TEXT # TEXT # TEXT # TEXT # TEXT # VSCROLL # 10 # # A4 # BUTTON # TEXT # TEXT # TEXT # TEXT # TEXT # TEXT # TEXT # VSCROLL # 10 # # A5 # BUTTON # TEXT # TEXT # TEXT # TEXT # TEXT # TEXT # TEXT # VSCROLL # 10 # # A6 # 1 # HSCROLL # HSCROLL # HSCROLL # HSCROLL # HSCROLL # HSCROLL # HSCROLL # HSCROLL # 10 # # A7 # FORMAT # SPLIT # SPLIT # DPI # DPI # COLOR # COLOR # QUALITY # QUALITY # 10 # # A8 # FORMAT # SPLIT # SPLIT # DPI # DPI # COLOR # COLOR # QUALITY # QUALITY # 10 # # A9 # FORMAT # SPLIT # SPLIT # DPI # DPI # COLOR # COLOR # QUALITY # QUALITY # 10 # # A10# P_BAR # P_BAR # P_BAR # P_BAR # P_BAR # P_BAR # P_BAR # P_BAR # P_BAR # 10 # #################################################################################################### self.text_box = Text(master, wrap='char', width=80, height=16) self.vscroll_text_box = Scrollbar( master, orient='vertical', command=self.text_box.yview()) self.hscroll_text_box = Scrollbar( master, orient='horizontal', command=self.text_box.xview()) self.text_box.config(yscrollcommand=self.vscroll_text_box.set, xscrollcommand=self.hscroll_text_box.set) self.text_box.grid(row=2, column=2, rowspan=4, columnspan=7) self.vscroll_text_box.grid( row=2, column=9, rowspan=4, sticky=('se', 'ne')) self.hscroll_text_box.grid( row=6, column=2, columnspan=8, sticky=('we', 'ne')) # # # Настройки формата файла self.labelframe_format = LabelFrame( master, text="Формат файла") self.labelframe_format.grid( row=7, column=1, columnspan=1, rowspan=3, sticky='wens') self.format_output_file = IntVar() self.format_output_file.set(0) self.radiobutton_pdf = Radiobutton(self.labelframe_format, text='Формат PDF', variable=self.format_output_file, value=0, command=self.shutdown_button) self.radiobutton_jpg = Radiobutton(self.labelframe_format, text='Формат JPEG', variable=self.format_output_file, value=1, command=self.shutdown_button) self.radiobutton_pdf.pack(fill='x') self.radiobutton_jpg.pack(fill='x') # # # Задаём фрейм в котором будем размещать настройки разделения self.labelframe_split = LabelFrame(master, text="Развибка на страницы") self.labelframe_split.grid( row=7, column=2, columnspan=2, rowspan=3, sticky='wens') self.scale_split = Scale(self.labelframe_split, from_=0, to=100, resolution=5, orient="horizontal") self.scale_split.pack(fill='both') # # # Задаём фрейм в котором будем размещать настройки качества файла self.labelframe_dpi = LabelFrame(master, text="Настройки качества") self.labelframe_dpi.grid( row=7, column=4, columnspan=2, rowspan=3, sticky='wens') self.dpi = IntVar() self.dpi.set(2) self.radiobutton_dpi_72 = Radiobutton(self.labelframe_dpi, text='Среднее', variable=self.dpi, value=0) self.radiobutton_dpi_100 = Radiobutton(self.labelframe_dpi, text='Хорошее', variable=self.dpi, value=1) self.radiobutton_dpi_150 = Radiobutton(self.labelframe_dpi, text='Отличное', variable=self.dpi, value=2) self.radiobutton_dpi_72.pack(fill='both') self.radiobutton_dpi_100.pack(fill='both') self.radiobutton_dpi_150.pack(fill='both') # # # Фрейм с настройками выбора цветное или ч/б self.labelframe_color = LabelFrame(master, text="Настройки цвета") self.labelframe_color.grid( row=7, column=6, columnspan=2, rowspan=3, sticky='wens') self.color = IntVar() self.color.set(0) self.radiobutton_bw = Radiobutton(self.labelframe_color, text='Чёрно/белое', variable=self.color, value=0) self.radiobutton_color = Radiobutton(self.labelframe_color, text='Цветное', variable=self.color, value=1) self.radiobutton_bw.pack(fill='both') self.radiobutton_color.pack(fill='both') # # # Фрейм с настройками качества сжатия JPEG self.labelframe_quality = LabelFrame( master, text="Настройка сжатия файла") self.labelframe_quality.grid( row=7, column=8, columnspan=2, rowspan=3, sticky='nw ne') self.scale_quality = Scale(self.labelframe_quality, label='Хуже Лучше', from_=1, to=100, resolution=1, orient="horizontal", state='active') self.scale_quality.set(100) self.scale_quality.pack(fill='both') # # # Чекбокс настройки оптимизации качества self.optimize_image = BooleanVar() self.optimize_image.set(False) self.checkbutton_optimize = Checkbutton( self.labelframe_quality, text='Автоматически', variable=self.optimize_image, onvalue=True, offvalue=False) self.checkbutton_optimize.pack() self.checkbutton_optimize.bind( '<Button>', lambda event: self.change_state(event)) # # # Задаем фрейм в котором будем размещать основные кнопки команд self.button_frame = Frame(master) self.button_frame.grid(row=2, column=1, rowspan=4) self.button_open = Button(self.button_frame, text="Добавить файлы", command=self.listFiles, state='active', pady=5, padx=8) self.button_open.pack() self.button_save = Button(self.button_frame, text="Сохранить файл", command=self.savefileName, state='active', pady=5, padx=9) self.button_save.pack() self.button_run = Button(self.button_frame, text="Запустить", command=lambda x=True: ConvertFile().process( input_file=self.list_files, output_file=self.filename, format_file=self.FORMAT[self.format_output_file.get( )], dpi=self.SETTINGS_DPI[self.dpi.get()], color=self.SETTINGS_COLOR[self.color.get()], optimize=self.optimize_image.get(), quality=self.scale_quality.get(), split_step=self.scale_split.get()), state='active', pady=5, padx=26) self.button_run.pack() # # # Progressbar self.pbar = ttk.Progressbar( master, orient='horizontal', mode='determinate', length=100, maximum=100) self.pbar.grid(row=10, column=1, columnspan=9, sticky='wens') # # # Меню программы self.menu = Menu(master) master.config(menu=self.menu) self.sub_menu1 = Menu(self.menu) self.menu.add_cascade(label='Файл', menu=self.sub_menu1) self.sub_menu1.add_command(label='Выход', command=self.closed_window) self.sub_menu2 = Menu(self.menu) self.menu.add_cascade(label='Информация', menu=self.sub_menu2) self.sub_menu2.add_command( label='О программе', command=self.show_about) def frange(self, start, stop, step): while start < stop: yield start start += step def change_state(self, event): if self.optimize_image.get() is False: self.scale_quality.config(state='disable') else: self.scale_quality.config(state='active') def shutdown_button(self): if self.format_output_file.get() == 1: self.button_save.config(state='disable') else: self.button_save.config(state='active') def update_progressbar(self, page): step = 100 / self.lenght_list_files step_range = list(self.frange(0, 100, step)) self.pbar['value'] = step_range[page] + step root.update() def show_about(self): messagebox.showinfo( title='О программе', message=ABOUT) def show_error(self, message): messagebox.showerror(title='ОШИБКА', message=message) def closed_window(self): root.quit() def listFiles(self): """ Функция привязана к кнопке "Добавить файлы". Результат работы функции - список файлов, который отображается в поле text_box """ self.list_files = filedialog.askopenfilenames() self.lenght_list_files = len(self.list_files) self.text_box.delete(1.0, END) for i in self.list_files: self.text_box.insert(END, i) self.text_box.insert(END, '\n') return self.list_files def savefileName(self): """ Функция привязана к кнопке "Сохранить файл". Результат работы функции - полный путь к выходному файлу """ default = self.FORMAT[0] setting_format = self.FORMAT[self.format_output_file.get()] self.filename = filedialog.asksaveasfilename(filetypes=[(f"Формат файла *{setting_format}", f"*{setting_format}")], defaultextension=default) return self.filename
class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.send_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind((host, port)) self.grid() self.columnconfigure(0, minsize=100) self.columnconfigure(1, minsize=200) self.columnconfigure(2, minsize=200) self.columnconfigure(3, minsize=150) self.columnconfigure(4, minsize=150) self.columnconfigure(5, minsize=150) self.columnconfigure(6, minsize=150) self.create_widgets() self.settables = self.assemble_settables() self.gui_logger = logging.getLogger('gui') self.request_update() def create_widgets(self): self.create_monitor() self.create_check_buttons() self.create_ranges() self.create_scales() self.create_radio_buttons() self.create_voices() self.quitButton = Button(self, text='Quit', command=self.quit) self.quitButton.grid(columnspan=7, sticky=E + W) def assemble_settables(self): settables = self.winfo_children() for w in settables: settables += w.winfo_children() return [w for w in settables if w.__class__.__name__ in ['Scale', 'Checkbutton']] def create_radio_buttons(self): # Scale related entries = ['DIATONIC', 'HARMONIC', 'MELODIC', 'PENTATONIC', 'PENTA_MINOR', 'GREEK_CHROMATIC', 'GREEK_ENHARMONIC'] self.scale = StringVar() self.scale.set('DIATONIC') self.rb_frame = Frame(self) for e in entries: rb = Radiobutton(self.rb_frame, value=e, text=e, anchor=W, command=self.send_scale, variable=self.scale) rb.grid(row=len(self.rb_frame.winfo_children()), sticky=W) self.rb_frame.grid(column=1, row=len(self.grid_slaves(column=1)), rowspan=3) def create_monitor(self): self.monitor_frame = LabelFrame(self, text="Monitor and Transport") this_cycle = Scale(self.monitor_frame, label='cycle_pos', orient=HORIZONTAL, from_=1, to=16, resolution=1) this_cycle.disable, this_cycle.enable = (None, None) this_cycle.ref = 'cycle_pos' this_cycle.grid(column=0, row=0, sticky=E + W) self.updateButton = Button(self.monitor_frame, text='Reload all Settings', command=self.request_update) self.updateButton.grid(row=1, sticky=E + W) self.ForceCaesuraButton = Button(self.monitor_frame, text='Force Caesura', command=self.force_caesura) self.ForceCaesuraButton.grid(row=2, sticky=E + W) self.saveBehaviourButton = Button(self.monitor_frame, text='Save current behaviour', command=self.request_saving_behaviour) self.saveBehaviourButton.grid(row=3, sticky=E + W) self.saveBehaviourNameEntry = Entry(self.monitor_frame) self.saveBehaviourNameEntry.grid(row=4, sticky=E + W) self.saveBehaviourNameEntry.bind('<KeyRelease>', self.request_saving_behaviour) self.selected_behaviour = StringVar() self.selected_behaviour.trace('w', self.new_behaviour_chosen) self.savedBehavioursMenu = OptionMenu(self.monitor_frame, self.selected_behaviour, None,) self.savedBehavioursMenu.grid(row=5, sticky=E + W) self.monitor_frame.grid(column=0, row=10, sticky=E + W) def request_update(self): self.send({'sys': 'update'}) def request_saving_behaviour(self, event=None): """callback for save behaviour button and textentry""" if event and event.widget == self.saveBehaviourNameEntry: if event.keysym == 'Return': name = self.saveBehaviourNameEntry.get() self.saveBehaviourNameEntry.delete(0, len(name)) else: return else: # button was pressed name = self.saveBehaviourNameEntry.get() if name: self.send({'sys': ['save_behaviour', name]}) def force_caesura(self): self.send({'force_caesura': True}) def create_voices(self): voice_ids = ['1', '2', '3', '4'] SCALES = OrderedDict([ ('pan_pos', {'min': -1, 'max': 1, 'start': 0.5, 'res': 0.001}), ('volume', {'min': 0, 'max': 1, 'start': 0.666, 'res': 0.001}), ('slide_duration_msecs', {'min': 0, 'max': 2000, 'start': 60, 'res': 1}), ('slide_duration_prop', {'min': 0, 'max': 2, 'start': 0.666, 'res': 0.001}), ('binaural_diff', {'min': 0, 'max': 66, 'start': 0.2, 'res': 0.01}) ]) for vid in voice_ids: counter = 0 for sca in SCALES: name = 'voice_' + vid + '_' + sca setattr(self, 'min_' + name, SCALES[sca]['min']) setattr(self, 'max_' + name, SCALES[sca]['max']) this_sca = Scale(self, label=sca, orient=HORIZONTAL, from_=getattr(self, 'min_' + name), to=getattr(self, 'max_' + name), resolution=SCALES[sca]['res']) this_sca.enable = ('enable' in list(SCALES[sca].keys()) and SCALES[sca]['enable'] or None) this_sca.disable = ('disable' in list(SCALES[sca].keys()) and SCALES[sca]['disable'] or None) this_sca.grid(column=int(2 + int(vid)), row=counter, sticky=E + W) this_sca.bind("<ButtonRelease>", self.scale_handler) this_sca.ref = name counter += 1 CHECK_BUTTONS = OrderedDict( [('mute', False), ('automate_binaural_diffs', True), ('automate_note_duration_prop', True), ('use_proportional_slide_duration', {'val': True, 'label': 'proportional slide'}), ('automate_pan', True), ('automate_wavetables', True)]) for vid in voice_ids: counter = 0 cb_frame = LabelFrame(self, text="Voice {0} - Automation".format(vid)) setattr(self, 'voice_' + vid + '_cb_frame', cb_frame) for cb in CHECK_BUTTONS: options = CHECK_BUTTONS[cb] name = 'voice_' + vid + '_' + cb if isinstance(options, dict) and 'label' in list(options.keys()): label = options['label'] else: label = cb[9:] if cb[:9] == 'automate_' else cb setattr(self, name, IntVar( value=type(options) == dict and options['val'] or options)) self.this_cb = Checkbutton(cb_frame, text=label, variable=getattr(self, name)) self.this_cb.bind('<Button-1>', self.check_boxes_handler) self.this_cb.disable = None self.this_cb.grid(sticky=W, column=0, row=counter) self.this_cb.ref = name counter += 1 # add trigger wavetable-button trigWavetableButton = Button(cb_frame, text='Next Wavetable') trigWavetableButton.bind('<Button-1>', self.trigger_waveform_handler) trigWavetableButton.ref = 'voice_' + vid + "_trigger_wavetable" trigWavetableButton.grid(row=counter) cb_frame.grid(column=int(vid) + 2, row=5, sticky=E + W + N, rowspan=8) for vid in voice_ids: generation_types = ["random", "random_harmonic", "harmonic"] partial_pools = ["even", "odd", "all"] prefix = 'voice_' + vid + '_' types_name = prefix + 'wavetable_generation_type' pools_name = prefix + 'partial_pool' setattr(self, types_name, StringVar()) getattr(self, types_name).set("random") setattr(self, pools_name, StringVar()) getattr(self, pools_name).set("all") target_frame = getattr(self, 'voice_' + vid + '_cb_frame') gen_typ_frame = LabelFrame(target_frame, text="type") gen_typ_frame.grid(row=len(target_frame.winfo_children()), sticky=W) for gen_t in generation_types: gen_t_entry = Radiobutton(gen_typ_frame, value=gen_t, text=gen_t, anchor=W, variable=getattr(self, types_name)) gen_t_entry.bind('<ButtonRelease-1>', self.wt_handler) gen_t_entry.ref = types_name gen_t_entry.grid(row=len(gen_typ_frame.winfo_children()), sticky=W) pp_frame = LabelFrame(target_frame, text="harmonics") for pp in partial_pools: pp_entry = Radiobutton(pp_frame, value=pp, text=pp, anchor=W, variable=getattr(self, pools_name)) pp_entry.bind('<ButtonRelease-1>', self.wt_handler) pp_entry.ref = pools_name pp_entry.grid(row=len(pp_frame.winfo_children()), sticky=E + W) this_num_partials = Scale(pp_frame, label='number of harmonics', orient=HORIZONTAL, from_=1, to=24, resolution=1) this_num_partials.ref = prefix + 'num_partials' this_num_partials.grid(column=0, row=len(pp_frame.winfo_children()), sticky=E + W) this_num_partials.bind("<ButtonRelease>", self.scale_handler) pp_frame.grid(row=len(target_frame.winfo_children()), sticky=E + W) def wt_handler(self, event): print(event.widget.tk) ref = event.widget.ref self.send({ref: getattr(self, ref).get()}) 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) def new_behaviour_chosen(self, a, b, c): self.send({'sys': ['change_behaviour', self.selected_behaviour.get()]}) def set_value(self, name, val): '''sets a widget to the specified value various different widget types need custom setting functionality''' direct = ['scale', 'wavetable_generation_type', 'partial_pool'] if [x for x in direct if match("(voice_\d_|)" + x, name)]: self.gui_logger.info("setting: '{0}' to '{1}' in GUI".format(name, val)) getattr(self, name).set(val) return if name == 'saved_behaviours' and len(val): self.savedBehavioursMenu.destroy() self.savedBehavioursMenu = OptionMenu(self.monitor_frame, self.selected_behaviour, *sorted(val)) self.savedBehavioursMenu.grid(row=5, sticky=E + W) return for w in self.settables: typ = w.__class__.__name__ if w.ref == name: # print "setting '{0}' of type: '{1}' to: {2}".format(name, typ, val) if typ == 'Scale': w.set(val) elif typ == "Checkbutton": w.select() if val else w.deselect() def check_boxes_handler(self, event): '''handles checkbox events. shows and hides gui elements according to their enable/disable fields''' # print event.__dict__ # print event.widget.__dict__ ref = event.widget.ref val = not getattr(self, ref).get() # because is read before the var is changed self.send({ref: val}) # print ref, val # handle gui elements # enable/disable functionality temporarily(?) commented on: # Wed Aug 17 09:39:54 CEST 2011 # if event.widget.disable: # for w in self.children.values(): # # # this try clause is for debugging, remove when stable # try: # w.ref # #print w.ref # except: # pass # if (w.__class__.__name__ == 'Scale' and # (w.disable or w.enable)): # if w.disable == ref: # if val: # w.grid() # else: # w.grid_remove() # elif w.enable == ref: # if val: # w.grid_remove() # else: # w.grid() # #print w.disable, w.enable def create_scales(self): counter = 0 for sca in SCALES: label = SCALES[sca]['label'] if 'label' in list(SCALES[sca].keys()) else sca setattr(self, 'min_' + sca, SCALES[sca]['min']) setattr(self, 'max_' + sca, SCALES[sca]['max']) self.this_scale = Scale(self, label=label, orient=HORIZONTAL, from_=getattr(self, 'min_' + sca), to=getattr(self, 'max_' + sca), resolution=SCALES[sca]['res']) self.this_scale.set(SCALES[sca]['start']) self.this_scale.enable = ('enable' in list(SCALES[sca].keys()) and SCALES[sca]['enable'] or None) self.this_scale.disable = ('disable' in list(SCALES[sca].keys()) and SCALES[sca]['disable'] or None) if 'pos' in list(SCALES[sca].keys()): pos = SCALES[sca]['pos'] col = pos['c'] row = pos['r'] else: row = counter col = 1 counter += 1 self.this_scale.grid(column=col, row=row, sticky=E + W) self.this_scale.ref = sca self.this_scale.bind("<ButtonRelease>", self.scale_handler) def scale_handler(self, event): self.send({event.widget.ref: event.widget.get()}) self.gui_logger.info("handling scale: {0}, with new value: {1}".format( event.widget.ref, event.widget.get())) def trigger_waveform_handler(self, event): self.send({event.widget.ref: True}) # print event.widget.ref, "- triggering wavetable" def send_scale(self): do = {'scale': self.scale.get()} self.send(do) def send(self, msg): self.gui_logger.info("sending: {0}".format(msg)) self.send_sock.sendto(json.dumps(msg), (remote_host, send_port)) def create_ranges(self): counter = 0 for ran in RANGES: setattr(self, 'min_' + ran, RANGES[ran]['min']) setattr(self, 'max_' + ran, RANGES[ran]['max']) self.this_min_scale = Scale(self, label='min ' + ran, orient=HORIZONTAL, from_=getattr(self, 'min_' + ran), to=getattr(self, 'max_' + ran), resolution=RANGES[ran]['res']) self.this_max_scale = Scale(self, label='max ' + ran, orient=HORIZONTAL, from_=getattr(self, 'min_' + ran), to=getattr(self, 'max_' + ran), resolution=RANGES[ran]['res']) self.this_min_scale.set(RANGES[ran]['min_start']) self.this_max_scale.set(RANGES[ran]['max_start']) self.this_min_scale.enable = ('enable' in list(RANGES[ran].keys()) and RANGES[ran]['enable'] or None) self.this_min_scale.disable = ('disable' in list(RANGES[ran].keys()) and RANGES[ran]['disable'] or None) self.this_max_scale.enable = ('enable' in list(RANGES[ran].keys()) and RANGES[ran]['enable'] or None) self.this_max_scale.disable = ('disable' in list(RANGES[ran].keys()) and RANGES[ran]['disable'] or None) self.this_min_scale.grid(column=2, row=counter, sticky=E + W) self.this_max_scale.grid(column=2, row=counter + 1, sticky=E + W) self.this_min_scale.ref = 'min_' + ran self.this_max_scale.ref = 'max_' + ran self.this_min_scale.bind("<ButtonRelease>", self.scale_handler) self.this_max_scale.bind("<ButtonRelease>", self.scale_handler) counter += 2 def socket_read_handler(self, file, mask): data_object = json.loads(file.recv(1024)) do = list(data_object.items())[0] self.set_value(do[0], do[1])
class LoginWindow: def __init__(self, master): self.master = master # Variables self.is_checked = IntVar() # Widgets self.tl_login = Toplevel() self.tl_login.title('Simple Email Client v1.0') self.credential_frame = Frame(self.tl_login) self.label_info = Label(self.credential_frame, text='Enter your email address and password.') self.label_user = Label(self.credential_frame, text='Username: '******'Password: '******'*') self.button_verify = Button(self.tl_login, text='Sign In', command=self.verify_user) self.check_password = Checkbutton(self.credential_frame, variable=self.is_checked) self.label_check_password = Label(self.credential_frame, text='Show Password: '******'<Button-1>', self.show_password) # Layout self.credential_frame.grid(row=0, column=0, padx=5, pady=5) self.label_info.grid(columnspan=2, padx=10, pady=10) self.label_user.grid(row=1, column=0, padx=5, pady=5, sticky='W') self.label_password.grid(row=2, column=0, padx=5, pady=5, sticky='W') self.entry_user.grid(row=1, column=1, padx=5, pady=5) self.entry_password.grid(row=2, column=1, padx=5, pady=5) self.button_verify.grid(padx=10, pady=10) self.label_check_password.grid(padx=5, pady=5, sticky='W') self.check_password.grid(pady=5, column=1, row=3, sticky='W') def verify_user(self): if self.entry_user.get() == '' or self.entry_password.get() == '': messagebox.showerror( 'Empty Fields', 'You must enter a valid email address and password.') return try: # Open a connection and login using the user credentials. If successful, destroy login window and move to main window. server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() server.login(self.entry_user.get(), self.entry_password.get()) self.master.deiconify() MainWindow(self.master, self.entry_user.get(), self.entry_password.get()) self.tl_login.destroy() except smtplib.SMTPAuthenticationError: # Raise exception and clear user and password fields. messagebox.showerror( 'Authentication Error', 'You have entered an incorrect username or password. Please try again.' ) self.entry_password.delete(0, len(self.entry_password.get())) self.entry_user.delete(0, len(self.entry_user.get())) def show_password(self, event): if self.is_checked.get() == 0: self.entry_password.config(show='') else: self.entry_password.config(show='*')