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
class Tx(Tk.Frame): def __init__(self, master=None): Tk.Frame.__init__(self, master) self.tx_frame = Tk.Frame(self) self.gpio = [] for i in range(0,20): self.gpio.append(GPIO(i)) # GPIO LABEL self.gpio_hdr = Tk.Label(self.tx_frame,text="PORT%02d"%i, anchor=Tk.W) # GPIO Configure self.c_gpio_config = ttk.Combobox(self.tx_frame,value=["INPUT","OUTPUT","HIZ"], state="readonly") self.c_gpio_config.current(HIZ) self.c_gpio_config.bind("<<ComboboxSelected>>",self.gpio[i].config_change) self.gpio[i].set_combo(self.c_gpio_config) # GPIO scaler self.s_gpio_value = Scale(self.tx_frame,orient = 'h',showvalue = 0,from_ = 0, to = 1,command = self.gpio[i].value_change) self.gpio[i].set_scale(self.s_gpio_value) self.gpio_hdr.grid(row=i, column=0, padx=5, pady=0) self.c_gpio_config.grid(row=i, column=1, padx=5, pady=0) self.s_gpio_value.grid(row=i, column=2, padx=5, pady=0) self.tx_frame.pack()
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 __init__(self, master, image, name, enhancer, lo, hi): Frame.__init__(self, master) # set up the image self.tkim = ImageTk.PhotoImage(image.mode, image.size) self.enhancer = enhancer(image) self.update("1.0") # normalize # image window Label(self, image=self.tkim).pack() # scale s = Scale(self, label=name, orient=HORIZONTAL, from_=lo, to=hi, resolution=0.01, command=self.update) s.set(self.value) s.pack()
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 __init__(self, master, image, image_name): Frame.__init__(self, master) self.image = image self.image_name = image_name # make a blank image for the text, initialized to transparent text color self.blank_image = Image.new('RGBA', self.image.size, (255,255,255,0)) self.fnt = ImageFont.truetype('fonts/MontereyFLF.ttf', 50) self.d = ImageDraw.Draw(self.blank_image) #default watermark self.name = "watermark" self.loc_x = 0 self.loc_y = 225 self.rgbo = (0,0,0,200) self.d.text((self.loc_x, self.loc_y), self.name, font=self.fnt, fill=self.rgbo) self.out = Image.alpha_composite(self.image, self.blank_image) self.tkim = ImageTk.PhotoImage(self.out) #display image Label(root, image=self.tkim).pack() # opacity scale s_opacity = Scale(self, label="Opacity", orient=HORIZONTAL, from_=0, to=255, resolution=1, command=self.update_opacity) s_opacity.set(200) s_opacity.pack(pady = 10) #update text self.textbox = Entry() self.textbox.pack(pady = 10) b_text = Button(master, text="update text", command=self.update_text) b_text.pack() b_color = Button(master, text="black/white", command=self.update_color) b_color.pack() b_save = Button(master, text="save image", command=self.save_image) b_save.pack()
def main(): window = Tk() # window.iconbitmap('Nik.ico') window.title('Селезнев Никита, ФИИТ-401') window.resizable(width=False, height=False) color1 = 'PaleGoldenrod' color2 = 'lightyellow' frame = Frame(window, bg=color1) frame.pack() Label(frame, text="Лабораторная работа №2.\n14 вариант.", justify=CENTER, font=("Helvetica", 12), bd=10, bg=color1).pack() Label(frame, text="""f(x) = y + Lx(1-x) + 2L + 2, L = 3.3,\ty0 = 0 Решение численными методами 1) Эйлера (явный) 2) Эйлера (с пересчётом) 3) Рунге-Кутта 4) Прогонка а также точное решение.""", justify=LEFT, font=("Helvetica", 12), bd=10, bg=color2).pack() Label(frame, text="\nВыберите количество точек:", justify=CENTER, font=("Helvetica", 12), bd=0, bg=color1).pack() w = Scale(frame, from_=5, to=500, resolution=1, length=300, bg=color1, borderwidth=0, relief=GROOVE, orient=HORIZONTAL, highlightthickness=0) w.pack() Label(frame, text='\n', bg=color1).pack() Button(frame, text="Нарисовать график", font=("Helvetica", 12), bg=color2, command=lambda: draw_all(int(w.get()))).pack() window.mainloop()
def createWidgets(self): Label(self.root, text="Value:").grid(row=0, sticky=W) Label(self.root, text="H:").grid(row=1, sticky=W) Label(self.root, text="S:").grid(row=2, sticky=W) Label(self.root, text="V:").grid(row=3, sticky=W) Label(self.root, text="S:").grid(row=4, sticky=W) Label(self.root, text="V:").grid(row=5, sticky=W) Label(self.root, text="H:").grid(row=6, sticky=W) self.valueLabel = Label(self.root, text="000-000-000 to 000-000-000") self.valueLabel.grid(row=0, column=1, sticky=W) self.Hvalue = Scale(self.root, from_=0, to=255, orient=HORIZONTAL, command=self.__sliderCallback) self.Hvalue.grid(row=1, column=1) self.Hvalue.set(0) self.Svalue = Scale(self.root, from_=0, to=255, orient=HORIZONTAL, command=self.__sliderCallback) self.Svalue.grid( row=2, column=1) self.Svalue.set(90) self.Vvalue = Scale(self.root, from_=0, to=255, orient=HORIZONTAL, command=self.__sliderCallback) self.Vvalue.grid( row=3, column=1) self.Vvalue.set(0) self.HvalueMax = Scale(self.root, from_=0, to=255, orient=HORIZONTAL, command=self.__sliderCallback) self.HvalueMax.grid(row=4, column=1) self.HvalueMax.set(255) self.SvalueMax = Scale(self.root, from_=0, to=255, orient=HORIZONTAL, command=self.__sliderCallback) self.SvalueMax.grid(row=5, column=1) self.SvalueMax.set(255) self.VvalueMax = Scale(self.root, from_=0, to=255, orient=HORIZONTAL, command=self.__sliderCallback) self.VvalueMax.grid(row=6, column=1) self.VvalueMax.set(120) self.Go = tk.Button(self.root, text="Go!", fg="Green", command=self.Funkify) self.Go.grid(row=7, column=0) self.QUIT = tk.Button(self.root, text="QUIT", fg="red", command=self.root.destroy) self.QUIT.grid(row=7, column=1)
class Slider: def __init__(self, parent, label, valueCarrier, groupLabel=""): self.instance = Scale(parent, from_=2, to=0, resolution=0.02, length=100, showvalue=0, command=valueCarrier.saveVal) self.valueCarrier = valueCarrier self.groupLabel = groupLabel self._label = None if isinstance(label, str): self._label = Label(parent, text=label) elif isinstance(label, PhotoImage): self._label = Label(parent, image=label) else: raise TypeError( 'Wrong Type. Label must be of type String or PhotoImage!') @property def label(self): return self._label.cget('text') # set pos for slider with label/icon def pos(self, row, column): self.instance.grid(row=row, column=column, padx=(21, 21), pady=5) self._label.grid(row=row + 1, column=column) # activate or deactivate slider def changeState(self, state): if state == DISABLED: self.instance.config(state=DISABLED, fg="#808080") self._label.config(fg="#808080") elif state == NORMAL: self.instance.config(state=NORMAL, fg="#000000") self._label.config(fg="#000000") else: raise ValueError( 'Wrong State. State can be either DISABLED or NORMAL!')
def create_buttons(self, parent, create_sliders): self.jso = Button(parent, text="Import from .json", command=self.import_json) self.jso.grid(row=0, column=0, sticky="w") self.sav = Button(parent, text="Import from .sav", command=self.import_sav) self.sav.grid(row=0, column=1, sticky="w") self.scales = [] # create sliders if create_sliders: self.jso.grid_configure(row=0, column=0) self.sav.grid_configure(row=1, column=0) resources = [ 'minerals', 'energy', 'physics', 'society', 'engineering' ] colors = ["red", "yellow", "blue", "green", "orange"] for i in range(len(resources)): var = DoubleVar() var.set(500) callback = lambda event, tag=i: self.weight_update(event, tag) b = Scale(parent, from_=1, to=1000, variable=var, length=135, orient='horizontal', troughcolor=colors[i], resolution=1, label=resources[i], showvalue=0) b.grid(row=2 + i, column=0, sticky="w") b.bind('<ButtonRelease-1>', self.redraw) # redraw when user release scale self.scales.append(var)
def __init__(self): self.root = ThemedTk(theme="radiance") INIT_WIDTH, INIT_HEIGHT = self.root.winfo_screenwidth( ), self.root.winfo_screenheight() boldStyle = ttk.Style() boldStyle.configure("Bold.TButton", font=('Sans', '12', 'bold')) #icon_loc = os.path.join(os.getcwd(),ICON_NAME) #img = ImageTk.PhotoImage(master = self.root, file=icon_loc) #self.root.wm_iconbitmap(img) #self.root.ttk.call('wm', 'iconphoto', self.root._w, img) self.root.title("Form Labeller") self.root.maxsize(INIT_WIDTH, INIT_HEIGHT) self.supported_formats = SUPPORTED_FORMATS self.left_frame = Frame(self.root, width=BUTTON_WIDTH) self.top_frame1 = Frame(self.left_frame, width=BUTTON_WIDTH, height=int(INIT_HEIGHT / 2)) self.top_frame = Frame(self.left_frame, width=BUTTON_WIDTH, height=INIT_HEIGHT - int(INIT_HEIGHT / 2)) self.bottom_frame = Frame(self.root, width=INIT_WIDTH - BUTTON_WIDTH) self.load_image_directory_button = Button(self.top_frame1, text='Open Folder', command=self.load_directory, width=int(BUTTON_WIDTH), style="Bold.TButton") self.load_image_directory_button.grid(row=OPEN_FOLDER_ROW, columnspan=2, sticky=tk.W + tk.E) self.prev_img_button = Button(self.top_frame1, text='← Prev', command=self.previous_img, state=tk.DISABLED, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.prev_img_button.grid(row=PREV_ROW, column=0, sticky=tk.W + tk.E) self.next_img_button = Button(self.top_frame1, text='Next → ', command=self.next_img, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.next_img_button.grid(row=NEXT_COL, column=1, sticky=tk.W + tk.E) self.save_image_button = Button(self.top_frame1, text='Save ', command=self.saver, width=int(BUTTON_WIDTH), style="Bold.TButton") self.save_image_button.grid(row=SAVE_ROW, columnspan=2, sticky=tk.W + tk.E) self.delete_poly_button = Button(self.top_frame, text='Delete Selected', command=self.delete_selected, width=int(BUTTON_WIDTH), style="Bold.TButton") self.delete_poly_button.grid(row=DEL_SELECTED_ROW, columnspan=2, sticky=tk.W + tk.E) self.type_choices = TYPE_CHOICES self.variable = StringVar(self.top_frame) self.variable.set(self.type_choices[0]) self.type_options = OptionMenu(self.top_frame, self.variable, *self.type_choices, style="Bold.TButton") self.type_options.config(width=int(BUTTON_WIDTH / 2)) self.type_options.grid(row=DROP_DOWN_ROW, column=0) self.save_type_button = Button(self.top_frame, text='Save Type', command=self.save_type, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.save_type_button.grid(row=SAVE_TYPE_ROW, column=1, sticky=tk.W + tk.E) self.deselect_all_button = Button(self.top_frame, text='Deselect All', command=self.deselect_all, width=BUTTON_WIDTH, style="Bold.TButton") self.deselect_all_button.grid(row=DESELECT_ALL_ROW, columnspan=2, sticky=tk.W + tk.E) self.select_all_button = Button(self.top_frame, text='Select All', command=self.select_all, width=BUTTON_WIDTH, style="Bold.TButton") self.select_all_button.grid(row=SELECT_ALL_ROW, columnspan=2, sticky=tk.W + tk.E) self.draw_poly_button = Button(self.top_frame, text='Draw Poly', command=self.draw_poly_func, width=BUTTON_WIDTH, style="Bold.TButton") self.draw_poly_button.grid(row=DRAW_POLY_ROW, columnspan=2, sticky=tk.W + tk.E) self.draw_rect_button = Button(self.top_frame, text='Draw Rectangle', command=self.draw_rect_func, width=BUTTON_WIDTH, style="Bold.TButton") self.draw_rect_button.grid(row=DRAW_RECT_ROW, columnspan=2, sticky=tk.W + tk.E) self.delete_all_button = Button(self.top_frame, text='Delete All', command=self.delete_all, width=BUTTON_WIDTH, style="Bold.TButton") self.save_poly_button = Button(self.top_frame, text='Save Poly', command=self.save_drawing, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.discard_poly_button = Button(self.top_frame, text='Discard Poly', command=self.discard_drawing, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.save_rect_button = Button(self.top_frame, text='Save Rect', command=self.save_drawing, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.discard_rect_button = Button(self.top_frame, text='Discard Rect', command=self.discard_drawing, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.show_type_button = Button(self.top_frame, text='Show Type', command=self.show_type, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.show_type_button.grid(row=SHOW_TYPE_ROW, column=0, columnspan=1, sticky=tk.W + tk.E) self.hide_type_button = Button(self.top_frame, text='Hide Type', command=self.hide_type, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.hide_type_button.grid(row=HIDE_TYPE_ROW, columnspan=1, column=1, sticky=tk.W + tk.E) self.make_tight_button = Button(self.top_frame, text='Make Tight', command=self.make_tight, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.make_tight_button.grid(row=MAKE_TIGHT_ROW, columnspan=2, column=0, sticky=tk.W + tk.E) self.threshold_scale = Scale(self.top_frame, from_=0, to=255, orient=HORIZONTAL, width=int(BUTTON_WIDTH / 2), label="Binary Threshold") self.threshold_scale.set(128) self.threshold_scale.grid(row=THRESHOLD_ROW, columnspan=2, column=0, sticky=tk.W + tk.E) self.tight_save_button = Button(self.top_frame, text='Accept Tight', command=self.save_tight) self.tight_discard_button = Button(self.top_frame, text='Discard Tight', command=self.discard_tight) self.canvas = Canvas(self.bottom_frame, width=INIT_WIDTH - BUTTON_WIDTH, height=INIT_HEIGHT, borderwidth=1) self.image_name = None #self.image_path = os.path.join('imgs','img1.jpg') self.image_dir = None self.images_in_dir = None self.curr_idx = None self.img_cnv = None #self.img_cnv = ImageOnCanvas(self.root,self.canvas,self.image_path) self.drawing_obj = None self.tight_box_obj = None self.left_frame.pack(side=tk.LEFT) self.top_frame1.pack(side=tk.TOP) self.top_frame.pack(side=tk.BOTTOM) self.bottom_frame.pack(side=tk.LEFT) self.canvas.pack() self.hide_buttons() self.load_image_directory_button.config(state="normal")
def __init__(self,parent): chosenFont = font.Font(family='Verdana', size=10, weight='normal') Frame.__init__(self,parent,background="white") self.parent = parent self.parent.title("simple window") self.style = ttk.Style() self.style.theme_use("default") self.centreWindow() self.pack(fill=BOTH,expand=1) # 라벨 표시와 입력 firstNameLabel = Label(self, text="First Name", font=chosenFont) # 폰트설정 firstNameLabel.grid(row=0, column=0, sticky=W + E) lastNameLabel = Label(self, text="Last Name") lastNameLabel.grid(row=1, column=0, sticky=W + E) countryLabel = Label(self, text="Country") countryLabel.grid(row=2, column=0, sticky=W + E) addressLabel = Label(self, text="Address") addressLabel.grid(row=3, column=0, pady=10, sticky=W + E + N) firstNameText = Entry(self, width=20) firstNameText.grid(row=0, column=1, padx=5, pady=5, ipady=2, sticky=W + E) lastNameText = Entry(self, width=20) lastNameText.grid(row=1, column=1, padx=5, pady=5, ipady=2, sticky=W + E) addressText = Text(self, padx=5, pady=5, width=20, height=6) addressText.grid(row=3, column=1, padx=5, pady=5, sticky=W) # 내가 필요한 클릭 스크롤바 self.countryVar = StringVar() self.countryCombo = ttk.Combobox(self, textvariable=self.countryVar) self.countryCombo['values'] = ('United States', 'United Kingdom', 'France') self.countryCombo.current(1) self.countryCombo.bind("<<ComboboxSelected>>", self.newCountry) self.countryCombo.grid(row=2, column=1, padx=5, pady=5, ipady=2, sticky=W) # 좌우 스크롤로 값 변경 self.salaryVar = StringVar() salaryLabel = Label(self, text="Salary:",textvariable=self.salaryVar) salaryLabel.grid(row=0, column=2,columnspan=2, sticky=W+E) salaryScale = Scale(self, from_=0,to=1, orient=HORIZONTAL, resolution=1,command=self.onSalaryScale) salaryScale.grid(row=1, column=2,columnspan=1, sticky=W+E) # 체크박스 기능 self.fullTimeVar = IntVar() fullTimeCheck = Checkbutton(self, text="Full-time?", variable=self.fullTimeVar, command=self.fullChecked) fullTimeCheck.grid(row=2, column=2, columnspan=2, sticky=W + E) # - self.titleVar = StringVar() self.titleVar.set("TBA") Label(self, textvariable=self.titleVar).grid( row=4, column=1, sticky=W + E ) # a reference to the label is not retained title = ['Programmer', 'Developer', 'Web Developer', 'Designer'] titleList = Listbox(self, height=5) for t in title: titleList.insert(END, t) titleList.grid(row=3, column=2, columnspan=2, pady=5, sticky=N + E + S + W) titleList.bind("<<ListboxSelect>>", self.newTitle) # 버튼 okBtn = Button(self, text="OK", width=10, command=self.onConfirm) okBtn.grid(row=4, column=2, padx=5, pady=3, sticky=W + E) closeBtn = Button(self, text="Close", width=10, command=self.onExit) closeBtn.grid(row=4, column=3, padx=5, pady=3, sticky=W + E)
class Gui(Frame): #============================================================================== # Metodos Basicos #============================================================================== def __init__(self, parent=None): Frame.__init__(self, parent) # Atributos GUI self.parent = parent self.file_opt = self.flopt = {} w, h = self.parent.winfo_screenwidth(), self.parent.winfo_screenheight( ) self.largura = w - 20 self.altura = h - 20 # Atributos funcionais self.img = None self.imgOld = None self.arqImg = StringVar() self.arqImg.set('') self.formatos = {} self.formatos['gif'] = 'GIF' self.formatos['jpg'] = 'JPEG' self.formatos['jpeg'] = 'JPEG' self.formatos['png'] = 'PNG' self.formatos['bmp'] = 'BMP' self.formatos['tif'] = 'TIFF' self.formatos['tiff'] = 'TIFF' self.formatos['ppm'] = 'PPM' self.formatos['pbm'] = 'PPM' self.formatos['pgm'] = 'PPM' self.tipos = [('Imagens', ('*.jpg', '*.png', '*.gif', '*.bmp', '*.ppm', '*.pgm', '*.pbm')), ('JPEG', '*.jpg'), ('PNG', '*.png'), ('GIF', '*.gif'), ('BMP', '*.bmp'), ('PPM', '*.ppm'), ('PGM', '*.pgm'), ('PBM', '*.pbm'), ('Todos arquivos', '*')] # Cria/atualiza GUI self.createWidgets() self.update_idletasks() #============================================================================== # Metodos relacionados ao comportamento da GUI #============================================================================== def createWidgets(self): self.canvas = Canvas(self.parent, width=1366, height=768) self.scroll = Scrollbar(self.parent, orient="vertical", command=self.canvas.yview) self.canvas.configure(yscrollcommand=self.scroll.set) self.scroll.pack(side="right", fill="y") self.canvas.pack(side="left", fill="both", expand=True) # Configura barra de menus self.menubar = Menu(self.parent) self.parent.config(menu=self.menubar) # Menu arquivo e suas opcoes self.menuArquivo = Menu(self.menubar) self.menuArquivo.add_command(label='Abrir', underline=0, command=self.abrir) self.menuArquivo.add_separator() self.menuArquivo.add_command(label='Salvar', underline=0, command=self.salvar) self.menuArquivo.add_command(label='Salvar Como...', underline=0, command=self.salvarComo) self.menuArquivo.add_separator() self.menuArquivo.add_command(label='Fechar imagem(ns)', underline=0, command=self.fecharArquivo) self.menuArquivo.add_command(label="Sair", underline=3, command=self.onExit) self.menubar.add_cascade(label="Arquivo", underline=0, menu=self.menuArquivo) # Menu editar e suas opcoes self.menuEditar = Menu(self.menubar) self.menuEditar.add_command(label='Desfazer', underline=0, command=self.desfazer) self.menubar.add_cascade(label="Editar", underline=0, menu=self.menuEditar) # Menu Imagem e suas opcoes self.menuImagem = Menu(self.menubar) self.submenuConverte = Menu(self.menuImagem) self.submenuConverte.add_command(label='Colorido RGB', underline=0, command=lambda: self.converte('RGB')) self.submenuConverte.add_command(label='Colorido RGBA', underline=0, command=lambda: self.converte('RGBA')) self.submenuConverte.add_command(label='Escala de cinza', underline=0, command=lambda: self.converte('L')) self.submenuConverte.add_command(label='Binario', underline=0, command=lambda: self.converte('1')) self.menuImagem.add_command(label='Informacoes gerais', underline=0, command=self.info) self.menuImagem.add_separator() self.menuImagem.add_cascade(label='Converter', underline=0, menu=self.submenuConverte) self.menubar.add_cascade(label="Imagem", underline=0, menu=self.menuImagem) # Menu de operacoes sobre cores e suas opcoes self.menuCores = Menu(self.menubar) self.submenuCinza = Menu(self.menuCores) self.submenuCinza.add_command(label='Decomposicao de Maximo', underline=18, command=self.emConstrucao) self.submenuCinza.add_command(label='Decomposicao de Minimo', underline=18, command=self.emConstrucao) self.submenuCinza.add_command(label='Average', underline=0, command=lambda: self.mudaCor('average')) self.submenuCinza.add_command(label='Lightness', underline=0, command=self.emConstrucao) self.submenuCinza.add_command(label='Luminosity', underline=0, command=self.emConstrucao) self.submenuCinza.add_command(label='Componente R', underline=11, command=lambda: self.mudaCor('r')) self.submenuCinza.add_command(label='Componente G', underline=11, command=self.emConstrucao) self.submenuCinza.add_command(label='Componente B', underline=11, command=self.emConstrucao) self.submenuCinza.add_command(label='Quantidade arbitraria de tons', underline=0, command=self.emConstrucao) self.submenuHalftone = Menu(self.menuCores) self.submenuHalftone.add_command( label='Bayer 2x2', underline=6, command=lambda: self.halftoning('bayer2')) self.submenuHalftone.add_command(label='Bayer 5x5', underline=6, command=self.emConstrucao) self.submenuHalftone.add_command(label='Atkinson', underline=0, command=self.emConstrucao) self.submenuHalftone.add_command(label='Sierra Lite', underline=0, command=self.emConstrucao) self.submenuHalftone.add_command(label='Jarvis, Judice, and Ninke', underline=0, command=self.emConstrucao) self.submenuHalftone.add_command( label='Floyd-Steinberg', underline=0, command=lambda: self.halftoning('floyd')) self.menuCores.add_cascade(label='Tons de cinza', underline=0, menu=self.submenuCinza) self.menuCores.add_command(label='Inverter', underline=0, command=lambda: self.mudaCor('inv')) self.menuCores.add_command(label='Sepia', underline=0, command=self.emConstrucao) self.menuCores.add_separator() self.menuCores.add_command(label='Pseudo Binaria', underline=0, command=self.binaria) self.menuCores.add_cascade(label='Halftoning', underline=0, menu=self.submenuHalftone) self.menuCores.add_separator() self.menuCores.add_command(label='Cisalhamento de Cor', underline=0, command=self.emConstrucao) self.menuCores.add_command(label='Balanco de cores', underline=0, command=self.balancoCor) self.menuCores.add_command(label='Quantizacao de cores', underline=0, command=self.emConstrucao) self.menubar.add_cascade(label="Cores", underline=0, menu=self.menuCores) # Menu de operacoes topologicas e suas opcoes self.menuTopologia = Menu(self.menubar) self.menuTopologia.add_command(label='Rotular Componentes', underline=0, command=self.emConstrucao) self.menuTopologia.add_command(label='Transformada da Distancia', underline=0, command=self.emConstrucao) self.menuTopologia.add_command(label='Esqueletizacao', underline=0, command=self.emConstrucao) self.menubar.add_cascade(label="Topologia", underline=0, menu=self.menuTopologia) # Menu do trabalho e suas opcoes self.trabalho = Menu(self.menubar) self.trabalho.add_command(label='Tarefa 01', underline=20, command=self.abrir) # Grupo principal, onde serao atualizados os widgets self.grupoPrincipal = Frame(self.canvas, width=self.largura, height=self.altura, bd=1, padx=10, pady=10) self.grupoPrincipal.pack() #self.grupoPrincipal.grid_propagate(False) # Faz com que o Frame nao seja redimensionado com a mudanca dos widgets self.canvas.create_window((4, 20), window=self.grupoPrincipal, anchor="nw", tags="self.grupoPrincipal") self.grupoPrincipal.bind("<Configure>", self.OnFrameConfigure) def OnFrameConfigure(self, event): '''Reset the scroll region to encompass the inner frame''' self.canvas.configure(scrollregion=self.canvas.bbox("all")) def onExit(self): self.parent.destroy() def limpaTela(self): for widget in self.grupoPrincipal.winfo_children(): widget.destroy() def emConstrucao(self): tkm.showinfo(title="Em construcao", message="Recurso em Construcao...") def load_file(self, titulo, varFile, tipos): if os.path.isfile(varFile.get()): path = os.path.dirname(varFile.get()) self.flopt['initialdir'] = path else: self.flopt['initialdir'] = os.path.curdir self.flopt['filetypes'] = tipos arquivo = tkf.askopenfilename(title=titulo, **self.flopt) if arquivo: varFile.set(arquivo) def widgetFile(self, master, titulo, texto, varFile, tuplaFiletype): esteFrame = LabelFrame(master, text=titulo, padx=5, pady=5) j = 0 varFile.set("Nenhum arquivo informado") labelRotulo = Label(esteFrame, text=texto) labelRotulo.grid(row=j, column=0, sticky=cte.E) botao = Button( esteFrame, text="Procurar", command=lambda: self.load_file(texto, varFile, tuplaFiletype), width=10) botao.grid(row=j, column=1, pady=5, sticky=cte.W) j += 1 labelArq = Label(esteFrame, textvariable=varFile, bg='white') labelArq.grid(row=j, column=0, columnspan=2) return esteFrame def refreshImg(self): try: self.grupoPrincipal.photo = ImageTk.PhotoImage(self.img.img) if hasattr(self.grupoPrincipal, 'canvas'): self.grupoPrincipal.canvas.destroy() self.grupoPrincipal.canvas = Canvas(self.grupoPrincipal) self.grupoPrincipal.canvas.create_image( 0, 0, image=self.grupoPrincipal.photo, anchor=cte.NW) self.grupoPrincipal.canvas.config(bg='white', width=self.img.altura, height=self.img.largura) #self.grupoPrincipal.canvas.place(x=self.parent.winfo_screenwidth()/2, y=self.parent.winfo_screenheight()/2, anchor=cte.CENTER) self.grupoPrincipal.canvas.place(x=0, y=0, anchor=cte.NW) self.grupoPrincipal.update_idletasks() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) #============================================================================== # Metodos relacionados ao meno Arquivo #============================================================================== def abrir(self): try: self.limpaTela() self.load_file('Arquivos de Imagem', self.arqImg, self.tipos) self.img = Imagem(self.arqImg.get()) self.refreshImg() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) def saveFile(self): try: nome, extensao = os.path.splitext(self.arqImg.get()) extensao = extensao.replace('.', '') self.img.salva(self.arqImg.get(), self.formatos[extensao.lower()]) tkm.showinfo( 'Sucesso', 'Arquivo %s salvo com sucesso' % os.path.basename(self.arqImg.get())) except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) def salvar(self): if self.arqImg.get() == '': tkm.showwarning('Aviso', 'Nao ha arquivo aberto para ser salvo') else: try: self.saveFile() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) def salvarComo(self): if self.arqImg.get() == '': tkm.showwarning('Aviso', 'Nao ha arquivo aberto para ser salvo') else: try: if os.path.isfile(self.arqImg.get()): path = os.path.dirname(self.arqImg.get()) self.flopt['initialdir'] = path else: self.flopt['initialdir'] = os.path.curdir self.flopt['filetypes'] = self.tipos nomeArq = tkf.asksaveasfilename(title='Salvar imagem como...', **self.flopt) if nomeArq: self.arqImg.set(nomeArq) self.saveFile() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) def fecharArquivo(self): if not hasattr( self.grupoPrincipal, 'canvas') or self.grupoPrincipal.canvas.find_all() == (): tkm.showwarning('Aviso', 'Nao ha imagens abertas') else: try: self.img = self.imgOld = None self.grupoPrincipal.canvas.delete('all') self.grupoPrincipal.update_idletasks() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) #============================================================================== # Metodos relacionados ao menu Editar #============================================================================== def desfazer(self): if self.arqImg.get() == '' or self.img is None: tkm.showwarning('Aviso', 'Nao ha arquivo aberto') elif self.imgOld is None: tkm.showwarning('Aviso', 'Impossivel Desfazer') else: try: temp = self.img self.img = self.imgOld self.imgOld = temp self.refreshImg() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) #============================================================================== # Metodos relacionados ao menu Cores #============================================================================== def mudaCor(self, metodo): if self.arqImg.get() == '' or self.img is None: tkm.showwarning('Aviso', 'Nao ha arquivo aberto') else: try: self.imgOld = self.img self.img = cor.mudaCor(self.imgOld, metodo) self.refreshImg() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) def binaria(self): if self.arqImg.get() == '' or self.img is None: tkm.showwarning('Aviso', 'Nao ha arquivo aberto') else: try: self.imgOld = self.img self.img = cor.binaria(self.imgOld) self.refreshImg() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) def getFatoresBalanco(self): self.fatores = [float(self.escalaFatorR.get())] self.fatores.append(float(self.escalaFatorG.get())) self.fatores.append(float(self.escalaFatorB.get())) self.w.destroy() def formBalanco(self): self.fator = None self.fatores = None self.w = Toplevel(self) self.w.wm_title("Informar os fatores de ajuste") self.w.geometry("+%d+%d" % (self.winfo_rootx() + 50, self.winfo_rooty() + 50)) self.w.focus_set() i = 0 self.labelFatorR = Label(self.w, text='Ajuste em R', width=25) self.labelFatorR.grid(row=i, column=0) self.escalaFatorR = Scale(self.w, from_=0, to=2, resolution=0.05, length=350, orient=cte.HORIZONTAL) self.escalaFatorR.set(0.5) self.escalaFatorR.grid(row=i, column=1) i += 1 self.labelFatorG = Label(self.w, text='Ajuste em G', width=25) self.labelFatorG.grid(row=i, column=0) self.escalaFatorG = Scale(self.w, from_=0, to=2, resolution=0.05, length=350, orient=cte.HORIZONTAL) self.escalaFatorG.set(0.5) self.escalaFatorG.grid(row=i, column=1) i += 1 self.labelFatorB = Label(self.w, text='Ajuste em B', width=25) self.labelFatorB.grid(row=i, column=0) self.escalaFatorB = Scale(self.w, from_=0, to=2, resolution=0.05, length=350, orient=cte.HORIZONTAL) self.escalaFatorB.set(0.5) self.escalaFatorB.grid(row=i, column=1) i += 1 self.botaoFator = Button(self.w, text='Ok', command=self.getFatoresBalanco, width=10) self.botaoFator.grid(row=i, column=0, columnspan=2) self.w.grid() def balancoCor(self): if self.arqImg.get() == '' or self.img is None: tkm.showwarning('Aviso', 'Nao ha arquivo aberto') else: try: self.formBalanco() self.wait_window(self.w) if self.fatores is not None: self.imgOld = self.img self.img = cor.balanco(self.imgOld, self.fatores[0], self.fatores[1], self.fatores[2]) self.refreshImg() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) def halftoning(self, metodo='bayer2'): if self.arqImg.get() == '' or self.img is None: tkm.showwarning('Aviso', 'Nao ha arquivo aberto') else: try: self.imgOld = self.img if metodo == 'bayer2': self.img = cor.bayer(self.imgOld) elif metodo == 'floyd': self.img = cor.floyd(self.imgOld) else: raise Exception('Metodo de halftoning desconhecido') self.refreshImg() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) #============================================================================== # Metodos relacionados ao menu Imagem #============================================================================== def converte(self, modo='RGB'): if self.arqImg.get() == '' or self.img is None: tkm.showwarning('Aviso', 'Nao ha arquivo aberto') else: try: self.imgOld = self.img.copia() self.img.converte(modo) self.refreshImg() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) def info(self): if self.arqImg.get() == '': tkm.showwarning('Aviso', 'Nao ha arquivo aberto') else: try: texto = 'Imagem %s, modo: %s (%d x %d pixels)' % ( self.img.img.format, self.img.img.mode, self.img.img.size[0], self.img.img.size[1]) tkm.showinfo('Aviso', texto) except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args))
class StartPage(tk.Frame): def callbackserial(self): global com com = self.combo.get() com = com.replace('- FT231X USB UART', '') print(com) def callbacktime(self): global stime stime = int(self.slider.get()) print(stime) def __init__(self, parent, controller): tk.Frame.__init__(self, parent, bg="#1959B3") self.controller = controller canvas = Canvas(self, bg="#1959B3", height=583, width=673) canvas.pack() canvas.create_line(320, 157, 320, 500, dash=(6, 4), fill="white") #Linea punteada canvas.place(x=10, y=10) #Linea externa label = tk.Label(self, text="OpenBCI", font=("Times", 70), fg="white", bg="#1959B3") label.pack(side="top", fill="x", pady=10) label.place(relx=0.32, rely=0.07) label2 = tk.Label(self, text="Camila Andrea Navarrete Cataño", fg="white", bg="#1959B3", font=("Verdana")) label2.pack(side="bottom", fill="x", pady=10) label2.place(relx=0.08, rely=0.96) label3 = tk.Label(self, text="Seleccionar puerto USB:", font=("Helvetica", 17), fg="white", bg="#1959B3") label3.pack(fill="x", pady=5) label3.place(relx=0.50, rely=0.31) label4 = tk.Label(self, text="Bluetooth:", font=("Helvetica", 17), fg="white", bg="#1959B3") label4.pack(fill="x", pady=5) label4.place(relx=0.50, rely=0.39) label6 = tk.Label(self, text="Seleccionar tiempo de grabación:", font=("Helvetica", 17), fg="white", bg="#1959B3") label6.pack(side="top", fill="x", pady=10) label6.place(relx=0.50, rely=0.58) label7 = tk.Label( self, text= "Este programa le ayudará a interactuar con las interfaces cerebro - computadora mediante el movimiento de una barra virtual y el robot mBot Ranger, en tiempo real." " En la siguiente página podra visualizar la señal de EEG del canal 8, el espectro de frecuencias y la barra ", font=("Helvetica", 17), fg="white", bg="#1959B3", justify="left", wraplength=250) label7.pack(side="top", fill="x", pady=10) label7.place(relx=0.1, rely=0.35) button1 = tk.Button(self, text="Iniciar", command=lambda: controller.show_frame("PageOne")) button1.pack() button1.place(relx=0.64, rely=0.81, height=50, width=80) button3 = tk.Button(self, text="OK", command=self.callbackserial) button3.pack() button3.place(relx=0.87, rely=0.46, height=35, width=60) button2 = tk.Button(self, text="OK", command=self.callbacktime) button2.pack() button2.place(relx=0.87, rely=0.67, height=35, width=60) number = tk.StringVar() self.combo = ttk.Combobox( self, textvariable=number) #Seleccionar puerto serial self.combo.place(x=355, y=285, width=240) self.combo["values"] = serial_ports() self.slider = Scale(self, orient='horizontal', from_=1, to=10, tickinterval=1) #Barra de tiempos self.slider.pack() self.slider.place(relx=0.50, rely=0.65, width=240)
class TelloUI: """Wrapper class to enable the GUI.""" def __init__(self, tello, outputpath): """ Initial all the element of the GUI,support by Tkinter :param tello: class interacts with the Tello drone. Raises: RuntimeError: If the Tello rejects the attempt to enter command mode. """ self.tello = tello # videostream device self.outputPath = outputpath # the path that save pictures created by clicking the takeSnapshot button self.frame = None # frame read from h264decoder and used for pose recognition self.thread = None # thread of the Tkinter mainloop self.stopEvent = None # control variables self.distance = 0.1 # default distance for 'move' cmd self.degree = 30 # default degree for 'cw' or 'ccw' cmd # if the pose recognition mode is opened self.pose_mode = False # if the flag is TRUE,the auto-takeoff thread will stop waiting for the response from tello self.quit_waiting_flag = False # if the flag is TRUE,the pose recognition skeleton will be drawn on the GUI picture self.draw_skeleton_flag = False # pose recognition self.my_tello_pose = Tello_Pose() # record the coordinates of the nodes in the pose recognition skeleton self.points = [] #list of all the possible connections between skeleton nodes self.POSE_PAIRS = [[0, 1], [1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [1, 14], [14, 8], [8, 9], [9, 10], [14, 11], [11, 12], [12, 13]] # initialize the root window and image panel self.root = tki.Tk() self.panel = None # self.panel_for_pose_handle_show = None # create buttons self.btn_snapshot = tki.Button(self.root, text="Snapshot!", command=self.takeSnapshot) self.btn_snapshot.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_pose = tki.Button(self.root, text="Pose Recognition Status: Off", command=self.setPoseMode) self.btn_pose.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_pause = tki.Button(self.root, text="Pause", relief="raised", command=self.pauseVideo) self.btn_pause.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_landing = tki.Button(self.root, text="Open Command Panel", relief="raised", command=self.openCmdWindow) self.btn_landing.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) # start a thread that constantly pools the video sensor for # the most recently read frame self.stopEvent = threading.Event() self.thread = threading.Thread(target=self.videoLoop, args=()) self.thread.start() # set a callback to handle when the window is closed self.root.wm_title("TELLO Controller") self.root.wm_protocol("WM_DELETE_WINDOW", self.onClose) # the auto-takeoff thread will start if the 'takeoff' button on command window is clicked self.auto_takeoff_thread = threading.Thread(target=self._autoTakeoff) # the sending_command will send command to tello every 5 seconds self.sending_command_thread = threading.Thread( target=self._sendingCommand) self.get_GUI_Image_thread = threading.Thread(target=self._getGUIImage) def videoLoop(self): """ The mainloop thread of Tkinter Raises: RuntimeError: To get around a RunTime error that Tkinter throws due to threading. """ try: # start the thread that get GUI image and drwa skeleton time.sleep(0.5) self.get_GUI_Image_thread.start() while not self.stopEvent.is_set(): # read the frame for pose recognition self.frame = self.tello.read() if self.frame is None or self.frame.size == 0: continue # smoothing filter self.frame = cv2.bilateralFilter(self.frame, 5, 50, 100) cmd = '' self.points.append(None) # process pose-recognition if self.pose_mode: cmd, self.draw_skeleton_flag, self.points = self.my_tello_pose.detect( self.frame) # process command - map your motion to whatever Tello movement you want! if cmd == 'moveback': self.telloMoveBackward(0.50) elif cmd == 'moveforward': self.telloMoveForward(0.50) elif cmd == 'land': self.telloLanding() except RuntimeError as e: print("[INFO] caught a RuntimeError") def _getGUIImage(self): """ Main operation to read frames from h264decoder and draw skeleton on frames if the pose mode is opened """ # read the system of your computer system = platform.system() while not self.stopEvent.is_set(): # read the frame for GUI show frame = self.tello.read() if frame is None or frame.size == 0: continue if self.pose_mode: # Draw the detected skeleton points for i in range(15): if self.draw_skeleton_flag == True: cv2.circle(frame, self.points[i], 8, (0, 255, 255), thickness=-1, lineType=cv2.FILLED) cv2.putText(frame, "{}".format(i), self.points[i], cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, lineType=cv2.LINE_AA) # Draw Skeleton for pair in self.POSE_PAIRS: partA = pair[0] partB = pair[1] if self.points[partA] and self.points[partB]: cv2.line(frame, self.points[partA], self.points[partB], (0, 255, 255), 2) cv2.circle(frame, self.points[partA], 8, (0, 0, 255), thickness=-1, lineType=cv2.FILLED) # transfer the format from frame to image image = Image.fromarray(frame) # we found compatibility problem between Tkinter,PIL and Macos,and it will # sometimes result the very long preriod of the "ImageTk.PhotoImage" function, # so for Macos,we start a new thread to execute the _updateGUIImage function. if system == "Windows" or system == "Linux": self._updateGUIImage(image) else: thread_tmp = threading.Thread(target=self._updateGUIImage, args=(image, )) thread_tmp.start() time.sleep(0.03) def _updateGUIImage(self, image): """ Main operation to initial the object of image,and update the GUI panel """ image = ImageTk.PhotoImage(image) # if the panel none ,we need to initial it if self.panel is None: self.panel = tki.Label(image=image) self.panel.image = image self.panel.pack(side="left", padx=10, pady=10) # otherwise, simply update the panel else: self.panel.configure(image=image) self.panel.image = image def _autoTakeoff(self): """ Firstly,it will waiting for the response that will be sent by Tello if Tello finish the takeoff command.If computer doesn't receive the response,it may be because tello doesn't takeoff normally,or because the UDP pack of response is lost.So in order to confirm the reason,computer will send 'height?'command to get several real-time height datas and get a average value.If the height is in normal range,tello will execute the moveup command.Otherwise,tello will land. Finally,the sending-command thread will start. """ response = None height_tmp = 0 # temp variable to content value of height height_val = 0 # average value of height cnt = 0 # effective number of height reading timeout = 6 # max waiting time of tello's response timer = threading.Timer(timeout, self._setQuitWaitingFlag) timer.start() # waiting for the response from tello while response != 'ok': if self.quit_waiting_flag is True: break response = self.tello.get_response() print("ack:%s" % response) timer.cancel() # receive the correct response if response == 'ok': self.tello.move_up(0.5) # calculate the height of tello else: for i in range(0, 50): height_tmp = self.tello.get_height() try: height_val = height_val + height_tmp cnt = cnt + 1 print(height_tmp, cnt) except: height_val = height_val height_val = height_val / cnt # if the height value is in normal range if height_val == 9 or height_val == 10 or height_val == 11: self.tello.move_up(0.5) else: self.tello.land() # start the sendingCmd thread self.sending_command_thread.start() def _sendingCommand(self): """ start a while loop that sends 'command' to tello every 5 second """ while True: self.tello.send_command('command') time.sleep(5) def _setQuitWaitingFlag(self): """ set the variable as TRUE,it will stop computer waiting for response from tello """ self.quit_waiting_flag = True def openCmdWindow(self): """ open the cmd window and initial all the button and text """ panel = Toplevel(self.root) panel.wm_title("Command Panel") # create text input entry text0 = tki.Label( panel, text= 'This Controller map keyboard inputs to Tello control commands\n' 'Adjust the trackbar to reset distance and degree parameter', font='Helvetica 10 bold') text0.pack(side='top') text1 = tki.Label( panel, text='W - Move Tello Up\t\t\tArrow Up - Move Tello Forward\n' 'S - Move Tello Down\t\t\tArrow Down - Move Tello Backward\n' 'A - Rotate Tello Counter-Clockwise\tArrow Left - Move Tello Left\n' 'D - Rotate Tello Clockwise\t\tArrow Right - Move Tello Right', justify="left") text1.pack(side="top") self.btn_landing = tki.Button(panel, text="Land", relief="raised", command=self.telloLanding) self.btn_landing.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_takeoff = tki.Button(panel, text="Takeoff", relief="raised", command=self.telloTakeOff) self.btn_takeoff.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) # binding arrow keys to drone control self.tmp_f = tki.Frame(panel, width=100, height=2) self.tmp_f.bind('<KeyPress-w>', self.on_keypress_w) self.tmp_f.bind('<KeyPress-s>', self.on_keypress_s) self.tmp_f.bind('<KeyPress-a>', self.on_keypress_a) self.tmp_f.bind('<KeyPress-d>', self.on_keypress_d) self.tmp_f.bind('<KeyPress-Up>', self.on_keypress_up) self.tmp_f.bind('<KeyPress-Down>', self.on_keypress_down) self.tmp_f.bind('<KeyPress-Left>', self.on_keypress_left) self.tmp_f.bind('<KeyPress-Right>', self.on_keypress_right) self.tmp_f.pack(side="bottom") self.tmp_f.focus_set() self.btn_landing = tki.Button(panel, text="Flip", relief="raised", command=self.openFlipWindow) self.btn_landing.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.distance_bar = Scale(panel, from_=0.02, to=5, tickinterval=0.01, digits=3, label='Distance(m)', resolution=0.01) self.distance_bar.set(0.2) self.distance_bar.pack(side="left") self.btn_distance = tki.Button( panel, text="Reset Distance", relief="raised", command=self.updateDistancebar, ) self.btn_distance.pack(side="left", fill="both", expand="yes", padx=10, pady=5) self.degree_bar = Scale(panel, from_=1, to=360, tickinterval=10, label='Degree') self.degree_bar.set(30) self.degree_bar.pack(side="right") self.btn_distance = tki.Button(panel, text="Reset Degree", relief="raised", command=self.updateDegreebar) self.btn_distance.pack(side="right", fill="both", expand="yes", padx=10, pady=5) def openFlipWindow(self): """ open the flip window and initial all the button and text """ panel = Toplevel(self.root) panel.wm_title("Gesture Recognition") self.btn_flipl = tki.Button(panel, text="Flip Left", relief="raised", command=self.telloFlip_l) self.btn_flipl.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_flipr = tki.Button(panel, text="Flip Right", relief="raised", command=self.telloFlip_r) self.btn_flipr.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_flipf = tki.Button(panel, text="Flip Forward", relief="raised", command=self.telloFlip_f) self.btn_flipf.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_flipb = tki.Button(panel, text="Flip Backward", relief="raised", command=self.telloFlip_b) self.btn_flipb.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) def takeSnapshot(self): """ save the current frame of the video as a jpg file and put it into outputpath """ # grab the current timestamp and use it to construct the filename ts = datetime.datetime.now() filename = "{}.jpg".format(ts.strftime("%Y-%m-%d_%H-%M-%S")) p = os.path.sep.join((self.outputPath, filename)) # save the file cv2.imwrite(p, cv2.cvtColor(self.frame, cv2.COLOR_RGB2BGR)) print(("[INFO] saved {}".format(filename))) def setPoseMode(self): """ Toggle the open/close of pose recognition mode """ if self.pose_mode is False: self.pose_mode = True self.btn_pose.config(text='Pose Recognition Status: On') else: self.pose_mode = False self.btn_pose.config(text='Pose Recognition Status: Off') def pauseVideo(self): """ Toggle the freeze/unfreze of video """ if self.btn_pause.config('relief')[-1] == 'sunken': self.btn_pause.config(relief="raised") self.tello.video_freeze(False) else: self.btn_pause.config(relief="sunken") self.tello.video_freeze(True) def telloTakeOff(self): """ send the takeoff command to tello,and wait for the first response, if get the 'error'response,remind the "battery low" warning.Otherwise, start the auto-takeoff thread """ takeoff_response = None self.tello.takeoff() time.sleep(0.2) takeoff_response = self.tello.get_response() if takeoff_response != 'error': self.auto_takeoff_thread.start() else: print("battery low,please repalce with a new one") def telloLanding(self): return self.tello.land() def telloFlip_l(self): return self.tello.flip('l') def telloFlip_r(self): return self.tello.flip('r') def telloFlip_f(self): return self.tello.flip('f') def telloFlip_b(self): return self.tello.flip('b') def telloCW(self, degree): return self.tello.rotate_cw(degree) def telloCCW(self, degree): return self.tello.rotate_ccw(degree) def telloMoveForward(self, distance): return self.tello.move_forward(distance) def telloMoveBackward(self, distance): return self.tello.move_backward(distance) def telloMoveLeft(self, distance): return self.tello.move_left(distance) def telloMoveRight(self, distance): return self.tello.move_right(distance) def telloUp(self, dist): return self.tello.move_up(dist) def telloDown(self, dist): return self.tello.move_down(dist) def updateTrackBar(self): self.my_tello_hand.setThr(self.hand_thr_bar.get()) def updateDistancebar(self): self.distance = self.distance_bar.get() print('reset distance to %.1f' % self.distance) def updateDegreebar(self): self.degree = self.degree_bar.get() print('reset distance to %d' % self.degree) def on_keypress_w(self, event): print("up %d m" % self.distance) self.telloUp(self.distance) def on_keypress_s(self, event): print("down %d m" % self.distance) self.telloDown(self.distance) def on_keypress_a(self, event): print("ccw %d degree" % self.degree) self.tello.rotate_ccw(self.degree) def on_keypress_d(self, event): print("cw %d m" % self.degree) self.tello.rotate_cw(self.degree) def on_keypress_up(self, event): print("forward %d m" % self.distance) self.telloMoveForward(self.distance) def on_keypress_down(self, event): print("backward %d m" % self.distance) self.telloMoveBackward(self.distance) def on_keypress_left(self, event): print("left %d m" % self.distance) self.telloMoveLeft(self.distance) def on_keypress_right(self, event): print("right %d m" % self.distance) self.telloMoveRight(self.distance) def on_keypress_enter(self, event): if self.frame is not None: self.registerFace() self.tmp_f.focus_set() def onClose(self): """ set the stop event, cleanup the camera, and allow the rest of the quit process to continue """ print("[INFO] closing...") self.stopEvent.set() del self.tello self.root.quit()
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 __init__(self, master): self.master = master master.title("GUI") self.label = Label(master, text="Fluid Cell Control") self.label.pack() self.var1 = IntVar() self.check1 = Checkbutton(master, text="1", variable=self.var1, command=self.update_valve) self.check1.pack() self.var2 = IntVar() self.check2 = Checkbutton(master, text="2", variable=self.var2, command=self.update_valve) self.check2.pack() self.var3 = IntVar() self.check3 = Checkbutton(master, text="3", variable=self.var3, command=self.update_valve) self.check3.pack() self.var4 = IntVar() self.check4 = Checkbutton(master, text="4", variable=self.var4, command=self.update_valve) self.check4.pack() self.var5 = IntVar() self.check5 = Checkbutton(master, text="5", variable=self.var5, command=self.update_valve) self.check5.pack() self.var6 = IntVar() self.check6 = Checkbutton(master, text="6", variable=self.var6, command=self.update_valve) self.check6.pack() self.apply_button = Button(master, text="Apply", command=self.print_valve) self.apply_button.pack() self.speed = StringVar() self.speed_entry = Entry(master, textvariable=self.speed) self.speed_entry.pack() self.speed_scale = Scale(master, from_=0, to=255, variable=self.speed, orient=HORIZONTAL) self.speed_scale.pack() self.apply_speed = Button(master, text="Apply", command=self.print_speed) self.apply_speed.pack() self.close_button = Button(master, text="Close", command=master.quit) self.close_button.pack()
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])
window.birdViewPhotoImage = Label(window, image=birdViewPhotoImage) window.birdViewPhotoImage.grid(row=3, column=0) detectedLinesPhotoImage = PhotoImage( Image.fromarray(resize_image(mpimg.imread(images[0])))) window.detectedLinesPhotoImage = Label(window, image=detectedLinesPhotoImage) window.detectedLinesPhotoImage.grid(row=3, column=1) projectedPhotoImage = PhotoImage( Image.fromarray(resize_image(mpimg.imread(images[0])))) window.projectedPhotoImage = Label(window, image=projectedPhotoImage) window.projectedPhotoImage.grid(row=3, column=2) window.sobelLowThreshold = Scale(window, from_=0, to=255, orient=HORIZONTAL, command=change_sobel_thresh_min, label="Low Sobel Threshold") window.sobelLowThreshold.grid(row=4, column=0, columnspan=3, sticky='we') window.sobelHighThreshold = Scale(window, from_=0, to=255, orient=HORIZONTAL, command=change_sobel_thresh_min, label="High Sobel Threshold") window.sobelHighThreshold.grid(row=5, column=0, columnspan=3, sticky='we') window.sobelHighThreshold.set(255) window.sLowThreshold = Scale(window, from_=0,
def _entry(self): '''Method for creating widgets for collecting user input.''' # N (no of turtles) dim = 30*30 self.fill_label = Label(self._entryPane, anchor='w', justify='left', text='Fill', relief='raised', width=12, height=1, font='italic 20') self.fill_label.grid(row=0, column=1, ipady=14) self.fill = Scale(self._entryPane, from_=0, to=1, resolution=0.01, bd=3, relief='sunken', orient='horizontal', length=235, tickinterval=20) self.fill.grid(row=0, column=2) self.fill.set(0.8) self._N_label = Label(self._entryPane, anchor='w', justify='left', text="N:", relief='raised', width=12, height=1, font="italic 20") self._N_label.grid(row=1, column=1, ipady=14) self._N = Scale(self._entryPane, from_=0, to=100, resolution=1, bd=3, relief='sunken', orient='horizontal', length=235, tickinterval=20) self._N.set(30) self._N.grid(row=1, column=2) # Ticks (length of simulation) self._Ticks_label = Label(self._entryPane, anchor='w', justify='left', text="Time:", relief='raised', width=12, height=1, font="bold 20") self._Ticks_label.grid(row=2, column=1, ipady=14) self._Ticks = Scale(self._entryPane, from_=10, to=1000, resolution=1, bd=3, relief='sunken', orient='horizontal', length=235, tickinterval=990) self._Ticks.set(500) self._Ticks.grid(row=2, column=2) # % similar wanted self._Similar_label = Label(self._entryPane, anchor='w', justify='left', text="Similar wanted:", relief='raised', width=12, height=1, font="bold 20") self._Similar_label.grid(row=3, column=1, ipady=14) self._Similar = Scale(self._entryPane, from_=0.0, to=1.0, resolution=0.01, bd=3, relief='sunken', orient='horizontal', length=235, tickinterval=0.5) self._Similar.set(0.76) self._Similar.grid(row=3, column=2) # Delay between steps self._delay_label = Label(self._entryPane, anchor='w', justify='left', text="Delay (s):", relief='raised', width=12, height=1, font="bold 20") self._delay_label.grid(row=4, column=1, ipady=14) self._delay = Scale(self._entryPane, from_=0.0, to=1.0, resolution=0.01, bd=3, relief='sunken', orient='horizontal', length=235, tickinterval=0.5) self._delay.set(0.15) self._delay.grid(row=4, column=2)
def __init__(self, master=None): """ Constructor """ Frame.__init__(self, master, name='pvApplication', bg='black', padx=5, pady=5) # set black background, pad sides with 15 points, top/bottom 5 points # fill=BOTH fills in padding with background color # w/o fill=BOTH padding is default color # side=TOP is the default self.pack(fill=BOTH) master.resizable(False, False) # not resizable in x or y master.title(PVAPP_TXT) # set title bar of master (a.k.a. root) master.protocol("WM_DELETE_WINDOW", self._quit) # close window to quit self.validationConstants = self.readJSON('validationConstants') self.messagetext = self.readJSON('messagetext' + '.' + LANGUAGE) MAX_STRINGS = self.validationConstants["pvapplication"]["numStrs"] MAX_MODULES = self.validationConstants["pvapplication"]["numMods"] MAX_SUNS = self.validationConstants["pvapplication"]["sysEe"] CAPTION_FONT = nametofont('TkCaptionFont') # font for titles # PVsystem pvSys = self.pvSys = PVsystem() # variables numStrs = self.numStrs = IntVar(self, NUMBERSTRS, 'numStrs') numMods = self.numMods = IntVar(self, NUMBERMODS, 'numMods') numCells = self.numCells = IntVar(self, NUMBERCELLS, 'numCells') txtIsys = self.txtIsys = DoubleVar(self, name='txtIsys') txtVsys = self.txtVsys = DoubleVar(self, name='txtVsys') txtPsys = self.txtPsys = DoubleVar(self, name='txtPsys') txtImp = self.txtImp = StringVar(self, name='txtImp') txtVmp = self.txtVmp = StringVar(self, name='txtVmp') txtPmp = self.txtPmp = StringVar(self, name='txtPmp') txtIsc = self.txtIsc = StringVar(self, name='txtIsc') txtVoc = self.txtVoc = StringVar(self, name='txtVoc') txtFF = self.txtFF = StringVar(self, name='txtFF') txtEff = self.txtEff = StringVar(self, name='txtEff') sysEe = self.sysEe = DoubleVar(self, 1, name='sysEe') txtImp.set("{:7.3f}".format(self.pvSys.Imp)) # [A] txtVmp.set("{:7.3f}".format(self.pvSys.Vmp)) # [V] txtPmp.set("{:7.3f}".format(self.pvSys.Pmp / 1000)) # [kW] txtIsc.set("{:7.3f}".format(self.pvSys.Isc)) # [A] txtVoc.set("{:7.3f}".format(self.pvSys.Voc)) # [V] txtFF.set("{:7.3f}".format(self.pvSys.FF * 100)) # [%] txtEff.set("{:7.3f}".format(self.pvSys.eff * 100)) # [%] self.msgtext = StringVar(self, READY_MSG, 'msgtext') # must register vcmd and invcmd as Tcl functions vcmd = (self.register(self.validateWidget), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') invcmd = (self.register(self.invalidWidget), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') # SP logo # convert image to tk-compatible format (.gif, .pgm, or .ppm) self.SPlogo = ImageTk.PhotoImage(Image.open(SPLOGO)) # bg='black' fills extra space with black # anchor=W aligns photoimage on left side, NW is no different # padding is ignored by images, use borderwidth Label(self, image=self.SPlogo, borderwidth=5, bg='black', anchor=W).pack(fill=BOTH) # fill=BOTH expands the photoimage to fill parent frame # w/o fill=BOTH photoimage is centered in frame even with anchor=W # Intro text introText = 'PVmismatch calculates I-V and P-V curves as well as the' introText += ' max power point (MPP) for any sized system.\nSet the' introText += ' number of strings in the system, the number of modules' introText += ' per string and the number cells per module.' # anchor=W aligns message on left side, NW is no different # fg='white' sets text color to white, default is black, so it doesn't # show on black background # default aspect is 150%, about as wide as high, or set width>0 Message(self, text=introText, width=750, bg='black', fg='white', anchor=W).pack(fill=BOTH) # fill=BOTH expands the message to fill parent frame # w/o fill=BOTH message is centered in frame even with anchor=W # PVsystem frame pvSysFrame = self.pvSysFrame = Frame(master, name='pvSysFrame') # fill=BOTH keeps widgets in frame on left when window is resized pvSysFrame.pack(fill=BOTH) # PVsystem matplotlib figure canvas self.pvSysPlotFrame = Frame(pvSysFrame, name='pvSysPlotFrame') pvSysPlotFrame = self.pvSysPlotFrame pvSysPlotFrame.pack(side=RIGHT) pvSysPlot = self.pvSysPlot = pvSys.plotSys() self.pvSysFigCanvas = FigureCanvasTkAgg(pvSysPlot, master=pvSysPlotFrame, resize_callback=None) pvSysFigCanvas = self.pvSysFigCanvas pvSysFigCanvas.get_tk_widget()._name = 'pvSysFigCanvas' # IGNORE:W0212 pvSysFigCanvas.show() # NB: FigureCanvasTkAgg._tkcanvas is FigureCanvasTkAgg.get_tk_widget() pvSysFigCanvas.get_tk_widget().pack(fill=BOTH) pvSysToolbar = NavigationToolbar2TkAgg(pvSysFigCanvas, pvSysPlotFrame) pvSysToolbar.update() pvSysToolbar.pack(fill=BOTH) # PVsystem data frame pvSysDataFrame = self.pvSysDataFrame = Frame(pvSysFrame, name='pvSysDataFrame') pvSysDataFrame.pack(side=LEFT) _row = 0 Label(pvSysDataFrame, text='PVsystem', font=CAPTION_FONT).grid(row=_row, columnspan=3, sticky=W) # number of strings _row += 1 # row 1 Label(pvSysDataFrame, text='Number of Strings').grid(row=_row, columnspan=2, sticky=W) # use textVar to set number of strings from LOAD, RESET or default spinboxCnf = {'name': 'numStrSpinbox', 'from_': 1, 'to': MAX_STRINGS, 'textvariable': numStrs, 'width': 5, 'validate': 'all', 'validatecommand': vcmd, 'invalidcommand': invcmd, 'command': self.updatePVsys} self.numStrSpinbox = Spinbox(pvSysDataFrame, cnf=spinboxCnf) self.numStrSpinbox.bind("<Return>", self.keyBinding) self.numStrSpinbox.grid(row=_row, column=2) # number of modules _row += 1 # row 2 Label(pvSysDataFrame, text='Number of Modules').grid(row=_row, columnspan=2, sticky=W) # number of modules spinbox spinboxCnf = {'name': 'numModSpinbox', 'from_': 1, 'to': MAX_MODULES, 'textvariable': numMods, 'width': 5, 'validate': 'all', 'validatecommand': vcmd, 'invalidcommand': invcmd, 'command': self.updatePVsys} self.numModSpinbox = Spinbox(pvSysDataFrame, cnf=spinboxCnf) self.numModSpinbox.bind("<Return>", self.keyBinding) self.numModSpinbox.grid(row=_row, column=2) # number of cells _row += 1 # row 3 Label(pvSysDataFrame, text='Number of Cells').grid(row=_row, columnspan=2, sticky=W) # http://www.logilab.org/card/pylintfeatures#basic-checker # pylint: disable = W0142 self.numCellOption = OptionMenu(pvSysDataFrame, numCells, *MODSIZES, command=self.updatePVsys) # pylint: enable = W0142 self.numCellOption._name = 'numCellOption' # IGNORE:W0212 self.numCellOption.grid(row=_row, column=2) # Advanced Configuration button _row += 1 # row 14 buttonCnf = {'name': 'advCnfButton', 'text': 'Advanced Configuration', 'command': self.startAdvCnf_tk} pvStrButton = self.pvStrButton = Button(pvSysDataFrame, buttonCnf) pvStrButton.grid(row=_row, columnspan=3, sticky=(E + W)) # slider to explore IV curves _row += 1 # row 4, 5 & 6 self.pvSysScale = Scale(pvSysDataFrame, orient=HORIZONTAL, label='I-V Curve', font=CAPTION_FONT, command=self.getIV, showvalue=False, from_=0, to=(pvSys.pvconst.npts - 1)) self.pvSysScale.grid(row=_row, columnspan=3, sticky=(E + W)) # Isys Label(pvSysDataFrame, text='Isys [A]').grid(row=(_row + 1)) self.pvIsys = Entry(pvSysDataFrame, textvariable=txtIsys, width=7) self.pvIsys.grid(row=(_row + 2)) # Vsys Label(pvSysDataFrame, text='Vsys [V]').grid(row=(_row + 1), column=1) self.pvVsys = Entry(pvSysDataFrame, textvariable=txtVsys, width=7) self.pvVsys.grid(row=(_row + 2), column=1) # Psys Label(pvSysDataFrame, text='Psys [kW]').grid(row=(_row + 1), column=2) self.pvPsys = Entry(pvSysDataFrame, textvariable=txtPsys, width=7) self.pvPsys.grid(row=(_row + 2), column=2) # Imp, Vmp & Pmp _row += 3 # row 7, 8, 9, 10, 11 & 12 Label(pvSysDataFrame, text='I-V Characteristics', font=CAPTION_FONT).grid(row=_row, columnspan=3, sticky=W) Label(pvSysDataFrame, text='Imp [A]').grid(row=(_row + 1)) Label(pvSysDataFrame, text='Vmp [V]').grid(row=(_row + 1), column=1) Label(pvSysDataFrame, text='Pmp [kW]').grid(row=(_row + 1), column=2) self.pvImp = Entry(pvSysDataFrame, textvariable=txtImp, width=7, state='readonly') self.pvImp.grid(row=(_row + 2)) self.pvVmp = Entry(pvSysDataFrame, textvariable=txtVmp, width=7, state='readonly') self.pvVmp.grid(row=(_row + 2), column=1) self.pvPmp = Entry(pvSysDataFrame, textvariable=txtPmp, width=7, state='readonly') self.pvPmp.grid(row=(_row + 2), column=2) # Isc, Voc & FF Label(pvSysDataFrame, text='Isc [A]').grid(row=(_row + 3)) Label(pvSysDataFrame, text='Voc [V]').grid(row=(_row + 3), column=1) Label(pvSysDataFrame, text='FF [%]').grid(row=(_row + 3), column=2) self.pvIsc = Entry(pvSysDataFrame, textvariable=txtIsc, width=7, state='readonly') self.pvIsc.grid(row=(_row + 4)) self.pvVoc = Entry(pvSysDataFrame, textvariable=txtVoc, width=7, state='readonly') self.pvVoc.grid(row=(_row + 4), column=1) self.pvFF = Entry(pvSysDataFrame, textvariable=txtFF, width=7, state='readonly') self.pvFF.grid(row=(_row + 4), column=2) Label(pvSysDataFrame, text='Efficiency [%]').grid(row=(_row + 5), columnspan=2) self.pvEff = Entry(pvSysDataFrame, textvariable=txtEff, width=7, state='readonly') self.pvEff.grid(row=(_row + 5), column=2) # set suns _row += 6 # row 13 Label(pvSysDataFrame, text='Irradiance [suns]', font=CAPTION_FONT).grid(row=_row, columnspan=2, sticky=W) # number of modules spinbox spinboxCnf = {'name': 'sunSpinbox', 'from_': 0.2, 'to': MAX_SUNS, 'increment': 0.1, 'textvariable': sysEe, 'width': 5, 'validate': 'all', 'validatecommand': vcmd, 'invalidcommand': invcmd, 'command': self.updatePVsys} self.sunSpinbox = Spinbox(pvSysDataFrame, cnf=spinboxCnf) self.sunSpinbox.bind("<Return>", self.keyBinding) self.sunSpinbox.grid(row=_row, column=2) # PVstring button _row += 1 # row 14 buttonCnf = {'name': 'pvStrButton', 'text': 'PVstring', 'command': self.startPVstring_tk} pvStrButton = self.pvStrButton = Button(pvSysDataFrame, buttonCnf) pvStrButton.grid(row=_row, columnspan=3, sticky=(E + W)) # toolbar toolbar = self.toolbarframe = Frame(master, name='toolbar') toolbar.pack(fill=BOTH) self.QUIT = Button(toolbar, text='Quit', command=self._quit) self.QUIT.pack(side=RIGHT) self.SAVE = Button(toolbar, text='Save', command=self._save) self.SAVE.pack(side=RIGHT) self.LOAD = Button(toolbar, text='Load', command=self._load) self.LOAD.pack(side=RIGHT) self.RESET = Button(toolbar, text='Reset', command=self._reset) self.RESET.pack(side=RIGHT) self.UPDATE = Button(toolbar, text='Update', command=self._update) self.UPDATE.pack(side=RIGHT) self.HELP = Button(toolbar, text='Help', command=self._help) self.HELP.pack(side=RIGHT) self.MESSAGE = Message(toolbar, textvariable=self.msgtext, width=500, fg='red') self.MESSAGE.pack(side=LEFT)
def init(): #setting variables to global scope that need to be accessed outside of init() global curve_smoothing_slider, horizontal_shift_slider, vertical_shift_slider, image_canvas, bounds_button, preview_button, export_button, baseline_choice, im, imload, peak_num_choice left_frame = Frame(root) left_frame.pack(side="left") middle_frame = Frame(root) middle_frame.pack(side="right") right_frame = Frame(root) right_frame.pack(side="right") sub_middle_frame = Frame(middle_frame) sub_middle_frame.pack(side="bottom", pady=(0, 10)) #left side inputs Button(left_frame, text="Help", command=help_window).pack(anchor='nw', padx=(10, 0), pady=(10, 10)) Button(left_frame, text="Select a file", command=select_file).pack(anchor='n', pady=(0, 15)) Label(left_frame, text="Threshold and Crop", justify="center").pack() threshold_slider = Scale(left_frame, orient="horizontal", length=200, from_=1.0, to=30.0, command=update_thresh) threshold_slider.pack(padx=20, pady=(0, 10)) #button for selecting the region of interest (ROI), this ROI is then analyzed for the graph Button(left_frame, text="Select a ROI", command=find_roi).pack(pady=(0, 15)) #slider for determining how much the curve is smoothed out (typically has very many oscillations and spikes) Label(left_frame, text="Curve Smoothing", justify="center", padx=20).pack() curve_smoothing_slider = Scale(left_frame, orient="horizontal", length=200, from_=0.0, to=30.0, command=update_smooth) curve_smoothing_slider.pack(padx=20, pady=(0, 20)) curve_smoothing_slider['state'] = 'disable' #determines whether the baselining will happen from the lowest value (from both curves lowest val is zeroed) or midpoint (average value of both is zeroed and then lowest value brought to zero) baseline_choice = tkinter.IntVar() baseline_choice.set(1) modes = [("Midpoint", 101), ("Lowest Value", 102)] Label(left_frame, text="Baseline from:", justify="left", padx=20).pack() for mode, val in modes: Radiobutton(left_frame, text=mode, indicatoron=1, command=update_baseline, justify="left", padx=20, variable=baseline_choice, value=val).pack(anchor='w') #a multiple choice field for how many peaks you want analyzed at the current moment peak_num_choice = tkinter.IntVar() peak_num_choice.set(1) modes = [("One Peak", 101), ("Two Peaks", 102)] Label(left_frame, text="How many peaks to compare:", justify="left", padx=20).pack(pady=(20, 0)) for mode, val in modes: Radiobutton(left_frame, text=mode, indicatoron=1, command=update_peaks, justify="left", padx=20, variable=peak_num_choice, value=val).pack(anchor='w') #bottom row inputs bounds_button = Button(left_frame, text="Choose Bounds", command=choose_peak_bounds) bounds_button.pack(side="left", padx=(15, 10), pady=(30, 10)) bounds_button["state"] = "disable" #building the preview button, used to look at the current strip being analyzed preview_button = Button(left_frame, text="Preview", command=preview_graph) preview_button.pack(side="left", padx=(10, 10), pady=(30, 10)) preview_button["state"] = "disable" #building the export button, disabled at first until you have data to export export_button = Button(left_frame, text="Export", command=save_graph) export_button.pack(side="left", padx=(10, 0), pady=(30, 10)) export_button["state"] = "disable" #building the horizontal shift (used to shift one line left and right) Label(sub_middle_frame, text="Horizontal Shift").grid(column=0, row=1, padx=(0, 20)) horizontal_shift_slider = Scale(sub_middle_frame, orient="horizontal", length=300, from_=-10.0, to=10.0, command=update_h_shift) horizontal_shift_slider.grid(column=0, row=0, padx=(0, 20)) horizontal_shift_slider['state'] = 'disable' #building the vertical shift (shifts one line up and down) Label(sub_middle_frame, text="Vertical Shift").grid(column=1, row=1) vertical_shift_slider = Scale(sub_middle_frame, orient="horizontal", length=300, from_=-10.0, to=10.0, command=update_v_shift) vertical_shift_slider.grid(column=1, row=0) vertical_shift_slider['state'] = 'disable' #right side graph width, height = plot_disp_size image_canvas = Canvas(middle_frame, width=width, height=height) image_canvas.pack(padx=(20, 0), pady=(0, 0)) #blanks canvas with a white frame, image_canvas is modified to add the graph onto screen each time im = ImageTk.PhotoImage(Image.new("RGB", plot_disp_size, (255, 255, 255))) #PIL solution imload = image_canvas.create_image(0, 0, image=im, anchor='nw')
class HsvGui(tk.Frame): def __init__(self, master=None,): tk.Frame.__init__(self, master) self.root = master self.Webcam = G2.Webcamera() self.baseImage = self.Webcam.save_image(persist=False) self.baseImage = cv2.cvtColor(numpy.array(self.baseImage), cv2.COLOR_RGB2BGR) self.createWidgets() self.OnValueChange = event.Event() self.title = "Webcam" cv2.startWindowThread() cv2.namedWindow(self.title, cv2.WINDOW_NORMAL) cv2.imshow(self.title, self.baseImage) self.Funkify() def createWidgets(self): Label(self.root, text="Value:").grid(row=0, sticky=W) Label(self.root, text="H:").grid(row=1, sticky=W) Label(self.root, text="S:").grid(row=2, sticky=W) Label(self.root, text="V:").grid(row=3, sticky=W) Label(self.root, text="S:").grid(row=4, sticky=W) Label(self.root, text="V:").grid(row=5, sticky=W) Label(self.root, text="H:").grid(row=6, sticky=W) self.valueLabel = Label(self.root, text="000-000-000 to 000-000-000") self.valueLabel.grid(row=0, column=1, sticky=W) self.Hvalue = Scale(self.root, from_=0, to=255, orient=HORIZONTAL, command=self.__sliderCallback) self.Hvalue.grid(row=1, column=1) self.Hvalue.set(0) self.Svalue = Scale(self.root, from_=0, to=255, orient=HORIZONTAL, command=self.__sliderCallback) self.Svalue.grid( row=2, column=1) self.Svalue.set(90) self.Vvalue = Scale(self.root, from_=0, to=255, orient=HORIZONTAL, command=self.__sliderCallback) self.Vvalue.grid( row=3, column=1) self.Vvalue.set(0) self.HvalueMax = Scale(self.root, from_=0, to=255, orient=HORIZONTAL, command=self.__sliderCallback) self.HvalueMax.grid(row=4, column=1) self.HvalueMax.set(255) self.SvalueMax = Scale(self.root, from_=0, to=255, orient=HORIZONTAL, command=self.__sliderCallback) self.SvalueMax.grid(row=5, column=1) self.SvalueMax.set(255) self.VvalueMax = Scale(self.root, from_=0, to=255, orient=HORIZONTAL, command=self.__sliderCallback) self.VvalueMax.grid(row=6, column=1) self.VvalueMax.set(120) self.Go = tk.Button(self.root, text="Go!", fg="Green", command=self.Funkify) self.Go.grid(row=7, column=0) self.QUIT = tk.Button(self.root, text="QUIT", fg="red", command=self.root.destroy) self.QUIT.grid(row=7, column=1) def Funkify(self): H = int(self.Hvalue.get()) S = int(self.Svalue.get()) V = int(self.Vvalue.get()) lower = [H, S, V] Hmax = int(self.HvalueMax.get()) Smax = int(self.SvalueMax.get()) Vmax = int(self.VvalueMax.get()) upper= [Hmax, Smax, Vmax] #self.valueLabel['text'] = '{0}-{1}-{2} to {3}-{4}-{5}'.format(H, S, V, Hmax, Smax, Vmax) output, a = self.Webcam.funkyfy(colorrange=(lower, upper)) cv2.imshow(self.title, numpy.hstack([output, a])) def __sliderCallback(self, args): print('Sliding!!')
if __name__ == '__main__': from tkinter import Tk, Scale from comtypes import CoCreateInstance from win32gui import GetParent tbm = CoCreateInstance(GUID_CTaskbarList, interface=ITaskbarList3) def onMove_gen(root): def onMove(value): tbm.SetProgressValue(GetParent(root.winfo_id()), int(value), 100) return onMove root = Tk() tbar = Scale(root, from_=0, to=100, orient='horizontal', command=onMove_gen(root)) tbar.pack() root.mainloop() #class ITaskbarList(IUnknown): # _iid_ = GUID('{56FDF342-FD6D-11D0-958A-006097C9A090}') # _methods_ = [ # COMMETHOD([], HRESULT, 'HrInit'), # # COMMETHOD([], HRESULT, 'AddTab', # (['in'], HWND, 'hwnd') # ), # # COMMETHOD([], HRESULT, 'DeleteTab',
Button(root, text='tk Button').grid(row=1, column=0) ttk.Button(root, text='ttk Button').grid(row=1, column=1) Checkbutton(root, text='tk CheckButton').grid(row=2, column=0) ttk.Checkbutton(root, text='ttk CheckButton').grid(row=2, column=1) Entry(root).grid(row=3, column=0) ttk.Entry(root).grid(row=3, column=1) PanedWindow(root).grid(row=4, column=0) ttk.PanedWindow(root).grid(row=4, column=1) Radiobutton(root, text='tk Radio').grid(row=5, column=0) ttk.Radiobutton(root, text='ttk Radio').grid(row=5, column=1) Scale(root, orient=HORIZONTAL).grid(row=6, column=0) ttk.Scale(root).grid(row=6, column=1) ttk.Separator(root, orient=HORIZONTAL).grid(row=7, columnspan=2, sticky="ew") ttk.Label(root, text='NEW WIDGETS INTRODUCED IN ttk').grid(row=8, columnspan=2) ttk.Separator(root, orient=HORIZONTAL).grid(row=9, columnspan=2, sticky="ew") ttk.Combobox(root).grid(row=11, column=0) my_notebook = ttk.Notebook(root) my_notebook.grid(row=12, column=1) frame_1 = ttk.Frame(my_notebook) frame_2 = ttk.Frame(my_notebook) my_notebook.add(frame_1, text='Tab One') my_notebook.add(frame_2, text='Tab Two')
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()
def start_options_frame(self,chosen_dir=None): self.p2d = par2deep(chosen_dir) self.args = {} subframe = Frame(self) basicset = LabelFrame(subframe, text="Basic Settings",pad=10) basicset.pack(fill=X,pady=(0,20)) advset = LabelFrame(subframe, text="Advanced Settings",pad=10) advset.pack(fill=X) def pickdir(): # self.args["directory"].delete(0,END) # self.args["directory"].insert(0,filedialog.askdirectory()) # self.p2d.__init__(self.args["directory"].get()) self.new_window(self.topbar_frame(0), self.start_options_frame(filedialog.askdirectory()), self.start_actions_frame()) Button(basicset, text="Pick directory", command=pickdir).pack(side='left') self.args["directory"] = Entry(basicset) self.args["directory"].pack(fill=X) if chosen_dir == None: self.args["directory"].insert(0,self.p2d.args["directory"]) else: self.args["directory"].insert(0,chosen_dir) self.args["overwrite"] = IntVar() self.args["overwrite"].set(self.p2d.args["overwrite"]) cb1 = Checkbutton(advset, text="Overwrite all parity data", variable=self.args["overwrite"]) cb1.pack(fill=X) CreateToolTip(cb1,"Any existing parity data found (any *.par* files) will be removed and overwritten.") self.args["noverify"] = IntVar() self.args["noverify"].set(self.p2d.args["noverify"]) cb2 = Checkbutton(advset, text="Skip verification", variable=self.args["noverify"]) cb2.pack(fill=X) CreateToolTip(cb2,"Skips verification of files with existing parity data. Use when you only want to create parity data for new files.") self.args["keep_old"] = IntVar() self.args["keep_old"].set(self.p2d.args["keep_old"]) cb3 = Checkbutton(advset, text="Keep old parity files or par2 backup files", variable=self.args["keep_old"]) cb3.pack(fill=X) CreateToolTip(cb3,"Do not remove par backup files (*.[0-9]) and do not remove unused parity files (*.par*).") Label(advset, text="Exclude directories (comma separated)").pack(fill=X) self.args["excludes"] = Entry(advset) self.args["excludes"].pack(fill=X) self.args["excludes"].insert(0,','.join(self.p2d.args["excludes"])) CreateToolTip(self.args["excludes"],"These subdirectories will be excluded from the analysis. Use 'root' for the root of the directory.") Label(advset, text="Exclude extensions (comma separated)").pack(fill=X) self.args["extexcludes"] = Entry(advset) self.args["extexcludes"].pack(fill=X) self.args["extexcludes"].insert(0,','.join(self.p2d.args["extexcludes"])) CreateToolTip(self.args["extexcludes"],"These extensions will be excluded from the analysis.") Label(advset, text="Path to par2.exe").pack(fill=X) self.args["par_cmd"] = Entry(advset) self.args["par_cmd"].pack(fill=X) self.args["par_cmd"].insert(0,self.p2d.args["par_cmd"]) CreateToolTip(self.args["par_cmd"],"Should be set automatically and correctly, but can be overriden.") Label(advset, text="Percentage of protection").pack(fill=X) self.args["percentage"] = IntVar() self.args["percentage"].set(self.p2d.args["percentage"]) s1 = Scale(advset,orient=HORIZONTAL,from_=5,to=100,resolution=1,variable=self.args["percentage"]) s1.pack(fill=X) CreateToolTip(s1,"The maximum percentage of corrupted data you will be able to recover from. Higher is safer, but uses more data.") return subframe
class PVapplicaton(Frame): """ classdocs """ def __init__(self, master=None): """ Constructor """ Frame.__init__(self, master, name='pvApplication', bg='black', padx=5, pady=5) # set black background, pad sides with 15 points, top/bottom 5 points # fill=BOTH fills in padding with background color # w/o fill=BOTH padding is default color # side=TOP is the default self.pack(fill=BOTH) master.resizable(False, False) # not resizable in x or y master.title(PVAPP_TXT) # set title bar of master (a.k.a. root) master.protocol("WM_DELETE_WINDOW", self._quit) # close window to quit self.validationConstants = self.readJSON('validationConstants') self.messagetext = self.readJSON('messagetext' + '.' + LANGUAGE) MAX_STRINGS = self.validationConstants["pvapplication"]["numStrs"] MAX_MODULES = self.validationConstants["pvapplication"]["numMods"] MAX_SUNS = self.validationConstants["pvapplication"]["sysEe"] CAPTION_FONT = nametofont('TkCaptionFont') # font for titles # PVsystem pvSys = self.pvSys = PVsystem() # variables numStrs = self.numStrs = IntVar(self, NUMBERSTRS, 'numStrs') numMods = self.numMods = IntVar(self, NUMBERMODS, 'numMods') numCells = self.numCells = IntVar(self, NUMBERCELLS, 'numCells') txtIsys = self.txtIsys = DoubleVar(self, name='txtIsys') txtVsys = self.txtVsys = DoubleVar(self, name='txtVsys') txtPsys = self.txtPsys = DoubleVar(self, name='txtPsys') txtImp = self.txtImp = StringVar(self, name='txtImp') txtVmp = self.txtVmp = StringVar(self, name='txtVmp') txtPmp = self.txtPmp = StringVar(self, name='txtPmp') txtIsc = self.txtIsc = StringVar(self, name='txtIsc') txtVoc = self.txtVoc = StringVar(self, name='txtVoc') txtFF = self.txtFF = StringVar(self, name='txtFF') txtEff = self.txtEff = StringVar(self, name='txtEff') sysEe = self.sysEe = DoubleVar(self, 1, name='sysEe') txtImp.set("{:7.3f}".format(self.pvSys.Imp)) # [A] txtVmp.set("{:7.3f}".format(self.pvSys.Vmp)) # [V] txtPmp.set("{:7.3f}".format(self.pvSys.Pmp / 1000)) # [kW] txtIsc.set("{:7.3f}".format(self.pvSys.Isc)) # [A] txtVoc.set("{:7.3f}".format(self.pvSys.Voc)) # [V] txtFF.set("{:7.3f}".format(self.pvSys.FF * 100)) # [%] txtEff.set("{:7.3f}".format(self.pvSys.eff * 100)) # [%] self.msgtext = StringVar(self, READY_MSG, 'msgtext') # must register vcmd and invcmd as Tcl functions vcmd = (self.register(self.validateWidget), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') invcmd = (self.register(self.invalidWidget), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') # SP logo # convert image to tk-compatible format (.gif, .pgm, or .ppm) self.SPlogo = ImageTk.PhotoImage(Image.open(SPLOGO)) # bg='black' fills extra space with black # anchor=W aligns photoimage on left side, NW is no different # padding is ignored by images, use borderwidth Label(self, image=self.SPlogo, borderwidth=5, bg='black', anchor=W).pack(fill=BOTH) # fill=BOTH expands the photoimage to fill parent frame # w/o fill=BOTH photoimage is centered in frame even with anchor=W # Intro text introText = 'PVmismatch calculates I-V and P-V curves as well as the' introText += ' max power point (MPP) for any sized system.\nSet the' introText += ' number of strings in the system, the number of modules' introText += ' per string and the number cells per module.' # anchor=W aligns message on left side, NW is no different # fg='white' sets text color to white, default is black, so it doesn't # show on black background # default aspect is 150%, about as wide as high, or set width>0 Message(self, text=introText, width=750, bg='black', fg='white', anchor=W).pack(fill=BOTH) # fill=BOTH expands the message to fill parent frame # w/o fill=BOTH message is centered in frame even with anchor=W # PVsystem frame pvSysFrame = self.pvSysFrame = Frame(master, name='pvSysFrame') # fill=BOTH keeps widgets in frame on left when window is resized pvSysFrame.pack(fill=BOTH) # PVsystem matplotlib figure canvas self.pvSysPlotFrame = Frame(pvSysFrame, name='pvSysPlotFrame') pvSysPlotFrame = self.pvSysPlotFrame pvSysPlotFrame.pack(side=RIGHT) pvSysPlot = self.pvSysPlot = pvSys.plotSys() self.pvSysFigCanvas = FigureCanvasTkAgg(pvSysPlot, master=pvSysPlotFrame, resize_callback=None) pvSysFigCanvas = self.pvSysFigCanvas pvSysFigCanvas.get_tk_widget()._name = 'pvSysFigCanvas' # IGNORE:W0212 pvSysFigCanvas.show() # NB: FigureCanvasTkAgg._tkcanvas is FigureCanvasTkAgg.get_tk_widget() pvSysFigCanvas.get_tk_widget().pack(fill=BOTH) pvSysToolbar = NavigationToolbar2TkAgg(pvSysFigCanvas, pvSysPlotFrame) pvSysToolbar.update() pvSysToolbar.pack(fill=BOTH) # PVsystem data frame pvSysDataFrame = self.pvSysDataFrame = Frame(pvSysFrame, name='pvSysDataFrame') pvSysDataFrame.pack(side=LEFT) _row = 0 Label(pvSysDataFrame, text='PVsystem', font=CAPTION_FONT).grid(row=_row, columnspan=3, sticky=W) # number of strings _row += 1 # row 1 Label(pvSysDataFrame, text='Number of Strings').grid(row=_row, columnspan=2, sticky=W) # use textVar to set number of strings from LOAD, RESET or default spinboxCnf = {'name': 'numStrSpinbox', 'from_': 1, 'to': MAX_STRINGS, 'textvariable': numStrs, 'width': 5, 'validate': 'all', 'validatecommand': vcmd, 'invalidcommand': invcmd, 'command': self.updatePVsys} self.numStrSpinbox = Spinbox(pvSysDataFrame, cnf=spinboxCnf) self.numStrSpinbox.bind("<Return>", self.keyBinding) self.numStrSpinbox.grid(row=_row, column=2) # number of modules _row += 1 # row 2 Label(pvSysDataFrame, text='Number of Modules').grid(row=_row, columnspan=2, sticky=W) # number of modules spinbox spinboxCnf = {'name': 'numModSpinbox', 'from_': 1, 'to': MAX_MODULES, 'textvariable': numMods, 'width': 5, 'validate': 'all', 'validatecommand': vcmd, 'invalidcommand': invcmd, 'command': self.updatePVsys} self.numModSpinbox = Spinbox(pvSysDataFrame, cnf=spinboxCnf) self.numModSpinbox.bind("<Return>", self.keyBinding) self.numModSpinbox.grid(row=_row, column=2) # number of cells _row += 1 # row 3 Label(pvSysDataFrame, text='Number of Cells').grid(row=_row, columnspan=2, sticky=W) # http://www.logilab.org/card/pylintfeatures#basic-checker # pylint: disable = W0142 self.numCellOption = OptionMenu(pvSysDataFrame, numCells, *MODSIZES, command=self.updatePVsys) # pylint: enable = W0142 self.numCellOption._name = 'numCellOption' # IGNORE:W0212 self.numCellOption.grid(row=_row, column=2) # Advanced Configuration button _row += 1 # row 14 buttonCnf = {'name': 'advCnfButton', 'text': 'Advanced Configuration', 'command': self.startAdvCnf_tk} pvStrButton = self.pvStrButton = Button(pvSysDataFrame, buttonCnf) pvStrButton.grid(row=_row, columnspan=3, sticky=(E + W)) # slider to explore IV curves _row += 1 # row 4, 5 & 6 self.pvSysScale = Scale(pvSysDataFrame, orient=HORIZONTAL, label='I-V Curve', font=CAPTION_FONT, command=self.getIV, showvalue=False, from_=0, to=(pvSys.pvconst.npts - 1)) self.pvSysScale.grid(row=_row, columnspan=3, sticky=(E + W)) # Isys Label(pvSysDataFrame, text='Isys [A]').grid(row=(_row + 1)) self.pvIsys = Entry(pvSysDataFrame, textvariable=txtIsys, width=7) self.pvIsys.grid(row=(_row + 2)) # Vsys Label(pvSysDataFrame, text='Vsys [V]').grid(row=(_row + 1), column=1) self.pvVsys = Entry(pvSysDataFrame, textvariable=txtVsys, width=7) self.pvVsys.grid(row=(_row + 2), column=1) # Psys Label(pvSysDataFrame, text='Psys [kW]').grid(row=(_row + 1), column=2) self.pvPsys = Entry(pvSysDataFrame, textvariable=txtPsys, width=7) self.pvPsys.grid(row=(_row + 2), column=2) # Imp, Vmp & Pmp _row += 3 # row 7, 8, 9, 10, 11 & 12 Label(pvSysDataFrame, text='I-V Characteristics', font=CAPTION_FONT).grid(row=_row, columnspan=3, sticky=W) Label(pvSysDataFrame, text='Imp [A]').grid(row=(_row + 1)) Label(pvSysDataFrame, text='Vmp [V]').grid(row=(_row + 1), column=1) Label(pvSysDataFrame, text='Pmp [kW]').grid(row=(_row + 1), column=2) self.pvImp = Entry(pvSysDataFrame, textvariable=txtImp, width=7, state='readonly') self.pvImp.grid(row=(_row + 2)) self.pvVmp = Entry(pvSysDataFrame, textvariable=txtVmp, width=7, state='readonly') self.pvVmp.grid(row=(_row + 2), column=1) self.pvPmp = Entry(pvSysDataFrame, textvariable=txtPmp, width=7, state='readonly') self.pvPmp.grid(row=(_row + 2), column=2) # Isc, Voc & FF Label(pvSysDataFrame, text='Isc [A]').grid(row=(_row + 3)) Label(pvSysDataFrame, text='Voc [V]').grid(row=(_row + 3), column=1) Label(pvSysDataFrame, text='FF [%]').grid(row=(_row + 3), column=2) self.pvIsc = Entry(pvSysDataFrame, textvariable=txtIsc, width=7, state='readonly') self.pvIsc.grid(row=(_row + 4)) self.pvVoc = Entry(pvSysDataFrame, textvariable=txtVoc, width=7, state='readonly') self.pvVoc.grid(row=(_row + 4), column=1) self.pvFF = Entry(pvSysDataFrame, textvariable=txtFF, width=7, state='readonly') self.pvFF.grid(row=(_row + 4), column=2) Label(pvSysDataFrame, text='Efficiency [%]').grid(row=(_row + 5), columnspan=2) self.pvEff = Entry(pvSysDataFrame, textvariable=txtEff, width=7, state='readonly') self.pvEff.grid(row=(_row + 5), column=2) # set suns _row += 6 # row 13 Label(pvSysDataFrame, text='Irradiance [suns]', font=CAPTION_FONT).grid(row=_row, columnspan=2, sticky=W) # number of modules spinbox spinboxCnf = {'name': 'sunSpinbox', 'from_': 0.2, 'to': MAX_SUNS, 'increment': 0.1, 'textvariable': sysEe, 'width': 5, 'validate': 'all', 'validatecommand': vcmd, 'invalidcommand': invcmd, 'command': self.updatePVsys} self.sunSpinbox = Spinbox(pvSysDataFrame, cnf=spinboxCnf) self.sunSpinbox.bind("<Return>", self.keyBinding) self.sunSpinbox.grid(row=_row, column=2) # PVstring button _row += 1 # row 14 buttonCnf = {'name': 'pvStrButton', 'text': 'PVstring', 'command': self.startPVstring_tk} pvStrButton = self.pvStrButton = Button(pvSysDataFrame, buttonCnf) pvStrButton.grid(row=_row, columnspan=3, sticky=(E + W)) # toolbar toolbar = self.toolbarframe = Frame(master, name='toolbar') toolbar.pack(fill=BOTH) self.QUIT = Button(toolbar, text='Quit', command=self._quit) self.QUIT.pack(side=RIGHT) self.SAVE = Button(toolbar, text='Save', command=self._save) self.SAVE.pack(side=RIGHT) self.LOAD = Button(toolbar, text='Load', command=self._load) self.LOAD.pack(side=RIGHT) self.RESET = Button(toolbar, text='Reset', command=self._reset) self.RESET.pack(side=RIGHT) self.UPDATE = Button(toolbar, text='Update', command=self._update) self.UPDATE.pack(side=RIGHT) self.HELP = Button(toolbar, text='Help', command=self._help) self.HELP.pack(side=RIGHT) self.MESSAGE = Message(toolbar, textvariable=self.msgtext, width=500, fg='red') self.MESSAGE.pack(side=LEFT) # Validation substitutions # %d Type of action: 1 for insert, 0 for delete, or -1 for focus, forced or # textvariable validation. # %i Index of char string to be inserted/deleted, if any, otherwise -1. # %P The value of the spinbox should edition occur. If you are configuring # the spinbox widget to have a new textvariable, this will be the value # of that textvariable. # %s The current value of spinbox before edition. # %S The text string being inserted/deleted, if any. Otherwise it is an # empty string. # %v The type of validation currently set. # %V The type of validation that triggered the callback (key, focusin, # focusout, forced). # %W The name of the spinbox widget. # TODO: Fix these functions so that delete and overwrite work def validateWidget(self, *args): # W = Tkinter.W = 'w' is already used, so use W_ instead (d, i, P, s, S, v, V, W_) = args # @UnusedVariable # IGNORE:W0612 logging.debug("OnValidate: d={}, i={}, P={}, s={}, S={}, v={}, V={}, W={}".format(*args)) if W_ == ".pvSysFrame.pvSysDataFrame.numStrSpinbox": valType = INTEGERS valTest = lambda val: int(val) # IGNORE:W0108 elif W_ == ".pvSysFrame.pvSysDataFrame.numModSpinbox": valType = INTEGERS valTest = lambda val: int(val) # IGNORE:W0108 elif W_ == ".pvSysFrame.pvSysDataFrame.sunSpinbox": valType = FLOATS valTest = lambda val: float(val) # IGNORE:W0108 else: return False w = self.nametowidget(W_) w.config(validate=v) if S in valType: try: valTest(P) except ValueError: return False return True else: return False def invalidWidget(self, *args): (d, i, P, s, S, v, V, W_) = args # @UnusedVariable # IGNORE:W0612 logging.debug("OnInvalid: d={}, i={}, P={}, s={}, S={}, v={}, V={}, W={}".format(*args)) if W_ == ".pvSysFrame.pvSysDataFrame.numStrSpinbox": errText = 'Invalid number of strings!' elif W_ == ".pvSysFrame.pvSysDataFrame.numModSpinbox": errText = 'Invalid number of modules!' elif W_ == ".pvSysFrame.pvSysDataFrame.sunSpinbox": errText = 'Invalid irradiance!' else: errText = 'Unknown widget!' w = self.nametowidget(W_) w.config(validate=v) self.msgtext.set(errText) self.bell() def getIV(self, *args): logging.debug('args:\n\t%r', args) x = np.float64(float(args[0]) / self.pvSys.pvconst.npts / 2.) xp = np.concatenate((self.pvSys.pvconst.negpts, self.pvSys.pvconst.pts), axis=0).flatten() Vsys = np.interp(x, xp, self.pvSys.Vsys) Isys = np.interp(x, xp, self.pvSys.Isys) Psys = Vsys * Isys / 1000 self.txtVsys.set("{:7.3f}".format(Vsys)) self.txtIsys.set("{:7.3f}".format(Isys)) self.txtPsys.set("{:7.3f}".format(Psys)) def startPVstring_tk(self): top = Toplevel() app = PVstring_tk(self, top) app.mainloop() # please destroy me or I'll continue to run in background top.destroy() def startAdvCnf_tk(self): """ open advnaced config window """ top = Toplevel(name='advCnfTop') app = AdvCnf_tk(self, top) app.mainloop() # please destroy me or I'll continue to run in background top.destroy() def keyBinding(self, event): logging.debug('event widget:\n\t%r', event.widget) logging.debug('event widget get:\n\t%r', event.widget.get()) self.updatePVsys() def updatePVsys(self, *args, **kwargs): logging.debug('args:\n\t%r', args) logging.debug('kwargs:\n\t%r', kwargs) if args and isinstance(args[0], PVsystem_cls): pvsys = args[0] for n, pvstr in enumerate(pvsys.pvstrs): for pvmod in pvstr.pvmods: pvmod.calcMod() pvstr.calcString() logging.debug('updating pvstring #%d: Pmp = %g[W]', n, pvstr.Pstring.max()) return PVAPP = "pvapplication" try: numStrs = self.numStrs.get() if not (0 < numStrs <= self.validationConstants[PVAPP]["numStrs"]): raise PVValidationError('numStrs', numStrs) numMods = self.numMods.get() if not (0 < numMods <= self.validationConstants[PVAPP]["numMods"]): raise PVValidationError('numMods', numMods) sysEe = self.sysEe.get() if not (0 < sysEe <= self.validationConstants[PVAPP]["sysEe"]): raise PVValidationError('sysEe', sysEe) except PVValidationError as err: logging.debug('err:\n\t%r', err) errtext = self.messagetext[PVAPP][err.argname] self.msgtext.set(errtext) self.bell() return numCells = self.numCells.get() self.msgtext.set(self.messagetext[PVAPP]["Ready"]) pvconst = self.pvSys.pvconst pvcell = PVcell(Ee=sysEe) if numCells == 24: numCells = STD24 elif numCells == 72: numCells = STD72 elif numCells == 96: numCells = STD96 elif numCells == 128: numCells = STD128 pvmods = PVmodule(cell_pos=numCells, pvcells=pvcell) self.pvSys = PVsystem(pvconst, numStrs, numberMods=numMods, pvmods=pvmods) self.updateIVstats() def updateIVstats(self): # reuse sysPlot figure and update pvSysFigCanvas self.pvSysPlot = self.pvSys.plotSys(self.pvSysPlot) self.pvSysFigCanvas.show() self.txtImp.set("{:7.3f}".format(self.pvSys.Imp)) # [A] self.txtVmp.set("{:7.3f}".format(self.pvSys.Vmp)) # [V] self.txtPmp.set("{:7.3f}".format(self.pvSys.Pmp / 1000)) # [kW] self.txtIsc.set("{:7.3f}".format(self.pvSys.Isc)) # [A] self.txtVoc.set("{:7.3f}".format(self.pvSys.Voc)) # [V] self.txtFF.set("{:7.3f}".format(self.pvSys.FF * 100)) # [%] self.txtEff.set("{:7.3f}".format(self.pvSys.eff * 100)) # [%] def _help(self): logging.debug('show docs in browser') webbrowser.open(DOCS) def _update(self): self.msgtext.set(READY_MSG) self.updatePVsys() def _reset(self): # number of strings integer variable self.numStrs.set(NUMBERSTRS) # default # number of modules integer variable self.numMods.set(NUMBERMODS) # default # number of cells integer variable self.numCells.set(NUMBERCELLS) # default value is 96 self.msgtext.set(READY_MSG) # TODO: need to reset advCnf too logging.debug('reset') def _load(self): logging.debug('load *.pv file') def _save(self): logging.debug('save *.pv file') def _quit(self): # this is necessary on Windows to prevent # Fatal Python Error: PyEval_RestoreThread: NULL tstate self.master.quit() # stops mainloop self.master.destroy() def readJSON(self, JSONfilename): if not JSONfilename.endswith('json'): JSONfilename += '.json' JSONfullpath = os.path.join(JSONDIR, JSONfilename) with open(JSONfullpath, 'r') as JSONfile: JSONObjects = json.load(JSONfile) logging.debug('JSON objects loaded from %s.', JSONfullpath) return JSONObjects
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 __init__(self): global CURRENTCONFIG global MAXCONFIG global CF_MODE self.confighandler = ConfigHandler() self.confighandler.backupConf() tmpconfig= configparser.ConfigParser() self.confighandler.backupConfTo(tmpconfig) top = tk.Toplevel() top.title("Set configuration") nb = ttk.Notebook(top) b_config_ok = tk.Button(top, text="OK", command=top.destroy) b_config_ok.bind('<ButtonRelease-1>',self.onSetConfigOK) b_config_apply = tk.Button(top, text="Apply", command=self.onSetConfigApply) b_config_cancel = tk.Button(top, text="Cancel", command=top.destroy) b_config_cancel.bind('<ButtonRelease-1>',self.onSetConfigCancel()) fr_paths = tk.Frame(nb,width=200, height=100) fr_penalties = tk.Frame(nb,width=200, height=100) fr_mode = ttk.Frame(nb,width=200, height=100) fr_cleanup = ttk.Frame(nb,width=200, height=100) fr_run = ttk.Frame(nb,width=200, height=100) fr_algorithm = ttk.Frame(nb,width=200, height=100) fr_fastaheader = ttk.Frame(nb,width=200, height=100) #######labels######################## self.txt_sec=[] self.txt_subsec={} for section in MAXCONFIG.sections(): #print( "["+section +"]\n") self.txt_sec.append(section) for opt in MAXCONFIG.options(section): try: self.txt_subsec[section].append(opt) except KeyError as e: self.txt_subsec[section]=[opt] lab_sec=[] lab_subsec={} dd_subsec={} self.var_subsec={} for t in self.txt_sec: lab_sec.append(tk.Label(fr_paths,text = t)) for t in self.txt_subsec: #print(t,self.txt_subsec[t]) for u in self.txt_subsec[t]: if t == CF_MODE: fr = fr_mode elif t == CF_PATHS: fr = fr_paths elif t == CF_CLEANUP: fr = fr_cleanup elif t == CF_RUN: fr = fr_run elif t == CF_PENALTIES: fr = fr_penalties elif t == CF_ALGORITHM: fr = fr_algorithm elif t == CF_FASTAHEADER: fr = fr_fastaheader #print("fastaheader_fr") ################################ else: sys.stderr.write("No such section:",t) try: lab_subsec[t].append(tk.Label(fr,text = u)) self.var_subsec[t].append(tk.StringVar(fr)) if u in OPTIONS: dd_subsec[t].append(OptionMenu(fr,self.var_subsec[t][-1],*OPTIONS[u])) else: dd_subsec[t].append("") except KeyError as e: try: lab_subsec[t]=[tk.Label(fr,text = u)] self.var_subsec[t]=[tk.StringVar(fr)] if u in OPTIONS: dd_subsec[t] = [OptionMenu(fr,self.var_subsec[t][-1],*OPTIONS[u])] else: dd_subsec[t] = [""] except KeyError as e: sys.stderr.write(str(e)) dd_subsec[t].append("") for t in lab_subsec: r=0 c=0 for i in lab_subsec[t]: #print(i.cget("text")) i.grid(row=r,column=c, sticky=tk.E) r+=1 #print(r,i.cget("text")) for t in dd_subsec: c=1 r=0 for i in dd_subsec[t]: #print(i) if i is not "": i.grid(row=r,column=c,sticky=tk.N) r+=1 #print(r) ###################################### self.st_submat = tk.StringVar() self.st_fasta_header_delimiter = tk.StringVar() self.st_fasta_header_part = tk.StringVar() #cpu_count starts at 0 for one cpu self.sc_config_numthreads = Scale(fr_run, from_=1, to=multiprocessing.cpu_count(), orient=tk.HORIZONTAL) self.sc_config_numthreads.grid(row=0, column=1, sticky=tk.E) en_config_gapopen=tk.Entry(fr_penalties, textvariable=self.var_subsec[CF_PENALTIES][0]) en_config_gapextend=tk.Entry(fr_penalties,textvariable=self.var_subsec[CF_PENALTIES][1] ) self.en_config_fasta_header_delimiter= tk.Entry(fr_fastaheader,textvariable=self.st_fasta_header_delimiter,width=6 ) self.en_config_fasta_header_part= tk.Entry(fr_fastaheader,textvariable=self.st_fasta_header_part ,width=6 ) self.om_config_submat=tk.OptionMenu(fr_penalties, self.st_submat, *["EBLOSUM62","EDNAFULL"]) self.om_config_submat.grid(row=2,column=1 ) en_config_gapopen.grid(row=0, column=1) en_config_gapextend.grid(row=1, column=1) self.en_config_fasta_header_delimiter.grid(row=0, column=1) self.en_config_fasta_header_part.grid(row=1,column=1) nb.add(fr_penalties, text=CF_PENALTIES) nb.add(fr_cleanup, text=CF_CLEANUP) nb.add(fr_run, text=CF_RUN) nb.add(fr_algorithm, text=CF_ALGORITHM) nb.add(fr_fastaheader, text=CF_FASTAHEADER) nb.grid() b_config_cancel.grid(row=1, column=0, sticky=tk.E,padx=115) b_config_apply.grid(row=1, column=0, sticky=tk.E,padx=50) b_config_ok.grid(row=1, column=0, sticky=tk.E) self.setFieldsFromConfig()
class ScytheConfigEditor: def __init__(self): global CURRENTCONFIG global MAXCONFIG global CF_MODE backupConf() print("BACKED UP") tmpconfig = configparser.ConfigParser() backupConfTo(tmpconfig) top = tk.Toplevel() top.title("Set configuration") nb = ttk.Notebook(top) b_config_ok = tk.Button(top, text="OK", command=top.destroy) b_config_ok.bind("<ButtonRelease-1>", self.onSetConfigOK) b_config_apply = tk.Button(top, text="Apply", command=self.onSetConfigApply) b_config_cancel = tk.Button(top, text="Cancel", command=top.destroy) b_config_cancel.bind("<ButtonRelease-1>", self.onSetConfigCancel()) fr_paths = tk.Frame(nb, width=200, height=100) fr_penalties = tk.Frame(nb, width=200, height=100) fr_mode = ttk.Frame(nb, width=200, height=100) # fr_output = ttk.Frame(nb,width=200, height=100) fr_cleanup = ttk.Frame(nb, width=200, height=100) fr_run = ttk.Frame(nb, width=200, height=100) fr_algorithm = ttk.Frame(nb, width=200, height=100) fr_paralogs = ttk.Frame(nb, width=200, height=100) fr_fastaheader = ttk.Frame(nb, width=200, height=100) #######labels######################## self.txt_sec = [] self.txt_subsec = {} for section in MAXCONFIG.sections(): print("[" + section + "]\n") self.txt_sec.append(section) for opt in MAXCONFIG.options(section): try: self.txt_subsec[section].append(opt) except KeyError as e: self.txt_subsec[section] = [opt] lab_sec = [] lab_subsec = {} dd_subsec = {} self.var_subsec = {} for t in self.txt_sec: lab_sec.append(tk.Label(fr_paths, text=t)) for t in self.txt_subsec: print(t, self.txt_subsec[t]) for u in self.txt_subsec[t]: if t == CF_MODE: fr = fr_mode elif t == CF_PATHS: fr = fr_paths elif t == CF_CLEANUP: fr = fr_cleanup elif t == CF_RUN: fr = fr_run elif t == CF_PENALTIES: fr = fr_penalties elif t == CF_ALGORITHM: fr = fr_algorithm elif t == CF_PARALOGS: fr = fr_paralogs ############TODO################ elif t == CF_FASTAHEADER: fr = fr_fastaheader print("fastaheader_fr") ################################ else: print("No such section:", t) try: lab_subsec[t].append(tk.Label(fr, text=u)) self.var_subsec[t].append(tk.StringVar(fr)) if u in OPTIONS: dd_subsec[t].append(OptionMenu(fr, self.var_subsec[t][-1], *OPTIONS[u])) else: dd_subsec[t].append("") except KeyError as e: try: lab_subsec[t] = [tk.Label(fr, text=u)] self.var_subsec[t] = [tk.StringVar(fr)] if u in OPTIONS: dd_subsec[t] = [OptionMenu(fr, self.var_subsec[t][-1], *OPTIONS[u])] else: dd_subsec[t] = [""] except KeyError as e: print(e) dd_subsec[t].append("") for t in lab_subsec: r = 0 c = 0 for i in lab_subsec[t]: print(i.cget("text")) i.grid(row=r, column=c, sticky=tk.E) r += 1 print(r, i.cget("text")) for t in dd_subsec: c = 1 r = 0 for i in dd_subsec[t]: print(i) if i is not "": i.grid(row=r, column=c, sticky=tk.N) r += 1 print(r) ###################################### self.st_submat = tk.StringVar() # self.st_outpref = tk.StringVar() # self.st_spliteach = tk.StringVar() self.st_fasta_header_delimiter = tk.StringVar() self.st_fasta_header_part = tk.StringVar() self.sc_config_numthreads = Scale(fr_run, from_=1, to=multiprocessing.cpu_count(), orient=tk.HORIZONTAL) self.sc_config_numthreads.grid(row=0, column=1, sticky=tk.E) en_config_gapopen = tk.Entry(fr_penalties, textvariable=self.var_subsec[CF_PENALTIES][0]) en_config_gapextend = tk.Entry(fr_penalties, textvariable=self.var_subsec[CF_PENALTIES][1]) # self.en_config_spliteach=tk.Entry(fr_run,textvariable=self.st_spliteach,width=6 ) self.en_config_fasta_header_delimiter = tk.Entry( fr_fastaheader, textvariable=self.st_fasta_header_delimiter, width=6 ) self.en_config_fasta_header_part = tk.Entry(fr_fastaheader, textvariable=self.st_fasta_header_part, width=6) self.om_config_submat = tk.OptionMenu(fr_penalties, self.st_submat, *["EBLOSUM62", "EDNAFULL"]) self.om_config_submat.grid(row=2, column=1) # self.en_config_outpref=tk.Entry(fr_output, width=6, textvariable=self.st_outpref) en_config_gapopen.grid(row=0, column=1) en_config_gapextend.grid(row=1, column=1) # en_config_submat.grid(row=2, column=1) # self.en_config_outpref.grid(row=1, column=1) # self.en_config_spliteach.grid(row=2,column=1) self.en_config_fasta_header_delimiter.grid(row=0, column=1) self.en_config_fasta_header_part.grid(row=1, column=1) # nb.add(fr_mode, text=CF_MODE) # nb.add(fr_paths, text=CF_PATHS) nb.add(fr_penalties, text=CF_PENALTIES) # nb.add(fr_output, text=CF_OUTPUT) nb.add(fr_cleanup, text=CF_CLEANUP) nb.add(fr_run, text=CF_RUN) nb.add(fr_algorithm, text=CF_ALGORITHM) # nb.add(fr_paralogs, text=CF_PARALOGS) ###################TODO################# nb.add(fr_fastaheader, text=CF_FASTAHEADER) nb.grid() b_config_cancel.grid(row=1, column=0, sticky=tk.E, padx=115) b_config_apply.grid(row=1, column=0, sticky=tk.E, padx=50) b_config_ok.grid(row=1, column=0, sticky=tk.E) self.setFieldsFromConfig() def onSetConfigApply(self): print("configapply") self.setConfigFromFields() # Infobox().todo() def onSetConfigOK(self, event): print("configapply") self.setConfigFromFields() def onSetConfigCancel(self): restoreConf() print("RESTORED-->CURRENTCONF set") # self.restoreOldConfig() print("Config CANCEL") def setConfigFromFields(self): tempconf = configparser.ConfigParser() backupConfTo(tempconf) # get all values from fields # penalties tempconf.set(CF_PENALTIES, CF_PENALTIES_gap_open_cost, self.var_subsec[CF_PENALTIES][0].get()) tempconf.set(CF_PENALTIES, CF_PENALTIES_gap_extend_cost, self.var_subsec[CF_PENALTIES][1].get()) tempconf.set(CF_PENALTIES, CF_PENALTIES_substitution_matrix, self.st_submat.get()) tempconf.set(CF_ALGORITHM, CF_ALGORITHM_use_global_max, self.var_subsec[CF_ALGORITHM][0].get()) tempconf.set(CF_ALGORITHM, CF_ALGORITHM_use_default, self.var_subsec[CF_ALGORITHM][1].get()) tempconf.set(CF_ALGORITHM, CF_ALGORITHM_use_global_sum, self.var_subsec[CF_ALGORITHM][2].get()) tempconf.set(CF_RUN, CF_RUN_max_threads, str(self.sc_config_numthreads.get())) tempconf.set(CF_RUN, CF_RUN_split_input, self.var_subsec[CF_RUN][1].get()) # CLEANUP tempconf.set(CF_CLEANUP, CF_CLEANUP_clean_up_directories, self.var_subsec[CF_CLEANUP][0].get()) # Fasta header tempconf.set(CF_FASTAHEADER, CF_FASTAHEADER_delimiter, self.var_subsec[CF_FASTAHEADER][0].get()) print("blabla", self.var_subsec[CF_FASTAHEADER][0].get()) tempconf.set(CF_FASTAHEADER, CF_FASTAHEADER_part, self.var_subsec[CF_FASTAHEADER][1].get()) print("III", self.var_subsec[CF_FASTAHEADER][0].get()) tempconf.set(CF_FASTAHEADER, CF_FASTAHEADER_part, self.st_fasta_header_part.get()) tempconf.set(CF_FASTAHEADER, CF_FASTAHEADER_delimiter, self.st_fasta_header_delimiter.get()) # output # outputprefix: # tempconf.set(CF_OUTPUT,CF_OUTPUT_output_prefix,self.en_config_outpref.get()) ########## TODO 02.12.13 ############ # print (self.en_config_outpref.get()) # self.var_subsec[CF_PENALTIES][0].set(CURRENTCONFIG.get(CF_PENALTIES,self.txt_subsec[CF_PENALTIES][0])) # print(CURRENTCONFIG.get(CF_PENALTIES,self.txt_subsec[CF_PENALTIES][1])) setCurrentConf(tempconf) print(CURRENTCONFIG) for t in tempconf.options(CF_PENALTIES): print(t) print(tempconf.get(CF_PENALTIES, t)) for t in tempconf.options(CF_ALGORITHM): print(t) print(tempconf.get(CF_ALGORITHM, t)) def setFieldsFromConfig(self): # penalties print(self.txt_subsec[CF_PENALTIES][0]) print(CURRENTCONFIG.get(CF_PENALTIES, self.txt_subsec[CF_PENALTIES][0])) self.var_subsec[CF_PENALTIES][0].set(CURRENTCONFIG.get(CF_PENALTIES, self.txt_subsec[CF_PENALTIES][0])) print(CURRENTCONFIG.get(CF_PENALTIES, self.txt_subsec[CF_PENALTIES][1])) self.var_subsec[CF_PENALTIES][1].set(CURRENTCONFIG.get(CF_PENALTIES, self.txt_subsec[CF_PENALTIES][1])) self.st_submat.set(CURRENTCONFIG.get(CF_PENALTIES, CF_PENALTIES_substitution_matrix)) # output # cleanup self.var_subsec[CF_CLEANUP][0].set(CURRENTCONFIG.get(CF_CLEANUP, self.txt_subsec[CF_CLEANUP][0])) # run # slider self.var_subsec[CF_RUN][1].set(CURRENTCONFIG.get(CF_RUN, self.txt_subsec[CF_RUN][1])) # algo self.var_subsec[CF_ALGORITHM][0].set(CURRENTCONFIG.get(CF_ALGORITHM, self.txt_subsec[CF_ALGORITHM][0])) self.var_subsec[CF_ALGORITHM][1].set(CURRENTCONFIG.get(CF_ALGORITHM, self.txt_subsec[CF_ALGORITHM][1])) self.var_subsec[CF_ALGORITHM][2].set(CURRENTCONFIG.get(CF_ALGORITHM, self.txt_subsec[CF_ALGORITHM][2])) # paralogs self.var_subsec[CF_PARALOGS][0].set(CURRENTCONFIG.get(CF_PARALOGS, self.txt_subsec[CF_PARALOGS][0])) #########TODO 02.12.13 ??? self.var_subsec[CF_FASTAHEADER][0].set(CURRENTCONFIG.get(CF_FASTAHEADER, self.txt_subsec[CF_FASTAHEADER][0])) # self.var_subsec[CF_FASTAHEADER][1].set(CURRENTCONFIG.get(CF_FASTAHEADER,self.st_fasta_header_part)) print(self.txt_subsec[CF_FASTAHEADER][0]) print(CURRENTCONFIG.get(CF_FASTAHEADER, self.txt_subsec[CF_FASTAHEADER][0])) self.var_subsec[CF_FASTAHEADER][0].set(CURRENTCONFIG.get(CF_FASTAHEADER, self.txt_subsec[CF_FASTAHEADER][0])) print(CURRENTCONFIG.get(CF_FASTAHEADER, self.txt_subsec[CF_FASTAHEADER][1])) self.var_subsec[CF_FASTAHEADER][1].set(CURRENTCONFIG.get(CF_FASTAHEADER, self.txt_subsec[CF_FASTAHEADER][1])) self.st_fasta_header_part.set(CURRENTCONFIG.get(CF_FASTAHEADER, CF_FASTAHEADER_part)) self.st_fasta_header_delimiter.set(CURRENTCONFIG.get(CF_FASTAHEADER, CF_FASTAHEADER_delimiter))
class Visual(Frame): '''Class that takes a world as argument and present it graphically on a tkinter canvas.''' def __init__(self): ''' Sets up a simulation GUI in tkinter. ''' Frame.__init__(self) self.master.title("The Schelling Segregation Model in Python") self.master.wm_resizable(0, 0) self.grid() self.movement_possible = True # --------------------------------------- # # --------- FRAMES FOR GUI -------------- # # --------------------------------------- # # The pane for user values self._entryPane = Frame(self, borderwidth=5, relief='sunken') self._entryPane.grid(row=0, column=0, sticky='n') # The buttons pane self._buttonPane = Frame(self, borderwidth=5) self._buttonPane.grid(row=1, column=0, sticky='n') # A temp pane where graph is located, just for cosmetic reasons width, height = 425, 350 self._graph = Canvas(self, width=width, height=height, background="black") self._graph.configure(relief='sunken', border=2) self._graph.grid(row=3, column=0) # The pane where the canvas is located self._animationPane = Frame(self, borderwidth=5, relief='sunken') self._animationPane.grid(row=0, column=1, rowspan=4, pady=10, sticky="n") # --------------------------------------- # # --------- FILLING THE FRAMES ---------- # # --------------------------------------- # self._canvas() # Create graphics canvas self._entry() # Create entry widgets self._buttons() # Create button widgets def _plot_setup(self, time): '''Method for crudely annotating the graph window.''' time = time # Main plot width, height = 425, 350 y0 = -time/10 self._graph = Canvas(self, width=width, height=height, background="black", borderwidth=5) self._graph.grid(row=3, column=0) self.trans = Plotcoords(width, height, y0, -0.2, time, 1.3) x, y = self.trans.screen(time // 2, 1.2) x1, y1 = self.trans.screen(time // 2, 1.13) self._graph.create_text(x, y, text="% Happy", fill="green", font="bold 12") self._graph.create_text(x1, y1, text="% Unhappy", fill="red", font="bold 12") # Line x-axis x, y = self.trans.screen((-5 * (time / 100)), -0.05) x1, y = self.trans.screen(time, -0.05) self._graph.create_line(x, y, x1, y, fill="white", width=1.5) # Text x-axis x_text, y_text = self.trans.screen(time / 2, -0.15) self._graph.create_text(x_text, y_text, text="Time", fill="white", font="bold 12") # Line y-axis x, y = self.trans.screen((-0.5 * (time / 100)), -0.05) x, y1 = self.trans.screen((-5 * (time / 100)), 1) self._graph.create_line(x, y, x, y1, fill="white", width=1.5) def _entry(self): '''Method for creating widgets for collecting user input.''' # N (no of turtles) dim = 30*30 self.fill_label = Label(self._entryPane, anchor='w', justify='left', text='Fill', relief='raised', width=12, height=1, font='italic 20') self.fill_label.grid(row=0, column=1, ipady=14) self.fill = Scale(self._entryPane, from_=0, to=1, resolution=0.01, bd=3, relief='sunken', orient='horizontal', length=235, tickinterval=20) self.fill.grid(row=0, column=2) self.fill.set(0.8) self._N_label = Label(self._entryPane, anchor='w', justify='left', text="N:", relief='raised', width=12, height=1, font="italic 20") self._N_label.grid(row=1, column=1, ipady=14) self._N = Scale(self._entryPane, from_=0, to=100, resolution=1, bd=3, relief='sunken', orient='horizontal', length=235, tickinterval=20) self._N.set(30) self._N.grid(row=1, column=2) # Ticks (length of simulation) self._Ticks_label = Label(self._entryPane, anchor='w', justify='left', text="Time:", relief='raised', width=12, height=1, font="bold 20") self._Ticks_label.grid(row=2, column=1, ipady=14) self._Ticks = Scale(self._entryPane, from_=10, to=1000, resolution=1, bd=3, relief='sunken', orient='horizontal', length=235, tickinterval=990) self._Ticks.set(500) self._Ticks.grid(row=2, column=2) # % similar wanted self._Similar_label = Label(self._entryPane, anchor='w', justify='left', text="Similar wanted:", relief='raised', width=12, height=1, font="bold 20") self._Similar_label.grid(row=3, column=1, ipady=14) self._Similar = Scale(self._entryPane, from_=0.0, to=1.0, resolution=0.01, bd=3, relief='sunken', orient='horizontal', length=235, tickinterval=0.5) self._Similar.set(0.76) self._Similar.grid(row=3, column=2) # Delay between steps self._delay_label = Label(self._entryPane, anchor='w', justify='left', text="Delay (s):", relief='raised', width=12, height=1, font="bold 20") self._delay_label.grid(row=4, column=1, ipady=14) self._delay = Scale(self._entryPane, from_=0.0, to=1.0, resolution=0.01, bd=3, relief='sunken', orient='horizontal', length=235, tickinterval=0.5) self._delay.set(0.15) self._delay.grid(row=4, column=2) def _buttons(self): '''Method for creating button widgets for setting up, running and plotting results from simulation.''' width = 7 height = 1 # The 'Setup' button self._setupButton = Button(self._buttonPane, text="Setup", command=self._setup, width=width, height=height, font="bold 30", relief='raised', borderwidth=5) self._setupButton.grid(row=0, column=0) # The 'Go' button self._goButton = Button(self._buttonPane, text="Go", command=self._go, width=width, height=height, font="bold 30", relief='raised', borderwidth=5) self._goButton.grid(row=0, column=1) # The 'Quit' button self._quitButton = Button(self._buttonPane, text="Quit", command=self._quit, width=width, height=height, font="bold 30", relief='raised', borderwidth=5) self._quitButton.grid(row=1, column=0, columnspan=2) def _canvas(self): '''Creates the canvas on which everything happens.''' # The tick counter information self._Tick_counter = Label(self._animationPane, anchor='w', justify='left', text="Time:", width=5, font="bold 20") self._Tick_counter.grid(row=0, column=0, sticky="e") self._Tick_counter1 = Label(self._animationPane, justify='center', text="", relief='raised', width=5, font="bold 20") self._Tick_counter1.grid(row=0, column=1, sticky='w') self.canvas_w, self.canvas_h = 750, 750 self.canvas = Canvas(self._animationPane, width=self.canvas_w, height=self.canvas_h, background="black") self.canvas.grid(row=1, column=0, columnspan=2) def _setup(self): '''Method for 'Setup' button.''' # Clearing the canvas and reset the go button self.canvas.delete('all') self._goButton['relief'] = 'raised' self.N = int(self._N.get()) self.Ticks = int(self._Ticks.get()) self.similar = float(self._Similar.get()) self.data = [] self.tick_counter = 0 self._Tick_counter1['text'] = str(self.tick_counter) self._plot_setup(self.Ticks) self.grid_size = self.N self.world = World(750, 750, self.grid_size) self.create_turtles() self.neighbouring_turtles() self.draw_turtles() def _go(self): '''Method for the 'Go' button, i.e. running the simulation.''' self._goButton['relief'] = 'sunken' if self.tick_counter <= self.Ticks: self._Tick_counter1['text'] = str(self.tick_counter) self.canvas.update() self._graph.update() self._graph.after(0) # Data collection turtles_unhappy = self.check_satisfaction() prop_happy, prop_unhappy = self.calc_prop_happy(self.tick_counter) self.data_collection(self.tick_counter, prop_happy, prop_unhappy) if self.tick_counter >= 1: # HAPPY values (%) x0 = self.tick_counter-1 x1 = self.tick_counter # Collecting values from stored data y0 = self.data[self.tick_counter-1][1] y1 = self.data[self.tick_counter][1] # Transforming to tkinter x1, y1 = self.trans.screen(x1, y1) x0, y0 = self.trans.screen(x0, y0) self._graph.create_line(x0, y0, x1, y1, fill="green", width=1.3, tag="happy") # Draw "happy lines # UNHAPPY values (%) x0 = self.tick_counter-1 x1 = self.tick_counter # Collecting values from stored data y0 = self.data[self.tick_counter-1][2] y1 = self.data[self.tick_counter][2] # Transforming to tkinter x1, y1 = self.trans.screen(x1, y1) x0, y0 = self.trans.screen(x0, y0) self._graph.create_line(x0, y0, x1, y1, fill="red", width=1.1, tag="unhappy") # Draw unhappy lines if prop_happy < 1: self.turtle_move(turtles_unhappy) time.sleep(self._delay.get()) self.update_neighbours() self.tick_counter += 1 self.canvas.after(0, self._go()) self._goButton['relief'] = 'raised' def _quit(self): '''Method for the 'Quit' button.''' self.master.destroy() # ------------------------------------------------------ # # ---------- FUNCTIONS CALLED AT EACH TICK ------------- # # ------------------------------------------------------ # def turtle_move(self, unhappy_turtles): '''Moves all the unhappy turtles (randomly).''' while unhappy_turtles: i = random.randint(0, len(unhappy_turtles)-1) turtle = unhappy_turtles.pop(i) turtle.move(self) def update_neighbours(self): '''Updates the turtles neigbour attributes. Called after all turtles have moved.''' for turtle in self.turtles: turtle.update_neighbours() def check_satisfaction(self): '''Checks to see if turtles are happy or not. Returns a list of unhappy turtles, i.e. turtles that should move. Called before the move method.''' for turtle in self.turtles: turtle.is_happy() unhappy_turtles = [] for element in self.turtles: if not element.happy: unhappy_turtles.append(element) return unhappy_turtles def calc_prop_happy(self, i): '''Calculates the proportion of happy turtles.''' happy = 0 unhappy = 0 for turtle in self.turtles: if turtle.happy: happy += 1 else: unhappy += 1 prop_happy = happy/len(self.turtles) prop_unhappy = unhappy/len(self.turtles) return prop_happy, prop_unhappy def data_collection(self, i, prop_happy, prop_unhappy): '''Method for collecting data at each tick.''' self.data.append((i, prop_happy, prop_unhappy)) # ------------------------------------------------------ # # ---------- INITIALISATION FUNCTIONS ------------------ # # ------------------------------------------------------ # def create_turtles(self): '''Method for creating a new list of turtles. Upon creation they are registered in the World object.''' if self.N*self.N <= self.grid_size*self.grid_size: counter = 0 self.turtles = [] while counter < self.N * self.N * self.fill.get(): s = "S"+str(counter) if counter <= int(self.N * self.N * self.fill.get() / 2): color = "green" else: color = "red" x = random.randint(0, self.grid_size-1) y = random.randint(0, self.grid_size-1) if not self.world.patch_list[x][y]: new_turtle = Schelling(world=self.world, x=x, y=y, s=s, color=color, similar_wanted=self.similar) self.world.register(new_turtle) counter += 1 self.turtles.append(new_turtle) else: print("Number of turtles exceeds world!") def draw_turtles(self): '''Method for drawing turtles on canvas. Calls each turtle's own method for drawing.''' for turtle in self.turtles: turtle.draw(self.canvas) def neighbouring_turtles(self): '''Method for updating turtles' neighbours. Calls on each turtle's own method for updating neighbours.''' for turtle in self.turtles: turtle.get_neighbouring_patches()
class Fenetre(Tk): def __init__(self): Tk.__init__(self) self.tilt_val_init = 110 self.pan_val_init = 75 self.pan_min = 0 self.pan_max = 105 self.tilt_min = 35 self.tilt_max = 135 self.pas = 5 # Full Screen largeur, hauteur = self.winfo_screenwidth(), self.winfo_screenheight() self.overrideredirect(0) self.geometry("%dx%d" % (largeur, hauteur)) # TILT self.tilt_bar = Scale(self, from_=self.tilt_min, to=self.tilt_max, length=250, label='Tilt', sliderlength=20, orient=HORIZONTAL, command=self.update_tilt) self.tilt_bar.set((self.tilt_max + self.tilt_min) // 2) self.tilt_bar.grid(row=1, column=2) self.tilt_angle = StringVar() self.tilt_val = self.tilt_bar.get() # PAN self.pan_bar = Scale(self, from_=self.pan_min, to=self.pan_max, length=250, label='Pan', sliderlength=20, orient=HORIZONTAL, command=self.update_pan) self.pan_bar.set((self.pan_max + self.pan_min) // 2) self.pan_bar.grid(row=2, column=2) self.pan_angle = StringVar() self.pan_val = self.pan_bar.get() # PS3 Controller self.bind("<a>", self.pan_plus) self.bind("<d>", self.pan_moins) self.bind("<s>", self.tilt_plus) self.bind("<w>", self.tilt_moins) self.bind("<p>", self.lean_left) self.bind("<m>", self.lean_right) self.bind("<q>", self.initialiser_positon) self.bind("<j>", self.forward) self.bind("<u>", self.reverse) self.bind("<h>", self.left) self.bind("<k>", self.right) self.bind("<i>", self.break_motor) self.bind("<Button-2>", self.alarm) self.bind("<Button-3>", self.beep) # Motor self.gear = 0 self.speed_init = 5 self.speed = self.speed_init self.leds = [led_1, led_2, led_3] self.bind("<e>", self.shift_down) self.bind("<r>", self.shift_up) self.pwm = gpio.PWM(enable_pin, 50) # 50 is the frequency # Infos self.pas_label = Label(self, text=str(self.pas)) self.pas_label.grid(row=3) self.buzzer_state = 0 #--------Buzzer-------- def beep(self, event, time=100): self.buzzer_on() self.after(time, self.buzzer_off) def buzzer_on(self): gpio.output(buzzer, gpio.HIGH) self.buzzer_state = 1 def buzzer_off(self): gpio.output(buzzer, gpio.LOW) self.buzzer_state = 0 def alarm(self, event): if self.buzzer_state == 0: gpio.output(buzzer, gpio.HIGH) self.buzzer_state = 1 else: gpio.output(buzzer, gpio.LOW) self.buzzer_state = 0 #-------Camera------- #-------Motor------- def shift_up(self, event): if self.gear != 3: self.gear += 1 gpio.output(self.leds[self.gear - 1], gpio.HIGH) else: self.beep(event, time=70) if self.gear == 0: self.speed = self.speed_init elif self.gear == 1: self.speed = 33 elif self.gear == 2: self.speed = 66 elif self.gear == 3: self.speed = 100 def shift_down(self, event): if self.gear != 0: gpio.output(self.leds[self.gear - 1], gpio.LOW) self.gear -= 1 if self.gear == 0: self.speed = self.speed_init elif self.gear == 1: self.speed = 33 elif self.gear == 2: self.speed = 66 elif self.gear == 3: self.speed = 100 def forward(self, event): self.go("forward") def reverse(self, event): self.go("reverse") def right(self, event): self.go("right") def left(self, event): self.go("left") def lean_left(self, event): self.go('lean left') def lean_right(self, event): self.go('lean right') def break_motor(self, event): self.go("stop") def go(self, direction): gpio_reset_motor() if direction == "forward": print("forward") gpio.output(right_forward, gpio.HIGH) gpio.output(left_forward, gpio.HIGH) elif direction == "reverse": print("reverse") gpio.output(right_reverse, gpio.HIGH) gpio.output(left_reverse, gpio.HIGH) elif direction == "right": print("right") gpio.output(left_reverse, gpio.HIGH) gpio.output(right_forward, gpio.HIGH) elif direction == "left": print("left") gpio.output(right_reverse, gpio.HIGH) gpio.output(left_forward, gpio.HIGH) elif direction == 'lean left': gpio.output(left_reverse, gpio.HIGH) elif direction == 'lean right': gpio.output(right_reverse, gpio.HIGH) elif direction == 'stop': self.pwm.stop() self.pwm = gpio.PWM(enable_pin, 50) # 50 is the frequency else: pass self.pwm.start(self.speed) # a "speed" of 50, sends power exactly every second cycle #time.sleep(1) #direction = input('Enter next direction') #-------Servos------- def tilt_plus(self, event): if verif_angle(self.tilt_val + self.pas, self.tilt_min, self.tilt_max): self.tilt_val += self.pas self.tilt_bar.set(self.tilt_val) def tilt_moins(self, event): if verif_angle(self.tilt_val - self.pas, self.tilt_min, self.tilt_max): self.tilt_val -= self.pas self.tilt_bar.set(self.tilt_val) def pan_plus(self, event): if verif_angle(self.pan_val + self.pas, self.pan_min, self.pan_max): self.pan_val += self.pas self.pan_bar.set(self.pan_val) def pan_moins(self, event): if verif_angle(self.pan_val - self.pas, self.pan_min, self.pan_max): self.pan_val -= self.pas * 2 self.pan_bar.set(self.pan_val) def pas_plus(self, event): if self.pas + 1 < 21: self.pas += 1 self.update_window() def pas_moins(self, event): if self.pas - 1 > 0: self.pas -= 1 self.update_window() def update_tilt(self, x): if x == 0: pass set_servo(int(x), 0) self.tilt_val = int(x) def update_pan(self, x): if x == 0: pass set_servo(int(x), 1) self.pan_val = int(x) def update_window(self): self.pas_label['text'] = str(self.pas) def initialiser_positon(self, event): self.tilt_bar.set(self.tilt_val_init) self.pan_bar.set(self.pan_val_init)
class GUI: def __init__(self, master): self.master = master master.title("GUI") self.label = Label(master, text="Fluid Cell Control") self.label.pack() self.var1 = IntVar() self.check1 = Checkbutton(master, text="1", variable=self.var1, command=self.update_valve) self.check1.pack() self.var2 = IntVar() self.check2 = Checkbutton(master, text="2", variable=self.var2, command=self.update_valve) self.check2.pack() self.var3 = IntVar() self.check3 = Checkbutton(master, text="3", variable=self.var3, command=self.update_valve) self.check3.pack() self.var4 = IntVar() self.check4 = Checkbutton(master, text="4", variable=self.var4, command=self.update_valve) self.check4.pack() self.var5 = IntVar() self.check5 = Checkbutton(master, text="5", variable=self.var5, command=self.update_valve) self.check5.pack() self.var6 = IntVar() self.check6 = Checkbutton(master, text="6", variable=self.var6, command=self.update_valve) self.check6.pack() self.apply_button = Button(master, text="Apply", command=self.print_valve) self.apply_button.pack() self.speed = StringVar() self.speed_entry = Entry(master, textvariable=self.speed) self.speed_entry.pack() self.speed_scale = Scale(master, from_=0, to=255, variable=self.speed, orient=HORIZONTAL) self.speed_scale.pack() self.apply_speed = Button(master, text="Apply", command=self.print_speed) self.apply_speed.pack() self.close_button = Button(master, text="Close", command=master.quit) self.close_button.pack() def update_valve(self): return (str(self.var1.get()) + str(self.var2.get()) + str(self.var3.get()) + str(self.var4.get()) + str(self.var5.get()) + str(self.var6.get())) def print_valve(self): print(GUI.update_valve(self)) valve_arr(GUI.update_valve(self)) def print_speed(self): print(format(int(self.speed.get()), "08b")) s = format(int(self.speed.get()), "08b") pump_speed(s)
def __init__(self): Tk.__init__(self) self.tilt_val_init = 110 self.pan_val_init = 75 self.pan_min = 0 self.pan_max = 105 self.tilt_min = 35 self.tilt_max = 135 self.pas = 5 # Full Screen largeur, hauteur = self.winfo_screenwidth(), self.winfo_screenheight() self.overrideredirect(0) self.geometry("%dx%d" % (largeur, hauteur)) # TILT self.tilt_bar = Scale(self, from_=self.tilt_min, to=self.tilt_max, length=250, label='Tilt', sliderlength=20, orient=HORIZONTAL, command=self.update_tilt) self.tilt_bar.set((self.tilt_max + self.tilt_min) // 2) self.tilt_bar.grid(row=1, column=2) self.tilt_angle = StringVar() self.tilt_val = self.tilt_bar.get() # PAN self.pan_bar = Scale(self, from_=self.pan_min, to=self.pan_max, length=250, label='Pan', sliderlength=20, orient=HORIZONTAL, command=self.update_pan) self.pan_bar.set((self.pan_max + self.pan_min) // 2) self.pan_bar.grid(row=2, column=2) self.pan_angle = StringVar() self.pan_val = self.pan_bar.get() # PS3 Controller self.bind("<a>", self.pan_plus) self.bind("<d>", self.pan_moins) self.bind("<s>", self.tilt_plus) self.bind("<w>", self.tilt_moins) self.bind("<p>", self.lean_left) self.bind("<m>", self.lean_right) self.bind("<q>", self.initialiser_positon) self.bind("<j>", self.forward) self.bind("<u>", self.reverse) self.bind("<h>", self.left) self.bind("<k>", self.right) self.bind("<i>", self.break_motor) self.bind("<Button-2>", self.alarm) self.bind("<Button-3>", self.beep) # Motor self.gear = 0 self.speed_init = 5 self.speed = self.speed_init self.leds = [led_1, led_2, led_3] self.bind("<e>", self.shift_down) self.bind("<r>", self.shift_up) self.pwm = gpio.PWM(enable_pin, 50) # 50 is the frequency # Infos self.pas_label = Label(self, text=str(self.pas)) self.pas_label.grid(row=3) self.buzzer_state = 0
for slider, bounds in zip(sliders, sliderbounds):randomise_slider(slider, bounds) def set_sliders_to_val_row(sliders, vals_row): for slider, val in zip(sliders, vals_row):slider.set(val) def multiply_bounds_from_mean(bounds, factor): midpoint=mean(bounds) distance=midpoint-bounds[0] return (midpoint-factor*distance, midpoint+factor*distance) root=Tk() component_bounds=[(min(vals[:,i]), max(vals[:,i])) for i in range(num_components)] sliderbounds=[multiply_bounds_from_mean(bounds, slider_factor) for bounds in component_bounds] sliders=[Scale(root, from_=min(bounds), to=max(bounds), length=500) for i,bounds in zip(range(num_components), sliderbounds)] for n,slider in enumerate(sliders): if display_sliders: slider.grid(row=0, column=num_images+n, rowspan=3) default_vals_row=random.choice(vals) set_sliders_to_val_row(sliders, default_vals_row) # Button(root, text="ok", command=display_image_from_sliders).pack() Button(root, text="randomise", command=randomise_sliders).grid(row=2, column=0, columnspan=num_images) frame=Frame(root, width=size[0], height=size[1], background='white') frame.grid(row=0, column=0, columnspan=num_images)
# 第8章.pptx, P155 & 156, program that uses a Scale control from tkinter import Tk, Scale winForm = Tk() scale = Scale(winForm, from_=0, to=100, resolution=1, orient="horizontal") scale.pack() winForm.mainloop()
class TelloUI: """Wrapper class to enable the GUI.""" def __init__(self, tello, outputpath): """ Initial all the element of the GUI,support by Tkinter :param tello: class interacts with the Tello drone. Raises: RuntimeError: If the Tello rejects the attempt to enter command mode. """ self.tello = tello # videostream device self.outputPath = outputpath # the path that save pictures created by clicking the takeSnapshot button self.frame = None # frame read from h264decoder and used for pose recognition self.thread = None # thread of the Tkinter mainloop self.stopEvent = None # control variables self.distance = 0.1 # default distance for 'move' cmd self.degree = 30 # default degree for 'cw' or 'ccw' cmd # if the flag is TRUE,the auto-takeoff thread will stop waiting for the response from tello self.quit_waiting_flag = False # initialize the root window and image panel self.root = tki.Tk() self.panel = None # create buttons self.btn_snapshot = tki.Button(self.root, text="Snapshot!", command=self.takeSnapshot) self.btn_snapshot.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_pause = tki.Button(self.root, text="Pause", relief="raised", command=self.pauseVideo) self.btn_pause.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_landing = tki.Button(self.root, text="Open Command Panel", relief="raised", command=self.openCmdWindow) self.btn_landing.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) # start a thread that constantly pools the video sensor for # the most recently read frame self.stopEvent = threading.Event() self.thread = threading.Thread(target=self.videoLoop, args=()) self.thread.start() # set a callback to handle when the window is closed self.root.wm_title("TELLO Controller") self.root.wm_protocol("WM_DELETE_WINDOW", self.onClose) # the sending_command will send command to tello every 5 seconds self.sending_command_thread = threading.Thread( target=self._sendingCommand) def videoLoop(self): """ The mainloop thread of Tkinter Raises: RuntimeError: To get around a RunTime error that Tkinter throws due to threading. """ try: # start the thread that get GUI image and drwa skeleton time.sleep(0.5) self.sending_command_thread.start() while not self.stopEvent.is_set(): system = platform.system() # read the frame for GUI show self.frame = self.tello.read() if self.frame is None or self.frame.size == 0: continue # transfer the format from frame to image image = Image.fromarray(self.frame) # we found compatibility problem between Tkinter,PIL and Macos,and it will # sometimes result the very long preriod of the "ImageTk.PhotoImage" function, # so for Macos,we start a new thread to execute the _updateGUIImage function. if system == "Windows" or system == "Linux": self._updateGUIImage(image) else: thread_tmp = threading.Thread(target=self._updateGUIImage, args=(image, )) thread_tmp.start() time.sleep(0.03) except RuntimeError as e: print("[INFO] caught a RuntimeError") def _updateGUIImage(self, image): """ Main operation to initial the object of image,and update the GUI panel """ image = ImageTk.PhotoImage(image) # if the panel none ,we need to initial it if self.panel is None: self.panel = tki.Label(image=image) self.panel.image = image self.panel.pack(side="left", padx=10, pady=10) # otherwise, simply update the panel else: self.panel.configure(image=image) self.panel.image = image def _sendingCommand(self): """ start a while loop that sends 'command' to tello every 5 second """ while True: self.tello.send_command('command') time.sleep(5) def _setQuitWaitingFlag(self): """ set the variable as TRUE,it will stop computer waiting for response from tello """ self.quit_waiting_flag = True def openCmdWindow(self): """ open the cmd window and initial all the button and text """ panel = Toplevel(self.root) panel.wm_title("Command Panel") # create text input entry text0 = tki.Label( panel, text= 'This Controller map keyboard inputs to Tello control commands\n' 'Adjust the trackbar to reset distance and degree parameter', font='Helvetica 10 bold') text0.pack(side='top') text1 = tki.Label( panel, text='W - Move Tello Up\t\t\tArrow Up - Move Tello Forward\n' 'S - Move Tello Down\t\t\tArrow Down - Move Tello Backward\n' 'A - Rotate Tello Counter-Clockwise\tArrow Left - Move Tello Left\n' 'D - Rotate Tello Clockwise\t\tArrow Right - Move Tello Right', justify="left") text1.pack(side="top") self.btn_landing = tki.Button(panel, text="Land", relief="raised", command=self.telloLanding) self.btn_landing.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_takeoff = tki.Button(panel, text="Takeoff", relief="raised", command=self.telloTakeOff) self.btn_takeoff.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) # binding arrow keys to drone control self.tmp_f = tki.Frame(panel, width=100, height=2) self.tmp_f.bind('<KeyPress-w>', self.on_keypress_w) self.tmp_f.bind('<KeyPress-s>', self.on_keypress_s) self.tmp_f.bind('<KeyPress-a>', self.on_keypress_a) self.tmp_f.bind('<KeyPress-d>', self.on_keypress_d) self.tmp_f.bind('<KeyPress-Up>', self.on_keypress_up) self.tmp_f.bind('<KeyPress-Down>', self.on_keypress_down) self.tmp_f.bind('<KeyPress-Left>', self.on_keypress_left) self.tmp_f.bind('<KeyPress-Right>', self.on_keypress_right) self.tmp_f.pack(side="bottom") self.tmp_f.focus_set() self.btn_landing = tki.Button(panel, text="Flip", relief="raised", command=self.openFlipWindow) self.btn_landing.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.distance_bar = Scale(panel, from_=0.02, to=5, tickinterval=0.01, digits=3, label='Distance(m)', resolution=0.01) self.distance_bar.set(0.2) self.distance_bar.pack(side="left") self.btn_distance = tki.Button( panel, text="Reset Distance", relief="raised", command=self.updateDistancebar, ) self.btn_distance.pack(side="left", fill="both", expand="yes", padx=10, pady=5) self.degree_bar = Scale(panel, from_=1, to=360, tickinterval=10, label='Degree') self.degree_bar.set(30) self.degree_bar.pack(side="right") self.btn_distance = tki.Button(panel, text="Reset Degree", relief="raised", command=self.updateDegreebar) self.btn_distance.pack(side="right", fill="both", expand="yes", padx=10, pady=5) def openFlipWindow(self): """ open the flip window and initial all the button and text """ panel = Toplevel(self.root) panel.wm_title("Gesture Recognition") self.btn_flipl = tki.Button(panel, text="Flip Left", relief="raised", command=self.telloFlip_l) self.btn_flipl.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_flipr = tki.Button(panel, text="Flip Right", relief="raised", command=self.telloFlip_r) self.btn_flipr.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_flipf = tki.Button(panel, text="Flip Forward", relief="raised", command=self.telloFlip_f) self.btn_flipf.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_flipb = tki.Button(panel, text="Flip Backward", relief="raised", command=self.telloFlip_b) self.btn_flipb.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) def takeSnapshot(self): """ save the current frame of the video as a jpg file and put it into outputpath """ # grab the current timestamp and use it to construct the filename ts = datetime.datetime.now() filename = "{}.jpg".format(ts.strftime("%Y-%m-%d_%H-%M-%S")) p = os.path.sep.join((self.outputPath, filename)) # save the file cv2.imwrite(p, cv2.cvtColor(self.frame, cv2.COLOR_RGB2BGR)) print("[INFO] saved {}".format(filename)) def pauseVideo(self): """ Toggle the freeze/unfreze of video """ if self.btn_pause.config('relief')[-1] == 'sunken': self.btn_pause.config(relief="raised") self.tello.video_freeze(False) else: self.btn_pause.config(relief="sunken") self.tello.video_freeze(True) def telloTakeOff(self): return self.tello.takeoff() def telloLanding(self): return self.tello.land() def telloFlip_l(self): return self.tello.flip('l') def telloFlip_r(self): return self.tello.flip('r') def telloFlip_f(self): return self.tello.flip('f') def telloFlip_b(self): return self.tello.flip('b') def telloCW(self, degree): return self.tello.rotate_cw(degree) def telloCCW(self, degree): return self.tello.rotate_ccw(degree) def telloMoveForward(self, distance): return self.tello.move_forward(distance) def telloMoveBackward(self, distance): return self.tello.move_backward(distance) def telloMoveLeft(self, distance): return self.tello.move_left(distance) def telloMoveRight(self, distance): return self.tello.move_right(distance) def telloUp(self, dist): return self.tello.move_up(dist) def telloDown(self, dist): return self.tello.move_down(dist) def updateTrackBar(self): self.my_tello_hand.setThr(self.hand_thr_bar.get()) def updateDistancebar(self): self.distance = self.distance_bar.get() print 'reset distance to %.1f' % self.distance def updateDegreebar(self): self.degree = self.degree_bar.get() print 'reset distance to %d' % self.degree def on_keypress_w(self, event): print "up %d m" % self.distance self.telloUp(self.distance) def on_keypress_s(self, event): print "down %d m" % self.distance self.telloDown(self.distance) def on_keypress_a(self, event): print "ccw %d degree" % self.degree self.tello.rotate_ccw(self.degree) def on_keypress_d(self, event): print "cw %d m" % self.degree self.tello.rotate_cw(self.degree) def on_keypress_up(self, event): print "forward %d m" % self.distance self.telloMoveForward(self.distance) def on_keypress_down(self, event): print "backward %d m" % self.distance self.telloMoveBackward(self.distance) def on_keypress_left(self, event): print "left %d m" % self.distance self.telloMoveLeft(self.distance) def on_keypress_right(self, event): print "right %d m" % self.distance self.telloMoveRight(self.distance) def on_keypress_enter(self, event): if self.frame is not None: self.registerFace() self.tmp_f.focus_set() def onClose(self): """ set the stop event, cleanup the camera, and allow the rest of the quit process to continue """ print("[INFO] closing...") self.stopEvent.set() del self.tello self.root.quit()
def dialogFromOptions(parent, opts, groups=None, callback=None, sticky='news', layout='horizontal'): """Auto create tk vars and widgets for corresponding options and and return the enclosing frame""" tkvars = {} widgets = {} dialog = Frame(parent) if groups == None: groups = {'options': opts.keys()} c=0 row=0 for g in groups: if g == 'hidden': continue if layout=='horizontal': row=0; c+=1 side=LEFT fill=Y else: c=0; row+=1 side=TOP fill=X frame = LabelFrame(dialog, text=g) #frame.grid(row=row,column=c,sticky=sticky) frame.pack(side=side,fill=fill,expand=False) for i in groups[g]: w=None opt = opts[i] if opt['type'] == 'entry': if 'label' in opt: label=opt['label'] else: label=i if 'width' in opt: w=opt['width'] else: w=6 Label(frame,text=label).pack() if type(opts[i]['default']) is int: tkvars[i] = v = IntVar() else: tkvars[i] = v = StringVar() v.set(opts[i]['default']) w = Entry(frame,textvariable=v, width=w, command=callback) elif opt['type'] == 'scrolledtext': w = ScrolledText(frame, width=20, wrap=WORD) tkvars[i] = None elif opt['type'] == 'checkbutton': tkvars[i] = v = IntVar() v.set(opts[i]['default']) w = Checkbutton(frame,text=opt['label'], variable=v) elif opt['type'] == 'combobox': if 'label' in opt: label=opt['label'] else: label = i if 'width' in opt: w=opt['width'] else: w=16 Label(frame,text=label).pack() tkvars[i] = v = StringVar() v.set(opts[i]['default']) w = Combobox(frame, values=opt['items'], textvariable=v,width=w, validatecommand=callback,validate='key') w.set(opt['default']) #w.configure(background='white') #w['state'] = 'readonly' if 'tooltip' in opt: ToolTip.createToolTip(w, opt['tooltip']) elif opt['type'] == 'listbox': if 'label' in opt: label=opt['label'] else: label = i Label(frame,text=label).pack() w,v = addListBox(frame, values=opt['items'],width=12) tkvars[i] = v #add widget instead of var elif opt['type'] == 'radio': Label(frame,text=label).pack() if 'label' in opt: label=opt['label'] else: label = i Label(frame,text=label).pack() tkvars[i] = v = StringVar() for item in opt['items']: w = Radiobutton(frame, text=item, variable=v, value=item).pack() elif opt['type'] == 'scale': fr,to=opt['range'] tkvars[i] = v = DoubleVar() v.set(opts[i]['default']) w = Scale(frame,label=opt['label'], from_=fr,to=to, orient='horizontal', resolution=opt['interval'], variable=v) if w != None: w.pack(fill=BOTH,expand=1) widgets[i] = w row+=1 return dialog, tkvars, widgets
def openCmdWindow(self): """ open the cmd window and initial all the button and text """ panel = Toplevel(self.root) panel.wm_title("Command Panel") # create text input entry text0 = tki.Label( panel, text= 'This Controller map keyboard inputs to Tello control commands\n' 'Adjust the trackbar to reset distance and degree parameter', font='Helvetica 10 bold') text0.pack(side='top') text1 = tki.Label( panel, text='W - Move Tello Up\t\t\tArrow Up - Move Tello Forward\n' 'S - Move Tello Down\t\t\tArrow Down - Move Tello Backward\n' 'A - Rotate Tello Counter-Clockwise\tArrow Left - Move Tello Left\n' 'D - Rotate Tello Clockwise\t\tArrow Right - Move Tello Right', justify="left") text1.pack(side="top") self.btn_landing = tki.Button(panel, text="Land", relief="raised", command=self.telloLanding) self.btn_landing.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_takeoff = tki.Button(panel, text="Takeoff", relief="raised", command=self.telloTakeOff) self.btn_takeoff.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) # binding arrow keys to drone control self.tmp_f = tki.Frame(panel, width=100, height=2) self.tmp_f.bind('<KeyPress-w>', self.on_keypress_w) self.tmp_f.bind('<KeyPress-s>', self.on_keypress_s) self.tmp_f.bind('<KeyPress-a>', self.on_keypress_a) self.tmp_f.bind('<KeyPress-d>', self.on_keypress_d) self.tmp_f.bind('<KeyPress-Up>', self.on_keypress_up) self.tmp_f.bind('<KeyPress-Down>', self.on_keypress_down) self.tmp_f.bind('<KeyPress-Left>', self.on_keypress_left) self.tmp_f.bind('<KeyPress-Right>', self.on_keypress_right) self.tmp_f.pack(side="bottom") self.tmp_f.focus_set() self.btn_landing = tki.Button(panel, text="Flip", relief="raised", command=self.openFlipWindow) self.btn_landing.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.distance_bar = Scale(panel, from_=0.02, to=5, tickinterval=0.01, digits=3, label='Distance(m)', resolution=0.01) self.distance_bar.set(0.2) self.distance_bar.pack(side="left") self.btn_distance = tki.Button( panel, text="Reset Distance", relief="raised", command=self.updateDistancebar, ) self.btn_distance.pack(side="left", fill="both", expand="yes", padx=10, pady=5) self.degree_bar = Scale(panel, from_=1, to=360, tickinterval=10, label='Degree') self.degree_bar.set(30) self.degree_bar.pack(side="right") self.btn_distance = tki.Button(panel, text="Reset Degree", relief="raised", command=self.updateDegreebar) self.btn_distance.pack(side="right", fill="both", expand="yes", padx=10, pady=5)
def guiMain(settings=None): frames = {} mainWindow = Tk() mainWindow.wm_title("OoT Randomizer %s" % ESVersion) 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) 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='Aesthetics') # Shared Controls # adds a LabelFrame containing a list of radio buttons based on the given data # returns the label_frame, and a variable associated with it def MakeRadioList(parent, data): # create a frame to hold the radio buttons lable_frame = LabelFrame(parent, text=data["name"], labelanchor=NW) # create a variable to hold the result of the user's decision radio_var = StringVar(value=data["default"]); # setup orientation side = TOP anchor = W if "horizontal" in data and data["horizontal"]: side = LEFT anchor = N # add the radio buttons for option in data["options"]: radio_button = Radiobutton(lable_frame, text=option["description"], value=option["value"], variable=radio_var, justify=LEFT, wraplength=data["wraplength"]) radio_button.pack(expand=True, side=side, anchor=anchor) # return the frame so it can be packed, and the var so it can be used return (lable_frame, radio_var) ####################### # 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['logic'] = LabelFrame(frames['rules_tab'], text='Logic', 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['tuniccolor'] = LabelFrame(frames['aesthetic_tab'], text='Tunic Color', labelanchor=NW) frames['navicolor'] = LabelFrame(frames['aesthetic_tab'], text='Navi Color', labelanchor=NW) frames['lowhp'] = LabelFrame(frames['aesthetic_tab'], text='Low HP SFX', labelanchor=NW) # shared settingsFrame = Frame(mainWindow) settings_string_var = StringVar() settingsEntry = Entry(settingsFrame, textvariable=settings_string_var) 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 = True for dep_var, dep_val in info.gui_params['dependency'].items(): if guivars[dep_var].get() != dep_val: dep_met = False if widgets[info.name].winfo_class() == 'Frame': for child in widgets[info.name].winfo_children(): child.configure(state= 'normal' if dep_met else 'disabled') else: widgets[info.name].config(state = 'normal' if dep_met else 'disabled') 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=(40,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)) multiworldFrame = LabelFrame(frames['rom_tab'], text='Multi-World Generation') countLabel = Label(multiworldFrame, wraplength=300, justify=LEFT, text='This is used for co-op generations. Increasing World Count will drastically increase the generation time. For more information see https://github.com/TestRunnerSRL/bizhawk-co-op') countLabel.pack(side=TOP, anchor=W, padx=5, pady=(1,1)) worldCountFrame = Frame(multiworldFrame) countLabel = Label(worldCountFrame, text='World 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=5, pady=(1,1)) playerNumFrame = Frame(multiworldFrame) countLabel = Label(playerNumFrame, text='Player Number') 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=5, pady=(1,1)) multiworldFrame.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=200, command=show_settings) 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'] == '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) # pack the hierarchy frames['open'].pack( fill=BOTH, expand=True, anchor=N, side=LEFT, pady=(5,1) ) frames['logic'].pack( fill=BOTH, expand=True, anchor=N, side=LEFT, 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['navicolor'].pack( fill=BOTH, expand=True, anchor=N, side=RIGHT, pady=(5,1) ) frames['tuniccolor'].pack(fill=BOTH, expand=True, anchor=W, side=TOP, pady=(5,1) ) frames['lowhp'].pack( fill=BOTH, expand=True, anchor=W, side=BOTTOM, pady=(5,1) ) notebook.pack(fill=BOTH, expand=True, padx=5, pady=5) # didn't refactor the rest, sorry # create the option menu settingsFrame.pack(fill=BOTH, anchor=W, padx=5, pady=(10,0)) def generateRom(): settings = guivars_to_settings(guivars) try: if settings.count is not None: orig_seed = settings.seed for i in range(settings.count): settings.update_seed(orig_seed + '-' + str(i)) main(settings) else: main(settings) except Exception as e: messagebox.showerror(title="Error while creating seed", message=str(e)) else: messagebox.showinfo(title="Success", message="Rom patched successfully") 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']) seedLabel.pack(side=LEFT) seedEntry.pack(side=LEFT) generateButton.pack(side=LEFT, padx=(5, 0)) generateSeedFrame.pack(side=BOTTOM, anchor=W, padx=5, pady=10) if settings is not None: # load values from commandline args settings_to_guivars(settings, guivars) else: # try to load saved settings try: with open('settings.sav') as f: settings = Settings( json.load(f) ) settings.update_seed("") settings_to_guivars(settings, guivars) except: pass show_settings() mainWindow.mainloop() # save settings on close with open('settings.sav', 'w') as outfile: settings = guivars_to_settings(guivars) json.dump(settings.__dict__, outfile)
def __init__(self, game: Game): Tk.__init__(self) # for 4k self.tk.call('tk', 'scaling', '-displayof', '.', 1) # setup variables self.game = game self.is_automoving = False # create widgets self.board_canvas = Canvas(self, background="white") self.control_frame = Frame(self) self.label_current_player = Label(self.control_frame, text="Current Player: X") self.button_next_turn = Button(self.control_frame, text="Next Turn", command=self.next_turn) self.slider_automove_speed = scale = Scale(self.control_frame, orient='horizontal', from_=0, to_=2000) self.button_toggle_automove = Button(self.control_frame, text="Start Automove", command=self.toggle_automove) self.checkbox_frame = Frame(self.control_frame) # controls user input self.user_controlled = [] for pick in ['X', 'A', 'B', 'C', 'D', 'E']: var = IntVar() chk = Checkbutton(self.checkbox_frame, text=pick, variable=var) chk.pack(side=TOP, anchor=N, expand=YES) self.user_controlled.append(var) self.text_user_input = Entry(self.control_frame, text="move") #self.text_user_input.grid(column=0, sticky='N') drop_down_options = {"taxi", "bus", "underground", "black"} self.drop_down_selected = StringVar(self.control_frame) self.drop_down_selected.set("taxi") self.drop_down_menu = OptionMenu(self.control_frame, self.drop_down_selected, *drop_down_options) #self.drop_down_menu.grid(column=1, sticky='N') self.button_send_action = Button(self.control_frame, text="Send", command=self.send_move) #self.button_send_action.grid(column=2, sticky='N') # layout widgets self.board_canvas.pack(fill='both', expand=True, anchor='w') self.control_frame.pack(before=self.board_canvas, side='right', anchor='e') self.label_current_player.pack(fill='x') self.button_next_turn.pack(fill='x') self.slider_automove_speed.pack(fill='x') self.button_toggle_automove.pack(fill='x') Label(self.control_frame, text="\n\n\n").pack(fill='x') self.checkbox_frame.pack(fill='x', expand=True, anchor='w') self.text_user_input.pack(fill='y') self.drop_down_menu.pack(fill='y') self.button_send_action.pack(fill='y') # setup canvas self.board_img_pil = Image.open('board.jpg') self.board_img = ImageTk.PhotoImage(self.board_img_pil) self.img_id = self.board_canvas.create_image(300, 300, image=self.board_img) # move image on resize self.bind("<Configure>", self.update_ui) self.player_colors = [ "black", "red", "yellow", "green", "blue", "purple" ] #random.shuffle(self.player_colors) self.old_canvas_size = self.winfo_width(), self.winfo_height() self.player_rects = [ self.board_canvas.create_rectangle(0, 0, 1, 1, fill=self.player_colors[i]) for i in range(len(self.game.players)) ] self.player_txts = [ self.board_canvas.create_text(0, 0, text=plr.name) for plr in self.game.players ] # create data for node locations on image self.node_locations = {} with open("node_locations.txt", "r") as f: for line in f: l = line.split(" ") self.node_locations[int(l[0])] = (float(l[1]), float(l[2]))
def __init__(self): # MQTT Client self.client = mqtt.Client(client_id="simulator") self.client.connect("localhost", port=1883) # Window settings self.window = Tk() self.window.title(cnst.WINDOW_TITLE) self.window.geometry( str(cnst.WINDOW_WIDTH) + 'x' + str(cnst.WINDOW_HEIGHT)) # Temperature slider self.temp_lbl = Label(self.window, text="Temperature") self.temp_lbl.pack(anchor=CENTER) self.temp_var = DoubleVar(value=cnst.DEFAULT_TEMP) self.slider_temperature = Scale(self.window, variable=self.temp_var, from_=cnst.MIN_TEMP, to_=cnst.MAX_TEMP, resolution=-1, orient=HORIZONTAL) self.slider_temperature.pack(anchor=CENTER) # API Temperature slider self.api_temp_lbl = Label(self.window, text="API Temperature") self.api_temp_lbl.pack(anchor=CENTER) self.api_temp_var = DoubleVar(value=cnst.DEFAULT_TEMP) self.slider_api_temperature = Scale(self.window, variable=self.api_temp_var, from_=cnst.MIN_TEMP, to_=cnst.MAX_TEMP, resolution=-1, orient=HORIZONTAL) self.slider_api_temperature.pack(anchor=CENTER) # API Min temperature slider self.api_min_temp_lbl = Label(self.window, text="API Min Temperature") self.api_min_temp_lbl.pack(anchor=CENTER) self.api_min_temp_var = DoubleVar(value=cnst.DEFAULT_TEMP) self.slider_api_min_temperature = Scale(self.window, variable=self.api_min_temp_var, from_=cnst.MIN_TEMP, to_=cnst.MAX_TEMP, resolution=-1, orient=HORIZONTAL) self.slider_api_min_temperature.pack(anchor=CENTER) # API Max temperature slider self.api_max_temp_lbl = Label(self.window, text="API Max Temperature") self.api_max_temp_lbl.pack(anchor=CENTER) self.api_max_temp_var = DoubleVar(value=cnst.DEFAULT_TEMP) self.slider_api_max_temperature = Scale(self.window, variable=self.api_max_temp_var, from_=cnst.MIN_TEMP, to_=cnst.MAX_TEMP, resolution=-1, orient=HORIZONTAL) self.slider_api_max_temperature.pack(anchor=CENTER) # API Feels temperature slider self.api_feels_temp_lbl = Label(self.window, text="API Feels Temperature") self.api_feels_temp_lbl.pack(anchor=CENTER) self.api_feels_temp_var = DoubleVar(value=cnst.DEFAULT_TEMP) self.slider_api_feels_temperature = Scale( self.window, variable=self.api_feels_temp_var, from_=cnst.MIN_TEMP, to_=cnst.MAX_TEMP, resolution=-1, orient=HORIZONTAL) self.slider_api_feels_temperature.pack(anchor=CENTER) # API Humidity slider self.api_humidity_lbl = Label(self.window, text="API Humidity") self.api_humidity_lbl.pack(anchor=CENTER) self.api_humidity_var = DoubleVar(value=cnst.DEFAULT_HUMIDITY) self.slider_api_humidity = Scale(self.window, variable=self.api_humidity_var, from_=cnst.MIN_HUMIDITY, to_=cnst.MAX_HUMIDITY, resolution=-1, orient=HORIZONTAL) self.slider_api_humidity.pack(anchor=CENTER) # Luminosity slider self.luminosity_lbl = Label(self.window, text="Luminosity") self.luminosity_lbl.pack(anchor=CENTER) self.luminosity_var = DoubleVar(value=cnst.DEFAULT_LUMINOSITY) self.slider_luminosity = Scale(self.window, variable=self.luminosity_var, from_=cnst.MIN_LUMINOSITY, to_=cnst.MAX_LUMINOSITY, resolution=-1, orient=HORIZONTAL) self.slider_luminosity.pack(anchor=CENTER) # Humidity slider self.humidity_lbl = Label(self.window, text="Humidity") self.humidity_lbl.pack(anchor=CENTER) self.humidity_var = DoubleVar(value=cnst.DEFAULT_HUMIDITY) self.slider_humidity = Scale(self.window, variable=self.humidity_var, from_=cnst.MIN_HUMIDITY, to_=cnst.MAX_HUMIDITY, resolution=-1, orient=HORIZONTAL) self.slider_humidity.pack(anchor=CENTER) # Noise slider self.noise_lbl = Label(self.window, text="Noise") self.noise_lbl.pack(anchor=CENTER) self.noise_var = DoubleVar(value=cnst.DEFAULT_NOISE) self.slider_noise = Scale(self.window, variable=self.noise_var, from_=cnst.MIN_NOISE, to_=cnst.MAX_NOISE, resolution=-1, orient=HORIZONTAL) self.slider_noise.pack(anchor=CENTER) # Air Quality slider self.airquality_lbl = Label(self.window, text="AirQuality") self.airquality_lbl.pack(anchor=CENTER) self.airquality_var = DoubleVar(value=cnst.DEFAULT_AIRQUALITY) self.slider_airquality = Scale(self.window, variable=self.airquality_var, from_=cnst.MIN_AIRQUALITY, to_=cnst.MAX_AIRQUALITY, resolution=-1, orient=HORIZONTAL) self.slider_airquality.pack(anchor=CENTER) # Button to publish the data self.submit_btn = Button(self.window, text="Simulate", command=self.publish) self.submit_btn.pack(anchor=CENTER)
#loops through and creates buttons and selecters etc. for trains for i in range(max_trains): #one section for each train temp_column = 0 #temp column decides how far left/right train options are placed if ((i == 1) | (i == 3)): temp_column = 5 temp_row = 1 #decides how far up or down train options are placed if ((i == 2) | (i == 3)): temp_row = 9 + num_train_actions - 5 #create label for train train_slider_labels[i] = Label(sliders_frame, text=("Train " + str(i + 1) + " Controls")) train_slider_labels[i].grid(column=temp_column, row=temp_row, columnspan=3) #create the speed slider for train train_speed_sliders[i] = Scale(sliders_frame, from_=50, to=0, tickinterval=10) train_speed_sliders[i].grid(column=temp_column, row=temp_row + 1, rowspan=5, columnspan=1, ipady=20, ipadx=10) #create forward/reverse options for train train_dir_variables[i] = IntVar() train_dir_buttons[i][0] = Radiobutton(sliders_frame, text="Forward", variable=train_dir_variables[i], value=0, indicatoron=0).grid(
def _entry(self): '''Method for creating widgets for collecting user input.''' # N (no of turtles) dim = 30 * 30 self._N_label = Label(self._entryPane, anchor='w', justify='left', text="N:", relief='raised', width=12, height=1, font="italic 20") self._N_label.grid(row=0, column=1, ipady=14) self._N = Scale(self._entryPane, from_=1, to=dim - 50, resolution=1, bd=3, relief='sunken', orient='horizontal', length=235, tickinterval=849) self._N.set(400) self._N.grid(row=0, column=2) # Ticks (lenght of simulation) self._Ticks_label = Label(self._entryPane, anchor='w', justify='left', text="Time:", relief='raised', width=12, height=1, font="bold 20") self._Ticks_label.grid(row=1, column=1, ipady=14) self._Ticks = Scale(self._entryPane, from_=10, to=1000, resolution=1, bd=3, relief='sunken', orient='horizontal', length=235, tickinterval=990) self._Ticks.set(500) self._Ticks.grid(row=1, column=2) # % similar wanted self._Similar_label = Label(self._entryPane, anchor='w', justify='left', text="Similar wanted:", relief='raised', width=12, height=1, font="bold 20") self._Similar_label.grid(row=2, column=1, ipady=14) self._Similar = Scale(self._entryPane, from_=0.0, to=1.0, resolution=0.01, bd=3, relief='sunken', orient='horizontal', length=235, tickinterval=1) self._Similar.set(0.76) self._Similar.grid(row=2, column=2)
class GUI(): def __init__(self): self.root = ThemedTk(theme="radiance") INIT_WIDTH, INIT_HEIGHT = self.root.winfo_screenwidth( ), self.root.winfo_screenheight() boldStyle = ttk.Style() boldStyle.configure("Bold.TButton", font=('Sans', '12', 'bold')) #icon_loc = os.path.join(os.getcwd(),ICON_NAME) #img = ImageTk.PhotoImage(master = self.root, file=icon_loc) #self.root.wm_iconbitmap(img) #self.root.ttk.call('wm', 'iconphoto', self.root._w, img) self.root.title("Form Labeller") self.root.maxsize(INIT_WIDTH, INIT_HEIGHT) self.supported_formats = SUPPORTED_FORMATS self.left_frame = Frame(self.root, width=BUTTON_WIDTH) self.top_frame1 = Frame(self.left_frame, width=BUTTON_WIDTH, height=int(INIT_HEIGHT / 2)) self.top_frame = Frame(self.left_frame, width=BUTTON_WIDTH, height=INIT_HEIGHT - int(INIT_HEIGHT / 2)) self.bottom_frame = Frame(self.root, width=INIT_WIDTH - BUTTON_WIDTH) self.load_image_directory_button = Button(self.top_frame1, text='Open Folder', command=self.load_directory, width=int(BUTTON_WIDTH), style="Bold.TButton") self.load_image_directory_button.grid(row=OPEN_FOLDER_ROW, columnspan=2, sticky=tk.W + tk.E) self.prev_img_button = Button(self.top_frame1, text='← Prev', command=self.previous_img, state=tk.DISABLED, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.prev_img_button.grid(row=PREV_ROW, column=0, sticky=tk.W + tk.E) self.next_img_button = Button(self.top_frame1, text='Next → ', command=self.next_img, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.next_img_button.grid(row=NEXT_COL, column=1, sticky=tk.W + tk.E) self.save_image_button = Button(self.top_frame1, text='Save ', command=self.saver, width=int(BUTTON_WIDTH), style="Bold.TButton") self.save_image_button.grid(row=SAVE_ROW, columnspan=2, sticky=tk.W + tk.E) self.delete_poly_button = Button(self.top_frame, text='Delete Selected', command=self.delete_selected, width=int(BUTTON_WIDTH), style="Bold.TButton") self.delete_poly_button.grid(row=DEL_SELECTED_ROW, columnspan=2, sticky=tk.W + tk.E) self.type_choices = TYPE_CHOICES self.variable = StringVar(self.top_frame) self.variable.set(self.type_choices[0]) self.type_options = OptionMenu(self.top_frame, self.variable, *self.type_choices, style="Bold.TButton") self.type_options.config(width=int(BUTTON_WIDTH / 2)) self.type_options.grid(row=DROP_DOWN_ROW, column=0) self.save_type_button = Button(self.top_frame, text='Save Type', command=self.save_type, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.save_type_button.grid(row=SAVE_TYPE_ROW, column=1, sticky=tk.W + tk.E) self.deselect_all_button = Button(self.top_frame, text='Deselect All', command=self.deselect_all, width=BUTTON_WIDTH, style="Bold.TButton") self.deselect_all_button.grid(row=DESELECT_ALL_ROW, columnspan=2, sticky=tk.W + tk.E) self.select_all_button = Button(self.top_frame, text='Select All', command=self.select_all, width=BUTTON_WIDTH, style="Bold.TButton") self.select_all_button.grid(row=SELECT_ALL_ROW, columnspan=2, sticky=tk.W + tk.E) self.draw_poly_button = Button(self.top_frame, text='Draw Poly', command=self.draw_poly_func, width=BUTTON_WIDTH, style="Bold.TButton") self.draw_poly_button.grid(row=DRAW_POLY_ROW, columnspan=2, sticky=tk.W + tk.E) self.draw_rect_button = Button(self.top_frame, text='Draw Rectangle', command=self.draw_rect_func, width=BUTTON_WIDTH, style="Bold.TButton") self.draw_rect_button.grid(row=DRAW_RECT_ROW, columnspan=2, sticky=tk.W + tk.E) self.delete_all_button = Button(self.top_frame, text='Delete All', command=self.delete_all, width=BUTTON_WIDTH, style="Bold.TButton") self.save_poly_button = Button(self.top_frame, text='Save Poly', command=self.save_drawing, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.discard_poly_button = Button(self.top_frame, text='Discard Poly', command=self.discard_drawing, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.save_rect_button = Button(self.top_frame, text='Save Rect', command=self.save_drawing, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.discard_rect_button = Button(self.top_frame, text='Discard Rect', command=self.discard_drawing, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.show_type_button = Button(self.top_frame, text='Show Type', command=self.show_type, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.show_type_button.grid(row=SHOW_TYPE_ROW, column=0, columnspan=1, sticky=tk.W + tk.E) self.hide_type_button = Button(self.top_frame, text='Hide Type', command=self.hide_type, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.hide_type_button.grid(row=HIDE_TYPE_ROW, columnspan=1, column=1, sticky=tk.W + tk.E) self.make_tight_button = Button(self.top_frame, text='Make Tight', command=self.make_tight, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.make_tight_button.grid(row=MAKE_TIGHT_ROW, columnspan=2, column=0, sticky=tk.W + tk.E) self.threshold_scale = Scale(self.top_frame, from_=0, to=255, orient=HORIZONTAL, width=int(BUTTON_WIDTH / 2), label="Binary Threshold") self.threshold_scale.set(128) self.threshold_scale.grid(row=THRESHOLD_ROW, columnspan=2, column=0, sticky=tk.W + tk.E) self.tight_save_button = Button(self.top_frame, text='Accept Tight', command=self.save_tight) self.tight_discard_button = Button(self.top_frame, text='Discard Tight', command=self.discard_tight) self.canvas = Canvas(self.bottom_frame, width=INIT_WIDTH - BUTTON_WIDTH, height=INIT_HEIGHT, borderwidth=1) self.image_name = None #self.image_path = os.path.join('imgs','img1.jpg') self.image_dir = None self.images_in_dir = None self.curr_idx = None self.img_cnv = None #self.img_cnv = ImageOnCanvas(self.root,self.canvas,self.image_path) self.drawing_obj = None self.tight_box_obj = None self.left_frame.pack(side=tk.LEFT) self.top_frame1.pack(side=tk.TOP) self.top_frame.pack(side=tk.BOTTOM) self.bottom_frame.pack(side=tk.LEFT) self.canvas.pack() self.hide_buttons() self.load_image_directory_button.config(state="normal") def save_tight(self): self.tight_box_obj.save_tight_box() self.tight_save_button.grid_forget() self.tight_discard_button.grid_forget() self.make_tight_button.grid(row=MAKE_TIGHT_ROW, columnspan=2, sticky=tk.W + tk.E) self.show_buttons() self.tight_box_obj = None def discard_tight(self): self.tight_box_obj.discard_tight_box() self.tight_save_button.grid_forget() self.tight_discard_button.grid_forget() self.make_tight_button.grid(row=MAKE_TIGHT_ROW, columnspan=2, sticky=tk.W + tk.E) self.show_buttons() self.tight_box_obj = None def show_type(self): for poly in self.img_cnv.polygons: if poly.select_poly: poly.show_type() def hide_type(self): for poly in self.img_cnv.polygons: poly.unshow_type() def hide_buttons(self): self.load_image_directory_button.config(state=tk.DISABLED) self.save_image_button.config(state=tk.DISABLED) self.delete_poly_button.config(state=tk.DISABLED) self.save_type_button.config(state=tk.DISABLED) self.deselect_all_button.config(state=tk.DISABLED) self.select_all_button.config(state=tk.DISABLED) self.delete_all_button.config(state=tk.DISABLED) self.show_type_button.config(state=tk.DISABLED) self.hide_type_button.config(state=tk.DISABLED) self.make_tight_button.config(state=tk.DISABLED) def show_buttons(self): self.load_image_directory_button.config(state="normal") self.save_image_button.config(state="normal") self.delete_poly_button.config(state="normal") self.save_type_button.config(state="normal") self.deselect_all_button.config(state="normal") self.select_all_button.config(state="normal") self.delete_all_button.config(state="normal") self.show_type_button.config(state="normal") self.hide_type_button.config(state="normal") self.draw_poly_button.config(state="normal") self.draw_rect_button.config(state="normal") self.make_tight_button.config(state="normal") def select_all(self): for poly in self.img_cnv.polygons: poly.select_polygon() def deselect_all(self): self.hide_type() for poly in self.img_cnv.polygons: poly.deselect_poly() def delete_all(self): result = messagebox.askyesno("Confirm Delete All", "Delete All Annotations?") if not result: return self.select_all() self.delete_selected() #self.img_cnv.polygons_mutex.acquire() #for poly in self.img_cnv.polygons: # poly.delete_self() #self.img_cnv.polygons_mutex.release() def save_type(self): selected_option = self.variable.get() self.img_cnv.polygons_mutex.acquire() for poly in self.img_cnv.polygons: if poly.select_poly == True: if selected_option == "None": poly.poly_type = None else: poly.poly_type = selected_option #poly.unshow_type() #poly.show_type() self.img_cnv.polygons_mutex.release() self.variable.set(self.type_choices[0]) #self.deselect_all() def load_new_img(self): self.canvas.delete('all') self.img_cnv = None path = os.path.join(self.image_dir, self.image_name) self.img_cnv = ImageOnCanvas(self.root, self.canvas, path) logger("LOADED: " + self.img_cnv.image_path) def load_directory(self): while True: selection = filedialog.askdirectory() if selection == () or selection == '': return self.root.directory = selection self.image_dir = self.root.directory file_names = os.listdir(self.image_dir) self.images_in_dir = [] self.curr_idx = None self.image_name = None for name in file_names: if name.split('.')[-1] in self.supported_formats: self.images_in_dir.append(name) if len(self.images_in_dir) == 0: self.pop_up("No supported images in the selected directory") else: break self.show_buttons() self.next_img() def pop_up(self, text): top = Toplevel() top.title("ERROR") msg = Message(top, text=text) msg.pack() button = Button(top, text="Dismiss", command=top.destroy) button.pack() def next_img(self): if self.curr_idx == None: self.curr_idx = -1 self.curr_idx = self.curr_idx + 1 if self.curr_idx >= len(self.images_in_dir): self.pop_up("Done with Images in this directory") self.curr_idx = self.curr_idx - 1 return if self.curr_idx > 0: self.prev_img_button.config(state="normal") self.image_name = self.images_in_dir[self.curr_idx] self.load_new_img() self.root.title("Form Labeller - " + self.image_name + "(" + str(self.curr_idx + 1) + "/" + str(len(self.images_in_dir)) + ")") def previous_img(self): if self.curr_idx == 1: self.curr_idx = -1 self.prev_img_button.config(state=tk.DISABLED) else: self.curr_idx = self.curr_idx - 2 self.next_img() def delete_selected(self): to_be_deleted = [] for i, poly in enumerate(self.img_cnv.polygons): if poly.select_poly == True: poly.delete_self() to_be_deleted.append(i) j = 0 for idx in to_be_deleted: self.img_cnv.polygons.pop(idx - j) self.img_cnv.bbs.pop(idx - j) self.img_cnv.poly_type.pop(idx - j) j = j + 1 def start_gui(self): self.root.mainloop() def saver(self): logger("Saving: " + self.img_cnv.image_path) self.save_image_button.config(state=tk.DISABLED) self.img_cnv.save_json(self.root.directory) self.save_image_button.config(state="normal") def draw_poly_func(self): self.deselect_all() self.img_cnv.drawing_polygon = True self.draw_poly_button.grid_forget() self.save_poly_button.grid(row=DRAW_POLY_ROW, column=0, sticky=tk.W + tk.E) self.discard_poly_button.grid(row=DRAW_POLY_ROW, column=1, sticky=tk.W + tk.E) self.hide_buttons() self.draw_rect_button.config(state=tk.DISABLED) self.drawing_obj = DrawPoly(self.bottom_frame, self.canvas, self.img_cnv, RADIUS) def draw_rect_func(self): self.deselect_all() self.img_cnv.drawing_polygon = True self.draw_rect_button.grid_forget() self.save_rect_button.grid(row=DRAW_RECT_ROW, column=0, sticky=tk.W + tk.E) self.discard_rect_button.grid(row=DRAW_RECT_ROW, column=1, sticky=tk.W + tk.E) self.hide_buttons() self.draw_poly_button.config(state=tk.DISABLED) self.drawing_obj = DrawRect(self.bottom_frame, self.canvas, self.img_cnv, RADIUS) def save_drawing(self): self.show_buttons() self.img_cnv.drawing_polygon = False new_poly_pts = self.drawing_obj.pt_coords print("Trying to save polygon with pts:", str(new_poly_pts)) for pt in self.drawing_obj.points: self.canvas.delete(pt) if self.img_cnv.scale_factor != None: for i in range(len(new_poly_pts)): for j in range(2): new_poly_pts[i][ j] = new_poly_pts[i][j] / self.img_cnv.scale_factor self.img_cnv.add_poly(new_poly_pts) #self.img_cnv.bbs.append(new_poly_pts) #self.img_cnv.draw_bbs([self.img_cnv.bbs[-1]]) #debug (1, str(type(self.drawing_obj))) if isinstance(self.drawing_obj, DrawRect): self.save_rect_button.grid_forget() self.discard_rect_button.grid_forget() self.draw_rect_button.grid(row=DRAW_RECT_ROW, columnspan=2, sticky=tk.W + tk.E) elif isinstance(self.drawing_obj, DrawPoly): self.save_poly_button.grid_forget() self.discard_poly_button.grid_forget() self.draw_poly_button.grid(row=DRAW_POLY_ROW, columnspan=2, sticky=tk.W + tk.E) self.drawing_obj.delete_self() self.drawing_obj = None def discard_drawing(self): self.show_buttons() self.img_cnv.drawing_polygon = False #for pt in self.drawing_obj.points: # self.canvas.delete(pt) self.drawing_obj.delete_self() if isinstance(self.drawing_obj, DrawRect): self.save_rect_button.grid_forget() self.discard_rect_button.grid_forget() self.draw_rect_button.grid(row=DRAW_RECT_ROW, columnspan=2, sticky=tk.W + tk.E) elif isinstance(self.drawing_obj, DrawPoly): self.save_poly_button.grid_forget() self.discard_poly_button.grid_forget() self.draw_poly_button.grid(row=DRAW_POLY_ROW, columnspan=2, sticky=tk.W + tk.E) self.drawing_obj = None def make_tight(self): self.hide_buttons() self.tight_box_obj = TightBox(self.root, self.img_cnv, self.threshold_scale.get()) self.tight_box_obj.tight_box() self.make_tight_button.grid_forget() self.tight_save_button.grid(row=MAKE_TIGHT_ROW, column=0, columnspan=1, sticky=tk.W + tk.E) self.tight_discard_button.grid(row=MAKE_TIGHT_ROW, column=1, columnspan=1, sticky=tk.W + tk.E)
class Visual(Frame): '''Class that takes a world as argument and present it graphically on a tkinter canvas.''' def __init__(self): '''Sets up a simulation GUI in tkinter. ''' Frame.__init__(self) self.master.title("The Schelling Segregation Model in Python") self.master.wm_resizable(0, 0) self.grid() self.movement_possible = True # --------------------------------------- # # --------- FRAMES FOR GUI -------------- # # --------------------------------------- # # The pane for user values self._entryPane = Frame(self, borderwidth=5, relief='sunken') self._entryPane.grid(row=0, column=0, sticky='n') # The buttons pane self._buttonPane = Frame(self, borderwidth=5) self._buttonPane.grid(row=1, column=0, sticky='n') # A temp pane where graph is located, just for cosmetic reasons width, height = 425, 350 self._graph = Canvas(self, width=width, height=height, background="black") self._graph.configure(relief='sunken', border=2) self._graph.grid(row=3, column=0) # The pane where the canvas is located self._animationPane = Frame(self, borderwidth=5, relief='sunken') self._animationPane.grid(row=0, column=1, rowspan=4, pady=10, sticky="n") # --------------------------------------- # # --------- FILLING THE FRAMES ---------- # # --------------------------------------- # self._canvas() # Create graphics canvas self._entry() # Create entry widgets self._buttons() # Create button widgets def _plot_setup(self, time): '''Method for crudely annotating the graph window.''' time = time # Main plot width, height = 425, 350 y0 = -time / 10 self._graph = Canvas(self, width=width, height=height, background="black", borderwidth=5) self._graph.grid(row=3, column=0) self.trans = Plotcoords(width, height, y0, -0.2, time, 1.3) x, y = self.trans.screen(time // 2, 1.2) x1, y1 = self.trans.screen(time // 2, 1.13) self._graph.create_text(x, y, text="% Happy", fill="yellow", font="bold 12") self._graph.create_text(x1, y1, text="% Unhappy", fill="blue", font="bold 12") # Line x-axis x, y = self.trans.screen((-5 * (time / 100)), -0.05) x1, y = self.trans.screen(time, -0.05) self._graph.create_line(x, y, x1, y, fill="white", width=1.5) # Text x-axis x_text, y_text = self.trans.screen(time / 2, -0.15) self._graph.create_text(x_text, y_text, text="Time", fill="white", font="bold 12") # Liney-axis x, y = self.trans.screen((-0.5 * (time / 100)), -0.05) x, y1 = self.trans.screen((-5 * (time / 100)), 1) self._graph.create_line(x, y, x, y1, fill="white", width=1.5) def _entry(self): '''Method for creating widgets for collecting user input.''' # N (no of turtles) dim = 30 * 30 self._N_label = Label(self._entryPane, anchor='w', justify='left', text="N:", relief='raised', width=12, height=1, font="italic 20") self._N_label.grid(row=0, column=1, ipady=14) self._N = Scale(self._entryPane, from_=1, to=dim - 50, resolution=1, bd=3, relief='sunken', orient='horizontal', length=235, tickinterval=849) self._N.set(400) self._N.grid(row=0, column=2) # Ticks (lenght of simulation) self._Ticks_label = Label(self._entryPane, anchor='w', justify='left', text="Time:", relief='raised', width=12, height=1, font="bold 20") self._Ticks_label.grid(row=1, column=1, ipady=14) self._Ticks = Scale(self._entryPane, from_=10, to=1000, resolution=1, bd=3, relief='sunken', orient='horizontal', length=235, tickinterval=990) self._Ticks.set(500) self._Ticks.grid(row=1, column=2) # % similar wanted self._Similar_label = Label(self._entryPane, anchor='w', justify='left', text="Similar wanted:", relief='raised', width=12, height=1, font="bold 20") self._Similar_label.grid(row=2, column=1, ipady=14) self._Similar = Scale(self._entryPane, from_=0.0, to=1.0, resolution=0.01, bd=3, relief='sunken', orient='horizontal', length=235, tickinterval=1) self._Similar.set(0.76) self._Similar.grid(row=2, column=2) def _buttons(self): '''Method for creating button widgets for setting up, running and plotting results from simulation.''' width = 7 height = 1 # The 'Setup' button self._setupButton = Button(self._buttonPane, text="Setup", command=self._setup, width=width, height=height, font="bold 30", relief='raised', borderwidth=5) self._setupButton.grid(row=0, column=0) # The 'Go' button self._goButton = Button(self._buttonPane, text="Go", command=self._go, width=width, height=height, font="bold 30", relief='raised', borderwidth=5) self._goButton.grid(row=0, column=1) # The 'Quit' button self._quitButton = Button(self._buttonPane, text="Quit", command=self._quit, width=width, height=height, font="bold 30", relief='raised', borderwidth=5) self._quitButton.grid(row=1, column=0, columnspan=2) def _canvas(self): '''Creates the canvas on which everything happens.''' # The tick counter information self._Tick_counter = Label(self._animationPane, anchor='w', justify='left', text="Time:", width=5, font="bold 20") self._Tick_counter.grid(row=0, column=0, sticky="e") self._Tick_counter1 = Label(self._animationPane, justify='center', text="", relief='raised', width=5, font="bold 20") self._Tick_counter1.grid(row=0, column=1, sticky='w') self.canvas_w, self.canvas_h = 750, 750 self.canvas = Canvas(self._animationPane, width=self.canvas_w, height=self.canvas_h, background="black") self.canvas.grid(row=1, column=0, columnspan=2) def _setup(self): '''Method for 'Setup' button.''' ## Clearing the canvas and reset the go button self.canvas.delete('all') self._goButton['relief'] = 'raised' self.N = int(self._N.get()) self.Ticks = int(self._Ticks.get()) self.similar = float(self._Similar.get()) self.data = [] self.tick_counter = 0 self._Tick_counter1['text'] = str(self.tick_counter) self._plot_setup(self.Ticks) self.grid_size = 30 self.world = World(750, 750, self.grid_size) self.create_turtles() self.neighbouring_turtles() self.draw_turtles() def _go(self): '''Method for the 'Go' button, i.e. running the simulation.''' self._goButton['relief'] = 'sunken' if self.tick_counter <= self.Ticks: self._Tick_counter1['text'] = str(self.tick_counter) self.canvas.update() self._graph.update() self._graph.after(0) # Data collection turtles_unhappy = self.check_satisfaction() prop_happy, prop_unhappy = self.calc_prop_happy(self.tick_counter) self.data_collection(self.tick_counter, prop_happy, prop_unhappy) if self.tick_counter >= 1: # HAPPY values (%) x0 = self.tick_counter - 1 x1 = self.tick_counter # Collecting values from stoblue data y0 = self.data[self.tick_counter - 1][1] y1 = self.data[self.tick_counter][1] # Transforming to tkinter x1, y1 = self.trans.screen(x1, y1) x0, y0 = self.trans.screen(x0, y0) self._graph.create_line(x0, y0, x1, y1, fill="yellow", width=1.3, tag="happy") # Draw "happy lines # UNHAPPY values (%) x0 = self.tick_counter - 1 x1 = self.tick_counter # Collecting values from stored data y0 = self.data[self.tick_counter - 1][2] y1 = self.data[self.tick_counter][2] # Transforming to tkinter x1, y1 = self.trans.screen(x1, y1) x0, y0 = self.trans.screen(x0, y0) self._graph.create_line(x0, y0, x1, y1, fill="blue", width=1.1, tag="unhappy") # Draw unhappy lines if prop_happy < 1: self.turtle_move(turtles_unhappy) self.update_neighbours() self.tick_counter += 1 self.canvas.after(0, self._go()) self._goButton['relief'] = 'raised' def _quit(self): '''Method for the 'Quit' button.''' self.master.destroy() # ------------------------------------------------------ # # ---------- FUNCTIONS CALLED AT EACH TICK ------------- # # ------------------------------------------------------ # def turtle_move(self, unhappy_turtles): '''Moves all the unhappy turtles (randomly).''' while unhappy_turtles: i = random.randint(0, len(unhappy_turtles) - 1) turtle = unhappy_turtles.pop(i) turtle.move(self) def update_neighbours(self): '''Updates the turtles neigbour attributes. Called after all turtles have moved.''' for turtle in self.turtles: turtle.update_neighbours() def check_satisfaction(self): '''Checks to see if turtles are happy or not. Returns a list of unhappy turtles, i.e. turtles that should move. Called before the move method.''' for turtle in self.turtles: turtle.is_happy() unhappy_turtles = [] for element in self.turtles: if not element.happy: unhappy_turtles.append(element) return unhappy_turtles def calc_prop_happy(self, i): '''Calculates the proportion of happy turtles.''' happy = 0 unhappy = 0 for turtle in self.turtles: if turtle.happy: happy += 1 else: unhappy += 1 prop_happy = happy / len(self.turtles) prop_unhappy = unhappy / len(self.turtles) return prop_happy, prop_unhappy def data_collection(self, i, prop_happy, prop_unhappy): '''Method for collecting data at each tick.''' self.data.append((i, prop_happy, prop_unhappy)) # ------------------------------------------------------ # # ---------- INITIALISATION FUNCTIONS ------------------ # # ------------------------------------------------------ # def create_turtles(self): '''Method for creating a new list of turtles. Upon creation they are registered in the World object.''' if self.N <= self.grid_size * self.grid_size: counter = 0 self.turtles = [] while counter < self.N: s = "S" + str(counter) if counter <= int(self.N / 2): color = "yellow" else: color = "blue" x = random.randint(0, self.grid_size - 1) y = random.randint(0, self.grid_size - 1) if not self.world.patch_list[x][y]: new_turtle = Schelling(world=self.world, x=x, y=y, s=s, color=color, similar_wanted=self.similar) self.world.register(new_turtle) counter += 1 self.turtles.append(new_turtle) else: print("Number of turtles exceeds world!") def draw_turtles(self): '''Method for drawing turtles on canvas. Calls each turtle's own method for drawing.''' for turtle in self.turtles: turtle.draw(self.canvas) def neighbouring_turtles(self): '''Method for updating turtles' neighbours. Calls on each turtle's own method for updating neighbours.''' for turtle in self.turtles: turtle.get_neighbouring_patches()
class SliderDialog(CustomDialog): def __init__(self, root, title="Slider Dialog", init_val=0, min_val=-1, max_val=1, default_val=0, on_change=list(), resolution=1, on_confirm=list(), on_cancel=list()): self.init_val = init_val self.default_val = default_val self.on_change = on_change self.on_confirm = on_confirm self.on_cancel = on_cancel self.window = Toplevel() self.window.title(title) self.window.transient(root) self.window.grab_set() self.scale = Scale(self.window, orient='horizontal', from_=min_val, to=max_val, command=self.on_update, resolution=resolution) self.scale.set(init_val) self.scale.grid(row=0, column=0, sticky='nesw') self.cancel_button = Button(self.window, text='Cancel', command=self.cancel) self.cancel_button.grid(row=1, column=0) self.reset_button = Button(self.window, text='Reset', command=self.reset) self.reset_button.grid(row=1, column=1) self.confirm_button = Button(self.window, text='Confirm', command=self.confirm) self.confirm_button.grid(row=1, column=2) def on_update(self, value): for callback in self.on_change: callback(value) def cancel(self): for callback in self.on_cancel: callback() self.on_change[0]( self.init_val ) # hardcoded atm, so assumes the set method is first (good enough for now) self.window.destroy() def reset(self): self.scale.set(self.default_val) def confirm(self): for callback in self.on_confirm: callback() self.window.destroy()
def setup_UI(self): # 第一行(两列) row1 = Frame(self) row1.pack(fill="x") scale_length = Scale(row1, label='每行每列的格子数', from_=2, to=20, orient=HORIZONTAL, length=200, showvalue=1, tickinterval=3, resolution=1, variable=self.length) scale_length.set(self.length.get()) scale_length.pack(side='top',expand='YES',fill='both') scale_size = Scale(row1, label='每个格子的大小', from_=10, to=200, orient=HORIZONTAL, length=200, showvalue=1, tickinterval=30, resolution=10, variable=self.size) scale_size.set(self.size.get()) scale_size.pack(side='top',expand='YES',fill='both') scale_start = Scale(row1, label='初始化数字格个数', from_=1, to=10, orient=HORIZONTAL, length=200, showvalue=1, tickinterval=2, resolution=1, variable=self.start) scale_start.set(self.start.get()) scale_start.pack(side='top',expand='YES',fill='both') scale_step = Scale(row1, label='每步添加的数字个数', from_=1, to=10, orient=HORIZONTAL, length=200, showvalue=1, tickinterval=2,resolution=1, variable=self.step) scale_step.set(self.step.get()) scale_step.pack(side='top',expand='YES',fill='both') # 第三行 row3 = Frame(self) row3.pack(fill="x") Button(row3, text="取消", command=self.cancel).pack(side=RIGHT) Button(row3, text="确定", command=self.ok).pack(side=RIGHT)
def __init__(self, parent, data, stepname): super().__init__(parent, data, stepname) lbl1 = Label( self, text= 'Click on each scale at the point that best indicates your experience of the task' ) lbl1.grid(row=1, column=1) lbl2 = Label(self, text="(1=extremely low,5=extremely high)") lbl2.grid(row=2, column=1) ########################### lbl3 = Label( self, text= 'Mental demand: How much mental and perceptual activity was required?' ) lbl3.grid(row=3, column=1) mentalscale = Scale(self, from_=1, to=10, length=200, tickinterval=1, orient=HORIZONTAL, command=self.updatemental) mentalscale.set(5) mentalscale.grid(row=3, column=2) self.data[self.stepname]["mental demand weight"] = mentalscale.get() ########### lbl4 = Label( self, text='Physical demand: How much physical activity was required?') lbl4.grid(row=4, column=1) physicalscale = Scale(self, from_=1, to=10, length=200, tickinterval=1, orient=HORIZONTAL, command=self.updatephysical) physicalscale.set(5) physicalscale.grid(row=4, column=2) self.data[ self.stepname]["physical demand weight"] = physicalscale.get() ########### ########### lbl5 = Label( self, text= 'Temporal demand: How much time pressure did you feel due to the rate of pace at which the tasks or task elements occurred?' ) lbl5.grid(row=5, column=1) temporalscale = Scale(self, from_=1, to=10, length=200, tickinterval=1, orient=HORIZONTAL, command=self.updatetemporal) temporalscale.set(5) temporalscale.grid(row=5, column=2) self.data[ self.stepname]["temporal demand weight"] = temporalscale.get() ########### ########### lbl6 = Label( self, text= 'Performance: How successful do you think you were in accomplishing the goals?' ) lbl6.grid(row=6, column=1) perforscale = Scale(self, from_=1, to=10, length=200, tickinterval=1, orient=HORIZONTAL, command=self.updateperformance) perforscale.set(5) perforscale.grid(row=6, column=2) self.data[self.stepname]["performance weight"] = perforscale.get() ########### ########### lbl7 = Label( self, text= 'Effort: How hard did you have to work (mentally and physically) to accomplish your level of performance?' ) lbl7.grid(row=7, column=1) effortscale = Scale(self, from_=1, to=10, length=200, tickinterval=1, orient=HORIZONTAL, command=self.updateeffort) effortscale.set(5) effortscale.grid(row=7, column=2) self.data[self.stepname]["effort weight"] = effortscale.get() ########### ########### lbl8 = Label( self, text= 'Frustration: How insecure, discouraged, irritated, stressed,and annoyed were you?' ) lbl8.grid(row=8, column=1) frustrationscale = Scale(self, from_=1, to=10, length=200, tickinterval=1, orient=HORIZONTAL, command=self.updatefrustration) frustrationscale.set(5) frustrationscale.grid(row=8, column=2) self.data[self.stepname]["frustration weight"] = frustrationscale.get() ########### self.data[self.stepname]["choose mental times"] = 0 self.data[self.stepname]["choose physical times"] = 0 self.data[self.stepname]["choose temporal times"] = 0 self.data[self.stepname]["choose performance times"] = 0 self.data[self.stepname]["choose effort times"] = 0 self.data[self.stepname]["choose frustration times"] = 0
def initui(self): self.parent.title("Light pollution map") self.style = Style() self.style.theme_use("alt") self.grid(row=0, column=0) padding = {'padx':'5', 'pady':'5'} big_heading_font = ("Arial", 14, 'bold') small_heading_font = ("Arial", 10, 'bold') # Create frames. # There are three frames for settings - preprocessing, convolve, and contour. # Each also has an image frame underneath it. # Layout is as follows: # # -------------------------------------------------------------------------- # | | | | | # | | | | | # | import_body | process_body | contour_body | export_body | # | | | | | # | | | | | # -------------------------------------------------------------------------- # Settings frames top = self.winfo_toplevel() top.rowconfigure(0, weight=1) top.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) self.columnconfigure(0, weight=1) self.columnconfigure(1, weight=1) self.columnconfigure(2, weight=1) self.columnconfigure(3, weight=1) import_body = Frame(self, relief=RAISED, borderwidth=1) import_body.grid(row=0, column=0, sticky=N+S+E+W) process_body = Frame(self, relief=RAISED, borderwidth=1) process_body.grid(row=0, column=1, sticky=N+S+E+W) contour_body = Frame(self, relief=RAISED, borderwidth=1) contour_body.grid(row=0, column=2, sticky=N+S+E+W) export_body = Frame(self, relief=RAISED, borderwidth=1) export_body.grid(row=0, column=3, sticky=N+S+E+W) # ============================================================================================================= # # Contents of load_image_frame # # ============================================================================================================= # Heading processing_frame_header = Label(import_body, text="Import", font=big_heading_font) processing_frame_header.grid(row=0, column=0, sticky=N, **padding) filename_variable = StringVar() # Import image import_canvas = Canvas(import_body, width=canvas_size, height=canvas_size, background='black') import_canvas.grid(row=1, column=0, sticky=N, **padding) # Load file method def choosefile(): filename_variable.set(filedialog.askopenfilename(parent=import_body)) image = Image.open(filename_variable.get()) thumbnail = create_thumbnail(image, canvas_size) import_canvas.create_image(0, 0, image=thumbnail, anchor=NW) load_image_button = Button(import_body, text="Import image", command=choosefile) load_image_button.grid(row=2, column=0, columnspan=2, sticky=E+W+S, **padding) import_body.rowconfigure(2, weight=1) # ============================================================================================================= # # Contents of processing_frame # # ============================================================================================================= processing_frame_header = Label(process_body, text="Process", font=big_heading_font) processing_frame_header.grid(row=0, column=0, columnspan=2, sticky=N, **padding) clipping_variable = IntVar() constants_label = Label(process_body, text="Clipping", font=("Arial", 10, 'bold')) constants_label.grid(row=1, column=0, sticky=E, **padding) clipping_label = Label(process_body, text="Remove pixels with \n brightness under") clipping_label.grid(row=2, column=0, sticky=E, **padding) clipping_entry = Entry(process_body, textvariable=clipping_variable, width=4) clipping_entry.grid(row=2, column=1, sticky=W, **padding) clipping_variable.set(value=default_clipping_value) convolve_header = Label(process_body, text="Kernel", font=small_heading_font) convolve_header.grid(row=4, column=0, sticky=E, **padding) kernel_size_variable = IntVar() kernel_size_label = Label(process_body, text="Convolve kernel size", justify=RIGHT) kernel_size_label.grid(row=5, column=0, sticky=E, **padding) kernel_size_entry = Entry(process_body, textvariable=kernel_size_variable, width=4) kernel_size_entry.grid(row=5, column=1, sticky=W, **padding) kernel_size_variable.set(value=default_kernel_size) # Constants for convolve equation constants_label = Label(process_body, text="Falloff", font=("Arial", 10, 'bold')) constants_label.grid(row=6, column=0, sticky=E, **padding) constant_a_label = Label(process_body, text="Constant A:") constant_b_label = Label(process_body, text="Constant B:") constant_c_label = Label(process_body, text="Constant C:") constant_a_label.grid(row=7, column=0, sticky=E, **padding) constant_b_label.grid(row=8, column=0, sticky=E, **padding) constant_c_label.grid(row=9, column=0, sticky=E, **padding) constant_a_variable = DoubleVar() constant_b_variable = DoubleVar() constant_c_variable = DoubleVar() constant_a_entry = Entry(process_body, textvariable=constant_a_variable, width=4) constant_b_entry = Entry(process_body, textvariable=constant_b_variable, width=4) constant_c_entry = Entry(process_body, textvariable=constant_c_variable, width=4) constant_a_variable.set(default_constant_a) constant_b_variable.set(default_constant_b) constant_c_variable.set(default_constant_c) constant_a_entry.grid(row=7, column=1, **padding) constant_b_entry.grid(row=8, column=1, **padding) constant_c_entry.grid(row=9, column=1, **padding) constants_note = Label(process_body, text="Falloff equation is (Ax^B)-C", font=("Arial", 9)) constants_note.grid(row=10, column=0, columnspan=2, sticky=E, **padding) # Start button! def process(): print("Filename was " + filename_variable.get()) image_data = process_image(filename=filename_variable.get(), kernel_size=kernel_size_variable.get(), clipping_value=clipping_variable.get(), constant_a=constant_a_variable.get(), constant_b=constant_b_variable.get(), constant_c=constant_c_variable.get() ) image_data = Image.open("processed_image.png") thumbnail = create_thumbnail(image_data, canvas_size) export_canvas.create_image(0, 0, image=thumbnail, anchor=NW) start_button = Button(process_body, text="Process image", command=process) start_button.grid(row=11, column=0, columnspan=3, sticky=E+W+S, **padding) process_body.rowconfigure(11, weight=1) # ============================================================================================================= # # Contents of contour_frame # # ============================================================================================================= contour_header = Label(contour_body, text="Contour", font=big_heading_font) contour_header.grid(row=0, column=0, sticky=S, columnspan=2, **padding) contour_note = Label(contour_body, text="(optional)") contour_note.grid(row=1, column=0, sticky=S, columnspan=2) scale_options = {"width":"5", "length":"150"} slider_padding = {"padx":"2", "pady":"0"} scale_list = [] scale_values_list = [] default_scale_values = [5, 7, 10, 20, 30, 40, 60, 100, 200] for i in range(9): scale = Scale(contour_body, from_=0, to_=255, orient=HORIZONTAL, **scale_options) scale.grid(row=i+2, column=0, columnspan=2, sticky=S, **slider_padding) scale.set(default_scale_values[i]) scale_list.append(scale) for scale in scale_list: print(scale) print(type(scale)) #print(scale.get()) def contour(): scale_values_list.clear() for scale in scale_list: scale_values_list.append(scale.get()) contour_image(scale_values_list) image_data = Image.open("Contoured_image.png") thumbnail = create_thumbnail(image_data, canvas_size) export_canvas.create_image(0, 0, image=thumbnail, anchor=NW) contour_button = Button(contour_body, text="Contour image", command=contour) contour_button.grid(row=11, column=0, columnspan=2, sticky=E+S+W, **padding) contour_body.rowconfigure(11, weight=1) contour_body.columnconfigure(1, weight=1) # ============================================================================================================= # # Contents of export_body # # ============================================================================================================= filename_export_variable = StringVar() def export_file(): filename_options = {} filename_options['filetypes'] = [('PNG', '.png')] filename_options['initialfile'] = 'output.png' filename_options['parent'] = self filename_export_variable.set(filedialog.asksaveasfilename(**filename_options)) image_data = Image.open("Contoured_image.png") image_data.save(filename_export_variable.get()) export_header = Label(export_body, text="Export", font=big_heading_font) export_header.grid(row=0, column=0, sticky=N, **padding) export_canvas = Canvas(export_body, width=canvas_size, height=canvas_size, background='black') export_canvas.grid(row=1, column=0, **padding) export_button = Button(export_body, text="Export image", command=export_file) export_button.grid(row=2, column=0, columnspan=2, sticky=E+W+S, **padding) export_body.rowconfigure(2, weight=1)