def main(): global drawing_area root = Tk() root.title("Drawer") drawing_area = Canvas(root, width=300, height=300, bg="white") # Binding Events to the canvas drawing_area.bind("<B1-Motion>", drag) drawing_area.bind("<ButtonRelease-1>", drag_end) drawing_area.pack() # Buttons # Quit Button b1 = Button(root, text="Quit") b1.pack() b1.bind("<Button-1>", quit) # Clear Button b2 = Button(root, text="Clear") b2.pack() b2.bind("<Button-1>", clear) # Save Button b3 = Button(root, text="Save") b3.pack() b3.bind("<Button-1>", save) root.mainloop()
def create_voices(self): voice_ids = ['1', '2', '3', '4'] SCALES = OrderedDict([ ('pan_pos', {'min': -1, 'max': 1, 'start': 0.5, 'res': 0.001}), ('volume', {'min': 0, 'max': 1, 'start': 0.666, 'res': 0.001}), ('slide_duration_msecs', {'min': 0, 'max': 2000, 'start': 60, 'res': 1}), ('slide_duration_prop', {'min': 0, 'max': 2, 'start': 0.666, 'res': 0.001}), ('binaural_diff', {'min': 0, 'max': 66, 'start': 0.2, 'res': 0.01}) ]) for vid in voice_ids: counter = 0 for sca in SCALES: name = 'voice_' + vid + '_' + sca setattr(self, 'min_' + name, SCALES[sca]['min']) setattr(self, 'max_' + name, SCALES[sca]['max']) this_sca = Scale(self, label=sca, orient=HORIZONTAL, from_=getattr(self, 'min_' + name), to=getattr(self, 'max_' + name), resolution=SCALES[sca]['res']) this_sca.enable = ('enable' in SCALES[sca].keys() and SCALES[sca]['enable'] or None) this_sca.disable = ('disable' in SCALES[sca].keys() and SCALES[sca]['disable'] or None) this_sca.grid(column=int(2 + int(vid)), row=counter, sticky=E + W) this_sca.bind("<ButtonRelease>", self.scale_handler) this_sca.ref = name counter += 1 CHECK_BUTTONS = OrderedDict( [('mute', False), ('automate_binaural_diffs', True), ('automate_note_duration_prop', True), ('use_proportional_slide_duration', {'val': True, 'label': 'proportional slide'}), ('automate_pan', True), ('automate_wavetables', True)]) for vid in voice_ids: counter = 0 cb_frame = LabelFrame(self, text="Voice {0} - Automation".format(vid)) setattr(self, 'voice_' + vid + '_cb_frame', cb_frame) for cb in CHECK_BUTTONS: options = CHECK_BUTTONS[cb] name = 'voice_' + vid + '_' + cb label = (options['label'] if isinstance(options, dict) and 'label' in options.keys() else (cb[9:] if cb[:9] == 'automate_' else cb)) setattr(self, name, IntVar(value=type(options) == dict and options['val'] or options)) self.this_cb = Checkbutton(cb_frame, text=label, variable=getattr(self, name)) self.this_cb.bind('<Button-1>', self.check_boxes_handler) self.this_cb.disable = None self.this_cb.grid(sticky=W, column=0, row=counter) self.this_cb.ref = name counter += 1 # add trigger wavetable-button trigWavetableButton = Button(cb_frame, text='Next Wavetable') trigWavetableButton.bind('<Button-1>', self.trigger_waveform_handler) trigWavetableButton.ref = 'voice_' + vid + "_trigger_wavetable" trigWavetableButton.grid(row=counter) cb_frame.grid(column=int(vid) + 2, row=5, sticky=E + W + N, rowspan=8) for vid in voice_ids: generation_types = ["random", "random_harmonic", "harmonic"] partial_pools = ["even", "odd", "all"] prefix = 'voice_' + vid + '_' types_name = prefix + 'wavetable_generation_type' pools_name = prefix + 'partial_pool' setattr(self, types_name, StringVar()) getattr(self, types_name).set("random") setattr(self, pools_name, StringVar()) getattr(self, pools_name).set("all") target_frame = getattr(self, 'voice_' + vid + '_cb_frame') gen_typ_frame = LabelFrame(target_frame, text="type") gen_typ_frame.grid(row=len(target_frame.winfo_children()), sticky=W) for gen_t in generation_types: gen_t_entry = Radiobutton(gen_typ_frame, value=gen_t, text=gen_t, anchor=W, variable=getattr(self, types_name)) gen_t_entry.bind('<ButtonRelease-1>', self.wt_handler) gen_t_entry.ref = types_name gen_t_entry.grid(row=len(gen_typ_frame.winfo_children()), sticky=W) pp_frame = LabelFrame(target_frame, text="harmonics") for pp in partial_pools: pp_entry = Radiobutton(pp_frame, value=pp, text=pp, anchor=W, variable=getattr(self, pools_name)) pp_entry.bind('<ButtonRelease-1>', self.wt_handler) pp_entry.ref = pools_name pp_entry.grid(row=len(pp_frame.winfo_children()), sticky=E + W) this_num_partials = Scale(pp_frame, label='number of harmonics', orient=HORIZONTAL, from_=1, to=24, resolution=1) this_num_partials.ref = prefix + 'num_partials' this_num_partials.grid(column=0, row=len(pp_frame.winfo_children()), sticky=E + W) this_num_partials.bind("<ButtonRelease>", self.scale_handler) pp_frame.grid(row=len(target_frame.winfo_children()), sticky=E + W)
def run(self): print "Creating animation server..." if os.path.exists(SOCKET_NAME): os.remove(SOCKET_NAME) self.server = Animator(AnimationRequestHandler, self.simulate) if not self.simulate: print "Starting animation server..." print "Animation server is running on socket {0}".format( SOCKET_NAME) #print "Quit the server with CONTROL-C." self.server.serve_forever() else: print "Starting simulation..." button_window = Toplevel() button_window.title('Button Input') img = PhotoImage(file="easy_button.gif") single_easy_button = Button(button_window, image=img) single_easy_button.pack() single_easy_button.bind( "<Button-1>", lambda e: server.processCommand(ButtonEvent.SINGLEPRESS)) double_easy_button = Button(button_window, text="double tap") double_easy_button.pack() double_easy_button.bind( "<Button-1>", lambda e: server.processCommand(ButtonEvent.DOUBLEPRESS)) mainloop()
def initUI(self): self.parent.title("Simple") self.pack(fill=BOTH, expand=1) self.fireFrame = Frame(self, background="lightgrey", height = 20) self.fireFrame.pack(fill=X, side=BOTTOM) leftFrame = Frame(self, background="lightgrey" ) leftFrame.pack(fill=Y, side = LEFT) rightFrame = Frame(self, background="lightgrey") rightFrame.pack(fill=Y, side = RIGHT) rightFill = Frame(rightFrame, background="lightgrey") rightFill.pack(side=TOP ) centreFrame = Frame(self, background="lightgrey") centreFrame.pack(fill=BOTH, expand=True) clusterFrame = Frame(centreFrame, background="lightgrey", width = 80, height = 80) clusterFrame.pack(pady = 60) self.lights = [] self.lights.append( Frame(clusterFrame, width=20, height=20, background="darkgrey") ) self.lights[0].grid(row=0, column =0, padx = 10, pady = 10) self.lights.append( Frame(clusterFrame, width=20, height=20, background="darkgrey") ) self.lights[1].grid(row=0, column =1, padx = 10, pady = 10) self.lights.append( Frame(clusterFrame, width=20, height=20, background="darkgrey") ) self.lights[2].grid(row=0, column =2, padx = 10, pady = 10) camera = Frame(clusterFrame, width=25, height=25, background = "black") camera.grid(row=1, column =1, padx = 10, pady = 10) self.lights.append( Frame(clusterFrame, width=20, height=20, background="darkgrey") ) self.lights[3].grid(row=2, column =0, padx = 10, pady = 10) self.lights.append( Frame(clusterFrame, width=20, height=20, background="darkgrey") ) self.lights[4].grid(row=2, column =2, padx = 10, pady = 10) self.cambuttons = Frame( clusterFrame, background="lightgrey") self.cambuttons.grid( row = 3, column = 1) accept = Button( self.cambuttons, text="Accept" , command= self.acceptButtonPress, width=5) accept.pack() reject = Button( self.cambuttons, text="Reject" , command= self.rejectButtonPress, width=5) reject.pack() fail = Button( self.cambuttons, text="Fail" , command= self.failButtonPress, width=5) fail.pack() self.cambuttons.grid_remove() self.doorStateVar = StringVar() self.doorStateVar.set('Closed'); doorSwitch = Tkinter.Checkbutton(leftFrame, text = "Door Closed", command = self.doorChange, onvalue = 'Closed', offvalue = 'Open', variable = self.doorStateVar) doorSwitch.pack() self.alarmRed = Frame(leftFrame, background='#A88', width=20, height=20) self.alarmRed.pack(side=BOTTOM, padx = 10, pady = 10) self.alarmGreen = Frame(leftFrame, background='#8A8', width=20, height=20) self.alarmGreen.pack(side=BOTTOM, padx = 10, pady = 10) userButton = Button(rightFrame, text = "Press", command = self.userButtonPress, padx = 20) userButton.bind('<Button-1>', self.userButtonDown) userButton.bind('<ButtonRelease-1>', self.userButtonUp) userButton.pack(side=BOTTOM)
class App(object): def __init__(self,master): frame=Frame(master) frame.pack(fill=BOTH,expand=True) label=Label(frame,text='URL:',fg='green',font=('Courier New',16)) label.grid(row=0,column=0,sticky=W) self.url='' self.text=Text(frame,width=60,height=7,font=('Courier New',12)) self.text.grid(row=1,columnspan=2) self.button=Button(frame,text='检测',font=('Courier New',12)) self.button.grid(row=2,column=1,sticky=E) self.response=Text(frame,font=('Courier New',12),width=60,height=10) self.response.grid(row=3, column=0,columnspan=2) self.msg=StringVar() self.result=Label(frame,textvariable=self.msg,fg='blue',font=('Courier New',12)) self.result.grid(row=4,column=0,columnspan=2,sticky=N+S+W+E) self.button.bind('<Button-1>',self.check) self.pattern=re.compile('^(?:http|https)://(?:\w+\.)+.+') self.header= { "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36" } self.payload='' def check(self,event): self.msg.set('') self.url=self.text.get(1.0,END).strip() chek_url=self.pattern.match(self.url) # print chek_url.group() if not chek_url : # print ('123') self.msg.set('请输入正确的(GET)URL!') else: try: response =get(self.url,headers=self.header) self.response.delete(1.0,END) self.response.insert(END,response.text) # print response.content req_pattern=re.compile('\s*?\w+\([\w\W]+?\)|;$') res_match=req_pattern.match(response.text) if res_match: self.result.config(fg='red') self.msg.set('该URL 存在 JSONP劫持 漏洞!!! payload生成后期有时间会完善!') else: self.msg.set('该URL 不存在 JSONP劫持 漏洞。') except : self.result.config(fg='red') self.msg.set('网络资源请求失败,请确保已经接入互联网和网址的有效性!')
class closing_comment(): def __init__(self, master): self._master = master self.interior = Frame(master, class_="closing") instruction_label_frame = Frame(self.interior, class_="closing") instruction_label_frame.pack(fill=X) self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic") self.content_font = tkfont.Font(family='Helvetica', size=14) self._label_instruction = Label( instruction_label_frame, text="Please give your overall comment to the system.", font=self.title_font) self._label_instruction.pack() # entry form self.var_entry = StringVar() entry_frame = Frame(self.interior, class_="entry") entry_frame.pack(fill=X) self._entry_comment = Entry(entry_frame, width=70, textvariable=self.var_entry) self._entry_comment.pack(side=LEFT, fill='both', expand=True) #button button_frame = Frame(self.interior, class_="Submit") button_frame.pack(fill=X) self._button_next = Button(button_frame, text="Submit", command=self.close_window, width=50, font=self.content_font) self._button_next.pack() self._button_next.bind("<Button-1>", self._on_button_submit) self._button_next.focus() def close_window(self): self._master.destroy() def _on_button_submit(self, event): # get the input from user print("var_entry:", self.var_entry.get()) _log = open("log.txt", "a") _log.write("\nClosing comment: %s" % self.var_entry.get())
def row_helper(): for row in range(1, 9): for column in range(1, 9): if row % 2 == 0: bg = "Black" if column % 2 == 0: bg = "White" else: bg = "White" if column % 2 == 0: bg = "Black" b1 = Button(self.labelframe, bg=bg, width=20, height=6, bd=8, relief=RAISED) b1.grid(row=row, column=column, sticky="N") b1.bind("<Button 1>", lambda e=row, i=row, k=column: self.movement(i, k))
def qbutton(f, l=None): def qbuttonin(event): event.widget.config(bg=Styles.colours["helpIN"]) def qbuttonout(event): event.widget.config(bg=Styles.colours["helpB"]) b = Button(f, text="?", justify=RIGHT, relief=FLAT, bg=Styles.colours["helpB"], width=2, font=Styles.fonts["button"], foreground=Styles.colours["helpText"]) b.bind("<Enter>", qbuttonin) b.bind("<FocusIn>", qbuttonin) b.bind("<Leave>", qbuttonout) b.bind("<FocusOut>", qbuttonout) if l is not None: b.bind("<Button-1>", l) return b
def camobutton(f, text, width, click=None): def camobuttonin(event): event.widget.config(bg=Styles.colours["grey"], foreground=Styles.colours["darkGrey"]) def camobuttonout(event): event.widget.config(bg=Styles.colours["darkGrey"], foreground=Styles.colours["grey"]) b = Button(f, text=text, justify=RIGHT, relief=FLAT, bg=Styles.colours["darkGrey"], width=width, font=Styles.fonts["entryFilled"], foreground=Styles.colours["grey"]) b.bind("<Enter>", camobuttonin) b.bind("<FocusIn>", camobuttonin) b.bind("<Leave>", camobuttonout) b.bind("<FocusOut>", camobuttonout) if click is not None: b.bind("<Button-1>", click) return b
def yellowbutton(f, text, width, click=None): def yellowbuttonin(event): event.widget.config(bg=Styles.colours["yellowHover"]) def yellowbuttonout(event): event.widget.config(bg=Styles.colours["yellow"]) b = Button(f, text=text, justify=RIGHT, relief=FLAT, bg=Styles.colours["yellow"], width=width, font=Styles.fonts["button"]) b.bind("<Enter>", yellowbuttonin) b.bind("<FocusIn>", yellowbuttonin) b.bind("<Leave>", yellowbuttonout) b.bind("<FocusOut>", yellowbuttonout) if click is not None: b.bind("<Button-1>", click) return b
def add_tabs(self, tabs=None): """ Add tab or lot of tabs tabs args is a list of dict where dict is a single tab format of dict is : * title => title for this tab * content => content for this tab If no title's defined the default title as NaN If no centent's defined the default content is the index of the tabs """ if not tabs or len(tabs) == 0: raise TabsError('Tabs args is required.') for current_tabs in tabs: # Button configure button = Button( self.frame_btn, text=current_tabs.get('title', 'NaN') ) button.configure( state='disabled', relief='flat', highlightbackground='white' ) button.pack(side='left') # Content configure #content = Frame(self.frame_content) content = current_tabs.get( 'content', Label(text='Tab %s' % len(self.content)) ) content.config() arguments = {'button' : button, 'content' : content} button.bind( '<Button-1>', lambda event, args=arguments: self.show_tabs(event, args) ) #component = current_tabs.get('content', Label(text='Tabs %d' % len(self.onglets))) #component.pack(side='bottom') self.onglets.append(button) self.content.append(content) if len(self.onglets) == 1: button.configure(state='normal', highlightbackground='gray') content.pack(side='bottom', fill='both', expand='yes')
def draw(self, init=False): if init: self.canvas_width, self.canvas_height = 0, 0 self.canvas = Canvas(self.root, bg="black") self.colour_cells = [] # update colour cells while self.colour_cells != []: #print('killing...') self.colour_cells[0].unbind("<Button-1>") self.colour_cells[0].destroy() del self.colour_cells[0] self.button_index_dict = dict() nb_colours = self.size[0]*self.size[1] pos = 0 for ix in range(self.size[0]): for iy in range(self.size[1]): colour = self.colours[pos] # create the new cell colour_cell = Button(self.canvas, bg=toHex([v/255. for v in colour]), activebackground=toHex([v/255. for v in colour])) colour_cell.bind("<Button-1>", self.handleColourSelector) # place the cell cell_width = self.canvas_width/self.size[0] cell_height = self.canvas_height/self.size[1] cell_width = min(cell_width, cell_height) cell_height = min(cell_width, cell_height) x = ix * cell_width y = iy * cell_height colour_cell.place(x = x, y = y, width = cell_width, height=cell_height) self.button_index_dict[colour_cell] = pos self.colour_cells.append(colour_cell) pos += 1
def initUI(self): self.parent.title("MinesweePy") for i in range(0, self.x): self.columnconfigure(i, pad=0) for i in range(0, self.y): self.rowconfigure(i, pad=0) for i in range(0, self.x): for j in range(0, self.y): button = Button(self, text=" ", borderwidth=0, relief=RAISED) button.grid(row=i, column=j) button.bind('<Button-1>', on_single_left_click) button.bind('<Button-2>', on_right_click) button.square = self.game.grid[i][j] self.pack()
def initUI(self): self.parent.title("MinesweePy") for i in range(0, self.x): self.columnconfigure(i, pad=0) for i in range(0, self.y): self.rowconfigure(i, pad=0) for i in range(0, self.x): for j in range(0, self.y): button = Button(self, text=" ", borderwidth=0, relief=RAISED) button.grid(row=i, column=j) button.bind('<Button-1>', on_single_left_click) button.bind('<Button-2>', on_right_click) button.square = self.game.grid[i][j] self.pack()
def display(self, frame_obj): canvas_popup = Canvas(frame_obj, background=conf.left_nav_background) # canvas_popup.config(x=0, y=0) canvas_popup.place(x=(frame_obj.sw/2), y=(frame_obj.sh/2)-100) if self.title != "": title_label = Label(canvas_popup, text=self.title, fg=conf.main_text_color) title_label.config(highlightbackground=conf.left_nav_background, background=conf.left_nav_background) title_label.grid(row=0, sticky='e,w', padx=10, pady=10) if self.content != "": content_label = Label(canvas_popup, text=self.content, fg=conf.main_text_color) content_label.config(highlightbackground=conf.left_nav_background, background=conf.left_nav_background) content_label.grid(row=1, sticky='e,w', padx=10, pady=10) if self.content != "": action_button = Button(canvas_popup, text="Ok", fg=conf.main_text_color) action_button.config(highlightbackground=conf.left_nav_background, background=conf.left_nav_background) action_button.bind("<Button-1>", self.dismiss) action_button.grid(row=2, sticky='e,w', padx=10, pady=10)
def main(): global drawing_area root = Tk() root.title("Drawer") drawing_area = Canvas(root, width=300, height=300, bg="white") # Binding Events to the canvas drawing_area.bind("<B1-Motion>", drag) drawing_area.bind("<ButtonRelease-1>", drag_end) drawing_area.pack() #Buttons #Quit Button b1 = Button(root, text="Quit") b1.pack() b1.bind("<Button-1>", quit) #Clear Button b2 = Button(root, text="Clear") b2.pack() b2.bind("<Button-1>", clear) #Save Button b3 = Button(root, text="Save") b3.pack() b3.bind("<Button-1>", save) root.mainloop()
def run(self): print "Creating animation server..." if os.path.exists(SOCKET_NAME): os.remove(SOCKET_NAME) self.server = Animator(AnimationRequestHandler, self.simulate) if not self.simulate: print "Starting animation server..." print "Animation server is running on socket {0}".format(SOCKET_NAME) #print "Quit the server with CONTROL-C." self.server.serve_forever() else: print "Starting simulation..." button_window = Toplevel() button_window.title('Button Input') img = PhotoImage(file="easy_button.gif") single_easy_button = Button(button_window, image=img) single_easy_button.pack() single_easy_button.bind("<Button-1>", lambda e: server.processCommand(ButtonEvent.SINGLEPRESS)) double_easy_button = Button(button_window, text="double tap") double_easy_button.pack() double_easy_button.bind("<Button-1>", lambda e: server.processCommand(ButtonEvent.DOUBLEPRESS)) mainloop()
def create_check_buttons(self): self.cb_frame = LabelFrame(self, text="Global Settings") for cb in CHECK_BUTTONS: label = cb target_parent = self.cb_frame if isinstance(CHECK_BUTTONS[cb], dict) and 'sub_frame' in CHECK_BUTTONS[cb].keys(): target_parent = getattr(self, CHECK_BUTTONS[cb]['sub_frame']) setattr(self, cb, IntVar(value=type(CHECK_BUTTONS[cb]) == dict and CHECK_BUTTONS[cb]['val'] or CHECK_BUTTONS[cb])) self.this_cb = Checkbutton(target_parent, text=label, variable=getattr(self, cb)) self.this_cb.bind('<Button-1>', self.check_boxes_handler) self.this_cb.disable = (type(CHECK_BUTTONS[cb]) == dict and 'disable' in CHECK_BUTTONS[cb].keys()) self.this_cb.grid(sticky=W, column=0, row=len(target_parent.winfo_children())) self.this_cb.ref = cb for but in GLOBAL_BUTTONS: label = but ele = GLOBAL_BUTTONS[but] this_but = Button(self.cb_frame, text=but) this_but.bind('<ButtonRelease-1>', getattr(self, ele['handler'])) this_but.ref = but this_but.grid(sticky=W, column=0, row=len(self.cb_frame.winfo_children())) self.cb_frame.grid(column=0, row=0, rowspan=10, sticky=N)
def initUI(self): self.parent.title("RepLineGui") pathLabel = Label(self, text="Path: %s" % '') pathLabel.grid(row=0, column=0, columnspan=3, sticky="w") self.widgetDict["pathLabel"] = pathLabel browseButton = Button(self, text="Browse") browseButton.grid(row=0, column=3, sticky="nsew") browseButton.bind("<ButtonRelease-1>", self.setAccessionList) self.widgetDict["browseButton"] = browseButton accessionLabel = Label(self, text="Accession:") accessionLabel.grid(row=1, column=0, sticky="w") self.widgetDict["accessionLabel"] = accessionLabel cobsLabel = Label(self, text="Cobs: Select an Accession") cobsLabel.grid(row=2, column=0, sticky="w") self.widgetDict["cobsLabel"] = cobsLabel kernelsLabel = Label(self, text="Kernels: Select a Cob") kernelsLabel.grid(row=2, column=1, sticky="w") self.widgetDict["kernelsLabel"] = kernelsLabel pixelsLabel = Label(self, text="Pixels: Select a Kernel") pixelsLabel.grid(row=2, column=2, sticky="w") self.widgetDict["pixelsLabel"] = pixelsLabel self.testButton() self.pack()
def __init__(self, *args, **kwargs): BasePAFrame.__init__(self, *args, **kwargs) self.current_file = {} self.last_move_path = settings.BASE_CATALOG self.widgets = OrderedDict( (label, { 'label': Label(self, text=label), 'label_data': Label(self) }) for label in LABELS) # виджеты для преименований self.widgets_with_rename = OrderedDict( (label, { 'label': Label(self, text=label), 'label_data': Label(self) }) for label in LABELS_RENAME) # переименование с моим именем self.w_entry_custom_name = Entry(self) self.w_btn_rename_custom_name = Button(self, text=u'Переименовать') self.w_btn_rename_custom_name.bind( '<Button-1>', self.click_rename_button) self.widgets_with_rename[TEXT_MY_NAME] = { 'label': Label(self, text=TEXT_MY_NAME), 'label_data': self.w_entry_custom_name, 'button_rename': self.w_btn_rename_custom_name, } # доп кнопки, переместить удалить _btn_mv = Button(self, text=u'Переместить') _btn_mv.bind('<Button-1>', self.click_move_button) _btn_rm = Button(self, text=u'Удалить') _btn_rm.bind('<Button-1>', self.click_remove_button) self.buttons = ( (_btn_mv, _btn_rm), ) # прописываем кнопки переместить for label, label_widgets in self.widgets_with_rename.iteritems(): if label in LABELS_RENAME: _btn = Button(self, text=u'Переименовать') _btn.bind('<Button-1>', self.click_rename_button) _btn.meta = {} label_widgets['button_rename'] = _btn
def main(): global URLentry global savedirentry global asob # root = Tk() # already done previously root.geometry("650x450+300+300") # it seems TkDND cannot bind members of classes (see below); # so URLentry must be here # must add a frame so label+entry are on top? Nope, # even it as parent messes things up #~ mframe = Tkinter.Frame(master=root, borderwidth=5, bg = 'cyan') #~ # mframe.grid(fill=BOTH) #nope: #~ mframe.pack(fill=BOTH, expand=1) #~ mframe.columnconfigure(1, weight=0) #~ mframe.columnconfigure(2, weight=1) #~ mframe.rowconfigure(1, weight=0) #~ mframe.rowconfigure(2, weight=1) root.columnconfigure(1, weight=0) root.columnconfigure(2, weight=1) root.rowconfigure(1, weight=0) root.rowconfigure(2, weight=0) root.rowconfigure(3, weight=1) # label showLabel = Tkinter.Label(text="URL: ") # master=root showLabel.grid(row=1, column=1, sticky=W) # text entry for URL # actually, even if the entry just has mframe as master, # then it still has ref .155766380.155791436 and # fails TkDND binding; # only when master=root does it work URLentry = Tkinter.Entry() # master=root #print "URLentry ref: ", URLentry # URLentry.grid(row=1, column=2, columnspan=1, sticky=E + W, padx=5) #~ URLentry.pack(fill=BOTH, expand=1) # button: savedirButton = Button(text="savedir") savedirButton.grid(row=2, column=1, padx=5, pady=0, sticky=W) # text entry for save (output) directory savedirentry = Tkinter.Entry() # master=root savedirentry.grid(row=2, column=2, columnspan=1, sticky=E + W, padx=5) # now the rest (will refer to URLentry inside) asob = AssetBuilder(root) asob.grid(row=3, column=1, columnspan=2, sticky=W + S + E) # note, binding to a function which is a class member is not a problem # note, text/plain also picks up filedrops like text/uri-list! dnd.bindtarget( URLentry, asob.handleURLentry, 'text/plain;charset=UTF-8' ) # this reacts on text selection drops from applications (but also file/dir icon drops); 'text/plain;charset=UTF-8' print dnd.bindtarget_query(URLentry) dnd.bindtarget(savedirentry, asob.handlesavedirentry, 'text/plain;charset=UTF-8') # print "-", dnd.bindtarget(savedirentry, asob.handlesavedirentry, 'text/uri-list'), "-" # only file/dir icon drops (no text sel) print dnd.bindtarget_query(savedirentry) savedirButton.bind("<ButtonRelease-1>", chooseSaveDir) # context menu (right-click) asob.make_menu(root) # binds class - so entries are covered with this URLentry.bind_class("Entry", "<Button-3><ButtonRelease-3>", asob.show_menu) # binds element asob.textarea.bind("<Button-3><ButtonRelease-3>", asob.show_menu) root.mainloop()
class SolidDatabaseImporter: def __init__(self, master, system, database_imported): """The constructor method.""" self.version = system.version self.fonttype = system.fonttype self.sfont = get_superfont(self.fonttype) self.master = master self.tframe = Frame(master.tframe) self.frame = Frame(master.frame) self.bframe = Frame(master.bframe) self.tkfont = tkFont.Font(font=system.fonttype) solids_list = database_imported.keys() solids_list.sort() self.solids_list = solids_list self.name_width = 10 for chemical_name in self.solids_list: if (self.tkfont.measure(chemical_name) + 10) > self.name_width: self.name_width = self.tkfont.measure(chemical_name) + 10 if self.name_width < 150: self.name_width = 150 self.solids = [] for solidname in self.solids_list: self.solids.append(Solid(solids_list.index(solidname))) self.solids[-1].read_database(database_imported[solidname]) self.sname = StringVar(self.frame, value='') self.cancelflag = 0 def make_widgets(self): self.instructions = Label( self.tframe, text= 'Please select the chemical you would like to added to the database ' ) self.leftcolumn = Label(self.tframe, text=' ', font='courier 10', width=2) self.checkcolumn = Label(self.tframe, text=' ', font='courier 10', width=5) self.orinamecolumn = Label( self.tframe, text=' ', font='courier 10', width=int(self.name_width * 1.1424219345 / 8) + 1) self.impnamecolumn1 = Label( self.tframe, text=' ', font='courier 10', width=int(self.name_width * 1.1424219345 / 8 / 2) + 1) self.impnamecolumn2 = Label( self.tframe, text=' ', font='courier 10', width=int(self.name_width * 1.1424219345 / 8 / 2) + 1) self.rightcolumn = Label(self.tframe, text=' ', font='courier 10', width=2) self.search_label = Label(self.tframe, text='Search:') self.search_entry = Entry(self.tframe, textvariable=self.sname) self.orinamelabel = Label(self.tframe, text='Original Name') self.impnamelabel = Label(self.tframe, text='Imported Name') self.blank1 = Label(self.tframe, text=' ') self.botleftcolumn = Label(self.frame, text=' ', width=2) self.botcheckcolumn = Label(self.frame, text=' ', width=5) self.botorinamecolumn = Label( self.frame, text=' ', width=int(self.name_width * 1.1424219345 / 8) + 1) self.botimpnamecolumn1 = Label( self.frame, text=' ', width=int(self.name_width * 1.1424219345 / 8 / 2) + 1) self.botimpnamecolumn2 = Label( self.frame, text=' ', width=int(self.name_width * 1.1424219345 / 8 / 2) + 1) self.botrightcolumn = Label(self.frame, text=' ', width=2) self.allbutton = Button(self.bframe, text='Select All', command=self.selectall, width=20) self.unallbutton = Button(self.bframe, text='Unselect All', command=self.unselectall, width=20) self.importbutton = Button(self.bframe, text='Import', command=self.OK, width=20) self.cancelbutton = Button(self.bframe, text='Cancel', command=self.cancel, width=20) self.blank2 = Label(self.bframe, text=' ') self.blank3 = Label(self.bframe, text=' ') self.blank4 = Label(self.frame, text=' ') #show the widgets on the grid (top to bottom and left to right) self.instructions.grid(row=0, columnspan=5, sticky='W', padx=8) self.leftcolumn.grid(row=1, column=0, sticky='WE') self.checkcolumn.grid(row=1, column=1, sticky='WE') self.orinamecolumn.grid(row=1, column=2, sticky='WE') self.impnamecolumn1.grid(row=1, column=3, sticky='WE') self.impnamecolumn2.grid(row=1, column=4, sticky='WE') self.rightcolumn.grid(row=1, column=5, sticky='WE') self.search_label.grid(row=2, column=1, sticky='E', padx=4) self.search_entry.grid(row=2, column=2, columnspan=3, sticky='WE', padx=4) self.blank1.grid(row=3) self.orinamelabel.grid(row=4, column=2, sticky='WE') self.impnamelabel.grid(row=4, column=3, columnspan=2, sticky='WE') self.botleftcolumn.grid(row=1, column=0, sticky='WE') self.botcheckcolumn.grid(row=1, column=1, sticky='WE') self.botorinamecolumn.grid(row=1, column=2, sticky='WE') self.botimpnamecolumn1.grid(row=1, column=3, sticky='WE') self.botimpnamecolumn2.grid(row=1, column=4, sticky='WE') self.botrightcolumn.grid(row=1, column=5, sticky='WE') self.searchname() self.sname.trace('w', self.searchname) def searchname(self, event=None, *args): row = 2 for solid in self.solids: try: solid.remove_importedsolidwidgets() except: pass if self.sname.get() == '': for solid in self.solids: if solid.check == 1: solid.importedsolidwidgets( self.frame, row=row, namewidth=int(self.name_width * 1.1424219345 / 8) + 1) row = row + 1 for solid in self.solids: if solid.check == 0: solid.importedsolidwidgets( self.frame, row=row, namewidth=int(self.name_width * 1.1424219345 / 8) + 1) row = row + 1 else: for solid in self.solids: if solid.name.lower()[:len(self.sname.get())].count( self.sname.get().lower()) >= 1: if solid.check == 1: solid.importedsolidwidgets( self.frame, row=row, namewidth=int(self.name_width * 1.1424219345 / 8) + 1) row = row + 1 for solid in self.solids: if solid.name.lower()[:len(self.sname.get())].count( self.sname.get().lower()) >= 1: if solid.check == 0: solid.importedsolidwidgets( self.frame, row=row, namewidth=int(self.name_width * 1.1424219345 / 8) + 1) row = row + 1 else: solid.check = IntVar(value=solid.check) self.blank4.grid(row=row) row = 2 self.blank2.grid(row=row) row = row + 1 self.allbutton.grid(row=row, column=0, columnspan=5, pady=1) row = row + 1 self.unallbutton.grid(row=row, column=0, columnspan=5, pady=1) row = row + 1 self.importbutton.grid(row=row, column=0, columnspan=5, pady=1) row = row + 1 self.cancelbutton.grid(row=row, column=0, columnspan=5, pady=1) row = row + 1 self.blank3.grid(row=row) self.cancelbutton.bind('<Return>', self.cancel) self.focusbutton = self.cancelbutton def updatename(self, event=None): row = 2 for solid in self.solids: try: solid.remove_importedsolidwidgets() except: pass for solid in self.solids: if solid.check == 1: solid.importedsolidwidgets( self.frame, row=row, namewidth=int(self.name_width * 1.1424219345 / 8) + 1) row = row + 1 for solid in self.solids: if solid.check == 0: solid.importedsolidwidgets( self.frame, row=row, namewidth=int(self.name_width * 1.1424219345 / 8) + 1) row = row + 1 self.blank4.grid(row=row) row = 2 self.blank2.grid(row=row) row = row + 1 self.updatebutton.grid(row=row, column=0, columnspan=5, pady=1) row = row + 1 self.allbutton.grid(row=row, column=0, columnspan=5, pady=1) row = row + 1 self.unallbutton.grid(row=row, column=0, columnspan=5, pady=1) row = row + 1 self.importbutton.grid(row=row, column=0, columnspan=5, pady=1) row = row + 1 self.cancelbutton.grid(row=row, column=0, columnspan=5, pady=1) row = row + 1 self.blank3.grid(row=row) self.cancelbutton.bind('<Return>', self.cancel) self.focusbutton = self.cancelbutton def selectall(self, event=None): for solid in self.solids: if solid.name.lower()[:len(self.sname.get())].count( self.sname.get().lower()) >= 1: solid.check.set(1) def unselectall(self, event=None): for solid in self.solids: if solid.name.lower()[:len(self.sname.get())].count( self.sname.get().lower()) >= 1: solid.check.set(0) def OK(self, event=None): for solid in self.solids: solid.get_importedsolid() self.frame.quit() def cancel(self, event=None): self.cancelflag = 1 self.frame.quit()
if sys.version_info < (3, 0): from Tkinter import Tk, Label, Button, LEFT, RIGHT else: from tkinter import Tk, Label, Button, LEFT, RIGHT def exit_btn_callback(evt): """Callback function to handle the button click event. :param Event evt: the instance of class Event from tkinter module. """ print("Inside exit_btn_callback. Event object is: {0}".format(evt)) if __name__ == '__main__': # Create the main window or Tk instance mainwin = Tk() mainwin.geometry("140x40") # Create a label widget and 'pack' it in a row (or column) lbl = Label(mainwin, text="Hello World!", bg='yellow') lbl.pack(side=LEFT) exit_button = Button(mainwin, text='Exit') # Bind the button click event to function exit_btn_callback exit_button.bind("<Button-1>", exit_btn_callback) exit_button.pack(side=RIGHT) mainwin.mainloop()
class ChemicalDeleter: def __init__(self, master, system, chemical): """Constructor method. Defines the parameters to be obtained in this window.""" self.master = master self.fonttype = system.fonttype self.version = system.version self.superfont = get_superfont(self.fonttype) #superscript font self.frame = Frame(master.frame) self.tframe = Frame(master.tframe) self.bframe = Frame(master.bframe) self.top = None #flag for existence of toplevel# self.soluableflag = chemical.soluable self.name = StringVar(value=chemical.name) self.MW = DoubleVar(value=chemical.MW) self.formula = StringVar(value=chemical.formula) self.temp = DoubleVar(value=chemical.temp) self.Dw = DoubleVar(value=chemical.Dw) self.Koc = DoubleVar(value=chemical.Koc) self.Kdoc = DoubleVar(value=chemical.Kdoc) self.Ref = StringVar(value=chemical.Ref) self.Kf = DoubleVar(value=chemical.Kf) self.N = DoubleVar(value=chemical.N) self.chemical = chemical self.cancelflag = 0 def make_widgets(self): self.bgcolor = self.frame.cget('bg') self.instructions = Label( self.frame, text= ' Are you sure to delete the following chemical? ' ) self.namelabel = Label(self.frame, text='Chemical name') self.MWlabel = Label(self.frame, text='Molecular\n weight') self.templabel = Label(self.frame, text='Temperature') self.Dwlabel = Label(self.frame, text='Molecular diffusivity\n in water') self.Koclabel = Label(self.frame, text='Organic carbon\n partition coefficient') self.Kdoclabel = Label( self.frame, text='Dissolved organic carbon\n partition coefficient') self.Reflabel = Label(self.frame, text='Reference') self.tempunits = Label(self.frame, text=unichr(176) + 'C') self.Dwunits = Label(self.frame, text=u'cm\u00B2/s') self.Kocunits = Label(self.frame, text='log(L/kg)') self.Kdocunits = Label(self.frame, text='log(L/kg)') self.namewidget = Label(self.frame, width=20, justify='center', textvariable=self.name) if self.soluableflag == 1: self.tempwidget = Label(self.frame, width=10, justify='center', textvariable=self.temp) self.MWwidget = Label(self.frame, width=16, justify='center', textvariable=self.MW) self.Dwwidget = Label(self.frame, width=16, justify='center', textvariable=self.Dw) self.Kocwidget = Label(self.frame, width=16, justify='center', textvariable=self.Koc) self.Kdocwidget = Label(self.frame, width=16, justify='center', textvariable=self.Kdoc) self.Refwidget = Label(self.frame, width=16, justify='center', textvariable=self.Ref) else: self.tempwidget = Label(self.frame, width=10, justify='center', text=' ') self.Dwwidget = Label(self.frame, width=16, justify='center', text='Not applicable') self.Kocwidget = Label(self.frame, width=16, justify='center', text='Not applicable') self.Kdocwidget = Label(self.frame, width=16, justify='center', text='Not applicable') self.insoluablestate = Label(self.frame, width=16, justify='center', text='Not applicable') #show the widgets on the grid self.blankcolumn = Label(self.frame, text=' ', width=2) self.namecolumn = Label(self.frame, text=' ', width=20) self.MWcolumn = Label(self.frame, text=' ', width=18) self.tempcolumn = Label(self.frame, text=' ', width=10) self.Dwcolumn = Label(self.frame, text=' ', width=18) self.Koccolumn = Label(self.frame, text=' ', width=18) self.Kdoccolumn = Label(self.frame, text=' ', width=18) self.Refcolumn = Label(self.frame, text=' ', width=18) self.deletebutton = Button(self.frame, text='Delete', width=20, command=self.Delete) self.cancelbutton = Button(self.frame, text='Cancel', width=20, command=self.Cancel) self.blank1 = Label(self.frame, text=' ') self.blank2 = Label(self.frame, text=' ') self.instructions.grid(row=0, column=0, columnspan=6, padx=8, sticky='W') self.blankcolumn.grid(row=1, column=0, sticky='WE', padx=1, pady=1) self.namecolumn.grid(row=1, column=1, sticky='WE', padx=1, pady=1) self.MWcolumn.grid(row=1, column=2, sticky='WE', padx=1, pady=1) self.tempcolumn.grid(row=1, column=3, sticky='WE', padx=1, pady=1) self.Dwcolumn.grid(row=1, column=4, sticky='WE', padx=1, pady=1) self.Koccolumn.grid(row=1, column=5, sticky='WE', padx=1, pady=1) self.Kdoccolumn.grid(row=1, column=6, sticky='WE', padx=1, pady=1) self.Refcolumn.grid(row=1, column=7, sticky='WE', padx=1, pady=1) self.namelabel.grid(row=2, column=1, sticky='WE', padx=4, pady=1) self.MWlabel.grid(row=2, column=2, sticky='WE', padx=1, pady=1) self.templabel.grid(row=2, column=3, sticky='WE', padx=1, pady=1) self.Dwlabel.grid(row=2, column=4, sticky='WE', padx=1, pady=1) self.Koclabel.grid(row=2, column=5, sticky='WE', padx=1, pady=1) self.Kdoclabel.grid(row=2, column=6, sticky='WE', padx=1, pady=1) self.Reflabel.grid(row=2, column=7, sticky='WE', padx=1, pady=1) self.tempunits.grid(row=3, column=3, sticky='WE', padx=1, pady=1) self.Dwunits.grid(row=3, column=4, sticky='WE', padx=1, pady=1) self.Kocunits.grid(row=3, column=5, sticky='WE', padx=1, pady=1) self.Kdocunits.grid(row=3, column=6, sticky='WE', padx=1, pady=1) self.namewidget.grid(row=4, column=1, padx=2, pady=1, sticky='WE') self.MWwidget.grid(row=4, column=2, padx=2, pady=1, sticky='WE') self.tempwidget.grid(row=4, column=3, padx=2, pady=1, sticky='WE') self.Dwwidget.grid(row=4, column=4, padx=2, pady=1) self.Kocwidget.grid(row=4, column=5, padx=2, pady=1) self.Kdocwidget.grid(row=4, column=6, padx=2, pady=1) self.Refwidget.grid(row=4, column=7, padx=2, pady=1) self.blank1.grid(row=5) self.deletebutton.grid(row=6, columnspan=11) self.cancelbutton.grid(row=7, columnspan=11) self.blank2.grid(row=8) self.deletebutton.bind('<Return>', self.Delete) self.focusbutton = self.deletebutton def Delete(self, event=None): """Finish and move on. Checks that the number chemicals are less than the total number of chemicals in database.""" if self.master.window.top is not None: self.master.open_toplevel() else: self.master.tk.quit() def Cancel(self): try: self.name.set(self.chemical.name) self.temp.set(self.chemical.temp) self.MW.set(self.chemical.MW) self.formula.set(self.chemical.formula) self.Dw.set(self.chemical.Dw) self.Koc.set(self.chemical.Koc) self.Kdoc.set(self.chemical.Kdoc) self.Ref.set(self.chemical.Ref) self.Kf.set(self.chemical.Kf) self.N.set(self.chemical.N) except: self.cancelflag = 1 if self.master.window.top is not None: self.master.open_toplevel() else: self.master.tk.quit()
class SolidDatabaseEditor: """Gets the contaminant properties.""" def __init__(self, master, system, solid, solid_database, editflag): """Constructor method. Defines the parameters to be obtained in this window.""" self.master = master self.fonttype = system.fonttype self.version = system.version self.superfont = get_superfont(self.fonttype) #superscript font self.tframe = Frame(master.tframe) self.frame = Frame(master.frame) self.bframe = Frame(master.bframe) self.top = None #flag for existence of toplevel# self.solid = solid self.solid_database = solid_database self.torts = ['Millington & Quirk', 'Boudreau', 'None'] self.sorps = [ 'Linear--Kd specified', 'Linear--Kocfoc', 'Freundlich', 'Langmuir' ] self.name = StringVar( value='Solid ' + str(solid_database[-1].number)) #stores the chemical name self.e = DoubleVar(value=0.5) #stores the porosity self.rho = DoubleVar(value=1.0) #stores the bulk density self.foc = DoubleVar(value=0.01) #stores the organic carbon fraction self.tort = StringVar( value=self.torts[0]) #stores the default tortuosity correction self.sorp = StringVar( value=self.sorps[0]) #stores the default sorption correction self.Ref = StringVar(value='') #stores the density self.editflag = editflag self.cancelflag = 0 if editflag == 1: #Detemine whether the chemical is added or edited self.name.set(solid.name) self.e.set(solid.e) self.rho.set(solid.rho) self.foc.set(solid.foc) self.tort.set(solid.tort) self.sorp.set(solid.sorp) self.Ref.set(solid.Ref) def make_widgets(self): """Make the widgets for the window.""" self.bgcolor = self.frame.cget('bg') self.instructions = Label( self.frame, text= ' Please provide the following properties for the solid/mixture: ' ) self.blankcolumn = Label(self.frame, text=' ', width=1) self.namecolumn = Label(self.frame, text=' ', width=18) self.ecolumn = Label(self.frame, text=' ', width=10) self.rhocolumn = Label(self.frame, text=' ', width=10) self.foccolumn = Label(self.frame, text=' ', width=10) self.tortcolumn = Label(self.frame, text=' ', width=18) self.sorpcolumn = Label(self.frame, text=' ', width=20) self.refcolumn = Label(self.frame, text=' ', width=18) self.endcolumn = Label(self.frame, text=' ', width=2) self.namelabel = Label(self.frame, text='Material') self.elabel = Label(self.frame, text='Porosity') self.rholabel = Label(self.frame, text='Bulk density') self.foclabel = Label(self.frame, text='Organic carbon fraction') self.tortlabel = Label(self.frame, text='Tortruosity correction') self.sorplabel = Label(self.frame, text='Sorption isotherms') self.reflabel = Label(self.frame, text='Reference') self.rhounitlabel = Label(self.frame, text=u'g/cm\u00B3') self.namewidget = Entry(self.frame, width=16, justify='center', textvariable=self.name) self.ewidget = Entry(self.frame, width=8, justify='center', textvariable=self.e) self.rhowidget = Entry(self.frame, width=8, justify='center', textvariable=self.rho) self.focwidget = Entry(self.frame, width=8, justify='center', textvariable=self.foc) self.tortwidget = OptionMenu(self.frame, self.tort, *self.torts) self.sorpwidget = OptionMenu(self.frame, self.sorp, *self.sorps) self.refwidget = Entry(self.frame, width=15, justify='center', textvariable=self.Ref) self.okbutton = Button(self.frame, text='OK', width=20, command=self.OK) self.cancelbutton = Button(self.frame, text='Cancel', width=20, command=self.Cancel) self.blank1 = Label(self.frame, text=' ') self.blank2 = Label(self.frame, text=' ') #show the widgets on the grid self.instructions.grid(row=0, column=0, columnspan=7, padx=8, sticky='W') self.blankcolumn.grid(row=1, column=0, sticky='WE', padx=1, pady=1) self.namecolumn.grid(row=1, column=1, sticky='WE', padx=1, pady=1) self.ecolumn.grid(row=1, column=2, sticky='WE', padx=1, pady=1) self.rhocolumn.grid(row=1, column=3, sticky='WE', padx=1, pady=1) self.foccolumn.grid(row=1, column=4, sticky='WE', padx=1, pady=1) self.tortcolumn.grid(row=1, column=5, sticky='WE', padx=1, pady=1) self.sorpcolumn.grid(row=1, column=6, sticky='WE', padx=1, pady=1) self.refcolumn.grid(row=1, column=7, sticky='WE', padx=1, pady=1) self.endcolumn.grid(row=1, column=8, sticky='WE', padx=1, pady=1) self.namelabel.grid(row=2, column=1, sticky='WE', padx=1, pady=1) self.elabel.grid(row=2, column=2, sticky='WE', padx=1, pady=1) self.rholabel.grid(row=2, column=3, sticky='WE', padx=1, pady=1) self.foclabel.grid(row=2, column=4, sticky='WE', padx=1, pady=1) self.tortlabel.grid(row=2, column=5, sticky='WE', padx=1, pady=1) self.sorplabel.grid(row=2, column=6, sticky='WE', padx=1, pady=1) self.reflabel.grid(row=2, column=7, sticky='WE', padx=1, pady=1) self.rhounitlabel.grid(row=3, column=3, sticky='WE', padx=1, pady=1) self.namewidget.grid(row=4, column=1, padx=1, pady=1) self.ewidget.grid(row=4, column=2, padx=1, pady=1) self.rhowidget.grid(row=4, column=3, padx=1, pady=1) self.focwidget.grid(row=4, column=4, padx=1, pady=1) self.tortwidget.grid(row=4, column=5, padx=1, pady=1, sticky='WE') self.sorpwidget.grid(row=4, column=6, padx=1, pady=1, sticky='WE') self.refwidget.grid(row=4, column=7, padx=1, pady=1) self.blank1.grid(row=5) self.okbutton.grid(row=6, columnspan=11) self.cancelbutton.grid(row=7, columnspan=11) self.blank2.grid(row=8) self.okbutton.bind('<Return>', self.OK) self.focusbutton = self.okbutton def OK(self, event=None): """Finish and move on. Checks that the number chemicals are less than the total number of chemicals in database.""" if self.editflag == 0: check = [(solid.name == self.name.get()) for solid in self.solid_database[0:-1]] if self.editflag == 1: check = [(solid.name == self.name.get() and self.solid.name != self.name.get()) for solid in self.solid_database[0:-1]] if self.master.window.top is not None: self.master.open_toplevel() elif self.e.get() > 1 or self.e.get() < 0: tkmb.showinfo( self.version, 'The porosity of a solid can not be larger than 1 or smaller than 0' ) self.e.set(0.5) elif self.rho.get() < 0: tkmb.showinfo(self.version, 'The bulk density of a solid can not be negative') self.e.set(1.0) elif self.foc.get() > 1 or self.foc.get() < 0: tkmb.showinfo( self.version, 'The organic carbon fraction of a solid can not be larger than 1 or smaller than 0' ) self.e.set(1.0) elif sum(check) >= 1 or self.name.get() == '': self.solids_error() else: self.master.tk.quit() def solids_error(self): tkmb.showerror( title=self.version, message= 'This solid material has already been added to the database!') self.focusbutton = self.okbutton self.master.tk.lift() def Cancel(self): try: self.name.set(self.solid.name) self.e.set(self.solid.e) self.rho.set(self.solid.rho) self.foc.set(self.solid.foc) self.tort.set(self.solid.tort) self.sorp.set(self.solid.sorp) self.Ref.set(self.solid.Ref) except: self.cancelflag = 1 if self.master.window.top is not None: self.master.open_toplevel() else: self.master.tk.quit()
lab1 = Label(fra1, text="Колличество каналов в пакете Социальный") lab2 = Label(fra1, text="Колличество каналов в пакете Базовый") lab3 = Label(fra1, text="Колличество каналов в пакете Полный") ent1 = Entry(fra1, width=4) ent2 = Entry(fra1, width=4) ent3 = Entry(fra1, width=4) but1 = Button(fra1, text = "Преобразовать") but2 = Button(fra3, text = "Отправить исходник") but3 = Button(fra3, text = "Отправить результат") tex = Text(fra2, width=60, height=12, font="12", wrap=WORD) lab1.grid(row = 0, column = 0) lab2.grid(row = 1, column = 0) lab3.grid(row = 2, column = 0) ent1.grid(row = 0, column = 1, padx=20) ent2.grid(row = 1, column = 1, padx=20) ent3.grid(row = 2, column = 1, padx=20) but1.grid(row = 3, column = 1, padx=20) tex.grid(row = 0, column = 0) but2.grid(row = 0, column = 1) but3.grid(row = 1, column = 1) fra1.pack() fra2.pack() fra3.pack() but1.bind("<Button-1>", transformation) but2.bind("<Button-1>", mail_source) but3.bind("<Button-1>", mail_result) root.mainloop()
class ChemicalEditor: """Gets the contaminant properties.""" def __init__(self, master, system, chemical, chemicals, database, editflag): """Constructor method. Defines the parameters to be obtained in this window.""" self.master = master self.fonttype = system.fonttype self.version = system.version self.superfont = get_superfont(self.fonttype) #superscript font self.frame = Frame(master.frame) self.tframe = Frame(master.tframe) self.bframe = Frame(master.bframe) self.system = system self.database = database self.top = None #flag for existence of toplevel# self.tkfont = tkFont.Font(font=system.fonttype) self.soluableflag = chemical.soluable self.editflag = editflag self.cancelflag = 0 self.chemicals = chemicals self.diffunit = system.diffunit self.diffunits = system.diffunits if self.soluableflag == 1: self.database = database self.chemical = chemical self.name = StringVar(value='') self.formula = StringVar(value='') self.MW = DoubleVar(value=0) self.temp = DoubleVar(value=0) self.Dw = DoubleVar(value=0) self.Ref = StringVar(value='') self.Koc = DoubleVar(value=0) self.Kdoc = DoubleVar(value=0) self.Kf = DoubleVar(value=0) self.N = DoubleVar(value=0) if editflag == 1: #Detemine whether the chemical is added or edited self.name.set(self.chemical.name) self.formula.set(self.chemical.formula) self.MW.set(self.chemical.MW) self.temp.set(self.chemical.temp) self.Dw.set(self.chemical.Dw) self.Koc.set(self.chemical.Koc) self.Kdoc.set(self.chemical.Kdoc) self.Ref.set(self.chemical.Ref) self.Kf.set(self.chemical.Kf) self.N.set(self.chemical.N) else: self.name = StringVar(value=' ') self.formula = StringVar(value=' ') self.MW = DoubleVar(value=100) self.temp = DoubleVar(value=0) self.Dw = DoubleVar(value=0) self.Koc = DoubleVar(value=0) self.Kdoc = DoubleVar(value=0) self.Kf = DoubleVar(value=0) self.N = DoubleVar(value=0) if editflag == 1: #Detemine whether the chemical is added or edited self.name.set(chemical.name) def make_widgets(self): """Make the widgets for the window.""" self.bgcolor = self.frame.cget('bg') self.instructions = Label( self.tframe, text= ' Please provide the following chemical properties: ' ) self.blankcolumn = Label(self.frame, text=' ', width=2) self.namecolumn = Label(self.frame, text=' ', width=20) self.MWcolumn = Label(self.frame, text=' ', width=12) self.tempcolumn = Label(self.frame, text=' ', width=10) self.Dwcolumn = Label(self.frame, text=' ', width=18) self.Koccolumn = Label(self.frame, text=' ', width=18) self.Kdoccolumn = Label(self.frame, text=' ', width=18) self.Refcolumn = Label(self.frame, text=' ', width=20) self.Rightcolumn = Label(self.frame, text=' ', width=2) self.namelabel = Label(self.frame, text='Chemical name') self.MWlabel = Label(self.frame, text='Molecular\n weight') self.templabel = Label(self.frame, text='Temperature') self.Dwlabel = Label(self.frame, text='Molecular diffusivity\n in water') self.Koclabel = Label(self.frame, text='Organic carbon\n partition coefficient') self.Kdoclabel = Label( self.frame, text='Dissolved organic carbon\n partition coefficient') self.Reflabel = Label(self.frame, text='Reference') self.tempunits = Label(self.frame, text=unichr(176) + 'C') self.Dwunits = Label(self.frame, text=self.diffunit) self.Kocunits = Label(self.frame, text='log(L/kg)') self.Kdocunits = Label(self.frame, text='log(L/kg)') self.importbutton = Button(self.frame, text='From Database', width=20, command=self.importchemical) self.okbutton = Button(self.frame, text='OK', width=20, command=self.OK) self.cancelbutton = Button(self.frame, text='Cancel', width=20, command=self.Cancel) self.blank1 = Label(self.frame, text=' ') self.blank2 = Label(self.frame, text=' ') #show the widgets on the grid self.instructions.grid(row=0, column=0, columnspan=6, padx=8, sticky='W') self.blankcolumn.grid(row=1, column=0, sticky='WE', padx=1, pady=1) self.namecolumn.grid(row=1, column=1, sticky='WE', padx=1, pady=1) self.MWcolumn.grid(row=1, column=2, sticky='WE', padx=1, pady=1) self.tempcolumn.grid(row=1, column=3, sticky='WE', padx=1, pady=1) self.Dwcolumn.grid(row=1, column=4, sticky='WE', padx=1, pady=1) self.Koccolumn.grid(row=1, column=5, sticky='WE', padx=1, pady=1) self.Kdoccolumn.grid(row=1, column=6, sticky='WE', padx=1, pady=1) self.Refcolumn.grid(row=1, column=7, sticky='WE', padx=1, pady=1) self.Rightcolumn.grid(row=1, column=8, sticky='WE', padx=1, pady=1) self.namelabel.grid(row=2, column=1, sticky='WE', padx=1, pady=1) self.MWlabel.grid(row=2, column=2, sticky='WE', padx=1, pady=1) self.templabel.grid(row=2, column=3, sticky='WE', padx=1, pady=1) self.Dwlabel.grid(row=2, column=4, sticky='WE', padx=1, pady=1) self.Koclabel.grid(row=2, column=5, sticky='WE', padx=1, pady=1) self.Kdoclabel.grid(row=2, column=6, sticky='WE', padx=1, pady=1) self.Reflabel.grid(row=2, column=7, sticky='WE', padx=1, pady=1) self.tempunits.grid(row=3, column=3, sticky='WE', padx=1, pady=1) self.Dwunits.grid(row=3, column=4, sticky='WE', padx=1, pady=1) self.Kocunits.grid(row=3, column=5, sticky='WE', padx=1, pady=1) self.Kdocunits.grid(row=3, column=6, sticky='WE', padx=1, pady=1) if self.soluableflag == 1: if self.editflag == 0: self.namewidget = Entry(self.frame, width=18, justify='center', textvariable=self.name) self.tempwidget = Entry(self.frame, width=10, justify='center', textvariable=self.temp) else: self.namewidget = Label(self.frame, width=18, justify='center', textvariable=self.name) self.tempwidget = Label(self.frame, width=10, justify='center', textvariable=self.temp) self.Dwwidget = Entry(self.frame, width=16, justify='center', textvariable=self.Dw) self.MWwidget = Entry(self.frame, width=10, justify='center', textvariable=self.MW) self.Kocwidget = Entry(self.frame, width=16, justify='center', textvariable=self.Koc) self.Kdocwidget = Entry(self.frame, width=16, justify='center', textvariable=self.Kdoc) self.Refwidget = Entry(self.frame, width=18, justify='center', textvariable=self.Ref) self.namewidget.grid(row=4, column=1, padx=2, pady=1) self.MWwidget.grid(row=4, column=2, padx=2, pady=1) self.tempwidget.grid(row=4, column=3, padx=2, pady=1) self.Dwwidget.grid(row=4, column=4, padx=2, pady=1) self.Kocwidget.grid(row=4, column=5, padx=2, pady=1) self.Kdocwidget.grid(row=4, column=6, padx=2, pady=1) self.Refwidget.grid(row=4, column=7, padx=2, pady=1) else: self.namewidget = Entry(self.frame, width=18, justify='center', textvariable=self.name) self.Dwwidget = Label(self.frame, width=16, justify='center', text='Not applicable') self.Kocwidget = Label(self.frame, width=16, justify='center', text='Not applicable') self.Kdocwidget = Label(self.frame, width=16, justify='center', text='Not applicable') self.namewidget.grid(row=4, column=1, padx=2, pady=1) self.Dwwidget.grid(row=4, column=3, padx=2, pady=1) self.Kocwidget.grid(row=4, column=4, padx=2, pady=1) self.Kdocwidget.grid(row=4, column=5, padx=2, pady=1) self.blank1.grid(row=5) if self.editflag == 0: self.importbutton.grid(row=6, columnspan=11) self.okbutton.grid(row=7, columnspan=11) self.cancelbutton.grid(row=8, columnspan=11) self.blank2.grid(row=9) self.okbutton.bind('<Return>', self.OK) self.focusbutton = self.okbutton if int((self.tkfont.measure(self.Ref.get()) + 10) * 1.1424219345 / 8) + 1 > 18: self.Refwidget.config( width=int((self.tkfont.measure(self.Ref.get()) + 10) * 1.1424219345 / 8) + 3) if int((self.tkfont.measure(self.name.get()) + 10) * 1.1424219345 / 8) + 1 > 18: self.namewidget.config( width=int((self.tkfont.measure(self.name.get()) + 10) * 1.1424219345 / 8) + 3) self.master.geometry() self.master.center() def importchemical(self): if self.top is None: self.top = CapSimWindow(master=self.master, buttons=2) self.top.make_window( ChemicalImporter(self.top, self.system, self.database)) self.top.tk.mainloop() if self.top.window.cancelflag == 0: self.updatechemical(self.top.window) if self.top is not None: self.top.destroy() self.top = None elif self.top is not None: tkmb.showerror( title=self.system.version, message= 'Please close the existing parameter input window first.') self.top.tk.focus() def updatechemical(self, window): self.name.set(window.name.get()) self.formula.set(window.formula.get()) self.MW.set(window.MW.get()) self.temp.set(window.temp.get()) self.Koc.set(window.Koc.get()) self.Kdoc.set(window.Kdoc.get()) self.Ref.set(window.Ref.get()) self.Kf.set(window.Kf.get()) self.N.set(window.N.get()) if self.diffunit == self.diffunits[0]: self.Dw.set(window.Dw.get()) elif self.diffunit == self.diffunits[1]: Dw = window.Dw.get() * 86400 * 365 if Dw > 1: self.Dw.set(round(Dw, 2)) else: i = 2 while Dw / 100 < 0.1**i: i = i + 1 self.Dw.set(round(Dw, i)) self.frame.update() if int((self.tkfont.measure(self.Ref.get()) + 10) * 1.1424219345 / 8) + 1 > 20: self.Refwidget.config( width=int((self.tkfont.measure(self.Ref.get()) + 10) * 1.1424219345 / 8) + 3) if int((self.tkfont.measure(self.name.get()) + 10) * 1.1424219345 / 8) + 1 > 20: self.namewidget.config( width=int((self.tkfont.measure(self.name.get()) + 10) * 1.1424219345 / 8) + 3) self.master.geometry() self.master.center() def OK(self, event=None): """Finish and move on. Checks that the number chemicals are less than the total number of chemicals in database.""" if self.editflag == 0: check = [(chemical.name == self.name.get()) for chemical in self.chemicals[0:-1]] else: check = [0] if self.master.window.top is not None: self.master.open_toplevel() elif sum(check) >= 1: self.chemicals_error() elif self.name.get() == '' or self.name.get().count(' ') == len( self.name.get()): self.name_error() elif self.Dw.get() == 0: self.Dw_error() else: self.master.tk.quit() def chemicals_error(self): tkmb.showerror(title=self.version, message='This chemical has already been selected!') self.focusbutton = self.okbutton self.master.tk.lift() def name_error(self): tkmb.showerror(title=self.version, message='Please input the name for the chemical!') self.focusbutton = self.okbutton self.master.tk.lift() def Dw_error(self): tkmb.showerror( title=self.version, message= 'The diffusivity of the chemical can not be zero, please correct!') self.focusbutton = self.okbutton self.master.tk.lift() def Cancel(self): try: self.name.set(self.chemical.name) self.MW.set(self.chemical.MW.get()) self.formula.set(self.chemical.formula.get()) self.temp.set(self.chemical.temp.get()) self.Dw.set(self.chemical.Dw.get()) self.Koc.set(self.chemical.Koc.get()) self.Kdoc.set(self.chemical.Kdoc.get()) self.Ref.set(self.chemical.Ref.get()) self.Kf.set(self.chemical.Kf.get()) self.N.set(self.chemical.N.get()) except: self.cancelflag = 1 if self.master.window.top is not None: self.master.open_toplevel() else: self.master.tk.quit()
class ListPage(BasePage): def __init__(self, parent, controller): BasePage.__init__(self, parent, controller) self.target_keep_profile_var = IntVar() self.mutex = Lock() def prepare(self): self.deviceList.config(state='normal') self.versionList.config(state='disabled') self.engList.config(state='disabled') self.packageList.config(state='disabled') self.ok.config(state='disabled') self.setData(self.controller.data) self.setDeviceList(self.data.keys()) self.controller.setDefault(self, self.controller.loadOptions()) self.deviceList.focus_force() def printErr(self, message): self.errLog.config(text=message) def setData(self, data): self.data = data def setupView(self, title="Select your flash", data=None): if (data): self.setData(data) self.errLog = Label(self, text="") self.errLog.grid(row=4, column=1, columnspan=3, sticky="NWSE") self.desc = Label(self, text=title, font=TITLE_FONT) self.desc.grid(row=0, column=0, columnspan=2) self.ok = Button(self, text='Next', command=lambda: self.confirm()) self.ok.grid(row=4, column=3, sticky="E") self.ok.config(state="disabled") # bind self.target_keep_profile_var (IntVar) to keepProfileCheckbutton, 1 is True, 0 is Flase self.keepProfileCheckbutton = Checkbutton( self, text="Keep User Profile (BETA)", variable=self.target_keep_profile_var) self.keepProfileCheckbutton.grid(row=5, column=0, columnspan=4, sticky="W") self.deviceLabel = Label(self, text="Device", font=TITLE_FONT) self.deviceLabel.grid(row=1, column=0) self.deviceList = Listbox(self, exportselection=0) self.deviceList.grid(row=2, column=0) self.deviceList.bind('<<ListboxSelect>>', self.deviceOnSelect) self.deviceList.config(state="disabled") self.versionLabel = Label(self, text="Branch", font=TITLE_FONT) self.versionLabel.grid(row=1, column=1) self.versionList = Listbox(self, exportselection=0) self.versionList.grid(row=2, column=1) self.versionList.bind('<<ListboxSelect>>', self.versionOnSelect) self.versionList.config(state="disabled") self.engLabel = Label(self, text="Build Type", font=TITLE_FONT) self.engLabel.grid(row=1, column=2) self.engList = Listbox(self, exportselection=0) self.engList.grid(row=2, column=2) self.engList.bind('<<ListboxSelect>>', self.engOnSelect) self.engList.config(state="disabled") self.packageLabel = Label(self, text="Gecko/Gaia/Full", font=TITLE_FONT) self.packageLabel.grid(row=1, column=3) self.packageList = Listbox(self, exportselection=0) self.packageList.grid(row=2, column=3) self.packageList.bind('<<ListboxSelect>>', self.packageOnSelect) self.packageList.config(state="disabled") self.bidVar = StringVar() Label(self, text="Build ID").grid(row=3, column=0, sticky='E') self.bidInput = Entry(self, textvariable=self.bidVar, width="30") self.bidInput.grid(row=3, column=1, columnspan=2, sticky="W") self.bidVar.set('latest') # binding unfocus for build id field self.bidInput.bind('<FocusOut>', self.updateBuildId) # binding the Return Key to each componments self.deviceList.bind('<Return>', self.pressReturnKey) self.versionList.bind('<Return>', self.pressReturnKey) self.engList.bind('<Return>', self.pressReturnKey) self.packageList.bind('<Return>', self.pressReturnKey) self.bidInput.bind('<Return>', self.pressReturnKey) self.ok.bind('<Return>', self.pressReturnKey) def selection_all_checked(self): result = False if len(self.deviceList.curselection()) == 0: self.logger.log('Please select device.', status_callback=self.printErr) self.ok.config(state="disabled") self.deviceList.focus_set() elif len(self.versionList.curselection()) == 0: self.logger.log('Please select branch.', status_callback=self.printErr) self.ok.config(state="disabled") self.versionList.focus_set() elif len(self.engList.curselection()) == 0: self.logger.log('Please select user or engineer build.', status_callback=self.printErr) self.ok.config(state="disabled") self.engList.focus_set() elif len(self.packageList.curselection()) == 0: self.logger.log('Please select package to flash.', status_callback=self.printErr) self.ok.config(state="disabled") self.packageList.focus_set() elif len(self.bidVar.get()) != 14 and self.bidVar.get() != 'latest': self.logger.log( 'Please enter build ID to flash or use "latest" to get the newest', status_callback=self.printErr) self.logger.log(self.bidVar.get() + ' is invalid: ' + str(len(self.bidVar.get()))) self.bidVar.set('latest') else: result = True return result def updateBuildId(self, event=None): # if the value is '' or 'latest', the set the build_id option as ''. buildId = self.bidVar.get() if buildId == 'latest': buildId = '' elif len(buildId) != 14: self.printErr("Invalid build ID: " + buildId + ", reset to latest") buildId = '' self.bidVar.set('latest') else: if len(self.engList.curselection()) != 0: self.refreshPackageList() def pressReturnKey(self, event=None): if self.selection_all_checked(): self.ok.config(state="disabled") self.confirm() def deviceOnSelect(self, evt): self.setVersionList() def versionOnSelect(self, evt): self.setEngList() def engOnSelect(self, evt): self.refreshPackageList() # hard coded right now def packageOnSelect(self, evt): self.ok.config(state="normal") def confirm(self): self.mutex.acquire() try: if self.selection_all_checked(): self.ok.config(state="disabled") params = [] package = self.packageList.get( self.packageList.curselection()[0]) self.logger.log('Start to flash [' + package + '].', status_callback=self.printErr) if (PathParser._IMAGES in package): params.append(PathParser._IMAGES) else: if (PathParser._GAIA in package): params.append(PathParser._GAIA) if (PathParser._GECKO in package): params.append(PathParser._GECKO) keep_profile = (self.target_keep_profile_var.get() == 1) archives = self.controller.do_download(params) self.controller.do_flash(params, archives, keep_profile=keep_profile) self.packageList.select_clear(0, END) self.controller.transition(self) finally: self.mutex.release() def setDeviceList(self, device=[]): self.deviceList.delete(0, END) for li in device: self.deviceList.insert(END, li) def setVersionList(self, version=[]): if len(version) == 0: version = self.data[self.deviceList.get( self.deviceList.curselection())] self.versionList.config(state="normal") self.engList.config(state="disabled") self.packageList.config(state="disabled") self.ok.config(state="disabled") self.versionList.delete(0, END) for li in version: self.versionList.insert(END, li) def setEngList(self, eng=[]): if len(eng) == 0: device = self.deviceList.get(self.deviceList.curselection()) version = self.versionList.get(self.versionList.curselection()) eng = self.data[device][version] self.engList.config(state="normal") self.packageList.config(state="disabled") self.ok.config(state="disabled") self.engList.delete(0, END) for li in eng: self.engList.insert(END, li) def refreshPackageList(self): self.mutex.acquire() try: self.packageList.config(state="normal") self.ok.config(state="normal") self.packageList.delete(0, END) device = self.deviceList.get(self.deviceList.curselection()) version = self.versionList.get(self.versionList.curselection()) eng = self.engList.get(self.engList.curselection()) buildId = '' if (len(self.bidVar.get()) == 0 or self.bidVar.get() == 'latest') else self.bidVar.get() package = self.controller.getPackages( self.data[device][version][eng]['src'], build_id=buildId) if len(package) == 0: self.logger.log('Invalid build ID: ' + buildId + ', reset to latest', status_callback=self.printErr) buildId = '' self.bidVar.set('latest') package = self.controller.getPackages( self.data[device][version][eng]['src'], build_id=buildId) for li in package: self.packageList.insert(END, li) finally: self.mutex.release()
def keyAlgorithm(keyArr): ## creates the keys based upon isQwerty (to make a ## qwerty keyboard or atomic keyboard). timeToReset ## exists to control when to change rows, and keyArr ## houses our strings of keys to grab from global isQwerty global timeToReset flag = True # We use this boolean value to know for Atomic Keyboards if our row has ended counter = 0 # We use this integer value to keep track of how many keys we have entered row = 0 # We use this integer value to allow for easy input of row number column = 0 # We use this integer value to allow for easy input of column number if isQwerty: # If we have a Qwerty Keyboard... for i in range(len(keyArr)): if keyArr[i] == '/': # We have our final row next! button = Button(master = root, text = keyArr[i], # grabs key from keyArr font = ('Times', 10), padx = 10, pady = 5, relief = RAISED) button.grid(row = row, column = column) # bind it to the coordinates row and column button.bind('<Button>', func=lambda event, x = keyArr[i]:click(event,x), add="+") button.bind('<B1-Motion>', func = lambda event, x = keyArr[i]:spit(event, x), add="+") counter = 0 # reset our counter row += 1 # increase the row column = 0 # reset our columns else: # we dont have our last row here! button = Button(master = root, text = keyArr[i], # grabs key from keyArr font = ('Times', 10), padx = 10, pady = 5, relief = RAISED) button.grid(row = row, column = column) button.bind('<Button>', func=lambda event, x = keyArr[i]:click(event,x), add="+") button.bind('<B1-Motion>', func = lambda event, x = keyArr[i]:spit(event, x), add="+") if counter == timeToReset: # are we at the end of our row? counter = 0 row += 1 column = 0 else: counter += 1 column += 1 else: # We have an Atomic Keyboard for i in range(len(keyArr)): if flag: # We have a large row! button = Button(master = root, text = keyArr[i], # grabs key from keyArr font = ('Times', 10), padx = 10, pady = 5, relief = RAISED) button.grid(row = row, column = column) # bind it to the coordinates row and column button.bind('<Button>', func=lambda event, x = keyArr[i]:click(event,x), add="+") button.bind('<B1-Motion>', func = lambda event, x = keyArr[i]:spit(event, x), add="+") if counter == timeToReset: # are we at the end of our row? counter = 0 # reset our counter flag = False # reset our flag row += 1 # increase the row column = 0 # reset our columns timeToReset = 7 # We have to change our timeToReset since Atomic Keyboards have an alternating row structure else: counter += 1 # increase both our counter and column values, but not row! column += 1 else: # we dont have a large row here! button = Button(master = root, text = keyArr[i], # grabs key from keyArr font = ('Times', 10), padx = 10, pady = 5, relief = RAISED) button.grid(row = row, column = column) button.bind('<Button>', func=lambda event, x = keyArr[i]:click(event,x), add="+") button.bind('<B1-Motion>', func = lambda event, x = keyArr[i]:spit(event, x), add="+") if counter == timeToReset: # are we at the end of our row? counter = 0 flag = True row += 1 column = 0 timeToReset = 8 # We have to change our timeToReset since Atomic Keyboards have an alternating row structure else: counter += 1 column += 1 return
Btn5 = Button(top, width=5, height=2, text='Home') # ============================================================================= # Buttons layout # ============================================================================= Btn0.grid(row=0, column=1) Btn1.grid(row=2, column=1) Btn2.grid(row=1, column=0) Btn3.grid(row=1, column=2) Btn4.grid(row=3, column=2) Btn5.grid(row=1, column=1) # ============================================================================= # Bind the buttons with the corresponding callback function. # ============================================================================= Btn0.bind('<ButtonPress-1>', forward_fun ) # When button0 is pressed down, call the function forward_fun(). Btn1.bind('<ButtonPress-1>', backward_fun) Btn2.bind('<ButtonPress-1>', left_fun) Btn3.bind('<ButtonPress-1>', right_fun) Btn0.bind('<ButtonRelease-1>', stop_fun) # When button0 is released, call the function stop_fun(). Btn1.bind('<ButtonRelease-1>', stop_fun) Btn2.bind('<ButtonRelease-1>', stop_fun) Btn3.bind('<ButtonRelease-1>', stop_fun) Btn4.bind('<ButtonRelease-1>', quit_fun) Btn5.bind('<ButtonRelease-1>', home_fun) # ============================================================================= # Create buttons # ============================================================================= Btn07 = Button(top, width=5, text='X+', bg='red')
class HDInspector(Frame): def __init__(self, parent, cmdr, is_beta, client, gridrow): "Initialise the ``Patrol``." Frame.__init__(self, parent) self.client = client self.commander = cmdr self.is_beta = is_beta self.grid(row=gridrow, column=0) self.button = Button( self, text="Click here to scan all your journals for Hyperdictions") self.button.bind('<Button-1>', self.run) self.button.grid(row=0, column=0) Emitter.setRoute(is_beta, client) def getUrl(self): if self.is_beta: url = Emitter.urls.get("staging") else: url = Emitter.route return url def excludesystems(self): url = self.getUrl() if not HDReport.hdsystems: debug("getting old hdsystems") r = requests.get( "{}/{}?cmdrName={}&_sort=created_at:DESC&_limit=100".format( url, "hdreports", self.commander)) for hd in r.json(): debug("excluding: {}".format(hd.get("fromSystemName"))) HDReport.hdsystems[hd.get("fromSystemName")] = hd.get( "fromSystemName") def run(self, event): self.button.grid_remove() HDScanner(self.scan_journals).start() def set_beta(self, entry): if entry.get("event") == "Fileheader": if "beta" in entry.get("gameversion").lower(): self.is_beta = True else: self.is_beta = False def set_commander(self, entry): if entry.get("event") == "Commander": self.commander = entry.get("Name") def detect_hyperdiction(self, entry): if entry.get("event") == "Statistics": debug("detected") submit(self.commander, self.is_beta, None, None, entry, self.client) time.sleep(0.1) # else: # debug(entry.get("event")) def scan_file(self, filename): with open(filename) as f: for line in f: entry = json.loads(line) self.set_beta(entry) self.set_commander(entry) self.detect_hyperdiction(entry) def scan_journals(self): self.excludesystems() config.default_journal_dir for filename in glob.glob( os.path.join(config.default_journal_dir, 'journal*.log')): self.scan_file(filename)
class Database: """Opens a window for inputing the properties of a compound.""" def __init__(self, master, system, database): """The constructor method.""" self.system = system self.version = system.version self.fonttype = system.fonttype self.sfont = get_superfont(self.fonttype) self.master = master self.tframe = Frame(master.tframe) self.frame = Frame(master.frame) self.bframe = Frame(master.bframe) self.top = None self.database = database #the database of values self.exitflag = 0 self.names = [] #a list of the chemical names solids_list = self.database.keys() solids_list.sort() self.solids_list = solids_list self.solids = [] for solidname in solids_list: self.solids.append(Solid(solids_list.index(solidname))) self.solids[-1].read_database(self.database[solidname]) def make_widgets(self): self.instructions = Label( self.tframe, text= 'Please provide the following fundamental properties for the material:\n' ) self.blankcolumn = Label(self.tframe, text='', font='courier 10', width=1) self.editcolumn = Label(self.tframe, text='', font='courier 10', width=6) self.delcolumn = Label(self.tframe, text='', font='courier 10', width=6) self.numbercolumn = Label(self.tframe, text='', font='courier 10', width=8) self.namecolumn = Label(self.tframe, text='', font='courier 10', width=18) self.ecolumn = Label(self.tframe, text='', font='courier 10', width=8) self.rhocolumn = Label(self.tframe, text='', font='courier 10', width=12) self.foccolumn = Label(self.tframe, text='', font='courier 10', width=20) self.tortcolumn = Label(self.tframe, text='', font='courier 10', width=18) self.sorpcolumn = Label(self.tframe, text='', font='courier 10', width=18) self.refcolumn = Label(self.tframe, text='', font='courier 10', width=15) self.numberlabel = Label(self.tframe, text='Number') self.namelabel = Label(self.tframe, text='Material') self.elabel = Label(self.tframe, text='Porosity') self.rholabel = Label(self.tframe, text='Bulk density') self.foclabel = Label(self.tframe, text='Organic carbon fraction') self.tortlabel = Label(self.tframe, text='Tortuosity correction') self.sorplabel = Label(self.tframe, text='Sorption isotherms') self.reflabel = Label(self.tframe, text='Reference') self.rhounitlabel = Label(self.tframe, text=u'g/cm\u00B3') self.botblankcolumn = Label(self.frame, text='', font='courier 10', width=1) self.boteditcolumn = Label(self.frame, text='', font='courier 10', width=6) self.botdelcolumn = Label(self.frame, text='', font='courier 10', width=6) self.botnumbercolumn = Label(self.frame, text='', font='courier 10', width=8) self.botnamecolumn = Label(self.frame, text='', font='courier 10', width=18) self.botecolumn = Label(self.frame, text='', font='courier 10', width=8) self.botrhocolumn = Label(self.frame, text='', font='courier 10', width=12) self.botfoccolumn = Label(self.frame, text='', font='courier 10', width=20) self.bottortcolumn = Label(self.frame, text='', font='courier 10', width=18) self.botsorpcolumn = Label(self.frame, text='', font='courier 10', width=18) self.botrefcolumn = Label(self.frame, text='', font='courier 10', width=15) self.addwidget = Button(self.bframe, text='Add solids', command=self.addsolid, width=20) self.savebutton = Button(self.bframe, text='Save', width=20, command=self.save) self.importwidget = Button(self.bframe, text='Import database file', command=self.importsoliddata, width=20) self.cancelbutton = Button(self.bframe, text='Cancel', command=self.cancel, width=20) self.blank1 = Label(self.bframe, text=' ') self.blank2 = Label(self.bframe, text=' ') self.blank3 = Label(self.bframe, text=' ') #show the widgets on the grid (top to bottom and left to right) self.instructions.grid(row=0, column=0, columnspan=11, padx=8, sticky='W', pady=10) self.blankcolumn.grid(row=1, column=0, sticky='WE', padx=1, pady=1) self.editcolumn.grid(row=1, column=1, sticky='WE', padx=1, pady=1) self.delcolumn.grid(row=1, column=2, sticky='WE', padx=1, pady=1) self.numbercolumn.grid(row=1, column=3, sticky='WE', padx=1, pady=1) self.namecolumn.grid(row=1, column=4, sticky='WE', padx=1, pady=1) self.ecolumn.grid(row=1, column=5, sticky='WE', padx=1, pady=1) self.rhocolumn.grid(row=1, column=6, sticky='WE', padx=1, pady=1) self.foccolumn.grid(row=1, column=7, sticky='WE', padx=1, pady=1) self.tortcolumn.grid(row=1, column=8, sticky='WE', padx=1, pady=1) self.sorpcolumn.grid(row=1, column=9, sticky='WE', padx=1, pady=1) self.refcolumn.grid(row=1, column=10, sticky='WE', padx=1, pady=1) self.numberlabel.grid(row=2, column=3, sticky='WE', padx=1, pady=1) self.namelabel.grid(row=2, column=4, sticky='WE', padx=1, pady=1) self.elabel.grid(row=2, column=5, sticky='WE', padx=1, pady=1) self.rholabel.grid(row=2, column=6, sticky='WE', padx=1, pady=1) self.foclabel.grid(row=2, column=7, sticky='WE', padx=1, pady=1) self.tortlabel.grid(row=2, column=8, sticky='WE', padx=1, pady=1) self.sorplabel.grid(row=2, column=9, sticky='WE', padx=1, pady=1) self.reflabel.grid(row=2, column=10, sticky='WE', padx=1, pady=1) self.rhounitlabel.grid(row=3, column=6, sticky='WE', padx=1, pady=1) self.updatesolids() #Bind the "return key" to the buttons self.focusbutton = self.cancelbutton def updatesolids(self): self.addwidget.grid_forget() self.blank1.grid_forget() self.blank2.grid_forget() self.botblankcolumn.grid_forget() self.boteditcolumn.grid_forget() self.botdelcolumn.grid_forget() self.botnumbercolumn.grid_forget() self.botnamecolumn.grid_forget() self.botecolumn.grid_forget() self.botrhocolumn.grid_forget() self.botfoccolumn.grid_forget() self.bottortcolumn.grid_forget() self.botsorpcolumn.grid_forget() self.botrefcolumn.grid_forget() namelabellength = 18 reflabellength = 15 row = 4 for solid in self.solids: try: solid.remove_propertieswidget() except: pass solid.number = self.solids.index(solid) + 1 solid.propertieswidget(self.frame, row, self.master) row = row + 1 if namelabellength < solid.namelabel.winfo_reqwidth() / 8: namelabellength = int(solid.namelabel.winfo_reqwidth() / 8) + 1 if reflabellength < solid.reflabel.winfo_reqwidth() / 8: reflabellength = int(solid.reflabel.winfo_reqwidth() / 8) + 1 self.namecolumn.config(width=namelabellength) self.botnamecolumn.config(width=namelabellength) self.refcolumn.config(width=reflabellength) self.botrefcolumn.config(width=reflabellength) self.botblankcolumn.grid(row=row, column=0, sticky='WE', padx=1, pady=1) self.boteditcolumn.grid(row=row, column=1, sticky='WE', padx=1, pady=1) self.botdelcolumn.grid(row=row, column=2, sticky='WE', padx=1, pady=1) self.botnumbercolumn.grid(row=row, column=3, sticky='WE', padx=1, pady=1) self.botnamecolumn.grid(row=row, column=4, sticky='WE', padx=1, pady=1) self.botecolumn.grid(row=row, column=5, sticky='WE', padx=1, pady=1) self.botrhocolumn.grid(row=row, column=6, sticky='WE', padx=1, pady=1) self.botfoccolumn.grid(row=row, column=7, sticky='WE', padx=1, pady=1) self.bottortcolumn.grid(row=row, column=8, sticky='WE', padx=1, pady=1) self.botsorpcolumn.grid(row=row, column=9, sticky='WE', padx=1, pady=1) self.botrefcolumn.grid(row=row, column=10, sticky='WE', padx=1, pady=1) row = row + 1 row = 0 self.blank1.grid(row=row) row = row + 1 self.blank2.grid(row=row) row = row + 1 self.addwidget.grid(row=row, columnspan=11) row = row + 1 self.importwidget.grid(row=row, columnspan=11) row = row + 1 self.savebutton.grid(row=row, columnspan=11) row = row + 1 self.cancelbutton.grid(row=row, columnspan=11) row = row + 1 self.blank3.grid(row=row) self.savebutton.bind('<Return>', self.save) self.cancelbutton.bind('<Return>', self.cancel) self.focusbutton = self.savebutton self.master.geometry() def addsolid(self): self.solids.append(Solid(self.solids[-1].number + 1)) if self.top is None: self.top = CapSimWindow(master=self.master, buttons=2) self.top.make_window( SolidDatabaseEditor(self.top, self.system, self.solids[-1], self.solids, editflag=0)) self.top.tk.mainloop() if self.top.window.cancelflag == 0: self.solids[-1].get_solid(self.top.window) else: self.solids.remove(self.solids[-1]) if self.top is not None: self.top.destroy() self.top = None elif self.top is not None: tkmb.showerror( title=self.system.version, message= 'Please close the existing parameter input window first.') self.top.tk.focus() self.updatesolids() def editsolid(self, number): if self.top is None: self.top = CapSimWindow(master=self.master, buttons=2) self.top.make_window( SolidDatabaseEditor(self.top, self.system, self.solids[number - 1], self.solids, editflag=1)) self.top.tk.mainloop() if self.top.window.cancelflag == 0: self.solids[number - 1].get_solid(self.top.window) if self.top is not None: self.top.destroy() self.top = None elif self.top is not None: tkmb.showerror( title=self.system.version, message= 'Please close the existing parameter input window first.') self.top.tk.focus() self.updatesolids() def importsoliddata(self): UserPath = os.environ['USERPROFILE'] Filepath = tkfd.askopenfilename(initialdir=UserPath) if Filepath != '': data = open(Filepath, 'r') database_imported = pickle.load(data) data.close() if self.top is None: self.top = CapSimWindow(master=self.master, buttons=2) self.top.make_window( SolidDatabaseImporter(self.top, self.system, database_imported)) self.top.tk.mainloop() duplicate_name = [] if self.top.window.cancelflag == 0: error_check = 0 for solid in self.top.window.solids: if solid.check == 1: if self.solids_list.count(solid.name_new) == 0: self.solids_list.append(solid.name_new) self.solids.append( Solid( self.solids_list.index( solid.name_new))) self.solids[-1].import_coefficients(solid) else: duplicate_name.append(solid.name_new) error_check = 1 error_message = 'The following compound information are duplicated:\n\n' for na in range(len(duplicate_name)): error_message = error_message + ' ' + str( duplicate_name[na]) + ' \n' if error_check == 1: tkmb.showerror(title=self.system.version, message=error_message) if self.top is not None: self.top.destroy() self.top = None elif self.top is not None: tkmb.showerror( title=self.system.version, message= 'Please close the existing parameter input window first.') self.top.tk.focus() self.updatesolids() def deletesolid(self, number): if self.top is None: self.top = CapSimWindow(master=self.master, buttons=2) self.top.make_window( SolidDatabaseDeleter(self.top, self.system, self.solids[number - 1])) self.top.tk.mainloop() if self.top.window.cancelflag == 0: self.solids[number - 1].remove_propertieswidget() self.solids.remove(self.solids[number - 1]) if self.top is not None: self.top.destroy() self.top = None elif self.top is not None: tkmb.showerror( title=self.system.version, message= 'Please close the existing parameter input window first.') self.top.tk.focus() self.updatesolids() def save(self, event=None): self.database = self.write_database() self.exitflag = 1 self.frame.quit() def cancel(self, event=None): self.exitflag = 1 self.frame.quit() def exit(self, event=None): """Exit CapSim.""" if tkmb.askyesno(self.version, 'Do you really want to exit CapSim?') == 1: sys.exit() def write_database(self): soliddatabase = {} for solid in self.solids: soliddatabase[solid.name] = SolidDatabase(solid.name, solid.number, solid.e, solid.rho, solid.foc, solid.tort, solid.sorp, solid.Ref) return soliddatabase
class ChemicalProperties: """Gets the contaminant properties.""" def __init__(self, master, system, database): """Constructor method. Defines the parameters to be obtained in this window.""" self.master = master self.fonttype = system.fonttype self.version = system.version self.superfont = get_superfont(self.fonttype) #superscript font self.tframe = Frame(master.tframe) self.frame = Frame(master.frame) self.bframe = Frame(master.bframe) self.top = None #flag for existence of toplevel# self.system = system self.database = database self.diffunit = system.diffunit self.concunit = system.concunit self.concunits = system.concunits if system.chemicals is None: self.chemicals = [] self.nchemicals = 0 else: self.chemicals = system.chemicals self.nchemicals = system.nchemicals def make_widgets(self): """Make the widgets for the window.""" self.bgcolor = self.frame.cget('bg') # Construct all label widgets used in the problem self.instructions = Label( self.tframe, text= ' Please provide the following chemical properties: ' ) self.blankcolumn = Label(self.tframe, text='', width=1) self.editcolumn = Label(self.tframe, text='', width=6) self.delcolumn = Label(self.tframe, text='', width=6) self.numbercolumn = Label(self.tframe, text='', width=6) self.namecolumn = Label(self.tframe, text='', width=18) self.MWcolumn = Label(self.tframe, text='', width=8) self.tempcolumn = Label(self.tframe, text='', width=10) self.Dwcolumn = Label(self.tframe, text='', width=16) self.Koccolumn = Label(self.tframe, text='', width=16) self.Kdoccolumn = Label(self.tframe, text='', width=18) self.Refcolumn = Label(self.tframe, text='', width=17) self.endcolumn = Label(self.tframe, text='', width=1) self.botblankcolumn = Label(self.frame, text='', width=1) self.boteditcolumn = Label(self.frame, text='', width=6) self.botdelcolumn = Label(self.frame, text='', width=6) self.botnumbercolumn = Label(self.frame, text='', width=6) self.botnamecolumn = Label(self.frame, text='', width=18) self.botMWcolumn = Label(self.frame, text='', width=8) self.bottempcolumn = Label(self.frame, text='', width=10) self.botDwcolumn = Label(self.frame, text='', width=16) self.botKoccolumn = Label(self.frame, text='', width=16) self.botKdoccolumn = Label(self.frame, text='', width=18) self.botRefcolumn = Label(self.frame, text='', width=17) self.botendcolumn = Label(self.frame, text='', width=1) self.numberlabel = Label(self.tframe, text='Number') self.namelabel = Label(self.tframe, text='Chemical name') self.MWlabel = Label(self.tframe, text='Molecular\n Weight') self.templabel = Label(self.tframe, text='Temperature') self.Dwlabel = Label(self.tframe, text='Molecular diffusivity\n in water') self.Koclabel = Label(self.tframe, text='Organic carbon\n partition coefficient') self.Kdoclabel = Label( self.tframe, text='Dissolved organic carbon\n partition coefficient') self.Reflabel = Label(self.tframe, text='Reference') self.tempunits = Label(self.tframe, text=unichr(176) + 'C') self.Dwunits = Label(self.tframe, text=self.diffunit) self.Kocunits = Label(self.tframe, text='log(L/kg)') self.Kdocunits = Label(self.tframe, text='log(L/kg)') self.blank1 = Label(self.frame, text=' ') self.blank2 = Label(self.bframe, text=' ') self.addwidget = Button(self.bframe, text='Add chemicals', command=self.addchemical, width=20) #show the widgets on the grid self.instructions.grid(row=0, column=0, columnspan=9, padx=1, sticky='W') self.blankcolumn.grid(row=1, column=0, sticky='WE', padx=1, pady=1) self.editcolumn.grid(row=1, column=1, sticky='WE', padx=1, pady=1) self.delcolumn.grid(row=1, column=2, sticky='WE', padx=1, pady=1) self.numbercolumn.grid(row=1, column=3, sticky='WE', padx=1, pady=1) self.namecolumn.grid(row=1, column=4, sticky='WE', padx=1, pady=1) self.MWcolumn.grid(row=1, column=5, sticky='WE', padx=1, pady=1) self.tempcolumn.grid(row=1, column=6, sticky='WE', padx=1, pady=1) self.Dwcolumn.grid(row=1, column=7, sticky='WE', padx=1, pady=1) self.Koccolumn.grid(row=1, column=8, sticky='WE', padx=1, pady=1) self.Kdoccolumn.grid(row=1, column=9, sticky='WE', padx=1, pady=1) self.Refcolumn.grid(row=1, column=10, sticky='WE', padx=1, pady=1) self.endcolumn.grid(row=1, column=11, sticky='WE', padx=1, pady=1) self.numberlabel.grid(row=2, column=3, sticky='WE', padx=1, pady=1) self.namelabel.grid(row=2, column=4, sticky='WE', padx=1, pady=1) self.MWlabel.grid(row=2, column=5, sticky='WE', padx=1, pady=1) self.templabel.grid(row=2, column=6, sticky='WE', padx=1, pady=1) self.Dwlabel.grid(row=2, column=7, sticky='WE', padx=1, pady=1) self.Koclabel.grid(row=2, column=8, sticky='WE', padx=1, pady=1) self.Kdoclabel.grid(row=2, column=9, sticky='WE', padx=1, pady=1) self.Reflabel.grid(row=2, column=10, sticky='WE', padx=1, pady=1) self.tempunits.grid(row=3, column=6, sticky='WE', padx=1, pady=1) self.Dwunits.grid(row=3, column=7, sticky='WE', padx=1, pady=1) self.Kocunits.grid(row=3, column=8, sticky='WE', padx=1, pady=1) self.Kdocunits.grid(row=3, column=9, sticky='WE', padx=1, pady=1) self.updatechemicals() def updatechemicals(self): try: self.botblankcolumn.grid_forget() self.boteditcolumn.grid_forget() self.botdelcolumn.grid_forget() self.botnumbercolumn.grid_forget() self.botnamecolumn.grid_forget() self.botMWcolumn.grid_forget() self.bottempcolumn.grid_forget() self.botDwcolumn.grid_forget() self.botKoccolumn.grid_forget() self.botKdoccolumn.grid_forget() self.botRefcolumn.grid_forget() self.botendcolumn.grid_forget() except: pass chemicals_list = self.database.keys() for chemical in self.chemicals: if chemical.soluable == 1: try: chemicals_list.remove(chemical.name) except: pass self.addwidget.grid_forget() namelabellength = 18 reflabellength = 18 row = 0 for chemical in self.chemicals: try: chemical.remove_chemicalwidgets() except: pass chemical.number = self.chemicals.index(chemical) + 1 chemical.chemicalwidgets(self.frame, row, self.master) row = row + 1 if namelabellength < chemical.namelabel.winfo_reqwidth() / 8: namelabellength = int( chemical.namelabel.winfo_reqwidth() / 8) + 1 if reflabellength < chemical.Reflabel.winfo_reqwidth( ) / 8 * 1.1424219345: reflabellength = int( chemical.Reflabel.winfo_reqwidth() / 8 * 1.1424219345) + 1 self.namecolumn.config(width=namelabellength) self.Refcolumn.config(width=reflabellength) self.botnamecolumn.config(width=namelabellength) self.botRefcolumn.config(width=reflabellength) self.botblankcolumn.grid(row=row, column=0, sticky='WE', padx=1, pady=1) self.boteditcolumn.grid(row=row, column=1, sticky='WE', padx=1, pady=1) self.botdelcolumn.grid(row=row, column=2, sticky='WE', padx=1, pady=1) self.botnumbercolumn.grid(row=row, column=3, sticky='WE', padx=1, pady=1) self.botnamecolumn.grid(row=row, column=4, sticky='WE', padx=1, pady=1) self.botMWcolumn.grid(row=row, column=5, sticky='WE', padx=1, pady=1) self.bottempcolumn.grid(row=row, column=6, sticky='WE', padx=1, pady=1) self.botDwcolumn.grid(row=row, column=7, sticky='WE', padx=1, pady=1) self.botKoccolumn.grid(row=row, column=8, sticky='WE', padx=1, pady=1) self.botKdoccolumn.grid(row=row, column=9, sticky='WE', padx=1, pady=1) self.botRefcolumn.grid(row=row, column=10, sticky='WE', padx=1, pady=1) self.botendcolumn.grid(row=row, column=11, sticky='WE', padx=1, pady=1) row = 0 self.blank2.grid(row=row) row = row + 1 if len(chemicals_list) > 0: self.addwidget.grid(row=row, columnspan=11) row = row + 1 self.addwidget.bind('<Return>', self.addchemical) if self.nchemicals == 0: self.focusbutton = self.addwidget else: self.focusbutton = None self.master.geometry() self.master.center() def addchemical(self, event=None): self.nchemicals = self.nchemicals + 1 self.chemicals.append(Chemical(self.nchemicals, soluable=1)) if self.top is None: self.top = CapSimWindow(master=self.master, buttons=2) self.top.make_window( ChemicalEditor(self.top, self.system, self.chemicals[-1], self.chemicals, self.database, editflag=0)) self.top.tk.mainloop() if self.top.window.cancelflag == 0: self.chemicals[-1].get_chemical(self.top.window) else: self.chemicals.remove(self.chemicals[-1]) self.nchemicals = self.nchemicals - 1 if self.top is not None: self.top.destroy() self.top = None elif self.top is not None: tkmb.showerror( title=self.system.version, message= 'Please close the existing parameter input window first.') self.top.tk.focus() self.updatechemicals() def editchemical(self, number): if self.top is None: self.top = CapSimWindow(master=self.master, buttons=2) self.top.make_window( ChemicalEditor(self.top, self.system, self.chemicals[number - 1], self.chemicals, self.database, editflag=1)) self.top.tk.mainloop() if self.top.window.cancelflag == 0: self.chemicals[number - 1].get_chemical(self.top.window) if self.top is not None: self.top.destroy() self.top = None elif self.top is not None: tkmb.showerror( title=self.system.version, message= 'Please close the existing parameter input window first.') self.top.tk.focus() self.updatechemicals() def deletechemical(self, number): if self.top is None: self.top = CapSimWindow(master=self.master, buttons=2) self.top.make_window( ChemicalDeleter(self.top, self.system, self.chemicals[number - 1])) self.top.tk.mainloop() if self.top.window.cancelflag == 0: self.chemicals[number - 1].remove_chemicalwidgets() self.chemicals.remove(self.chemicals[number - 1]) self.nchemicals = self.nchemicals - 1 if self.top is not None: self.top.destroy() self.top = None self.updatechemicals() def error_check(self, event=None): """Finish and move on. Checks that the number chemicals are less than the total number of chemicals in database.""" error = 0 if self.nchemicals == 0: error = 1 return error def warning(self): tkmb.showerror( title=self.version, message= 'No chemical has been selected, please add chemicals by pressing the button "Add chemicals"' ) self.focusbutton = None self.master.tk.lift()
class SelectBox: """ SelectBox class should be considered "private" and is used entirely by the ScaleUI class. It is responsible for the raw mechanics of actually drawing a box on the selected entities and dealing with user-input on the control points. """ MIN_WIDTH = 30 MIN_HEIGHT = 30 def __init__(self, dc, selectionDict): self.__dc = dc self.__selectionDict = selectionDict self.__selectedEntityBoxDict = dict() for tag in selectionDict: obj = selectionDict[tag][1] atom3i = obj.semanticObject.parent self.__UI_Statechart = atom3i.UI_Statechart self.__callbackState = atom3i.cb break bbox = getBoundingBox(selectionDict) minx, miny, maxx, maxy = bbox # Put a box around the selection self.__selectionBoxHandler = self.__dc.create_rectangle( bbox, width=4, outline='green', dash=(4, 4)) # Define re-size entity buttons self.NW_button = Button(self.__dc, bg='SpringGreen') self.NE_button = Button(self.__dc, bg='SpringGreen') self.SW_button = Button(self.__dc, bg='SpringGreen') self.SE_button = Button(self.__dc, bg='SpringGreen') self.NW_button.pack() self.NE_button.pack() self.SW_button.pack() self.SE_button.pack() self.NW_button.bind('<Button-1>', self.scaleHandler) self.NE_button.bind('<Button-1>', self.scaleHandler) self.SW_button.bind('<Button-1>', self.scaleHandler) self.SE_button.bind('<Button-1>', self.scaleHandler) # Define re-size text buttons self.N_button = Button(self.__dc, font=("Times", 8, "bold"), text='T', bg='SpringGreen') self.E_button = Button(self.__dc, font=("Times", 8, "bold"), text='T', bg='SpringGreen') self.S_button = Button(self.__dc, font=("Times", 8, "bold"), text='T', bg='SpringGreen') self.W_button = Button(self.__dc, font=("Times", 8, "bold"), text='T', bg='SpringGreen') self.N_button.pack() self.E_button.pack() self.S_button.pack() self.W_button.pack() self.N_button.bind('<Button-1>', self.textScaleHandler) self.E_button.bind('<Button-1>', self.textScaleHandler) self.S_button.bind('<Button-1>', self.textScaleHandler) self.W_button.bind('<Button-1>', self.textScaleHandler) # Place the buttons on the canvas size = 10 self.NW_window = self.__dc.create_window(minx, miny, width=size, height=size, window=self.NW_button) self.NE_window = self.__dc.create_window(maxx, miny, width=size, height=size, window=self.NE_button) self.SW_window = self.__dc.create_window(minx, maxy, width=size, height=size, window=self.SW_button) self.SE_window = self.__dc.create_window(maxx, maxy, width=size, height=size, window=self.SE_button) # Text re-size buttons widthOver2 = float(maxx - minx) / 2.0 heightOver2 = float(maxy - miny) / 2.0 self.N_window = self.__dc.create_window(minx + widthOver2, miny, width=size, height=size, window=self.N_button) self.E_window = self.__dc.create_window(maxx, miny + heightOver2, width=size, height=size, window=self.E_button) self.S_window = self.__dc.create_window(minx + widthOver2, maxy, width=size, height=size, window=self.S_button) self.W_window = self.__dc.create_window(minx, miny + heightOver2, width=size, height=size, window=self.W_button) # Make individual elements of the selection obvious if (len(selectionDict) > 1): self.individualPackaging() def individualPackaging(self): """ Give each element of the selection its own mini-box """ for tag in self.__selectionDict: obj = self.__selectionDict[tag][1] self.__selectedEntityBoxDict[tag] = self.__dc.create_rectangle( obj.getbbox(), width=3, outline='green', dash=(2, 2)) def destroy(self): self.__dc.delete(self.__selectionBoxHandler) self.__dc.delete(self.NW_window) self.__dc.delete(self.NE_window) self.__dc.delete(self.SW_window) self.__dc.delete(self.SE_window) self.__dc.delete(self.N_window) self.__dc.delete(self.E_window) self.__dc.delete(self.S_window) self.__dc.delete(self.W_window) for itemHandler in self.__selectedEntityBoxDict.values(): self.__dc.delete(itemHandler) self.__individuallyPackagedList = dict() def scaleHandler(self, event=None): """ Activate the UI_Statechart to handle the reactive behaviour """ self.__UI_Statechart.event('<KeyPress-r>', self) def textScaleHandler(self, event=None): """ Activate the UI_Statechart to handle the reactive behaviour """ if (not self.__callbackState.isLabelDragMode()): self.__callbackState.toggleLabelDragMode() self.__UI_Statechart.event('<KeyPress-r>', self) self.__callbackState.toggleLabelDragMode() else: self.__UI_Statechart.event('<KeyPress-r>', self) def update(self): """ After scaling, make sure the boxes & buttons are scaled too! """ minx, miny, maxx, maxy = getBoundingBox(self.__selectionDict) self.__dc.coords(self.__selectionBoxHandler, (minx, miny, maxx, maxy)) self.__dc.coords(self.NW_window, (minx, miny)) self.__dc.coords(self.NE_window, (maxx, miny)) self.__dc.coords(self.SW_window, (minx, maxy)) self.__dc.coords(self.SE_window, (maxx, maxy)) widthOver2 = float(maxx - minx) / 2.0 heightOver2 = float(maxy - miny) / 2.0 self.__dc.coords(self.N_window, (minx + widthOver2, miny)) self.__dc.coords(self.E_window, (maxx, miny + heightOver2)) self.__dc.coords(self.S_window, (minx + widthOver2, maxy)) self.__dc.coords(self.W_window, (minx, miny + heightOver2)) for tag in self.__selectedEntityBoxDict: obj = self.__selectionDict[tag][1] try: self.__dc.coords(self.__selectedEntityBoxDict[tag], obj.getbbox()) except: pass
class AssetBuilder(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.isRunning = False self.initUI() def initUI(self): self.parent.title("Script Runner/Caller") # self.style = Style() # self.style.theme_use("default") self.pack(fill=BOTH, expand=1) #create a grid 5x4 in to which we will place elements. self.columnconfigure(1, weight=1) self.columnconfigure(2, weight=0) self.columnconfigure(3, weight=0) self.columnconfigure(4, weight=0) self.columnconfigure(5, weight=0) self.rowconfigure(1, weight=1) self.rowconfigure(2, weight=0) self.rowconfigure(3, weight=0) #create the main text are with scrollbars xscrollbar = Scrollbar(self, orient=HORIZONTAL) xscrollbar.grid(row=2, column=1, columnspan=4, sticky=E + W) yscrollbar = Scrollbar(self, orient=VERTICAL) yscrollbar.grid(row=1, column=5, sticky=N + S) self.textarea = Text(self, wrap=NONE, bd=0, xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set) self.textarea.grid(row=1, column=1, columnspan=4, rowspan=1, padx=0, sticky=E + W + S + N) xscrollbar.config(command=self.textarea.xview) yscrollbar.config(command=self.textarea.yview) #create the buttons/checkboxes to go along the bottom self.clearButton = Button(self, text="Clear") self.clearButton.grid(row=3, column=1, padx=5, pady=5, sticky=W) self.clearButton.bind("<ButtonRelease-1>", self.clearText) self.runbutton = Button(self, text="Run/Call") self.runbutton.grid(row=3, column=3, padx=5, pady=5) self.runbutton.bind("<ButtonRelease-1>", self.runScript) self.stopbutton = Button(self, text="Stop") self.stopbutton.grid(row=3, column=4, padx=5, pady=5) self.stopbutton.bind("<ButtonRelease-1>", self.stopScript) #tags are used to colorise the text added to the text widget. # see self.addTtext and self.tagsForLine self.textarea.tag_config("errorstring", foreground="#CC0000") self.textarea.tag_config("infostring", foreground="#008800") self.addText("Path A: " + os.getcwd() + "\n", ("infostring", )) self.addText("(chdir)" + "\n", ("infostring", )) os.chdir(dirname(os.path.realpath(__file__))) self.addText("Path B: " + os.getcwd() + "\n\n", ("infostring", )) self.addText("Script is: " + " ".join(scriptcall) + "\n\n", ("infostring", )) def tagsForLine(self, line): """return a tuple of tags to be applied to the line of text 'line' when being added to the text widet""" l = line.lower() if "error" in l or "traceback" in l: return ("errorstring", ) return () def addText(self, str, tags=None): """Add a line of text to the textWidget. If tags is None then self.tagsForLine will be used to assign tags to the line""" self.textarea.insert(INSERT, str, tags or self.tagsForLine(str)) self.textarea.yview(END) def clearText(self, event): """Clear all the text from the text widget""" self.textarea.delete("1.0", END) print "isAlive:", self.worker.isAlive(), ", isRunning:", self.isRunning def moveCursorToEnd(self): """move the cursor to the end of the text widget's text""" self.textarea.mark_set("insert", END) def runScript(self, event): if (not (self.isRunning)): self.isRunning = True self.worker = threading.Thread(target=self.runScriptThread, args=(event, )) self.worker.start() def runScriptThread(self, event): """callback from the run/call button""" self.moveCursorToEnd() self.addText("Calling script %s\n" % (str(datetime.now())), ("infostring", )) #~ cmdlist = filter(lambda x: x if x else None, #~ [pythonpath, mainpath, self.verboseVar.get(), self.forceVar.get()]) cmdlist = scriptcall self.addText(" ".join(cmdlist) + "\n", ("infostring", )) self.proc = subprocess.Popen(cmdlist, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, preexec_fn=os.setsid) while True: line = self.proc.stdout.readline() if not line: break self.addText(line) #this triggers an update of the text area, otherwise it doesn't update self.textarea.update_idletasks() self.isRunning = False self.addText("Script Finished %s\n" % (str(datetime.now())), ("infostring", )) self.addText("*" * 80 + "\n", ("infostring", )) def stopScript(self, event): """callback from the stop button""" #~ os.kill(signal.CTRL_C_EVENT, 0) #~ os.kill(self.proc.pid, signal.CTRL_C_EVENT) # AttributeError: 'module' object has no attribute 'CTRL_C_EVENT' #~ os.kill(self.proc.pid, signal.SIGTERM) os.killpg(self.proc.pid, signal.SIGTERM) self.proc.terminate() self.proc.kill() print self.worker.isAlive() # True here
class Database: """Opens a window for inputing the properties of a compound.""" def __init__(self, master, system, database): """The constructor method.""" self.version = system.version self.fonttype = system.fonttype self.sfont = get_superfont(self.fonttype) self.master = master self.tframe = Frame(master.tframe) self.frame = Frame(master.frame) self.bframe = Frame(master.bframe) self.top = None self.system = system self.database = database #the chemical database self.chemicals_list = self.database.keys() self.chemicals_list.sort() self.chemicaldatas = {} for name in self.chemicals_list: self.chemicaldatas[name] = ChemicalData(name) self.chemicaldatas[name].read_database(self.database[name]) def make_widgets(self): self.insruction = Label( self.tframe, text= 'Please provide the following fundamental properties for the chemicals:\n' ) self.blankcolumn = Label(self.tframe, text=' ', width=1) self.editcolumn = Label(self.tframe, text=' ', width=6) self.delcolumn = Label(self.tframe, text=' ', width=6) self.namecolumn = Label(self.tframe, text=' ', width=18) self.formcolumn = Label(self.tframe, text=' ', width=10) self.tempcolumn = Label(self.tframe, text=' ', width=10) self.Dwcolumn = Label(self.tframe, text=' ', width=18) self.Koccolumn = Label(self.tframe, text=' ', width=18) self.Kdoccolumn = Label(self.tframe, text=' ', width=18) self.Refcolumn = Label(self.tframe, text=' ', width=18) self.endcolumn = Label(self.tframe, text=' ', width=2) self.namelabel = Label(self.tframe, text='Chemical name') self.formlabel = Label(self.tframe, text='Formula') self.templabel = Label(self.tframe, text='Temperature') self.Dwlabel = Label(self.tframe, text='Molecular diffusivity\n in water') self.Koclabel = Label(self.tframe, text='Organic carbon\n partition coefficient') self.Kdoclabel = Label( self.tframe, text='Dissolved organic carbon\n partition coefficient') self.Reflabel = Label(self.tframe, text='Reference') self.tempunits = Label(self.tframe, text=unichr(176) + 'C') self.Dwunits = Label(self.tframe, text=u'cm\u00B2/s') self.Kocunits = Label(self.tframe, text='log(L/kg)') self.Kdocunits = Label(self.tframe, text='log(L/kg)') self.addwidget = Button(self.bframe, text='Add new chemicals', command=self.addchemicaldata, width=20) self.tempwidget = Button(self.bframe, text='Add new temperatures', command=self.addtempdata, width=20) self.importwidget = Button(self.bframe, text='Import database file', command=self.importchemicaldata, width=20) self.savebutton = Button(self.bframe, text='Save', command=self.OK, width=20) self.cancelbutton = Button(self.bframe, text='Cancel', command=self.cancel, width=20) self.botblankcolumn = Label(self.frame, text=' ', width=1) self.boteditcolumn = Label(self.frame, text=' ', width=6) self.botdelcolumn = Label(self.frame, text=' ', width=6) self.botnamecolumn = Label(self.frame, text=' ', width=18) self.botformcolumn = Label(self.frame, text=' ', width=10) self.bottempcolumn = Label(self.frame, text=' ', width=10) self.botDwcolumn = Label(self.frame, text=' ', width=18) self.botKoccolumn = Label(self.frame, text=' ', width=18) self.botKdoccolumn = Label(self.frame, text=' ', width=18) self.botRefcolumn = Label(self.frame, text=' ', width=18) self.botendcolumn = Label(self.frame, text=' ', width=2) self.blank1 = Label(self.bframe, text=' ') self.blank2 = Label(self.bframe, text=' ') self.blank3 = Label(self.bframe, text=' ') self.insruction.grid(row=0, column=0, sticky='W', padx=1, pady=1, columnspan=11) self.blankcolumn.grid(row=1, column=0, sticky='WE', padx=1, pady=1) self.editcolumn.grid(row=1, column=1, sticky='WE', padx=1, pady=1) self.delcolumn.grid(row=1, column=2, sticky='WE', padx=1, pady=1) self.namecolumn.grid(row=1, column=3, sticky='WE', padx=1, pady=1) self.formcolumn.grid(row=1, column=4, sticky='WE', padx=1, pady=1) self.tempcolumn.grid(row=1, column=5, sticky='WE', padx=1, pady=1) self.Dwcolumn.grid(row=1, column=6, sticky='WE', padx=1, pady=1) self.Koccolumn.grid(row=1, column=7, sticky='WE', padx=1, pady=1) self.Kdoccolumn.grid(row=1, column=8, sticky='WE', padx=1, pady=1) self.Refcolumn.grid(row=1, column=9, sticky='WE', padx=1, pady=1) self.endcolumn.grid(row=1, column=10, sticky='WE', padx=1, pady=1) self.namelabel.grid(row=2, column=3, sticky='WE', padx=1, pady=1) self.formlabel.grid(row=2, column=4, sticky='WE', padx=1, pady=1) self.templabel.grid(row=2, column=5, sticky='WE', padx=1, pady=1) self.Dwlabel.grid(row=2, column=6, sticky='WE', padx=1, pady=1) self.Koclabel.grid(row=2, column=7, sticky='WE', padx=1, pady=1) self.Kdoclabel.grid(row=2, column=8, sticky='WE', padx=1, pady=1) self.Reflabel.grid(row=2, column=9, sticky='WE', padx=1, pady=1) self.tempunits.grid(row=3, column=5, sticky='WE', padx=1, pady=1) self.Dwunits.grid(row=3, column=6, sticky='WE', padx=1, pady=1) self.Kocunits.grid(row=3, column=7, sticky='WE', padx=1, pady=1) self.Kdocunits.grid(row=3, column=8, sticky='WE', padx=1, pady=1) #Bind the "return key" to the buttons self.updatechemicals() def updatechemicals(self, event=None): self.addwidget.grid_forget() self.tempwidget.grid_forget() self.savebutton.grid_forget() self.cancelbutton.grid_forget() self.blank1.grid_forget() self.blank2.grid_forget() self.chemicals_list = self.chemicaldatas.keys() self.chemicals_list.sort() row = 4 namelabellength = 18 formlabellength = 10 Reflabellength = 18 for name in self.chemicals_list: try: self.chemicaldatas[name].remove_chemicalwidgets() except: pass self.chemicaldatas[name].chemicalwidgets(self.frame, row, self.master) row = row + 1 if namelabellength < self.chemicaldatas[ name].namelabel.winfo_reqwidth() / 8: namelabellength = int( self.chemicaldatas[name].namelabel.winfo_reqwidth() / 8) + 1 if formlabellength < self.chemicaldatas[ name].formlabel.winfo_reqwidth() / 8: formlabellength = int( self.chemicaldatas[name].formlabel.winfo_reqwidth() / 8) + 1 if Reflabellength < self.chemicaldatas[ name].Reflabel.winfo_reqwidth() / 8: Reflabellength = int( self.chemicaldatas[name].Reflabel.winfo_reqwidth() / 8) + 1 self.namecolumn.config(width=namelabellength) self.formcolumn.config(width=formlabellength) self.Refcolumn.config(width=Reflabellength) self.botnamecolumn.config(width=namelabellength) self.botformcolumn.config(width=formlabellength) self.botRefcolumn.config(width=Reflabellength) self.botblankcolumn.grid(row=row, column=0, sticky='WE', padx=1, pady=1) self.boteditcolumn.grid(row=row, column=1, sticky='WE', padx=1, pady=1) self.botdelcolumn.grid(row=row, column=2, sticky='WE', padx=1, pady=1) self.botnamecolumn.grid(row=row, column=3, sticky='WE', padx=1, pady=1) self.botformcolumn.grid(row=row, column=4, sticky='WE', padx=1, pady=1) self.bottempcolumn.grid(row=row, column=5, sticky='WE', padx=1, pady=1) self.botDwcolumn.grid(row=row, column=6, sticky='WE', padx=1, pady=1) self.botKoccolumn.grid(row=row, column=7, sticky='WE', padx=1, pady=1) self.botKdoccolumn.grid(row=row, column=8, sticky='WE', padx=1, pady=1) self.botRefcolumn.grid(row=row, column=9, sticky='WE', padx=1, pady=1) self.botendcolumn.grid(row=row, column=10, sticky='WE', padx=1, pady=1) self.blank2.grid(row=row) row = row + 1 self.addwidget.grid(row=row, columnspan=11) row = row + 1 self.tempwidget.grid(row=row, columnspan=11) row = row + 1 self.importwidget.grid(row=row, columnspan=11) row = row + 1 self.savebutton.grid(row=row, columnspan=11) row = row + 1 self.cancelbutton.grid(row=row, columnspan=11) row = row + 1 self.blank3.grid(row=row) row = row + 1 self.savebutton.bind('<Return>', self.OK) self.cancelbutton.bind('<Return>', self.cancel) self.focusbutton = self.cancelbutton self.master.geometry() self.master.center() def addchemicaldata(self, event=None): new_name = 'chemical' + str(len(self.chemicals_list)) self.chemicaldatas[new_name] = ChemicalData(new_name) if self.top is None: self.top = CapSimWindow(master=self.master, buttons=2) self.top.make_window( DatabaseEditor(self.top, self.system, self.chemicaldatas[new_name], self.chemicaldatas, editflag=0, tempflag=0)) self.top.tk.mainloop() if self.top.window.cancelflag == 0: self.chemicaldatas[new_name].get_chemicaldata(self.top.window) self.chemicaldatas[self.chemicaldatas[new_name]. name] = self.chemicaldatas[new_name].copy() del self.chemicaldatas[new_name] if self.top is not None: self.top.destroy() self.top = None elif self.top is not None: tkmb.showerror( title=self.system.version, message= 'Please close the existing parameter input window first.') self.top.tk.focus() self.updatechemicals() def importchemicaldata(self): UserPath = os.environ['USERPROFILE'] Filepath = tkfd.askopenfilename(initialdir=UserPath) if Filepath != '': data = open(Filepath, 'r') database_imported = pickle.load(data) data.close() if self.top is None: self.top = CapSimWindow(master=self.master, buttons=2) self.top.make_window( DatabaseImporter(self.top, self.system, database_imported)) self.top.tk.mainloop() duplicate_name = [] duplicate_temp = [] if self.top.window.cancelflag == 0: error_check = 0 for name in self.top.window.chemicals_list: if self.top.window.importedchemicals[name].check == 1: if self.chemicals_list.count( self.top.window.importedchemicals[name]. name_new) == 0: self.chemicals_list.append( self.top.window.importedchemicals[name]. name_new) self.chemicaldatas[ self.top.window.importedchemicals[name]. name_new] = ChemicalData( self.top.window. importedchemicals[name].name_new) self.chemicaldatas[ self.top.window.importedchemicals[name]. name_new].read_database( self.top.window.importedchemicals[name] ) else: for temp in self.top.window.importedchemicals[ name].temps: if self.chemicaldatas[ self.top.window. importedchemicals[name]. name_new].temps.count(temp) == 0: self.chemicaldatas[ self.top.window. importedchemicals[name]. name_new].read_temperature( self.top.window. importedchemicals[name], temp) else: duplicate_name.append( self.top.window. importedchemicals[name].name_new) duplicate_temp.append(temp) error_check = 1 error_message = 'The following compound information are duplicated:\n\n' for na in range(len(duplicate_name)): error_message = error_message + ' ' + str( duplicate_name[na]) + ' @ ' + str( duplicate_temp[na]) + 'C \n' if error_check == 1: tkmb.showerror(title=self.system.version, message=error_message) if self.top is not None: self.top.destroy() self.top = None elif self.top is not None: tkmb.showerror( title=self.system.version, message= 'Please close the existing parameter input window first.') self.top.tk.focus() self.updatechemicals() def addtempdata(self, event=None): name = self.chemicals_list[0] if self.top is None: self.top = CapSimWindow(master=self.master, buttons=2) self.top.make_window( DatabaseEditor(self.top, self.system, self.chemicaldatas[name], self.chemicaldatas, editflag=0, tempflag=1)) self.top.tk.mainloop() if self.top.window.cancelflag == 0: self.chemicaldatas[ self.top.window.name.get()].get_chemicaldata( self.top.window) if self.top is not None: self.top.destroy() self.top = None elif self.top is not None: tkmb.showerror( title=self.system.version, message= 'Please close the existing parameter input window first.') self.top.tk.focus() self.updatechemicals() def editchemicaldata(self, name): if self.top is None: self.top = CapSimWindow(master=self.master, buttons=2) self.top.make_window( DatabaseEditor(self.top, self.system, self.chemicaldatas[name], self.chemicaldatas, editflag=1, tempflag=0)) self.top.tk.mainloop() if self.top.window.cancelflag == 0: self.chemicaldatas[name].get_chemicaldata(self.top.window) if self.top is not None: self.top.destroy() self.top = None elif self.top is not None: tkmb.showerror( title=self.system.version, message= 'Please close the existing parameter input window first.') self.top.tk.focus() self.updatechemicals() def deletechemicaldata(self, name): if self.top is None: self.top = CapSimWindow(master=self.master, buttons=2) self.top.make_window( DatabaseDeleter(self.top, self.system, self.chemicaldatas[name])) self.top.tk.mainloop() if self.top.window.cancelflag == 0: self.chemicaldatas[name].get_chemicaldata(self.top.window) if self.top.window.cancelflag == 2: self.chemicaldatas[name].remove_chemicalwidgets() del self.chemicaldatas[name] if self.top is not None: self.top.destroy() self.top = None self.updatechemicals() def cancel(self, event=None): self.exitflag = 1 self.frame.quit() def OK(self, event=None): """Finish and move on.""" self.database = {} for name in self.chemicals_list: chemicaldata = self.chemicaldatas[name] index = self.chemicals_list.index(name) self.database[name] = ChemicalDatabase(chemicaldata.name, chemicaldata.formula, index + 1, chemicaldata.MW) for temp in chemicaldata.temps: Dw = chemicaldata.Dw[temp] Kow = chemicaldata.Kow[temp] density = chemicaldata.density[temp] Ref = chemicaldata.Ref[temp] Koc = chemicaldata.Koc[temp] Kdoc = chemicaldata.Kdoc[temp] Kf = chemicaldata.Kf[temp] N = chemicaldata.N[temp] self.database[name].add_properties(temp, Kow, density, Ref, Dw, Koc, Kdoc, Kf, N) self.exitflag = 1 self.frame.quit()
def run(): root = Tk() root.resizable(0, 0) def url_check(event): checked_url = url_format_correct(url_entry.get()) if checked_url == 'URL correct': url_status.configure(text=checked_url, foreground='green') url_status.update() start_pysoar() else: url_status.configure(text=checked_url, foreground='red') url_status.update() def go_bugform(event): import webbrowser form_url = settings.debug_form_url versionID = settings.pysoar_version_formID urlID = settings.competition_url_formID pysoar_version = settings.version comp_url = url_entry.get() complete_url = '%s?entry.%s=%s&entry.%s=%s' % (form_url, versionID, pysoar_version, urlID, comp_url) webbrowser.open(complete_url) def start_pysoar(): settings = Settings() soaring_spot_info = SoaringSpotImport() competition_day = CompetitionDay() soaring_spot_info.load(url_entry.get()) for index in range(len(soaring_spot_info.file_urls)): while not os.path.exists(soaring_spot_info.igc_directory + "/" + soaring_spot_info.file_names[index]): soaring_spot_info.download_flight(index) time.sleep(0.1) soaring_spot_info.flights_downloaded += 1 download_progress.configure(text='Downloaded: ' + str(soaring_spot_info.flights_downloaded) + '/' + str(len(soaring_spot_info.file_names))) download_progress.update() if settings.debugging: soaring_spot_info.save(settings) for ii in range(len(soaring_spot_info.file_names)): file_name = soaring_spot_info.file_names[ii] ranking = soaring_spot_info.rankings[ii] competition_day.file_paths.append(soaring_spot_info.igc_directory + file_name) competition_day.flights.append(Flight(file_name, ranking)) competition_day.flights[-1].read_igc(competition_day, soaring_spot_info) competition_day.write_task() if competition_day.multi_start: url_status.configure(text="Multiple starting points not implemented!", foreground='red') url_status.update() return if settings.debugging: competition_day.save() for flight in competition_day.flights: print flight.file_name flight.determine_tsk_times(competition_day) flight.save(soaring_spot_info) flight.phases = FlightPhases(competition_day) flight.phases.determine_phases(settings, competition_day, flight) if settings.debugging: flight.phases.save(soaring_spot_info, flight) flight.phases.determine_point_statistics(flight, competition_day) flight.performance = Performance(competition_day, flight) flight.performance.determine_performance(flight, competition_day) soaring_spot_info.flights_analyzed += 1 analysis_progress.configure(text='Analyzed: ' + str(soaring_spot_info.flights_analyzed) + '/' + str(len(soaring_spot_info.file_names))) analysis_progress.update() excel_sheet = ExcelExport(settings, competition_day) excel_sheet.write_file(competition_day, settings, soaring_spot_info) analysis_done = Button(root, text='Excel produced', command=open_analysis_file) analysis_done.grid(row=6, column=0, pady=5) print "Analysis complete, excel produced" title = Label(root, text=' PySoar', font=("Helvetica", 30)) url_accompanying_text = Label(root, text='Give Soaringspot URL:') url_entry = Entry(root, width=60) url_confirmation = Button(root, text='ok') url_confirmation.bind('<Button-1>', url_check) url_status = Label(root, text='', foreground='red') download_progress = Label(root, text='Downloaded: ') analysis_progress = Label(root, text='Analyzed: ') report_problem = Button(root, text='Report problem') report_problem.bind('<Button-1>', go_bugform) root.bind('<Return>', url_check) version = Label(root, text='v %s' % settings.version) title.grid(row=0, column=0) url_accompanying_text.grid(row=1, column=0, sticky=W) url_entry.grid(row=2, column=0) url_confirmation.grid(row=2, column=1) url_status.grid(row=3, column=0) download_progress.grid(row=4, column=0, pady=5) analysis_progress.grid(row=5, column=0, pady=5) report_problem.grid(row=7, column=0, sticky=W) version.grid(row=7, column=1, sticky=E) root.mainloop()
if __name__ == "__main__": print "Creating animation server" if os.path.exists(SOCKET_NAME): os.remove(SOCKET_NAME) server = Animator(AnimationRequestHandler, SIMULATE) if not SIMULATE: print "Starting animation server..." print "Animation server is running on socket {0}".format(SOCKET_NAME) print "Quit the server with CONTROL-C." server.serve_forever() else: print "Starting simulation..." button_window = Toplevel() button_window.title('Button Input') img = PhotoImage(file="easy_button.gif") single_easy_button = Button(button_window, image=img) single_easy_button.pack() single_easy_button.bind( "<Button-1>", lambda e: server.processCommand(ButtonEvent.SINGLEPRESS)) double_easy_button = Button(button_window, text="double tap") double_easy_button.pack() double_easy_button.bind( "<Button-1>", lambda e: server.processCommand(ButtonEvent.DOUBLEPRESS)) mainloop()
class MainMenu: """Creates the main menu for CapSim.""" def __init__(self, master, system): """Constructor method.""" self.version = system.version self.fonttype = system.fonttype self.master = master self.tframe = Frame(master.tframe) self.frame = Frame(master.frame) self.bframe = Frame(master.bframe) self.option = IntVar(value=0) self.filename = StringVar() self.top = None def make_widgets(self): """Create the widgets for the window.""" self.intro = Label( self.tframe, text='Welcome to CapSim: ' + 'Software for Simulating Contaminant ' + 'Transport\nthrough a Sediment Capping ' + 'Environment (CapSim ' + self.version + ')\n\n(c)' + ' 2017 Xiaolong Shen, David Lampert, Xin Zhang and ' + 'Danny Reible\n\n' + 'Unauthorized use prohibited\n\n Last Updates Apr 27 2017\n', justify='left') self.inst = Label(self.frame, text='Please choose from the ' + 'following selections:\n') self.newbutton = Button(self.frame, text='Create new input file', width=20, command=self.master.OK) self.loadbutton = Button(self.frame, text='Load existing input file', width=20, command=self.load) self.graphbutton = Button(self.frame, text='Load existing results', width=20, command=self.graph) self.batchbutton = Button(self.frame, text='Run a batch file', width=20, command=self.batch) self.databutton = Button(self.frame, text='Edit chemical database', width=20, command=self.data) self.solidbutton = Button(self.frame, text='Edit material database', width=20, command=self.soliddata) self.exitbutton = Button(self.frame, text='Exit CapSim', width=20, command=self.master.exit) self.blank1 = Label(self.frame, text='') self.blank2 = Label(self.frame, text='') #display the widgets self.intro.grid(row=0, sticky='W', padx=8) self.inst.grid(row=2, padx=8, pady=1) self.newbutton.grid(row=4, pady=1) self.loadbutton.grid(row=5, pady=1) self.graphbutton.grid(row=6, pady=1) self.batchbutton.grid(row=7, pady=1) self.databutton.grid(row=8, pady=1) self.solidbutton.grid(row=9, pady=1) self.exitbutton.grid(row=10, pady=1) self.blank1.grid(row=11) self.blank2.grid(row=12) #bind the commands to the keyboard self.newbutton.bind('<Return>', self.master.OK) self.loadbutton.bind('<Return>', self.load) self.batchbutton.bind('<Return>', self.batch) self.databutton.bind('<Return>', self.data) self.solidbutton.bind('<Return>', self.soliddata) self.exitbutton.bind('<Return>', self.master.exit) self.focusbutton = self.newbutton def load(self, event=None): """Get input file choice.""" self.option.set(1) filename = tkfd.askopenfilename(initialdir=Filepath + r'/input_cpsm_files', filetypes=[('CPSM files', '*.cpsm')]) if filename == '': self.option.set(6) self.filename.set(filename) self.frame.quit() def batch(self, event=None): """Run a batch file.""" self.option.set(2) self.frame.quit() def graph(self, event=None): """Run a batch file.""" self.option.set(3) self.frame.quit() def data(self, event=None): """Add new compound to database.""" self.option.set(4) self.frame.quit() def soliddata(self, event=None): """Add new compound to database.""" self.option.set(5) self.frame.quit() def help(self, event=None): """Show the help file.""" self.option.set(6) self.frame.quit()
if __name__ == '__main__': try: from Tkinter import Tk except ImportError: from tkinter import Tk fenetre = Tk() frame_test_1 = Frame() btn_test_1 = Button(frame_test_1, text='test') btn_test_1.pack() test = Tabs( fenetre, [ {'title' : 'test1'}, {'content' : Entry()}, {'title' : 'test2', 'content' : frame_test_1} ], bg='yellow', border=1, relief='raised' ) test.pack(side='top', expand='yes', fill='both') btn_test_2 = Button(text='add') btn_test_2.bind('<Button-1>', lambda event: test.add_tabs([{'title' : 'after'}])) test.add_tabs([{'content' : btn_test_2}]) btn_test_1.bind('<Button-1>', lambda event: test.delete_tabs_by_index(1)) btn_test_3 = Button(text='delete by value') btn_test_3.bind('<Button-1>', lambda event: test.delete_tabs_by_value(btn_test_2)) test.add_tabs([{'content' : btn_test_3}]) fenetre.mainloop()
class ChemicalImporter: def __init__(self, master, system, database): """The constructor method.""" self.version = system.version self.fonttype = system.fonttype self.sfont = get_superfont(self.fonttype) self.master = master self.frame = Frame(master.frame) self.tframe = Frame(master.tframe) self.bframe = Frame(master.bframe) self.tkfont = tkFont.Font(font=system.fonttype) self.chemicals_list = database.keys() self.chemicals_list.sort() self.name = StringVar() self.formula = StringVar() self.MW = DoubleVar() self.temp = DoubleVar(value=0) self.Dw = DoubleVar(value=0) self.Ref = StringVar(value=0) self.Koc = DoubleVar(value=0) self.Kdoc = DoubleVar(value=0) self.Kf = DoubleVar(value=0) self.N = DoubleVar(value=0) self.importedchemicals = {} for name in self.chemicals_list: self.importedchemicals[name] = ChemicalData(name) self.importedchemicals[name].read_database(database[name]) self.name_width = 10 self.ref_width = 10 for chemical_name in self.chemicals_list: if (self.tkfont.measure(chemical_name) + 10) > self.name_width: self.name_width = self.tkfont.measure(chemical_name) + 10 for temp in self.importedchemicals[chemical_name].temps: if (self.tkfont.measure( self.importedchemicals[chemical_name].Ref[temp]) + 10) > self.name_width: self.name_width = self.tkfont.measure( self.importedchemicals[chemical_name].Ref[temp]) + 10 if self.name_width < 150: self.name_width = 150 if self.ref_width < 150: self.ref_width = 150 self.cancelflag = 0 self.sname = StringVar(self.frame, value='') def make_widgets(self): self.instructions = Label( self.tframe, text='Please select the chemical you would like to add ') self.leftcolumn = Label(self.tframe, text=' ', width=2) self.checkcolumn = Label(self.tframe, text=' ', width=5) self.orinamecolumn = Label( self.tframe, text=' ', width=int(self.name_width * 1.1424219345 / 8) + 1) self.tempcolumn = Label(self.tframe, text=' ', width=15) self.ref1column = Label( self.tframe, text=' ', width=int(self.ref_width * 1.1424219345 / 8 / 2) + 1) self.ref2column = Label( self.tframe, text=' ', width=int(self.ref_width * 1.1424219345 / 8 / 2) + 1) self.rightcolumn = Label(self.tframe, text=' ', width=2) self.search_label = Label(self.tframe, text='Search:') self.search_entry = Entry(self.tframe, textvariable=self.sname) self.namelabel = Label(self.tframe, text='Name') self.templabel = Label(self.tframe, text='Temperature') self.reflabel = Label(self.tframe, text='Reference') self.botleftcolumn = Label(self.frame, text=' ', width=2) self.botcheckcolumn = Label(self.frame, text=' ', width=5) self.botorinamecolumn = Label( self.frame, text=' ', width=int(self.name_width * 1.1424219345 / 8) + 1) self.bottempcolumn = Label(self.frame, text=' ', width=15) self.botref1column = Label( self.frame, text=' ', width=int(self.ref_width * 1.1424219345 / 8 / 2) + 1) self.botref2column = Label( self.frame, text=' ', width=int(self.ref_width * 1.1424219345 / 8 / 2) + 1) self.botrightcolumn = Label(self.frame, text=' ', width=2) self.importbutton = Button(self.bframe, text='Import', command=self.OK, width=20) self.cancelbutton = Button(self.bframe, text='Cancel', command=self.cancel, width=20) self.blank1 = Label(self.tframe, text=' ') self.blank2 = Label(self.frame, text=' ') self.blank3 = Label(self.bframe, text=' ') self.blank4 = Label(self.bframe, text=' ') #show the widgets on the grid (top to bottom and left to right) self.instructions.grid(row=0, columnspan=5, sticky='W', padx=8) self.leftcolumn.grid(row=1, column=0, sticky='WE') self.checkcolumn.grid(row=1, column=1, sticky='WE') self.orinamecolumn.grid(row=1, column=2, sticky='WE') self.tempcolumn.grid(row=1, column=3, sticky='WE') self.ref1column.grid(row=1, column=4, sticky='WE') self.ref2column.grid(row=1, column=5, sticky='WE') self.rightcolumn.grid(row=1, column=6, sticky='WE') self.search_label.grid(row=2, column=1, sticky='E', padx=4) self.search_entry.grid(row=2, column=2, columnspan=4, sticky='WE', padx=4) self.blank1.grid(row=3) self.namelabel.grid(row=4, column=2, sticky='WE') self.templabel.grid(row=4, column=3, sticky='WE') self.reflabel.grid(row=4, column=4, columnspan=2, sticky='WE') self.botleftcolumn.grid(row=1, column=0, sticky='WE') self.botcheckcolumn.grid(row=1, column=1, sticky='WE') self.botorinamecolumn.grid(row=1, column=2, sticky='WE') self.bottempcolumn.grid(row=1, column=3, sticky='WE') self.botref1column.grid(row=1, column=4, sticky='WE') self.botref2column.grid(row=1, column=5, sticky='WE') self.botrightcolumn.grid(row=1, column=6, sticky='WE') self.searchname() self.sname.trace('w', self.searchname) def searchname(self, event=None, *args): row = 2 for name in self.chemicals_list: try: self.importedchemicals[name].remove_selectchemicalwidgets() except: pass if self.sname.get() == '': for name in self.chemicals_list: self.importedchemicals[name].selectchemicalwidgets( self.frame, row=row, master=self.master, namewidth=int(self.name_width * 1.1424219345 / 8) + 1, refwidth=int(self.ref_width * 1.1424219345 / 8) + 1) row = row + 1 else: for name in self.chemicals_list: if name.lower()[:len(self.sname.get())].count( self.sname.get().lower()) >= 1: self.importedchemicals[name].selectchemicalwidgets( self.frame, row=row, master=self.master, namewidth=int(self.name_width * 1.1424219345 / 8) + 1, refwidth=int(self.ref_width * 1.1424219345 / 8) + 1) row = row + 1 else: self.importedchemicals[name].check = IntVar( value=self.importedchemicals[name].check) self.blank2.grid(row=row) row = 2 self.blank3.grid(row=row) row = row + 1 self.importbutton.grid(row=row, column=0, columnspan=5, pady=1) row = row + 1 self.cancelbutton.grid(row=row, column=0, columnspan=5, pady=1) row = row + 1 self.blank4.grid(row=row) self.cancelbutton.bind('<Return>', self.cancel) self.focusbutton = self.cancelbutton def selectchemicaldata(self, name): for othername in self.chemicals_list: if othername <> name: try: self.importedchemicals[othername].check.set(0) except: pass def cancelname(self, event=None): self.sname.set('') self.searchname() def OK(self, event=None): for name in self.chemicals_list: if self.importedchemicals[name].check.get() == 1: self.name.set(name) self.formula.set(self.importedchemicals[name].formula) self.MW.set(self.importedchemicals[name].MW) self.temp.set(self.importedchemicals[name].temp.get()) self.Dw.set(self.importedchemicals[name].Dw[self.temp.get()]) self.Ref.set(self.importedchemicals[name].Ref[self.temp.get()]) self.Koc.set(self.importedchemicals[name].Koc[self.temp.get()]) self.Kdoc.set( self.importedchemicals[name].Kdoc[self.temp.get()]) self.Kf.set(self.importedchemicals[name].Kf[self.temp.get()]) self.N.set(self.importedchemicals[name].N[self.temp.get()]) for name in self.chemicals_list: try: self.importedchemicals[name].remove_selectchemicalwidgets() except: pass self.frame.quit() def cancel(self, event=None): self.cancelflag = 1 self.frame.quit()
class SettingsFrame(BasePAFrame): """ фрейм с параметрами """ def __init__(self, *args, **kwargs): BasePAFrame.__init__(self, *args, **kwargs) self.current_file = {} self.last_move_path = settings.BASE_CATALOG self.widgets = OrderedDict( (label, { 'label': Label(self, text=label), 'label_data': Label(self) }) for label in LABELS) # виджеты для преименований self.widgets_with_rename = OrderedDict( (label, { 'label': Label(self, text=label), 'label_data': Label(self) }) for label in LABELS_RENAME) # переименование с моим именем self.w_entry_custom_name = Entry(self) self.w_btn_rename_custom_name = Button(self, text=u'Переименовать') self.w_btn_rename_custom_name.bind( '<Button-1>', self.click_rename_button) self.widgets_with_rename[TEXT_MY_NAME] = { 'label': Label(self, text=TEXT_MY_NAME), 'label_data': self.w_entry_custom_name, 'button_rename': self.w_btn_rename_custom_name, } # доп кнопки, переместить удалить _btn_mv = Button(self, text=u'Переместить') _btn_mv.bind('<Button-1>', self.click_move_button) _btn_rm = Button(self, text=u'Удалить') _btn_rm.bind('<Button-1>', self.click_remove_button) self.buttons = ( (_btn_mv, _btn_rm), ) # прописываем кнопки переместить for label, label_widgets in self.widgets_with_rename.iteritems(): if label in LABELS_RENAME: _btn = Button(self, text=u'Переименовать') _btn.bind('<Button-1>', self.click_rename_button) _btn.meta = {} label_widgets['button_rename'] = _btn def _pa_layout(self): BasePAFrame._pa_layout(self) for index, labels in enumerate(self.widgets.values()): labels['label'].grid(row=index, column=0) labels['label_data'].grid(row=index, column=1) for index, labels in enumerate( self.widgets_with_rename.values(), index+1): labels['label'].grid(row=index, column=0) labels['label_data'].grid(row=index, column=1) labels['button_rename'].grid(row=index, column=2) for row, btns in enumerate(self.buttons, index+1): for col, btn in enumerate(btns): btn.grid(row=row, column=col) def set_file(self, file_path, image): stat = os.stat(file_path) self.current_file['file_path'] = file_path self.current_file['size'] = stat.st_size date_create = datetime.datetime.fromtimestamp(stat.st_ctime) date_modify = datetime.datetime.fromtimestamp(stat.st_mtime) date_access = datetime.datetime.fromtimestamp(stat.st_atime) try: exif_data = image._getexif() except AttributeError: exif_data = None if not exif_data: exif_data = { EXIF_TAGS_REVERSE['DateTimeOriginal']: u'n/d', EXIF_TAGS_REVERSE['DateTimeDigitized']: u'n/d', EXIF_TAGS_REVERSE['DateTime']: u'n/d', } self.widgets[TEXT_FILE_PATH]['label_data']['text'] = ( self.current_file['file_path']) self.widgets[TEXT_IMAGE_SIZE]['label_data']['text'] = ( u'{0} / {1}'.format(*(image.size if image else (0, 0)))) self.widgets[TEXT_SIZE]['label_data']['text'] = ( u'{1} МБ / {0} Б'.format( self.current_file['size'], round(stat.st_size / 1024.0 / 1024, 2)) ) bind_maps = ( (TEXT_DATE_CREATE, date_create.strftime(settings.DATE_TIME_FORMAT)), (TEXT_DATE_MODIFY, date_modify.strftime(settings.DATE_TIME_FORMAT)), (TEXT_DATE_ACCESS, date_access.strftime(settings.DATE_TIME_FORMAT)), (TEXT_EXIF_DATE_ORIGINAL, exif_data.get(EXIF_TAGS_REVERSE['DateTimeOriginal'], u'n/a')), (TEXT_EXIF_DATE_DIGITIZED, exif_data.get(EXIF_TAGS_REVERSE['DateTimeDigitized'], u'n/a')), (TEXT_EXIF_DATE_TIME, exif_data.get(EXIF_TAGS_REVERSE['DateTime'], u'n/a')), ) for text, data in bind_maps: self.widgets_with_rename[text]['label_data'].config(text=data) self.widgets_with_rename[text]['button_rename'].meta['data'] = data def reset(self): self.current_file = {} def click_rename_button(self, event): if not self.current_file: return if event.widget == self.w_btn_rename_custom_name: data = self.w_entry_custom_name.get() re_suffix = "re" if data.startswith(re_suffix): _, re_template, replacer = data.split("|") file_name = os.path.basename(self.current_file['file_path']) finds = re.findall(re_template, file_name)[0] data = replacer.format(*finds) else: self.w_entry_custom_name.delete(0, END) else: meta = event.widget.meta if not meta: return try: date = datetime.datetime.strptime( meta['data'], settings.DATE_TIME_FORMAT) except ValueError: try: date = datetime.datetime.strptime( meta['data'], settings.DATE_TIME_FORMAT_EXIF) except ValueError: return data = date.strftime(date_format) new_file_name = ( u'{0} {1}{2}'.format( data, self.current_file['size'], os.path.splitext(self.current_file['file_path'])[-1])) new_file_dir = os.path.dirname(self.current_file['file_path']) new_file_path = os.path.join(new_file_dir, new_file_name) if new_file_path != self.current_file['file_path']: if os.path.exists(new_file_path): showerror( u'Ошибка', u'Файл ({0}) уже существует, ' u'переименовать невозможно'.format(new_file_path)) else: os.rename(self.current_file['file_path'], new_file_path) self.master.handle_update_files() def click_move_button(self, event): """ переместить файл :param event: :return: """ if self.current_file: path = askdirectory( title=u'Выберите папку для перемещения', initialdir=self.last_move_path) if not path: return self.last_move_path = path src = self.current_file['file_path'] file_name = os.path.basename(src) dst = os.path.join(path, file_name) os.rename(src, dst) self.master.reset() self.master.handle_update_files() def click_remove_button(self, event): # error, info, question, or warning if askyesno( u'Удалить файл?', self.current_file['file_path'], icon='warning'): os.remove(self.current_file['file_path']) self.master.reset() self.master.handle_update_files()
class TopLevel(Frame): def __init__(self, parent): Frame.__init__(self, parent, background="gray") self.parent = parent self.init_global_vars() self.init_UI() self.detect_debug_mode() self.set_state_stopped() def init_global_vars(self): self.switch_status = 'none' self.home_result = IntVar() self.move_result = IntVar() self.timer_active = IntVar() self.test_active = False self.test_paused = False self.timer = [0, 0] self.timer_reset_val = [0, 0] #self.active_cycle = 0 #self.active_temp = 'foo' #self.up_motor_res = 2 #self.right_motor_res = 2 self.move_motor_resolution = 2 self.up_full_steps = 3200 self.right_full_steps = 7200 self.debug_mode = False self.event_schedule = [] self.move_total_duration = 0 self.move_direction = '' self.move_started_time = datetime.now() self.pause_time = datetime.now() self.resume_time = datetime.now() self.planned_steps = 0 def init_UI(self): self.parent.title('Liquid Thermal Shock Tester v0.2') self.pack(fill=BOTH, expand=True) options_frame = Frame(self, background='gray', pady=5, padx=5) options_frame.pack(side=LEFT, fill=BOTH, expand=True) options_label = Label(options_frame, text='Test Setup', background='gray', font=('Courier', 22, 'bold'), justify=LEFT) ul_bold_font = Font(options_label, options_label.cget('font')) ul_bold_font.configure(underline=True) options_label.configure(font=ul_bold_font) options_label.pack(anchor=CENTER, side=TOP, padx=5, pady=5) cycles_frame = Frame(options_frame, background='gray', pady=5) cycles_frame.pack(side=TOP, fill=BOTH, expand=True) cycles_label = Label(cycles_frame, text='# of cycles', background='gray', font=('Courier', 12), justify=CENTER) cycles_label.grid(row=0, column=0, rowspan=1, columnspan=2, sticky='news') ul_plain_font = Font(cycles_label, cycles_label.cget('font')) ul_plain_font.configure(underline=True) cycles_label.configure(font=ul_plain_font) self.cycles_select_disp = Label(cycles_frame, text='5', background='white', font=('Courier', 32)) self.cycles_select_disp.grid(row=1, column=0, rowspan=2, columnspan=1, sticky='wens', padx=5, pady=5) self.cycles_increase_button = Button(cycles_frame, text=u'\u25b2', font=('Courier', 18, 'bold'), command=self.cycles_increment) self.cycles_increase_button.grid(row=1, column=1, rowspan=1, columnspan=1, sticky='wens', padx=5, pady=5) self.cycles_decrease_button = Button(cycles_frame, text=u'\u25BC', font=('Courier', 18, 'bold'), command=self.cycles_decrement) self.cycles_decrease_button.grid(row=2, column=1, rowspan=1, columnspan=1, sticky='wens', padx=5, pady=5) self.fix_grid(cycles_frame) soak_time_frame = Frame(options_frame, background='gray', pady=5) soak_time_frame.pack(side=TOP, fill=BOTH, expand=True) soak_time_label = Label(soak_time_frame, text='Minutes per Soak', background='gray', font=('Courier', 12), justify=CENTER) soak_time_label.grid(row=0, column=0, rowspan=1, columnspan=2, sticky='news') soak_time_label.configure(font=ul_plain_font) self.soak_time_disp = Label(soak_time_frame, text='5', background='white', font=('Courier', 32)) self.soak_time_disp.grid(row=1, column=0, rowspan=2, columnspan=1, sticky='wens', padx=5, pady=5) self.soak_time_increment_button = Button( soak_time_frame, text=u'\u25b2', font=('Courier', 18, 'bold'), command=self.soak_time_increment) self.soak_time_increment_button.grid(row=1, column=1, rowspan=1, columnspan=1, sticky='wens', padx=5, pady=5) self.soak_time_decrement_button = Button( soak_time_frame, text=u'\u25BC', font=('Courier', 18, 'bold'), command=self.soak_time_decrement) self.soak_time_decrement_button.grid(row=2, column=1, rowspan=1, columnspan=1, sticky='wens', padx=5, pady=5) self.fix_grid(soak_time_frame) controls_frame = Frame(self, background='gray') controls_frame.pack(side=LEFT, fill=BOTH, expand=True) run_pause_frame = Frame(controls_frame, background='gray') run_pause_frame.pack(side=TOP, fill=BOTH, expand=True, pady=5) self.run_button = Button(run_pause_frame, text='RUN', background='green', activebackground='green', font=('Courier', 30, 'bold'), width=5, command=self.run_init) self.run_button.grid(row=0, column=0, sticky='wens', padx=5, pady=5) self.pause_button = Button(run_pause_frame, text='PAUSE', background='orange', activebackground='orange', font=('Courier', 30, 'bold'), width=5, command=self.pause_button_pressed) self.pause_button.grid(row=0, column=1, sticky='wens', padx=5, pady=5) self.fix_grid(run_pause_frame) stop_button = Button(controls_frame, text='STOP', background='red', activebackground='red', font=('Courier', 36, 'bold'), command=self.stop_test) stop_button.pack(side=TOP, fill=BOTH, expand=True, padx=5) jog_frame = Frame(controls_frame, background='gray') jog_frame.pack(side=TOP, fill=BOTH, expand=True, pady=5) jog_label = Label(jog_frame, text='Motor\rjog', font=('Courier', 12, 'bold'), background='gray') jog_label.grid(row=1, column=1) self.jog_up_button = Button(jog_frame, text=u'\u25b2', font=('Courier', 18, 'bold')) self.jog_up_button.grid(row=0, column=1, rowspan=1, columnspan=1, sticky='wens', padx=5, pady=5) self.jog_up_button.bind("<Button-1>", self.jog_up_on) self.jog_up_button.bind("<ButtonRelease-1>", self.jog_off) self.jog_left_button = Button(jog_frame, text=u'\u25C4', font=('Courier', 18, 'bold')) self.jog_left_button.grid(row=1, column=0, rowspan=1, columnspan=1, sticky='wens', padx=5, pady=5) self.jog_left_button.bind("<Button-1>", self.jog_left_on) self.jog_left_button.bind("<ButtonRelease-1>", self.jog_off) self.jog_right_button = Button(jog_frame, text=u'\u25BA', font=('Courier', 18, 'bold')) self.jog_right_button.grid(row=1, column=2, rowspan=1, columnspan=1, sticky='wens', padx=5, pady=5) self.jog_right_button.bind("<Button-1>", self.jog_right_on) self.jog_right_button.bind("<ButtonRelease-1>", self.jog_off) self.jog_down_button = Button(jog_frame, text=u'\u25BC', font=('Courier', 18, 'bold')) self.jog_down_button.grid(row=2, column=1, rowspan=1, columnspan=1, sticky='wens', padx=5, pady=5) self.jog_down_button.bind("<Button-1>", self.jog_down_on) self.jog_down_button.bind("<ButtonRelease-1>", self.jog_off) self.fix_grid(jog_frame) status_frame = Frame(self, background='gray') status_frame.pack(side=LEFT, fill=BOTH, expand=True, padx=5, pady=5) status_label = Label(status_frame, text='Tester Status', background='gray', font=('Courier', 22, 'bold'), justify=LEFT) status_label.configure(font=ul_bold_font) status_label.pack(anchor=CENTER, side=TOP, padx=5, pady=5) self.status_disp = Text(status_frame) self.status_disp.pack(side=TOP, fill=BOTH, padx=5, pady=5) self.status_disp.configure(state='disabled') self.power_button = Button(status_frame, text='POWER OFF', font=('Courier', 24, 'bold'), background="red", activebackground="red", command=self.shutdown, height=2) self.power_button.pack(side=TOP, fill=BOTH, padx=5, pady=5) def fix_grid(self, target_frame): [columns, rows] = target_frame.grid_size() for i in range(rows): target_frame.rowconfigure(i, weight=1) for j in range(columns): target_frame.columnconfigure(j, weight=1) def detect_debug_mode(self): if str(sys.argv[0]) == 'debug': self.update_status('Tester is in debug mode.', 'newline') self.update_status('', 'newline') self.update_status('The tester will run with a 6 second', 'newline') self.update_status(' soak time regardless of the soak', 'newline') self.update_status(' time selected in the GUI.', 'newline') self.debug_mode = True else: self.update_status('Welcome to the Liquid Thermal Shock', 'newline') self.update_status(' Tester. Select the number of', 'newline') self.update_status(' cycles and the soak time per cycle', 'newline') self.update_status(' to begin testing. Please ensure', 'newline') self.update_status(' that the limit switches are free', 'newline') self.update_status(' from obstructions prior to running', 'newline') self.update_status(' a test.', 'newline') self.debug_mode = False def cycles_increment(self): """ Increments the number of cycles per test. """ str_num_cycles = self.cycles_select_disp.cget('text') num_cycles = int(str_num_cycles) num_cycles += 1 self.cycles_select_disp.configure(text=str(num_cycles)) def cycles_decrement(self): """ Decrements the number of cycles per test. """ str_num_cycles = self.cycles_select_disp.cget('text') num_cycles = int(str_num_cycles) # Check for attempts to set num_cycles < 1. if num_cycles <= 1: self.cycles_select_disp.configure(text=str(num_cycles)) else: num_cycles -= 1 self.cycles_select_disp.configure(text=str(num_cycles)) def soak_time_increment(self): """ Increments the soak time. """ str_soak_time = self.soak_time_disp.cget('text') soak_time = int(str_soak_time) soak_time += 1 self.soak_time_disp.configure(text=str(soak_time)) self.reset_timer() def soak_time_decrement(self): """ Decrements the soak time. """ str_soak_time = self.soak_time_disp.cget('text') soak_time = int(str_soak_time) # Check for attempts to set soak time < 1. if soak_time <= 1: self.soak_time_disp.configure(text=str(soak_time)) else: soak_time -= 1 self.soak_time_disp.configure(text=str(soak_time)) self.reset_timer() def reset_timer(self): """ Resets the timer to whatever is displayed in the soak time window.""" str_soak_time = self.soak_time_disp.cget('text') if self.debug_mode: self.timer = [0, 6] else: self.timer = [int(str_soak_time), 0] # Use line below for tester debugging -- forces a 5 second soak time. # Comment out for normal operations. # self.timer = [0, 5] # Callback functions for manual motor jog def jog_off(self, event): motors_off() def jog_up_on(self, event): jog_motor('up') def jog_down_on(self, event): jog_motor('down') def jog_left_on(self, event): jog_motor('left') def jog_right_on(self, event): jog_motor('right') def shutdown(self): """ Shuts down the tester. """ motors_off() confirm_string = "Do you really want to power down the tester?" confirm = tkMessageBox.askokcancel("Shutdown", confirm_string) if confirm: subprocess.call("sudo poweroff", shell=True) else: pass def update_status(self, new_text, writemode): """ Prints text to the tester status window. """ self.status_disp.configure(state='normal') if writemode == 'overwrite': self.status_disp.delete('end-1c linestart', 'end') self.status_disp.insert('end', '\n' + new_text) self.status_disp.see(END) self.status_disp.configure(state='disabled') def append_event(self, cycle, type, destination, direction, steps, duration): """ Add new event (motor move or temperature soak) to event schedule. """ self.event_schedule.append({ 'Cycle': cycle, 'Event type': type, 'Destination': destination, 'Direction': direction, 'Steps': steps, 'Duration': duration }) def start_homing_move(self, direction): """ Starts the homing procedure in the given direction. """ self.update_status('Finding ' + direction + ' home position...', 'newline') self.status_disp.update() self.home_result.set(0) self.queue = Queue.Queue() Find_Home_Nonblocking(self.queue, direction).start() self.master.after(100, self.process_homing_queue) self.wait_variable(self.home_result) if self.home_result.get() == 0: self.update_status('Homing error. Test aborted.', 'newline') return else: self.update_status( direction.capitalize() + ' home position found.', 'newline') def run_init(self): """ Run button callback. Collects run parameters, creates event schedule, then runs the series of scheduled events. """ self.set_state_running() # Set number of steps for each motor move. Depends on motor resolution # set in static variables section. up_steps = self.up_full_steps * (2**self.move_motor_resolution) right_steps = self.right_full_steps * (2**self.move_motor_resolution) # Get the total number of cycles total_cycles_str = self.cycles_select_disp.cget('text') total_cycles_int = int(total_cycles_str) # Get the soak time in minutes. This is forced to 0.1 minutes when # the GUI is launched in debug mode if self.debug_mode: soak_time_str = '0.1' soak_time_float = 0.1 else: soak_time_str = self.soak_time_disp.cget('text') soak_time_float = float(soak_time_str) # Build event schedule self.event_schedule = [] for i in range(1, total_cycles_int + 1): self.append_event(i, 'move', 'hot', 'down', up_steps, up_steps / 2000.0) self.append_event(i, 'soak', 'hot', '', '', soak_time_float) self.append_event(i, 'move', 'cold', 'up', up_steps, up_steps / 2000.0) self.append_event(i, 'move', 'cold', 'left', right_steps, right_steps / 2000.0) self.append_event(i, 'move', 'cold', 'down', up_steps, up_steps / 2000.0) self.append_event(i, 'soak', 'cold', '', '', soak_time_float) self.append_event(i, 'move', 'hot', 'up', up_steps, up_steps / 2000.0) self.append_event(i, 'move', 'hot', 'right', right_steps, right_steps / 2000.0) # Set the destination to 'complete' for the final 'up' and 'right' moves. # Edit the 'Steps' parameter of the final move to end the test in the # center of the rail. self.event_schedule[-2]['Destination'] = 'complete' self.event_schedule[-1]['Destination'] = 'complete' self.event_schedule[-1]['Steps'] = right_steps / 2 self.event_schedule[-1][ 'Duration'] = self.event_schedule[-1]['Steps'] / 2000.0 self.test_active = True # Print initial runtime message to status window if soak_time_float == 1.0: soak_time_out = '1 minute' else: soak_time_out = soak_time_str + ' minutes' self.update_status('', 'newline') self.update_status('Test started.', 'newline') out_string = 'The tester will run for ' + total_cycles_str + ' cycles, ' self.update_status(out_string, 'newline') out_string = soak_time_out + ' per cycle.' self.update_status(out_string, 'newline') if self.test_active == True: self.start_homing_move('up') if self.test_active == True and self.home_result.get() == 1: self.start_homing_move('right') if self.test_active == True and self.home_result.get() == 1: self.update_status('Moving to hot position...', 'newline') self.run_scheduled_events() def run_scheduled_events(self): """ Runs the series of events listed in self.event_schedule. """ if self.test_active == True: current_event = self.event_schedule.pop(0) if current_event['Event type'] == 'soak': self.set_state_running() self.reset_timer() cycle = str(current_event['Cycle']) temperature = current_event['Destination'] self.timer_active.set(1) self.countdown_timer(cycle, temperature) self.wait_variable(self.timer_active) elif current_event['Event type'] == 'move': if current_event['Direction'] == 'up': self.set_state_running() if current_event['Destination'] == 'complete': out_string = 'Test complete, moving to neutral ' out_string += ' position...' self.update_status(out_string, 'newline') else: out_string = 'Moving to ' + current_event['Destination'] out_string += ' position...' self.update_status(out_string, 'newline') elif current_event['Direction'] == 'down': self.set_state_running() else: self.pause_button.config(state='normal') self.move_direction = current_event['Direction'] self.move_total_duration = current_event['Duration'] self.planned_steps = current_event['Steps'] #self.move_result.set(0) self.queue = Queue.Queue() self.move_started_time = datetime.now() Move_Motor_Nonblocking(self.queue, current_event['Direction'], self.move_motor_resolution, current_event['Steps']).start() self.master.after(100, self.process_move_queue) self.wait_variable(self.move_result) motors_off() # If there are any events left in the schedule, run the next scheduled # event. If there are no events left in the schedule and the last event # was a completed move, then the test is complete and this function should # output the 'test complete' message. If there are no events in the schedule # and the last event was not a completed move, then the test is paused and # this function should do nothing else. if self.event_schedule: self.after(1000, self.run_scheduled_events) elif self.move_result.get() == 1: self.update_status('Test complete.', 'overwrite') self.set_state_stopped() else: pass def set_state_running(self): """ Deactivates cycle time select, soak time select, motor jog and power off buttons. This is to stop users from changing test parameters during a running test, which could result in some difficult to handle undefined states. """ self.cycles_increase_button.config(state='disabled') self.cycles_decrease_button.config(state='disabled') self.soak_time_increment_button.config(state='disabled') self.soak_time_decrement_button.config(state='disabled') self.run_button.config(state='disabled') self.jog_up_button.config(state='disabled') self.jog_down_button.config(state='disabled') self.jog_left_button.config(state='disabled') self.jog_right_button.config(state='disabled') self.power_button.config(state='disabled') self.pause_button.config(state='disabled') # This is absurd, but apparently setting a button to 'disabled' does # not actually disable the button event bindings, so binding the buttons # to a 'do_nothing()' function is required. self.jog_up_button.bind("<Button-1>", self.do_nothing) self.jog_up_button.bind("<ButtonRelease-1>", self.do_nothing) self.jog_down_button.bind("<Button-1>", self.do_nothing) self.jog_down_button.bind("<ButtonRelease-1>", self.do_nothing) self.jog_left_button.bind("<Button-1>", self.do_nothing) self.jog_left_button.bind("<ButtonRelease-1>", self.do_nothing) self.jog_right_button.bind("<Button-1>", self.do_nothing) self.jog_right_button.bind("<ButtonRelease-1>", self.do_nothing) def set_state_stopped(self): """ Reactivates all of the buttons deactivated in the set_state_running function. """ self.test_active = False self.test_paused = False self.cycles_increase_button.config(state='normal') self.cycles_decrease_button.config(state='normal') self.soak_time_increment_button.config(state='normal') self.soak_time_decrement_button.config(state='normal') self.run_button.config(state='normal') self.jog_up_button.config(state='normal') self.jog_down_button.config(state='normal') self.jog_left_button.config(state='normal') self.jog_right_button.config(state='normal') self.power_button.config(state='normal') self.pause_button.config(state='disabled') self.pause_button.config(text='PAUSE', background='orange', activebackground='orange') self.jog_up_button.bind("<Button-1>", self.jog_up_on) self.jog_up_button.bind("<ButtonRelease-1>", self.jog_off) self.jog_down_button.bind("<Button-1>", self.jog_down_on) self.jog_down_button.bind("<ButtonRelease-1>", self.jog_off) self.jog_left_button.bind("<Button-1>", self.jog_left_on) self.jog_left_button.bind("<ButtonRelease-1>", self.jog_off) self.jog_right_button.bind("<Button-1>", self.jog_right_on) self.jog_right_button.bind("<ButtonRelease-1>", self.jog_off) def do_nothing(self, event): """ Does absolutely nothing. This is a workaround for the fact that button event bindings are not disabled when a button's state is set to 'disabled'. """ pass def pause_timer(self): """ Displays the running duration of a test pause. """ if self.test_paused: timer_string = '{0:1d}:{1:02d}'.format(self.timer[0], self.timer[1]) out_string = 'Test paused for ' + timer_string self.update_status(out_string, 'overwrite') self.timer[1] += 1 if self.timer[1] >= 60: self.timer[0] += 1 self.timer[1] -= 60 self.after(1000, self.pause_timer) def countdown_timer(self, cycle, temperature): """ Displays countdown timer and current cycle number/temperature information in status window. This function will only process if the timer_active flag is set to 1. The function will then recursively call itself after a 1 second wait until the timer_active flag is set to zero. The timing is not precise because it will wait 1 full second between function calls, and therefore does not take into account the time necessary to process the function itself. However, over a typical soak time this will only amount to milliseconds, so it's certainly close enough for this application. """ if self.timer_active.get() == 1: timer_string = '{0:1d}:{1:02d}'.format(self.timer[0], self.timer[1]) out_string = 'Cycle ' + cycle + ' of ' out_string += self.cycles_select_disp.cget('text') + ', ' out_string += temperature + '. ' + timer_string + ' remaining.' self.update_status(out_string, 'overwrite') # Decrement 1 second from timer. If this flips the seconds to a # negative value, decrement 1 minute and add 60 seconds self.timer[1] -= 1 if self.timer[1] < 0: # If timer is run down to zero, display soak complete message # and set timer_active flag to zero. if self.timer[0] <= 0: out_string = 'Cycle ' + cycle + ' of ' out_string += self.cycles_select_disp.cget('text') + ', ' out_string += temperature + ' complete.' self.update_status(out_string, 'overwrite') self.timer_active.set(0) else: self.timer[0] -= 1 self.timer[1] += 60 # Have the countdown_timer function recursively call itself # after 1000ms. self.after(1000, self.countdown_timer, cycle, temperature) def stop_test(self): """ Stop button callback. Allows user to abort test sequence. """ # Clear event schedule and toggle home and move result monitoring # variables. This helps prevent errors on restart motors_off() self.event_schedule = [] self.home_result.set(0) self.move_result.set(0) if self.test_active: self.update_status('Test stopped by user.', 'newline') self.test_active = False # Stop and reset timer, reactivate buttons (in case the test # needs to be restarted). self.timer_active.set(0) self.reset_timer() self.set_state_stopped() def pause_button_pressed(self): """ Pause button callback. """ if self.test_paused: self.test_paused = False self.resume_test() else: self.test_paused = True self.timer = [0, 0] self.pause_test() def pause_test(self): """ Pauses a running test """ motors_off() self.pause_time = datetime.now() self.pause_button.config(text='RESUME', background='green', activebackground='green') self.resume_schedule = self.event_schedule self.event_schedule = [] self.move_result.set(0) pause_delta = self.pause_time - self.move_started_time pause_delta_seconds = float(pause_delta.seconds) pause_delta_seconds += pause_delta.microseconds / 1000000.0 steps_prepause = int(pause_delta_seconds * 2000) steps_remaining = self.planned_steps - steps_prepause move_time_remaining = self.move_total_duration - pause_delta_seconds resume_event = { 'Cycle': '', 'Event type': 'move', 'Destination': '', 'Direction': self.move_direction, 'Steps': steps_remaining, 'Duration': move_time_remaining } self.resume_schedule.insert(0, resume_event) self.update_status('', 'newline') self.pause_timer() def resume_test(self): """ Resumes a paused test """ self.pause_button.config(text='PAUSE', background='orange', activebackground='orange') self.resume_time = datetime.now() self.event_schedule = self.resume_schedule pause_duration = self.resume_time - self.pause_time pause_duration_seconds = float(pause_duration.seconds) pause_duration_seconds += pause_duration.microseconds / 1000000.0 self.test_active = True self.update_status('Test resumed.', 'newline') self.run_scheduled_events() def process_homing_queue(self): """ Checks if homing function has returned a value. """ # Try to read the first value in the queue. If nothing is there, then # the homing function has not yet returned a value and must still be # active. In this case, the function recursively calls itself after # 100ms. If there is something in the queue, the value is read into # the self.home_result variable and the function is not called again. try: self.home_result.set(self.queue.get(0)) except Queue.Empty: self.master.after(10, self.process_homing_queue) def process_move_queue(self): """ Checks if motor move queue as returned value. """ # Try to read the first value in the queue. If nothing is there, then # the motor move function has not yet returned a value and must still be # active. In this case, the function recursively calls itself after # 100ms. If there is something in the queue, the value is read into # the self.move_result variable and the function is not called again. try: self.move_result.set(self.queue.get(0)) except Queue.Empty: self.master.after(100, self.process_move_queue)
class LeftNavView(Canvas): def __init__(self, controller, parent): # prev: def __init__(self, main_window, player_, left_nav): self.controller = controller self.parent = parent self.app = self.parent.app self.enabled = False def build(self): if self.enabled: self.redraw() else: self.build_left_nav_menu() self.enabled = True def build_left_nav_menu(self): app = self.app main_window = self.app.main_controller.view player = self.app.game.player # global left_nav, left_canvas, left left_nav = Frame(main_window, height=main_window.sh, width=200, background=app.conf.left_nav_background) left_nav.place(x=0, y=0) # left = LeftNav(main_window, player, left_nav) self.selected_planet = player.selected_planet if isset(player.selected_ship): self.selected_ship_name = player.selected_ship.name else: self.selected_ship_name = "" self.main_window = main_window self.selected_ship_id = 0 self.planet_images = [] self.left_canvas = Canvas(left_nav) self.left_canvas.config(background=app.conf.left_nav_background, highlightthickness=0, height=main_window.sh, width=200) self.left_canvas.place(x=0, y=0) if app.conf.debug_lines == 1: self.left_canvas.create_line(0, 0, 200, main_window.sh, fill='red') self.left_canvas.create_line(200, 0, 0, main_window.sh, fill='red') # left nav values self.logo_image = Image.open(app.conf.title_image_path) self.logo_image.thumbnail([198, 48], Image.ANTIALIAS) self.logo_image_res = ImageTk.PhotoImage(self.logo_image) self.new_planet_image = self.logo_image_res self.planet_images.append(self.new_planet_image) self.label_logo = Label(self.left_canvas, image=self.logo_image_res) self.label_logo.config(background=app.conf.left_nav_background) self.label_logo.planet_image_res = self.logo_image_res # keep a reference! self.label_logo.place(anchor='n', x=100, y=0) # Resources Set row = 0 self.resources_start_y = 55 self.resources_canvas = Canvas(self.left_canvas) self.resources_canvas.config(background=app.conf.left_nav_background, width=198, highlightthickness=0, border=0) self.resources_canvas.grid_propagate(False) self.resources_canvas.place(anchor='nw', x=0, y=self.resources_start_y) self.label_resources = Label(self.resources_canvas, text="Resources:", fg=app.conf.main_text_color) self.label_resources.config(background=app.conf.left_nav_background) self.label_resources.grid(row=row, column=0, sticky='w') row += 1 self.label_planets = Label(self.resources_canvas, text="Planets:", fg=app.conf.second_text_color) self.label_planets.config(background=app.conf.left_nav_background) self.label_planets.grid(row=row, column=0, sticky='w') self.label_planets_val = Label(self.resources_canvas, text=str(len(player.owned_planets)) , fg=app.conf.second_text_color) self.label_planets_val.config(background=app.conf.left_nav_background) self.label_planets_val.grid(row=row, column=1, sticky='e') row += 1 self.label_ships = Label(self.resources_canvas, text="Ships:", fg=app.conf.second_text_color) self.label_ships.config(background=app.conf.left_nav_background) self.label_ships.grid(row=row, column=0, sticky='w') self.label_ships_val = Label(self.resources_canvas, text=len(player.ships), fg=app.conf.second_text_color) self.label_ships_val.config(background=app.conf.left_nav_background) self.label_ships_val.grid(row=row, column=1, sticky='e') row += 1 self.label_allies = Label(self.resources_canvas, text="Allies:", fg=app.conf.second_text_color) self.label_allies.config(background=app.conf.left_nav_background) self.label_allies.grid(row=row, column=0, sticky='w') self.label_allies_val = Label(self.resources_canvas, text=len(player.allies), fg=app.conf.second_text_color) self.label_allies_val.config(background=app.conf.left_nav_background) self.label_allies_val.grid(row=row, column=1, sticky='e') row += 1 self.label_enemies = Label(self.resources_canvas, text="Enemies:", fg=app.conf.second_text_color) self.label_enemies.config(background=app.conf.left_nav_background) self.label_enemies.grid(row=row, column=0, sticky='w') self.label_enemies_val = Label(self.resources_canvas, text=len(player.enemies), fg=app.conf.second_text_color) self.label_enemies_val.config(background=app.conf.left_nav_background) self.label_enemies_val.grid(row=row, column=1, sticky='e') row += 1 self.label_separator = Label(self.resources_canvas, text="", fg=app.conf.left_nav_background, width=24) self.label_separator.config(background=app.conf.left_nav_background) self.label_separator.grid(row=row, columnspan=2, sticky='e,w') # left nav buttons self.left_buttons_start_y = main_window.sh-112 if self.left_buttons_start_y < 500: self.left_buttons_start_y = 500 self.left_buttons_canvas = Canvas(self.left_canvas) self.left_buttons_canvas.config(background=app.conf.left_nav_background, height=200, width=200, highlightthickness=0, border=0) self.left_buttons_canvas.place(anchor='n', x=100, y=self.left_buttons_start_y) self.button_next_planet = Button(self.left_buttons_canvas, text="Next Planet", padx=60 , highlightbackground=app.conf.left_nav_background) self.button_next_ship = Button(self.left_buttons_canvas, text="Next Ship" , highlightbackground=app.conf.left_nav_background) self.button_home_planet = Button(self.left_buttons_canvas, text="Home Planet" , highlightbackground=app.conf.left_nav_background) self.button_end_turn = Button(self.left_buttons_canvas, text="End Turn" , highlightbackground=app.conf.left_nav_background) self.button_next_planet.bind("<Button-1>", self.controller.button_next_planet_clicked) self.button_next_ship.bind("<Button-1>", self.controller.button_next_ship_clicked) self.button_home_planet.bind("<Button-1>", self.controller.button_home_planet_clicked) self.button_end_turn.bind("<Button-1>", self.controller.button_end_turn_clicked) self.button_next_planet.grid(row=0, column=0, sticky='w,e') self.button_next_ship.grid(row=1, column=0, sticky='w,e') self.button_home_planet.grid(row=2, column=0, sticky='w,e') self.button_end_turn.grid(row=3, column=0, sticky='w,e') # Planet Info Set row = 0 self.planet_info_start_y = self.resources_start_y + 115 self.planet_info_canvas = Canvas(self.left_canvas) self.planet_info_canvas.config(background=app.conf.left_nav_background, width=198, highlightthickness=0, border=0) self.planet_info_canvas.grid_propagate(False) self.planet_info_canvas.place(anchor='nw', x=0, y=self.planet_info_start_y) self.label_planet_info = Label(self.planet_info_canvas, text="Planet Info:", fg=app.conf.main_text_color) self.label_planet_info.config(background=app.conf.left_nav_background) self.label_planet_info.grid(row=row, column=0, sticky='w') row += 1 self.label_planet_name = Label(self.planet_info_canvas, text="Name:", fg=app.conf.second_text_color) self.label_planet_name.config(background=app.conf.left_nav_background) self.label_planet_name.grid(row=row, column=0, sticky='w') self.label_planet_name_val = Label(self.planet_info_canvas, text=str(player.selected_planet.name) , fg=app.conf.second_text_color) self.label_planet_name_val.config(background=app.conf.left_nav_background) self.label_planet_name_val.grid(row=row, column=1, sticky='e') row += 1 self.label_planet_metals = Label(self.planet_info_canvas, text="Metals:", fg=app.conf.second_text_color) self.label_planet_metals.config(background=app.conf.left_nav_background) self.label_planet_metals.grid(row=row, column=0, sticky='w') self.label_planet_metals_val = Label(self.planet_info_canvas, text=str(player.selected_planet.metals) , fg=app.conf.second_text_color) self.label_planet_metals_val.config(background=app.conf.left_nav_background) self.label_planet_metals_val.grid(row=row, column=1, sticky='e') row += 1 self.label_planet_food = Label(self.planet_info_canvas, text="Food:", fg=app.conf.second_text_color) self.label_planet_food.config(background=app.conf.left_nav_background) self.label_planet_food.grid(row=row, column=0, sticky='w') self.label_planet_food_val = Label(self.planet_info_canvas, text=str(player.selected_planet.food) , fg=app.conf.second_text_color) self.label_planet_food_val.config(background=app.conf.left_nav_background) self.label_planet_food_val.grid(row=row, column=1, sticky='e') row += 1 self.label_planet_terrain = Label(self.planet_info_canvas, text="Terrain:", fg=app.conf.second_text_color) self.label_planet_terrain.config(background=app.conf.left_nav_background) self.label_planet_terrain.grid(row=row, column=0, sticky='w') self.label_planet_terrain_val = Label(self.planet_info_canvas, text=str(get_terrain(player.selected_planet.terrain)) , fg=app.conf.second_text_color) self.label_planet_terrain_val.config(background=app.conf.left_nav_background) self.label_planet_terrain_val.grid(row=row, column=1, sticky='e') row += 1 self.label_separator_p = Label(self.planet_info_canvas, text="", fg=app.conf.left_nav_background, width=24) self.label_separator_p.config(background=app.conf.left_nav_background) self.label_separator_p.grid(row=row, columnspan=2, sticky='e,w') # ship info row = 0 self.ship_select_start_y = self.planet_info_start_y + 115 self.ship_select_canvas = Canvas(self.left_canvas) self.ship_select_canvas.config(background=app.conf.left_nav_background, width=198, highlightthickness=0, border=0) self.ship_select_canvas.grid_propagate(False) self.ship_select_canvas.place(anchor='nw', x=0, y=self.ship_select_start_y) self.label_ship_select = Label(self.ship_select_canvas, text="Select Ship:", fg=app.conf.main_text_color) self.label_ship_select.config(background=app.conf.left_nav_background) self.label_ship_select.grid(row=row, column=0, sticky='w') # future implementation # if selected_ship.name != '': if isset(self.selected_ship_name): if app.conf.debug == 1: print "Showing Selected Ship (init)" current_ship = player.get_ship(self.selected_ship_name) row += 1 self.listbox_ship = Listbox(self.ship_select_canvas, width=198 , background=app.conf.alternate_left_nav_background, borderwidth=1) self.listbox_ship.config(selectmode=SINGLE) for ship in player.ships: self.listbox_ship.insert(END, ship.name) self.listbox_ship.selection_set(self.selected_ship_id) self.listbox_ship.grid(row=row, columnspan=4, sticky='w,e') self.listbox_ship.bind('<<ListboxSelect>>', self.poll_ship_list) row = 0 self.ship_info_start_y = self.ship_select_start_y + 200 self.ship_info_canvas = Canvas(self.left_canvas) self.ship_info_canvas.config(background=app.conf.left_nav_background, width=198, highlightthickness=0, border=0) self.ship_info_canvas.grid_propagate(False) self.ship_info_canvas.place(anchor='nw', x=0, y=self.ship_info_start_y) self.label_ship_info = Label(self.ship_info_canvas, text="Ship Info:", fg=app.conf.main_text_color) self.label_ship_info.config(background=app.conf.left_nav_background) self.label_ship_info.grid(row=row, column=0, sticky='w') row += 1 self.label_ship_name = Label(self.ship_info_canvas, text="Name:", fg=app.conf.second_text_color) self.label_ship_name.config(background=app.conf.left_nav_background) self.label_ship_name.grid(row=row, column=0, columnspan=2, sticky='w') self.label_ship_name_val = Label(self.ship_info_canvas, text=current_ship.name , fg=app.conf.second_text_color) self.label_ship_name_val.config(background=app.conf.left_nav_background) self.label_ship_name_val.grid(row=row, column=2, columnspan=2, sticky='e') row += 1 self.label_ship_attack = Label(self.ship_info_canvas, text="Attack:", fg=app.conf.second_text_color) self.label_ship_attack.config(background=app.conf.left_nav_background) self.label_ship_attack.grid(row=row, column=0, sticky='w') self.label_ship_attack_val = Label(self.ship_info_canvas, text=current_ship.attack , fg=app.conf.second_text_color) self.label_ship_attack_val.config(background=app.conf.left_nav_background) self.label_ship_attack_val.grid(row=row, column=1, sticky='e') self.label_ship_defense = Label(self.ship_info_canvas, text="Defense:", fg=app.conf.second_text_color) self.label_ship_defense.config(background=app.conf.left_nav_background) self.label_ship_defense.grid(row=row, column=2, sticky='w') self.label_ship_defense_val = Label(self.ship_info_canvas, text=current_ship.defense , fg=app.conf.second_text_color) self.label_ship_defense_val.config(background=app.conf.left_nav_background) self.label_ship_defense_val.grid(row=row, column=3, sticky='e') row += 1 self.label_ship_storage = Label(self.ship_info_canvas, text="Storage:", fg=app.conf.second_text_color) self.label_ship_storage.config(background=app.conf.left_nav_background) self.label_ship_storage.grid(row=row, column=0, columnspan=2, sticky='w') self.label_ship_storage_val = Label(self.ship_info_canvas, text=current_ship.storage , fg=app.conf.second_text_color) self.label_ship_storage_val.config(background=app.conf.left_nav_background) self.label_ship_storage_val.grid(row=row, column=2, columnspan=2, sticky='e') row += 1 self.label_ship_seats = Label(self.ship_info_canvas, text="Seats:", fg=app.conf.second_text_color) self.label_ship_seats.config(background=app.conf.left_nav_background) self.label_ship_seats.grid(row=row, column=0, columnspan=2, sticky='w') self.label_ship_seats_val = Label(self.ship_info_canvas, text=current_ship.seats , fg=app.conf.second_text_color) self.label_ship_seats_val.config(background=app.conf.left_nav_background) self.label_ship_seats_val.grid(row=row, column=2, columnspan=2, sticky='e') row += 1 self.label_separator_s = Label(self.ship_info_canvas, text="", fg=app.conf.left_nav_background, width=24) self.label_separator_s.config(background=app.conf.left_nav_background) self.label_separator_s.grid(row=row, columnspan=4, sticky='e,w') else: if app.conf.debug == 1: print "No Selected Ship Detected (init)" row += 1 self.listbox_ship = Listbox(self.ship_select_canvas, width=198 , background=app.conf.alternate_left_nav_background, borderwidth=1) for ship in player.ships: self.listbox_ship.insert(END, ship.name) self.listbox_ship.grid(row=row, columnspan=4, sticky='w,e') self.listbox_ship.bind('<<ListboxSelect>>', self.poll_ship_list) row += 1 self.label_ship_name = Label(self.ship_select_canvas, text="No Ship Selected", fg=app.conf.second_text_color) self.label_ship_name.config(background=app.conf.left_nav_background) self.label_ship_name.grid(row=row, columnspan=4, sticky='w') row += 1 self.label_separator_s = Label(self.ship_select_canvas, text="", fg=app.conf.left_nav_background, width=24) self.label_separator_s.config(background=app.conf.left_nav_background) self.label_separator_s.grid(row=row, columnspan=4, sticky='e,w') if app.conf.debug == 1: print "CreatedLine:", 0, " ", 0, " ", main_window.sw-200, " ", main_window.sh-200 print "CreatedLine:", main_window.sw-200, " ", 0, " ", 0, " ", main_window.sh-200 print "CurrWin0:", convert_coords_x(main_window, 0), convert_coords_y(main_window, 0) if app.conf.debug == 1: print "Displayed: left_nav,", main_window.sh, ",200" def poll_ship_list(self, event): w = event.widget index = int(w.curselection()[0]) new_ship_name = w.get(index) if isset(self.selected_ship_name): if self.selected_ship_name == "": if new_ship_name != self.selected_ship_name: self.ship_selction_has_changed(new_ship_name) self.selected_ship_name = new_ship_name self.selected_ship_id = w.curselection() if app.conf.debug == 1: print "SelectedShip:", self.selected_ship_name self.redraw(self.main_window, self.player) else: self.selected_ship_name = new_ship_name self.selected_ship_id = w.curselection() self.app.debug(("SelectedShip:", self.selected_ship_name)) self.redraw() def redraw(self): app = self.app main_window = app.main_controller.view player = app.game.player self.player = player app.debug("Redrawing Left Nav") self.label_logo.place(anchor='n', x=100, y=0) self.resources_canvas.config(background=app.conf.left_nav_background, height=main_window.sh-self.resources_start_y-202, width=198, highlightthickness=0, border=0) self.resources_canvas.place(anchor='nw', x=0, y=self.resources_start_y) row = 0 self.label_resources.grid(row=row, column=0, sticky='w') row += 1 self.label_planets.grid(row=row, column=0, sticky='w') self.label_planets_val.config(text=str(len(player.owned_planets))) self.label_planets_val.grid(row=row, column=1, sticky='e') row += 1 self.label_ships.grid(row=row, column=0, sticky='w') self.label_ships_val.config(text=len(player.ships)) self.label_ships_val.grid(row=row, column=1, sticky='e') row += 1 self.label_allies.grid(row=row, column=0, sticky='w') self.label_allies_val.config(text=len(player.allies)) self.label_allies_val.grid(row=row, column=1, sticky='e') row += 1 self.label_enemies.grid(row=row, column=0, sticky='w') self.label_enemies_val.config(text=len(player.enemies)) self.label_enemies_val.grid(row=row, column=1, sticky='e') row += 1 self.label_separator.grid(row=row, columnspan=2, sticky='e,w') # left nav buttons self.left_buttons_start_y = main_window.sh-112 if self.left_buttons_start_y < 500: self.left_buttons_start_y = 500 self.left_buttons_canvas.place(anchor='n', x=100, y=self.left_buttons_start_y) self.button_next_planet.grid(row=0, column=0, sticky='w,e') self.button_next_ship.grid(row=1, column=0, sticky='w,e') self.button_home_planet.grid(row=2, column=0, sticky='w,e') self.button_end_turn.grid(row=3, column=0, sticky='w,e') app.debug(("Left Buttons Start Y:", self.left_buttons_start_y)) # Planet Info Set row = 0 self.planet_info_start_y = self.resources_start_y + 115 self.planet_info_canvas.place(anchor='nw', x=0, y=self.planet_info_start_y) self.label_planet_info.grid(row=row, column=0, sticky='w') row += 1 self.label_planet_name.grid(row=row, column=0, sticky='w') self.label_planet_name_val.config(text=str(player.selected_planet.name)) self.label_planet_name_val.grid(row=row, column=1, sticky='e') row += 1 self.label_planet_metals.grid(row=row, column=0, sticky='w') self.label_planet_metals_val.config(text=str(player.selected_planet.metals)) self.label_planet_metals_val.grid(row=row, column=1, sticky='e') row += 1 self.label_planet_food.grid(row=row, column=0, sticky='w') self.label_planet_food_val.config(text=str(player.selected_planet.food)) self.label_planet_food_val.grid(row=row, column=1, sticky='e') row += 1 self.label_planet_terrain.grid(row=row, column=0, sticky='w') self.label_planet_terrain_val.config(text=str(get_terrain(player.selected_planet.terrain))) self.label_planet_terrain_val.grid(row=row, column=1, sticky='e') row += 1 self.label_separator_p.grid(row=row, columnspan=2, sticky='e,w') # prep for ship section if isset(self.ship_select_canvas): self.ship_select_canvas.destroy() # ship info row = 0 self.ship_select_start_y = self.planet_info_start_y + 115 self.ship_select_canvas = Canvas(self.left_canvas) self.ship_select_canvas.config(background=app.conf.left_nav_background, width=198, highlightthickness=0, border=0) self.ship_select_canvas.grid_propagate(False) self.ship_select_canvas.place(anchor='nw', x=0, y=self.ship_select_start_y) self.label_ship_select = Label(self.ship_select_canvas, text="Select Ship:", fg=app.conf.main_text_color) self.label_ship_select.config(background=app.conf.left_nav_background) self.label_ship_select.grid(row=row, column=0, sticky='w') # future implementation # if selected_ship.name != '': if self.selected_ship_name != "": app.debug("Showing Selected Ship (redraw)") current_ship = player.get_ship(self.selected_ship_name) row += 1 self.listbox_ship = Listbox(self.ship_select_canvas, width=198 , background=app.conf.alternate_left_nav_background, borderwidth=1) self.listbox_ship.config(selectmode=SINGLE) for ship in player.ships: self.listbox_ship.insert(END, ship.name) self.listbox_ship.selection_set(self.selected_ship_id) self.listbox_ship.grid(row=row, columnspan=4, sticky='w,e') self.listbox_ship.bind('<<ListboxSelect>>', self.poll_ship_list) row = 0 self.ship_info_start_y = self.ship_select_start_y + 200 self.ship_info_canvas = Canvas(self.left_canvas) self.ship_info_canvas.config(background=app.conf.left_nav_background, width=198, highlightthickness=0, border=0) self.ship_info_canvas.grid_propagate(False) self.ship_info_canvas.place(anchor='nw', x=0, y=self.ship_info_start_y) self.label_ship_info = Label(self.ship_info_canvas, text="Ship Info:", fg=app.conf.main_text_color) self.label_ship_info.config(background=app.conf.left_nav_background) self.label_ship_info.grid(row=row, column=0, sticky='w') row += 1 self.label_ship_name = Label(self.ship_info_canvas, text="Name:", fg=app.conf.second_text_color) self.label_ship_name.config(background=app.conf.left_nav_background) self.label_ship_name.grid(row=row, column=0, columnspan=2, sticky='w') self.label_ship_name_val = Label(self.ship_info_canvas, text=current_ship.name , fg=app.conf.second_text_color) self.label_ship_name_val.config(background=app.conf.left_nav_background) self.label_ship_name_val.grid(row=row, column=2, columnspan=2, sticky='e') row += 1 self.label_ship_attack = Label(self.ship_info_canvas, text="Attack:", fg=app.conf.second_text_color) self.label_ship_attack.config(background=app.conf.left_nav_background) self.label_ship_attack.grid(row=row, column=0, sticky='w') self.label_ship_attack_val = Label(self.ship_info_canvas, text=current_ship.attack , fg=app.conf.second_text_color) self.label_ship_attack_val.config(background=app.conf.left_nav_background) self.label_ship_attack_val.grid(row=row, column=1, sticky='e') self.label_ship_defense = Label(self.ship_info_canvas, text="Defense:", fg=app.conf.second_text_color) self.label_ship_defense.config(background=app.conf.left_nav_background) self.label_ship_defense.grid(row=row, column=2, sticky='w') self.label_ship_defense_val = Label(self.ship_info_canvas, text=current_ship.defense , fg=app.conf.second_text_color) self.label_ship_defense_val.config(background=app.conf.left_nav_background) self.label_ship_defense_val.grid(row=row, column=3, sticky='e') row += 1 self.label_ship_storage = Label(self.ship_info_canvas, text="Storage:", fg=app.conf.second_text_color) self.label_ship_storage.config(background=app.conf.left_nav_background) self.label_ship_storage.grid(row=row, column=0, columnspan=2, sticky='w') self.label_ship_storage_val = Label(self.ship_info_canvas, text=current_ship.storage , fg=app.conf.second_text_color) self.label_ship_storage_val.config(background=app.conf.left_nav_background) self.label_ship_storage_val.grid(row=row, column=2, columnspan=2, sticky='e') row += 1 self.label_ship_seats = Label(self.ship_info_canvas, text="Seats:", fg=app.conf.second_text_color) self.label_ship_seats.config(background=app.conf.left_nav_background) self.label_ship_seats.grid(row=row, column=0, columnspan=2, sticky='w') self.label_ship_seats_val = Label(self.ship_info_canvas, text=current_ship.seats , fg=app.conf.second_text_color) self.label_ship_seats_val.config(background=app.conf.left_nav_background) self.label_ship_seats_val.grid(row=row, column=2, columnspan=2, sticky='e') row += 1 self.label_separator_s = Label(self.ship_info_canvas, text="", fg=app.conf.left_nav_background, width=24) self.label_separator_s.config(background=app.conf.left_nav_background) self.label_separator_s.grid(row=row, columnspan=4, sticky='e,w') else: app.debug("No Selected Ship Detected (redraw)") row += 1 self.listbox_ship = Listbox(self.ship_select_canvas, width=198 , background=app.conf.alternate_left_nav_background, borderwidth=1) for ship in player.ships: self.listbox_ship.insert(END, ship.name) self.listbox_ship.grid(row=row, columnspan=2, sticky='w,e') self.listbox_ship.bind('<<ListboxSelect>>', self.poll_ship_list) row += 1 self.label_ship_name = Label(self.ship_select_canvas, text="No Ship Selected", fg=app.conf.second_text_color) self.label_ship_name.config(background=app.conf.left_nav_background) self.label_ship_name.grid(row=row, columnspan=2, sticky='w') row += 1 self.label_separator_s = Label(self.ship_select_canvas, text="", fg=app.conf.left_nav_background, width=24) self.label_separator_s.config(background=app.conf.left_nav_background) self.label_separator_s.grid(row=row, columnspan=4, sticky='e,w')
class SolidDatabaseDeleter: def __init__(self, master, system, solid): """Constructor method. Defines the parameters to be obtained in this window.""" self.master = master self.fonttype = system.fonttype self.version = system.version self.superfont = get_superfont(self.fonttype) #superscript font self.tframe = Frame(master.tframe) self.frame = Frame(master.frame) self.bframe = Frame(master.bframe) self.top = None #flag for existence of toplevel# self.name = StringVar(value=solid.name) #stores the chemical name self.e = DoubleVar(value=solid.e) #stores the porosity self.rho = DoubleVar(value=solid.rho) #stores the bulk density self.foc = DoubleVar( value=solid.foc) #stores the organic carbon fraction self.tort = StringVar( value=solid.tort) #stores the default tortuosity correction self.sorp = StringVar( value=solid.sorp) #stores the default sorption correction self.Ref = StringVar( value=solid.Ref) #stores the default sorption correction self.cancelflag = 0 def make_widgets(self): self.bgcolor = self.frame.cget('bg') self.instructions = Label( self.frame, text= ' Are you sure to delete the following solid from database? ' ) self.namelabel = Label(self.frame, text='Material') self.elabel = Label(self.frame, text='Porosity') self.rholabel = Label(self.frame, text='Bulk density\n (kg/L') self.foclabel = Label(self.frame, text='Organic carbon\n fraction') self.tortlabel = Label(self.frame, text='Tortruosity correction') self.sorplabel = Label(self.frame, text='Sorption isotherms') self.Reflabel = Label(self.frame, text='Reference') self.rhounitlabel = Label(self.frame, text=u'g/cm\u00B3') self.namewidget = Label(self.frame, width=16, justify='center', textvariable=self.name) self.ewidget = Label(self.frame, width=8, justify='center', textvariable=self.e) self.rhowidget = Label(self.frame, width=8, justify='center', textvariable=self.rho) self.focwidget = Label(self.frame, width=8, justify='center', textvariable=self.foc) self.tortwidget = Label(self.frame, width=16, justify='center', textvariable=self.tort) self.sorpwidget = Label(self.frame, width=16, justify='center', textvariable=self.sorp) self.Refwidget = Label(self.frame, width=10, justify='center', textvariable=self.Ref) self.blankcolumn = Label(self.frame, text=' ', width=1) self.namecolumn = Label(self.frame, text=' ', width=18) self.ecolumn = Label(self.frame, text=' ', width=10) self.rhocolumn = Label(self.frame, text=' ', width=10) self.foccolumn = Label(self.frame, text=' ', width=10) self.tortcolumn = Label(self.frame, text=' ', width=18) self.sorpcolumn = Label(self.frame, text=' ', width=18) self.Refcolumn = Label(self.frame, text=' ', width=18) self.endcolumn = Label(self.frame, text=' ', width=2) self.deletebutton = Button(self.frame, text='Delete', width=20, command=self.Delete) self.cancelbutton = Button(self.frame, text='Cancel', width=20, command=self.Cancel) self.blank1 = Label(self.frame, text=' ') self.blank2 = Label(self.frame, text=' ') #show the widgets on the grid self.instructions.grid(row=0, column=0, columnspan=6, padx=8, sticky='W') self.blankcolumn.grid(row=1, column=0, sticky='WE', padx=1, pady=1) self.namecolumn.grid(row=1, column=1, sticky='WE', padx=1, pady=1) self.ecolumn.grid(row=1, column=2, sticky='WE', padx=1, pady=1) self.rhocolumn.grid(row=1, column=3, sticky='WE', padx=1, pady=1) self.foccolumn.grid(row=1, column=4, sticky='WE', padx=1, pady=1) self.tortcolumn.grid(row=1, column=5, sticky='WE', padx=1, pady=1) self.sorpcolumn.grid(row=1, column=6, sticky='WE', padx=1, pady=1) self.Refcolumn.grid(row=1, column=7, sticky='WE', padx=1, pady=1) self.endcolumn.grid(row=1, column=8, sticky='WE', padx=1, pady=1) self.namelabel.grid(row=2, column=1, sticky='WE', padx=1, pady=1) self.elabel.grid(row=2, column=2, sticky='WE', padx=1, pady=1) self.rholabel.grid(row=2, column=3, sticky='WE', padx=1, pady=1) self.foclabel.grid(row=2, column=4, sticky='WE', padx=1, pady=1) self.tortlabel.grid(row=2, column=5, sticky='WE', padx=1, pady=1) self.sorplabel.grid(row=2, column=6, sticky='WE', padx=1, pady=1) self.Reflabel.grid(row=2, column=7, sticky='WE', padx=1, pady=1) self.rhounitlabel.grid(row=3, column=3, sticky='WE', padx=1, pady=1) self.namewidget.grid(row=4, column=1, padx=1, pady=1, sticky='WE') self.ewidget.grid(row=4, column=2, padx=1, pady=1) self.rhowidget.grid(row=4, column=3, padx=1, pady=1) self.focwidget.grid(row=4, column=4, padx=1, pady=1) self.tortwidget.grid(row=4, column=5, padx=1, pady=1) self.sorpwidget.grid(row=4, column=6, padx=1, pady=1) self.Refwidget.grid(row=4, column=7, padx=1, pady=1) self.blank1.grid(row=5) self.deletebutton.grid(row=6, columnspan=11) self.cancelbutton.grid(row=7, columnspan=11) self.blank2.grid(row=8) self.deletebutton.bind('<Return>', self.Delete) self.focusbutton = self.deletebutton def Delete(self, event=None): """Finish and move on. Checks that the number chemicals are less than the total number of chemicals in database.""" if self.master.window.top is not None: self.master.open_toplevel() else: self.master.tk.quit() def Cancel(self): try: self.name.set(self.solid.name) self.e.set(self.solid.e) self.rho.set(self.solid.rho) self.foc.set(self.solid.foc) self.tort.set(self.solid.tort) self.sorp.set(self.solid.sorp) self.Ref.set(self.solid.Ref) except: self.cancelflag = 1 if self.master.window.top is not None: self.master.open_toplevel() else: self.master.tk.quit()
class AssetBuilder(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.isRunning = False self.initUI() def initUI(self): global scriptdir, calldir global dnd global URLentry global savedirentry troot = self.parent # self.parent.master # was self.parent; # now parent is child of root troot.title("youtube-dl Tkinter/TkDND GUI") #~ self.pack(fill=BOTH, expand=1) # just a reference here: self.URLentry = URLentry self.savedirentry = savedirentry self.lfname = "" self.outdir = scriptdir savedirentry.delete(0, END) savedirentry.insert(0, self.outdir) #create a grid 5x4 in to which we will place elements. self.columnconfigure(1, weight=0) self.columnconfigure(2, weight=1) self.columnconfigure(3, weight=0) self.columnconfigure(4, weight=0) self.columnconfigure(5, weight=0) self.rowconfigure(1, weight=0) self.rowconfigure(2, weight=1) self.rowconfigure(3, weight=0) #create the main text are with scrollbars xscrollbar = Scrollbar(self, orient=HORIZONTAL) xscrollbar.grid(row=3, column=1, columnspan=4, sticky=E + W) yscrollbar = Scrollbar(self, orient=VERTICAL) yscrollbar.grid(row=2, column=5, sticky=N + S) self.textarea = Text(self, wrap=NONE, bd=0, xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set) self.textarea.grid(row=2, column=1, columnspan=4, rowspan=1, padx=0, sticky=E + W + S + N) xscrollbar.config(command=self.textarea.xview) yscrollbar.config(command=self.textarea.yview) #create the buttons/checkboxes to go along the bottom self.clearButton = Button(self, text="Clear") self.clearButton.grid(row=1, column=1, padx=5, pady=5, sticky=W) self.clearButton.bind("<ButtonRelease-1>", self.clearText) self.delButton = Button(self, text="Del.Files") self.delButton.grid(row=1, column=2, padx=5, pady=5, sticky=W) self.delButton.bind("<ButtonRelease-1>", self.deleteFiles) self.runbutton = Button(self, text="Run/Call") self.runbutton.grid(row=1, column=3, padx=5, pady=5) self.runbutton.bind("<ButtonRelease-1>", self.runScript) self.stopbutton = Button(self, text="Stop") self.stopbutton.grid(row=1, column=4, padx=5, pady=5) self.stopbutton.bind("<ButtonRelease-1>", self.stopScript) #tags are used to colorise the text added to the text widget. # see self.addTtext and self.tagsForLine self.textarea.tag_config("errorstring", foreground="#CC0000") self.textarea.tag_config("infostring", foreground="#008800") self.addText("Path A: " + calldir + "\n", ("infostring", )) self.addText("(chdir)" + "\n", ("infostring", )) os.chdir(scriptdir) self.addText("Path B: " + os.getcwd() + "\n\n", ("infostring", )) self.addText("DL command is: " + " ".join(scriptcall) + "\n", ("infostring", )) self.addText("Player command is: " + " ".join(playcommand) + "\n\n", ("infostring", )) def handleURLentry(self, event): # to replace text - delete first istr = event.data.strip() #~ ''.join(c for c in filename if c in valid_chars) # no need event.widget.delete(0, END) event.widget.insert(0, istr) def handlesavedirentry(self, event): istr = event.data.strip() # to replace text - delete first event.widget.delete(0, END) event.widget.insert(0, istr) # http://stackoverflow.com/questions/8449053/how-to-make-menubar def make_menu(self, w): global the_menu the_menu = Tkinter.Menu(w, tearoff=0) the_menu.add_command(label="Cut") the_menu.add_command(label="Copy") the_menu.add_command(label="Paste") the_menu.add_command(label="Delete") def show_menu(self, e): global the_menu w = e.widget the_menu.entryconfigure("Cut", command=lambda: w.event_generate("<<Cut>>")) the_menu.entryconfigure("Copy", command=lambda: w.event_generate("<<Copy>>")) the_menu.entryconfigure("Paste", command=lambda: w.event_generate("<<Paste>>")) #no <<Delete>> as generic event - there is <<Clear>> # http://www.tcl.tk/man/tcl8.5/TkCmd/event.htm the_menu.entryconfigure("Delete", command=lambda: w.event_generate("<<Clear>>")) the_menu.tk.call("tk_popup", the_menu, e.x_root, e.y_root) def tagsForLine(self, line): """return a tuple of tags to be applied to the line of text 'line' when being added to the text widet""" l = line.lower() if "error" in l or "traceback" in l: return ("errorstring", ) return () def addText(self, str, tags=None): """Add a line of text to the textWidget. If tags is None then self.tagsForLine will be used to assign tags to the line""" self.textarea.insert(INSERT, str, tags or self.tagsForLine(str)) self.textarea.yview(END) def clearText(self, event): """Clear all the text from the text widget""" self.textarea.delete("1.0", END) print "isAlive:", self.worker.isAlive(), ", isRunning:", self.isRunning def moveCursorToEnd(self): """move the cursor to the end of the text widget's text""" self.textarea.mark_set("insert", END) def runScript(self, event): if (not (self.isRunning)): self.isRunning = True self.worker = threading.Thread(target=self.runScriptThread, args=(event, )) self.worker.start() def runPlayer(self): # with subprocess.PIPE so it doesn't lock the rest self.addText(" ".join(playcommand) + "\n", ("infostring", )) subprocess.Popen(playcommand, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) localfiles.append(self.lfname) # push self.addText("Local files: " + str(localfiles) + "\n", ("infostring", )) def deleteFiles(self, event): for i in reversed(range(len(localfiles))): file = localfiles.pop(i) try: os.remove(file) except OSError as e: self.addText("Error removing: " + file + "; " + e + "\n", ("infostring", )) else: self.addText("Removed: " + file + "\n", ("infostring", )) def runScriptThread(self, event): """callback from the run/call button""" myURL = self.URLentry.get() self.outdir = self.savedirentry.get() self.moveCursorToEnd() if not myURL: self.addText("URL is empty, can't do anything.\n", ("infostring", )) self.isRunning = False return if not (self.outdir and os.path.exists(self.outdir) and os.path.isdir(self.outdir)): self.addText("Invalid save directory, can't do anything.\n", ("infostring", )) self.isRunning = False return self.addText("Starting run %s\n" % (str(datetime.now())), ("infostring", )) scriptcall[-1] = myURL # myURL is last, anyways # then a bit nastier - must consider exact third field to set outdir, and concat too; careful if changing scriptcall args scriptcall[ 2] = self.outdir + os.sep + "%(autonumber)s-%(title)s-%(id)s.%(ext)s" # don't put this in single quotes! cmdlist = scriptcall self.addText(" ".join(cmdlist) + "\n", ("infostring", )) self.proc = subprocess.Popen(cmdlist, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, preexec_fn=os.setsid) while True: line = self.proc.stdout.readline() # if match [download] Destination if "[download] Destination" in line: tda = line.split(": ") self.lfname = tda[1].rstrip() playcommand[ -1] = self.lfname # [playerexe, lfname]; # now lfname contains the self.outdir + os.sep + # yet another call - to player to start playing # tkInter has after to run scheduled function after delay self.parent.after(runplayerdelay, self.runPlayer) # parent is root if not line: break self.addText(line) #this triggers an update of the text area, otherwise it doesn't update self.textarea.update_idletasks() self.isRunning = False retcode = self.proc.wait() # should return self.proc.returncode self.addText( "Script Finished (%s) %s\n" % (str(retcode), str(datetime.now())), ("infostring", )) self.addText("*" * 80 + "\n", ("infostring", )) if not ((retcode == 0) or (retcode == -15)): # -15 is when it is interrupted by user self.addText("* Command did not complete succesfully\n", ("infostring", )) randwait = random.randint(10, 20) self.addText("* Waiting at random %d seconds, and\n" % (randwait), ("infostring", )) time.sleep(randwait) self.addText("* Restarting command\n", ("infostring", )) #self.isRunning = True #self.worker = threading.Thread( # target=self.runScriptThread, # args=(event,)) #self.worker.start() # seems Timer needs float (ignored int) as delay argument?! t = threading.Timer(1.0, self.runScript(event=None)) t.start() def stopScript(self, event): """callback from the stop button""" os.killpg(self.proc.pid, signal.SIGTERM) self.proc.terminate() self.proc.kill() print self.worker.isAlive() # True here. still
print e finally: sock.close() if __name__ == "__main__": print "Creating animation server" if os.path.exists(SOCKET_NAME): os.remove(SOCKET_NAME) server = Animator(AnimationRequestHandler, SIMULATE) if not SIMULATE: print "Starting animation server..." print "Animation server is running on socket {0}".format(SOCKET_NAME) print "Quit the server with CONTROL-C." server.serve_forever() else: print "Starting simulation..." button_window = Toplevel() button_window.title('Button Input') img = PhotoImage(file="easy_button.gif") single_easy_button = Button(button_window, image=img) single_easy_button.pack() single_easy_button.bind("<Button-1>", lambda e: server.processCommand(ButtonEvent.SINGLEPRESS)) double_easy_button = Button(button_window, text="double tap") double_easy_button.pack() double_easy_button.bind("<Button-1>", lambda e: server.processCommand(ButtonEvent.DOUBLEPRESS)) mainloop()
class LED8x8AndButton(object): def __init__(self, buttonDownCallback=None, buttonUpCallback=None): self.root = Tk() self.root.title("8x8") self.buttonUpCallback = buttonUpCallback self.buttonDownCallback = buttonDownCallback self.pixels = [] for y in xrange(8): for x in xrange(8): bt = Button(self.root, bg="gray", width=2, height=1, state="disabled") self.pixels.append(bt) bt.grid(column=x, row=y) self.but = Button(self.root, text="#", width=3, height=1) self.but.grid(column=3, row=8, columnspan=2) self.butColor = Button(self.root, state="disabled", width=3) self.butColor.grid(column=1, row=8, columnspan=2) self.orgColor = self.butColor.cget("bg") self.but.bind("<Button-1>", self._buttonDown) self.but.bind("<ButtonRelease-1>", self._buttonUp) def mainLoop(self): self.root.mainloop() def _setXY(self, x, y, val): if val == 0: self.pixels[y * 8 + x].configure(bg="gray") elif val == 1: self.pixels[y * 8 + x].configure(bg="green") elif val == 2: self.pixels[y * 8 + x].configure(bg="red") elif val == 3: self.pixels[y * 8 + x].configure(bg="orange") else: self.pixels[y * 8 + x].configure(bg="white") def setButtonColor(self, val): if val == 0: self.butColor.configure(bg=self.orgColor) elif val == 1: self.butColor.configure(bg="green") elif val == 2: self.butColor.configure(bg="red") elif val == 3: self.butColor.configure(bg="orange") else: self.butColor.configure(bg="white") def writeDisplay(self, image): pos = 0 for x in xrange(8): sv = 1 v1 = ord(image[pos]) v2 = ord(image[pos + 1]) pos = pos + 2 for y in xrange(8): pv = 0 if (v1 & sv) != 0: pv = pv | 1 if (v2 & sv) != 0: pv = pv | 2 sv = sv << 1 self._setXY(7 - x, y, pv) def _buttonDown(self, event): if self.buttonDownCallback: self.buttonDownCallback() def _buttonUp(self, event): if self.buttonUpCallback: self.buttonUpCallback()
class TkAdmin(TkWindow, RPCComponent): """ Development graphical user interface for cape systems. """ unique = True directory_name = "TkAdmin" # TODO: # * Clean up user interface # * Develop interaction elements for all primitives def __init__(self): self.nodelist = {} self.messages = [] self.title = "cape TkAdmin - [%s]" % identity.SystemName super(TkAdmin, self).__init__() self.Configuration['fixsender'] = False self.Configuration['autoclear'] = True self.Configuration['autoscan'] = True self.Configuration['showresponses'] = False self.autoscan.set(self.Configuration['autoscan']) self.fixsender.set(self.Configuration['fixsender']) self.autoclear.set(self.Configuration['autoclear']) self.showresponses.set(self.Configuration['showresponses']) # The invisibleroot is necessary to avoid stopping Tk's eventloop # upon closure of tkWindows. # TODO: Good idea to already activate here? # TODO: Don't we need a central InvisibleWindow thats kept inbetween destruction of tkinterfaces? self._invisibleRoot = tkInvisibleWindow().activate() # self.clearInput = tkinter.BooleanVar() self.MapViewer = None def __on_ButtonClear_Press(self, Event=None): self.clearEntry() def __on_ButtonTransmit_Release(self, Event=None): self.usertransmit() def __on_EntryInput_Enter__C(self, Event=None): self.usertransmit() def __on_ButtonClearResponses_Press(self, Event=None): self.__TextResponses.clear() def showMessage(self, ev=None): msglb = self.__MessageLog._listbox sel = msglb.curselection() if len(sel) > 1: self.logwarning("Multiple messages selected to display. Can't.") msg = self.messages[int(sel[0])] msgdialog = TkMessageDialog(self.window, msg) def composeMessage(self, name="", node="", sender=None): if not sender: sender = self.name msg = Message(sender=sender, recipientnode=node, recipient=name) msgdialog = TkMessageDialog(self.window, msg, onclosecallback=self.transmit) def clearEntry(self): self.__EntryInput.delete(0, END) self.__FrameInput['bg'] = self.defaultcolors['bg'] # self.__EntryInput['fg'] = self.defaultcolors['fg'] def scanregistry(self, node=""): msg = Message(sender=self.name, recipientnode=node, recipient=self.systemregistry, func="listRegisteredComponents", arg=None ) self.transmit(msg) msg = Message(sender=self.name, recipientnode=node, recipient=self.systemregistry, func="listRegisteredTemplates", arg=None ) self.transmit(msg) def scangateways(self): msg = Message(sender=self.name, recipient=self.systemdispatcher, func="listgateways" ) self.transmit(msg) def dumpnodelist(self): from pprint import pprint pprint(self.nodelist) def scancomponent(self, name, node=""): self.logdebug("Scanning component '%s'." % name) msg = Message(sender=self.name, recipientnode=node, recipient=name, func="getComponentInfo", arg=None) self.transmit(msg) def createcomponent(self, name, node=""): self.loginfo("Creating component from template '%s'." % name) msg = Message(sender=self.name, recipientnode=node, recipient=self.systemregistry, func="createComponent", arg={'templatename': name}) self.transmit(msg) def copystring(self, name): self.window.clipboard_clear() self.window.clipboard_append(name) def callComplexMethod(self, componentname, node, func): self.loginfo("Creating function dialog for '%s'@'%s'." % (func, componentname)) componentlist = self.nodelist[node]['componentlist'] component = componentlist[componentname] componentinfo = component["info"] methods = componentinfo["methods"] methodregister = methods[func] InputDialog = TkRPCArgDialog(self.window, self.callComplexMethodFinal, componentname, node, func, methodregister) def callComplexMethodFinal(self, name, node, func, args): self.loginfo("Finally calling func '%s'@'%s' with args '%s'" % (func, name, args)) msg = Message(sender=self.name, recipientnode=node, recipient=name, func=func, arg=args) self.transmit(msg) def callSimpleMethod(self, name, node, func): self.loginfo("Calling '%s'@'%s'." % (func, name)) msg = Message(sender=self.name, recipient=name, recipientnode=node, func=func, arg=None) self.transmit(msg) def transmit(self, msg): self.logdebug("Transmitting Message '%s'" % msg) self.recordMessage(msg) self.send(msg, "outbox") def recordMessage(self, msg): self.messages.append(msg) self.updateMessageLog() def updateMessageLog(self): loglistbox = self.__MessageLog._listbox loglistbox.delete(0, END) # GAH. Addition should be sufficient. CHANGE! for msg in sorted(self.messages, key=lambda msg: msg.timestamp): loglistbox.insert(END, msg) if msg.recipient == self.name: loglistbox.itemconfig(END, bg='green', fg='black') else: loglistbox.itemconfig(END, bg='red', fg='black') def editidentity(self): self.logerror("Not implemented. Here is a dump of this node's identity:") self.loginfo(identity.Systemidentity) self.loginfo(identity.SystemUUID) def usertransmit(self): def send(msg): if self.fixsender.get() and msg.sender != self.name: self.loginfo("Fixing sender to '%s'." % self.name) msg.sender = self.name self.loginfo("Transmitting message '%s'" % msg) self.transmit(msg) self.__FrameInput['bg'] = self.defaultcolors['bg'] message = self.__EntryInput.get() if len(message) <= 1: self.logdebug("No message to send entered.") return try: msg = jsonpickle.decode(message) send(msg) except ValueError as e: errmsg = 'Invalid JSON:\n%s' % e self.logerror(e) if "column" in errmsg: col = errmsg.split("(char ")[1].split(")")[0] col = col.split(" -")[0] self.__EntryInput.icursor(col) self.logwarning(errmsg) self.__FrameInput['bg'] = 'red' # self.__FrameInput['fg'] = 'yellow' messagebox.showinfo("Transmit failed!", errmsg) if self.autoclear.get(): self.clearEntry() def rebuildNodeMenu(self): NodeMenu = self.__MenuNodes NodeMenu.delete(4, END) for node in self.nodelist: NodeMenu.add_cascade(menu=self.nodelist[node]['menu'], label=node if node != "" else "LOCAL") def __handleNewNode(self, node): if node not in self.nodelist: self.loginfo("New node appeared! Hmm.") else: self.loginfo("Node rescanned.") print self.__MenuNodes componentlist = {} ComponentMenu = Menu(self.__MenuNodes) ComponentMenu.add_command(label="Scan", command=lambda node=node: self.scanregistry(node)) ComponentMenu.add_command(label="Copy Name", command=lambda node=node: self.copystring(node)) ComponentMenu.add_separator() nodeinfo = {'componentlist': componentlist, 'menu': ComponentMenu} self.nodelist[node] = nodeinfo def handleResponse(self, msg): self.recordMessage(msg) def __addComponents(components, node): componentlist = self.nodelist[node]['componentlist'] ComponentMenu = self.nodelist[node]['menu'] for comp in components: self.loginfo("Adding component '%s@%s'" % (comp, node)) if self.autoscan.get() and comp not in componentlist: self.scancomponent(comp, node) FuncMenu = Menu(ComponentMenu) FuncMenu.add_command(label="Scan", command=lambda (name,node)=(comp, node): self.scancomponent(name, node)) FuncMenu.add_command(label="Copy Name", command=lambda name=comp: self.copystring(name)) FuncMenu.add_command(label="Compose...", command=lambda (name,node)=(comp,node): self.composeMessage(name, node)) FuncMenu.add_separator() FuncMenu = Menu(ComponentMenu) ComponentMenu.add_cascade(label=comp, menu=FuncMenu) componentlist[comp] = {'menu': FuncMenu} def __handleListRegisteredTemplates(msg): MenuTemplates = self.__MenuTemplates MenuTemplates.delete(0, END) for template in sorted(msg.arg): node = '' MenuTemplates.add_command(label=template, command=lambda (name,node)=(template, node): self.createcomponent(name, node)) self.__MenuTemplates = MenuTemplates def __handleComponentInfo(msg): node = msg.sendernode if node not in self.nodelist: self.logerror('Node unknown') else: componentlist = self.nodelist[node]['componentlist'] if msg.sender not in componentlist: if self.autoscan.get(): self.loginfo("Unknown component '%s'. Rescanning registry." % msg.senderid) self.scanregistry(node) else: self.loginfo("Unknown component's ('%s') info encountered. Ignoring.") else: self.logdebug("Got a component's ('%s') RPC info. Parsing." % msg.sender) if componentlist[msg.sender] == 'scanned': self.logdebug("Scan from a self-created component returned.") component = msg.sender result = msg.arg componentlist[component]["info"] = result FuncMenu = componentlist[component]["menu"] FuncMenu.delete(5, END) mr = result['methods'] for meth in mr: self.logdebug("Got method '%s'." % meth) if len(mr[meth]['args']) > 0: FuncMenu.add_command(label=meth, command=lambda (node, name, meth)=(node, component, meth): self.callComplexMethod(name, node, meth)) else: FuncMenu.add_command(label=meth, command=lambda (node, name, meth)=(node, component, meth): self.callSimpleMethod(name, node, meth)) def __handleCreateComponent(msg): node = msg.sendernode component = msg.arg if node not in self.nodelist: self.__handleNewNode(node) componentlist = self.nodelist[node]['componentlist'] __addComponents([component], node) def __handleRegisteredComponents(msg): node = msg.sendernode self.loginfo("Got a list of registered components from '%s'. Parsing." % node) self.__handleNewNode(node) # Schema nodelist: # {nodeUUID: {'componentlist': componentlist, 'menu': ComponentMenu} # Schema componentlist: # {componentname: {'funclist': funclist, 'menu': funcmenu} # Schema funclist: # {func: menu} components = msg.arg __addComponents(components, node) self.rebuildNodeMenu() def __handleGatewayList(msg): self.loginfo("Received a list of connected nodes.") for node in msg.arg: self.__handleNewNode(node) if self.autoscan.get(): self.scanregistry(node) self.rebuildNodeMenu() if isinstance(msg, Message): if msg.sender == self.systemdispatcher: if msg.func == "listgateways": __handleGatewayList(msg) if msg.sender == self.systemregistry and not msg.error: if msg.func == "createComponent": __handleCreateComponent(msg) if msg.func == "listRegisteredComponents": __handleRegisteredComponents(msg) elif msg.func == "listRegisteredTemplates": __handleListRegisteredTemplates(msg) if msg.func == "getComponentInfo": if not msg.error: __handleComponentInfo(msg) if msg.func in ("renderArea", "renderCoord"): if not msg.error: if self.MapViewer: self.MapViewer.drawMap(msg.arg) else: self.MapViewer = TkMapDialog(msg.arg) self.MapViewer.activate() def scanlinetest(self): polygon = [[50, 5], [100, 270], [150, 270], [220, 30]] ScanlineTestDialog = TkScanlineTestDialog(polygon) def quit(self): self.logcritical("Shutting down hard.") try: import cherrypy self.loginfo("WebGate running. Stopping cherrypy first.") cherrypy.engine.stop() except ImportError: self.loginfo("WebGate not running. Not killing cherrypy.") Scheduler.scheduler.run.stop() def setupWindow(self): self.logdebug("Setting up TkAdmin GUI") Pmw.initialise(self.window) self.window.title(self.title) ### Menu ### self.__FrameMenu = Frame(self.window) self.__FrameMenu.pack(anchor='n', side='top') self.__Menu = Menu(self.window) self.__MenuFile = Menu(self.__Menu) self.__MenuEdit = Menu(self.__Menu) self.__MenuMessage = Menu(self.__Menu) self.__MenuSettings = Menu(self.__Menu) self.__MenuSystem = Menu(self.__Menu) self.__Menu.add_cascade(menu=self.__MenuFile, label="File") self.__Menu.add_cascade(menu=self.__MenuEdit, label="Edit") self.__Menu.add_cascade(menu=self.__MenuMessage, label="Message") self.__Menu.add_cascade(menu=self.__MenuSettings, label="Settings") self.__Menu.add_cascade(menu=self.__MenuSystem, label="System") self.window.config(menu=self.__Menu) self.__MenuFile.add_command(label="Update Message Log", command=self.updateMessageLog) self.__MenuFile.add_command(label="Quit", command=self.quit) self.autoscan = BooleanVar() self.fixsender = BooleanVar() self.autoclear = BooleanVar() self.showresponses = BooleanVar() self.__MenuMessage.add_command(label="View", command=self.showMessage) self.__MenuMessage.add_command(label="Compose New", command=self.composeMessage) self.__MenuSettings.add_checkbutton(label="Fix sender", onvalue=True, offvalue=False, variable=self.fixsender) self.__MenuSettings.add_checkbutton(label="Autoscan", onvalue=True, offvalue=False, variable=self.autoscan) self.__MenuSettings.add_checkbutton(label="Autoclear", onvalue=True, offvalue=False, variable=self.autoclear) self.__MenuSettings.add_checkbutton(label="Show responses", onvalue=True, offvalue=False, variable=self.showresponses) self.__MenuSystem.add_command(label="View/Edit identity", command=self.editidentity) self.__MenuTemplates = Menu(self.__MenuSystem) self.__MenuSystem.add_cascade(label='Create Component', menu=self.__MenuTemplates) self.__MenuNodes = Menu(self.__Menu) self.__MenuNodes.add_command(label="Update connected nodes", command=self.scangateways) self.__MenuNodes.add_command(label="Scan Local", command=self.scanregistry) self.__MenuNodes.add_command(label="Dump Nodelist", command=self.dumpnodelist) self.__MenuNodes.add_separator() self.__Menu.add_cascade(menu=self.__MenuNodes, label="Nodes") ### /Menu ### ### Output ### self.__FrameOutput = Frame(self.window) self.__FrameOutput.pack(side='top', fill='both', expand='yes') self.__NotebookOutput = Pmw.NoteBook(self.__FrameOutput) self.__NotebookOutput.pack(fill='both', expand=1) self.__PageMessages = self.__NotebookOutput.add('Messages') self.__PageMap = self.__NotebookOutput.add('Map') self.__PageResponses = self.__NotebookOutput.add('Responses') #self.__PageLog = self.__NotebookOutput.add('Log') # Needs a loggercomponent and revised logging first self.__MessageLog = Pmw.ScrolledListBox(self.__PageMessages) self.__MessageLog.pack(expand='yes', fill='both') self.__NotebookOutput.tab('Messages').focus_set() self.__FrameInput = Frame(self.window, borderwidth=2) self.__FrameInput.pack(anchor='s', expand='no', fill='x', side='top') self.__FrameStatusbar = Frame(self.window, relief='raised') self.__FrameStatusbar.pack(anchor='sw', side='top') # ,fill='x' self.__LabelStatus = Label(self.__FrameStatusbar, text='Ready.') self.__LabelStatus.pack(anchor='w', expand='yes', side='top') # ,fill='both' self.__FrameResponses = Frame(self.__PageResponses, background="yellow") self.__FrameResponsesHeader = Frame(self.__FrameResponses) self.__LabelResponses = Label(self.__FrameResponsesHeader, text='Responses') self.__LabelResponses.pack(anchor='e', side='right', fill='x') self.__ButtonClearResponses = Button(self.__FrameResponsesHeader, text='Clear') self.__ButtonClearResponses.pack(anchor='w', side='left') self.__FrameResponsesHeader.pack(anchor='n', fill='x', side=TOP) self.__TextResponses = Pmw.ScrolledText(self.__FrameResponses) self.__TextResponses.pack(expand=1, fill='both', side=BOTTOM) self.__FrameResponses.pack(expand=1, fill="both") #self.__FrameLog = Frame(self.__PageLog) #self.__FrameLog.pack(side='left', expand=1, fill="both") #self.__FrameLogHeader = Frame(self.__FrameLog) #self.__FrameLogHeader.pack(anchor='n',expand='yes', fill='x', side='top') #self.__LabelLog = Label(self.__FrameLogHeader,text='Log') #self.__LabelLog.pack(anchor='e',side='right', fill='both') #self.__ButtonClearLog = Button(self.__FrameLogHeader, text='Clear') #self.__ButtonClearLog.pack(anchor='w',side='left') #self.__TextLog = Pmw.ScrolledText(self.__FrameLog) #self.__TextLog.pack(expand=1,fill='both') self.__MapCanvas = Canvas(self.__PageMap) self.__MapCanvas.pack(expand=1, fill='both') self.__NotebookOutput.setnaturalsize() ### /Output ### ### Input ### self.__FrameInputEntry = Frame(self.__FrameInput) self.__EntryInput = Entry(self.__FrameInput) self.__EntryInput.pack(expand='yes', fill='both', side='left') self.__FrameTransmitButton = Frame(self.__FrameInput) self.__FrameTransmitButton.pack(anchor='w', side='left') self.__ButtonTransmit = Button(self.__FrameTransmitButton , text='Transmit') self.__ButtonTransmit.pack(expand='yes', fill='both', side='top') self.__FrameClearButton = Frame(self.__FrameInput) self.__FrameClearButton.pack(anchor='w', side='left') self.__ButtonClear = Button(self.__FrameClearButton, text='Clear') self.__ButtonClear.pack(expand='yes', fill='both', side='top') self.__FrameInputEntry.pack(side='left') ### /Input ### ### Bindings ### self.__MessageLog._listbox.bind("<Double-Button-1>", self.showMessage) self.__ButtonClearResponses.bind('<ButtonRelease-1>' , self.__on_ButtonClearResponses_Press) self.__ButtonTransmit.bind('<ButtonRelease-1>' , self.__on_ButtonTransmit_Release) self.__ButtonClear.bind('<ButtonPress-1>', self.__on_ButtonClear_Press) self.__EntryInput.bind('<Control-Return>', self.__on_EntryInput_Enter__C) self.defaultcolors = {'bg': self.window['bg'], 'fg': self.__EntryInput['fg']} def main(self): """ Main loop. Stub method, reimplement with your own functionality. Must regularly call self.tkupdate() to ensure tk event processing happens. """ if self.autoscan.get(): self.loginfo("Local autoscan initiated.") self.scanregistry() while not self.isDestroyed(): yield 1 if self.dataReady("control"): msg = self.recv("control") if isinstance(msg, producerFinished) or isinstance(msg, shutdownMicroprocess): self.send(msg, "signal") self.window.destroy() if self.dataReady("inbox"): msg = self.recv("inbox") self.logdebug("Received message '%s'" % msg) self.handleRPC(msg) if self.showresponses.get(): self.__TextResponses.insert(END, "%s\n" % msg) self.tkupdate()
class AuthPage(BasePage): def __init__(self, parent, controller): self.is_auth = False self.mutex = Lock() BasePage.__init__(self, parent, controller) def prepare(self): mode = self.mode.get() user = self.userVar.get() pwd = self.pwdVar.get() if mode is 1 and user and pwd: self.confirm(mode, user, pwd) self.userInput.focus_force() def printErr(self, message): self.errLog.config(text=message) def entryToggle(self, toggle, target): if(toggle): for t in target: t.configure(state='normal') else: for t in target: t.configure(state='disabled') def confirm(self, mode, user, pwd): self.mutex.acquire() try: if mode == 1 and not self.is_auth: # mode:1 flash from pvt # TODO: the GUI do not updated due to the correct way to update the UI in tk is to use the after method. self.logger.log('Logging into server...', status_callback=self.printErr) if self.controller.setAuth(user, pwd): self.is_auth = True self.ok.config(state="disabled") self.userInput.config(state="disabled") self.pwdInput.config(state="disabled") self.controller.transition(self) else: self.printErr("Auththentication failed") else: # mode:2, flash from local pass finally: self.mutex.release() def pressReturnKey(self, event=None): if len(self.userVar.get()) > 0 and len(self.pwdVar.get()) > 0: self.confirm(self.mode.get(), self.userVar.get(), self.pwdVar.get()) elif len(self.userVar.get()) == 0: self.logger.log('Please enter username.', status_callback=self.printErr) self.userInput.focus_set() else: self.logger.log('Please enter password.', status_callback=self.printErr) self.pwdInput.focus_set() def setupView(self, title="Test Auth Page", user='', pwd_ori=''): self.mode = IntVar() self.mode.set(1) Label(self, width=25).grid(row=1, column=0, columnspan=2) self.errLog = Label(self, text="") self.errLog.grid( row=4, column=1, columnspan=3, rowspan=3, sticky="NWSE" ) self.userVar = StringVar() self.pwdVar = StringVar() Label(self, text="Account").grid(row=2, column=1, sticky='E') self.userInput = Entry( self, textvariable=self.userVar, width="30") self.userInput.grid( row=2, column=2, columnspan=2, sticky="W") Label(self, text="Password").grid(row=3, column=1, sticky='E') self.pwdInput = Entry( self, textvariable=self.pwdVar, show="*", width="30") self.pwdInput.grid( row=3, column=2, columnspan=2, sticky="W") self.userVar.set(user) self.pwdVar.set(pwd_ori) Label( self, text=' Welcome to fxos flash tool', font=TITLE_FONT ).grid( row=0, column=1, columnspan=3, sticky="WE") Radiobutton(self, state='disabled', text='Download build from pvt', variable=self.mode, value=1, command=lambda: self.entryToggle( True, [self.userInput, self.pwdInput]) ).grid(row=1, column=2, columnspan=2, sticky="E") Radiobutton(self, state='disabled', text='Flash build from local', variable=self.mode, value=2, command=lambda: self.entryToggle( False, [self.userInput, self.pwdInput]) ).grid(row=1, column=4, sticky="W") self.ok = Button(self, text='Next', command=lambda: self. confirm(self.mode.get(), self.userVar.get(), self.pwdVar.get())) self.ok.grid(row=4, column=4, sticky="W") self.userInput.bind('<Return>', self.pressReturnKey) self.pwdInput.bind('<Return>', self.pressReturnKey) self.ok.bind('<Return>', self.pressReturnKey)
class ListPage(BasePage): def __init__(self, parent, controller): BasePage.__init__(self, parent, controller) self.mutex = Lock() def prepare(self): self.deviceList.config(state='normal') self.versionList.config(state='disabled') self.engList.config(state='disabled') self.packageList.config(state='disabled') self.ok.config(state='disabled') self.setData(self.controller.data) self.setDeviceList(self.data.keys()) self.controller.setDefault(self, self.controller.loadOptions()) self.deviceList.focus_force() def printErr(self, message): self.errLog.config(text=message) def setData(self, data): self.data = data def setupView(self, title="Select your flash", data=None): if(data): self.setData(data) self.errLog = Label(self, text="") self.errLog.grid(row=4, column=1, columnspan=3, sticky="NWSE") self.desc = Label(self, text=title, font=TITLE_FONT) self.desc.grid(row=0, column=0, columnspan=2) self.ok = Button(self, text='Next', command=lambda: self. confirm()) self.ok.grid(row=4, column=3, sticky="E") self.ok.config(state="disabled") self.deviceLabel = Label(self, text="Device", font=TITLE_FONT) self.deviceLabel.grid(row=1, column=0) self.deviceList = Listbox(self, exportselection=0) self.deviceList.grid(row=2, column=0) self.deviceList.bind('<<ListboxSelect>>', self.deviceOnSelect) self.deviceList.config(state="disabled") self.versionLabel = Label(self, text="Branch", font=TITLE_FONT) self.versionLabel.grid(row=1, column=1) self.versionList = Listbox(self, exportselection=0) self.versionList.grid(row=2, column=1) self.versionList.bind('<<ListboxSelect>>', self.versionOnSelect) self.versionList.config(state="disabled") self.engLabel = Label(self, text="Build Type", font=TITLE_FONT) self.engLabel.grid(row=1, column=2) self.engList = Listbox(self, exportselection=0) self.engList.grid(row=2, column=2) self.engList.bind('<<ListboxSelect>>', self.engOnSelect) self.engList.config(state="disabled") self.packageLabel = Label( self, text="Gecko/Gaia/Full", font=TITLE_FONT) self.packageLabel.grid(row=1, column=3) self.packageList = Listbox(self, exportselection=0) self.packageList.grid(row=2, column=3) self.packageList.bind('<<ListboxSelect>>', self.packageOnSelect) self.packageList.config(state="disabled") self.bidVar = StringVar() Label(self, text="Build ID").grid(row=3, column=0, sticky='E') self.bidInput = Entry( self, textvariable=self.bidVar, width="30") self.bidInput.grid( row=3, column=1, columnspan=2, sticky="W") self.bidVar.set('latest') # binding unfocus for build id field self.bidInput.bind('<FocusOut>', self.updateBuildId) # binding the Return Key to each componments self.deviceList.bind('<Return>', self.pressReturnKey) self.versionList.bind('<Return>', self.pressReturnKey) self.engList.bind('<Return>', self.pressReturnKey) self.packageList.bind('<Return>', self.pressReturnKey) self.bidInput.bind('<Return>', self.pressReturnKey) self.ok.bind('<Return>', self.pressReturnKey) def selection_all_checked(self): result = False if len(self.deviceList.curselection()) == 0: self.logger.log('Please select device.', status_callback=self.printErr) self.ok.config(state="disabled") self.deviceList.focus_set() elif len(self.versionList.curselection()) == 0: self.logger.log('Please select branch.', status_callback=self.printErr) self.ok.config(state="disabled") self.versionList.focus_set() elif len(self.engList.curselection()) == 0: self.logger.log('Please select user or engineer build.', status_callback=self.printErr) self.ok.config(state="disabled") self.engList.focus_set() elif len(self.packageList.curselection()) == 0: self.logger.log('Please select package to flash.', status_callback=self.printErr) self.ok.config(state="disabled") self.packageList.focus_set() elif len(self.bidVar.get()) == 0: self.logger.log('Please enter build ID to flash or use "latest" to get the newest', status_callback=self.printErr) self.bidVar.set('latest') else: result = True return result def updateBuildId(self, event=None): if len(self.engList.curselection()) != 0: self.refreshPackageList() def pressReturnKey(self, event=None): if self.selection_all_checked(): self.ok.config(state="disabled") self.confirm() def deviceOnSelect(self, evt): self.setVersionList() def versionOnSelect(self, evt): self.setEngList() def engOnSelect(self, evt): self.refreshPackageList() # hard coded right now def packageOnSelect(self, evt): self.ok.config(state="normal") def confirm(self): self.mutex.acquire() try: if self.selection_all_checked(): self.ok.config(state="disabled") params = [] package = self.packageList.get(self.packageList.curselection()[0]) self.logger.log('Start to flash [' + package + '].', status_callback=self.printErr) if(PathParser._IMAGES in package): params.append(PathParser._IMAGES) else: if(PathParser._GAIA in package): params.append(PathParser._GAIA) if(PathParser._GECKO in package): params.append(PathParser._GECKO) self.controller.doFlash(params) self.packageList.select_clear(0, END) self.controller.transition(self) finally: self.mutex.release() def setDeviceList(self, device=[]): self.deviceList.delete(0, END) for li in device: self.deviceList.insert(END, li) def setVersionList(self, version=[]): if len(version) == 0: version = self.data[ self.deviceList.get(self.deviceList.curselection()) ] self.versionList.config(state="normal") self.engList.config(state="disabled") self.packageList.config(state="disabled") self.ok.config(state="disabled") self.versionList.delete(0, END) for li in version: self.versionList.insert(END, li) def setEngList(self, eng=[]): if len(eng) == 0: device = self.deviceList.get(self.deviceList.curselection()) version = self.versionList.get(self.versionList.curselection()) eng = self.data[device][version] self.engList.config(state="normal") self.packageList.config(state="disabled") self.ok.config(state="disabled") self.engList.delete(0, END) for li in eng: self.engList.insert(END, li) def refreshPackageList(self): self.mutex.acquire() try: self.packageList.config(state="normal") self.ok.config(state="normal") self.packageList.delete(0, END) device = self.deviceList.get(self.deviceList.curselection()) version = self.versionList.get(self.versionList.curselection()) eng = self.engList.get(self.engList.curselection()) # if the value is '' or 'latest', the set the build_id option as ''. buildId = '' if (len(self.bidVar.get()) == 0 or self.bidVar.get() == 'latest') else self.bidVar.get() package = self.controller.getPackages(self.data[device][version][eng]['src'], build_id=buildId) if len(package) == 0: package = [PathParser._GAIA_GECKO, PathParser._GAIA, PathParser._GECKO, PathParser._IMAGES] for li in package: self.packageList.insert(END, li) finally: self.mutex.release()
class SelectBox: """ SelectBox class should be considered "private" and is used entirely by the ScaleUI class. It is responsible for the raw mechanics of actually drawing a box on the selected entities and dealing with user-input on the control points. """ MIN_WIDTH = 30 MIN_HEIGHT = 30 def __init__(self, dc, selectionDict): self.__dc = dc self.__selectionDict = selectionDict self.__selectedEntityBoxDict = dict() for tag in selectionDict: obj = selectionDict[tag][1] atom3i = obj.semanticObject.parent self.__UI_Statechart = atom3i.UI_Statechart self.__callbackState = atom3i.cb break bbox = getBoundingBox(selectionDict) minx, miny, maxx, maxy = bbox # Put a box around the selection self.__selectionBoxHandler = self.__dc.create_rectangle(bbox, width=4, outline='green', dash=(4,4)) # Define re-size entity buttons self.NW_button = Button(self.__dc, bg='SpringGreen') self.NE_button = Button(self.__dc, bg='SpringGreen') self.SW_button = Button(self.__dc, bg='SpringGreen') self.SE_button = Button(self.__dc, bg='SpringGreen') self.NW_button.pack() self.NE_button.pack() self.SW_button.pack() self.SE_button.pack() self.NW_button.bind('<Button-1>', self.scaleHandler) self.NE_button.bind('<Button-1>', self.scaleHandler) self.SW_button.bind('<Button-1>', self.scaleHandler) self.SE_button.bind('<Button-1>', self.scaleHandler) # Define re-size text buttons self.N_button = Button(self.__dc, font=("Times", 8, "bold"), text='T', bg='SpringGreen') self.E_button = Button(self.__dc, font=("Times", 8, "bold"), text='T', bg='SpringGreen') self.S_button = Button(self.__dc, font=("Times", 8, "bold"), text='T', bg='SpringGreen') self.W_button = Button(self.__dc, font=("Times", 8, "bold"), text='T', bg='SpringGreen') self.N_button.pack() self.E_button.pack() self.S_button.pack() self.W_button.pack() self.N_button.bind('<Button-1>', self.textScaleHandler) self.E_button.bind('<Button-1>', self.textScaleHandler) self.S_button.bind('<Button-1>', self.textScaleHandler) self.W_button.bind('<Button-1>', self.textScaleHandler) # Place the buttons on the canvas size = 10 self.NW_window = self.__dc.create_window(minx, miny, width=size, height=size, window=self.NW_button) self.NE_window = self.__dc.create_window(maxx, miny, width=size, height=size, window=self.NE_button) self.SW_window = self.__dc.create_window(minx, maxy, width=size, height=size, window=self.SW_button) self.SE_window = self.__dc.create_window(maxx, maxy, width=size, height=size, window=self.SE_button) # Text re-size buttons widthOver2 = float(maxx - minx) / 2.0 heightOver2 = float(maxy - miny) / 2.0 self.N_window = self.__dc.create_window(minx + widthOver2, miny, width=size, height=size, window=self.N_button) self.E_window = self.__dc.create_window(maxx, miny + heightOver2, width=size, height=size, window=self.E_button) self.S_window = self.__dc.create_window(minx + widthOver2, maxy, width=size, height=size, window=self.S_button) self.W_window = self.__dc.create_window(minx, miny + heightOver2, width=size, height=size, window=self.W_button) # Make individual elements of the selection obvious if(len(selectionDict) > 1): self.individualPackaging() def individualPackaging(self): """ Give each element of the selection its own mini-box """ for tag in self.__selectionDict: obj = self.__selectionDict[tag][1] self.__selectedEntityBoxDict[tag] = self.__dc.create_rectangle( obj.getbbox(), width=3, outline='green', dash=(2,2)) def destroy(self): self.__dc.delete(self.__selectionBoxHandler) self.__dc.delete(self.NW_window) self.__dc.delete(self.NE_window) self.__dc.delete(self.SW_window) self.__dc.delete(self.SE_window) self.__dc.delete(self.N_window) self.__dc.delete(self.E_window) self.__dc.delete(self.S_window) self.__dc.delete(self.W_window) for itemHandler in self.__selectedEntityBoxDict.values(): self.__dc.delete(itemHandler) self.__individuallyPackagedList = dict() def scaleHandler(self, event=None): """ Activate the UI_Statechart to handle the reactive behaviour """ self.__UI_Statechart.event('<KeyPress-r>', self) def textScaleHandler(self, event=None): """ Activate the UI_Statechart to handle the reactive behaviour """ if(not self.__callbackState.isLabelDragMode()): self.__callbackState.toggleLabelDragMode() self.__UI_Statechart.event('<KeyPress-r>', self) self.__callbackState.toggleLabelDragMode() else: self.__UI_Statechart.event('<KeyPress-r>', self) def update(self): """ After scaling, make sure the boxes & buttons are scaled too! """ minx, miny, maxx, maxy = getBoundingBox(self.__selectionDict) self.__dc.coords(self.__selectionBoxHandler, (minx, miny, maxx, maxy)) self.__dc.coords(self.NW_window, (minx, miny)) self.__dc.coords(self.NE_window, (maxx, miny)) self.__dc.coords(self.SW_window, (minx, maxy)) self.__dc.coords(self.SE_window, (maxx, maxy)) widthOver2 = float(maxx - minx) / 2.0 heightOver2 = float(maxy - miny) / 2.0 self.__dc.coords(self.N_window, (minx + widthOver2, miny)) self.__dc.coords(self.E_window, (maxx, miny + heightOver2)) self.__dc.coords(self.S_window, (minx + widthOver2, maxy)) self.__dc.coords(self.W_window, (minx, miny + heightOver2)) for tag in self.__selectedEntityBoxDict: obj = self.__selectionDict[tag][1] try: self.__dc.coords(self.__selectedEntityBoxDict[tag], obj.getbbox()) except: pass
class AuthPage(BasePage): def __init__(self, parent, controller): self.is_auth = False self.mutex = Lock() BasePage.__init__(self, parent, controller) def prepare(self): mode = self.mode.get() user = self.userVar.get() pwd = self.pwdVar.get() if mode is 1 and user and pwd: self.confirm(mode, user, pwd) self.userInput.focus_force() def printErr(self, message): self.errLog.config(text=message) def entryToggle(self, toggle, target): if (toggle): for t in target: t.configure(state='normal') else: for t in target: t.configure(state='disabled') def confirm(self, mode, user, pwd): self.mutex.acquire() try: if mode == 1 and not self.is_auth: # mode:1 flash from pvt # TODO: the GUI do not updated due to the correct way to update the UI in tk is to use the after method. self.logger.log('Logging into server...', status_callback=self.printErr) if self.controller.setAuth(user, pwd): self.is_auth = True self.ok.config(state="disabled") self.userInput.config(state="disabled") self.pwdInput.config(state="disabled") self.controller.transition(self) else: self.printErr("Auththentication failed") else: # mode:2, flash from local pass finally: self.mutex.release() def pressReturnKey(self, event=None): if len(self.userVar.get()) > 0 and len(self.pwdVar.get()) > 0: self.confirm(self.mode.get(), self.userVar.get(), self.pwdVar.get()) elif len(self.userVar.get()) == 0: self.logger.log('Please enter username.', status_callback=self.printErr) self.userInput.focus_set() else: self.logger.log('Please enter password.', status_callback=self.printErr) self.pwdInput.focus_set() def setupView(self, title="Test Auth Page", user='', pwd_ori=''): self.mode = IntVar() self.mode.set(1) Label(self, width=25).grid(row=1, column=0, columnspan=2) self.errLog = Label(self, text="") self.errLog.grid(row=4, column=1, columnspan=3, rowspan=3, sticky="NWSE") self.userVar = StringVar() self.pwdVar = StringVar() Label(self, text="Account").grid(row=2, column=1, sticky='E') self.userInput = Entry(self, textvariable=self.userVar, width="30") self.userInput.grid(row=2, column=2, columnspan=2, sticky="W") Label(self, text="Password").grid(row=3, column=1, sticky='E') self.pwdInput = Entry(self, textvariable=self.pwdVar, show="*", width="30") self.pwdInput.grid(row=3, column=2, columnspan=2, sticky="W") self.userVar.set(user) self.pwdVar.set(pwd_ori) Label(self, text=' Welcome to fxos flash tool', font=TITLE_FONT).grid(row=0, column=1, columnspan=3, sticky="WE") Radiobutton(self, state='disabled', text='Download build from pvt', variable=self.mode, value=1, command=lambda: self.entryToggle( True, [self.userInput, self.pwdInput])).grid( row=1, column=2, columnspan=2, sticky="E") Radiobutton(self, state='disabled', text='Flash build from local', variable=self.mode, value=2, command=lambda: self.entryToggle( False, [self.userInput, self.pwdInput])).grid( row=1, column=4, sticky="W") self.ok = Button(self, text='Next', command=lambda: self.confirm(self.mode.get( ), self.userVar.get(), self.pwdVar.get())) self.ok.grid(row=4, column=4, sticky="W") self.userInput.bind('<Return>', self.pressReturnKey) self.pwdInput.bind('<Return>', self.pressReturnKey) self.ok.bind('<Return>', self.pressReturnKey)
def initUI(self): ''' Initializes the interface ''' AtoH = {} for x, y in zip(range(1, 10), string.ascii_uppercase): AtoH[x] = y AtoH[9] = '' self.parent.title("Aphid Visualizer") Style().configure("TButton", padding=(0, 5, 0, 5), font='serif 10') for i in range(5): self.columnconfigure(i, pad=3) if i > 0: label = str(i) widget = Label(self, text=label) widget.grid(row=0, column=i) self.widget_dict["colLabel:0,%s" % label] = widget for i in range(10): self.rowconfigure(i, pad=5) if i > 0: label = AtoH[i] widget = Label(self, text=label) widget.grid(row=i, column=0) self.widget_dict["rowLabel:%s,0" % i] = widget self.rowconfigure(9, pad = 25) entry = Entry(self) for r in range(1, 9): for c in range(1, 5): lbl = Canvas(self, width=64,height=64, bg = "SystemButtonFace") lbl.grid(row=r, column=c) self.widget_dict["Canvas:%s%s" % (AtoH[r], c)] = lbl newFile = Button(self, text="New File", bg = "SystemButtonFace") newFile.grid(row=9, column=1, sticky= "we") newFile.bind("<Button-1>", self.set_dataList) self.widget_dict["Button:newFile"] = newFile next = Button(self, text="Next") next.grid(row=9, column=3, sticky= "we") next.bind("<1>", self.change_time_forward) self.widget_dict["Button:next"] = next previous = Button(self, text="Previous") previous.grid(row=9, column=2, sticky= "we") previous.bind("<1>", self.change_time_backward) draw = Button(self,text="Draw") draw.grid(row=9, column = 4, sticky= "we") draw.bind("<1>", self.draw_circles) self.widget_dict["Button:draw"] = draw testprint = Button(self, text="testprint") # testprint.grid(row=9, column=5, sticky= "we") testprint.bind('<1>', self.print_value_event) self.widget_dict["Button:testprint"] = testprint toggle = Button(self,text="Toggle Disease") toggle.grid(row=10, column = 4, sticky= "we") toggle.bind("<1>", self.toggle_disease) self.widget_dict["Button:toggle"] = toggle self.pack()
def sunfounder_client(ip, key): #!/usr/bin/env python # -*- coding: utf-8 -*- from Tkinter import Tk, Button, Label, Scale, HORIZONTAL print "Connecting to IP", ip ctrl_cmd = ['forward', 'backward', 'left', 'right', 'stop', 'read cpu_temp', 'home', 'distance', 'x+', 'x-', 'y+', 'y-', 'xy_home'] top = Tk() # Create a top window top.title('Sunfounder Raspberry Pi Smart Video Car') HOST = ip # Server(Raspberry Pi) IP address PORT = 21567 BUFSIZ = 1024 # buffer size ADDR = (HOST, PORT) tcpCliSock = socket(AF_INET, SOCK_STREAM) # Create a socket tcpCliSock.connect(ADDR) # Connect with the server # ============================================================================= # The function is to send the command forward to the server, so as to make the # car move forward. # ============================================================================= def forward_fun(event): print "\nUser command = forward" print "Encrypted command = ",crypto.AES_encrypt('forward',key)[2] tcpCliSock.send(str(crypto.AES_encrypt('forward',key))) def backward_fun(event): print '\nUser command = backward' print "Encrypted command = ",crypto.AES_encrypt('backward',key)[2] tcpCliSock.send(str(crypto.AES_encrypt('backward',key))) def left_fun(event): print '\nUser command = left' print "Encrypted command = ",crypto.AES_encrypt('left',key)[2] tcpCliSock.send(str(crypto.AES_encrypt('left',key))) def right_fun(event): print '\nUser command = right' print "Encrypted command = ",crypto.AES_encrypt('right',key)[2] tcpCliSock.send(str(crypto.AES_encrypt('right',key))) def stop_fun(event): print '\nUser command = stop' print "Encrypted command = ",crypto.AES_encrypt('stop',key)[2] tcpCliSock.send(str(crypto.AES_encrypt('stop',key))) def home_fun(event): print '\nUser command = home' print "Encrypted command = ",crypto.AES_encrypt('home',key)[2] tcpCliSock.send(str(crypto.AES_encrypt('home',key))) def x_increase(event): print '\nUser command = x+' print "Encrypted command = ",crypto.AES_encrypt('x+',key)[2] tcpCliSock.send(str(crypto.AES_encrypt('x+',key))) def x_decrease(event): print '\nUser command = x-' print "Encrypted command = ",crypto.AES_encrypt('x-',key)[2] tcpCliSock.send(str(crypto.AES_encrypt('x-',key))) def y_increase(event): print '\nUser command = y+' print "Encrypted command = ",crypto.AES_encrypt('y+',key)[2] tcpCliSock.send(str(crypto.AES_encrypt('y+',key))) def y_decrease(event): print '\nUser command = y-' print "Encrypted command = ",crypto.AES_encrypt('y-',key)[2] tcpCliSock.send(str(crypto.AES_encrypt('y-',key))) def xy_home(event): print '\nUser command = xy_home' print "Encrypted command = ",crypto.AES_encrypt('xy_home',key)[2] tcpCliSock.send(str(crypto.AES_encrypt('xy_home',key))) # ============================================================================= # Exit the GUI program and close the network connection between the client # and server. # ============================================================================= def quit_fun(event): print "\nShutting down program..." top.quit() tcpCliSock.send(str(crypto.AES_encrypt('stop',key))) tcpCliSock.close() # ============================================================================= # Create buttons # ============================================================================= Btn0 = Button(top, width=5, text='Forward') Btn1 = Button(top, width=5, text='Backward') Btn2 = Button(top, width=5, text='Left') Btn3 = Button(top, width=5, text='Right') Btn4 = Button(top, width=5, text='Quit') Btn5 = Button(top, width=5, height=2, text='Home') # ============================================================================= # Buttons layout # ============================================================================= Btn0.grid(row=0,column=1) Btn1.grid(row=2,column=1) Btn2.grid(row=1,column=0) Btn3.grid(row=1,column=2) Btn4.grid(row=3,column=2) Btn5.grid(row=1,column=1) # ============================================================================= # Bind the buttons with the corresponding callback function. # ============================================================================= Btn0.bind('<ButtonPress-1>', forward_fun) # When button0 is pressed down, call the function forward_fun(). Btn1.bind('<ButtonPress-1>', backward_fun) Btn2.bind('<ButtonPress-1>', left_fun) Btn3.bind('<ButtonPress-1>', right_fun) Btn0.bind('<ButtonRelease-1>', stop_fun) # When button0 is released, call the function stop_fun(). Btn1.bind('<ButtonRelease-1>', stop_fun) Btn2.bind('<ButtonRelease-1>', stop_fun) Btn3.bind('<ButtonRelease-1>', stop_fun) Btn4.bind('<ButtonRelease-1>', quit_fun) Btn5.bind('<ButtonRelease-1>', home_fun) # ============================================================================= # Create buttons # ============================================================================= Btn07 = Button(top, width=5, text='X+', bg='red') Btn08 = Button(top, width=5, text='X-', bg='red') Btn09 = Button(top, width=5, text='Y-', bg='red') Btn10 = Button(top, width=5, text='Y+', bg='red') Btn11 = Button(top, width=5, height=2, text='HOME', bg='red') # ============================================================================= # Buttons layout # ============================================================================= Btn07.grid(row=1,column=5) Btn08.grid(row=1,column=3) Btn09.grid(row=2,column=4) Btn10.grid(row=0,column=4) Btn11.grid(row=1,column=4) # ============================================================================= # Bind button events # ============================================================================= Btn07.bind('<ButtonPress-1>', x_increase) Btn08.bind('<ButtonPress-1>', x_decrease) Btn09.bind('<ButtonPress-1>', y_decrease) Btn10.bind('<ButtonPress-1>', y_increase) Btn11.bind('<ButtonPress-1>', xy_home) #Btn07.bind('<ButtonRelease-1>', home_fun) #Btn08.bind('<ButtonRelease-1>', home_fun) #Btn09.bind('<ButtonRelease-1>', home_fun) #Btn10.bind('<ButtonRelease-1>', home_fun) #Btn11.bind('<ButtonRelease-1>', home_fun) # ============================================================================= # Bind buttons on the keyboard with the corresponding callback function to # control the car remotely with the keyboard. # ============================================================================= top.bind('<KeyPress-a>', left_fun) # Press down key 'A' on the keyboard and the car will turn left. top.bind('<KeyPress-d>', right_fun) top.bind('<KeyPress-s>', backward_fun) top.bind('<KeyPress-w>', forward_fun) top.bind('<KeyPress-h>', home_fun) top.bind('<KeyRelease-a>', home_fun) # Release key 'A' and the car will turn back. top.bind('<KeyRelease-d>', home_fun) top.bind('<KeyRelease-s>', stop_fun) top.bind('<KeyRelease-w>', stop_fun) spd = 50 def changeSpeed(ev=None): tmp = 'speed' global spd spd = speed.get() data = tmp + str(spd) # Change the integers into strings and combine them with the string 'speed'. #print 'sendData = %s' % data print '\nUser command = ', data print "Encrypted command = ",crypto.AES_encrypt(data,key)[2] tcpCliSock.send(str(crypto.AES_encrypt(data,key))) # Send the speed data to the server(Raspberry Pi) label = Label(top, text='Speed:', fg='red') # Create a label label.grid(row=6, column=0) # Label layout speed = Scale(top, from_=0, to=100, orient=HORIZONTAL, command=changeSpeed) # Create a scale speed.set(50) speed.grid(row=6, column=1) def main(): top.mainloop() if __name__ == '__main__': main()
class MatrixProperties: """Gets the contaminant properties.""" def __init__(self, master, system, materials): """Constructor method. Defines the parameters to be obtained in this window.""" self.master = master self.fonttype = system.fonttype self.version = system.version self.superfont = get_superfont(self.fonttype) #superscript font self.tframe = Frame(master.tframe) self.frame = Frame(master.frame) self.bframe = Frame(master.bframe) self.top = None #flag for existence of toplevel# self.system = system self.materials = materials if system.matrices is None: self.matrices = [] self.nmatrices = 0 else: self.matrices = system.matrices self.nmatrices = system.nmatrices def make_widgets(self): """Make the widgets for the window.""" self.bgcolor = self.frame.cget('bg') # Construct all label widgets used in the problem self.instructions = Label(self.tframe, text = ' Please select the potential layer materials and provide the following properties: ') self.blankcolumn = Label(self.tframe, text ='', width = 1) self.editcolumn = Label(self.tframe, text =' ', width = 6) self.delcolumn = Label(self.tframe, text =' ', width = 6) self.namecolumn = Label(self.tframe, text =' ', width = 20) self.ecolumn = Label(self.tframe, text =' ', width = 15) self.rhocolumn = Label(self.tframe, text =' ', width = 15) self.foccolumn = Label(self.tframe, text =' ', width = 20) self.endcolumn = Label(self.tframe, text =' ', width = 2) self.namelabel = Label(self.tframe, text = 'Matrix') self.elabel = Label(self.tframe, text = 'Porosity') self.rholabel = Label(self.tframe, text = 'Bulk density' ) self.foclabel = Label(self.tframe, text = 'Organic carbon fraction') self.rhounit = Label(self.tframe, text = u'g/cm\u00B3') self.botblankcolumn = Label(self.frame, text ='', width = 1) self.boteditcolumn = Label(self.frame, text =' ', width = 6) self.botdelcolumn = Label(self.frame, text =' ', width = 6) self.botnamecolumn = Label(self.frame, text =' ', width = 20) self.botecolumn = Label(self.frame, text =' ', width = 15) self.botrhocolumn = Label(self.frame, text =' ', width = 15) self.botfoccolumn = Label(self.frame, text =' ', width = 20) self.botendcolumn = Label(self.frame, text =' ', width = 2) self.blank1 = Label(self.bframe, text = ' ') self.blank2 = Label(self.bframe, text = ' ') self.blank3 = Label(self.bframe, text = ' ') self.addwidget = Button(self.bframe, text = 'Add materials', command = self.addmatrix, width = 20) self.loadwidget = Button(self.bframe, text = 'Load materials', command = self.loadmatrix, width = 20) self.mixwidget = Button(self.bframe, text = 'Create mixtures', command = self.addmixture, width = 20) #show the widgets on the grid self.instructions.grid( row = 0, column = 0, sticky = 'W', padx = 8, columnspan = 6,) self.blankcolumn.grid( row = 1, column = 0, sticky = 'WE', padx = 1, pady = 1) self.editcolumn.grid( row = 1, column = 1, sticky = 'WE', padx = 1, pady = 1) self.delcolumn.grid( row = 1, column = 2, sticky = 'WE', padx = 1, pady = 1) self.namecolumn.grid( row = 1, column = 3, sticky = 'WE', padx = 1, pady = 1) self.ecolumn.grid( row = 1, column = 4, sticky = 'WE', padx = 1, pady = 1) self.rhocolumn.grid( row = 1, column = 5, sticky = 'WE', padx = 1, pady = 1) self.foccolumn.grid( row = 1, column = 6, sticky = 'WE', padx = 1, pady = 1) self.namelabel.grid( row = 2, column = 3, sticky = 'WE', padx = 1, pady = 1) self.elabel.grid ( row = 2, column = 4, sticky = 'WE', padx = 1, pady = 1) self.rholabel.grid ( row = 2, column = 5, sticky = 'WE', padx = 1, pady = 1) self.foclabel.grid ( row = 2, column = 6, sticky = 'WE', padx = 1, pady = 1) self.rhounit.grid ( row = 3, column = 5, sticky = 'WE', padx = 1, pady = 1) self.updatematrices() def updatematrices(self): self.addwidget.grid_forget() self.loadwidget.grid_forget() self.blank1.grid_forget() self.botblankcolumn.grid_forget() self.boteditcolumn.grid_forget() self.botdelcolumn.grid_forget() self.botnamecolumn.grid_forget() self.botecolumn.grid_forget() self.botrhocolumn.grid_forget() self.botfoccolumn.grid_forget() material_list = self.materials.keys() for matrix in self.matrices: if len(matrix.components) == 1 : try: material_list.remove(matrix.name) except: pass row = 4 for matrix in self.matrices: try: matrix.remove_propertieswidgets() except:pass matrix.number = self.matrices.index(matrix) + 1 matrix.propertieswidgets(self.frame, row, self.master) row = row + 1 self.botblankcolumn.grid( row = row, column = 0, sticky = 'WE', padx = 1, pady = 1) self.boteditcolumn.grid( row = row, column = 1, sticky = 'WE', padx = 1, pady = 1) self.botdelcolumn.grid( row = row, column = 2, sticky = 'WE', padx = 1, pady = 1) self.botnamecolumn.grid( row = row, column = 3, sticky = 'WE', padx = 1, pady = 1) self.botecolumn.grid( row = row, column = 4, sticky = 'WE', padx = 1, pady = 1) self.botrhocolumn.grid( row = row, column = 5, sticky = 'WE', padx = 1, pady = 1) self.botfoccolumn.grid( row = row, column = 6, sticky = 'WE', padx = 1, pady = 1) row = 0 self.blank1.grid(row = row) row = row + 1 self.blank2.grid(row = row) row = row + 1 self.addwidget.grid(row = row, columnspan = 11) row = row + 1 if len(material_list) > 0: self.loadwidget.grid(row = row, columnspan = 11) row = row + 1 self.mixwidget.grid(row = row, columnspan = 11) row = row + 1 self.addwidget.bind('<Return>', self.addmatrix) self.mixwidget.bind('<Return>', self.addmixture) if self.nmatrices == 0: self.focusbutton = self.addwidget else: self.focusbutton = None self.master.geometry() self.master.center() def addmixture(self, default = None): self.nmatrices = self.nmatrices + 1 self.matrices.append(Matrix(self.nmatrices)) if self.top is None: self.top = CapSimWindow(master = self.master, buttons = 2) self.top.make_window(MixtureEditor(self.top, self.system, self.matrices[-1], self.matrices, self.materials, editflag = 0)) self.top.tk.mainloop() if self.top.window.cancelflag == 0: self.matrices[-1].get_matrix(self.top.window) else: self.matrices.remove(self.matrices[-1]) self.nmatrices = self.nmatrices - 1 for component in self.matrices[-1].components: for matrix in self.matrices[:-1]: for sub_component in matrix.components: if sub_component.name == component.name: sub_component.e = component.e sub_component.rho = component.rho sub_component.foc = component.foc if len(matrix.components) > 1: e = 0 rho = 0 moc = 0 foc = 0 fractions = 0 for component in matrix.components: fractions = fractions + component.fraction e = e + component.fraction * component.e rho = rho + component.fraction * component.rho moc = moc + component.fraction * component.rho * component.foc foc = moc/rho matrix.e = (round(e,2)) matrix.rho = (round(rho,3)) matrix.foc = (round(foc,3)) else: matrix.e = matrix.components[-1].e matrix.rho = matrix.components[-1].rho matrix.foc = matrix.components[-1].foc if self.top is not None: self.top.destroy() self.top = None elif self.top is not None: tkmb.showerror(title = self.system.version, message = 'Please close the existing parameter input window first.') self.top.tk.focus() self.updatematrices() def addmatrix(self, default = None): self.nmatrices = self.nmatrices + 1 self.matrices.append(Matrix(self.nmatrices)) if self.top is None: self.top = CapSimWindow(master = self.master, buttons = 2) self.top.make_window(MatrixEditor(self.top, self.system, self.matrices[-1], self.matrices, self.materials, editflag = 0, newflag = 1)) self.top.tk.mainloop() if self.top.window.cancelflag == 0: self.matrices[-1].get_matrix(self.top.window) else: self.matrices.remove(self.matrices[-1]) self.nmatrices = self.nmatrices - 1 if len(self.matrices) > 0: for component in self.matrices[-1].components: for matrix in self.matrices[:-1]: for sub_component in matrix.components: if sub_component.name == component.name: sub_component.e = component.e sub_component.rho = component.rho sub_component.foc = component.foc if len(matrix.components) > 1: e = 0 rho = 0 moc = 0 foc = 0 fractions = 0 for component in matrix.components: fractions = fractions + component.fraction e = e + component.fraction * component.e rho = rho + component.fraction * component.rho moc = moc + component.fraction * component.rho * component.foc foc = moc/rho matrix.e = (round(e,2)) matrix.rho = (round(rho,3)) matrix.foc = (round(foc,3)) else: matrix.e = matrix.components[-1].e matrix.rho = matrix.components[-1].rho matrix.foc = matrix.components[-1].foc if self.top is not None: self.top.destroy() self.top = None elif self.top is not None: tkmb.showerror(title = self.system.version, message = 'Please close the existing parameter input window first.') self.top.tk.focus() self.updatematrices() def loadmatrix(self, default = None): self.nmatrices = self.nmatrices + 1 self.matrices.append(Matrix(self.nmatrices)) if self.top is None: self.top = CapSimWindow(master = self.master, buttons = 2) self.top.make_window(MatrixEditor(self.top, self.system, self.matrices[-1], self.matrices, self.materials, editflag = 0, newflag = 0)) self.top.tk.mainloop() if self.top.window.cancelflag == 0: self.matrices[-1].get_matrix(self.top.window) else: self.matrices.remove(self.matrices[-1]) self.nmatrices = self.nmatrices - 1 if len(self.matrices) > 0: for component in self.matrices[-1].components: for matrix in self.matrices[:-1]: for sub_component in matrix.components: if sub_component.name == component.name: sub_component.e = component.e sub_component.rho = component.rho sub_component.foc = component.foc if len(matrix.components) > 1: e = 0 rho = 0 moc = 0 foc = 0 fractions = 0 for component in matrix.components: fractions = fractions + component.fraction e = e + component.fraction * component.e rho = rho + component.fraction * component.rho moc = moc + component.fraction * component.rho * component.foc foc = moc/rho matrix.e = (round(e,2)) matrix.rho = (round(rho,3)) matrix.foc = (round(foc,3)) else: matrix.e = matrix.components[-1].e matrix.rho = matrix.components[-1].rho matrix.foc = matrix.components[-1].foc if self.top is not None: self.top.destroy() self.top = None elif self.top is not None: tkmb.showerror(title = self.system.version, message = 'Please close the existing parameter input window first.') self.top.tk.focus() self.updatematrices() def editmatrix(self, number): if self.top is None: self.top = CapSimWindow(master = self.master, buttons = 2) if len(self.matrices[number - 1].components) < 2: self.top.make_window(MatrixEditor(self.top, self.system, self.matrices[number-1], self.matrices, self.materials, editflag = 1, newflag = 0)) else: self.top.make_window(MixtureEditor(self.top, self.system,self.matrices[number-1], self.matrices, self.materials, editflag = 1)) self.top.tk.mainloop() if self.top.window.cancelflag == 0: self.matrices[number-1].get_matrix(self.top.window) if self.top is not None: self.top.destroy() self.top = None elif self.top is not None: tkmb.showerror(title = self.system.version, message = 'Please close the existing parameter input window first.') self.top.tk.focus() self.updatematrices() def deletematrix(self, number): if self.top is None: self.top = CapSimWindow(master = self.master, buttons = 2) self.top.make_window(MatrixDeleter(self.top, self.system, self.matrices[number-1])) self.top.tk.mainloop() if self.top.window.cancelflag == 0: self.matrices[number-1].remove_propertieswidgets() self.matrices.remove(self.matrices[number-1]) self.nmatrices = self.nmatrices - 1 if self.top is not None: self.top.destroy() self.top = None elif self.top is not None: tkmb.showerror(title = self.system.version, message = 'Please close the existing parameter input window first.') self.top.tk.focus() self.updatematrices() def error_check(self): error = 0 if self.nmatrices == 0: error = 1 return error def warning(self): tkmb.showerror(title = self.version, message = 'No matrices has been selected, please add matrices by pressing the button "Add materials" or the button "Add mixture"') self.focusbutton = None self.master.tk.lift()