class Example(Frame): def __init__(self, master): Frame.__init__(self, master) self.dict = {'Asia': ['Japan', 'China', 'India'], 'Europe': ['Portugal', 'Switzerland', 'Ukraine']} self.var_a = StringVar(self) self.var_b = StringVar(self) self.var_a.trace('w', self.update_options) self.option_menu_a = OptionMenu(self, self.var_a, *self.dict.keys()) self.option_menu_a.pack(side="top") self.option_menu_a["width"] = 10 self.option_menu_b = OptionMenu(self, self.var_b, '') self.option_menu_b["width"] = 10 self.option_menu_b.pack(side="top") self.var_a.set('Asia') def update_options(self, *args): countries = self.dict[self.var_a.get()] self.var_b.set(countries[0]) menu = self.option_menu_b['menu'] menu.delete(0, 'end') for c in countries: menu.add_command(label=c, command=lambda x=c: self.var_b.set(x))
def __init__(self, pipepanel, pipeline_name, *args, **kwargs) : PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs) self.pairs = None eframe = self.eframe = LabelFrame(self,text="Options") #,fg=textLightColor,bg=baseColor) eframe.grid( row=5, column=1, sticky=W, columnspan=7, padx=10, pady=5 ) label = Label(eframe,text="Pipeline")#,fg=textLightColor,bg=baseColor) label.grid(row=3,column=0,sticky=W,padx=10,pady=5) PipelineLabels = ['Initial QC', 'Germline', 'Somatic Tumor-Normal', 'Somatic Tumor-Only'] Pipelines=["initialqcgenomeseq", "wgslow", 'wgs-somatic', 'wgs-somatic-tumoronly'] self.label2pipeline = { k:v for k,v in zip(PipelineLabels, Pipelines)} PipelineLabel = self.PipelineLabel = StringVar() Pipeline = self.Pipeline = StringVar() PipelineLabel.set(PipelineLabels[0]) #om = OptionMenu(eframe, Pipeline, *Pipelines, command=self.option_controller) om = OptionMenu(eframe, PipelineLabel, *PipelineLabels, command=self.option_controller) om.config()#bg = widgetBgColor,fg=widgetFgColor) om["menu"].config()#bg = widgetBgColor,fg=widgetFgColor) #om.pack(side=LEFT,padx=20,pady=5) om.grid(row=3,column=1,sticky=W,padx=10,pady=5)
class GuiGeneratorSelect(Frame): def __init__(self, parent, generators): Frame.__init__(self, parent) self.parent = parent self.pack() self._generators = generators self._generatorName = StringVar() self._generatorName.set(generators[0].getName()) self._generatorName.trace("w", self._switchSettings) self._generatorLbl = Label(self, text="Generator"); self._generatorLbl.pack(side=LEFT) param = (self, self._generatorName) + tuple(i.getName() for i in generators) self._generatorOpt = OptionMenu(*param) self._generatorOpt.pack(side=LEFT) self._switchSettings() def _switchSettings(self, *args): print("DBG: switch generator settings") for i in self._generators: if i.getName() == self._generatorName.get(): i.pack() self._generatorGui = i print("pack " + str(i.getName())) else: i.pack_forget() print("unpack " + str(i.getName())) def getCurrGeneratorGui(self): return self._generatorGui
def __init__(self, master, variable, value, *values, **kwargs): # TODO copy value instead of whole dict kwargsCopy=copy.copy(kwargs) if 'highlightthickness' in list(kwargs.keys()): del(kwargs['highlightthickness']) OptionMenu.__init__(self, master, variable, value, *values, **kwargs) self.config(highlightthickness=kwargsCopy.get('highlightthickness')) #self.menu=self['menu'] self.variable=variable self.command=kwargs.get('command')
def __init__(self, master, variable, value, *values, **kwargs): #get a copy of kwargs before OptionMenu.__init__ munges them kwargsCopy=copy.copy(kwargs) if 'highlightthickness' in list(kwargs.keys()): del(kwargs['highlightthickness']) OptionMenu.__init__(self, master, variable, value, *values, **kwargs) self.config(highlightthickness=kwargsCopy.get('highlightthickness')) #self.menu=self['menu'] self.variable=variable self.command=kwargs.get('command')
class GuiBasicSettings(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.pack() #Unit self.sizeUnits = {"Byte": 1, "KiB":1024, "MiB":1024**2, "GiB":1024**3} self._initFile() self._initSize() def _initFile(self): self._fileLbl = Label(self, text="File: ") self._fileTxt = Entry(self) self._fileTxt.insert(0, "/tmp/out.txt") self._fileBtn = Button(self, text="Create", command=self._callbackFun) self._fileLbl.grid(row=0, column=0) self._fileTxt.grid(row=0, column=1) self._fileBtn.grid(row=0, column=2) def _initSize(self): self._sizeLbl = Label(self, text="FileSize: ") self._sizeTxt = Entry(self) self._sizeTxt.insert(0, "1024") self._sizeVar = StringVar() self._sizeVar.set("Byte") #FIXME: replace "Byte" with variable sizeOptParam = (self, self._sizeVar) + tuple(self.sizeUnits.keys()) self._sizeOptMen = OptionMenu(*sizeOptParam) self._sizeLbl.grid(row=1, column=0) self._sizeTxt.grid(row=1, column=1) self._sizeOptMen.grid(row=1, column=2) def _callbackFun(self): print("_callbackBtn") self.outerCallback() def enableButton(self, enabled=True): if enabled: self._fileBtn.config(state="normal") else: self._fileBtn.config(state="disabled") def getFileName(self): return self._fileTxt.get() def getFileSize(self): mult = int(self.sizeUnits[self._sizeVar.get()]) val = int(self._sizeTxt.get()) return val * mult def setCallback(self, aCallback): self.outerCallback = aCallback
def _init_corpus_select(self, parent): innerframe = Frame(parent, background=self._BACKGROUND_COLOUR) self.var = StringVar(innerframe) self.var.set(self.model.DEFAULT_CORPUS) Label(innerframe, justify=LEFT, text=' Corpus: ', background=self._BACKGROUND_COLOUR, padx = 2, pady = 1, border = 0).pack(side='left') other_corpora = list(self.model.CORPORA.keys()).remove(self.model.DEFAULT_CORPUS) om = OptionMenu(innerframe, self.var, self.model.DEFAULT_CORPUS, command=self.corpus_selected, *self.model.non_default_corpora()) om['borderwidth'] = 0 om['highlightthickness'] = 1 om.pack(side='left') innerframe.pack(side='top', fill='x', anchor='n')
class AccountDialog(gui.tksimpledialog.Dialog): def __init__(self, parent, title="", login_name="", password="", path="", dx="dx11"): self.login_name = login_name self.password = password self.path = path self.dx = dx self.entry_ln = None self.variable = None self.entry_pw = None self.entry_path = None self.entry_dx = None super().__init__(parent, title) def body(self, master): Label(master, text="Login Name:").grid(row=0) Label(master, text="Password:"******"Eve Path:").grid(row=2) Label(master, text="DirectX:").grid(row=3) self.entry_ln = Entry(master) self.entry_pw = Entry(master, show="*") self.entry_path = Entry(master) self.variable = StringVar(master) self.variable.set(self.dx) self.entry_dx = OptionMenu(master, self.variable, "dx9", "dx11") self.entry_ln.insert(END, self.login_name) self.entry_pw.insert(END, self.password) self.entry_path.insert(END, self.path) # self.entry_path.bind("<FocusIn>", self.select_eve_path) self.entry_ln.grid(row=0, column=1) self.entry_pw.grid(row=1, column=1) self.entry_path.grid(row=2, column=1) self.entry_dx.grid(row=3, column=1) return self.entry_ln # def select_eve_path(self, event): # if event.widget == self.entry_path: # self.path # res = os.path.normpath(askdirectory(initialdir=self.path)) # self.path = res # self.entry_path.insert(END, res) def apply(self): login_name = self.entry_ln.get() password = self.entry_pw.get() path = self.entry_path.get() dx = self.variable.get() self.result = [login_name, password, path, dx]
def makelist(self): if havePMW: self.list = ComboBox(self.list_frame, selectioncommand = self.onSelChange, scrolledlist_items = self.files, ) self.list.grid(row=0, column=0, padx=0, pady=0, sticky="NEWS") self.list.component('entryfield').component('entry').configure(state = 'readonly', relief = 'raised') self.picked_name = self.list else: self.list = OptionMenu(*(self.list_frame, self.picked_name) + tuple(self.files)) self.list.grid(row=0, column=0, sticky="NEW") self.picked_name.trace("w", self.onSelChange)
def createWidgets(self): self.sayHi = tk.Button(self) self.sayHi["text"] = "Eds Button" self.sayHi["command"] = self.say_Hello self.sayHi.pack(side="bottom") for option in options: f = Frame(self) f.pack(side="bottom") Label(f, text=option).pack(side="left") v = StringVar(self) o = OptionMenu(f, v, *options.get(option).values()) o.pack(side="right") self.options[option] = v
def __init__(self, pipepanel, pipeline_name, *args, **kwargs) : PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs) self.info = None eframe = self.eframe = LabelFrame(self,text="Options") #,fg=textLightColor,bg=baseColor) eframe.grid( row=5, column=1, sticky=W, columnspan=7, padx=10, pady=5 ) label = Label(eframe,text="Pipeline:")#,fg=textLightColor,bg=baseColor) label.grid(row=3,column=0,sticky=W,padx=10,pady=5) Pipelines=["InitialChIPseqQC", "ChIPseq" ] Pipeline = self.Pipeline = StringVar() Pipeline.set(Pipelines[0]) om = OptionMenu(eframe, Pipeline, *Pipelines, command=self.option_controller) om.config()#bg = widgetBgColor,fg=widgetFgColor) om["menu"].config()#bg = widgetBgColor,fg=widgetFgColor) #om.pack(side=LEFT,padx=20,pady=5) om.grid(row=3,column=1,sticky=W,padx=20,pady=5) readtypes = ['Single', 'Paired'] self.readtype = readtype = StringVar() readtype.set(readtypes[0]) readtype_menu = OptionMenu(eframe, readtype, *readtypes) readtype_menu.grid(row=3, column=3, sticky=E, pady=5) readtype_label = Label(eframe, text="-end ") readtype_label.grid( row=3, column=4, stick=W, pady=5) self.add_info(eframe) self.option_controller() self.peakinfo_fn = 'peakcall.tab' self.contrast_fn = 'contrast.tab'
def __init__(self, pipepanel, pipeline_name, *args, **kwargs) : PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs) self.pairs = None eframe = self.eframe = LabelFrame(self,text="Options") #,fg=textLightColor,bg=baseColor) eframe.grid( row=5, column=1, sticky=W, columnspan=7, padx=10, pady=5 ) label = Label(eframe,text="Pipeline")#,fg=textLightColor,bg=baseColor) label.grid(row=3,column=0,sticky=W,padx=10,pady=5) PipelineLabels = ["Initial QC", "Germline", 'Somatic Tumor-Normal', 'Somatic Tumor-Only'] Pipelines=["initialqc", "exomeseq-germline", "exomeseq-somatic", "exomeseq-somatic-tumoronly"] self.label2pipeline = { k:v for k,v in zip(PipelineLabels, Pipelines)} Pipeline = self.Pipeline = StringVar() PipelineLabel = self.PipelineLabel = StringVar() self.Pipeline = StringVar() PipelineLabel.set(PipelineLabels[0]) om = OptionMenu(eframe, PipelineLabel, *PipelineLabels, command=self.option_controller) #om.config()#bg = widgetBgColor,fg=widgetFgColor) #om["menu"].config()#bg = widgetBgColor,fg=widgetFgColor) #om.pack(side=LEFT,padx=20,pady=5) om.grid(row=3,column=1,sticky=W,padx=10,pady=5) targetsL=Label(eframe, text="Target Capture Kit") #,fg=textLightColor,bg=baseColor) targetsL.grid(row=5,column=0,sticky=W,padx=10,pady=5) targetsE = Entry(eframe,textvariable=self.targetspath, width=50) if self.genome=="hg19": self.targetspath.set( "/data/CCBR_Pipeliner/db/PipeDB/lib/SS_v5_UTRs_hg19.bed" ) elif self.genome=="hg38": self.targetspath.set( "/data/CCBR_Pipeliner/db/PipeDB/lib/SS_v5_UTRs_hg38.bed" ) else: self.targetspath.set( "/data/CCBR_Pipeliner/db/PipeDB/lib/SureSelect_mm10.bed") targetsE.grid(row=5,column=1,columnspan=6,sticky=W,padx=10,pady=5) self.targetspath.trace('w', lambda a,b,c,x="targetspath":self.makejson(x)) label = Label (eframe, text = "By default, the path to the Agilent V5+UTR targets file is filled in here" ) label.grid(row=6, column=0, columnspan=5, sticky=W, padx=10, pady=5)
def createWidgets(self): self.title = Label(self, text="Image!", font=("Helvetica", 16)) self.title.grid(row=0, column=1, columnspan=2) self.open_file = Button(self) self.open_file['text'] = "OPEN" self.open_file["command"] = self.openfile self.open_file.grid(row=1, column=0) self.save_button = Button(self, text='SAVE', command=self.save_file) self.save_button.grid(row=1, column=1) self.canvas = Canvas(self, width=400, height=300) self.canvas.grid(row=2, column=0, rowspan=5, columnspan=4) self.convert_grayscale_button= Button(self) self.convert_grayscale_button['text'] = "Convert to\n grayscale" self.convert_grayscale_button["command"] = self.convert_grayscale self.convert_grayscale_button.grid(row=7, column=0) self.variable = StringVar(self) self.variable.set("gray") self.choose_color_menu = OptionMenu(self, self.variable,"gray", "blue", "green", "red") self.choose_color_menu['text'] = "Choose Color" self.choose_color_menu.grid(row=7, column=1) self.color_button = Button(self, text="COLOR", command=self.color_image) self.color_button.grid(row=7, column=2) self.quit_button = Button(self, text="QUIT", command=self.quit) self.quit_button.grid(row=7, column=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 createInterface(self): """ Tworzenie interfejsu - nieistotne dla idei zadania """ self.frame_choice = StringVar(self.parent) self.frame_choice.set(tuple(self.frames.keys())[0]) self.frame_choice.trace("w", self.createBike) self.frame_options = OptionMenu(self.parent,self.frame_choice, *self.frames.keys()) Label(self.parent,text="Rama:").pack() self.frame_options.pack(fill=BOTH, expand=1) self.fork_choice = StringVar(self.parent) self.fork_choice.set(tuple(self.forks.keys())[0]) self.fork_choice.trace("w", self.createBike) self.fork_options = OptionMenu(self.parent,self.fork_choice, *self.forks.keys()) Label(self.parent,text="Widelec:").pack() self.fork_options.pack(fill=BOTH, expand=1) self.wheelset_choice = StringVar(self.parent) self.wheelset_choice.set(tuple(self.wheelsets.keys())[0]) self.wheelset_choice.trace("w", self.createBike) self.wheelset_options = OptionMenu(self.parent,self.wheelset_choice, *self.wheelsets.keys()) Label(self.parent,text="Koła:").pack() self.wheelset_options.pack(fill=BOTH, expand=1) self.group_choice = StringVar(self.parent) self.group_choice.set(tuple(self.groups.keys())[0]) self.group_choice.trace("w", self.createBike) self.group_options = OptionMenu(self.parent,self.group_choice, *self.groups.keys()) Label(self.parent,text="Grupa osprzętu:").pack() self.group_options.pack(fill=BOTH, expand=1) self.components_choice = StringVar(self.parent) self.components_choice.set(tuple(self.components.keys())[0]) self.components_choice.trace("w", self.createBike) self.components_options = OptionMenu(self.parent,self.components_choice, *self.components.keys()) Label(self.parent,text="Komponenty:").pack() self.components_options.pack(fill=BOTH, expand=1)
def __init__(self, pipepanel, pipeline_name, *args, **kwargs) : PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs) self.pairs = None eframe = self.eframe = LabelFrame(self,text="Options") #,fg=textLightColor,bg=baseColor) eframe.grid( row=5, column=1, sticky=W, columnspan=7, padx=10, pady=5 ) label = Label(eframe,text="Pipeline")#,fg=textLightColor,bg=baseColor) label.grid(row=3,column=0,sticky=W,padx=10,pady=5) Pipelines=["initialqcgenomeseq","wgslow"] Pipeline = self.Pipeline = StringVar() Pipeline.set(Pipelines[0]) om = OptionMenu(eframe, Pipeline, *Pipelines, command=self.option_controller) om.config()#bg = widgetBgColor,fg=widgetFgColor) om["menu"].config()#bg = widgetBgColor,fg=widgetFgColor) #om.pack(side=LEFT,padx=20,pady=5) om.grid(row=3,column=1,sticky=W,padx=10,pady=5)
def __init__(self, master): Frame.__init__(self, master) self.dict = {'Asia': ['Japan', 'China', 'India'], 'Europe': ['Portugal', 'Switzerland', 'Ukraine']} self.var_a = StringVar(self) self.var_b = StringVar(self) self.var_a.trace('w', self.update_options) self.option_menu_a = OptionMenu(self, self.var_a, *self.dict.keys()) self.option_menu_a.pack(side="top") self.option_menu_a["width"] = 10 self.option_menu_b = OptionMenu(self, self.var_b, '') self.option_menu_b["width"] = 10 self.option_menu_b.pack(side="top") self.var_a.set('Asia')
def login(self, username, password): print('U: ' + username) self.username = username if username == '' or not all(char in string.ascii_letters+string.digits+'_-' for char in username): print('Please enter a username') self.entryUsername.focus_set() self.labelErrorPointer.grid(row=0, column=2) elif password == '': print('Please enter a password') self.entryPassword.focus_set() self.labelErrorPointer.grid(row=1, column=2) else: self.labelErrorPointer.grid_forget() print('Attempting login for ' + username) try: self.USERAGENT = username + ' practices Tkinter+PRAW mixing with utility by /u/GoldenSights.' self.r = praw.Reddit(self.USERAGENT) #self.r.login(username, password) print('Success') self.labelU.grid_forget() self.labelP.grid_forget() self.entryUsername.grid_forget() self.entryPassword.grid_forget() self.newbutton.grid_forget() self.quitbutton.grid_forget() self.usernamelabel = Label(self, text=username + ', Sending to /u/' + self.mailrecipient) self.usernamelabel.grid(row=0, column=0, columnspan=8) self.quitbutton.grid(row=900, column=0) self.labellist = [] self.entrylist = [] self.verifylist = [] self.misclist = [] self.optionDiscuss = "Discussion Flair + Crossposting" self.optionRegister = "Register a new Candidate" self.prevmode = self.optionDiscuss self.curmode = self.optionDiscuss self.optionvar = tkinter.StringVar(self) self.optionvar.trace("w",self.permaloop) self.optionvar.set(self.optionDiscuss) self.option = OptionMenu(self, self.optionvar, self.optionDiscuss, self.optionRegister, "three", "four") self.newbutton.unbind("<Return>") self.entryUsername.unbind("<Return>") self.entryPassword.unbind("<Return>") self.option.grid(row=1,column=0,columnspan=8,pady=8) self.updategui(True) except praw.errors.InvalidUserPass: pass print('Invalid username or password') self.entryPassword.delete(0,200) self.labelErrorPointer.grid(row=1, column=2)
def _initSize(self): self._sizeLbl = Label(self, text="FileSize: ") self._sizeTxt = Entry(self) self._sizeTxt.insert(0, "1024") self._sizeVar = StringVar() self._sizeVar.set("Byte") #FIXME: replace "Byte" with variable sizeOptParam = (self, self._sizeVar) + tuple(self.sizeUnits.keys()) self._sizeOptMen = OptionMenu(*sizeOptParam) self._sizeLbl.grid(row=1, column=0) self._sizeTxt.grid(row=1, column=1) self._sizeOptMen.grid(row=1, column=2)
def __init__(self, master, filemask='*.mln', default=None, allowNone=False, onselchange=None, directory='.'): self.allowNone = allowNone self.directory = directory self.list_frame = master self.onchange = onselchange if type(filemask) != list: filemask = [filemask] self.file_mask = filemask self.updateList() if havePMW: self.list = ComboBox(master, selectioncommand=onselchange, scrolledlist_items = self.files) self.list.component('entryfield').component('entry').configure(state = 'readonly', relief = 'raised') self.picked_name = self.list else: self.picked_name = StringVar() self.list = OptionMenu(*(master, self.picked_name) + tuple(self.files)) if onselchange is not None: self.picked_name.trace("w", self.onchange) if default is not None: self.select(default) else: self.select(self.files[0])
def __init__(self, parent, generators): Frame.__init__(self, parent) self.parent = parent self.pack() self._generators = generators self._generatorName = StringVar() self._generatorName.set(generators[0].getName()) self._generatorName.trace("w", self._switchSettings) self._generatorLbl = Label(self, text="Generator"); self._generatorLbl.pack(side=LEFT) param = (self, self._generatorName) + tuple(i.getName() for i in generators) self._generatorOpt = OptionMenu(*param) self._generatorOpt.pack(side=LEFT) self._switchSettings()
def _createUIElements(self): """ Create the main frame's UI elements """ # Top frame with the Load Directory controls frmLoadDir = Frame(self) frmLoadDir.pack(side=TOP, anchor=N, fill=X) self.sLoadDirVar = StringVar() lblLoadDir = Label(frmLoadDir, text="<Empty Directory>", textvariable=self.sLoadDirVar) lblLoadDir.pack(side=LEFT) btnLoadDir = Button(frmLoadDir, text="Load Directory", command=self._onBtnLoadDir) btnLoadDir.pack(side=RIGHT) # Dropdown with list of series (directories) detected frmSeriesSelector = Frame(self) frmSeriesSelector.pack(side=TOP, anchor=N, fill=X) self.sSeriesVar = StringVar() self.optSeries = OptionMenu(frmSeriesSelector, self.sSeriesVar, 'one', 'two', 'three', 'Loading', command=self._onBtnSeriesSelected) self.optSeries.pack(side=LEFT) # The two diff-style listboxes containing original and new episode list names frmListBoxes = Frame(self) frmListBoxes.pack(fill=BOTH, expand=1) self.lstOrgFiles = Listbox(frmListBoxes) self.lstOrgFiles.bind("<<ListboxSelect>>", self._onListOrgFiles) self.lstOrgFiles.pack(side=LEFT, fill=BOTH, expand=1, anchor=W) self.lstNewFiles = Listbox(frmListBoxes) self.lstNewFiles.bind("<<ListboxSelect>>", self._onListNewFiles) self.lstNewFiles.pack(side=RIGHT, fill=BOTH, expand=1, anchor=E) # Bottom buttons frmFinal = Frame(self) frmFinal.pack(side=BOTTOM, anchor=S, fill=X) btnRename = Button(frmFinal, text="Rename", command=self._onBtnRename) btnRename.pack(side=LEFT) btnExit = Button(frmFinal, text="Exit", command=self._onBtnExit) btnExit.pack(side=RIGHT)
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 body(self, master): Label(master, text="Login Name:").grid(row=0) Label(master, text="Password:"******"Eve Path:").grid(row=2) Label(master, text="DirectX:").grid(row=3) self.entry_ln = Entry(master) self.entry_pw = Entry(master, show="*") self.entry_path = Entry(master) self.variable = StringVar(master) self.variable.set(self.dx) self.entry_dx = OptionMenu(master, self.variable, "dx9", "dx11") self.entry_ln.insert(END, self.login_name) self.entry_pw.insert(END, self.password) self.entry_path.insert(END, self.path) # self.entry_path.bind("<FocusIn>", self.select_eve_path) self.entry_ln.grid(row=0, column=1) self.entry_pw.grid(row=1, column=1) self.entry_path.grid(row=2, column=1) self.entry_dx.grid(row=3, column=1) return self.entry_ln
def startwindow(self): # self.root=Tk() a=str(self.x+'x'+self.y) self.root.title('Wahrscheinlichkeinten & Simulation') self.root.geometry(a) self.g=Label(self.root,bg='white') self.g.place(x=0,y=0,width=self.x,height=self.y) # self.g.bind('<1>',self.optioncanged) self.lst1 = ['Marriage','Atom','BubbleGum','House_of_Cards','Lotto','SecretSanta','Coins'] self.var1 = StringVar(self.root) self.var1.set('Marriage') self.drop = OptionMenu(self.root,self.var1,*self.lst1) self.drop.config(font=('Arial',(30)),bg='white') self.drop['menu'].config(font=('calibri',(20)),bg='white') self.drop.pack(side=TOP) self.photo = PhotoImage(file='z1.gif') self.label = Label(image=self.photo,borderwidth=0) self.label.image = self.photo self.label.bind('<1>',self.MouseOneDown) self.label.place(y=0,x=int(self.x)-200) self.startbutton=Button(self.root,text='Start',font=('Arial',40),bg='#B4045F',borderwidth=5,command=self.startpressed) self.startbutton.place(x=0,y=int(self.y)-100,width=int(self.y)-200,height=100) self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed) self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
class ApplicationUI(tkinter.Frame): def __init__(self, master = None): master.minsize(width=550, height=450) master.maxsize(width=550, height=450) tkinter.Frame.__init__(self, master) self.grid() self.pack() self.createWidgets() def createWidgets(self): self.title = Label(self, text="Image!", font=("Helvetica", 16)) self.title.grid(row=0, column=1, columnspan=2) self.open_file = Button(self) self.open_file['text'] = "OPEN" self.open_file["command"] = self.openfile self.open_file.grid(row=1, column=0) self.save_button = Button(self, text='SAVE', command=self.save_file) self.save_button.grid(row=1, column=1) self.canvas = Canvas(self, width=400, height=300) self.canvas.grid(row=2, column=0, rowspan=5, columnspan=4) self.convert_grayscale_button= Button(self) self.convert_grayscale_button['text'] = "Convert to\n grayscale" self.convert_grayscale_button["command"] = self.convert_grayscale self.convert_grayscale_button.grid(row=7, column=0) self.variable = StringVar(self) self.variable.set("gray") self.choose_color_menu = OptionMenu(self, self.variable,"gray", "blue", "green", "red") self.choose_color_menu['text'] = "Choose Color" self.choose_color_menu.grid(row=7, column=1) self.color_button = Button(self, text="COLOR", command=self.color_image) self.color_button.grid(row=7, column=2) self.quit_button = Button(self, text="QUIT", command=self.quit) self.quit_button.grid(row=7, column=3) def openfile(self): self.filename = askopenfilename() self.pilImage = Image.open(self.filename) width, height = self.pilImage.size rate = 400/width new_width = 400 new_height = int(height*rate) print (new_width, new_height) self.pilImage=self.pilImage.resize((new_width, new_height), Image.ANTIALIAS) self.image = ImageTk.PhotoImage(self.pilImage) self.canvas.create_image(250, 200, image=self.image, anchor='center') def save_file(self): self.filename=asksaveasfilename() with open(self.filename, 'wb') as f: self.backwards.export(f.name, format="png") def quit(self): if hasattr(self, 'player'): os.remove(TEMP_FILE) root.destroy() def choose_color(self): self.color = self.variable.get() def color_image(self): if hasattr(self, 'grayImage'): self.choose_color() if self.color == 'blue': color = '#0000FF' elif self.color == 'red': color = '#FF0000' elif self.color == 'green': color = '#00FF00' self.coloredImg = ImageOps.colorize(self.grayImage, (0,0,0,0), color) self.image = ImageTk.PhotoImage(self.coloredImg) self.canvas.create_image(250, 200, image=self.image, anchor='center') else: tkMessageBox.showinfo('Warning', "Convert the file to grayscale first") def convert_grayscale(self): self.grayImage = self.pilImage.convert('L') self.image = ImageTk.PhotoImage(self.grayImage) self.canvas.create_image(250, 200, image=self.image, anchor='center')
def __init__(self,parent,title,*option_tuple,**configs): self.result = StringVar_WithHistory() self.result.set(title) OptionMenu.__init__(self,parent,self.result,*option_tuple,**configs)
def __init__(self, master): ''' Saves basic GUI buttons and data entries ''' self.master = master master.geometry("600x500") master.title("Enrichment Analysis Tool") # string variables from user input self.fsp = StringVar() # Formulation Sheet file Path self.ncp = StringVar() # Normalized Counts file Path self.sc = StringVar() # list of Sorted Cells self.dfp = StringVar() # Destination Folder Path self.tbp = StringVar() # Top/Bottom Percent self.op = StringVar() # Outliers Percentile self.opt = StringVar() # Average and sort by self.org = StringVar() # Organ self.ct = StringVar() # Cell Type Label(master, text="Enrichment Analysis", relief="solid", font=("arial", 16,\ "bold")).pack() Label(master, text="Formulation Sheet File Path", font=("arial", 12,\ "bold")).place(x=20, y=50) Button(master, text="Formulation sheet file", width=20, fg="green", font=("arial",\ 16), command=self.open_excel_file).place(x=370, y=48) Label(master, text="Normalized Counts CSV File Path", font=("arial", 12,\ "bold")).place(x=20, y=82) Button(master, text="Normalized counts file", width=20, fg="green", font=("arial",\ 16), command=self.open_csv_file).place(x=370, y=80) Label(master, text="List of Sorted Cells (separate by commas)", font=("arial", 12,\ "bold")).place(x=20, y=114) Entry(master, textvariable=self.sc).place(x=370, y=112) Label(master, text="Destination Folder Path", font=("arial", 12, "bold")).place(\ x=20, y=146) Entry(master, textvariable=self.dfp).place(x=370, y=144) Label(master, text="Top/Bottom Percent", font=("arial", 12, "bold")).place(x=20,\ y=178) Entry(master, textvariable=self.tbp).place(x=370, y=176) Label(master, text="(OPTIONAL: Default = 99.9) Outliers Percentile", font=("arial",\ 12, "bold")).place(x=20, y=212) Entry(master, textvariable=self.op).place(x=370, y=210) # Pick how user would like data sorted by Label(master, text="Sort by", font=("arial", 12, "bold")).place(x=20,\ y=244) options = ["Organ average","Cell type average", "Average of all samples"] org_droplist = OptionMenu(master, self.opt, *options) self.opt.set("Sorting method") org_droplist.config(width=15) org_droplist.place(x=370, y=246) Label(master, text="Select organ and/or cell type", font=("arial", 12, "bold")).place(x=20,\ y=276) # drop down menu organ = ["Liver", "Lung", "Spleen", "Heart", "Kidney", "Pancreas", "Marrow", "Muscle",\ "Brain", "Lymph Node", "Thymus"] cell_type = ["Hepatocytes", "Endothelial", "Kupffer", "Other Immune", "Dendritic",\ "B cells", "T cells", "Macrophages", "Epithelial", "Hematopoetic Stem Cells",\ "Fibroblasts", "Satellite Cells", "Other"] org_droplist = OptionMenu(master, self.org, *organ) self.org.set("Select Organ") org_droplist.config(width=15) org_droplist.place(x=220, y=278) ct_droplist = OptionMenu(master, self.ct, *cell_type) self.ct.set("Select Cell Type") ct_droplist.config(width=15) ct_droplist.place(x=400, y=278) Button(master, text="ENTER", width=16, fg="blue", font=("arial", 16),\ command=self.enrichment_analysis).place(x=150, y=310) Button(master, text="CANCEL", width=16, fg="blue", font=("arial", 16),\ command=exit1).place(x=300, y=310)
def init_project_frame(self): projframe = Frame(self) ###################### #The Project Entry Form # #Current design inherited from others #is very bad. It should have been made as #json or dictionary as is in this point #then the subsequent coding will be much #eaiser. #BK ###################### BS = StringVar() self.eprojectid = eprojectid = StringVar() self.eorganism = eorganism = StringVar() self.eanalyst = eanalyst = StringVar() self.epoc = epoc = StringVar() self.epi = epi = StringVar() self.euser = euser = StringVar() self.eflowcell = eflowcell = StringVar() self.eplatform = eplatform = StringVar() eplatform.set("Illumina") self.technique = technique = StringVar() editframe = Frame(self) editframe.grid(column=0, row=3, columnspan=3) projpanel1 = LabelFrame(editframe, text="Project Information") #,fg=textLightColor,bg=baseColor) projpanel1.pack(side=TOP, fill=X, padx=10, pady=5, expand=YES) pipeline_panel = LabelFrame(editframe, text="Global Settings") pipeline_panel.pack(side=TOP, fill=X, padx=10, pady=5, expand=YES) l = Label(pipeline_panel, text="Genome:") l.grid(row=1, column=1, sticky=W, padx=0, pady=5) l = Label(pipeline_panel, text="Pipeline Family:") l.grid(row=1, column=3, sticky=W, padx=0, pady=5) annotations = ['hg19', 'mm10'] self.annotation = annotation = StringVar() annotation.set(annotations[0]) #annotation.trace('w', lambda *_ :settargets(annotation) ) om = OptionMenu(pipeline_panel, annotation, *annotations) #, command=lambda _:makejson("refsets")) om.config() #bg = widgetBgColor,fg=widgetFgColor) om["menu"].config() #bg = widgetBgColor,fg=widgetFgColor) om.grid(row=1, column=2, sticky=W, padx=10, pady=10) pfamilys = ['exomeseq', 'rnaseq', 'genomeseq', 'mirseq', 'chipseq'] self.pfamily = pfamily = StringVar() pfamily.set('Select a pipeline') om = OptionMenu(pipeline_panel, pfamily, *pfamilys, command=self.set_pipeline) #, command=lambda _:makejson(pfamily.get())) om.config() #bg = widgetBgColor,fg=widgetFgColor) om["menu"].config() #bg = widgetBgColor,fg=widgetFgColor) om.grid(row=1, column=4, sticky=W, padx=10, pady=5) #add_button = Button( pipeline_panel, # text="Set a pipeline", # command=self.add_pipeline # ) #add_button.grid(row=1, column=5, sticky=W, padx=10, pady=5) self.notebook = notebook = Notebook(editframe) self.pipelineframe = None #the pipeline frame in the notebook frame! projpanel2 = Frame(notebook) #,fg=textLightColor,bg=baseColor) projpanel2.pack(side=LEFT, fill=BOTH, padx=10, pady=5, expand=YES) notebook.add(projpanel2, text="Project Description") notebook.pack(side=LEFT, fill=BOTH, padx=10, pady=5, expand=YES) Dscrollbar = Scrollbar(projpanel2) Dscrollbar.grid(row=2, column=4, rowspan=40) self.description = description = Text( projpanel2, width=75, height=28, #bg=commentBgColor, #fg=commentFgColor, font=("nimbus mono bold", "10"), yscrollcommand=Dscrollbar.set) description.delete("1.0", END) description.insert(INSERT, "Enter CCBR Project Description and Notes here.") #description.bind('<FocusOut>',lambda _:makejson("none")) description.grid(row=2, column=3, sticky="e", padx=10, pady=5) Dscrollbar['command'] = description.yview L = Label(projpanel1, text="Project Id", anchor="ne") #,bg=baseColor,fg=textLightColor) E = Entry( projpanel1, bd=2, width=20, #bg=entryBgColor, #fg=entryFgColor, textvariable=eprojectid) #L.pack(pady=5,padx=5) #E.pack(pady=1,padx=5) L.grid(row=0, column=0, sticky=W, padx=10, pady=5) E.grid(row=0, column=2, sticky=W, padx=10, pady=5) eprojectid.set("project") #eprojectid.trace('w', makejson) L2 = Label(projpanel1, text="(Examples: CCBR-nnn,Labname or short project name)", anchor="ne") #,bg="firebrick",fg="white") L2.grid(row=0, column=3, padx=10, pady=5, sticky="w") L = Label(projpanel1, text="Email address", anchor="ne") #,bg=baseColor,fg=textLightColor) E = Entry( projpanel1, bd=2, width=20, #bg=entryBgColor, #fg=entryFgColor, textvariable=euser) L3 = Label(projpanel1, text="(Mandatory field: must use @nih.gov email address)", anchor="ne") L3.grid(row=1, column=3, padx=10, pady=5, sticky="w") L.grid(row=1, column=0, sticky=W, padx=10, pady=5) E.grid(row=1, column=2, sticky=W, padx=10, pady=5) #euser.trace('w', makejson) L = Label(projpanel1, text="Flow Cell ID", anchor="ne") E = Entry(projpanel1, bd=2, width=20, textvariable=eflowcell) #, bg=entryBgColor) L4 = Label( projpanel1, text="(Examples: FlowCellID, Labname, date or short project name)", anchor="ne") #,bg="firebrick",fg="white") L4.grid(row=2, column=3, padx=10, pady=5, sticky="w") L.grid(row=2, column=0, sticky=W, padx=10, pady=5) E.grid(row=2, column=2, sticky=W, padx=10, pady=5) eflowcell.set("stats") #eflowcell.trace('w', makejson) Projscrollbar = Scrollbar(projframe) Projscrollbar.grid(row=2, column=4, rowspan=30) self.jsonconf = jsonconf = Text( projframe, width=80, height=30, #bg=projectBgColor, #fg=projectFgColor, font=("nimbus mono bold", "11"), yscrollcommand=Projscrollbar.set) Projscrollbar['command'] = jsonconf.yview jsonconf.grid(row=3, column=0, sticky="e", padx=10, pady=5)
def __init__(self, root): self.root = root # membuat kolom untuk menentukan data yang akan di cari Label(self.root, text="Cari Berdasarkan : ").place(x=10, y=10) # membuat menu dropdown untuk mencari data berdasarkan katagori application.set_gui.variable = StringVar(self.root) application.set_gui.variable.set(application.katagori[0]) application.set_gui.input_katagori = OptionMenu( self.root, application.set_gui.variable, *application.katagori) application.set_gui.input_katagori.place(x=10, y=30) # membuat kolom untuk cari Label(self.root, text="Keyword : ").place(x=10, y=65) application.set_gui.input_key = Entry(self.root) application.set_gui.input_key.place(x=10, y=85) #menangani keypress di kolom cari application.set_gui.input_key.bind( '<Key>', application.command().key_search) # menampilkan tombol utuk memulai pencarian Button(self.root, text="Cari", command=application.command().cari_data).place(x=10, y=110) # membuat table self.buat_table() # membuat fungsi perpindahan halaman # membuat button untuk tombol kembali application.set_gui.btn_back = Button(self.root) application.set_gui.btn_back['text'] = "<< Kembali" application.set_gui.btn_back['state'] = "disable" application.set_gui.btn_back['command'] = application.command( ).prev_halaman application.set_gui.btn_back.place(x=400, y=390) # membuat kolom halaman application.set_gui.txt_halaman = Entry(self.root) application.set_gui.txt_halaman['width'] = 4 application.set_gui.txt_halaman.place(x=510, y=395) application.set_gui.txt_halaman.insert(0, "0") # menangani keypress di kolom halaman application.set_gui.txt_halaman.bind( '<Key>', application.command().key_got_to) Label(self.root, text=" Dari : ").place(x=540, y=395) application.set_gui.txt_jml_halaman = Label(self.root) application.set_gui.txt_jml_halaman['text'] = "1" application.set_gui.txt_jml_halaman.place(x=580, y=395) Label(self.root, text=" Halaman").place(x=630, y=395) # membuat tombol utnuk next application.set_gui.btn_next = Button(self.root) application.set_gui.btn_next['text'] = "Next >>" application.set_gui.btn_next['state'] = "disable" application.set_gui.btn_next['command'] = application.command( ).next_halaman application.set_gui.btn_next.place(x=715, y=390) # membuat kolom utuk setting jml data yang ditampilkan Label(self.root, text="Jumlah data yang ditampilkan : ").place(x=10, y=390) application.set_gui.txt_tampil = Entry(self.root) application.set_gui.txt_tampil.insert(0, "10") application.set_gui.txt_tampil['width'] = 6 application.set_gui.txt_tampil.place(x=220, y=390) #menangani keypress di kolom tampil application.set_gui.txt_tampil.bind( '<Key>', application.command().key_search) # copyrigth Label(self.root, text="Create By : Safrudin").place(x=500, y=440) Label(self.root, text="Email : [email protected]").place(x=445, y=460)
#label2 = tk.Label(root, text=type(x1)) #ask_display.create_window(200, 250, window=label2) #else: label2 = tk.Label(root, text="") ask_display.create_window(200, 250, window=label2) obstaculos = int(x1) if x2 == "Small" and x1 < 29: rows = 10 root.destroy() elif x2 == "Medium" and x1 < 150: rows = 20 root.destroy() elif x2 == "Large(slower)" and x1 < 400: rows = 50 root.destroy() else: label2 = tk.Label(root, text="Number of obstacles exceeded") ask_display.create_window(200, 250, window=label2) variable = StringVar(root) variable.set("Small") menu = OptionMenu(root, variable, "Small", "Medium", "Large(slower)") ask_display.create_window(200, 200, window=menu) button1 = tk.Button(text='Submit', command=get_input) ask_display.create_window(200, 275, window=button1) root.mainloop() main()
def init_window(self): # changing the title of our master widget self.root.title("EnergyPlus Regression Tool 2") self.root.protocol("WM_DELETE_WINDOW", self.client_exit) # create the menu menu = Menu(self.root) self.root.config(menu=menu) file_menu = Menu(menu) file_menu.add_command(label="Exit", command=self.client_exit) menu.add_cascade(label="File", menu=file_menu) # main notebook holding everything main_notebook = ttk.Notebook(self.root) # run configuration pane_run = Frame(main_notebook) group_build_dir_1 = LabelFrame(pane_run, text="Build Directory 1") group_build_dir_1.pack(fill=X, padx=5) self.build_dir_1_button = Button(group_build_dir_1, text="Change...", command=self.client_build_dir_1) self.build_dir_1_button.grid(row=1, column=1, sticky=W) self.build_dir_1_label = Label(group_build_dir_1, textvariable=self.build_dir_1_var) self.build_dir_1_label.grid(row=1, column=2, sticky=E) group_build_dir_2 = LabelFrame(pane_run, text="Build Directory 2") group_build_dir_2.pack(fill=X, padx=5) self.build_dir_2_button = Button(group_build_dir_2, text="Change...", command=self.client_build_dir_2) self.build_dir_2_button.grid(row=1, column=1, sticky=W) self.build_dir_2_label = Label(group_build_dir_2, textvariable=self.build_dir_2_var) self.build_dir_2_label.grid(row=1, column=2, sticky=E) group_run_options = LabelFrame(pane_run, text="Run Options") group_run_options.pack(fill=X, padx=5) Label(group_run_options, text="Number of threads for suite: ").grid(row=1, column=1, sticky=E) self.num_threads_spinner = Spinbox(group_run_options, from_=1, to_=48) # validate later self.num_threads_spinner.grid(row=1, column=2, sticky=W) Label(group_run_options, text="Test suite run configuration: ").grid(row=2, column=1, sticky=E) self.run_period_option_menu = OptionMenu(group_run_options, self.run_period_option, *RunOptions.get_all()) self.run_period_option_menu.grid(row=2, column=2, sticky=W) Label(group_run_options, text="Minimum reporting frequency: ").grid(row=3, column=1, sticky=E) self.reporting_frequency_option_menu = OptionMenu( group_run_options, self.reporting_frequency, *ReportingFrequency.get_all() ) self.reporting_frequency_option_menu.grid(row=3, column=2, sticky=W) main_notebook.add(pane_run, text='Configuration') # now let's set up a list of checkboxes for selecting IDFs to run pane_idfs = Frame(main_notebook) group_idf_tools = LabelFrame(pane_idfs, text="IDF Selection Tools") group_idf_tools.pack(fill=X, padx=5) self.idf_select_all_button = Button( group_idf_tools, text="Refresh", command=self.client_idf_refresh ) self.idf_select_all_button.pack(side=LEFT, expand=1) self.idf_select_all_button = Button( group_idf_tools, text="Select All", command=self.idf_select_all ) self.idf_select_all_button.pack(side=LEFT, expand=1) self.idf_deselect_all_button = Button( group_idf_tools, text="Deselect All", command=self.idf_deselect_all ) self.idf_deselect_all_button.pack(side=LEFT, expand=1) self.idf_select_n_random_button = Button( group_idf_tools, text="Select N Random", command=self.idf_select_random ) self.idf_select_n_random_button.pack(side=LEFT, expand=1) group_full_idf_list = LabelFrame(pane_idfs, text="Full IDF List") group_full_idf_list.pack(fill=X, padx=5) scrollbar = Scrollbar(group_full_idf_list) self.full_idf_listbox = Listbox(group_full_idf_list, yscrollcommand=scrollbar.set) self.full_idf_listbox.bind('<Double-1>', self.idf_move_to_active) self.full_idf_listbox.pack(fill=BOTH, side=LEFT, expand=True) scrollbar.pack(fill=Y, side=LEFT) scrollbar.config(command=self.full_idf_listbox.yview) self.move_idf_to_active_button = Button( pane_idfs, text="↓ Add to Active List ↓", command=self.idf_move_to_active ) self.move_idf_to_active_button.pack(side=TOP, fill=X, expand=True) self.remove_idf_from_active_button = Button( pane_idfs, text="↑ Remove from Active List ↑", command=self.idf_remove_from_active ) self.remove_idf_from_active_button.pack(side=TOP, fill=X, expand=True) group_active_idf_list = LabelFrame(pane_idfs, text="Active IDF List") group_active_idf_list.pack(fill=X, padx=5) scrollbar = Scrollbar(group_active_idf_list) self.active_idf_listbox = Listbox(group_active_idf_list, yscrollcommand=scrollbar.set) self.active_idf_listbox.bind('<Double-1>', self.idf_remove_from_active) self.active_idf_listbox.pack(fill=BOTH, side=LEFT, expand=True) scrollbar.pack(fill=Y, side=LEFT) scrollbar.config(command=self.active_idf_listbox.yview) self.build_idf_listing(initialize=True) main_notebook.add(pane_idfs, text="IDF Selection") # set up a scrolled listbox for the log messages frame_log_messages = Frame(main_notebook) group_log_messages = LabelFrame(frame_log_messages, text="Log Message Tools") group_log_messages.pack(fill=X, padx=5) Button(group_log_messages, text="Clear Log Messages", command=self.clear_log).pack(side=LEFT, expand=1) Button(group_log_messages, text="Copy Log Messages", command=self.copy_log).pack(side=LEFT, expand=1) scrollbar = Scrollbar(frame_log_messages) self.log_message_listbox = Listbox(frame_log_messages, yscrollcommand=scrollbar.set) self.add_to_log("Program started!") self.log_message_listbox.pack(fill=BOTH, side=LEFT, expand=True) scrollbar.pack(fill=Y, side=LEFT) scrollbar.config(command=self.log_message_listbox.yview) main_notebook.add(frame_log_messages, text="Log Messages") # set up a tree-view for the results frame_results = Frame(main_notebook) scrollbar = Scrollbar(frame_results) self.results_tree = ttk.Treeview(frame_results, columns=("Base File", "Mod File", "Diff File")) self.results_tree.heading("#0", text="Results") self.results_tree.column('#0', minwidth=200, width=200) self.results_tree.heading("Base File", text="Base File") self.results_tree.column("Base File", minwidth=100, width=100) self.results_tree.heading("Mod File", text="Mod File") self.results_tree.column("Mod File", minwidth=100, width=100) self.results_tree.heading("Diff File", text="Diff File") self.results_tree.column("Diff File", minwidth=100, width=100) self.build_results_tree() self.results_tree.pack(fill=BOTH, side=LEFT, expand=True) scrollbar.pack(fill=Y, side=LEFT) scrollbar.config(command=self.results_tree.yview) main_notebook.add(frame_results, text="Run Control and Results") # pack the main notebook on the window main_notebook.pack(fill=BOTH, expand=1) # status bar at the bottom frame_status = Frame(self.root) self.run_button = Button(frame_status, text="Run", bg=self.run_button_color, command=self.client_run) self.run_button.pack(side=LEFT, expand=0) self.stop_button = Button(frame_status, text="Stop", command=self.client_stop, state='disabled') self.stop_button.pack(side=LEFT, expand=0) self.progress = ttk.Progressbar(frame_status) self.progress.pack(side=LEFT, expand=0) label = Label(frame_status, textvariable=self.label_string) self.label_string.set("Initialized") label.pack(side=LEFT, anchor=W) frame_status.pack(fill=X)
from tkinter import Tk, Label, Button, Canvas, Entry, TOP, X, mainloop, LEFT, StringVar, OptionMenu from functools import partial master = Tk() value = StringVar(master) value.set('N/A') m = OptionMenu(master, value, *[0, 1, 2]) m.pack() def callback(result_var=None): print(result_var.get()) callback_no_args = partial(callback, result_var=value) b = Button(master, text="Get Dropdown value", command=callback_no_args) b.pack() # l = Label(master, textvariable = value) # l.pack() mainloop() # Goal: Stateful application - 2 texts fields, button to add them
def MP3PLAYING(): #Main interface which initiates the MP3 player global seek global oc2 global listofsongs global listofsongs2 global songlist global songname global len1 global time1 songname=Label(root5,textvariable=m,width=90,bg="#220047",fg="#CE9141",font=("roboto",13)) songname.place(x=-120,y=450) pygame.mixer.init() songlist=Listbox(root5,selectbackground="#CE9141",height=14,width=60,relief=GROOVE,bd=3,bg="#220047",fg="#CE9141",font=("fixedsys",10)) songlist.place(x=20,y=205) a=StringVar() a.set("Default") oc=StringVar(root5) oc.set("Select") listofsongs2.reverse() for h in listofsongs2: songlist.insert(0,h) listofsongs2.reverse() #currentsong=Label(root5,text="Current Song:",font=("georgia",15),bg="#220047",fg="#CE9141") #currentsong.place(x=230,y=500) orderofsongs=Label(root5,text="Your Playlist",font=("georgia",15),bg="#220047",fg="#CE9141") orderofsongs.place(x=40,y=170) startbutton=Button(root5,text="Start",bg="#CE9141",relief=RAISED,fg="#220047",bd=1,activebackground="#220047",activeforeground="#CE9141",font=("fixedsys",10)) startbutton.place(x=400,y=480) playnext=Button(root5,text=">>>",bg="#CE9141",relief=RAISED,fg="#220047",bd=1,activebackground="#220047",activeforeground="#CE9141",font=("fixedsys",10)) playnext.place(x=355,y=480) playbefore=Button(root5,text="<<<",bg="#CE9141",fg="#220047",relief=RAISED,bd=1,activebackground="#220047",activeforeground="#CE9141",font=("fixedsys",10)) playbefore.place(x=190,y=480) stop=Button(root5,text="Stop",bg="#CE9141",fg="#220047",relief=RAISED,bd=1,activebackground="#220047",activeforeground="#CE9141",font=("fixedsys",10)) stop.place(x=137,y=480) pause=Button(root5,text="Pause",bg="#CE9141",fg="#220047",relief=RAISED,bd=1,activebackground="#220047",activeforeground="#CE9141",font=("fixedsys",10)) pause.place(x=237,y=480) play=Button(root5,text="Play",bg="#CE9141",fg="#220047",relief=RAISED,bd=1,activebackground="#220047",activeforeground="#CE9141",font=("fixedsys",10)) play.place(x=300,y=480) volume1=Label(root5,text="Volume",font=("georgia",11),fg="#CE9141",bg="#220047") volume1.place(x=533,y=190) selection=MP3(listofsongs[0]) len1=selection.info.length len1//=1 seek=Scale(root5,from_=0,to=len1,orient=HORIZONTAL,length=400,cursor="cross",bd=1,bg="#CE9141",fg="#220047",activebackground="#220047",command=seek1) seek.place(x=100,y=530) oc1=StringVar(root5) oc1.set("Welcome"+ " "+ user11) options=["Home","Back","Close"] dropdown=OptionMenu(root5,oc1,*options,command=choice1) dropdown.configure(font=("georgia",15),fg="#220047",bg="#CE9141",activebackground="#CE9141",activeforeground="#220047") dropdown.place(x=200,y=110) oc2=StringVar(root5) oc2.set("Options") options1=["Shuffle[]","Random[?]","Delete[-]","Add[+]"] dropdown1=OptionMenu(root5,oc2,*options1,command=choice2) dropdown1.configure(text="Options",font=("georgia",10),fg="#220047",bg="#CE9141",activebackground="#220047",activeforeground="#CE9141") dropdown1.place(x=500,y=50) volume2=Scale(root5,from_=100,to=0,orient=VERTICAL,length=210,cursor="cross",bd=1,bg="#CE9141",fg="#220047",activebackground="#220047",command=volume) volume2.set(100) volume2.place(x=540,y=215) pygame.mixer.music.set_volume(100) if conditionalval==2: saveplaylist=Button(root5,text="Save",bg="#CE9141",fg="#220047",relief=RAISED,bd=1,activebackground="#220047",activeforeground="#CE9141",font=("fixedsys",10)) saveplaylist.place(x=40,y=560) saveplaylist.bind("<Button>",createplay) elif conditionalval==3: orderofsongs.place_forget() defer="Your Playlist :"+" "+appendlist orderofsongs=Label(root5,text=defer,font=("georgia",15),bg="#220047",fg="#CE9141") orderofsongs.place(x=40,y=170) else: print("okay") """time1=IntVar() time1.set(0) timer1= Label(root5, textvar= time1,font=("georgia",8),fg="#220047",bg="#CE9141") timer1.place(x= 250, y= 550)""" pause.bind("<Button-1>",pausesong) play.bind("<Button-1>",unpause) startbutton.bind("<Button-1>",playmusic) playnext.bind("<Button-1>",nextsong) playbefore.bind("<Button-1>",previous) stop.bind("<Button-1>",stopmusic) pygame.mixer.music.load(listofsongs[0]) pygame.mixer.music.play() updatename() """timer()
entry_2.place(x=270, y=180) label_3 = Label(root, text="Stream", width=20, font=("bold", 10)) label_3.place(x=90, y=230) Radiobutton(root, text="DS", padx=4, variable=streamm, value=1)\ .place(x=270, y=230) Radiobutton(root, text="Engineering", padx=5, variable=streamm, value=2)\ .place(x=321, y=230) label_4 = Label(root, text="Experience", width=20, font=("bold", 10)) label_4.place(x=90, y=280) range = ['<1', '1-2', '2-4', '4-6', '6-10', '10+'] droplist = OptionMenu(root, year, *range) droplist.config(width=15) year.set('Years of Experience') droplist.place(x=270, y=280) label_4 = Label(root, text="Skills", width=20, font=("bold", 10)) label_4.place(x=90, y=330) Checkbutton(root, text="SQL", variable=SQL).place(x=270, y=330) Checkbutton(root, text="Python", variable=Python).place(x=320, y=330) Checkbutton(root, text="Spark", variable=spark).place(x=270, y=350) Checkbutton(root, text="EDA", variable=EDA).place(x=332, y=350) Button(root, text='Submit', width=20, bg='black', fg='white',
def __init__(self, root, install_config): """Initializer for the EditSingleModuleGUI class """ self.root = root self.install_config = install_config self.master = Toplevel() self.master.title('Edit Single Module') self.master.resizable(False, False) self.smallFont = tkFont.Font(family="Helvetica", size=10) self.largeFont = tkFont.Font(family="Helvetica", size=14) self.url_type_var = StringVar() self.url_type_var.set('GIT_URL') self.legal_url_types = ['GIT_URL', 'WGET_URL'] self.edit_name_var = StringVar() self.edit_name_var.set(self.install_config.get_module_list()[0].name) self.legal_names = [] for module in self.install_config.get_module_list(): self.legal_names.append(module.name) self.clone_check = BooleanVar() self.clone_check.set(False) self.build_check = BooleanVar() self.build_check.set(False) self.package_check = BooleanVar() self.package_check.set(False) self.viewFrame = Frame(self.master, relief=GROOVE, padx=10, pady=10) self.viewFrame.pack() Button(self.viewFrame, text='Save Changes', command=self.applyChanges, width=10).grid(row=0, column=0, columnspan=1, padx=5, pady=5) Button(self.viewFrame, text='Return', command=self.exitWindow, width=10).grid(row=0, column=1, columnspan=1, padx=5, pady=5) Button(self.viewFrame, text='Reload', command=self.reloadPanel, width=10).grid(row=0, column=2, columnspan=1, padx=5, pady=5) Label(self.viewFrame, text='Edit individual module:').grid(row=1, column=0, columnspan=1, padx=5, pady=5) self.module_dropdown = ttk.Combobox(self.viewFrame, textvariable=self.edit_name_var, values=self.legal_names) self.module_dropdown.grid(row=1, column=1) self.edit_name_var.trace('w', self.reloadPanelWrapper) Label(self.viewFrame, text='Version:').grid(row=3, column=0, padx=5, pady=5) self.version_box = Text(self.viewFrame, height=1, width=40, padx=3, pady=3) self.version_box.grid(row=3, column=1, columnspan=2) Label(self.viewFrame, text='Relative Install Path:').grid(row=4, column=0, padx=5, pady=5) self.rel_path_box = Text(self.viewFrame, height=1, width=40, padx=3, pady=3) self.rel_path_box.grid(row=4, column=1, columnspan=2) Label(self.viewFrame, text='Url Type:').grid(row=5, column=0, padx=5, pady=5) self.url_type_dropdown = OptionMenu(self.viewFrame, self.url_type_var, *self.legal_url_types) self.url_type_dropdown.grid(row=5, column=1) Label(self.viewFrame, text='Url:').grid(row=6, column=0, padx=5, pady=5) self.url_box = Text(self.viewFrame, height=1, width=40, padx=3, pady=3) self.url_box.grid(row=6, column=1, columnspan=2) Label(self.viewFrame, text='Repository:').grid(row=7, column=0, padx=5, pady=5) self.repository_box = Text(self.viewFrame, height=1, width=40, padx=3, pady=3) self.repository_box.grid(row=7, column=1, columnspan=2) #self.clone_build_label = Label(self.viewFrame, text = 'Clone - Build - Package:').grid(row = 8, column = 0, padx = 5, pady = 5) self.clone_button = Checkbutton(self.viewFrame, text='Clone', onvalue=True, offvalue=False, variable=self.clone_check) self.build_button = Checkbutton(self.viewFrame, text='Build', onvalue=True, offvalue=False, variable=self.build_check) self.package_button = Checkbutton(self.viewFrame, text='Package', onvalue=True, offvalue=False, variable=self.package_check) self.clone_button.grid(row=8, column=0, padx=3, pady=3) self.build_button.grid(row=8, column=1, padx=3, pady=3) self.package_button.grid(row=8, column=2, padx=3, pady=3) self.master.mainloop()
class EditSingleModuleGUI: """Class representing a window for adding a new install module to loaded config Attributes ---------- root : InstallSynAppsGUI The top TK instance that opened this window master : Toplevel The main container Tk object viewFrame Tk frame that contains all widgets url_type_var/edit_name_var : StringVar tied to url type and list of module names respectively legal_url_types/legal_names : list of str lists legal url types and list of module names clone_check/build_check : BooleanVar boolean variables that track whether or not to build the module module_dropdown : Checkbox A dropdown menu for selecting which module to edit applyButton/exitWindowButton : Button button that runs the apply method (and exits) name_box/version_box/rel_path_box/url_box/repository_box : Text Boxes for editing certain module features. url_type_dropdown : OptionMenu dropdown for url types clone_button/build_button : CheckButton toggles to clone/build """ def __init__(self, root, install_config): """Initializer for the EditSingleModuleGUI class """ self.root = root self.install_config = install_config self.master = Toplevel() self.master.title('Edit Single Module') self.master.resizable(False, False) self.smallFont = tkFont.Font(family="Helvetica", size=10) self.largeFont = tkFont.Font(family="Helvetica", size=14) self.url_type_var = StringVar() self.url_type_var.set('GIT_URL') self.legal_url_types = ['GIT_URL', 'WGET_URL'] self.edit_name_var = StringVar() self.edit_name_var.set(self.install_config.get_module_list()[0].name) self.legal_names = [] for module in self.install_config.get_module_list(): self.legal_names.append(module.name) self.clone_check = BooleanVar() self.clone_check.set(False) self.build_check = BooleanVar() self.build_check.set(False) self.package_check = BooleanVar() self.package_check.set(False) self.viewFrame = Frame(self.master, relief=GROOVE, padx=10, pady=10) self.viewFrame.pack() Button(self.viewFrame, text='Save Changes', command=self.applyChanges, width=10).grid(row=0, column=0, columnspan=1, padx=5, pady=5) Button(self.viewFrame, text='Return', command=self.exitWindow, width=10).grid(row=0, column=1, columnspan=1, padx=5, pady=5) Button(self.viewFrame, text='Reload', command=self.reloadPanel, width=10).grid(row=0, column=2, columnspan=1, padx=5, pady=5) Label(self.viewFrame, text='Edit individual module:').grid(row=1, column=0, columnspan=1, padx=5, pady=5) self.module_dropdown = ttk.Combobox(self.viewFrame, textvariable=self.edit_name_var, values=self.legal_names) self.module_dropdown.grid(row=1, column=1) self.edit_name_var.trace('w', self.reloadPanelWrapper) Label(self.viewFrame, text='Version:').grid(row=3, column=0, padx=5, pady=5) self.version_box = Text(self.viewFrame, height=1, width=40, padx=3, pady=3) self.version_box.grid(row=3, column=1, columnspan=2) Label(self.viewFrame, text='Relative Install Path:').grid(row=4, column=0, padx=5, pady=5) self.rel_path_box = Text(self.viewFrame, height=1, width=40, padx=3, pady=3) self.rel_path_box.grid(row=4, column=1, columnspan=2) Label(self.viewFrame, text='Url Type:').grid(row=5, column=0, padx=5, pady=5) self.url_type_dropdown = OptionMenu(self.viewFrame, self.url_type_var, *self.legal_url_types) self.url_type_dropdown.grid(row=5, column=1) Label(self.viewFrame, text='Url:').grid(row=6, column=0, padx=5, pady=5) self.url_box = Text(self.viewFrame, height=1, width=40, padx=3, pady=3) self.url_box.grid(row=6, column=1, columnspan=2) Label(self.viewFrame, text='Repository:').grid(row=7, column=0, padx=5, pady=5) self.repository_box = Text(self.viewFrame, height=1, width=40, padx=3, pady=3) self.repository_box.grid(row=7, column=1, columnspan=2) #self.clone_build_label = Label(self.viewFrame, text = 'Clone - Build - Package:').grid(row = 8, column = 0, padx = 5, pady = 5) self.clone_button = Checkbutton(self.viewFrame, text='Clone', onvalue=True, offvalue=False, variable=self.clone_check) self.build_button = Checkbutton(self.viewFrame, text='Build', onvalue=True, offvalue=False, variable=self.build_check) self.package_button = Checkbutton(self.viewFrame, text='Package', onvalue=True, offvalue=False, variable=self.package_check) self.clone_button.grid(row=8, column=0, padx=3, pady=3) self.build_button.grid(row=8, column=1, padx=3, pady=3) self.package_button.grid(row=8, column=2, padx=3, pady=3) self.master.mainloop() def reloadPanelWrapper(self, *args): """A wrapper function for reloading the panel """ self.reloadPanel() def reloadPanel(self): """Reloads panel to defaults """ self.version_box.delete('1.0', END) self.rel_path_box.delete('1.0', END) self.url_box.delete('1.0', END) self.repository_box.delete('1.0', END) for module in self.install_config.get_module_list(): if module.name == self.edit_name_var.get(): self.version_box.insert(INSERT, module.version) self.rel_path_box.insert(INSERT, module.rel_path) self.url_type_var.set(module.url_type) self.url_box.insert(INSERT, module.url) self.repository_box.insert(INSERT, module.repository) clone_bool = False build_bool = False package_bool = False if module.clone == 'YES': clone_bool = True if module.build == 'YES': build_bool = True if module.package == 'YES': package_bool = True self.clone_check.set(clone_bool) self.build_check.set(build_bool) self.package_check.set(package_bool) def applyChanges(self): """Function that reads all of the inputted information and edits the module parameters based on these inputs. Then refreshes the data model to account for the new changes. """ version = self.version_box.get('1.0', END).strip() rel_path = self.rel_path_box.get('1.0', END).strip() url_type = self.url_type_var.get() url = self.url_box.get('1.0', END).strip() repo = self.repository_box.get('1.0', END).strip() clone = self.clone_check.get() build = self.build_check.get() package = self.package_check.get() clone_str = 'NO' build_str = 'NO' package_str = 'NO' if clone: clone_str = 'YES' if build: build_str = 'YES' if package: package_str = 'YES' if len(version) == 0: version = 'master' if len(rel_path) == 0: self.root.showErrorMessage( 'Edit Module Error', 'ERROR - Please enter a valid relative path.', force_popup=True) return if len(url) == 0 or len(repo) == 0: self.root.showErrorMessage( 'Edit Module Error', 'ERROR - Please enter a url and repository.', force_popup=True) if not url.endswith('/'): url = url + '/' existing_modules = self.install_config.get_module_list() for module in existing_modules: if module.name == self.edit_name_var.get(): module.version = version module.rel_path = rel_path module.abs_path = self.install_config.convert_path_abs( rel_path) module.url_type = url_type module.url = url module.repository = repo module.clone = clone_str module.build = build_str module.package = package_str self.root.updateAllRefs(self.install_config) self.root.updateConfigPanel() self.root.unsaved_changes = True self.root.showMessage( 'Info', 'Upated module: {}'.format(self.edit_name_var.get())) def exitWindow(self): """Exits from the window """ self.master.destroy()
class Delete(): def __init__(self, master): self.master = master self.master.geometry("250x100") self.master.title("Delete List") self.master.resizable(False, False) self.menu = Menu(self.master) self.file_menu = Menu(self.menu, tearoff=0) self.file_menu.add_command(label="Delete", accelerator='Alt+D', command=self.deletefile) self.file_menu.add_command(label="Exit", accelerator='Alt+F4', command=self.exitmenu) self.menu.add_cascade(label="File", menu=self.file_menu) self.about_menu = Menu(self.menu, tearoff=0) self.about_menu.add_command(label="About", accelerator='Ctrl+I', command=about_menu) self.menu.add_cascade(label="About", menu=self.about_menu) self.help_menu = Menu(self.menu, tearoff=0) self.help_menu.add_command(label="Help", accelerator='Alt+F1', command=self.helpmenu) self.menu.add_cascade(label="Help", menu=self.help_menu) self.master.config(menu=self.menu) self.master.bind('<Alt-d>', lambda event: self.deletefile()) self.master.bind('<Alt-F4>', lambda event: self.exitmenu()) self.master.bind('<Control-F1>', lambda event: self.helpmenu()) self.master.bind('<Control-i>', lambda event: about_menu()) f = os.listdir() if not f: msg.showerror("ERROR", "NO ROUTINE") self.master.destroy() else: self.flist = StringVar(master) self.flist.set(f[0]) self.chomenu = OptionMenu(self.master, self.flist, *f) self.chomenu.pack() self.deleteb = Button(self.master, text="DELETE", command=self.deletefile) self.deleteb.pack() def deletefile(self): """ deletes a routine """ os.remove(self.flist.get()) msg.showinfo( "SUCCESS", "THE " + str(self.flist.get()) + " ROUTINE FILE HAS SUCCESSFULLY DELETED") self.master.destroy() def exitmenu(self): """ exit menu function """ if msg.askokcancel("Quit?", "Really quit?"): self.master.destroy() def helpmenu(self): msg.showinfo("Help", "Here you can delete the routine files")
def creeInterface(a_largeur=LARGEUR_FEN, a_hauteur=HAUTEUR_FEN): global Wcanvas, ValLargeur, ValHauteur, EntreeX, EntreeY, SortieX, SortieY global CoulEntreeLbl, CoulEntreeBtn, CoulSortieLbl, CoulSortieBtn, Main, Orient, Replay # Fenêtre principale root = Tk() root.title(TITRE + VERSION) root.geometry(str(a_largeur) + "x" + str(a_hauteur + 140) + "-10+10") # Frame des données dataFrame = Frame(root) # Partie 'Labyrinthe' labyFrame = LabelFrame(dataFrame, text='Labyrinthe') # Première ligne : largeur du labyrinthe Label(labyFrame, text='Largeur').grid(row=0, column=0) ValLargeur = StringVar(root) ValLargeur.set(LARGEUR_DEF) Entry(labyFrame, textvariable=ValLargeur, width=2).grid(row=0, column=1) # Deuxième ligne : hauteur du labyrinthe Label(labyFrame, text='Hauteur').grid(row=1, column=0) ValHauteur = StringVar(root) ValHauteur.set(HAUTEUR_DEF) Entry(labyFrame, textvariable=ValHauteur, width=2).grid(row=1, column=1) # Troisième ligne : bouton 'Créer' Button(labyFrame, text='Créer', command=creerLabyCmd).grid(row=2, column=0, columnspan=2) # Fin de la partie labyFrame labyFrame.grid(row=0, column=0, sticky=tkinter.N + tkinter.S) # Partie 'Entrée' entreeFrame = LabelFrame(dataFrame, text='Entrée') # Abscisse Label(entreeFrame, text="X").grid(row=0, column=0) EntreeX = Scale(entreeFrame, to=LARGEUR_DEF - 1, showvalue=False, orient='h', command=xEntreeCmd) EntreeX.grid(row=0, column=1) # Ordonnée Label(entreeFrame, text="Y").grid(row=1, column=0) EntreeY = Scale(entreeFrame, to=HAUTEUR_DEF - 1, showvalue=False, orient='h', command=yEntreeCmd) EntreeY.grid(row=1, column=1) # Label Couleur CoulEntreeLbl = Label(entreeFrame, text="Couleur", bg=CoulEntree) CoulEntreeLbl.grid(row=2, column=0) # Bouton Couleur CoulEntreeBtn = Button(entreeFrame, text=CoulEntree, bg=CoulEntree, command=coulEntreeCmd) CoulEntreeBtn.grid(row=2, column=1) # Fin de la partie entreeFrame entreeFrame.grid(row=0, column=1, sticky=tkinter.N + tkinter.S) # Partie 'Sortie' sortieFrame = LabelFrame(dataFrame, text='Sortie') # Abscisse Label(sortieFrame, text="X").grid(row=0, column=0) SortieX = Scale(sortieFrame, to=LARGEUR_DEF - 1, showvalue=False, orient='h', command=xSortieCmd) SortieX.grid(row=0, column=1) # Ordonnée Label(sortieFrame, text="Y").grid(row=1, column=0) SortieY = Scale(sortieFrame, to=HAUTEUR_DEF - 1, showvalue=False, orient='h', command=ySortieCmd) SortieY.grid(row=1, column=1) # Label Couleur CoulSortieLbl = Label(sortieFrame, text="Couleur", bg=CoulSortie) CoulSortieLbl.grid(row=2, column=0) # Bouton Couleur CoulSortieBtn = Button(sortieFrame, text=CoulSortie, bg=CoulSortie, command=coulSortieCmd) CoulSortieBtn.grid(row=2, column=1) # Fin de la partie sortieFrame sortieFrame.grid(row=0, column=2, sticky=tkinter.N + tkinter.S) # Partie 'Algo' algoFrame = LabelFrame(dataFrame, text='Algorithme') # Main Label(algoFrame, text='Main').grid(row=0, column=0) Main = StringVar(root) Main.set(MAIN[0]) OptionMenu(algoFrame, Main, *MAIN, command=mainCmd).grid(row=0, column=1) # Orientation Label(algoFrame, text='Orient.').grid(row=1, column=0) Orient = StringVar(root) Orient.set(ORIENTATION[0]) OptionMenu(algoFrame, Orient, *ORIENTATION, command=orientationCmd).grid(row=1, column=1) # Bouton 'Démarrer' Button(algoFrame, text='Démarrer', command=demarrerCmd).grid(row=2, column=0) #, columnspan=2) # Scale 'Replay' Replay = Scale(algoFrame, showvalue=False, orient='h', command=replayCmd) Replay.grid(row=2, column=1) # Fin de la partie algoFrame algoFrame.grid(row=0, column=3, sticky=tkinter.N + tkinter.S) # Fin de la partie dataFrame et affichage dataFrame.grid(sticky=tkinter.W) # Fenêtre graphique (canvas) Wcanvas = Canvas(root, background="white", width=a_largeur, height=a_hauteur) # Fin de la partie Wcanvas et affichage Wcanvas.grid(row=1, column=0) return
def make_option_menu(self, frame, options): choice = StringVar(frame) choice.set(options[0]) options = OptionMenu(frame, choice, *options) options.pack(fill='both', expand=1) return choice
class Notifier(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.text_clicked = False self.time_clicked = False self.running = False self.afterv = [] self.max_tries = 5 self.initUI() def initUI(self): # Establish frames self.pack(side="top", fill="both", expand=True) self.top_frame = Frame(self) self.bottom_frame = Frame(self) self.top_frame.pack(side="top", fill="both", expand=False) self.bottom_frame.pack(side="bottom", fill="both", expand=True) self.top_top_frame = Frame(self.top_frame) self.top_top_frame.pack(side="top", fill="both", expand=False) self.bottom_top_frame = Frame(self.top_frame) self.bottom_top_frame.pack(side="bottom", fill="both", expand=False) # Entry combo box self.cboxv = StringVar(self.top_top_frame) self.cbox = Combobox(self.top_top_frame, value=self.cboxv, width=40) self.cbox['values'] = ("all", "FreeGamesOnSteam", "funny", "news") self.cbox.current(0) self.cbox.bind("<Button-1>", self.text_callback) self.cbox.bind("<Tab>", self.time_callback) self.cbox.pack(side="left", padx=10, pady=10, expand=True) # Entry time box self.tentry = Entry(self.top_top_frame, width=8, foreground='gray') self.tentry.bind("<Button-1>", self.time_callback) self.tentry.insert(0, "Time(s)") self.tentry.pack(side="left", padx=10, pady=10, expand=True) # Category drop-down menu self.category = StringVar(self.top_top_frame) self.category.set("hot") # default value self.omenu = OptionMenu(self.top_top_frame, self.category, "hot", "new", "top", "controversial", "rising") self.omenu.pack(side="right", padx=10, pady=10, expand=True) # Limit drop-down menu self.limit = IntVar(self.top_top_frame) self.limit.set(5) # default value self.lmenu = OptionMenu(self.top_top_frame, self.limit, *list(range(10))) self.lmenu.pack(side="right", padx=10, pady=10, expand=True) # Scan button self.scanb = Button(self.bottom_top_frame, text="Scan", command=self.scan_subreddit) self.scanb.pack(side="left", padx=10, pady=10, expand=True) self.parent.bind("<Return>", lambda x: self.scan_subreddit()) # Popup check self.checkvar = BooleanVar() self.check = Checkbutton(self.bottom_top_frame, text="Popup", variable=self.checkvar) self.check.pack(side="left", padx=10, pady=10, expand=True) # Continuous check self.contvar = BooleanVar() self.contb = Checkbutton(self.bottom_top_frame, text="Continuous", variable=self.contvar) self.contb.pack(side="left", padx=10, pady=10, expand=True) # Stop button self.stopb = Button(self.bottom_top_frame, text="Stop", command=self.stop_scanning, state="disabled") self.stopb.pack(side="right", padx=10, pady=10, expand=True) self.parent.bind("<Escape>", lambda x: self.stop_scanning()) # Results text box self.text = CustomText(self.bottom_frame, height=10, width=50) self.text.configure(state="disabled") self.text.pack(side="top", padx=10, pady=10, expand=True, fill="both") def text_callback(self, event=None): if not self.text_clicked: self.cbox.delete(0, "end") self.text_clicked = True def time_callback(self, event=None): if not self.time_clicked: self.tentry.delete(0, "end") self.tentry.config(foreground="black") self.time_clicked = True def scan_subreddit(self): self.running = True self.scanb.config(state="disabled") self.stopb.config(state="normal") self.omenu.config(state="disabled") self.lmenu.config(state="disabled") self.cbox.config(state="disabled") self.tentry.config(state="disabled") self.check.config(state="disabled") self.contb.config(state="disabled") self.parent.unbind("<Return>") # Clean text box self.text.config(state="normal") self.text.delete(1.0, 'end') self.text.config(state="disabled") # Get values from boxes sub_name = self.cbox.get() cat = self.category.get() self.slimit = self.limit.get() self.popup = self.checkvar.get() self.cont = self.contvar.get() try: subreddit = reddit.subreddit(sub_name) except Exception: self.text.tinsert("Error: insert a subreddit" + '\n') self.stop_scanning() return try: self.stime = max(0, int(self.tentry.get())) except Exception: self.text.tinsert("Error: time must be a number" + '\n') self.stop_scanning() return self.text.tinsert("Info: getting " + cat + " posts from /r/" + sub_name + '\n') self.subcat = get_subreddit_cat(subreddit, cat) self.tries = 0 self.done_trying = False self.started_managing = False self.done_managing = False self.submissions = None self.get_results() def stop_scanning(self): self.running = False self.scanb.config(state="normal") self.stopb.config(state="disabled") self.omenu.config(state="normal") self.lmenu.config(state="normal") self.cbox.config(state="normal") self.tentry.config(state="normal") self.check.config(state="normal") self.contb.config(state="normal") self.parent.bind("<Return>", lambda x: self.scan_subreddit()) for a in self.afterv: self.parent.after_cancel(a) del self.afterv[:] def get_results(self): if self.running: now = time.time() if not self.done_trying: if self.tries < self.max_tries: try: self.submissions = [ x for x in self.subcat(limit=self.slimit) if (now - x.created_utc) < self.stime ] self.done_trying = True except Exception: self.text.tinsert("Error: [" + nows() + "] try n. " + str(self.tries + 1) + ", cannot access subreddit" + '\n') self.tries += 1 self.afterv.append( self.parent.after(5000, self.get_results)) else: self.text.tinsert( "Error: [" + nows() + "] couldn't access subreddit. Stopping scan." + '\n') self.stop_scanning() self.done_trying = True self.tries = 0 if self.done_trying: if not self.submissions: if not self.started_managing: self.text.tinsert("Info: [" + nows() + "] no results found" '\n') self.done_managing = True else: if not self.started_managing: self.text.tinsert("Info: [" + nows() + "] " + str(len(self.submissions)) + " results found" '\n') self.started_managing = True s = self.submissions[0] self.text.tinsert("Title: " + convert65536(s.title) + '\n') self.text.tinsert("Url: " + s.url + '\n') self.text.tinsert("Created: " + pretty_date(s) + '\n\n') self.parent.update_idletasks() if self.popup: if sys.platform.startswith('win'): import winsound winsound.PlaySound("media/jamaica.wav", winsound.SND_FILENAME) Dialog(self.parent, s.url, s.title) self.submissions = self.submissions[1:] self.afterv.append( self.parent.after(1000, self.get_results)) if self.done_managing: if self.cont: self.text.tinsert( "Info: [" + nows() + "] continuous mode, will check again in " + str(self.stime) + " seconds\n\n") self.afterv.append( self.parent.after(self.stime * 1000, self.get_results)) self.done_trying = False self.started_managing = False self.done_managing = False else: self.text.tinsert("Info: [" + nows() + "] scanning finished" '\n') self.stop_scanning()
class TSP_SOLVER2(): """ tsp solver class""" def __init__(self, master): self.master = master self.master.title("TSP_SOLVER 2") self.master.geometry("250x200") self.master.resizable(False, False) self.filed = "" # menu self.menu = Menu(self.master) self.file_menu = Menu(self.menu, tearoff=0) self.file_menu.add_command(label="Insert a file", accelerator='Ctrl+O', command=self.insertfile) self.file_menu.add_command(label="Solve", accelerator='Alt+F5', command=self.solve) self.file_menu.add_command(label="Close file", accelerator="Ctrl+F5", command=self.cf) self.file_menu.add_command(label="Exit", accelerator='Alt+F4', command=self.exitmenu) self.menu.add_cascade(label="File", menu=self.file_menu) self.show_menu = Menu(self.menu, tearoff=0) self.show_menu.add_command(label='Instance Plot', command=self.instanceplot) self.menu.add_cascade(label='Show', menu=self.show_menu) self.about_menu = Menu(self.menu, tearoff=0) self.about_menu.add_command(label="About", accelerator='Ctrl+I', command=aboutmenu) self.menu.add_cascade(label="About", menu=self.about_menu) self.help_menu = Menu(self.menu, tearoff=0) self.help_menu.add_command(label="Help", accelerator='Ctrl+F1', command=helpmenu) self.menu.add_cascade(label="Help", menu=self.help_menu) self.master.config(menu=self.menu) self.master.bind('<Control-o>', lambda event: self.insertfile()) self.master.bind('<Alt-F5>', lambda event: self.solve()) self.master.bind('<Alt-F4>', lambda event: self.exitmenu()) self.master.bind('<Control-F1>', lambda event: helpmenu()) self.master.bind('<Control-i>', lambda event: aboutmenu()) self.master.bind('<Control-F5>', lambda event: self.cf()) self.binsert = Button(self.master, text="Insert a file", command=self.insertfile) self.binsert.pack() setslist = list(["2-opt", "Relocate", "Swap"]) self.varnumset = StringVar(master) self.varnumset.set(setslist[0]) self.popupsetmenu = OptionMenu(self.master, self.varnumset, *setslist) self.popupsetmenu.pack() self.lb = Label(self.master, text="TRIES") self.lb.pack() self.textt = Text(self.master, height=1) self.textt.pack() def exitmenu(self): """ exit menu function """ if msg.askokcancel("Quit?", "Really quit?"): self.master.destroy() def instanceplot(self): """ plots the instance""" if self.filed == "": msg.showerror("ERROR", "NO FILE IMPORTED TO PLOT") else: data = np.loadtxt(self.filed) x = data[:, 0] y = data[:, 1] plt.scatter(x, y) plt.show() def cf(self): """ closes the file """ if self.filed == "": msg.showerror("NO FILE", "NO FILE TO CLOSE") else: self.filed = "" self.popupsetmenu.forget() self.solvb.forget() msg.showinfo("FILE CLOSED", "SUCCESS") #CHANGE THE MESSAGE def file_verification_gui(self): """ gui created after file verification""" self.nodelist = list(self.number) self.varnumnode = StringVar(self.master) self.varnumnode.set(self.nodelist[0]) self.popupsetmenu = OptionMenu(self.master, self.varnumnode, *self.nodelist) self.popupsetmenu.pack() self.solvb = Button(self.master, text="Solve", command=self.solve) self.solvb.pack() def file_verification(self): try: self.table, self.number = fileparser(self.filed) self.file_verification_gui() msg.showinfo( "SUCCESS", "THE FILE SUCCESSFULLY INSERTED \nNumber of nodes:" + str(len(self.number))) except ValueError: msg.showerror("ERROR", "NO TSP INSTANCE INSERTED") self.filed = "" def checkinsertedfiletype(self): if ".txt" in self.filed: self.file_verification() else: msg.showerror("Error", "NO TXT FILE ADDED") def insertfile(self): """ user inserts a .txt file (problem instance ) """ if self.filed == "": self.filed = filedialog.askopenfilename( initialdir="/", title="Select txt file", filetypes=(("txt files", "*.txt"), ("all files", "*.*"))) self.checkinsertedfiletype() else: msg.showerror("ERROR", "YOU NEED TO CLOSE THE FILE") def algouse(self, tries, visited_nodes, totalscore): if self.varnumset.get() == "2-opt": current_route, current_score = _2optf(visited_nodes, totalscore, tries, self.table, self.number) elif self.varnumset.get() == "Relocate": current_route, current_score = relocatef(visited_nodes, totalscore, tries, self.table, self.number) else: current_route, current_score = swap(visited_nodes, totalscore, tries, self.table, self.number) msg.showinfo( "SUCCESS", "THE ROUTE USING " + self.varnumset.get() + " :" + str(current_route) + "WITH SCORE:" + str(current_score)) self.textt.delete(1.0, END) def check_tries(self, visited_nodes, totalscore): try: if int(self.textt.get(1.0, END)) > 0: self.algouse(int(self.textt.get(1.0, END)), visited_nodes, totalscore) else: msg.showerror("Value Error", "Enter a number higher than zero") self.textt.delete(1.0, END) except ValueError: msg.showerror("Value Error", "Enter a number higher than zero") self.textt.delete(1.0, END) def solve(self): """ solves the problem """ if self.filed == "": msg.showinfo("Import", "You need to import a .txt file") else: visited_nodes, totalscore = nearserN(self.table, self.number, self.varnumnode.get()) self.check_tries(visited_nodes, totalscore)
class MyApp(Frame): def __init__(self): self.root = Tk() Frame.__init__(self, self.root) # high level GUI configuration self.root.geometry('800x600') self.root.resizable(width=1, height=1) self.root.option_add('*tearOff', False) # keeps file menus from looking weird # members related to the background thread and operator instance self.long_thread = None self.background_operator = None # tk variables we can access later self.label_string = StringVar() self.build_dir_1_var = StringVar() self.build_dir_2_var = StringVar() self.run_period_option = StringVar() self.run_period_option.set(RunOptions.DONT_FORCE) self.reporting_frequency = StringVar() self.reporting_frequency.set(ReportingFrequency.HOURLY) # widgets that we might want to access later self.build_dir_1_button = None self.build_dir_2_button = None self.run_button = None self.stop_button = None self.build_dir_1_label = None self.build_dir_1_var.set('/eplus/repos/1eplus/builds') # "<Select build dir 1>") self.build_dir_2_label = None self.build_dir_2_var.set('/eplus/repos/1eplus/builds') # "<Select build dir 2>") self.progress = None self.log_message_listbox = None self.results_tree = None self.num_threads_spinner = None self.full_idf_listbox = None self.move_idf_to_active_button = None self.active_idf_listbox = None self.remove_idf_from_active_button = None self.idf_select_all_button = None self.idf_deselect_all_button = None self.idf_select_n_random_button = None self.run_period_option_menu = None self.reporting_frequency_option_menu = None # some data holders self.tree_folders = dict() self.valid_idfs_in_listing = False self.run_button_color = '#008000' # initialize the GUI self.init_window() # wire up the background thread pub.subscribe(self.status_handler, PubSubMessageTypes.STATUS) pub.subscribe(self.finished_handler, PubSubMessageTypes.FINISHED) pub.subscribe(self.cancelled_handler, PubSubMessageTypes.CANCELLED) def init_window(self): # changing the title of our master widget self.root.title("EnergyPlus Regression Tool 2") self.root.protocol("WM_DELETE_WINDOW", self.client_exit) # create the menu menu = Menu(self.root) self.root.config(menu=menu) file_menu = Menu(menu) file_menu.add_command(label="Exit", command=self.client_exit) menu.add_cascade(label="File", menu=file_menu) # main notebook holding everything main_notebook = ttk.Notebook(self.root) # run configuration pane_run = Frame(main_notebook) group_build_dir_1 = LabelFrame(pane_run, text="Build Directory 1") group_build_dir_1.pack(fill=X, padx=5) self.build_dir_1_button = Button(group_build_dir_1, text="Change...", command=self.client_build_dir_1) self.build_dir_1_button.grid(row=1, column=1, sticky=W) self.build_dir_1_label = Label(group_build_dir_1, textvariable=self.build_dir_1_var) self.build_dir_1_label.grid(row=1, column=2, sticky=E) group_build_dir_2 = LabelFrame(pane_run, text="Build Directory 2") group_build_dir_2.pack(fill=X, padx=5) self.build_dir_2_button = Button(group_build_dir_2, text="Change...", command=self.client_build_dir_2) self.build_dir_2_button.grid(row=1, column=1, sticky=W) self.build_dir_2_label = Label(group_build_dir_2, textvariable=self.build_dir_2_var) self.build_dir_2_label.grid(row=1, column=2, sticky=E) group_run_options = LabelFrame(pane_run, text="Run Options") group_run_options.pack(fill=X, padx=5) Label(group_run_options, text="Number of threads for suite: ").grid(row=1, column=1, sticky=E) self.num_threads_spinner = Spinbox(group_run_options, from_=1, to_=48) # validate later self.num_threads_spinner.grid(row=1, column=2, sticky=W) Label(group_run_options, text="Test suite run configuration: ").grid(row=2, column=1, sticky=E) self.run_period_option_menu = OptionMenu(group_run_options, self.run_period_option, *RunOptions.get_all()) self.run_period_option_menu.grid(row=2, column=2, sticky=W) Label(group_run_options, text="Minimum reporting frequency: ").grid(row=3, column=1, sticky=E) self.reporting_frequency_option_menu = OptionMenu( group_run_options, self.reporting_frequency, *ReportingFrequency.get_all() ) self.reporting_frequency_option_menu.grid(row=3, column=2, sticky=W) main_notebook.add(pane_run, text='Configuration') # now let's set up a list of checkboxes for selecting IDFs to run pane_idfs = Frame(main_notebook) group_idf_tools = LabelFrame(pane_idfs, text="IDF Selection Tools") group_idf_tools.pack(fill=X, padx=5) self.idf_select_all_button = Button( group_idf_tools, text="Refresh", command=self.client_idf_refresh ) self.idf_select_all_button.pack(side=LEFT, expand=1) self.idf_select_all_button = Button( group_idf_tools, text="Select All", command=self.idf_select_all ) self.idf_select_all_button.pack(side=LEFT, expand=1) self.idf_deselect_all_button = Button( group_idf_tools, text="Deselect All", command=self.idf_deselect_all ) self.idf_deselect_all_button.pack(side=LEFT, expand=1) self.idf_select_n_random_button = Button( group_idf_tools, text="Select N Random", command=self.idf_select_random ) self.idf_select_n_random_button.pack(side=LEFT, expand=1) group_full_idf_list = LabelFrame(pane_idfs, text="Full IDF List") group_full_idf_list.pack(fill=X, padx=5) scrollbar = Scrollbar(group_full_idf_list) self.full_idf_listbox = Listbox(group_full_idf_list, yscrollcommand=scrollbar.set) self.full_idf_listbox.bind('<Double-1>', self.idf_move_to_active) self.full_idf_listbox.pack(fill=BOTH, side=LEFT, expand=True) scrollbar.pack(fill=Y, side=LEFT) scrollbar.config(command=self.full_idf_listbox.yview) self.move_idf_to_active_button = Button( pane_idfs, text="↓ Add to Active List ↓", command=self.idf_move_to_active ) self.move_idf_to_active_button.pack(side=TOP, fill=X, expand=True) self.remove_idf_from_active_button = Button( pane_idfs, text="↑ Remove from Active List ↑", command=self.idf_remove_from_active ) self.remove_idf_from_active_button.pack(side=TOP, fill=X, expand=True) group_active_idf_list = LabelFrame(pane_idfs, text="Active IDF List") group_active_idf_list.pack(fill=X, padx=5) scrollbar = Scrollbar(group_active_idf_list) self.active_idf_listbox = Listbox(group_active_idf_list, yscrollcommand=scrollbar.set) self.active_idf_listbox.bind('<Double-1>', self.idf_remove_from_active) self.active_idf_listbox.pack(fill=BOTH, side=LEFT, expand=True) scrollbar.pack(fill=Y, side=LEFT) scrollbar.config(command=self.active_idf_listbox.yview) self.build_idf_listing(initialize=True) main_notebook.add(pane_idfs, text="IDF Selection") # set up a scrolled listbox for the log messages frame_log_messages = Frame(main_notebook) group_log_messages = LabelFrame(frame_log_messages, text="Log Message Tools") group_log_messages.pack(fill=X, padx=5) Button(group_log_messages, text="Clear Log Messages", command=self.clear_log).pack(side=LEFT, expand=1) Button(group_log_messages, text="Copy Log Messages", command=self.copy_log).pack(side=LEFT, expand=1) scrollbar = Scrollbar(frame_log_messages) self.log_message_listbox = Listbox(frame_log_messages, yscrollcommand=scrollbar.set) self.add_to_log("Program started!") self.log_message_listbox.pack(fill=BOTH, side=LEFT, expand=True) scrollbar.pack(fill=Y, side=LEFT) scrollbar.config(command=self.log_message_listbox.yview) main_notebook.add(frame_log_messages, text="Log Messages") # set up a tree-view for the results frame_results = Frame(main_notebook) scrollbar = Scrollbar(frame_results) self.results_tree = ttk.Treeview(frame_results, columns=("Base File", "Mod File", "Diff File")) self.results_tree.heading("#0", text="Results") self.results_tree.column('#0', minwidth=200, width=200) self.results_tree.heading("Base File", text="Base File") self.results_tree.column("Base File", minwidth=100, width=100) self.results_tree.heading("Mod File", text="Mod File") self.results_tree.column("Mod File", minwidth=100, width=100) self.results_tree.heading("Diff File", text="Diff File") self.results_tree.column("Diff File", minwidth=100, width=100) self.build_results_tree() self.results_tree.pack(fill=BOTH, side=LEFT, expand=True) scrollbar.pack(fill=Y, side=LEFT) scrollbar.config(command=self.results_tree.yview) main_notebook.add(frame_results, text="Run Control and Results") # pack the main notebook on the window main_notebook.pack(fill=BOTH, expand=1) # status bar at the bottom frame_status = Frame(self.root) self.run_button = Button(frame_status, text="Run", bg=self.run_button_color, command=self.client_run) self.run_button.pack(side=LEFT, expand=0) self.stop_button = Button(frame_status, text="Stop", command=self.client_stop, state='disabled') self.stop_button.pack(side=LEFT, expand=0) self.progress = ttk.Progressbar(frame_status) self.progress.pack(side=LEFT, expand=0) label = Label(frame_status, textvariable=self.label_string) self.label_string.set("Initialized") label.pack(side=LEFT, anchor=W) frame_status.pack(fill=X) def run(self): self.root.mainloop() def build_idf_listing(self, initialize=False, desired_selected_idfs=None): # clear any existing ones self.active_idf_listbox.delete(0, END) self.full_idf_listbox.delete(0, END) # now rebuild them self.valid_idfs_in_listing = False path_1 = Path(self.build_dir_1_var.get()) path_2 = Path(self.build_dir_2_var.get()) if path_1.exists() and path_2.exists(): idf_dir_1 = dummy_get_idf_dir(path_1) idfs_dir_1 = dummy_get_idfs_in_dir(idf_dir_1) idf_dir_2 = dummy_get_idf_dir(path_2) idfs_dir_2 = dummy_get_idfs_in_dir(idf_dir_2) common_idfs = idfs_dir_1.intersection(idfs_dir_2) for idf in sorted(common_idfs): self.full_idf_listbox.insert(END, str(idf)) self.valid_idfs_in_listing = True elif initialize: self.full_idf_listbox.insert(END, "This will be the master list") self.full_idf_listbox.insert(END, "Select build folders to fill listing") elif path_1.exists(): self.full_idf_listbox.insert(END, "Cannot update master list master list") self.full_idf_listbox.insert(END, "Build folder path #2 is invalid") self.full_idf_listbox.insert(END, "Select build folders to fill listing") elif path_2.exists(): self.full_idf_listbox.insert(END, "Cannot update master list master list") self.full_idf_listbox.insert(END, "Build folder path #1 is invalid") self.full_idf_listbox.insert(END, "Select build folders to fill listing") else: self.full_idf_listbox.insert(END, "Cannot update master list master list") self.full_idf_listbox.insert(END, "Both build folders are invalid") self.full_idf_listbox.insert(END, "Select build folders to fill listing") if desired_selected_idfs is None: ... # add things to the listbox def build_results_tree(self, results=None): self.results_tree.delete(*self.results_tree.get_children()) for root in ResultsTreeRoots.get_all(): self.tree_folders[root] = self.results_tree.insert( parent="", index='end', text=root, values=("", "", "") ) if results: self.results_tree.insert( parent=self.tree_folders[root], index="end", text="Pretend", values=("These", "Are", "Real") ) else: self.results_tree.insert( parent=self.tree_folders[root], index="end", text="Run test for results", values=("", "", "") ) def add_to_log(self, message): self.log_message_listbox.insert(END, f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}]: {message}") def clear_log(self): self.log_message_listbox.delete(0, END) def copy_log(self): messages = self.log_message_listbox.get(0, END) message_string = '\n'.join(messages) self.root.clipboard_append(message_string) def client_idf_refresh(self): self.build_idf_listing() def idf_move_to_active(self, _): if not self.valid_idfs_in_listing: simpledialog.messagebox.showerror("IDF Selection Error", "Invalid build folders or IDF list") return current_selection = self.full_idf_listbox.curselection() if not current_selection: simpledialog.messagebox.showerror("IDF Selection Error", "No IDF Selected") return currently_selected_idf = self.full_idf_listbox.get(current_selection) try: self.active_idf_listbox.get(0, "end").index(currently_selected_idf) simpledialog.messagebox.showwarning("IDF Selection Warning", "IDF already exists in active list") return except ValueError: pass # the value error indicates it was _not_ found, so this is success self.active_idf_listbox.insert(END, currently_selected_idf) self.idf_refresh_count_status(currently_selected_idf, True) def idf_remove_from_active(self, event=None): if not self.valid_idfs_in_listing: simpledialog.messagebox.showerror("IDF Selection Error", "Invalid build folders or IDF list") return current_selection = self.active_idf_listbox.curselection() if not current_selection: if event: return simpledialog.messagebox.showerror("IDF Selection Error", "No IDF Selected") return self.active_idf_listbox.delete(current_selection) self.idf_refresh_count_status(current_selection, False) def idf_select_all(self): self.idf_deselect_all() if not self.valid_idfs_in_listing: simpledialog.messagebox.showerror("IDF Selection Error", "Invalid build folders or IDF list") return all_idfs = self.full_idf_listbox.get(0, END) for idf in all_idfs: self.active_idf_listbox.insert(END, idf) self.idf_refresh_count_status() def idf_deselect_all(self): if not self.valid_idfs_in_listing: simpledialog.messagebox.showerror("IDF Selection Error", "Invalid build folders or IDF list") return self.active_idf_listbox.delete(0, END) self.idf_refresh_count_status() def idf_select_random(self): if not self.valid_idfs_in_listing: simpledialog.messagebox.showerror("IDF Selection Error", "Invalid build folders or IDF list") return potential_number_to_select = simpledialog.askinteger("Input Amount", "How many would you like to select?") if not potential_number_to_select: return self.idf_deselect_all() number_to_select = int(potential_number_to_select) number_of_idf_files = self.full_idf_listbox.size() if number_of_idf_files <= number_to_select: # just take all of them self.idf_select_all() else: # down select randomly indices_to_take = random.sample(range(number_of_idf_files), number_to_select) idfs_to_take = list() for i in indices_to_take: idf_to_get = self.full_idf_listbox.get(i) idfs_to_take.append(idf_to_get) for idf_to_get in sorted(idfs_to_take): self.active_idf_listbox.insert(END, idf_to_get) self.idf_refresh_count_status() def idf_refresh_count_status(self, test_case=None, checked=False): if not self.valid_idfs_in_listing: return num_total = self.full_idf_listbox.size() num_active = self.active_idf_listbox.size() if test_case: chk_string = "Checked" if checked else "Unchecked" if checked: self.label_string.set(f"{chk_string} {test_case} ({num_active}/{num_total} selected)") else: self.label_string.set(f"{num_active}/{num_total} selected") def set_gui_status_for_run(self, is_running: bool): if is_running: run_button_state = 'disabled' stop_button_state = 'normal' else: run_button_state = 'normal' stop_button_state = 'disabled' self.build_dir_1_button.configure(state=run_button_state) self.build_dir_2_button.configure(state=run_button_state) self.run_button.configure(state=run_button_state) self.idf_select_all_button.configure(state=run_button_state) self.idf_deselect_all_button.configure(state=run_button_state) self.idf_select_n_random_button.configure(state=run_button_state) self.move_idf_to_active_button.configure(state=run_button_state) self.remove_idf_from_active_button.configure(state=run_button_state) self.run_period_option_menu.configure(state=run_button_state) self.reporting_frequency_option_menu.configure(state=run_button_state) self.num_threads_spinner.configure(state=run_button_state) self.stop_button.configure(state=stop_button_state) def client_build_dir_1(self): selected_dir = filedialog.askdirectory() if selected_dir: self.build_dir_1_var.set(selected_dir) self.build_idf_listing() def client_build_dir_2(self): selected_dir = filedialog.askdirectory() if selected_dir: self.build_dir_2_var.set(selected_dir) self.build_idf_listing() def client_run(self): if self.long_thread: messagebox.showerror("Cannot run another thread, wait for the current to finish -- how'd you get here?!?") return potential_num_threads = self.num_threads_spinner.get() try: num_threads = int(potential_num_threads) except ValueError: messagebox.showerror("Invalid Configuration", "Number of threads must be an integer") return idfs_to_run = list() for i in self.active_idf_listbox.get(0, END): idfs_to_run.append(i) self.background_operator = BackgroundOperation(num_threads, idfs_to_run) self.background_operator.get_ready_to_go( MyApp.status_listener, MyApp.finished_listener, MyApp.cancelled_listener ) self.set_gui_status_for_run(True) self.long_thread = Thread(target=self.background_operator.run) self.add_to_log("Starting a new set of tests") self.long_thread.start() def client_stop(self): self.add_to_log("Attempting to cancel") self.label_string.set("Attempting to cancel...") self.background_operator.please_stop() def client_exit(self): if self.long_thread: messagebox.showerror("Uh oh!", "Cannot exit program while operations are running; abort them then exit") return exit() def client_done(self): self.set_gui_status_for_run(False) self.long_thread = None # -- Callbacks from the background thread coming via PyPubSub @staticmethod def status_listener(status, object_completed, percent_complete): """Operates on background thread, just issues a pubsub message""" pub.sendMessage( PubSubMessageTypes.STATUS, status=status, object_completed=object_completed, percent_complete=percent_complete) def status_handler(self, status, object_completed, percent_complete): self.add_to_log(object_completed) self.progress['value'] = percent_complete self.label_string.set(f"Hey, status update: {str(status)}") @staticmethod def finished_listener(results_dict): """Operates on background thread, just issues a pubsub message""" pub.sendMessage(PubSubMessageTypes.FINISHED, results=results_dict) def finished_handler(self, results): self.add_to_log("All done, finished") self.label_string.set("Hey, all done!") self.build_results_tree(results) self.client_done() @staticmethod def cancelled_listener(): """Operates on background thread, just issues a pubsub message""" pub.sendMessage(PubSubMessageTypes.CANCELLED) def cancelled_handler(self): self.add_to_log("Cancelled!") self.label_string.set("Properly cancelled!") self.client_done()
class Hangman: """Hangman Game MVP""" def __init__(self, root): """ - Save references for hangman game-stage images - Initalize widgets, layout - Populate GUI with secret word/phrase """ self.master = root self.master.title("Hangman") self.master.iconbitmap(f"{dirname(__file__)}/img/icon.ico") self.center_window() self.master.resizable(False, False) self.stages = [] self.stages.append( PhotoImage(file=f"{dirname(__file__)}/img/0.gif", master=self.master)) self.stages.append( PhotoImage(file=f"{dirname(__file__)}/img/1.gif", master=self.master)) self.stages.append( PhotoImage(file=f"{dirname(__file__)}/img/2.gif", master=self.master)) self.stages.append( PhotoImage(file=f"{dirname(__file__)}/img/3.gif", master=self.master)) self.stages.append( PhotoImage(file=f"{dirname(__file__)}/img/4.gif", master=self.master)) self.stages.append( PhotoImage(file=f"{dirname(__file__)}/img/5.gif", master=self.master)) self.stages.append( PhotoImage(file=f"{dirname(__file__)}/img/6.gif", master=self.master)) # Widgets self.hangman = Label(self.master) self.current_guess = StringVar(self.master) self.current_guess.set("A") self.btn_frame = Frame(self.master, borderwidth=2, relief="groove", padx=10, pady=10) self.option_menu = OptionMenu(self.btn_frame, self.current_guess, "") self.option_menu.config(font="Calibri 9", width=3) self.scale = Scale(self.btn_frame, orient="horizontal", from_=1, to=5, label=" Words") self.scale.set(3) self.new_game_btn = Button( self.btn_frame, text="New Game", command=self.new_game, width=20, ) self.guess_btn = Button( self.btn_frame, text="Guess", width=10, command=lambda: self.guess(self.current_guess.get())) self.letter_frame = Frame(self.master, borderwidth=2, relief="groove", padx=10, pady=10) self.result_label = Label(self.master, font="Calibri 20", foreground="red") # Layout self.master.columnconfigure(0, weight=1) self.hangman.grid(row=0, column=0) self.btn_frame.grid(row=1, column=0, pady=20) self.scale.grid(row=0, column=1, columnspan=2, pady=10) self.new_game_btn.grid(row=1, column=1, columnspan=2, pady=10) self.guess_btn.grid(row=2, column=1, padx=2) self.option_menu.grid(row=2, column=2) self.letter_frame.grid(row=2, column=0, pady=10) self.result_label.grid(row=3, column=0) # Initalize self.new_game() def __str__(self): """Return address of self""" return f"Hangman GUI @ {hex(id(self))}" def new_game(self): """ - Reset GUI & flags from previous round, fill optionmenu with a fresh alphabet - Populate self.secret and letter_frame with a new secret phrase, initalized to underscores (except for whitespace) """ self.hangman.config(image=self.stages[0]) self.result_label.config(text="") for widget in self.letter_frame.winfo_children(): widget.destroy() self.stage = 0 self.blanks = [] self.game_over = False # self.secret = generate_random_phrase() self.secret = generate_random_words(self.scale.get()) for i, letter in enumerate(self.secret): if letter == " ": letter_label = Label(self.letter_frame, text=" ") self.blanks.append(letter_label) else: letter_label = Label(self.letter_frame, text="_") self.blanks.append(letter_label) letter_label.config(font=('calibri', 15)) letter_label.grid(row=0, column=i, padx=1) self.option_menu["menu"].delete(0, "end") for char in ascii_uppercase: self.option_menu["menu"].add_command(label=char, command=_setit( self.current_guess, char)) self.current_guess.set("A") def guess(self, guessed: str): """ - Remove the guessed letter from the optionmenu - Increment the stage if the guess is incorrect, check if we're at last stage - If we reach final stage, game over & result_label set accordingly - Otherwise, reveal the guessed letter(s) in their respective label(s) - Finally, check if we reached the winning condition, in which no labels contain underscores - If so, game over & result_label set to "winner" message """ if self.game_over: return indices = [i for i, x in enumerate(self.secret) if x == guessed] r_index = self.option_menu["menu"].index(guessed) self.option_menu["menu"].delete(r_index) self.current_guess.set(self.option_menu["menu"].entrycget(0, "label")) if not indices: self.stage += 1 self.hangman.config(image=self.stages[self.stage]) if self.stage >= 6: self.game_over = True return self.result_label.config(text=f"Game Over.\n{self.secret}") for i in indices: self.blanks[i].config(text=guessed) winner = True for widget in self.letter_frame.winfo_children(): if (widget.cget("text") == "_"): winner = False if (winner): self.result_label.config(text="Winner!") self.game_over = True def center_window(self): self.master.geometry("600x800") self.master.update() (width_offset, height_offset) = self.get_offset(self.master) self.master.geometry(f"+{width_offset}+{height_offset}") @staticmethod def get_offset(tk_window): """ Returns an appropriate offset for a given tkinter toplevel, such that it always is created center screen on the primary display. """ width_offset = int((tk_window.winfo_screenwidth() / 2) - (tk_window.winfo_width() / 2)) height_offset = int((tk_window.winfo_screenheight() / 2) - (tk_window.winfo_height() / 2)) return (width_offset, height_offset)
ch_button_show_hex = tk.Button(character_frame, text="Show Hex", command=lambda: b_show_hex()) ch_button_show_hex.place(relwidth=0.1, height=20, relx=0.28) ch_button_add = tk.Button(character_frame, text="Add", command=lambda: b_add_row()) ch_button_add.place(relwidth=0.15, height=20, relx=0.4) ch_button_delete = tk.Button(character_frame, text="Delete", command=lambda: b_delete_row()) ch_button_delete.place(relwidth=0.15, height=20, relx=0.57) ch_button_preview = tk.Button(character_frame, text="Preview", command=lambda: get_preview(root)) ch_button_preview.place(relwidth=0.15, height=20, relx=0.74) zoom_var = StringVar(character_frame) zoom_var.set("x1") zoom_list = OptionMenu(character_frame, zoom_var, "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10") zoom_list.place(relwidth=0.07, height=20, relx=0.9) ch_frame = tk.Frame(character_frame, bg='light blue') ch_frame.place(relx=0.01, rely=0.2, relwidth=0.99, relheight=0.84) sp_ch_frame = tk.Frame(sp_character_frame, bg='light blue') sp_ch_frame.place(relx=0.01, rely=0.2, relwidth=0.99, relheight=0.84) model = TableModel() table = TableCanvas(ch_frame, model=model) table.show() model2 = TableModel()
def __init__(self, root): """ - Save references for hangman game-stage images - Initalize widgets, layout - Populate GUI with secret word/phrase """ self.master = root self.master.title("Hangman") self.master.iconbitmap(f"{dirname(__file__)}/img/icon.ico") self.center_window() self.master.resizable(False, False) self.stages = [] self.stages.append( PhotoImage(file=f"{dirname(__file__)}/img/0.gif", master=self.master)) self.stages.append( PhotoImage(file=f"{dirname(__file__)}/img/1.gif", master=self.master)) self.stages.append( PhotoImage(file=f"{dirname(__file__)}/img/2.gif", master=self.master)) self.stages.append( PhotoImage(file=f"{dirname(__file__)}/img/3.gif", master=self.master)) self.stages.append( PhotoImage(file=f"{dirname(__file__)}/img/4.gif", master=self.master)) self.stages.append( PhotoImage(file=f"{dirname(__file__)}/img/5.gif", master=self.master)) self.stages.append( PhotoImage(file=f"{dirname(__file__)}/img/6.gif", master=self.master)) # Widgets self.hangman = Label(self.master) self.current_guess = StringVar(self.master) self.current_guess.set("A") self.btn_frame = Frame(self.master, borderwidth=2, relief="groove", padx=10, pady=10) self.option_menu = OptionMenu(self.btn_frame, self.current_guess, "") self.option_menu.config(font="Calibri 9", width=3) self.scale = Scale(self.btn_frame, orient="horizontal", from_=1, to=5, label=" Words") self.scale.set(3) self.new_game_btn = Button( self.btn_frame, text="New Game", command=self.new_game, width=20, ) self.guess_btn = Button( self.btn_frame, text="Guess", width=10, command=lambda: self.guess(self.current_guess.get())) self.letter_frame = Frame(self.master, borderwidth=2, relief="groove", padx=10, pady=10) self.result_label = Label(self.master, font="Calibri 20", foreground="red") # Layout self.master.columnconfigure(0, weight=1) self.hangman.grid(row=0, column=0) self.btn_frame.grid(row=1, column=0, pady=20) self.scale.grid(row=0, column=1, columnspan=2, pady=10) self.new_game_btn.grid(row=1, column=1, columnspan=2, pady=10) self.guess_btn.grid(row=2, column=1, padx=2) self.option_menu.grid(row=2, column=2) self.letter_frame.grid(row=2, column=0, pady=10) self.result_label.grid(row=3, column=0) # Initalize self.new_game()
class TSP_META_SOLVER(): """ tsp meta solver """ def __init__(self, master): self.master = master self.master.title("TSP_META_SOLVER") self.master.geometry("250x130") self.master.resizable(False, False) self.filed = "" self.menu = Menu(self.master) self.file_menu = Menu(self.menu, tearoff=0) self.file_menu.add_command(label="Insert a file", accelerator='Ctrl+O', command=self.insertfile) self.file_menu.add_command(label="Solve", accelerator='Alt+F5', command=self.solve) self.file_menu.add_command(label="Close file", accelerator="Ctrl+F5", command=self.cf) self.file_menu.add_command(label="Exit", accelerator='Alt+F4', command=self.exitmenu) self.menu.add_cascade(label="File", menu=self.file_menu) self.about_menu = Menu(self.menu, tearoff=0) self.about_menu.add_command(label="About", accelerator='Ctrl+I', command=aboutmenu) self.menu.add_cascade(label="About", menu=self.about_menu) self.help_menu = Menu(self.menu, tearoff=0) self.help_menu.add_command(label="Help", accelerator='Ctrl+F1', command=helpmenu) self.menu.add_cascade(label="Help", menu=self.help_menu) self.master.config(menu=self.menu) self.master.bind('<Control-o>', lambda event: self.insertfile()) self.master.bind('<Alt-F5>', lambda event: self.solve()) self.master.bind('<Alt-F4>', lambda event: self.exitmenu()) self.master.bind('<Control-F1>', lambda event: helpmenu()) self.master.bind('<Control-F5>', lambda event: self.cf()) self.master.bind('<Control-i>', lambda event: aboutmenu()) self.binsert = Button(self.master, text="Insert a file", command=self.insertfile) self.binsert.pack() self.lb = Label(self.master, text="TRIES") self.lb.pack() self.textt = Text(self.master, height=1) self.textt.pack() def cf(self): """ close file""" if self.filed == "": msg.showerror("ERROR", "NO FILE IMPORTED TO CLOSE") else: self.filed = "" self.popupsetmenu.forget() self.solvb.forget() msg.showinfo("SUCCESS", "FILE CLOSED") def exitmenu(self): """ exit menu function """ if msg.askokcancel("Quit?", "Really quit?"): self.master.destroy() def file_verification_gui(self): nodelist = list(self.number) self.varnumnode = StringVar(self.master) self.varnumnode.set(nodelist[0]) self.popupsetmenu = OptionMenu(self.master, self.varnumnode, *nodelist) self.popupsetmenu.pack() self.solvb = Button(self.master, text="Solve", command=self.solve) self.solvb.pack() def instance_verification(self): try: self.table, self.number = fileparser(self.filed) self.file_verification_gui() except ValueError: self.filed = "" msg.showerror("ERROR", "NO TSP INSTANCE") def txt_file_verification(self): if ".txt" in self.filed: self.instance_verification() else: msg.showerror("Error", "NO TXT FILE ADDED") def insertfile(self): """ insert file function """ if self.filed == "": self.filed = filedialog.askopenfilename( initialdir="/", title="Select txt file", filetypes=(("txt files", "*.txt"), ("all files", "*.*"))) self.txt_file_verification() else: msg.showerror("ERROR", "YOU NEED TO CLOSE THE FILE") def solve(self): """ solve Button function """ if self.filed == "": msg.showinfo("Import", "You need to import a .txt file") else: visited_nodes, totalscore = nearserN(self.table, self.number, self.varnumnode.get()) try: if int(self.textt.get(1.0, END)) > 0: tries = int(self.textt.get(1.0, END)) lista = [ relocatef(visited_nodes, totalscore, tries, self.table, self.number), _2optf(visited_nodes, totalscore, tries, self.table, self.number) ] new_route, new_score = bvns(visited_nodes, totalscore, lista, tries) msg.showinfo( "Total Score", "Route:" + str(new_route) + "Score:" + str(new_score)) self.textt.delete(1.0, END) else: msg.showerror("Value Error", "Enter a number higher than zero") self.textt.delete(1.0, END) except ValueError: msg.showerror("Value Error", "Enter a number higher than zero") self.textt.delete(1.0, END)
def __init__(self): # main window root = Tk() root.title("rsHRF Toolbox") # get screen width and height screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() # placing the toplevel root.geometry("500x300+%d+%d" % (((280 / 1900) * screen_width + 425), (((1040.0 - 220) / 1000) * screen_height) - 670)) # defining the toplevels input_window = InputWindow() parameter_window = ParameterWindow() core = Core() logger = LoggingWindow() plotter = PlotterOptionsWindow() # defining variables used by tkinter widgets current = StringVar() current_subject = StringVar() output_path = os.getcwd() self.options = ["None"] self.subjects = ["None"] current.set("None") current_subject.set("None") # other variables input = () # receives the input from the input window output = {} # receives the output from the core # initializing parameter window parameter_window.setParameters(core.get_parameters()) parameter_window.display() ''' Gets the input from the input toplevel. The input comprises of three elements: 1. Input file (resting-state fMRI) 2. Brain Mask 3. Estimation Rule ''' def makeInput(): start = time.process_time() # interacting with the input window input = input_window.getInput() # interacting with the back-end parameters = parameter_window.getParameters() parameters['estimation'] = input[-2] core.updateParameters( parameters) # only passing the estimation-rule output = core.makeInput(input[:-2]) # receiving input from core output_path = input[-1] # the path to output directory # interacting with the parameter-window parameter_window.setParameters(core.get_parameters()) parameter_window.display() # updating data updateSubjects() # logging time_taken = time.process_time() - start output.set_time(str(time_taken)[:5]) logger.putLog(status=output) def changeEstimationRule(): start = time.process_time() # interacting with the input window input = input_window.getInput() # interacting with the core output = core.updateParameters({"estimation": input[-2]}) # interacting with the parameter-window parameter_window.setParameters(core.get_parameters()) parameter_window.display() # logging time_taken = time.process_time() - start output.set_time(str(time_taken)[:5]) logger.putLog(status=output) def updateParameters(): start = time.process_time() # interacting with the core output = core.updateParameters( dic=parameter_window.updateParameters()) # interacting with the parameter-window parameter_window.setParameters(core.get_parameters()) parameter_window.display() time_taken = time.process_time() - start # logging output.set_time(str(time_taken)[:5]) logger.putLog(status=output) def retrieveHRF(get_pos=False): if "Preprocessed-BOLD" not in current.get(): logger.putLog(status=Status( False, error= "Select a Preprocessed-BOLD Timeseries to retrieve HRF")) else: start = time.process_time() core.updateParameters(dic=parameter_window.updateParameters()) bold_ts = core.get_time_series(current.get()) output = core.retrieveHRF(bold_ts, get_pos) # updating data updateValues(log=False) # logging time_taken = time.process_time() - start if get_pos: output, pos = output else: pos = None output.set_time(str(time_taken)[:5]) logger.putLog(status=output) return pos def retrieveHRFParameters(pos=None): if pos != None: current.set(current.get().split("_")[0] + "_HRF_" + str(pos)) if "HRF" not in current.get(): logger.putLog(status=Status( False, error="Select an HRF Timeseries to retrieve parameters")) else: start = time.process_time() # interacting with the core output = core.getHRFParameters( core.get_time_series(current.get())) # updating data updateValues(log=False) # logging time_taken = time.process_time() - start output.set_time(str(time_taken)[:5]) logger.putLog(status=output) def deconvolveHRF(pos=None): if pos != None: current.set(current.get().split("_")[0] + "_HRF_" + str(pos)) if "HRF" not in current.get(): logger.putLog(status=Status( False, error="Select an HRF Timeseries to deconvolve BOLD")) else: start = time.process_time() # interacting with the core output = core.deconvolveHRF(core.get_time_series( current.get())) # updating data updateValues(log=False) # logging time_taken = time.process_time() - start output.set_time(str(time_taken)[:5]) logger.putLog(status=output) def runCompletePipeline(): if "Preprocessed-BOLD" in current.get(): pos = retrieveHRF(get_pos=True) retrieveHRFParameters(pos) deconvolveHRF(pos) elif "HRF" in current.get(): retrieveHRFParameters() deconvolveHRF() else: logger.putLog(status=Status( False, error= "Select an HRF or Preprocessed-BOLD Timeseries to run pipeline" )) def updatePlots(): # interacting with the core try: plotables = core.get_plotables(current_subject.get()) except: logger.putLog( status=Status(False, error="Please select a subject")) else: # logging if plotables == None: logger.putLog( status=Status(False, error="Please select a subject")) else: logger.putLog(plotables=plotables) # interacting with the plotter plotter.updatePlots(plotables) def getInfo(): try: if len(current.get().split("_")) == 3: logger.putLog(data_info=core.get_store_info(current.get())) else: logger.putLog(status=Status( False, error="Select a valid input to get information")) except: logger.putLog(status=Status( False, error="Select a valid input to get information")) def saveValue(): try: if len(current.get().split("_")) == 3: if os.path.isdir(output_path): out = output_path else: out = os.cwd() if core.save_info(current.get(), out): logger.putLog(status=Status( True, info="File saved successfully")) else: logger.putLog( status=Status(False, error="Unable to save file")) else: logger.putLog(status=Status( False, error="Select a valid input to save")) except: logger.putLog( status=Status(False, error="Select a valid input to save")) def saveForSubject(): try: temp = core.get_data_labels(current_subject.get()) except: logger.putLog( status=Status(False, error="Please select a subject")) else: for each in temp: current.set(each) saveValue() def add_new(l1, l2): if l1 == None: return l2 if l2 == None: return l1 out = [] for each in l1: if each not in l2: out.append(each) for each in l2: out.append(each) return out def updateSubjects(): temp = list(core.get_subjects()) temp.append("None") self.subjects = add_new(self.subjects, temp) self.subjects = sorted(self.subjects) subjectOptions = OptionMenu(root, current_subject, *self.subjects) subjectOptions.grid(row=0, column=1, padx=(30, 30), pady=(5, 5)) def updateValues(log=True): try: temp = core.get_data_labels(current_subject.get()) except: logger.putLog( status=Status(False, error="Please select a subject")) else: if log: logger.putLog( status=Status(True, info="Updated values for subject: " + current_subject.get())) temp.append("None") self.options = add_new(self.options, temp) self.options = sorted(self.options) valueOptions = OptionMenu(root, current, *self.options) valueOptions.grid(row=1, column=1, padx=(30, 30), pady=(5, 5)) # defining the widgets getInput = Button(root, text="Get Input", command=makeInput, height=1, width=20) changeParameterButton = Button(root, text="Update Parameters", command=updateParameters, height=1, width=20) retrieveHRFButton = Button(root, text="Retrieve HRF", command=retrieveHRF, height=1, width=20) retrieveHRFParametersButton = Button(root, text="Retrieve HRF Parameters", command=retrieveHRFParameters, height=1, width=20) deconvolveHRFButton = Button(root, text="Deconvolve BOLD", command=deconvolveHRF, height=1, width=20) updatePlotsButton = Button(root, text="Update Plots", command=updatePlots, height=1, width=20) changeEstimationRule = Button(root, text="Set Estimation Rule", command=changeEstimationRule, height=1, width=20) getValueInfo = Button(root, text="Get Info", command=getInfo, height=1, width=20) storeValue = Button(root, text="Save Value", command=saveValue, height=1, width=20) updateStore = Button(root, text="Update Values", command=updateValues, height=1, width=20) runCompletePipeline = Button(root, text="Run Pipeline", command=runCompletePipeline, height=1, width=20) saveAllValues = Button(root, text="Save All", command=saveForSubject, height=1, width=20) dataLabel = Label(root, text="Stored Values: ") subjectLabel = Label(root, text="Subjects: ") valueOptions = OptionMenu(root, current, *self.options) subjectOptions = OptionMenu(root, current_subject, *self.subjects) # placing the widgets subjectLabel.grid(row=0, column=0, padx=(30, 30), pady=(5, 5)) subjectOptions.grid(row=0, column=1, padx=(30, 30), pady=(5, 5)) dataLabel.grid(row=1, column=0, padx=(30, 30), pady=(5, 5)) valueOptions.grid(row=1, column=1, padx=(30, 30), pady=(5, 5)) getInput.grid(row=2, column=0, padx=(30, 30), pady=(5, 5)) updateStore.grid(row=2, column=1, padx=(30, 30), pady=(5, 5)) changeEstimationRule.grid(row=3, column=0, padx=(30, 30), pady=(5, 5)) changeParameterButton.grid(row=3, column=1, padx=(30, 30), pady=(5, 5)) retrieveHRFButton.grid(row=4, column=0, padx=(30, 30), pady=(5, 5)) retrieveHRFParametersButton.grid(row=4, column=1, padx=(30, 30), pady=(5, 5)) deconvolveHRFButton.grid(row=5, column=0, padx=(30, 30), pady=(5, 5)) updatePlotsButton.grid(row=5, column=1, padx=(30, 30), pady=(5, 5)) getValueInfo.grid(row=6, column=0, padx=(30, 30), pady=(5, 5)) storeValue.grid(row=6, column=1, padx=(30, 30), pady=(5, 5)) runCompletePipeline.grid(row=7, column=0, padx=(30, 30), pady=(5, 5)) saveAllValues.grid(row=7, column=1, padx=(30, 30), pady=(5, 5)) root.mainloop()
class mainApp(Frame): def __init__(self, master, **kw): super().__init__(master, **kw) self.master = master self.proceed = False self.difficulties = ["Expert", "Hard", "Normal", "Easy", "Community"] self.label = Label(self.master, text="Difficulty :") self.label.grid(row=0, column=0) self.difficulty_var = StringVar() self.difficulty_var.set(self.difficulties[0]) self.difficulty_dropdown = OptionMenu(self.master, self.difficulty_var, *self.difficulties) self.difficulty_dropdown.grid(row=0, column=1) self.start_button = Button(self.master, text="Import cues", command=self.import_cues) self.start_button.grid(row=2, columnspan=2) def import_cues(self): def do_work(tracks): initial_dir = os.path.dirname(get_curr_project_filename()) cues_file = filedialog.askopenfilename( initialdir=initial_dir, title="Select cues file", filetypes=(("cues files", "*.cues"), ("all files", "*.*"))) cues = load_cues(cues_file) for cue in cues["cues"]: tick = cue["tick"] tickLength = cue["tickLength"] pitch = cue["pitch"] velocity = cue["velocity"] x = cue["gridOffset"]["x"] y = cue["gridOffset"]["y"] z = 0 if "zOffset" in cue: z = cue["zOffset"] handType = cue["handType"] behavior = cue["behavior"] channel = 0 cc16 = x cc17 = y cc18 = z cc19 = 0 cc20 = 0 cc21 = 0 if behavior == 2: channel = 1 elif behavior == 1: channel = 2 elif behavior == 4: channel = 3 elif behavior == 5: channel = 4 while cc16 > 1: cc16 -= 1 cc19 += 1 while cc17 > 1: cc17 -= 1 cc20 += 1 while cc18 > 1: cc18 -= 1 cc21 += 1 while cc16 < -1: cc16 += 1 cc19 -= 1 while cc17 < -1: cc17 += 1 cc20 -= 1 while cc18 < -1: cc18 += 1 cc21 -= 1 track = None for i in range(len(tracks[0])): if handType == 0: if "Melee" in tracks[1][i]: track = tracks[0][i] elif handType == 1: if "RH" in tracks[1][i]: track = tracks[0][i] elif handType == 2: if "LH" in tracks[1][i]: track = tracks[0][i] take = RPR_GetMediaItemTake(RPR_GetTrackMediaItem(track, 0), 0) RPR_MIDI_InsertNote(take, False, False, tick, tick + tickLength, channel, pitch, velocity, False) if cc16 != 0: RPR_MIDI_InsertCC(take, False, False, tick, 176, 0, 16, int(cc16 * 64 + 64)) if cc17 != 0: RPR_MIDI_InsertCC(take, False, False, tick, 176, 0, 17, int(cc17 * 64 + 64)) if cc18 != 0: RPR_MIDI_InsertCC(take, False, False, tick, 176, 0, 18, int(cc18 * 64 + 64)) if cc19 != 0: RPR_MIDI_InsertCC(take, False, False, tick, 176, 0, 19, int(cc19 + 64)) if cc20 != 0: RPR_MIDI_InsertCC(take, False, False, tick, 176, 0, 20, int(cc20 + 64)) if cc21 != 0: RPR_MIDI_InsertCC(take, False, False, tick, 176, 0, 21, int(cc21 + 64)) if behavior == 2: RPR_MIDI_InsertTextSysexEvt(take, False, False, tick, 1, "h", 1) elif behavior == 1: RPR_MIDI_InsertTextSysexEvt(take, False, False, tick, 1, "v", 1) elif behavior == 4: RPR_MIDI_InsertTextSysexEvt(take, False, False, tick, 1, "C", 1) elif behavior == 5: RPR_MIDI_InsertTextSysexEvt(take, False, False, tick, 1, "c", 1) for i in range(len(cues["tempos"])): RPR_AddTempoTimeSigMarker( 0, RPR_MIDI_GetProjTimeFromPPQPos(take, cues["tempos"][i]["tick"]), cues["tempos"][i]["tempo"], 0, 0, 0) for i in range(len(tracks[0])): trackname = tracks[1][i] take = RPR_GetMediaItemTake( RPR_GetTrackMediaItem(tracks[0][i], 0), 0) RPR_MIDI_InsertTextSysexEvt(take, False, False, 0, 3, trackname, len(trackname)) for repeater in cues["repeaters"]: tick = repeater["tick"] tickLength = repeater["tickLength"] pitch = repeater["pitch"] velocity = repeater["velocity"] handType = repeater["handType"] track = None for i in range(len(tracks[0])): if handType == 0: if "Melee" in tracks[1][i]: track = tracks[0][i] elif handType == 1: if "RH" in tracks[1][i]: track = tracks[0][i] elif handType == 2: if "LH" in tracks[1][i]: track = tracks[0][i] take = RPR_GetMediaItemTake(RPR_GetTrackMediaItem(track, 0), 0) RPR_MIDI_InsertNote(take, False, False, tick, tick + tickLength, 0, pitch, velocity, False) tracks = get_tracks_matching_names([self.difficulty_var.get()]) found = False for track in tracks[0]: if not is_track_empty(track): found = True self.warning_popup() break if self.proceed: for track in tracks[0]: wipe_track(track) self.proceed = False if not is_tempo_empty(): found = True self.warning_popup(mode=1) if self.proceed: wipe_tempo_map() self.proceed = False do_work(tracks) else: do_work(tracks) if found == False: do_work(tracks) def continue_handle(self, button): if button["text"] == "Continue": self.proceed = True elif button["text"] == "Cancel": self.proceed = False self.warning.destroy() def warning_popup(self, mode=0): self.warning = Toplevel() if mode == 0: self.warning_label = Label( self.warning, text= "Found notes in the selected track. If you continue they will be wiped." ) elif mode == 1: self.warning_label = Label( self.warning, text="Found a tempo/time sig marker. All markers will be wiped." ) self.warning_label.grid(row=0, columnspan=20) self.warning_continue_button = Button(self.warning, text="Continue") self.warning_continue_button.grid(row=1, column=9) self.warning_cancel_button = Button(self.warning, text="Cancel") self.warning_cancel_button.grid(row=1, column=10) add_callback(self.warning_continue_button, self.continue_handle) add_callback(self.warning_cancel_button, self.continue_handle) self.warning.wait_window()
class Fenetre(Tk): def __init__(self, partie): super().__init__() # Nom de la fenêtre. self.title("Échiquier") # La position sélectionnée. self.position_selectionnee = None # Truc pour le redimensionnement automatique des éléments de la fenêtre. self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) # Création du canvas échiquier. self.canvas_echiquier = CanvasEchiquier(self, 60, partie) self.canvas_echiquier.grid(sticky=NSEW) # Ajout d'une étiquette d'information. self.messages = Label(self) self.messages.grid() # Création d'un cadre a droite de l'échiquier. self.cadre_droite = Frame(self) self.cadre_droite.grid(row=0, column=1) # Création des étiquettes pour afficher les pièces perdues self.piece_perdue = Frame(self.cadre_droite) self.piece_perdue.grid(row=0, column=0) Label(self.piece_perdue, text="Piece Perdu:", font=("DejaVu Sans", 12)).grid(row=0) Label(self.piece_perdue, text="Noire:", font=("DejaVu Sans", 12)).grid(row=1, column=0) Label(self.piece_perdue, text="Blanc:", font=("DejaVu Sans", 12)).grid(row=2, column=0) Label(self.piece_perdue, text="", font=("DejaVu", 14)).grid(row=1, column=1) Label(self.piece_perdue, text="", font=("DejaVu", 14)).grid(row=2, column=1) # Création des étiquettes pour afficher qui joue self.tour = Label(self.cadre_droite, text="Tour:\nBlanc", font=("DejaVu Sans", 16)) self.tour.grid(row=1, column=0, padx=10, pady=10) cadre_deplacement = Frame(self.cadre_droite) cadre_deplacement.grid(row=2, column=0, padx=10, pady=10) Label(cadre_deplacement, text="Dernier déplacements", font=("DejaVu Sans", 12)).grid(row=0, column=0) self.deplacements = Text(cadre_deplacement, height=5, width=15, wrap=WORD, font=("DejaVu Sans", 12)) self.deplacements.grid(sticky=NSEW) barre_defilement = Scrollbar(cadre_deplacement, orient=VERTICAL) barre_defilement.config(command=self.deplacements.yview) self.deplacements.config(yscrollcommand=barre_defilement.set) barre_defilement.grid(row=1, column=1, sticky=NSEW) self.sauvegarde = Button(self.cadre_droite, text="Annuler dernier deplacement", font=("DejaVu Sans", 10), command=self.annuler_deplacement_avec_message) self.sauvegarde.grid(padx=5, pady=5, sticky=E + W) self.sauvegarde = Button(self.cadre_droite, text="Sauvegarde", font=("DejaVu Sans", 10), command=self.sauvegarder_partie) self.sauvegarde.grid(padx=5, pady=5, sticky=E + W) self.sauvegarde = Button(self.cadre_droite, text="Charger", font=("DejaVu Sans", 10), command=self.charger_partie) self.sauvegarde.grid(padx=5, pady=5, sticky=E + W) self.sauvegarde = Button(self.cadre_droite, text="Nouvelle Partie", font=("DejaVu Sans", 10), command=self.nouvelle_partie) self.sauvegarde.grid(padx=5, pady=5, sticky=E + W) self.couleur_background_defaut = self.cget("bg") self.couleur_theme = StringVar(self.cadre_droite) self.couleur_theme.set('Thème gris (défaut)') self.drop = OptionMenu(self.cadre_droite, self.couleur_theme, 'Thème jaune', 'Thème bleu', 'Thème gris (défaut)', command=self.changer_theme) self.drop.grid(padx=5, pady=5, sticky=W) self.fin_partie_echec_et_mat = False self.canvas_echiquier.bind('<Button-1>', self.selectionner) def changer_theme(self, couleur): if couleur == 'Thème jaune': couleur = 'LightYellow' elif couleur == 'Thème bleu': couleur = 'LightBlue' else: couleur = self.couleur_background_defaut super().configure(background=couleur) self.cadre_droite.configure(background=couleur) self.piece_perdue.configure(background=couleur) def selectionner(self, event): echec_au_roi = False if not self.canvas_echiquier.partie.partie_terminee( ) and not self.fin_partie_echec_et_mat: # On trouve le numéro de ligne/colonne en divisant les positions en y/x par le nombre de pixels par case. ligne = event.y // self.canvas_echiquier.n_pixels_par_case colonne = event.x // self.canvas_echiquier.n_pixels_par_case position = "{}{}".format( self.canvas_echiquier.lettres_colonnes[colonne], int(self.canvas_echiquier.chiffres_rangees[ self.canvas_echiquier.n_lignes - ligne - 1])) #si une pièce est déjà sélectionnée, on attend sa position cible if self.position_selectionnee != None: try: self.canvas_echiquier.partie.echiquier.deplacer( self.position_selectionnee, position ) # les exceptions sont situées dans cette fonction if self.verifier_echec_au_roi( self.canvas_echiquier.partie.joueur_actif): self.annuler_deplacement_sans_message() self.messages['foreground'] = 'red' self.messages[ 'text'] = 'Déplacement invalide; Roi en position échec.' echec_au_roi = True self.canvas_echiquier.dessiner_cases(None) self.canvas_echiquier.dessiner_pieces() if not echec_au_roi: self.messages['foreground'] = 'black' self.messages[ 'text'] = 'Déplacement effectué de {} à {}.'.format( self.position_selectionnee, position) self.canvas_echiquier.partie.joueur_suivant() echec_au_roi = self.verifier_echec_au_roi( self.canvas_echiquier.partie.joueur_actif) if echec_au_roi != False: if self.verifier_echec_et_mat( echec_au_roi, self.canvas_echiquier.partie.joueur_actif): self.messages['foreground'] = 'black' self.fin_partie_echec_et_mat = True self.canvas_echiquier.partie.joueur_suivant() gagnant_partie = self.canvas_echiquier.partie.joueur_actif self.messages[ 'text'] = 'Échec et mat; félicitations au joueur {}'.format( gagnant_partie) self.canvas_echiquier.partie.joueur_suivant() self.sauvegarder_deplacement(self.position_selectionnee, position) if self.canvas_echiquier.partie.echiquier.deplacements[ -1] != None: self.update_piece_perdu() self.tour['text'] = "Tour:\n{}".format( self.canvas_echiquier.partie.joueur_actif.title()) self.position_selectionnee = None except reclic_sur_piece: # si le joueur reclique sur sa piece, on désélectionne la pièce self.position_selectionnee = None self.canvas_echiquier.dessiner_cases( self.position_selectionnee) self.canvas_echiquier.dessiner_pieces() except deplacement_invalide: try: assert self.canvas_echiquier.pieces[ position].couleur == self.canvas_echiquier.partie.joueur_actif self.position_selectionnee = position piece = self.canvas_echiquier.pieces[position] self.messages['foreground'] = 'black' self.messages[ 'text'] = 'Pièce sélectionnée : {} à la position {}.'.format( piece, self.position_selectionnee) self.canvas_echiquier.dessiner_cases( self.position_selectionnee) self.canvas_echiquier.dessiner_pieces() except (AssertionError, KeyError): self.messages['foreground'] = 'red' self.messages[ 'text'] = 'Veuillez sélectionner un déplacement valide' else: try: piece = self.canvas_echiquier.pieces[position] assert piece.couleur == self.canvas_echiquier.partie.joueur_actif self.position_selectionnee = position self.messages['foreground'] = 'black' self.messages[ 'text'] = 'Pièce sélectionnée : {} à la position {}.'.format( piece, self.position_selectionnee) self.canvas_echiquier.dessiner_cases( self.position_selectionnee ) # on redessine les cases pour visualiser la selection self.canvas_echiquier.dessiner_pieces() except KeyError: # s'il n'y a pas de piece à l'endroit sélectionné self.messages['foreground'] = 'red' self.messages[ 'text'] = 'Erreur: Aucune pièce à cet endroit.' except AssertionError: # si ce n'est pas le tour du joueur de la couleur de la pièce sélectionnée self.messages['foreground'] = 'red' self.messages[ 'text'] = 'C\'est au tour du joueur {}.'.format( self.canvas_echiquier.partie.joueur_actif) def verifier_echec_au_roi(self, couleur): deplacements = {} echec = {} dictionnaire_pieces = self.canvas_echiquier.partie.echiquier.dictionnaire_pieces for position_source, piece in dictionnaire_pieces.items(): if isinstance(piece, Roi) and piece.couleur == couleur: position_roi = position_source elif piece.couleur != couleur: deplacement_piece = self.deplacement_possible( position_source, piece) if deplacement_piece != None: deplacements[position_source] = deplacement_piece for position_source, deplacement_possible in deplacements.items(): for position in deplacement_possible: if position == position_roi: echec[position_source] = deplacement_possible if len(echec) == 0: return False else: self.messages['foreground'] = 'red' self.messages['text'] = 'Échec au Roi' return echec def verifier_echec_et_mat(self, echecs, couleur): positions_echec = [] deplacements_piece = {} dictionnaire_pieces = self.canvas_echiquier.partie.echiquier.dictionnaire_pieces # on trouve la position du roi for position_source, piece in dictionnaire_pieces.items(): if isinstance(piece, Roi) and piece.couleur == couleur: position_roi = position_source roi = piece for echec in echecs.values(): positions_echec = positions_echec + echec # déplacements possibles du roi deplacement_roi = self.deplacement_possible(position_roi, roi) for deplacement in deplacement_roi: if deplacement not in positions_echec: return False # si une seule pièce met en échec, vérifie si on peut la manger if len(echecs) == 1: for echec in echecs.keys(): position_piece_echec = echec for position_source, piece in dictionnaire_pieces.items(): if isinstance(piece, Roi) == False and piece.couleur == couleur: deplacement = self.deplacement_possible( position_source, piece) if deplacement != None: if position_piece_echec in deplacement: return False else: deplacements_piece[position_source] = deplacement # On continue la recherche de pour l'échec et mat # on regarde si les déplacements possibles des pièces permettent de protéger le Roi for position_source, deplacements in deplacements_piece.items(): for deplacement in deplacements: self.canvas_echiquier.partie.echiquier.dictionnaire_pieces[ deplacement] = self.canvas_echiquier.partie.echiquier.recuperer_piece_a_position( position_source) if self.verifier_echec_au_roi(couleur) == False: del self.canvas_echiquier.partie.echiquier.dictionnaire_pieces[ deplacement] return False del self.canvas_echiquier.partie.echiquier.dictionnaire_pieces[ deplacement] # Aucune solution possible # échec et mat return True def deplacement_possible(self, position_source, piece): deplacements = [] for colonne in self.canvas_echiquier.lettres_colonnes: for rangee in self.canvas_echiquier.chiffres_rangees: if self.canvas_echiquier.partie.echiquier.deplacement_est_valide( position_source, colonne + rangee): deplacements.append(colonne + rangee) if len(deplacements) == 0: return None else: return deplacements def verifier_si_partie_terminee(self): gagnant_partie = self.canvas_echiquier.partie.determiner_gagnant() if gagnant_partie != 'aucun': self.messages['foreground'] = 'black' self.messages[ 'text'] = 'La partie est terminée; félicitations au joueur {}.'.format( gagnant_partie) def sauvegarder_partie(self): nom_fichier_sortie = filedialog.asksaveasfilename(title='Copy', filetypes=[('txt', '*txt')]) if nom_fichier_sortie == '': return None ma_chaine = nom_fichier_sortie.split('.') if len(ma_chaine) > 1: self.messages['foreground'] = 'red' self.messages[ 'text'] = 'Partie non sauvegarder, veiller entrer un extension valide.' return None if len(ma_chaine) == 1: nom_fichier_sortie += '.txt' elif ma_chaine[1] != '.txt': nom_fichier_sortie = ma_chaine[0] + '.txt' fichier_sortie = open(nom_fichier_sortie, 'w') fichier_sortie.write('joueur_actif:{}\n\n'.format( self.canvas_echiquier.partie.joueur_actif)) fichier_sortie.write('pieces:{}\n') pieces = self.canvas_echiquier.pieces for cle in pieces: fichier_sortie.write('{}:{}:{}\n'.format( cle, self.canvas_echiquier.pieces[cle].__class__.__name__, pieces[cle].couleur)) fichier_sortie.write('\ndeplacements:{}\n') deplacements = self.canvas_echiquier.partie.echiquier.deplacements for index, value in enumerate(deplacements): if value[3].__class__.__name__ == 'NoneType': value3 = None else: value3 = value[3].__class__.__name__ fichier_sortie.write('{}:{}:{}:{}:{}\n'.format( index + 1, value[0], value[1], value[2], value3)) fichier_sortie.close() def charger_partie(self): nom_fichier_entré = filedialog.askopenfilename(title='Copy', filetypes=[('txt', '*txt')]) if nom_fichier_entré == '': return None fichier_entré = open(nom_fichier_entré, 'r') self.canvas_echiquier.partie.echiquier.initialiser_echiquier_depart self.fin_partie_echec_et_mat = False ma_chaine = fichier_entré.readline() ma_chaine = ma_chaine[:-1].split(':') self.canvas_echiquier.partie.joueur_actif = ma_chaine[1] ma_chaine = fichier_entré.readlines(2) ma_chaine = fichier_entré.readline() pieces = {} while ma_chaine != '\n': position, piece, couleur = ma_chaine[:-1].split(':') if piece == "Roi": pieces[position] = Roi(couleur) elif piece == "Dame": pieces[position] = Dame(couleur) elif piece == "Cavalier": pieces[position] = Cavalier(couleur) elif piece == "Fou": pieces[position] = Fou(couleur) elif piece == "Tour": pieces[position] = Tour(couleur) elif piece == "Pion": pieces[position] = Pion(couleur) ma_chaine = fichier_entré.readline() self.canvas_echiquier.partie.echiquier.dictionnaire_pieces = pieces self.canvas_echiquier.pieces = pieces ma_chaine = fichier_entré.readline() ma_chaine = fichier_entré.readline() self.deplacements.delete('1.0', END) self.canvas_echiquier.partie.echiquier.deplacements = [] while ma_chaine != '': index, couleur, position1, position2, perdue = ma_chaine[: -1].split( ':') if couleur == 'blanc': couleur2 = 'noir' else: couleur2 = 'blanc' if perdue == "Roi": perdue = Roi(couleur2) elif perdue == "Dame": perdue = Dame(couleur2) elif perdue == "Cavalier": perdue = Cavalier(couleur2) elif perdue == "Fou": perdue = Fou(couleur2) elif perdue == "Tour": perdue = Tour(couleur2) elif perdue == "Pion": perdue = Pion(couleur2) else: perdue = None self.canvas_echiquier.partie.echiquier.deplacements.append( [couleur, position1, position2, perdue]) texte_cible = "{}. {}: {} - {}\n".format(index, couleur, position1, position2) self.deplacements.insert('1.0', texte_cible) ma_chaine = fichier_entré.readline() self.messages['foreground'] = 'black' self.messages['text'] = 'C\'est au tour du joueur {}.'.format( self.canvas_echiquier.partie.joueur_actif) self.canvas_echiquier.dessiner_cases(None) self.canvas_echiquier.delete('piece') self.canvas_echiquier.dessiner_pieces() self.update_piece_perdu() fichier_entré.close() self.tour['text'] = "Tour:\n{}".format( self.canvas_echiquier.partie.joueur_actif.title()) def nouvelle_partie(self): self.canvas_echiquier.partie.echiquier.initialiser_echiquier_depart() self.canvas_echiquier.pieces = self.canvas_echiquier.partie.echiquier.dictionnaire_pieces self.canvas_echiquier.partie.joueur_actif = 'blanc' self.deplacements.delete('1.0', END) self.tour['text'] = "Tour:\n{}".format( self.canvas_echiquier.partie.joueur_actif.title()) self.canvas_echiquier.delete('piece') self.canvas_echiquier.dessiner_pieces() self.fin_partie_echec_et_mat = False self.messages['foreground'] = 'black' self.messages['text'] = 'C\'est au tour du joueur {}.'.format( self.canvas_echiquier.partie.joueur_actif) def sauvegarder_deplacement(self, position_selectionnee, position): mouvement_numero = len( self.canvas_echiquier.partie.echiquier.deplacements) texte_cible = "{}. {}: {} - {}\n".format( mouvement_numero, self.canvas_echiquier.partie.joueur_actif, position_selectionnee, position) self.deplacements.insert('1.0', texte_cible) def annuler_deplacement_sans_message(self): self.fin_partie_echec_et_mat = False self.dictionnaire_pieces = self.canvas_echiquier.partie.echiquier.dictionnaire_pieces self.liste_deplacements = self.canvas_echiquier.partie.echiquier.deplacements dernier_deplacement = self.liste_deplacements[-1] position_initiale = dernier_deplacement[1] position_finale = dernier_deplacement[2] piece_mangee = dernier_deplacement[3] self.dictionnaire_pieces[position_initiale] = self.dictionnaire_pieces[ position_finale] if piece_mangee == None: del self.dictionnaire_pieces[position_finale] else: self.dictionnaire_pieces[position_finale] = piece_mangee del (self.liste_deplacements[-1]) self.canvas_echiquier.partie.joueur_suivant() self.tour['text'] = "Tour:\n{}".format( self.canvas_echiquier.partie.joueur_actif.title()) self.deplacements.delete('1.0', '2.0') self.canvas_echiquier.delete('piece') self.canvas_echiquier.dessiner_pieces() self.update_piece_perdu() def annuler_deplacement_avec_message(self): self.annuler_deplacement_sans_message() self.messages['foreground'] = 'black' self.messages['text'] = 'C\'est au tour du joueur {}.'.format( self.canvas_echiquier.partie.joueur_actif) def update_piece_perdu(self): caracteres_pieces = { 'PB': '\u2659', 'PN': '\u265f', 'TB': '\u2656', 'TN': '\u265c', 'CB': '\u2658', 'CN': '\u265e', 'FB': '\u2657', 'FN': '\u265d', 'RB': '\u2654', 'RN': '\u265a', 'DB': '\u2655', 'DN': '\u265b' } piece_blanc = '' piece_noir = '' for deplacement in self.canvas_echiquier.partie.echiquier.deplacements: if deplacement[3] != None: if deplacement[3].couleur == 'noir': piece = deplacement[3].__class__.__name__ piece = str.upper(piece[:1]) + 'N' piece_blanc = piece_blanc + ' ' + caracteres_pieces[piece] if deplacement[3].couleur == 'blanc': piece = deplacement[3].__class__.__name__ piece = str.upper(piece[:1]) + 'B' piece_noir = piece_noir + ' ' + caracteres_pieces[piece] Label(self.piece_perdue, text=piece_noir + ' ', font=("DejaVu", 14)).grid(row=1, column=1) Label(self.piece_perdue, text=piece_blanc + ' ', font=("DejaVu", 14)).grid(row=2, column=1)
def create_widgets(self) : #Search keyword self.keyword_desc = Label(self,text="Enter Keyword") self.keyword_desc.grid(row=0, column=0, columnspan=3) self.keyword = Entry(self) self.keyword.grid(row=1, column=0, columnspan=3) #Divider self.div1 = Label(self,text="____________________________________________________________________") self.div1.grid(row=3, column=0, columnspan=3) #ADVANCED OPTIONS self.advanced_opts_div = Label(self,text="ADVANCED OPTIONS") self.advanced_opts_div.grid(row=4, column=0, columnspan=3) #Divider self.div2 = Label(self,text="____________________________________________________________________") self.div2.grid(row=5, column=0, columnspan=3) #MAX_Results self.max_results_desc = Label(self,text="Maximum Results") self.max_results_desc.grid(row=7, column=0, columnspan=1) self.max_results = Entry(self) self.max_results.grid(row=8, column=0, columnspan=1) #Geocode #(latitude,longitude,radius[mi/km]) self.geocode_desc = Label(self,text="Enter Geocode") self.geocode_desc.grid(row=7, column=1, columnspan=1) self.geocode = Entry(self) self.geocode.grid(row=8, column=1, columnspan=1) #Lang #use 639-1 language codes #picked top languages http://www.statista.com/statistics/267129/most-used-languages-on-twitter/ self.lang_desc = Label(self,text="Select Language") self.lang_desc.grid(row=7, column=2, columnspan=1) self.lang_options = {'None':'None','Arabic':'ar', 'Dutch':'nl', 'English':'en', 'Japanese':'ja', 'Korean':'ko', 'Portuguese':'pt', 'Spanish':'es', 'Malay':'ms', 'Thai':'th'} self.lang_v = StringVar() self.lang_v.set(self.lang_options['None']) self.lang_om = OptionMenu(self, self.lang_v, *self.lang_options) self.lang_om.grid(row=8, column=2, columnspan=1) #Result_type self.result_type_desc = Label(self,text="Select Result Type") self.result_type_desc.grid(row=9, column=0, columnspan=1) result_type_options = ['Mixed','Recent','Popular'] self.result_type_v = StringVar() self.result_type_v.set(result_type_options[0]) self.result_type_om = OptionMenu(self, self.result_type_v, *result_type_options) self.result_type_om.grid(row=10, column=0, columnspan=1) #Max Date #(YYYY-MM-DD) self.max_date_desc = Label(self,text="Enter Max Date") self.max_date_desc.grid(row=9, column=2, columnspan=1) self.max_date = Entry(self) self.max_date.grid(row=10, column=2, columnspan=1) #Divider self.div3 = Label(self,text="____________________________________________________________________") self.div3.grid(row=11, column=0, columnspan=3) #File Name self.file_name = Button(self, text="Save as...", command=self.save_as) self.file_name.grid(row=12, column=0, columnspan=1) #Execute search self.search_button = Button(self, text="Search", command=self.start_search) self.search_button.grid(row=12, column=2, columnspan=1)
def __init__(self, partie): super().__init__() # Nom de la fenêtre. self.title("Échiquier") # La position sélectionnée. self.position_selectionnee = None # Truc pour le redimensionnement automatique des éléments de la fenêtre. self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) # Création du canvas échiquier. self.canvas_echiquier = CanvasEchiquier(self, 60, partie) self.canvas_echiquier.grid(sticky=NSEW) # Ajout d'une étiquette d'information. self.messages = Label(self) self.messages.grid() # Création d'un cadre a droite de l'échiquier. self.cadre_droite = Frame(self) self.cadre_droite.grid(row=0, column=1) # Création des étiquettes pour afficher les pièces perdues self.piece_perdue = Frame(self.cadre_droite) self.piece_perdue.grid(row=0, column=0) Label(self.piece_perdue, text="Piece Perdu:", font=("DejaVu Sans", 12)).grid(row=0) Label(self.piece_perdue, text="Noire:", font=("DejaVu Sans", 12)).grid(row=1, column=0) Label(self.piece_perdue, text="Blanc:", font=("DejaVu Sans", 12)).grid(row=2, column=0) Label(self.piece_perdue, text="", font=("DejaVu", 14)).grid(row=1, column=1) Label(self.piece_perdue, text="", font=("DejaVu", 14)).grid(row=2, column=1) # Création des étiquettes pour afficher qui joue self.tour = Label(self.cadre_droite, text="Tour:\nBlanc", font=("DejaVu Sans", 16)) self.tour.grid(row=1, column=0, padx=10, pady=10) cadre_deplacement = Frame(self.cadre_droite) cadre_deplacement.grid(row=2, column=0, padx=10, pady=10) Label(cadre_deplacement, text="Dernier déplacements", font=("DejaVu Sans", 12)).grid(row=0, column=0) self.deplacements = Text(cadre_deplacement, height=5, width=15, wrap=WORD, font=("DejaVu Sans", 12)) self.deplacements.grid(sticky=NSEW) barre_defilement = Scrollbar(cadre_deplacement, orient=VERTICAL) barre_defilement.config(command=self.deplacements.yview) self.deplacements.config(yscrollcommand=barre_defilement.set) barre_defilement.grid(row=1, column=1, sticky=NSEW) self.sauvegarde = Button(self.cadre_droite, text="Annuler dernier deplacement", font=("DejaVu Sans", 10), command=self.annuler_deplacement_avec_message) self.sauvegarde.grid(padx=5, pady=5, sticky=E + W) self.sauvegarde = Button(self.cadre_droite, text="Sauvegarde", font=("DejaVu Sans", 10), command=self.sauvegarder_partie) self.sauvegarde.grid(padx=5, pady=5, sticky=E + W) self.sauvegarde = Button(self.cadre_droite, text="Charger", font=("DejaVu Sans", 10), command=self.charger_partie) self.sauvegarde.grid(padx=5, pady=5, sticky=E + W) self.sauvegarde = Button(self.cadre_droite, text="Nouvelle Partie", font=("DejaVu Sans", 10), command=self.nouvelle_partie) self.sauvegarde.grid(padx=5, pady=5, sticky=E + W) self.couleur_background_defaut = self.cget("bg") self.couleur_theme = StringVar(self.cadre_droite) self.couleur_theme.set('Thème gris (défaut)') self.drop = OptionMenu(self.cadre_droite, self.couleur_theme, 'Thème jaune', 'Thème bleu', 'Thème gris (défaut)', command=self.changer_theme) self.drop.grid(padx=5, pady=5, sticky=W) self.fin_partie_echec_et_mat = False self.canvas_echiquier.bind('<Button-1>', self.selectionner)
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("") #self.style = Style() #self.style.theme_use("clam") #self.pack(fill=BOTH, expand = 1) self.labelU = Label(self, text="U:") self.labelP = Label(self, text="P:") self.mailrecipient = 'GoldenSights' self.entryUsername = Entry(self) self.entryUsername.focus_set() self.entryUsername.bind('<Return>', lambda event: self.entryPassword.focus_set()) self.entryPassword = Entry(self) self.entryPassword.config(show='•') self.entryPassword.bind('<Return>', lambda event: self.login(self.entryUsername.get(), self.entryPassword.get())) self.newbutton = Button(self, text="Login", command= lambda: self.login(self.entryUsername.get(), self.entryPassword.get())) self.newbutton.bind('<Return>', lambda event: self.login(self.entryUsername.get(), self.entryPassword.get())) self.newbutton.config(width=6) self.quitbutton = Button(self, text="Quit", command= lambda: self.quit()) self.quitbutton.config(width=6) self.labelU.grid(row=0, column=0,padx=0) self.entryUsername.grid(row=0, column=1) self.labelP.grid(row=1, column=0) self.entryPassword.grid(row=1, column=1, pady=4) self.newbutton.grid(row=2, column=1) self.quitbutton.grid(row=3, column=1, pady=4) self.labelErrorPointer = Label(self, text="◀") self.indicatorGreen = PhotoImage(file="indicatorGreen.gif") self.indicatorRed = PhotoImage(file="indicatorRed.gif") self.indicatorBlue = PhotoImage(file="indicatorBlue.gif") self.indicatorBlack = PhotoImage(file="indicatorBlack.gif") sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() w=400 h=480 x = (sw - w) / 2 y = (sh - h) / 2 self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y-50)) def login(self, username, password): print('U: ' + username) self.username = username if username == '' or not all(char in string.ascii_letters+string.digits+'_-' for char in username): print('Please enter a username') self.entryUsername.focus_set() self.labelErrorPointer.grid(row=0, column=2) elif password == '': print('Please enter a password') self.entryPassword.focus_set() self.labelErrorPointer.grid(row=1, column=2) else: self.labelErrorPointer.grid_forget() print('Attempting login for ' + username) try: self.USERAGENT = username + ' practices Tkinter+PRAW mixing with utility by /u/GoldenSights.' self.r = praw.Reddit(self.USERAGENT) #self.r.login(username, password) print('Success') self.labelU.grid_forget() self.labelP.grid_forget() self.entryUsername.grid_forget() self.entryPassword.grid_forget() self.newbutton.grid_forget() self.quitbutton.grid_forget() self.usernamelabel = Label(self, text=username + ', Sending to /u/' + self.mailrecipient) self.usernamelabel.grid(row=0, column=0, columnspan=8) self.quitbutton.grid(row=900, column=0) self.labellist = [] self.entrylist = [] self.verifylist = [] self.misclist = [] self.optionDiscuss = "Discussion Flair + Crossposting" self.optionRegister = "Register a new Candidate" self.prevmode = self.optionDiscuss self.curmode = self.optionDiscuss self.optionvar = tkinter.StringVar(self) self.optionvar.trace("w",self.permaloop) self.optionvar.set(self.optionDiscuss) self.option = OptionMenu(self, self.optionvar, self.optionDiscuss, self.optionRegister, "three", "four") self.newbutton.unbind("<Return>") self.entryUsername.unbind("<Return>") self.entryPassword.unbind("<Return>") self.option.grid(row=1,column=0,columnspan=8,pady=8) self.updategui(True) except praw.errors.InvalidUserPass: pass print('Invalid username or password') self.entryPassword.delete(0,200) self.labelErrorPointer.grid(row=1, column=2) def permaloop(self, *args): self.curmode = self.optionvar.get() print('Was: ' + self.prevmode + ' | Now: ' + self.curmode) if self.curmode != self.prevmode: self.prevmode = self.curmode self.updategui(True) def updategui(self, *args): if args[0] == True: print('Cleaning GUI') for item in self.labellist: item.grid_forget() for item in self.entrylist: item.grid_forget() for item in self.verifylist: item.grid_forget() for item in self.misclist: item.grid_forget() self.labellist = [] self.entrylist = [] self.verifylist = [] self.misclist = [] if self.curmode == self.optionDiscuss: self.newrowindex = 4 self.labelPermalink = Label(self, text="Thread Permalink:") self.entryPermalink = Entry(self) self.rowconfigure(2,weight=2) self.labelPermalink.grid(row=2,column=0) self.entryPermalink.grid(row=2,column=1) self.labelcrossposting = Label(self,text="Crosspost to:") self.labelcrossposting.grid(row=3,column=0,columnspan=2,sticky="w") for m in range(5): self.redditlabel = Label(self,text="/r/") self.redditlabel.grid(row=self.newrowindex,column=0, sticky="e") self.labellist.append(self.redditlabel) self.redditentry = Entry(self) self.redditentry.grid(row=self.newrowindex,column=1) self.entrylist.append(self.redditentry) self.newrowindex +=1 self.morerowbutton = Button(self,text="+row",command=lambda: self.morerows('/r/', 0, 1, 20)) self.morerowbutton.grid(row=898,column=0,columnspan=2) self.verifybutton = Button(self,text="Verify",command= lambda: self.updategui(False)) self.verifybutton.grid(row=899,column=0,columnspan=2) self.newrowindex += 2 self.misclist.append(self.labelPermalink) self.misclist.append(self.labelcrossposting) self.misclist.append(self.entryPermalink) self.misclist.append(self.morerowbutton) self.misclist.append(self.verifybutton) if self.curmode == self.optionRegister: self.newrowindex = 6 self.labelCanUsername = Label(self, text="Candidate's Username: /u/") self.entryCanUsername = Entry(self) self.labelCanRealname = Label(self, text="Candidate's Realname:") self.entryCanRealname = Entry(self) self.labelCanFlair = Label(self, text="Candidate's Flair:") self.entryCanFlair = Entry(self) self.entryMo = Spinbox(self, width=9, values=('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')) self.entryDa = Spinbox(self, width=2, from_=1, to=31) self.entryYr = Spinbox(self, width=4, from_=2014, to=2500) self.labelHH = Label(self, text="Schedule time UTC:") self.entryHH = Spinbox(self, from_=0, to=23, width=2) self.entryMM = Spinbox(self, from_=0, to=59, width=2) self.entryYr.delete(0,'end') self.entryYr.insert(0,2014) self.morerowbutton = Button(self,text="+question",command=lambda: self.morerows('Q:', 0, 1, 25)) self.morerowbutton.grid(row=898,column=0,columnspan=8) self.verifybutton = Button(self,text="Verify",command= lambda: self.updategui(False)) self.verifybutton.grid(row=899,column=0,columnspan=8) self.misclist.append(self.labelCanUsername) self.misclist.append(self.labelCanRealname) self.misclist.append(self.entryCanUsername) self.misclist.append(self.entryCanRealname) self.misclist.append(self.labelHH) self.misclist.append(self.entryHH) self.misclist.append(self.entryMM) self.misclist.append(self.entryMo) self.misclist.append(self.entryDa) self.misclist.append(self.entryYr) self.labelCanUsername.grid(row=2, column=0, sticky="e") self.labelCanRealname.grid(row=3, column=0, sticky="e") self.entryCanUsername.grid(row=2, column=1, columnspan=3) self.entryCanRealname.grid(row=3, column=1, columnspan=3) self.entryMo.grid(row=4, column=1,sticky="e") self.entryDa.grid(row=4, column=2) self.entryYr.grid(row=4, column=3) self.labelHH.grid(row=4, column=0, sticky="se", pady=5) self.entryHH.grid(row=5, column=1, sticky="e") self.entryMM.grid(row=5, column=2, sticky="w") else: if self.curmode == self.optionDiscuss: verifies = [] i = self.entryPermalink.get() if len(i) == 6: pid = i else: if 'www.reddit.com/r/' in i and '/comments/' in i: pid = i.split('/comments/')[1].split('/')[0] if 'http://redd.it/' in i: pid = i.split('redd.it/')[1] for flag in self.verifylist: flag.grid_forget() self.verifylist.remove(flag) try: print('Fetching Submission ' + pid) self.r.get_info(thing_id="t3_" + pid).title + 'Check' self.redditlabel = Label(self, image=self.indicatorGreen) self.redditlabel.grid(row=2,column=2) self.verifylist.append(self.redditlabel) verifies.append(True) print('\tSuccess') except: print('Failed. Make sure to include the http://. Copy and paste straight from your browser for best result') self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=2,column=2) self.verifylist.append(self.redditlabel) verifies.append(False) for entry in self.entrylist: i = entry.get() if i != '': print('Fetching /r/' + i) if all(char in string.ascii_letters+string.digits+'_-' for char in i): try: sub = self.r.get_subreddit(i,fetch=True) self.redditlabel = Label(self, image=self.indicatorGreen) self.redditlabel.grid(row=entry.grid_info()['row'],column=2) self.verifylist.append(self.redditlabel) verifies.append(True) print('\tSuccess') except: self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=entry.grid_info()['row'],column=2) self.verifylist.append(self.redditlabel) verifies.append(False) print('\tFailed') time.sleep(2) else: self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=entry.grid_info()['row'],column=2) self.verifylist.append(self.redditlabel) verifies.append(False) print('\tFailed') print(verifies) if self.curmode == self.optionRegister: verifies = [] u=self.entryCanUsername.get() print('Fetching /u/' + u) if not all(char in string.ascii_letters+string.digits+'_-' for char in u): self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=2, column=4) self.verifylist.append(self.redditlabel) verifies.append(False) print('\tBad characterage') else: try: u = self.r.get_redditor(u) print(u) self.redditlabel = Label(self, image=self.indicatorGreen) self.redditlabel.grid(row=2,column=4) self.verifylist.append(self.redditlabel) verifies.append(True) print('\tSuccess') except: self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=2,column=4) self.verifylist.append(self.redditlabel) verifies.append(False) print('\tFailed') try: print('Checking Time') t = self.entryMo.get() + ' ' + self.entryDa.get() + ' ' + self.entryYr.get() + ' ' + self.entryHH.get() + ':' + self.entryMM.get() plandate = datetime.datetime.strptime(t, "%B %d %Y %H:%M") plandate = datetime.datetime.utcfromtimestamp(plandate.timestamp()) print('\t' + str(plandate.timestamp())) self.redditlabel = Label(self, image=self.indicatorGreen) self.redditlabel.grid(row=5,column=3) self.verifylist.append(self.redditlabel) verifies.append(True) except: print('\tFailed') self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=5,column=3) self.verifylist.append(self.redditlabel) verifies.append(False) print(verifies) def morerows(self, label, columnm, columnn, limit, *args): self.redditlabel = Label(self,text=label) self.redditlabel.grid(row=self.newrowindex,column=columnm, sticky="e") self.labellist.append(self.redditlabel) self.redditentry = Entry(self) self.redditentry.grid(row=self.newrowindex,column=columnn, columnspan=8) self.entrylist.append(self.redditentry) self.newrowindex += 1 if self.newrowindex >= limit: self.morerowbutton.grid_forget() print(self.newrowindex)
def init_project_frame( self ) : projframe = Frame(self) ###################### #The Project Entry Form # #Current design inherited from others #is very bad. It should have been made as #json or dictionary as is in this point #then the subsequent coding will be much #eaiser. #BK ###################### BS=StringVar() self.eprojectid = eprojectid= StringVar() self.eorganism = eorganism=StringVar() self.eanalyst = eanalyst=StringVar() self.epoc = epoc=StringVar() self.epi = epi=StringVar() self.euser = euser=StringVar() self.eflowcell = eflowcell=StringVar() self.eplatform = eplatform=StringVar() eplatform.set("Illumina") self.technique = technique=StringVar() self.pipehome = pipehome=StringVar() pipehome.set(PIPELINER_HOME) editframe = Frame( self ) editframe.grid( column=0, row=3, columnspan=3 ) projpanel1 = LabelFrame(editframe,text="Project Information") #,fg=textLightColor,bg=baseColor) projpanel1.pack( side = TOP, fill=X, padx=10, pady=5, expand=YES ) pipeline_panel = LabelFrame(editframe, text="Global Settings") pipeline_panel.pack( side=TOP, fill=X, padx=10, pady=5, expand=YES ) l=Label( pipeline_panel, text="Genome:" ) l.grid(row=1,column=3,sticky=W,padx=0,pady=5) l = Label( pipeline_panel, text="Pipeline Family:" ) l.grid(row=1,column=1,sticky=W,padx=0,pady=5) annotations=['hg19','mm10','mm9','hg38','GRCh38'] self.annotation = annotation = StringVar() annotation.set(annotations[0]) #annotation.trace('w', lambda *_ :settargets(annotation) ) om = OptionMenu(pipeline_panel, annotation, *annotations, command=self.set_pipeline) #, command=lambda _:makejson("refsets")) om.config() #bg = widgetBgColor,fg=widgetFgColor) om["menu"].config() #bg = widgetBgColor,fg=widgetFgColor) om.grid(row=1,column=4,sticky=W,padx=10,pady=10) pfamilys = ['exomeseq', 'rnaseq', 'genomeseq', 'mirseq', 'ChIPseq', 'scrnaseq'] self.pfamily = pfamily = StringVar() pfamily.set('Select a pipeline') om = OptionMenu(pipeline_panel, pfamily, *pfamilys, command=self.set_pipeline) #, command=lambda _:makejson(pfamily.get())) om.config() #bg = widgetBgColor,fg=widgetFgColor) om["menu"].config() #bg = widgetBgColor,fg=widgetFgColor) om.grid(row=1,column=2,sticky=W,padx=10,pady=5) #add_button = Button( pipeline_panel, # text="Set a pipeline", # command=self.add_pipeline # ) #add_button.grid(row=1, column=5, sticky=W, padx=10, pady=5) self.notebook = notebook = Notebook( editframe ) self.pipelineframe = None #the pipeline frame in the notebook frame! projpanel2 = Frame(notebook) #,fg=textLightColor,bg=baseColor) projpanel2.pack( side = LEFT, fill=BOTH, padx=10, pady=5, expand=YES ) notebook.add( projpanel2, text="Project Description" ) notebook.pack( side=LEFT, fill=BOTH, padx=10, pady=5, expand=YES ) Dscrollbar = Scrollbar(projpanel2) Dscrollbar.grid(row=2,column=4,rowspan=40) self.description =description= Text(projpanel2, width=75, height=28, #bg=commentBgColor, #fg=commentFgColor, font=("nimbus mono bold","10"), yscrollcommand = Dscrollbar.set) description.delete("1.0", END) description.insert(INSERT, "Enter CCBR Project Description and Notes here.") #description.bind('<FocusOut>',lambda _:makejson("none")) description.grid(row=2,column=3,sticky="e",padx=10,pady=5) Dscrollbar['command']=description.yview L=Label(projpanel1, text="Project Id", anchor="ne" ) #,bg=baseColor,fg=textLightColor) E = Entry(projpanel1, bd =2, width=20, #bg=entryBgColor, #fg=entryFgColor, textvariable=eprojectid ) #L.pack(pady=5,padx=5) #E.pack(pady=1,padx=5) L.grid(row=0, column=0, sticky=W, padx=10, pady=5) E.grid(row=0, column=2, sticky=W, padx=10, pady=5) eprojectid.set("project") #eprojectid.trace('w', makejson) L2=Label(projpanel1, text = "(Examples: CCBR-nnn,Labname or short project name)", anchor="ne" )#,bg="firebrick",fg="white") L2.grid(row=0, column=3, padx=10, pady=5, sticky="w") L=Label( projpanel1, text="Email address", anchor="ne")#,bg=baseColor,fg=textLightColor) E = Entry( projpanel1, bd =2, width=20, #bg=entryBgColor, #fg=entryFgColor, textvariable=euser) L3 = Label(projpanel1, text ="(Mandatory field: must use @nih.gov email address)", anchor="ne") L3.grid(row=1,column=3,padx=10,pady=5,sticky="w") L.grid(row=1,column=0,sticky=W,padx=10,pady=5) E.grid(row=1,column=2,sticky=W,padx=10,pady=5) #euser.trace('w', makejson) L=Label(projpanel1,text="Flow Cell ID",anchor="ne") E = Entry(projpanel1, bd =2, width=20, textvariable=eflowcell )#, bg=entryBgColor) L4=Label( projpanel1, text="(Examples: FlowCellID, Labname, date or short project name)", anchor="ne" )#,bg="firebrick",fg="white") L4.grid(row=2,column=3,padx=10,pady=5,sticky="w") L.grid(row=2,column=0,sticky=W,padx=10,pady=5) E.grid(row=2,column=2,sticky=W,padx=10,pady=5) eflowcell.set("stats") #eflowcell.trace('w', makejson) Projscrollbar = Scrollbar(projframe) Projscrollbar.grid(row=2,column=4,rowspan=30 ) self.jsonconf = jsonconf = Text( projframe, width=80, height=30, #bg=projectBgColor, #fg=projectFgColor, font=("nimbus mono bold","11"), yscrollcommand = Projscrollbar.set) Projscrollbar['command']=jsonconf.yview jsonconf.grid(row=3,column=0,sticky="e",padx=10,pady=5)
class FPLGUI: SPLASH_WIDTH = 350 SPLASH_HEIGHT = 250 def __init__(self): # Get database folder. self.srcDir = os.path.dirname(os.path.abspath(__file__)) self.databaseDir = os.path.join(os.path.dirname(self.srcDir),'database') self.supportFilesDir = os.path.join(os.path.dirname(self.srcDir),'supportFiles') # Create Database folder. if not os.path.isdir(self.databaseDir): os.makedirs(self.databaseDir) # Show splash splashWindow = Tk() splashWindow.title('FPLGUI') self.screenWidth = splashWindow.winfo_screenwidth() # width of the screen self.screenHeight = splashWindow.winfo_screenheight() # height of the screen x = round((self.screenWidth/2) - (self.SPLASH_WIDTH/2)) y = round((self.screenHeight/2) - (self.SPLASH_HEIGHT/2)) splashWindow.geometry('{}x{}+{}+{}'.format(self.SPLASH_WIDTH,self.SPLASH_HEIGHT,x,y)) splashWindow.resizable(0, 0) splashWindow.iconbitmap(os.path.join(self.supportFilesDir,'FPLGUI.ico')) Label(splashWindow,text="Loading Navdata, Please wait.",justify='left',font=("Helvetica", 14)).place(relx=0.1,rely=0.1,anchor='nw') with open(os.path.join(self.supportFilesDir,'startupMessage.txt')) as startupFile: Label(splashWindow, text=startupFile.read(),justify='left',font=("Helvetica", 8)).place(relx=0.1, rely=0.4, anchor='nw') splashWindow.update() # check options for X-Plane directory self.getOptions() # Let user select X-Plane dir and write options. if self.xPlaneDir is None: OptionsWindow(splashWindow,self.databaseDir,'FPLGUI: Set inital options') self.getOptions() while self.xPlaneDir is None: showwarning('XplaneDir not specified', 'XplaneDir is mandatory. Specify it first!') OptionsWindow(splashWindow,self.databaseDir,'FPLGUI: Set inital options') self.getOptions() # Get navdata folder. if os.path.exists(os.path.join(self.xPlaneDir,'Custom Data','earth_fix.dat')) and \ os.path.exists(os.path.join(self.xPlaneDir,'Custom Data','earth_nav.dat')) and \ os.path.exists(os.path.join(self.xPlaneDir,'Custom Data','earth_awy.dat')) and \ os.path.exists(os.path.join(self.xPlaneDir,'Custom Data','apt.csv')): self.navdataDir = os.path.join(self.xPlaneDir,'Custom Data') else: self.navdataDir = os.path.join(self.xPlaneDir,'Resources','default data') #inititalize Fpl-object self.fplPath = os.path.join(self.xPlaneDir,'Resources\\plugins\\X-IvAp Resources\\Flightplans') self.fpl = Fpl(self.fplPath) # Load Fixes # self.fpl.getFixes(os.path.join(self.navdataDir,'earth_fix.dat')) # self.fpl.getNavaids(os.path.join(self.navdataDir,'earth_nav.dat')) # self.fpl.getAirports(os.path.join(self.navdataDir,'apt.csv')) # self.fpl.getAirways(os.path.join(self.navdataDir,'earth_awy.dat')) # Remove Splash. splashWindow.destroy() # Create main window self.master = Tk() self.master.title('FPLGUI') self.master.resizable(0, 0) ## menu ## menubar = Menu(self.master) filemenu = Menu(menubar,tearoff=0) filemenu.add_command(label="Clear",command=self.clear) filemenu.add_command(label="Send to XP",command=self.send) filemenu.add_separator() filemenu.add_command(label="Load",command=self.load) filemenu.add_command(label="Save",command=self.save) filemenu.add_separator() filemenu.add_command(label="Exit",command=self.master.quit) menubar.add_cascade(label="File", menu=filemenu) acmenu = Menu(menubar,tearoff=0) acmenu.add_command(label="Load Template",command=self.acLoad) acmenu.add_command(label="Save Template",command=self.acSave) menubar.add_cascade(label="Aircraft", menu=acmenu) utilmenu = Menu(menubar,tearoff=0) utilmenu.add_command(label="Import Route",command=self.importRoute) utilmenu.add_separator() utilmenu.add_command(label="Open Simbrief",command=self.simbrief) utilmenu.add_command(label="Simbrief process",command= lambda: self.simbrief(True)) utilmenu.add_command(label="Flightaware",command=self.flightaware) utilmenu.add_separator() utilmenu.add_command(label="Show at Skyvector",command=self.showSkyvector) utilmenu.add_command(label="Export to X-Plane",command=self.export2xp) utilmenu.add_command(label="Export to FF A320",command=self.export2FFA320) utilmenu.add_separator() utilmenu.add_command(label="Show FPL text",command=self.showFplText) utilmenu.add_separator() utilmenu.add_command(label="Options",command=lambda: OptionsWindow(self.master,self.databaseDir)) menubar.add_cascade(label="Extras",menu=utilmenu) self.master.config(menu=menubar) ## row 0-1 ## ## send button self.b_send = Button(self.master, text = "Send", command=self.send) self.b_send.grid(row=0, column=0, rowspan = 2) ## callsign self.l_callsign = Label(self.master, text="7 a/c ident") self.l_callsign.grid(row=0, column=1) self.callsign = StringVar(self.master) self.e_callsign = Entry(self.master, textvariable=self.callsign) self.e_callsign.grid(row=1, column=1) self.callsign.trace_add('write', self.e_callsignCB) ## rules self.l_rules = Label(self.master, text="8 flight rules") self.l_rules.grid(row=0, column=2) self.rules = StringVar(self.master) self.rules.set("V") self.o_rules = OptionMenu(self.master, self.rules, "V", "I", "Y", "Z") self.o_rules.grid(row=1, column=2) ## flighttype self.l_flighttype = Label(self.master, text=" type of flight") self.l_flighttype.grid(row=0, column=3) self.flighttype = StringVar(self.master) self.flighttype.set("S") self.o_flighttype = OptionMenu(self.master, self.flighttype, "S", "N", "G", "M", "X") self.o_flighttype.grid(row=1, column=3) ## row 2-3 ## ## number self.l_number = Label(self.master, text="9 number") self.l_number.grid(row=2, column=0) self.number = StringVar(self.master) self.e_number = Entry(self.master, textvariable=self.number) self.e_number.grid(row=3, column=0) self.number.trace_add('write', self.e_numberCB) ## type of aircraft self.l_actype = Label(self.master, text="type of aircraft") self.l_actype.grid(row=2, column=1) self.actype = StringVar(self.master) self.e_actype = Entry(self.master, textvariable=self.actype) self.e_actype.grid(row=3, column=1) self.actype.trace_add('write', self.e_actypeCB) ## wakecat self.l_wakecat = Label(self.master, text="wake turb cat") self.l_wakecat.grid(row=2, column=2) self.wakecat = StringVar(self.master) self.wakecat.set("L") self.o_wakecat = OptionMenu(self.master, self.wakecat, "L", "M", "H", "J") self.o_wakecat.grid(row=3, column=2) ## equipment self.l_equipment = Label(self.master, text="10 equipment") self.l_equipment.grid(row=2, column=3) self.equipment = StringVar(self.master) self.e_equipment = Entry(self.master, textvariable=self.equipment) self.e_equipment.grid(row=3, column=3) self.equipment.trace_add('write', self.e_equipmentCB) ## equipment self.l_transponder = Label(self.master, text="transponder") self.l_transponder.grid(row=2, column=4) self.transponder = StringVar(self.master) self.e_transponder = Entry(self.master, textvariable=self.transponder) self.e_transponder.grid(row=3, column=4) self.transponder.trace_add('write', self.e_transponderCB) ## row 4-5 ## ## depicao self.l_depicao = Label(self.master, text="13 departure aerodrome") self.l_depicao.grid(row=4, column=0) self.depicao = StringVar(self.master) self.e_depicao = Entry(self.master, textvariable=self.depicao) self.e_depicao.grid(row=5, column=0) self.depicao.trace_add('write', self.e_depicaoCB) ## deptime self.l_deptime = Label(self.master, text="departure time") self.l_deptime.grid(row=4, column=1) self.deptime = StringVar(self.master) self.e_deptime = Entry(self.master, textvariable=self.deptime) self.e_deptime.grid(row=5, column=1) self.deptime.trace_add('write', self.e_deptimeCB) ## row 6-7 ## ## speed self.l_speed = Label(self.master, text="15 cruising speed") self.l_speed.grid(row=6, column=0, columnspan=2) self.speedtype = StringVar(self.master) self.speedtype.set("N") self.o_speedtype = OptionMenu(self.master, self.speedtype, "N", "M") self.o_speedtype.grid(row=7, column=0) self.speed = StringVar(self.master) self.e_speed = Entry(self.master, textvariable=self.speed) self.e_speed.grid(row=7, column=1) self.speed.trace_add('write', self.e_speedCB) ## level self.l_level = Label(self.master, text="flight altutude/level") self.l_level.grid(row=6, column=2, columnspan=2) self.leveltype = StringVar(self.master) self.leveltype.set("F") self.o_level = OptionMenu(self.master, self.leveltype, "F", "A", "VFR") self.o_level.grid(row=7, column=2) self.level = StringVar(self.master) self.e_level = Entry(self.master, textvariable=self.level) self.e_level.grid(row=7, column=3) self.level.trace_add('write', self.e_levelCB) ## row 8-9 ## ##route self.l_route = Label(self.master, text=" route") self.l_route.grid(row=8, column=0, sticky=W) self.route = StringVar(self.master) self.e_route = Entry(self.master, width=105, textvariable=self.route) self.e_route.grid(row=9, column=0, columnspan=5) self.route.trace_add('write', self.e_routeCB) ## row 10-11 ## ## destinationAP self.l_desticao = Label(self.master, text="13 destination aerodrome") self.l_desticao.grid(row=10, column=0) self.desticao = StringVar(self.master) self.e_desticao = Entry(self.master, textvariable=self.desticao) self.e_desticao.grid(row=11, column=0) self.desticao.trace_add('write', self.e_desticaoCB) ## duration self.l_eet = Label(self.master, text="EET") self.l_eet.grid(row=10, column=1) self.eet = StringVar(self.master) self.e_eet = Entry(self.master, textvariable=self.eet) self.e_eet.grid(row=11, column=1) self.eet.trace_add('write', self.e_eetCB) ## alternates self.l_alticao = Label(self.master, text="alternate") self.l_alticao.grid(row=10, column=2) self.alticao = StringVar(self.master) self.e_alticao = Entry(self.master, textvariable=self.alticao) self.e_alticao.grid(row=11, column=2) self.alticao.trace_add('write', self.e_alticaoCB) self.l_alt2icao = Label(self.master, text="2nd alternate") self.l_alt2icao.grid(row=10, column=3) self.alt2icao = StringVar(self.master) self.e_alt2icao = Entry(self.master, textvariable=self.alt2icao) self.e_alt2icao.grid(row=11, column=3) self.alt2icao.trace_add('write', self.e_alt2icaoCB) ## row 12-13 ## ##other self.l_other = Label(self.master, text="other") self.l_other.grid(row=12, column=0, sticky=W) self.other = StringVar(self.master) self.e_other = Entry(self.master, width=105, textvariable=self.other) self.e_other.grid(row=13, column=0, columnspan=5) self.other.trace_add('write', self.e_otherCB) ## row 14-15 ## ##endurance self.l_endurance = Label(self.master, text="19 endurance") self.l_endurance.grid(row=14, column=0) self.endurance = StringVar(self.master) self.e_endurance = Entry(self.master, textvariable=self.endurance) self.e_endurance.grid(row=15, column=0) self.endurance.trace_add('write', self.e_enduranceCB) ##persons self.l_pob = Label(self.master, text="persons on board") self.l_pob.grid(row=14, column=1) self.pob = StringVar(self.master) self.e_pob = Entry(self.master, textvariable=self.pob) self.e_pob.grid(row=15, column=1) self.pob.trace_add('write', self.e_pobCB) ##pic self.l_pic = Label(self.master, text="pilot in command") self.l_pic.grid(row=14, column=2) self.pic = StringVar(self.master) self.e_pic = Entry(self.master, width=40, textvariable=self.pic) self.e_pic.grid(row=15, column=2, columnspan=2) self.pic.trace_add('write', self.e_picCB) ## row 16 ## ##empty empty = Label(self.master, text="") empty.grid(row=16, column=0) self.updateContent() # Set master window options self.master.update() masterWidth = self.master.winfo_width() masterHeight = self.master.winfo_height() x = round((self.screenWidth/2) - (masterWidth/2)) y = round((self.screenHeight/2) - (masterHeight/2)) self.master.geometry('{}x{}+{}+{}'.format(masterWidth,masterHeight,x,y)) self.master.title('FPLGUI') self.master.resizable(0, 0) self.master.iconbitmap(os.path.join(self.supportFilesDir,'FPLGUI.ico')) # Start master mainloop. self.master.mainloop() def updateContent(self): ## row 0-1 ## ## callsign self.e_callsign.delete(0, END) self.e_callsign.insert(0,self.fpl.callsign) ## rules if self.fpl.rules: self.rules.set(self.fpl.rules) else: self.rules.set("V") ## flightType if self.fpl.flighttype: self.flighttype.set(self.fpl.flighttype) else: self.flighttype.set("S") ## row 2-3 ## ## number self.e_number.delete(0, END) self.e_number.insert(0,self.fpl.number) ## type of aircraft self.e_actype.delete(0, END) self.e_actype.insert(0,self.fpl.actype) ## wakecat if self.fpl.wakecat: self.wakecat.set(self.fpl.wakecat) else: self.wakecat.set("L") ## equipment self.e_equipment.delete(0, END) self.e_equipment.insert(0,self.fpl.equipment) ## equipment self.e_transponder.delete(0, END) self.e_transponder.insert(0,self.fpl.transponder) ## row 4-5 ## ## depicao self.e_depicao.delete(0, END) self.e_depicao.insert(0,self.fpl.depicao) ## deptime self.e_deptime.delete(0, END) self.e_deptime.insert(0,self.fpl.deptime) ## row 6-7 ## ## speed if self.fpl.speedtype: self.speedtype.set(self.fpl.speedtype) else: self.speedtype.set("N") self.e_speed.delete(0, END) self.e_speed.insert(0,self.fpl.speed) ## level if self.fpl.leveltype: self.leveltype.set(self.fpl.leveltype) else: self.leveltype.set("N") self.e_level.delete(0, END) self.e_level.insert(0,self.fpl.level) ## row 8-9 ## ##route self.e_route.delete(0, END) self.e_route.insert(0,self.fpl.route) ## row 10-11 ## ## destinationAP self.e_desticao.delete(0, END) self.e_desticao.insert(0,self.fpl.desticao) ## eet self.e_eet.delete(0, END) self.e_eet.insert(0,self.fpl.eet) ## alternates self.e_alticao.delete(0, END) self.e_alticao.insert(0,self.fpl.alticao) self.e_alt2icao.delete(0, END) self.e_alt2icao.insert(0,self.fpl.alt2icao) ## row 12-13 ## ##other self.e_other.delete(0, END) self.e_other.insert(0,self.fpl.other) ## row 14-15 ## ##endurance self.e_endurance.delete(0, END) self.e_endurance.insert(0,self.fpl.endurance) ##persons self.e_pob.delete(0, END) self.e_pob.insert(0,self.fpl.pob) ##pic self.e_pic.delete(0, END) self.e_pic.insert(0,self.fpl.pic) def updateFpl(self): self.fpl.callsign = self.e_callsign.get() self.fpl.pic = self.e_pic.get() self.fpl.speedtype = self.speedtype.get() self.fpl.pob = self.e_pob.get() self.fpl.endurance = self.e_endurance.get() self.fpl.other = self.e_other.get() self.fpl.alt2icao = self.e_alt2icao.get() self.fpl.alticao = self.e_alticao.get() self.fpl.eet = self.e_eet.get() self.fpl.desticao = self.e_desticao.get() self.fpl.route = self.e_route.get() self.fpl.level = self.e_level.get() self.fpl.leveltype = self.leveltype.get() self.fpl.speed = self.e_speed.get() self.fpl.deptime = self.e_deptime.get() self.fpl.depicao = self.e_depicao.get() self.fpl.transponder = self.e_transponder.get() self.fpl.equipment = self.e_equipment.get() self.fpl.wakecat = self.wakecat.get() self.fpl.actype = self.e_actype.get() self.fpl.number = self.e_number.get() self.fpl.flighttype = self.flighttype.get() self.fpl.rules = self.rules.get() def load(self): filepath = askopenfilename(filetypes=[("X-Plane Flightplan","*.fpl"),("All","*")],initialdir=self.fpl.path) self.fpl.load(filepath) self.updateContent() def save(self): self.updateFpl() filepath = asksaveasfilename(filetypes=[("X-Plane Flightplan","*.fpl"),("All","*")],initialdir=self.fpl.path) if filepath[-4:] != ".fpl": filepath += ".fpl" self.fpl.save(filepath) print("saved!") def send(self): self.updateFpl() self.fpl.save(self.fpl.path + "\\Default.fpl") if (len(self.fpl.route) + len(self.fpl.other)) > 255: showwarning("Too long entries",'"Route" and "Other" entries are too long ({}/255 characters combined)!\nThis will lead to disconnection in flight.\nTry to shorten these fields.'.format(len(self.fpl.route) + len(self.fpl.other))) print("generated!") def clear(self): self.e_callsign.delete(0, END) self.e_number.delete(0, END) self.e_actype.delete(0, END) self.e_equipment.delete(0, END) self.e_transponder.delete(0, END) self.e_depicao.delete(0, END) self.e_deptime.delete(0, END) self.e_speed.delete(0, END) self.e_level.delete(0, END) self.e_route.delete(0, END) self.e_desticao.delete(0, END) self.e_eet.delete(0, END) self.e_alticao.delete(0, END) self.e_alt2icao.delete(0, END) self.e_other.delete(0, END) self.e_endurance.delete(0, END) self.e_pob.delete(0, END) self.e_pic.delete(0, END) def getOptions(self): # Init options with None self.xPlaneDir = None # Get options if os.path.isfile(os.path.join(self.databaseDir,'FPLGUI.cfg')): self.config = ConfigParser.RawConfigParser() self.config.read(os.path.join(self.databaseDir,'FPLGUI.cfg')) # xPlaneDir try: self.xPlaneDir = self.config.get('FPLGUI','XPLANEDIR') except ConfigParser.NoSectionError: return except ConfigParser.NoOptionError: pass if self.xPlaneDir is not None and not re.match(r'[A-Za-z]:\\',self.xPlaneDir): self.xPlaneDir = None def updateRouteDbButtonCB(self): # dbUpdated = False downloadUrl = "https://www.ivao.de/scripts/php/cms/pfpx" # curDate = int(time.time()) # lastUpdate = 0 #TODO: replace, when options implemented # timeDiff = curDate - lastUpdate timeDiff = 0 if timeDiff > 864000: ivaoDatabase = urlopen(downloadUrl) database = ivaoDatabase.read() # lastUpdate = int(time.time()) # dbUpdated = True DataFile = open(self.srcDir + r"\routeDatabase.txt",'w') DataFile.write(database) DataFile.close() def optionsButtonOkCB(self): self.top.destroy() def optionsButtonCancelCB(self): self.top.destroy() def simbrief(self,*args): self.updateFpl() url = 'https://www.simbrief.com/system/dispatch.php?' options = '' # Airports. if self.fpl.depicao and self.fpl.desticao: url = '{}&orig={}&dest={}'.format(url,self.fpl.depicao,self.fpl.desticao) else: showwarning('Airport missing','Departure and destination airport is mandatory for Simbrief.\nSpecify them first!') # Times if self.fpl.deptime: deph = self.fpl.deptime[0:1] depm = self.fpl.deptime[2:3] options = '{}&deph={}&depm={}'.format(options,deph,depm) else: showwarning('Time missing','Departure time is mandatory for Simbrief.\nSpecify it first!') return # Aircraft. if self.fpl.actype: url = '{}&type={}'.format(url,self.fpl.actype) else: showwarning('Aircraft type missing','Aircraft type is mandatory for Simbrief.\nSpecify it first!') # Route. if self.fpl.route: url = '{}&route={}'.format(url,self.fpl.route) else: showinfo('Route missing','The route is missing and will be created by Simbrief.\nNote: These routes are often not CFMU valid!') # Flightlevel. if self.fpl.level: url = '{}&fl={}00'.format(url,self.fpl.level) # Date. reFind = re.search('(?<=DOF/)\d{6}',self.fpl.other) if reFind: date = reFind.group() date = datetime.datetime(int(date[0:2])+2000,int(date[2:4]),int(date[4:6])) else: date = datetime.datetime.today() url = '{}&date={}'.format(url,date.strftime('%d%b%y')) # Airline, fltnum, registration, selcal. airline = '' fltnum = '' registration = '' selcal = '' # Airline, fltnum, registration from Callsign field. reFind = re.search('[A-Z]{5}',self.fpl.callsign) if reFind: registration = reFind.group() else: reFindAirline = re.search('[A-Z]{3}(?=\w+)',self.fpl.callsign) reFindFltnum = re.search('(?<=[A-Z]{3})\w+',self.fpl.callsign) if reFindAirline and reFindFltnum: airline = reFindAirline.group() fltnum = reFindFltnum.group() else: print('invalid Callsign!') # Registration (REG/) from other field. if not registration: reFind = re.search('(?<=REG/)[A-Z]{5}',self.fpl.other) if reFind: registration = reFind.group() # Airline (OPR/) from other field. if not airline: reFind = re.search('(?<=OPR/)[A-Z]{3}',self.fpl.other) if reFind: airline = reFind.group() # Selcal (SEL) from other field. reFind = re.search('(?<=SEL/)[A-S]{4}',self.fpl.other) if reFind: selcal = reFind.group() # Add the found values if airline: url = '{}&airline={}'.format(url,airline) if fltnum: url = '{}&fltnum={}'.format(url,fltnum) if registration: url = '{}®={}'.format(url,registration) if selcal: url = '{}&selcal={}'.format(url,selcal) # ----FPL---- # Alternates. # ----ADD---- # Extra Fuel. # Cont fuel # Reserve Fuel. # Taxi out. # Taxi in. # Cargo. # Pax. # Dep rwy. # Arr rwy. # CI # ETOPS. # Specify options. # For Simbrief process. if len(args) and args[0]: url = '{}&planformat=LIDO&units=KGS&navlog=0&etops=0&stepclimbs=0&tlr=0¬ams=0&firnot=0&maps=none'.format(url) # For show Simbiref. else: url = '{}&planformat=LIDO&units=KGS&navlog=1&etops=1&stepclimbs=0&tlr=0¬ams=1&firnot=1&maps=detail'.format(url) # print(url) # pass # Open simbrief. webbrowser.open(url,new=2) def simbriefOpen(self): pass def simbriefProcess(self): pass ## Display flights for departure and destination airport on flightaware. def flightaware(self): self.updateFpl() url = 'https://de.flightaware.com/live/findflight?origin={}&destination={}'.format(self.fpl.depicao,self.fpl.desticao) webbrowser.open(url,new=2) def importRoute(self): self.updateFpl() with open(self.databaseDir + r"\routeDatabase.txt") as dataFile: database = dataFile.read() self.fpl.desticao = self.fpl.desticao.upper() self.fpl.depicao = self.fpl.depicao.upper() patRte = re.compile(self.fpl.depicao + self.fpl.desticao + r"\d{2};.+\n") routes = patRte.findall(database) ## parse routes self.routing = [] self.comment = [] self.fl = [] maxLenCom = 0 for k in range(len(routes)): parts = re.split(";",routes[k]) self.routing.append(parts[1]) curComment = parts[2] #curComment = curComment[1:-2] curComment = re.split(",",curComment) curFL = curComment[0] curCommentList = curComment[1:] curComment = "" for l in curCommentList: curComment += l self.comment.append(curComment[1:-2]) if len(curComment[1:-2]) > maxLenCom: maxLenCom = len(curComment[1:-2]) self.fl.append(curFL) ## show window self.importRouteTop = Toplevel(self.master) if len(self.routing) > 0: Label(self.importRouteTop, text="Choose a Route").pack() self.importRouteListboxTl = Listbox(self.importRouteTop,width=180) self.importRouteListboxTl.pack() for k in range(len(self.routing)): self.importRouteListboxTl.insert(END, "{:11} {:50} {}".format(self.fl[k],self.comment[k],self.routing[k])) self.importRouteListboxTl.selection_set(0) self.tlOkButton = Button(self.importRouteTop,text="OK",command=self.routeListCB,width=80) self.tlOkButton.pack() self.master.wait_window(self.importRouteTop) else: Label(self.importRouteTop, text="No Routes found!").pack() self.tlOkButton = Button(self.importRouteTop,text="OK",command=self.importRouteTop.destroy,width=10) self.tlOkButton.pack() def export2FFA320(self): """ Write the route to Flight Factor A320 Company Routes Database. Import to aircraft via the MCDU """ self.updateFpl() #self.fpl.actype,self.fpl.depicao,self.fpl.desticao,deph,depm,reg,selcal,self.fpl.route,self.fpl.level fpl = self.fpl # check if ac type is A320 if fpl.actype != 'A320': warn('A/C type is not A320!') # remove SID/STAR from route route = re.sub('[A-Z]{5}\d[A-Z]','',fpl.route).strip() # write route string routeString = 'RTE {}{} {} {} {} CI30 FL{}'.format(fpl.depicao, fpl.desticao, fpl.depicao, route, fpl.desticao, fpl.level ) # find and open route database # check for duplicate and overwrite or append route coRoutePath = os.path.join(self.xPlaneDir,r'Aircraft\FlightFactorA320\data\corte.in') with open(coRoutePath,'r') as coRouteFile: lines = coRouteFile.readlines() written = False for k in range(len(lines)): if 'RTE {}{}'.format(fpl.depicao,fpl.desticao) in lines[k]: lines[k] = '{}\n'.format(routeString) written = True break if not written: if lines[-1][-1] == '\n': lines.append(routeString) else: lines.append('\n{}'.format(routeString)) # write new file with open(coRoutePath,'w') as coRouteFile: for k in lines: coRouteFile.write(k) # print success message print('exported (FF A320)!') def export2xp(self): self.updateFpl() # Get file path for export. fileCount = 0 fmsFilePath = os.path.abspath(__file__) while os.path.isfile(fmsFilePath): fileCount += 1 fmsFilePath = os.path.join(self.xPlaneDir,'Output','FMS plans','{}{}{:02}.fms'.format(self.fpl.depicao,self.fpl.desticao,fileCount)) # Get coordinates of dep. curCoordinates = self.fpl.airports[self.fpl.depicao] # Get start altitude. curAltitude = int(self.fpl.level) * 100 newAltitude = curAltitude # Remove SID/STAR from route and split in parts route = re.sub('[A-Z]{5}\d[A-Z]','',self.fpl.route).strip() route = route.split() # with open(fmsFilePath,'w') as fmsFile: # Write header and departure. fmsStr = '' # Process route. nWaypoints = 1 curWaypoint = None curWaypointName = None lastWaypointName = None curAirway = None for rpId,rp in enumerate(route): if not(rpId % 2): # Waypoint # Split altitude from wp if '/' in rp: wpSplit = rp.split('/') curWaypointName = wpSplit[0] altMatch = re.search('F\d+', wpSplit[1]) if altMatch is not None: newAltitude = int(wpSplit[1][altMatch.start()+1:altMatch.end()]) * 100 else: curWaypointName = rp if curAirway is None: # After DCT curAltitude = newAltitude curWaypoint = self.fpl.waypoints[curWaypointName] minDistance = 3.2 # slightly greater than pi for wp in curWaypoint: distance = avFormula.gcDistance(curCoordinates[0],curCoordinates[1],wp[0],wp[1]) if distance < minDistance: minDistance = distance nearWp = wp fmsStr = '{}{} {} DRCT {} {} {}\n'.format(fmsStr,nearWp[2],curWaypointName,curAltitude,nearWp[0],nearWp[1]) nWaypoints += 1 else: # After Airway curAirwayParts = self.fpl.airways[curAirway].parts curAirwayName = curAirway curAirway = None # Get part with both waypoints. for pa in curAirwayParts: if lastWaypointName in [k for m in pa for k in m] and curWaypointName in [n for o in pa for n in o]: curAirway = pa break if curAirway is None: print('One or both waypoints are no part of airway {}!'.format(curAirwayName)) raise(Exception,'Airway Error!') curWaypointId = None lastWaypointId = None for wpId,wp in enumerate(curAirway): if curWaypointName in wp: curWaypointId = wpId elif lastWaypointName in wp: lastWaypointId = wpId if curWaypointId is not None and lastWaypointId is not None: step = int(copysign(1,curWaypointId - lastWaypointId)) break for wp in range(lastWaypointId+step,curWaypointId+step,step): if curAirway[wp][0] == curWaypointName: curAltitude = newAltitude fmsStr = '{}{} {} {} {} {} {}\n'.format(fmsStr,curAirway[wp][3],curAirway[wp][0],curAirwayName,curAltitude,curAirway[wp][1],curAirway[wp][2]) nWaypoints += 1 curAirway = None elif rp != 'DCT': # Airway curAirway = rp lastWaypointName = curWaypointName curCoordinates = self.fpl.airports[self.fpl.desticao] fmsStr = '{}1 {} ADES 0.000000 {} {}'.format(fmsStr,self.fpl.desticao,curCoordinates[0],curCoordinates[1]) nWaypoints += 1 curCoordinates = self.fpl.airports[self.fpl.depicao] fmsStr = 'I\n1100 Version\nCYCLE {}\nADEP {}\nADES {}\nNUMENR {}\n1 {} ADEP 0.000000 {} {}\n{}'.format(self.fpl.cycleNumber, self.fpl.depicao, self.fpl.desticao, nWaypoints, self.fpl.depicao, curCoordinates[0],curCoordinates[1], fmsStr) # print(fmsStr) with open(fmsFilePath,'w') as fmsFile: fmsFile.write(fmsStr) print('fms file exported to XP!') def acLoad(self): self.updateFpl() self.getAcTemplates() # get the right template. if self.fpl.actype in self.acTemplates: template = self.acTemplates[self.fpl.actype] # Assign values to FPL. self.fpl.equipment = template[0] self.fpl.transponder = template[1] matchObj = re.search(r'PBN/\w+', self.fpl.other,flags=re.A) # @UndefinedVariable if matchObj is not None: self.fpl.other = self.fpl.other.replace(self.fpl.other[matchObj.start():matchObj.end()], '') self.fpl.other = re.sub(' +',' ',self.fpl.other) self.fpl.other = self.fpl.other.strip() self.fpl.other = 'PBN/{} {}'.format(template[2],self.fpl.other) self.fpl.other = self.fpl.other.strip() self.fpl.wakecat = template[3] self.fpl.speed = template[4] self.fpl.pob = template[5] # Update Fields. self.updateContent() else: messagebox.showinfo("FPL", "No templates found for\naircraft {}!".format(self.fpl.actype)) def acSave(self): # Preparations. self.updateFpl() self.getAcTemplates() # Check if template already exists and ask what to do. if self.fpl.actype in self.acTemplates: if messagebox.askyesno("Overwrite?","A template for the aircraft {} already exists.\nOverwrite?".format(self.fpl.actype)): self.acTemplates.pop(self.fpl.actype) else: return # Update Aircraft templates. self.acTemplates[self.fpl.actype] = [] self.acTemplates[self.fpl.actype].append(self.fpl.equipment) self.acTemplates[self.fpl.actype].append(self.fpl.transponder) matchObj = re.search(r'PBN/\w+', self.fpl.other,flags=re.A) # @UndefinedVariable if matchObj is not None: self.acTemplates[self.fpl.actype].append(self.fpl.other[matchObj.start():matchObj.end()].replace('PBN/','')) else: self.acTemplates[self.fpl.actype].append('') self.acTemplates[self.fpl.actype].append(self.fpl.wakecat) self.acTemplates[self.fpl.actype].append(self.fpl.speed) self.acTemplates[self.fpl.actype].append(self.fpl.pob) # Write the new list with open(os.path.join(self.databaseDir,'aircraft.csv'),'w') as acFile: acFile.write('ac;equip;transponder;PBN;wakeCat;speed;x;POB\n') for te in self.acTemplates: curTemplate = self.acTemplates[te] acFile.write('{};{};{};{};{};{};{}\n'.format(te,curTemplate[0],curTemplate[1],curTemplate[2],curTemplate[3],curTemplate[4],curTemplate[5])) def getAcTemplates(self): self.acTemplates = {} if not os.path.exists(os.path.join(self.databaseDir,'aircraft.csv')): open(os.path.join(self.databaseDir,'aircraft.csv'),'w').close() with open(os.path.join(self.databaseDir,'aircraft.csv')) as acFile: for lineNr,line in enumerate(acFile): if lineNr: lineSplit = line.rstrip('\n').split(';') self.acTemplates[lineSplit[0]] = [lineSplit[1],lineSplit[2],lineSplit[3],lineSplit[4],lineSplit[5],lineSplit[6]] def showSkyvector(self): # Calculate middle point. depCoordinates = self.fpl.airports[self.fpl.depicao] destCoordinates = self.fpl.airports[self.fpl.desticao] intermediatePoint = avFormula.gcIntermediatePoint(depCoordinates[0], depCoordinates[1], destCoordinates[0], destCoordinates[1]) skyvectorUrl = 'http://skyvector.com/?ll={:9.6f},{:9.6f}&chart=304&zoom=6&fpl=%20{}%20{}%20{}'.format(intermediatePoint[0], intermediatePoint[1], self.fpl.depicao, self.fpl.route.replace(' ','%20'), self.fpl.desticao) webbrowser.open(skyvectorUrl,new=2) def showFplText(self): # Get Field contents. self.updateFpl() # Init string. fplString = '(FPL\n' # Complete string. fplString = '{}-{}-{}{}\n'.format(fplString, self.fpl.callsign, self.fpl.rules, self.fpl.flighttype) fplString = '{}-{}{}/{}-{}/{}\n'.format(fplString, self.fpl.number, self.fpl.actype, self.fpl.wakecat, self.fpl.equipment, self.fpl.transponder) fplString = '{}-{}{}\n'.format(fplString, self.fpl.depicao, self.fpl.deptime) fplString = '{}-N{:04}F{:03} {}\n'.format(fplString, int(self.fpl.speed), int(self.fpl.level), self.fpl.route) fplString = '{}-{}{} {} {}\n'.format(fplString, self.fpl.desticao, self.fpl.eet, self.fpl.alticao, self.fpl.alt2icao) fplString = '{}-{})'.format(fplString,self.fpl.other) # Print string. print(fplString) # Copy to clipboard. r = Tk() r.withdraw() r.clipboard_clear() r.clipboard_append(str(fplString)) r.update() r.destroy() # Show in window. showinfo("Flightplan text", '{}\n\n(Copied to clipboard.)'.format(fplString)) # Callbacks def routeListCB(self): selectedRoute = self.importRouteListboxTl.curselection() selectedRoute = selectedRoute[0] self.fpl.route = self.routing[selectedRoute] self.fpl.route = self.fpl.route[5:-5] self.importRouteTop.destroy() self.updateContent() def e_callsignCB(self,*args): #@UnusedVariable string = self.callsign.get() if len(string): enteredChar = string[-1] if not enteredChar.isalnum(): self.callsign.set(string[0:-1]) else: self.callsign.set(self.callsign.get().upper()) def e_numberCB(self,*args): #@UnusedVariable string = self.number.get() if len(string): enteredChar = string[-1] if not enteredChar.isdigit(): self.number.set(string[0:-1]) def e_actypeCB(self,*args): #@UnusedVariable string = self.actype.get() if len(string): enteredChar = string[-1] if not enteredChar.isalnum() or len(string) > 4: self.actype.set(string[0:-1]) else: self.actype.set(self.actype.get().upper()) def e_equipmentCB(self,*args): #@UnusedVariable string = self.equipment.get() if len(string): enteredChar = string[-1] if not enteredChar.isalnum(): self.equipment.set(string[0:-1]) else: self.equipment.set(self.equipment.get().upper()) def e_transponderCB(self,*args): #@UnusedVariable string = self.transponder.get() if len(string): enteredChar = string[-1] if not enteredChar.isalnum(): self.transponder.set(string[0:-1]) else: self.transponder.set(self.transponder.get().upper()) def e_depicaoCB(self,*args): #@UnusedVariable string = self.depicao.get() if len(string): enteredChar = string[-1] if not enteredChar.isalnum() or len(string) > 4: self.depicao.set(string[0:-1]) else: self.depicao.set(self.depicao.get().upper()) def e_deptimeCB(self,*args): #@UnusedVariable string = self.deptime.get() if len(string): enteredChar = string[-1] if not enteredChar.isdigit() or len(string) > 4: self.deptime.set(string[0:-1]) def e_speedCB(self,*args): #@UnusedVariable string = self.speed.get() if len(string): enteredChar = string[-1] if not enteredChar.isdigit() or len(string) > 4: self.speed.set(string[0:-1]) def e_levelCB(self,*args): #@UnusedVariable string = self.level.get() if len(string): enteredChar = string[-1] if not enteredChar.isdigit() or len(string) > 3: self.level.set(string[0:-1]) def e_routeCB(self,*args): #@UnusedVariable string = self.route.get() if len(string): enteredChar = string[-1] if not enteredChar.isalnum() and enteredChar != '/' and enteredChar != ' ': self.route.set(string[0:-1]) else: self.route.set(self.route.get().upper()) def e_desticaoCB(self,*args): #@UnusedVariable string = self.desticao.get() if len(string): enteredChar = string[-1] if not enteredChar.isalnum() or len(string) > 4: self.desticao.set(string[0:-1]) else: self.desticao.set(self.desticao.get().upper()) def e_eetCB(self,*args): #@UnusedVariable string = self.eet.get() if len(string): enteredChar = string[-1] if not enteredChar.isdigit() or len(string) > 4: self.eet.set(string[0:-1]) def e_alticaoCB(self,*args): #@UnusedVariable string = self.alticao.get() if len(string): enteredChar = string[-1] if not enteredChar.isalnum() or len(string) > 4: self.alticao.set(string[0:-1]) else: self.alticao.set(self.alticao.get().upper()) def e_alt2icaoCB(self,*args): #@UnusedVariable string = self.alt2icao.get() if len(string): enteredChar = string[-1] if not enteredChar.isalnum() or len(string) > 4: self.alt2icao.set(string[0:-1]) else: self.alt2icao.set(self.alt2icao.get().upper()) def e_otherCB(self,*args): #@UnusedVariable string = self.other.get() if len(string): enteredChar = string[-1] if not enteredChar.isalnum() and enteredChar != '/' and enteredChar != ' ': self.other.set(string[0:-1]) else: self.other.set(self.other.get().upper()) def e_enduranceCB(self,*args): #@UnusedVariable string = self.endurance.get() if len(string): enteredChar = string[-1] if not enteredChar.isdigit() or len(string) > 4: self.endurance.set(string[0:-1]) def e_pobCB(self,*args): #@UnusedVariable string = self.pob.get() if len(string): enteredChar = string[-1] if not enteredChar.isdigit(): self.pob.set(string[0:-1]) def e_picCB(self,*args): #@UnusedVariable string = self.pic.get() if len(string): enteredChar = string[-1] if not enteredChar.isalpha() and enteredChar != ' ' and enteredChar != "'" and enteredChar != '-': self.pic.set(string[0:-1])
def initUI(self): # Establish frames self.pack(side="top", fill="both", expand=True) self.top_frame = Frame(self) self.bottom_frame = Frame(self) self.top_frame.pack(side="top", fill="both", expand=False) self.bottom_frame.pack(side="bottom", fill="both", expand=True) self.top_top_frame = Frame(self.top_frame) self.top_top_frame.pack(side="top", fill="both", expand=False) self.bottom_top_frame = Frame(self.top_frame) self.bottom_top_frame.pack(side="bottom", fill="both", expand=False) # Entry combo box self.cboxv = StringVar(self.top_top_frame) self.cbox = Combobox(self.top_top_frame, value=self.cboxv, width=40) self.cbox['values'] = ("all", "FreeGamesOnSteam", "funny", "news") self.cbox.current(0) self.cbox.bind("<Button-1>", self.text_callback) self.cbox.bind("<Tab>", self.time_callback) self.cbox.pack(side="left", padx=10, pady=10, expand=True) # Entry time box self.tentry = Entry(self.top_top_frame, width=8, foreground='gray') self.tentry.bind("<Button-1>", self.time_callback) self.tentry.insert(0, "Time(s)") self.tentry.pack(side="left", padx=10, pady=10, expand=True) # Category drop-down menu self.category = StringVar(self.top_top_frame) self.category.set("hot") # default value self.omenu = OptionMenu(self.top_top_frame, self.category, "hot", "new", "top", "controversial", "rising") self.omenu.pack(side="right", padx=10, pady=10, expand=True) # Limit drop-down menu self.limit = IntVar(self.top_top_frame) self.limit.set(5) # default value self.lmenu = OptionMenu(self.top_top_frame, self.limit, *list(range(10))) self.lmenu.pack(side="right", padx=10, pady=10, expand=True) # Scan button self.scanb = Button(self.bottom_top_frame, text="Scan", command=self.scan_subreddit) self.scanb.pack(side="left", padx=10, pady=10, expand=True) self.parent.bind("<Return>", lambda x: self.scan_subreddit()) # Popup check self.checkvar = BooleanVar() self.check = Checkbutton(self.bottom_top_frame, text="Popup", variable=self.checkvar) self.check.pack(side="left", padx=10, pady=10, expand=True) # Continuous check self.contvar = BooleanVar() self.contb = Checkbutton(self.bottom_top_frame, text="Continuous", variable=self.contvar) self.contb.pack(side="left", padx=10, pady=10, expand=True) # Stop button self.stopb = Button(self.bottom_top_frame, text="Stop", command=self.stop_scanning, state="disabled") self.stopb.pack(side="right", padx=10, pady=10, expand=True) self.parent.bind("<Escape>", lambda x: self.stop_scanning()) # Results text box self.text = CustomText(self.bottom_frame, height=10, width=50) self.text.configure(state="disabled") self.text.pack(side="top", padx=10, pady=10, expand=True, fill="both")
def __init__(self): # Get database folder. self.srcDir = os.path.dirname(os.path.abspath(__file__)) self.databaseDir = os.path.join(os.path.dirname(self.srcDir),'database') self.supportFilesDir = os.path.join(os.path.dirname(self.srcDir),'supportFiles') # Create Database folder. if not os.path.isdir(self.databaseDir): os.makedirs(self.databaseDir) # Show splash splashWindow = Tk() splashWindow.title('FPLGUI') self.screenWidth = splashWindow.winfo_screenwidth() # width of the screen self.screenHeight = splashWindow.winfo_screenheight() # height of the screen x = round((self.screenWidth/2) - (self.SPLASH_WIDTH/2)) y = round((self.screenHeight/2) - (self.SPLASH_HEIGHT/2)) splashWindow.geometry('{}x{}+{}+{}'.format(self.SPLASH_WIDTH,self.SPLASH_HEIGHT,x,y)) splashWindow.resizable(0, 0) splashWindow.iconbitmap(os.path.join(self.supportFilesDir,'FPLGUI.ico')) Label(splashWindow,text="Loading Navdata, Please wait.",justify='left',font=("Helvetica", 14)).place(relx=0.1,rely=0.1,anchor='nw') with open(os.path.join(self.supportFilesDir,'startupMessage.txt')) as startupFile: Label(splashWindow, text=startupFile.read(),justify='left',font=("Helvetica", 8)).place(relx=0.1, rely=0.4, anchor='nw') splashWindow.update() # check options for X-Plane directory self.getOptions() # Let user select X-Plane dir and write options. if self.xPlaneDir is None: OptionsWindow(splashWindow,self.databaseDir,'FPLGUI: Set inital options') self.getOptions() while self.xPlaneDir is None: showwarning('XplaneDir not specified', 'XplaneDir is mandatory. Specify it first!') OptionsWindow(splashWindow,self.databaseDir,'FPLGUI: Set inital options') self.getOptions() # Get navdata folder. if os.path.exists(os.path.join(self.xPlaneDir,'Custom Data','earth_fix.dat')) and \ os.path.exists(os.path.join(self.xPlaneDir,'Custom Data','earth_nav.dat')) and \ os.path.exists(os.path.join(self.xPlaneDir,'Custom Data','earth_awy.dat')) and \ os.path.exists(os.path.join(self.xPlaneDir,'Custom Data','apt.csv')): self.navdataDir = os.path.join(self.xPlaneDir,'Custom Data') else: self.navdataDir = os.path.join(self.xPlaneDir,'Resources','default data') #inititalize Fpl-object self.fplPath = os.path.join(self.xPlaneDir,'Resources\\plugins\\X-IvAp Resources\\Flightplans') self.fpl = Fpl(self.fplPath) # Load Fixes # self.fpl.getFixes(os.path.join(self.navdataDir,'earth_fix.dat')) # self.fpl.getNavaids(os.path.join(self.navdataDir,'earth_nav.dat')) # self.fpl.getAirports(os.path.join(self.navdataDir,'apt.csv')) # self.fpl.getAirways(os.path.join(self.navdataDir,'earth_awy.dat')) # Remove Splash. splashWindow.destroy() # Create main window self.master = Tk() self.master.title('FPLGUI') self.master.resizable(0, 0) ## menu ## menubar = Menu(self.master) filemenu = Menu(menubar,tearoff=0) filemenu.add_command(label="Clear",command=self.clear) filemenu.add_command(label="Send to XP",command=self.send) filemenu.add_separator() filemenu.add_command(label="Load",command=self.load) filemenu.add_command(label="Save",command=self.save) filemenu.add_separator() filemenu.add_command(label="Exit",command=self.master.quit) menubar.add_cascade(label="File", menu=filemenu) acmenu = Menu(menubar,tearoff=0) acmenu.add_command(label="Load Template",command=self.acLoad) acmenu.add_command(label="Save Template",command=self.acSave) menubar.add_cascade(label="Aircraft", menu=acmenu) utilmenu = Menu(menubar,tearoff=0) utilmenu.add_command(label="Import Route",command=self.importRoute) utilmenu.add_separator() utilmenu.add_command(label="Open Simbrief",command=self.simbrief) utilmenu.add_command(label="Simbrief process",command= lambda: self.simbrief(True)) utilmenu.add_command(label="Flightaware",command=self.flightaware) utilmenu.add_separator() utilmenu.add_command(label="Show at Skyvector",command=self.showSkyvector) utilmenu.add_command(label="Export to X-Plane",command=self.export2xp) utilmenu.add_command(label="Export to FF A320",command=self.export2FFA320) utilmenu.add_separator() utilmenu.add_command(label="Show FPL text",command=self.showFplText) utilmenu.add_separator() utilmenu.add_command(label="Options",command=lambda: OptionsWindow(self.master,self.databaseDir)) menubar.add_cascade(label="Extras",menu=utilmenu) self.master.config(menu=menubar) ## row 0-1 ## ## send button self.b_send = Button(self.master, text = "Send", command=self.send) self.b_send.grid(row=0, column=0, rowspan = 2) ## callsign self.l_callsign = Label(self.master, text="7 a/c ident") self.l_callsign.grid(row=0, column=1) self.callsign = StringVar(self.master) self.e_callsign = Entry(self.master, textvariable=self.callsign) self.e_callsign.grid(row=1, column=1) self.callsign.trace_add('write', self.e_callsignCB) ## rules self.l_rules = Label(self.master, text="8 flight rules") self.l_rules.grid(row=0, column=2) self.rules = StringVar(self.master) self.rules.set("V") self.o_rules = OptionMenu(self.master, self.rules, "V", "I", "Y", "Z") self.o_rules.grid(row=1, column=2) ## flighttype self.l_flighttype = Label(self.master, text=" type of flight") self.l_flighttype.grid(row=0, column=3) self.flighttype = StringVar(self.master) self.flighttype.set("S") self.o_flighttype = OptionMenu(self.master, self.flighttype, "S", "N", "G", "M", "X") self.o_flighttype.grid(row=1, column=3) ## row 2-3 ## ## number self.l_number = Label(self.master, text="9 number") self.l_number.grid(row=2, column=0) self.number = StringVar(self.master) self.e_number = Entry(self.master, textvariable=self.number) self.e_number.grid(row=3, column=0) self.number.trace_add('write', self.e_numberCB) ## type of aircraft self.l_actype = Label(self.master, text="type of aircraft") self.l_actype.grid(row=2, column=1) self.actype = StringVar(self.master) self.e_actype = Entry(self.master, textvariable=self.actype) self.e_actype.grid(row=3, column=1) self.actype.trace_add('write', self.e_actypeCB) ## wakecat self.l_wakecat = Label(self.master, text="wake turb cat") self.l_wakecat.grid(row=2, column=2) self.wakecat = StringVar(self.master) self.wakecat.set("L") self.o_wakecat = OptionMenu(self.master, self.wakecat, "L", "M", "H", "J") self.o_wakecat.grid(row=3, column=2) ## equipment self.l_equipment = Label(self.master, text="10 equipment") self.l_equipment.grid(row=2, column=3) self.equipment = StringVar(self.master) self.e_equipment = Entry(self.master, textvariable=self.equipment) self.e_equipment.grid(row=3, column=3) self.equipment.trace_add('write', self.e_equipmentCB) ## equipment self.l_transponder = Label(self.master, text="transponder") self.l_transponder.grid(row=2, column=4) self.transponder = StringVar(self.master) self.e_transponder = Entry(self.master, textvariable=self.transponder) self.e_transponder.grid(row=3, column=4) self.transponder.trace_add('write', self.e_transponderCB) ## row 4-5 ## ## depicao self.l_depicao = Label(self.master, text="13 departure aerodrome") self.l_depicao.grid(row=4, column=0) self.depicao = StringVar(self.master) self.e_depicao = Entry(self.master, textvariable=self.depicao) self.e_depicao.grid(row=5, column=0) self.depicao.trace_add('write', self.e_depicaoCB) ## deptime self.l_deptime = Label(self.master, text="departure time") self.l_deptime.grid(row=4, column=1) self.deptime = StringVar(self.master) self.e_deptime = Entry(self.master, textvariable=self.deptime) self.e_deptime.grid(row=5, column=1) self.deptime.trace_add('write', self.e_deptimeCB) ## row 6-7 ## ## speed self.l_speed = Label(self.master, text="15 cruising speed") self.l_speed.grid(row=6, column=0, columnspan=2) self.speedtype = StringVar(self.master) self.speedtype.set("N") self.o_speedtype = OptionMenu(self.master, self.speedtype, "N", "M") self.o_speedtype.grid(row=7, column=0) self.speed = StringVar(self.master) self.e_speed = Entry(self.master, textvariable=self.speed) self.e_speed.grid(row=7, column=1) self.speed.trace_add('write', self.e_speedCB) ## level self.l_level = Label(self.master, text="flight altutude/level") self.l_level.grid(row=6, column=2, columnspan=2) self.leveltype = StringVar(self.master) self.leveltype.set("F") self.o_level = OptionMenu(self.master, self.leveltype, "F", "A", "VFR") self.o_level.grid(row=7, column=2) self.level = StringVar(self.master) self.e_level = Entry(self.master, textvariable=self.level) self.e_level.grid(row=7, column=3) self.level.trace_add('write', self.e_levelCB) ## row 8-9 ## ##route self.l_route = Label(self.master, text=" route") self.l_route.grid(row=8, column=0, sticky=W) self.route = StringVar(self.master) self.e_route = Entry(self.master, width=105, textvariable=self.route) self.e_route.grid(row=9, column=0, columnspan=5) self.route.trace_add('write', self.e_routeCB) ## row 10-11 ## ## destinationAP self.l_desticao = Label(self.master, text="13 destination aerodrome") self.l_desticao.grid(row=10, column=0) self.desticao = StringVar(self.master) self.e_desticao = Entry(self.master, textvariable=self.desticao) self.e_desticao.grid(row=11, column=0) self.desticao.trace_add('write', self.e_desticaoCB) ## duration self.l_eet = Label(self.master, text="EET") self.l_eet.grid(row=10, column=1) self.eet = StringVar(self.master) self.e_eet = Entry(self.master, textvariable=self.eet) self.e_eet.grid(row=11, column=1) self.eet.trace_add('write', self.e_eetCB) ## alternates self.l_alticao = Label(self.master, text="alternate") self.l_alticao.grid(row=10, column=2) self.alticao = StringVar(self.master) self.e_alticao = Entry(self.master, textvariable=self.alticao) self.e_alticao.grid(row=11, column=2) self.alticao.trace_add('write', self.e_alticaoCB) self.l_alt2icao = Label(self.master, text="2nd alternate") self.l_alt2icao.grid(row=10, column=3) self.alt2icao = StringVar(self.master) self.e_alt2icao = Entry(self.master, textvariable=self.alt2icao) self.e_alt2icao.grid(row=11, column=3) self.alt2icao.trace_add('write', self.e_alt2icaoCB) ## row 12-13 ## ##other self.l_other = Label(self.master, text="other") self.l_other.grid(row=12, column=0, sticky=W) self.other = StringVar(self.master) self.e_other = Entry(self.master, width=105, textvariable=self.other) self.e_other.grid(row=13, column=0, columnspan=5) self.other.trace_add('write', self.e_otherCB) ## row 14-15 ## ##endurance self.l_endurance = Label(self.master, text="19 endurance") self.l_endurance.grid(row=14, column=0) self.endurance = StringVar(self.master) self.e_endurance = Entry(self.master, textvariable=self.endurance) self.e_endurance.grid(row=15, column=0) self.endurance.trace_add('write', self.e_enduranceCB) ##persons self.l_pob = Label(self.master, text="persons on board") self.l_pob.grid(row=14, column=1) self.pob = StringVar(self.master) self.e_pob = Entry(self.master, textvariable=self.pob) self.e_pob.grid(row=15, column=1) self.pob.trace_add('write', self.e_pobCB) ##pic self.l_pic = Label(self.master, text="pilot in command") self.l_pic.grid(row=14, column=2) self.pic = StringVar(self.master) self.e_pic = Entry(self.master, width=40, textvariable=self.pic) self.e_pic.grid(row=15, column=2, columnspan=2) self.pic.trace_add('write', self.e_picCB) ## row 16 ## ##empty empty = Label(self.master, text="") empty.grid(row=16, column=0) self.updateContent() # Set master window options self.master.update() masterWidth = self.master.winfo_width() masterHeight = self.master.winfo_height() x = round((self.screenWidth/2) - (masterWidth/2)) y = round((self.screenHeight/2) - (masterHeight/2)) self.master.geometry('{}x{}+{}+{}'.format(masterWidth,masterHeight,x,y)) self.master.title('FPLGUI') self.master.resizable(0, 0) self.master.iconbitmap(os.path.join(self.supportFilesDir,'FPLGUI.ico')) # Start master mainloop. self.master.mainloop()
def __init__(self, master): self.master_frame = master Toplevel.__init__(self) self.transient(root) self.geometry('400x400') self.lift() # Elementos lbl_titulo = Label(self, text="Produtos") lbl_nome = Label(self, text="Nome:") txt_nome = Entry(self) lbl_consignado = Label(self, text="Consignado:") var_rdio = IntVar() rdio_consignado = Radiobutton(self, text="Sim", variable=var_rdio, value=1) rdio_consignado.grid(row=2, column=1) rdio_consignado = Radiobutton(self, text="Não", variable=var_rdio, value=0) rdio_consignado.grid(row=2, column=2) lbl_distribuidor = Label(self, text="Distribuidor:") var_drop = StringVar(root) list_distribuidores = ModelDistribuidor.lista(self) var_drop.set(list_distribuidores[0]) popupMenu = OptionMenu(self, var_drop, *list_distribuidores) btn_alterar = Button( self, text="Alterar", command=lambda: self.ControllerAlterar( self.list_produtos.get(ACTIVE), txt_nome.get())) btn_adicionar = Button( self, text="Adicionar", command=lambda: self.ControllerAdicionar(txt_nome.get())) self.list_produtos = Listbox(self) btn_remover = Button(self, text="Remover", command=lambda: self.ControllerRemover( self.list_produtos.get(ACTIVE))) btn_voltar = Button(self, text="Voltar", command=lambda: self.voltar()) # Layout lbl_titulo.grid(row=0, column=1) lbl_nome.grid(row=1, column=0) txt_nome.grid(row=1, column=1) lbl_consignado.grid(row=2, column=0) lbl_distribuidor.grid(row=3, column=0) popupMenu.grid(row=3, column=1) btn_adicionar.grid(row=4, column=2) btn_alterar.grid(row=4, column=3) self.list_produtos.grid(row=5, column=1) btn_remover.grid(row=5, column=2) btn_voltar.grid(row=6, column=1) # Calculos self.ControllerListar()
def __init__(self, master): self.master = master master.title("PDF-App GUI") master.resizable(False, False) main_frame = Frame(master) top_frame = Frame(main_frame) bottom_frame = Frame(main_frame) label_input_path = Label(top_frame, text="Input file(s)") self.input_path = StringVar() input_path_field = Entry(top_frame, textvariable=self.input_path) input_browse_button = Button( top_frame, text="Browse", command=lambda: self.browse_multiple(self.input_path)) self.add_bookmarks = IntVar() bookmarks_checkbox = Checkbutton(top_frame, text="Add bookmarks", variable=self.add_bookmarks) label_watermark_path = Label(top_frame, text="Watermark") self.watermark_path = StringVar() watermark_path_field = Entry(top_frame, textvariable=self.watermark_path) watermark_browse_button = Button( top_frame, text="Browse", command=lambda: self.browse_single(self.watermark_path, [( "PDF files", "*.pdf")])) label_js_path = Label(top_frame, text="Javascript file") self.js_path = StringVar() js_path_field = Entry(top_frame, textvariable=self.js_path) js_browse_button = Button( top_frame, text="Browse", command=lambda: self.browse_single(self.js_path, [( "Javascript files", "*.js"), ("Any files", "*.*")])) label_js = Label(top_frame, text="Javascript") js_frame = Frame(top_frame) scrollbar = Scrollbar(js_frame) self.js_field = Text(js_frame, height=4, width=30) scrollbar.pack(side=RIGHT, fill=Y) self.js_field.pack(side=LEFT, fill=Y) scrollbar.config(command=self.js_field.yview) self.js_field.config(yscrollcommand=scrollbar.set) self.encrypt = StringVar() label_encrypt = Label(top_frame, text="Encrypt") encrypt_field = Entry(top_frame, textvariable=self.encrypt) self.encryption = StringVar() encryptions = ["128bit", "40bit"] self.encryption.set(encryptions[0]) encryption_dropdown = OptionMenu(top_frame, self.encryption, *encryptions) self.decrypt = StringVar() label_decrypt = Label(top_frame, text="Decrypt") decrypt_field = Entry(top_frame, textvariable=self.decrypt) label_rotation = Label(top_frame, text="Rotation") self.rotation = StringVar() rotations = [0, 90, 180, 270] self.rotation.set(rotations[0]) rotation_dropdown = OptionMenu(top_frame, self.rotation, *rotations) self.start_button = Button(top_frame, text="Start", command=self.start) # self.progress_listbox = Listbox(bottomFrame) progress_listbox_frame = Frame(root, bd=0, relief=SUNKEN) xscrollbar = Scrollbar(progress_listbox_frame, orient=HORIZONTAL) yscrollbar = Scrollbar(progress_listbox_frame) xscrollbar.pack(side=BOTTOM, fill=X) yscrollbar.pack(side=RIGHT, fill=Y) self.progress_listbox = Listbox(progress_listbox_frame, xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set) self.progress_listbox.pack(fill=X) xscrollbar.config(command=self.progress_listbox.xview) yscrollbar.config(command=self.progress_listbox.yview) main_frame.pack(fill=BOTH, expand=True) top_frame.pack(fill=X, side=TOP, expand=False) label_input_path.grid(row=0, column=0, sticky=W + E) input_path_field.grid(row=0, column=1, sticky=W + E) input_browse_button.grid(row=0, column=2, sticky=W + E) bookmarks_checkbox.grid(row=1, column=0, columnspan=3, sticky=W + E) label_rotation.grid(row=2, column=0, sticky=W + E) rotation_dropdown.grid(row=2, column=1, columnspan=2, sticky=W + E) label_encrypt.grid(row=3, column=0, sticky=W + E) encrypt_field.grid(row=3, column=1, sticky=W + E) encryption_dropdown.grid(row=3, column=2, sticky=W + E) label_decrypt.grid(row=4, column=0, sticky=W + E) decrypt_field.grid(row=4, column=1, columnspan=2, sticky=W + E) label_watermark_path.grid(row=5, column=0, sticky=W + E) watermark_path_field.grid(row=5, column=1, sticky=W + E) watermark_browse_button.grid(row=5, column=2, sticky=W + E) label_js_path.grid(row=6, column=0, sticky=W + E) js_path_field.grid(row=6, column=1, sticky=W + E) js_browse_button.grid(row=6, column=2, sticky=W + E) label_js.grid(row=7, column=0, sticky=W + E) js_frame.grid(row=7, column=1, columnspan=2, sticky=W + E) self.start_button.grid(row=8, column=0, columnspan=3, sticky=W + E) bottom_frame.pack(fill=X, side=BOTTOM, expand=False) progress_listbox_frame.pack(fill=X)
def __init__(self): window = Toplevel() window.title("Plotting Menu") # get screen width and height screen_width = window.winfo_screenwidth() screen_height = window.winfo_screenheight() window.geometry("650x200+%d+%d" % (screen_width / 2.95, 100 + screen_height / 2)) self.plotterScreen = PlotterWindow() # can have 3 different plots at once self.numberOfPlots = self.plotterScreen.get_numberOfPlots() self.plot = [StringVar() for i in range(self.numberOfPlots)] self.plotVal = [IntVar() for i in range(self.numberOfPlots)] self.plotValStore = [0 for i in range(self.numberOfPlots)] self.plotables = [] self.options = ["None"] for each in self.plot: each.set("None") def plotTS(): for i in range(0, self.numberOfPlots): if self.plotVal[i].get() != self.plotValStore[i]: self.plotValStore[i] = self.plotVal[i].get() if self.plotValStore[i] == 0: self.plotterScreen.makePlot(None, 0, i) return for each in self.plotables: if each[0] == self.plot[i].get(): self.plotterScreen.makePlot( each[1][:, int(self.selectVoxel[i].get())], 1, i) return self.plotterScreen.makePlot(None, 0, i) return self.plotSelectDropDown = [ OptionMenu(window, self.plot[i], *self.options) for i in range(self.numberOfPlots) for i in range(self.numberOfPlots) ] self.selectVoxel = [ Entry(window, width=10) for i in range(self.numberOfPlots) for i in range(self.numberOfPlots) ] self.plotButton = [ Checkbutton(window, text=" Plot TS " + str(i), variable=self.plotVal[i], command=plotTS) for i in range(self.numberOfPlots) ] for each in self.selectVoxel: each.insert(0, 0) for i in range(0, self.numberOfPlots): self.plotSelectDropDown[i].grid(row=0, column=i, padx=(5, 5), pady=(5, 5)) self.selectVoxel[i].grid(row=1, column=i, padx=(5, 5), pady=(5, 5)) self.plotButton[i].grid(row=2, column=i, padx=(5, 5), pady=(5, 5))