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 __init__(self): Tk.__init__(self) self.title("Speed Reader") main_frame = MainFrame(master=self) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) main_frame.grid(padx=50, pady=50, sticky=(N, S, E, W))
class New_Doc(): def __init__(self): self.master = Tk() Label(self.master, text="Square_size:").grid(row=0) Label(self.master, text="Number of Squares Horizonal").grid(row=1) Label(self.master, text="Number of Squares Vertical").grid(row=2) self.e1 = Entry(self.master) self.e2 = Entry(self.master) self.e3 = Entry(self.master) self.e1.grid(row=0, column=1) self.e2.grid(row=1, column=1) self.e3.grid(row=2, column=1) Tkinter.Button(self.master, text='OK', command = self.show_entry_fields).grid(row=3, column = 0, sticky = W, pady = 4) Tkinter.Button(self.master, text='Cancel', command = self.master.destroy).grid(row=3, column = 1, sticky = W, pady = 4) mainloop() def show_entry_fields(self): puzzle = Square_Puzzle(int(self.e1.get()), int(self.e2.get()), int(self.e3.get())) self.master.destroy() Edit_Doc(puzzle)
def demo(): from nltk import Nonterminal, parse_cfg nonterminals = 'S VP NP PP P N Name V Det' (S, VP, NP, PP, P, N, Name, V, Det) = [Nonterminal(s) for s in nonterminals.split()] grammar = parse_cfg(""" S -> NP VP PP -> P NP NP -> Det N NP -> NP PP VP -> V NP VP -> VP PP Det -> 'a' Det -> 'the' Det -> 'my' NP -> 'I' N -> 'dog' N -> 'man' N -> 'park' N -> 'statue' V -> 'saw' P -> 'in' P -> 'up' P -> 'over' P -> 'with' """) def cb(grammar): print grammar top = Tk() editor = CFGEditor(top, grammar, cb) Label(top, text='\nTesting CFG Editor\n').pack() Button(top, text='Quit', command=top.destroy).pack() top.mainloop()
def main(): tk = Tk() menuBar = Pmw.MainMenuBar(tk) def command(): print('Pressed') menuBar.addmenu('File', 'File') menuBar.addmenuitem( 'File', 'command', 'Close', command=command, label='Close' ) insertmenuitem( menuBar, 'File', 'command', 'Open', command=command, index=0, label='Open' ) tk.configure(menu=menuBar) tk.mainloop()
def main(posts = Search.FrontPage()): #main window root = Tk() root.geometry("600x300+300+300") app = GUI(root,posts) root.mainloop()
def gain_focus(): t = Tk() t.destroy() find_cmd_str = 'ps -o command | grep "%s"'%__file__ find_results = Popen(find_cmd_str, shell=True, stdout=PIPE).stdout.read() py_path = search('(.*Python\.app)', find_results).groups()[0] Popen(['open',py_path])
def main(): queue = Queue.Queue() parent = Tk() musicplayer1 = musicplayer.MusicPlayer() gui = Example(parent, queue, musicplayer1) #client.endApplication() parent.mainloop()
def __init__(self): #Creating main window. And initializing components Tk.__init__(self) f = Frame(self, width=400, height=200) f.pack(expand=True) #Blank labels are added to make window alignment better Label(f,text="").grid(row=0) #Blank labels are added to make window alignment better Label(f,text=" ").grid(row=1,column=0) #Add label fileName Label(f,text="File Name").grid(row=1,column=1) #Adding text box self.textbox1=Entry(f,width=20) self.textbox1.grid(row=1,column=2) #Adding file Browse button. Set its even handler as openFileBrowser() Button(f,text="Choose File",command=self.openFileBrowser).grid(row=1,column=3) #Blank labels are added to make window alignment better Label(f,text=" ").grid(row=1,column=4) #Blank labels are added to make window alignment better Label(f,text="").grid(row=2) #Adding Summarize button. Set its even handler as summarize() Button(f,text="Summarize",command=self.summarize).grid(row=3,column=2) #Adding frame to window f.pack_propagate(0) #Set window title self.title("Auto Text Summarizer") self.mainloop()
def main(): root=Tk() root.geometry("250x150+300+300") app=GUI(root) app.mainloop() pass
def directions_window(): directions_window = Tk() directions_window.title("How To Operate The Board") label = Label(directions_window, text="Left Click to pick a piece \n Right Click to place the piece", height=20, width=50) label.pack()
def main(): global self, root root = Tk() root.geometry("800x800+0+0") self = at_graph(root) self.pack(fill=BOTH, expand=1)
def test_tabs(): a = Tk() n = Notebook( a, TOP ) # uses the Notebook's frame f1 = Frame( n() ) b1 = Button( f1, text="Ignore me" ) e1 = Entry( f1 ) # pack your widgets before adding the frame # to the Notebook (but not the frame itself)! b1.pack( fill=BOTH, expand=1 ) e1.pack( fill=BOTH, expand=1 ) # keeps the reference to the radiobutton (optional) x1 = n.add_screen( f1, "Tab 1" ) f2 = Frame( n() ) # this button destroys the 1st screen radiobutton b2 = Button( f2, text='Remove Tab 1', command=lambda:x1.destroy() ) b3 = Button( f2, text='Beep...', command=lambda:Tk.bell( a ) ) b2.pack( fill=BOTH, expand=1 ) b3.pack( fill=BOTH, expand=1 ) f3 = Frame( n() ) n.add_screen( f2, "Tab 2" ) n.add_screen( f3, "Minimize" ) a.mainloop()
class ColonistGame(object): def __init__(self): pass def initialize_game(self): #initialize model instances print "initialize game" self.model_instance = GameModel() for colonist in self.model_instance.colonistlist: print colonist.get_name() self.root = Tk() self.app = GameScreen(self.root, game_instance) self.root.mainloop() self.app.update_screen() def next_turn(self): """ Model update """ self.model_instance.resolve_turn_phase() """ Screen update """ self.app.update_screen() print "Next turn"
class DataViewDialog: """Manages the windows and initialization for creating a box to display the entire data set at once.""" ##### Initialization #################################################################### def __init__( self, filename, data ): """Initializes the data view window.""" self.root = Tk() self.root.title(filename) self.root.geometry('1024x768') # Create the scrollbar UI widgets scrollbarY = tk.Scrollbar(self.root) scrollbarY.pack(side=tk.RIGHT, fill=tk.Y) scrollbarX = tk.Scrollbar(self.root, orient=tk.HORIZONTAL) scrollbarX.pack(side=tk.BOTTOM, fill=tk.X) # Adds the text object to the window and makes it un-editable. w = tk.Text(self.root, wrap=tk.NONE, yscrollcommand=scrollbarY.set, xscrollcommand=scrollbarX.set, font='courier 12 bold') w.insert(tk.INSERT, data) w.config( state=tk.DISABLED ) w.pack( expand=1, fill=tk.BOTH) # Activate the scrollbars for their respective views. scrollbarY.config(command=w.yview) scrollbarX.config(command=w.xview)
class TK_Framework(object): def __init__(self): self.root = Tk() # list of open windows self.windows = {'main':self.root} # setup the overall style of the gui self.style = Style() self.style.theme_use('clam') def get_window(self,name): return self.windows[name] def create_window(self, name): self.windows[name] = Toplevel() @staticmethod def open_file(init_dir): filename = askopenfilename(initialdir=init_dir) return filename def hide_root(self): """Hides the root window""" self.root.withdraw() def get_root(self): return self.root
def run(self): """ Runs the music stand. This method will not return until the application exits. """ callbacks = dict(song_loaded=self._start_song, song_stopped=self._abort_song, song_restarted=self._restart_song) self._capturer.start() # also starts the listener self._matcher.start() try: self._running = True root = Tk() self._display = Display(root, callbacks, self._debug) # run the Tkinter event loop root.mainloop() except KeyboardInterrupt: print finally: self._running = False self._matcher.shutdown() self._capturer.stop() # similarly, also stops the listener
class WelcomeDialog: """Manages the window and initialization for creating a the V.I.O.L.A.S. welcome box.""" ##### Initialization #################################################################### def __init__( self ): """Initializes the welcome window.""" self.root = Tk() self.root.title('Welcome') self.root.geometry('515x350') w = tk.Message(self.root, anchor='center', text= " Welcome to V.I.O.L.A.S.!\n\n" + " Visual Information Observation, Logging and Analysis System\n\n" + " Key Features Include:\n\n" + " *Ability to Read in any CSV File\n" + " *Made to Order Graphical Representations\n" + " *Quick and Easy Statistical Computation\n\n" + " How to Use V.I.O.L.A.S:\n\n" + " *Step 1: Under the file menu, use Open to import any csv file. The\n" + " data will be presented in an easy to read format in the\n" + " terminal.\n\n" + " *Step 2: Under the graphs menu, one can create either a histogram, a\n" + " scatterplot (4D,3D,2D), or a box plot. Each type of graphical\n" + " representation takes user input in order to create the graph.\n\n" + " *Step 3: Under the calculations menu, one can calculate the mean,\n" + " median, mode, standard deviation, and the range depending on \n" + " the user's wants. \n\n" + " *Step 4: Have fun and immerse yourself in the wonders of \n" + " graphical analysis that this program has to offer!\n\n", background='blue', foreground='white', border=0, width=550, font='courier 12 bold') w.pack()
def main(): root = Tk() root.geometry("500x350+300+300") app = Example(root) root.mainloop()
def __init__(self, input): Tk.__init__(self) self.input = input if sys.platform == "win32": self.iconbitmap(bitmap=settings.mainicon) else: img = ImageTk.PhotoImage(master=self, file=settings.mainicon) self.tk.call('wm', 'iconphoto', self._w, img) self.resizable(width=FALSE, height=FALSE) self.end = None self.serialized = dict() self.title('Download.am') self.ok_element = None self.cancel_element = None self.bind('<Return>', lambda event: self.unbound_ok()) self.bind('<Escape>', lambda event: self.unbound_cancel()) if input.close_aborts: self.protocol("WM_DELETE_WINDOW", self.unbound_cancel) else: self.protocol("WM_DELETE_WINDOW", self.destroy) ctx = Context(self, self, input.elements) ctx.frame.pack() self.wm_attributes("-topmost", 1) self.focus_force()
def points(): cikis = Tk() cikis.title('Puan durumu') Label(cikis, text=' Puan Durumu ').pack(pady=15) Label(cikis, text='YEŞİL:' + str(greenPoints)).pack(pady=15) Label(cikis, text='YELLOW:' + str(yellowPoints)).pack(pady=15) Button(cikis, text="EXIT", command=cikis.destroy).pack(side=BOTTOM)
class ABC(Frame): def __init__(self,parent=None): Frame.__init__(self,parent) self.parent = parent self.pack() # Pack.config(self) # same as self.pack() ABC.make_widgets(self) Button(self, text='Pop1', command=self.dialog1).pack() enable = {'ID1050': 0, 'ID1106': 0, 'ID1104': 0, 'ID1102': 0} for machine in enable: enable[machine] = Variable() l = Checkbutton(self, text=machine, variable=enable[machine]) l.pack() self.pack() def make_widgets(self): self.root = Tk() self.root.title("Simple Prog") def dialog1(self): ans = Dialog(self, title = 'Title!', text = 'text' 'and text "quotation".', bitmap = 'questhead', default = 0, strings = ('Yes', 'No', 'Cancel'))
def run_pinballview(width, height, configuration): """ Changed from original Pierre-Luc Bacon implementation to reflect the visualization changes in the PinballView Class. """ width, height = float(width), float(height) master = Tk() master.title('RLPY Pinball') screen = Canvas(master, width=500.0, height=500.0) screen.configure(background='LightGray') screen.pack() environment = PinballModel(configuration) environment_view = PinballView(screen, width, height, environment) actions = [ PinballModel.ACC_X, PinballModel.DEC_Y, PinballModel.DEC_X, PinballModel.ACC_Y, PinballModel.ACC_NONE] done = False while not done: user_action = np.random.choice(actions) environment_view.blit() if environment.episode_ended(): done = True if environment.take_action(user_action) == environment.END_EPISODE: done = True environment_view.blit() screen.update()
def interactive_ask_diff(self, code, tmpfn, reffn, testid): from os import environ if 'UNITTEST_INTERACTIVE' not in environ: return False from Tkinter import Tk, Label, LEFT, RIGHT, BOTTOM, Button from PIL import Image, ImageTk self.retval = False root = Tk() def do_close(): root.destroy() def do_yes(): self.retval = True do_close() phototmp = ImageTk.PhotoImage(Image.open(tmpfn)) photoref = ImageTk.PhotoImage(Image.open(reffn)) Label(root, text='The test %s\nhave generated an different' 'image as the reference one..' % testid).pack() Label(root, text='Which one is good ?').pack() Label(root, text=code, justify=LEFT).pack(side=RIGHT) Label(root, image=phototmp).pack(side=RIGHT) Label(root, image=photoref).pack(side=LEFT) Button(root, text='Use the new image -->', command=do_yes).pack(side=BOTTOM) Button(root, text='<-- Use the reference', command=do_close).pack(side=BOTTOM) root.mainloop() return self.retval
class TestBase(unittest.TestCase): def setUp(self): self.root = Tk() def tearDown(self): self.root.destroy()
def main(): app = "netconvert" appOptions = parse_help(app) # appOptions = [] root = Tk() app = Launcher(root, app, appOptions) root.mainloop()
def interactive_ask_ref(self, code, imagefn, testid): from os import environ if 'UNITTEST_INTERACTIVE' not in environ: return True from Tkinter import Tk, Label, LEFT, RIGHT, BOTTOM, Button from PIL import Image, ImageTk self.retval = False root = Tk() def do_close(): root.destroy() def do_yes(): self.retval = True do_close() image = Image.open(imagefn) photo = ImageTk.PhotoImage(image) Label(root, text='The test %s\nhave no reference.' % testid).pack() Label(root, text='Use this image as a reference ?').pack() Label(root, text=code, justify=LEFT).pack(side=RIGHT) Label(root, image=photo).pack(side=LEFT) Button(root, text='Use as reference', command=do_yes).pack(side=BOTTOM) Button(root, text='Discard', command=do_close).pack(side=BOTTOM) root.mainloop() return self.retval
def checkExit(): root = Tk() root.geometry("200x90+300+300") app = Escape(root) root.mainloop() result = app.getStatus() return result
def __init__(self, drs, size_canvas=True, canvas=None): """ :param drs: C{AbstractDrs}, The DRS to be drawn :param size_canvas: bool, True if the canvas size should be the exact size of the DRS :param canvas: C{Canvas} The canvas on which to draw the DRS. If none is given, create a new canvas. """ master = None if not canvas: master = Tk() master.title("DRT") font = Font(family='helvetica', size=12) if size_canvas: canvas = Canvas(master, width=0, height=0) canvas.font = font self.canvas = canvas (right, bottom) = self._visit(drs, self.OUTERSPACE, self.TOPSPACE) width = max(right+self.OUTERSPACE, 100) height = bottom+self.OUTERSPACE canvas = Canvas(master, width=width, height=height)#, bg='white') else: canvas = Canvas(master, width=300, height=300) canvas.pack() canvas.font = font self.canvas = canvas self.drs = drs self.master = master
def __init__(self): Tk.__init__(self) self.geometry('%dx%d+500+500' % (WIDTH,HEIGHT)) self.title('GooMPy') self.canvas = Canvas(self, width=WIDTH, height=HEIGHT) self.canvas.pack() self.bind("<Key>", self.check_quit) self.bind('<B1-Motion>', self.drag) self.bind('<Button-1>', self.click) self.label = Label(self.canvas) self.radiogroup = Frame(self.canvas) self.radiovar = IntVar() self.maptypes = ['OSM', 'GoogleSatellite', 'Satellite'] self.add_radio_button('OSM', 0) self.add_radio_button('GoogleSatellite', 1) self.add_radio_button('Satellite', 2) self.zoom_in_button = self.add_zoom_button('+', +1) self.zoom_out_button = self.add_zoom_button('-', -1) self.zoomlevel = ZOOM maptype_index = 0 self.radiovar.set(maptype_index) self.goompy = GooMPy(WIDTH, HEIGHT, LATITUDE, LONGITUDE, ZOOM, MAPTYPE) self.restart()
def __init__(self): Tk.__init__(self)
class WSGui(threading.Thread): #Word Suggester GUI ''' Creates the GUI when initialized, and allows the word displayed in the box to update. The GUI will always be "in-front" of other application windows, so that it will always be visible. ''' def __init__(self, bg, corner, dcm, fontsize, txtcolor, Q, height=2, width=40): threading.Thread.__init__(self) self.root = Tk() self.dcm = dcm self.q = Q self.fg = txtcolor # Convert corner string into appropriate newGeometry value for # root.geometry(). This functionality is Windows OS specific. if corner == "topright": newGeometry = "-1+1" elif corner == "topleft": newGeometry = "+1+1" elif corner == "bottomright": newGeometry = "-1-1" elif corner == "bottomleft": newGeometry = "+1-1" else: raise ValueError("GUI corner string has unrecognized value.") # Set the window to always be visible, but be non-interactable self.root.wm_attributes("-topmost", 1) self.root.overrideredirect(1) # Create the variable to store the text to display self.textvar = StringVar() # Create the label widget to pack into the root window self.label = Label(self.root, anchor=CENTER, background=bg, fg=self.fg, font=('', fontsize), textvariable=self.textvar, height=height, width=width) self.label.pack(expand=0, fill=None) # Place the window where specified by the corner parameter self.root.geometry(newGeometry) if self.dcm == True: self.root.withdraw() def run(self): self.root.after(1000, self.poll) self.root.mainloop() def poll(self): try: word = self.q.get(block=True) except Queue.Empty: print "THIS SHOULDN'T HAPPEN. CRY DEEPLY THAT I CODED NO REAL \ EXCEPTION HANDLING." while not self.q.empty(): word = self.q.get() if type(word) is str: if self.dcm == False: self.update_word(word) elif type(word) is list: options_list = word self.update_config(options_list) elif word == 1: self.flash_color() elif word == 0: self.end() return if self.dcm != True: self.root.after(100, self.poll) else: self.root.after(2000, self.poll) def update_word(self, word): #updates the text displayed, changing it to the word string passed in self.textvar.set(word) self._update_idle() def update_config(self, options_l): GUI_size, GUI_corner, GUI_bg, GUI_txtcolor, GUI_fontsize, DCM, p_s, spc, p_n = options_l if GUI_size == "small": GUI_height = 1 GUI_width = 20 elif GUI_size == "normal": GUI_height = 2 GUI_width = 40 elif GUI_size == "large": GUI_height = 3 GUI_width = 60 if GUI_corner == "topright": newGeometry = "-1+1" elif GUI_corner == "topleft": newGeometry = "+1+1" elif GUI_corner == "bottomright": newGeometry = "-1-1" elif GUI_corner == "bottomleft": newGeometry = "+1-1" if GUI_fontsize == "small": fontsize = 15 elif GUI_fontsize == "normal": fontsize = 25 elif GUI_fontsize == "large": fontsize = 35 if DCM == True: if self.dcm != DCM: self.root.withdraw() elif DCM == False: if self.dcm != DCM: self.root.deiconify() self.dcm = DCM self.fg = GUI_txtcolor self.label.config(bg=GUI_bg, fg=self.fg, font=('', fontsize), height=GUI_height, width=GUI_width) self.root.geometry(newGeometry) def flash_color(self, color="blue", color_opt="black"): ''' Sets the text to the color, passed in as a string. ''' if self.fg != color: self.label.config(fg=color) else: self.label.config(fg=color_opt) self._update_idle() self.root.after(100, self._reset_color) def end(self): try: self.root.destroy() except Exception as e: print(e) print "ROOT DID NOT DESTROY" def _update_idle(self): self.root.update_idletasks() def _reset_color(self): self.label.config(fg=self.fg)
yellow = "blue" red = "cyan" white = "black" black = "white" else: grey = "light slate grey" green = "green" yellow = "yellow" red = "red" white = "white" black = "black" c_height = 476 #the border lines are approx 2px c_width = 316 #316 root = Tk() root.config(width=(c_width - 45), height=c_height, bg=black) if not testMode: root.config(cursor="none") root.attributes("-fullscreen", True) #if not in test mode switch to fullscreen textFont = tkFont.Font(family="Helvetica", size=36, weight="bold") # Declare Variables measuredItems = [ "RPM", "Water TMP", "Oil Temp", "Oil Press", "EGT", "Fuel Flow", "Fuel(left)", "Voltage" ] errorBoxItems = ["TEMP", "PRESS", "FUEL", "POWER", "ERROR"] errorBoxItemsColor = ["red", "green", "green", "yellow", "green"]
def copia_entrambe(self): """ Copy descr. and query sql into clipboard """ the_tk = Tk() the_tk.withdraw() the_tk.clipboard_clear() the_tk.clipboard_append(self.testo_descriz) the_tk.clipboard_append('\n\n-----\n\n') the_tk.clipboard_append(self.testo_query) the_tk.update() the_tk.destroy() self.tedDescriz.selectAll() self.tedQuerySql.selectAll() self.labInfoDone.setText('Copiate descriz. e query negli appunti')
def copia_query(self): """ Copy query sql into clipboard """ the_tk = Tk() the_tk.withdraw() the_tk.clipboard_clear() the_tk.clipboard_append(self.testo_query) the_tk.update() the_tk.destroy() self.tedQuerySql.selectAll() self.labInfoDone.setText('Copiata query sql negli appunti')
def copia_descriz(self): """ Copy descr. into clipboard """ the_tk = Tk() the_tk.withdraw() the_tk.clipboard_clear() the_tk.clipboard_append(self.testo_descriz) the_tk.update() the_tk.destroy() self.tedDescriz.selectAll() self.labInfoDone.setText('Copiata descriz. negli appunti')
class fenetre_mac: def __init__(self, resu1, resu2, mac): from Calc_essai.outils_ihm import MacWindowFrame from Tkinter import Tk, Frame, StringVar, Entry, Label, Button self.resu1 = resu1 self.resu2 = resu2 self.mac = mac self.root = Tk() nom1 = resu1.nom nom2 = resu2.nom titre = "MAC pour la base " + nom1 + " et " + nom2 size = (20, 300) # la fenetre de MAC mac_win = MacWindowFrame(self.root, titre, nom1, nom2, size) mac_win.grid(row=0, column=0) self.freq1 = get_modes(resu1) self.freq2 = get_modes(resu2) # la variable NUMERIQUE qui contient ces memes listes. On remplit # ces valeurs quand on ferme la fenetre self.l1 = None self.l2 = None # la variable GRAPHIQUE qui donne le contenu des listes self.var_l1 = StringVar() self.var_l2 = StringVar() mac_win.set_modes(self.freq1, self.freq2, self.mac) # Une deuxieme fentre, dans laquelle on peut modifier l'appariement des # modes f = Frame(self.root) f.grid(row=1, column=0, sticky='news') f.columnconfigure(0, weight=1) f.columnconfigure(1, weight=4) Label(f, text="Liste de mode 1").grid(row=0, column=0, sticky='e') # l1 = Entry(f, textvariable=self.var_l1 ) Label(f, textvariable=self.var_l1).grid(row=0, column=1, sticky='w') # l1.grid(row=0,column=1,sticky='ew')#,columnspan=3) Label(f, text="Liste de mode 2").grid(row=1, column=0, sticky='e') l2 = Entry(f, textvariable=self.var_l2) l2.grid(row=1, column=1, sticky='ew') # ,columnspan=3) close = Button(f, text='Fermer', command=self.close_win) close.grid(row=2, column=1, sticky='e') self.set_default_pair() self.root.mainloop() def get_pair(self): """rend une double liste donnant les appariements de modes""" return [self.var_l1.get(), self.var_l2.get()] def set_pair(self, liste): """affiche une liste d'appariement donnee""" self.var_l1.set(liste[0]) self.var_l2.set(liste[1]) def set_default_pair(self): """ affiche la liste d'appariement par defaut. Le nombre de modes correspond au plus petit nombre de modes entre resu1 et resu2""" nb_mod = min(len(self.freq1), len(self.freq2)) self.var_l1.set(range(1, nb_mod + 1)) self.var_l2.set(range(1, nb_mod + 1)) def close_win(self): self.l1 = self.var_l1.get() self.l2 = self.var_l2.get() self.root.quit() def get_list(self): exec('l1=' + self.l1) exec('l2=' + self.l2) return l1, l2
self.msg.set('该URL 不存在 JSONP劫持 漏洞。') except : self.result.config(fg='red') self.msg.set('网络资源请求失败,请确保已经接入互联网和网址的有效性!') root=Tk() root.title('JSONP漏洞检测工具 by WD(WX:13503941314) Topsec V2 ') root.geometry('700x500+100+100') app=App(root) root.mainloop() if __name__ == '__main__': pass
text='Battery level:\n{} %'.format(data.percentage)) def publish_pos(self): #publishing the position of the target position in pixels if not rospy.is_shutdown(): p = Point() p.x = pos_x p.y = pos_y p.z = 0 self.gui_target_pub.publish(p) self.rate.sleep() rospy.loginfo("New Gui target published (%d, %d)", pos_x, pos_y) ## sizing the gui window and initialising ImageFile.LOAD_TRUNCATED_IMAGES = True root = Tk() root.geometry('1700x850') gui = DroneGUI(root) gui.update_image() col_count, row_count = root.grid_size() for col in xrange(col_count): root.grid_columnconfigure(col, minsize=40) for row in xrange(row_count): root.grid_rowconfigure(row, minsize=20) root.mainloop()
def clip(self): locale.setlocale(locale.LC_ALL, '') r = Tk() r.withdraw() r.clipboard_clear() r.clipboard_append(locale.format("%.1f", distance / mpc2kpc, grouping=False) + '\t' + locale.format("%.0f", vinf, grouping=False) + '\t' + locale.format("%.2f", rc, grouping=False) + '\t' + locale.format("%.2f", p0, grouping=False) + '\t' + locale.format("%.2E", M, grouping=False)) r.update() # now it stays on the clipboard after the window is closed r.destroy()
def destroy(self): self.interior.destroy() def item_ID(self, index): return self.interior.get_children()[index] if __name__ == '__main__': try: from Tkinter import Tk import tkMessageBox as messagebox except ImportError: from tkinter import Tk from tkinter import messagebox root = Tk() def on_select(data): print("called command when row is selected") print(data) print("\n") def show_info(msg): messagebox.showinfo("Table Data", msg) mc = Multicolumn_Listbox(root, ["column one","column two", "column three"], stripped_rows = ("white","#f2f2f2"), command=on_select, cell_anchor="center") mc.interior.pack() mc.insert_row([1,2,3]) show_info("mc.insert_row([1,2,3])")
class zfitwin(tkinter.Tk): """ The basic class of the widget """ def __init__(self,parent, startfile=None, z_start=0.0): """ My constructor """ self.tk = Tk() #set min and preferred size of main gui self.minwinwidth=300 self.minwinheight=300 screen_width = self.winfo_screenwidth() screen_height = self.winfo_screenheight() self.preferwinwidth=int(screen_width*0.8) self.preferwinheight=int(screen_height*0.8) self.minsize(width=self.minwinwidth, height=self.minwinheight) self.geometry("{}x{}".format(self.preferwinwidth,self.preferwinheight)) #tweak the aspect ratio of the menu and data gui self.menuaspect=[1,0.24] #Ruari 24/05 fixes bug where different resolutions cause the menu to be cut off self.dataaspect=[1,1-0.24] #Ruari 24/05 fixes bug where different resolutions cause the menu to be cut off self.dpi=80 #find exect dir self.execdir=__file__.split('zfit.py')[0] if(len(self.execdir)==0): self.execdir='./' #Fiddle with font default_font = tkfont.nametofont("TkDefaultFont") scalefont = int(screen_height/1080.0*14) default_font.configure(size=scalefont) #init gui frame self.initialize(startfile, z_start) def initialize(self, startfile, z_start): """ This init the basic gui """ #create a menu frame self.menuframe=tkinter.Frame(self,width=int(self.preferwinwidth*self.menuaspect[0]), height=int(self.preferwinheight*self.menuaspect[1])) self.menuframe.grid_propagate(0) self.menuframe.grid() #create a data frame self.dataframe=tkinter.Frame(self,width=int(self.preferwinwidth*self.dataaspect[0]), height=int(self.preferwinheight*self.dataaspect[1])) self.dataframe.grid_propagate(0) self.dataframe.grid() #stick the 2D image in a separate window self.imgframe=tkinter.Toplevel(width=600,height=600) #update for later use of units self.update() #now initialise the menu frame self.init_menuframe() #now initialise the data frame self.init_dataframe(startfile) #If zstart exists show the lines automatically if z_start != 0.0: self.displaylines() self.shwlinstate.set(1) self.redshiftline.set("{}".format(z_start)) def init_menuframe(self): """ This init the menu specific part """ #exit button self.menu_exit = tkinter.Button(self.menuframe,text=u"EXIT",command=self.OnExit) self.menu_exit.grid(column=0,row=0) #save button self.menu_save = tkinter.Button(self.menuframe,text=u"Save",command=self.OnSave) self.menu_save.grid(column=0,row=1) #choice of spectra self.menu_select = tkinter.Button(self.menuframe,text=u"Open Spectrum", command=self.SelectFile) self.menu_select.grid(column=0,row=2) #current spectrum self.currspec=tkinter.StringVar() self.currspec.set('Spect: Demo') self.current=tkinter.Label(self.menuframe,textvariable = self.currspec) self.current.grid(column=0,row=3) self.mouse_position=tkinter.StringVar() self.mouse_position.set('Mouse:(None,None)') self.mouse_position_w=tkinter.Label(self.menuframe,textvariable = self.mouse_position) self.mouse_position_w.grid(column=0,row=4,columnspan=3) #Message window self.generic_message=tkinter.StringVar() self.generic_message.set('zfit-> Ready to go!') self.generic_message_w=tkinter.Label(self.menuframe,textvariable = self.generic_message) self.generic_message_w.grid(column=5,row=3,columnspan=3) #line control stuff self.init_linecontrol() #templates control stuff self.init_templcontrol() def init_dataframe(self, startfile): """ This init the data specific part """ #Work out the geometry of the different data parts #canvas for spectrum ... self.pltspec_width=self.dataframe.winfo_width() self.pltspec_height=int(self.dataframe.winfo_height()*0.6) #canvas for twod spec self.twodspc_width=self.dataframe.winfo_width() self.twodspc_height=int((self.dataframe.winfo_height()-self.pltspec_height)*0.6) #canvas for twod err self.twoderr_width=self.dataframe.winfo_width() self.twoderr_height=int((self.dataframe.winfo_height()-self.pltspec_height)*0.5) #work out dimensions for twod image self.twodimg_width=self.imgframe.winfo_width() self.twodimg_height=self.imgframe.winfo_height() #now open with default spectrum and plot #self.filename=os.path.abspath(self.execdir)+"/test_spectrum.fits" RUari Jul 17 17 if startfile==None: self.filename=os.path.abspath(self.execdir)+"/test_spectrum.fits" else: self.filename=startfile self.currspec.set('Spect: '+startfile) self.fits=fits.open(self.filename) #unpack self.fitwav1d=self.fits[2].data self.fitspe1d=self.fits[0].data self.fitspe1d_original=np.copy(self.fitspe1d) self.fiterr1d=self.fits[1].data self.fitspe2d=self.fits[4].data self.fiterr2d=self.fits[5].data self.fitimg=self.fits[6].data #load sky model and normalise to source flux skyspe=fits.open('{}/templates/sky/SKY_SPECTRUM_0001.fits'.format(self.execdir)) skycnt=fits.open('{}/templates/sky/SKY_CONTINUUM_0001.fits'.format(self.execdir)) #compute continuum subtracted sky model self.wavesky=np.array(skyspe[1].data['LAMBDA']) cont_resampled=interp1d(skycnt[1].data['LAMBDA'],skycnt[1].data['FLUX'],bounds_error=False,fill_value=0)(skyspe[1].data['LAMBDA']) self.fluxsky=np.array(skyspe[1].data['DATA'])-cont_resampled self.fluxsky=self.fluxsky/np.max(self.fluxsky)*0.5*np.max(self.fitspe1d) self.drawdata() #set tmpfitxcorr to None to avoid error or later init self.tmpfitxcorr=None #set smoothwindow self.smooth=3 def init_linecontrol(self): """ This controls operation with emission lines """ #just say what it is linelabel=tkinter.Label(self.menuframe,text = "Emission lines") linelabel.grid(column=1,row=0,columnspan=2) #drop down menu to select emission lines llab = tkinter.Label(self.menuframe, text="Select Lines: ") llab.grid(column=1,row=1) self.linelist = tkinter.StringVar(self.menuframe) self.linelist.set("gal_vac") # default value self.lineselect = tkinter.OptionMenu(self.menuframe, self.linelist,"gal_vac","gal_air","lbg","lls","tell") self.lineselect.grid(column=2,row=1) #set the linelist in trace state self.linelist.trace("w",self.displaylines) #line redshift window zlab = tkinter.Label(self.menuframe, text="z = ") zlab.grid(column=1,row=2) self.redshiftline = tkinter.StringVar() self.redlinecntr = tkinter.Entry(self.menuframe,textvariable=self.redshiftline) self.redlinecntr.grid(column=2,row=2) self.redshiftline.set("0.0000") #set the redshift in a trace state self.redshiftline.trace("w",self.displaylines) #display lines self.shwlinstate=tkinter.IntVar() self.lineshow = tkinter.Checkbutton(self.menuframe, text="Show Lines", variable=self.shwlinstate,command=self.displaylines) self.lineshow.grid(column=1,row=3) #fit lines self.line_fit = tkinter.Button(self.menuframe,text=u"FitLines",command=self.fitlines) self.line_fit.grid(column=2,row=3) def init_templcontrol(self): """ Control the options for template fitting """ #just say what it is templabel=tkinter.Label(self.menuframe,text = "Templates") templabel.grid(column=3,row=0,columnspan=4) #drop down menu to select template family llab = tkinter.Label(self.menuframe, text="Pick template: ") llab.grid(column=3,row=1) self.tempgroup= tkinter.StringVar(self.menuframe) self.tempgroup.set("Select") self.tempselect = tkinter.OptionMenu(self.menuframe,self.tempgroup,"kinney","lbgs","sdss") self.tempselect.grid(column=4,row=1) self.tempgroup.trace("w",self.loadtemplate) #just say what it is self.currenttemplate=tkinter.StringVar(self.menuframe) self.currenttemplate.set("Current: None") self.tempchoice=tkinter.Label(self.menuframe,textvariable = self.currenttemplate) self.tempchoice.grid(column=5,row=1,columnspan=2) #D not use trace for template, as these are expensive to compute #template redshift window zlab = tkinter.Label(self.menuframe, text="z = ") zlab.grid(column=3,row=2) self.redshifttemp = tkinter.StringVar() self.redtempcntr = tkinter.Entry(self.menuframe,textvariable=self.redshifttemp) self.redtempcntr.grid(column=4,row=2) self.redshifttemp.set("0.0000") #rmag window rmg = tkinter.Label(self.menuframe, text="flux = ") rmg.grid(column=3,row=3) self.magtemp = tkinter.StringVar() self.magtemcntr = tkinter.Entry(self.menuframe,textvariable=self.magtemp) self.magtemcntr.grid(column=4,row=3) self.magtemp.set("1.00") #display template self.shwtempstate=tkinter.IntVar() self.tempshow = tkinter.Button(self.menuframe,text="Show Template",command=self.displaytemplate) self.tempshow.grid(column=3,row=4) self.temphide = tkinter.Button(self.menuframe,text="Hide Template",command=self.hidetemplate) self.temphide.grid(column=4,row=4) #fit template self.template_fit = tkinter.Button(self.menuframe,text=u"FitTemplate",command=self.fittemplate) self.template_fit.grid(column=5,row=2) #toggle sky self.shwskystate=tkinter.IntVar() self.template_sky=tkinter.Button(self.menuframe,text=u"Sky On/Off",command=self.togglesky) self.template_sky.grid(column=5,row=4) def OnExit(self): """ Quit all on exit """ self.fits.close() self.quit() self.destroy() def OnSave(self): """ Save screen """ print('Placeholder') def SelectFile(self): """ Select and open file as one wishes """ #select file self.filename=filedialog.askopenfilename(initialdir='./') #update name self.currspec.set("Spec: "+self.filename.split("/")[-1]) #close old and reopen self.fits.close() self.fits=fits.open(self.filename) #unpack self.fitwav1d=self.fits[2].data self.fitspe1d=self.fits[0].data self.fitspe1d_original=np.copy(self.fits[0].data) self.fiterr1d=self.fits[1].data self.fitspe2d=self.fits[4].data self.fiterr2d=self.fits[5].data self.fitimg=self.fits[6].data #redraw self.drawdata(refresh=True) def drawdata(self,refresh=False): """ Once the spectrum is set, populate the data part of the gui refresh -> True, wipe all canvas before redrawing """ if(refresh): #now destroy all data canvas self.twodimagePlot.get_tk_widget().destroy() self.spectrumPlot.get_tk_widget().destroy() self.twodspcPlot.get_tk_widget().destroy() self.twoderrPlot.get_tk_widget().destroy() #refresh 2D image self.init_twodimage() #refresh the spectrum self.init_spectrum() #refresh 2D spec self.init_twodspec() #refresh 2D err self.init_twoderr() def init_twodimage(self): """ Draw the 2D image """ #create properties for this plot self.twodimagePlot_prop={} #figure staff self.twodimagePlot_prop["figure"] = Figure(figsize=(self.twodimg_width/self.dpi,self.twodimg_height/self.dpi), dpi=self.dpi) self.twodimagePlot_prop["axis"] = self.twodimagePlot_prop["figure"].add_subplot(111) #call plotting routine self.update_twodimage() #send it to canvas - connect event self.twodimagePlot = FigureCanvasTkAgg(self.twodimagePlot_prop["figure"],master=self.imgframe) #Draw is required in matplotlib > 2.2, show is kept for legacy only try: self.twodimagePlot.draw() except: self.twodimagePlot.show() #need to set tight layout after showing self.twodimagePlot_prop["figure"].tight_layout() #enable event on click self.twodimagePlot.mpl_connect("button_press_event", self.pressbutton) self.twodimagePlot.mpl_connect("key_press_event", self.presskey) self.twodimagePlot.get_tk_widget().grid() def update_twodimage(self,update=False): """ Code that updates the 2D image Update = True, redraw """ self.twodimagePlot_prop["image"] =self.twodimagePlot_prop["axis"].imshow(self.fitimg,origin='lower',aspect='auto') self.twodimagePlot_prop["image"].set_cmap('hot') #self.twodimagePlot_prop["axis"].set_xlabel('Pix') #self.twodimagePlot_prop["axis"].set_ylabel('Pix') def init_spectrum(self): """ Draw the spectrum """ #create properties for this plot self.spectrumPlot_prop={} self.spectrumPlot_prop["xmin"]=np.min(np.nan_to_num(self.fitwav1d)) self.spectrumPlot_prop["xmax"]=np.max(np.nan_to_num(self.fitwav1d)) self.spectrumPlot_prop["ymin"]=np.min(np.nan_to_num(self.fitspe1d)) self.spectrumPlot_prop["ymax"]=np.max(np.nan_to_num(self.fitspe1d)) #figure stuff self.spectrumPlot_prop["figure"]= Figure(figsize=(0.99*self.pltspec_width/self.dpi,0.96*self.pltspec_height/self.dpi), dpi=self.dpi) self.spectrumPlot_prop["axis"]= self.spectrumPlot_prop["figure"].add_subplot(111) #call plotting routine self.update_spectrum() #send it to canvas self.spectrumPlot = FigureCanvasTkAgg(self.spectrumPlot_prop["figure"],master=self.dataframe) try: self.spectrumPlot.draw() except: self.spectrumPlot.show() #enable event on click self.spectrumPlot_prop["figure"].tight_layout() self.spectrumPlot.mpl_connect("button_press_event", self.pressbutton) self.spectrumPlot.mpl_connect("motion_notify_event", self.movemouse) self.spectrumPlot.mpl_connect("key_press_event", self.presskey) self.spectrumPlot.get_tk_widget().grid(column=0,row=0) def update_spectrum(self,update=False): """ Code that updates the spectrum Update = True, redraw """ if(update): self.spectrumPlot_prop["axis"].cla() #plot main data self.spectrumPlot_prop["axis"].step(self.fitwav1d,self.fitspe1d,where='mid') self.spectrumPlot_prop["axis"].step(self.fitwav1d,self.fiterr1d,color='red',\ linestyle='--',zorder=1,where='mid') self.spectrumPlot_prop["axis"].set_xlim(self.spectrumPlot_prop["xmin"],self.spectrumPlot_prop["xmax"]) self.spectrumPlot_prop["axis"].set_ylim(self.spectrumPlot_prop["ymin"],self.spectrumPlot_prop["ymax"]) self.spectrumPlot_prop["axis"].set_xlabel('Wavelength') #self.spectrumPlot_prop["axis"].set_ylabel('Flux') #if needed plot sky if(self.shwskystate.get()): self.spectrumPlot_prop["axis"].step(self.wavesky,self.fluxsky,where='mid',color='black') #if needed, plot lines if(self.shwlinstate.get()): #set redshift try: redsh=float(self.redshiftline.get()) except: redsh=0.0 #loop over lines and draw for lw,lnam in self.infoline: #find the obs wave lwplot=lw*(1+redsh) if((lwplot > self.spectrumPlot_prop["xmin"]) & (lwplot < self.spectrumPlot_prop["xmax"])): self.spectrumPlot_prop["axis"].axvline(lwplot, color='grey', linestyle='--') self.spectrumPlot_prop["axis"].text(lwplot,self.spectrumPlot_prop["ymax"],lnam, verticalalignment='top',rotation=90,fontsize=12) #if needed, plot template if(self.shwtempstate.get()): self.spectrumPlot_prop["axis"].plot(self.fitwav1d,self.templatedata_current,color='black',zorder=3) #plot zero line self.spectrumPlot_prop["axis"].plot([self.spectrumPlot_prop["xmin"],self.spectrumPlot_prop["xmax"]], [0,0],color='green',zorder=2,linestyle=':') #finally draw if(update): self.spectrumPlot.draw() def init_twodspec(self): """ Draw the 2D spectrum """ #create properties for this plot self.twodspcPlot_prop={} #figure staff self.twodspcPlot_prop["figure"]= Figure(figsize=(0.99*self.twodspc_width/self.dpi,0.96*self.twodspc_height/self.dpi), dpi=self.dpi) self.twodspcPlot_prop["axis"] = self.twodspcPlot_prop["figure"].add_subplot(111) #call plotting routine self.update_twodspec() #send it to canvas self.twodspcPlot = FigureCanvasTkAgg(self.twodspcPlot_prop["figure"],master=self.dataframe) try: self.twodspcPlot.draw() except: self.twodspcPlot.show() #enable event on click self.twodspcPlot_prop["figure"].tight_layout() self.twodspcPlot.mpl_connect("button_press_event", self.pressbutton) self.twodspcPlot.mpl_connect("key_press_event", self.presskey) self.twodspcPlot.mpl_connect("motion_notify_event", self.movemouse) self.twodspcPlot.get_tk_widget().grid(column=0,row=1,sticky='NW') def wavemap(self,x,pos): """ Utility to map the pixel in 2D image to wavelegth """ #wavelength mapper index=np.arange(0,len(self.fitwav1d)) wave=np.interp(x,index,self.fitwav1d) 'The two args are the value and tick position' return "%.1f" % wave def inv_wavemap(self,x): """ Utility to map wavelegth to pixel in 2D mage """ #wavelength mapper index=np.arange(0,len(self.fitwav1d)) pix=np.interp(x,self.fitwav1d,index,left=0,right=len(self.fitwav1d)) return pix def update_twodspec(self,update=False): """ Code that updates the 2D spectrum Update = True, redraw """ if(update): self.twodspcPlot_prop["axis"].cla() self.twodspcPlot_prop["image"]=self.twodspcPlot_prop["axis"].imshow(np.rot90(self.fitspe2d),origin='lower',aspect='auto') self.twodspcPlot_prop["image"].set_cmap('hot') #control level medianlevel=np.median(np.nan_to_num(self.fitspe2d)) stdlevel=np.std(np.nan_to_num(self.fitspe2d)) self.twodspcPlot_prop["image"].set_clim(medianlevel-3.*stdlevel,medianlevel+3*stdlevel) #wave mapper self.twodspcPlot_prop["axis"].xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(self.wavemap)) #now set X axis as in 1d spectrum xpixmin=self.inv_wavemap(self.spectrumPlot_prop["xmin"]) xpixmax=self.inv_wavemap(self.spectrumPlot_prop["xmax"]) #force minimum maximum if(xpixmin == xpixmax): xpixmin = xpixmax-1 if(xpixmax == 0): xpixmax = 1 self.twodspcPlot_prop["axis"].set_xlim(xpixmin,xpixmax) self.twodspcPlot_prop["axis"].set_xlabel('Wavelength') if(update): self.twodspcPlot.draw() def init_twoderr(self): """ Draw the 2D error """ #create properties for this plot self.twoderrPlot_prop={} #figure staff #self.twoderr.grid(column=1,row=2,sticky='NW') self.twoderrPlot_prop['figure'] = Figure(figsize=(0.99*self.twoderr_width/self.dpi,0.96*self.twoderr_height/self.dpi), dpi=self.dpi) self.twoderrPlot_prop['axis'] = self.twoderrPlot_prop['figure'].add_subplot(111) #call plotting routine self.update_twoderr() #send it to canvas self.twoderrPlot = FigureCanvasTkAgg(self.twoderrPlot_prop['figure'],master=self.dataframe) try: self.twoderrPlot.draw() except: self.twoderrPlot.show() #enable event on click self.twoderrPlot_prop['figure'].tight_layout() self.twoderrPlot.mpl_connect("button_press_event", self.pressbutton) self.twoderrPlot.mpl_connect("key_press_event", self.presskey) self.twoderrPlot.mpl_connect("motion_notify_event", self.movemouse) self.twoderrPlot.get_tk_widget().grid(column=0,row=2,sticky='NW') def update_twoderr(self,update=False): """ Code that updates the 2D error Update = True, redraw """ if(update): self.twoderrPlot_prop["axis"].cla() self.twoderrPlot_prop['image'] =self.twoderrPlot_prop['axis'].imshow(np.rot90(self.fiterr2d),origin='lower',aspect='auto') self.twoderrPlot_prop['image'].set_cmap('hot') #control level medianlevel=np.median(np.nan_to_num(self.fiterr2d)) stdlevel=np.std(np.nan_to_num(self.fiterr2d)) self.twoderrPlot_prop["image"].set_clim(medianlevel-3.*stdlevel,medianlevel+3*stdlevel) #wave mapper self.twoderrPlot_prop["axis"].xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(self.wavemap)) #now set X axis as in 1d spectrum xpixmin=self.inv_wavemap(self.spectrumPlot_prop["xmin"]) xpixmax=self.inv_wavemap(self.spectrumPlot_prop["xmax"]) #force minimum maximum if(xpixmin == xpixmax): xpixmin = xpixmax-1 if(xpixmax == 0): xpixmax = 1 self.twoderrPlot_prop["axis"].set_xlim(xpixmin,xpixmax) self.twoderrPlot_prop["axis"].set_xlabel('Wavelength') if(update): self.twoderrPlot.draw() def displaylines(self,*args): """ Display the line list by refreshing plot in update state """ #first parse the line lists linefile=self.execdir+"/lines/"+self.linelist.get()+".lst" self.infoline = Table.read(linefile, format='ascii.basic') #self.infoline=np.loadtxt(linefile, dtype={'names': ('wave', 'tag'), # 'formats': ('f4', 'S4')}) #refresh plot self.update_spectrum(update=True) def loadtemplate(self,*args): """ Load template from disk and preselect some useful default """ #if so, start dialogue to pick the desired template self.picktemplate=filedialog.askopenfilename(initialdir='{}/templates/{}'.format(self.execdir,self.tempgroup.get())) #set current template self.currenttemplate.set("Current: "+self.picktemplate.split("/")[-1]) #load current template if('sdss' in self.tempgroup.get()): #load fits fitstemp=fits.open(self.picktemplate) #grab flux self.templatedata={'flux':fitstemp[0].data[0,:]} #cosntruct wave waveinx=np.arange(0,len(self.templatedata['flux']),1) wavevac=10**(waveinx*1.*fitstemp[0].header['COEFF1']+1.*fitstemp[0].header['COEFF0']) ##go to air #self.templatedata['wave']= wavevac/(1.0+2.735182e-4+131.4182/wavevac**2+2.76249e8/wavevac**4) #remain in vac self.templatedata['wave']= wavevac else: #load text #self.templatedata=np.loadtxt(self.picktemplate, dtype={'names': ('wave', 'flux'), # 'formats': ('f10', 'f10')},usecols=(0,1)) self.templatedata = Table.read(self.picktemplate, format='ascii.basic') #set sensible pick in redshift and adjust data as needed if('lbg' in self.tempgroup.get()): self.redshifttemp.set("3.000") elif('kinney' in self.tempgroup.get()): self.templatedata['flux']=self.templatedata['flux']/1e-14 elif('sdss' in self.tempgroup.get()): self.templatedata['flux']=self.templatedata['flux']*100. else: self.redshifttemp.set("0.000") def displaytemplate(self,*args): """ Compute and display template """ self.shwtempstate.set(1) #compute template given current values self.adapttemplate() #refresh plot self.update_spectrum(update=True) def hidetemplate(self,*args): """ Hide template """ self.shwtempstate.set(0) #refresh plot self.update_spectrum(update=True) def adapttemplate(self): """ Interpolate a template over the data """ #redshift factor redhfactor=(1+float(self.redshifttemp.get())) #now construct interpolation thisw=self.templatedata['wave']*redhfactor thisf=self.templatedata['flux'] intflx = interp1d(thisw,thisf,kind='linear',bounds_error=False,fill_value=0.0) #apply normalisation self.templatedata_current=intflx(self.fitwav1d)*float(self.magtemp.get()) def togglesky(self,*args): """ Switch on/off sky """ if(self.shwskystate.get()): self.shwskystate.set(0) else: self.shwskystate.set(1) #refresh plot self.update_spectrum(update=True) def fitlines(self): """ Fit the line list """ #loop over lines inside spectrum #lounch a new window self.lnfit=tkinter.Toplevel(self.tk) #add a display fig=Figure(figsize=(self.preferwinwidth/self.dpi,self.preferwinheight/self.dpi),dpi=self.dpi) #pick z try: redsh=float(self.redshiftline.get()) except: redsh=0.0 lines_good_wave_rest=[] lines_good_wave_obs=[] lines_good_name=[] for lw,lnam in self.infoline: lwplot=lw*(1+redsh) if((lwplot > min(self.fitwav1d)+8) & (lwplot < max(self.fitwav1d)-8)): #do a boxchart in 6A bin to see if line exists inside=np.where((self.fitwav1d > lwplot-4)& (self.fitwav1d < lwplot+4)) continuum=np.where(((self.fitwav1d > lwplot-20)& (self.fitwav1d < lwplot-10)) | ((self.fitwav1d > lwplot+10)& (self.fitwav1d < lwplot+20))) clevel=np.median(self.fitspe1d[continuum]) flux=np.sum((self.fitspe1d[inside]-clevel)) noise=np.sqrt(np.sum(self.fiterr1d[inside]**2)) #cut in SN if(flux/noise > 2): #stash lines_good_wave_rest.append(lw) lines_good_wave_obs.append(lwplot) lines_good_name.append(lnam) #generate a 4x? grid of plots nlines=len(lines_good_wave_rest) ncol=4 nraw=int(nlines/ncol) if(nlines%ncol > 0): nraw=nraw+1 czall=[] #loop on good stuff for fits for ii in range(nlines): #select region to fit fitwindow=np.where((self.fitwav1d > lines_good_wave_obs[ii]-10) & (self.fitwav1d < lines_good_wave_obs[ii]+10)) continuum=np.where(((self.fitwav1d > lines_good_wave_obs[ii]-20)& (self.fitwav1d < lines_good_wave_obs[ii]-10)) | ((self.fitwav1d > lines_good_wave_obs[ii]+10)& (self.fitwav1d < lines_good_wave_obs[ii]+20))) clevel=np.median(self.fitspe1d[continuum]) p0=np.array([10.,1.*float(lines_good_wave_obs[ii]),2.,0.]) #fit a Gaussian yval=np.nan_to_num(self.fitspe1d[fitwindow]-clevel) yerr=np.nan_to_num(self.fiterr1d[fitwindow]*1.) xval=np.nan_to_num(self.fitwav1d[fitwindow]*1.) popt,pcov=curve_fit(self.gauss,xval,yval,p0=p0, sigma=yerr) perr = np.sqrt(np.diag(pcov)) #eval fit xg=np.arange(min(xval)-2,max(xval)+2,0.2) fitg=self.gauss(xg,*popt) #grab fits czfit=popt[1]/lines_good_wave_rest[ii]-1. czfiterr=perr[1]/lines_good_wave_rest[ii] czall.append(czfit) #display ax = fig.add_subplot(nraw,ncol,ii+1) ax.plot(xval,yval) ax.plot(xval,yerr,color='red',linestyle="--",zorder=1) ax.plot(xg,fitg,color='black',linestyle=":") ax.set_title("{0}{1} z = {2:.6} +/- {3:.5}".format(lines_good_name[ii],int(lines_good_wave_rest[ii]),czfit,czfiterr)) #send message to user and reset redshift bestz=np.median(np.array(czall)) bestez=np.std(np.array(czall)) self.generic_message.set(r'zfit-> Best fit is {:6.5f}+/-{:6.5f}'.format(bestz,bestez)) self.redshiftline.set(bestz) #send figure to canvas self.linefitplot = FigureCanvasTkAgg(fig,master=self.lnfit) try: self.linefitplot.draw() except: self.linefitplot.show() #fig.tight_layout() self.linefitplot.get_tk_widget().grid() def fittemplate(self): """ Fit the template """ #init the template correlation realdata={'wave':self.fitwav1d,'flux':self.fitspe1d,'error':self.fiterr1d} ##Testing sequence #realdata={'wave':self.templatedata['wave']*(1+0.4329),'flux':self.templatedata['flux'], # 'error':self.templatedata['flux']} print('Computing correlation... be patient!') #find the wavelength range covering the min/max extent absmin=np.min([np.min(self.templatedata['wave']),np.min(realdata['wave'])]) absmax=np.max([np.max(self.templatedata['wave']),np.max(realdata['wave'])]) #resample in log deltal=5e-4 lnwave=np.arange(np.log(absmin),np.log(absmax),deltal) #resample with spline (s controls the smoothing) x=np.nan_to_num(self.templatedata['wave']) y=np.nan_to_num(self.templatedata['flux']) resamp_templ=interpolate.splrep(np.log(x),y,s=0) x=np.nan_to_num(realdata['wave']) y=np.nan_to_num(realdata['flux']) resamp_real=interpolate.splrep(np.log(x),y,s=0) #put everything on the same array - zero padding the extrapolation flux_templ=interpolate.splev(lnwave,resamp_templ,der=0,ext=1) flux_real=interpolate.splev(lnwave,resamp_real,der=0,ext=1) #masking strong sky lines mask=np.where((lnwave > np.log(5569.)) & (lnwave < np.log(5584.))) flux_real[mask]=0 mask=np.where((lnwave > np.log(6292.)) & (lnwave < np.log(6308.))) flux_real[mask]=0 mask=np.where((lnwave > np.log(6356.)) & (lnwave < np.log(6369.))) flux_real[mask]=0 mask=np.where((lnwave > 8.6752) & (lnwave < 8.6860)) flux_real[mask]=0 mask=np.where((lnwave > 8.8274) & (lnwave < 8.8525)) flux_real[mask]=0 mask=np.where((lnwave > 8.8862) & (lnwave < np.log(12000.))) flux_real[mask]=0 #correlate xcorr=np.correlate(flux_real,flux_templ,mode='full') #find the peak in the second half in units of redshift indxmax=np.argmax(xcorr)-len(xcorr)/2 peakz=np.exp(indxmax*deltal)-1 #print peakz #find the reshift axis indxarr=np.arange(0,len(lnwave),1) self.xcorr_redax=np.exp(indxarr*deltal)-1 self.xcorr_xcorr=xcorr[len(xcorr)/2:] self.xcorr_redshift=peakz #set the redshift in template window self.redshifttemp.set("{}".format(self.xcorr_redshift)) #trigger display options #lounch a new window self.tmlfit=tkinter.Toplevel(self.tk) #add xcorr to display #create properties for this plot self.tmpfitxcorr_prop={} self.tmpfitxcorr_prop["xmin"]=np.min(np.nan_to_num(self.xcorr_redax)) self.tmpfitxcorr_prop["xmax"]=np.max(np.nan_to_num(self.xcorr_redax)) self.tmpfitxcorr_prop["ymin"]=np.min(np.nan_to_num(self.xcorr_xcorr)) self.tmpfitxcorr_prop["ymax"]=np.max(np.nan_to_num(self.xcorr_xcorr)) self.tmpfitxcorr_prop["figure"]=Figure(figsize=(self.preferwinwidth/self.dpi*0.75,self.preferwinheight/self.dpi*0.75),dpi=self.dpi) self.tmpfitxcorr_prop["axis"]= self.tmpfitxcorr_prop["figure"].add_subplot(111) #call plotting routine self.update_xcorrplot() #send it to canvas self.tmpfitxcorr = FigureCanvasTkAgg(self.tmpfitxcorr_prop["figure"],master=self.tmlfit) self.tmpfitxcorr.show() #enable event on click self.tmpfitxcorr_prop["figure"].tight_layout() self.tmpfitxcorr.mpl_connect("button_press_event", self.pressbutton) self.tmpfitxcorr.mpl_connect("key_press_event", self.presskey) self.tmpfitxcorr.get_tk_widget().grid(column=0,row=0) def update_xcorrplot(self,update=False): """ Update plot for xcorrplot """ if(update): self.tmpfitxcorr_prop["axis"].cla() #plot main data self.tmpfitxcorr_prop["axis"].plot(self.xcorr_redax,self.xcorr_xcorr) self.tmpfitxcorr_prop["axis"].axvline(self.xcorr_redshift, color='grey', linestyle='--') self.tmpfitxcorr_prop["axis"].set_xlim(self.tmpfitxcorr_prop["xmin"],self.tmpfitxcorr_prop["xmax"]) self.tmpfitxcorr_prop["axis"].set_ylim(self.tmpfitxcorr_prop["ymin"],self.tmpfitxcorr_prop["ymax"]) self.tmpfitxcorr_prop["axis"].set_xlabel('Redshift') self.tmpfitxcorr_prop["axis"].set_ylabel('XCORR') #finally draw if(update): self.tmpfitxcorr.draw() def movemouse(self,event): """ Do stuff when mouse moves """ if(event.canvas == self.spectrumPlot): self.mouse_position.set('Mouse:({},{})'.format(event.xdata,event.ydata)) elif(event.canvas == self.twodspcPlot): try: self.mouse_position.set('Mouse:({},{})'.format(self.wavemap(event.xdata,0.0),event.ydata)) except: self.mouse_position.set('Mouse:(None,None)') elif(event.canvas == self.twoderrPlot): try: self.mouse_position.set('Mouse:({},{})'.format(self.wavemap(event.xdata,0.0),event.ydata)) except: self.mouse_position.set('Mouse:(None,None)') def pressbutton(self,event): """ Do stuff when data plot is pressed with mouse """ #this is how to redirect events if(event.canvas == self.twoderrPlot): #set focus self.twoderrPlot.get_tk_widget().focus_set() if(event.canvas == self.twodspcPlot): #set focus self.twodspcPlot.get_tk_widget().focus_set() if(event.canvas == self.twodimagePlot): #set focus self.twodimagePlot.get_tk_widget().focus_set() if(event.canvas == self.spectrumPlot): #set focus self.spectrumPlot.get_tk_widget().focus_set() #for right click, trigger line selector if(event.button == 3): self.lineselectorwidget(event) if(event.canvas == self.tmpfitxcorr): #set focus self.tmpfitxcorr.get_tk_widget().focus_set() def presskey(self,event): """ Do stuff when data plot is pressed with key """ #quit on q if(event.key == "q"): self.OnExit() #keyboard event when focus on spectrum if(event.canvas == self.spectrumPlot): self.spetrumPlot_events(event) #keyboard event when focus on xcorr if(event.canvas == self.tmpfitxcorr): self.tmpfitxcorr_events(event) def tmpfitxcorr_events(self,event): """ Handle events of xcorr plot """ #set bottom plot if(event.key == "b"): self.tmpfitxcorr_prop["ymin"]=event.ydata self.update_xcorrplot(update=True) #set top plot if(event.key == "t"): self.tmpfitxcorr_prop["ymax"]=event.ydata self.update_xcorrplot(update=True) #set left plot if(event.key == "l"): self.tmpfitxcorr_prop["xmin"]=event.xdata self.update_xcorrplot(update=True) #set right plot if(event.key == "r"): self.tmpfitxcorr_prop["xmax"]=event.xdata self.update_xcorrplot(update=True) #zoom in if(event.key == "i"): #find the current width in x currentwidth=self.tmpfitxcorr_prop["xmax"]-self.tmpfitxcorr_prop["xmin"] #zoom in by factor of 2 currentwidth=currentwidth*0.5 #zoom around selected wave self.tmpfitxcorr_prop["xmin"]=event.xdata-currentwidth/2. self.tmpfitxcorr_prop["xmax"]=event.xdata+currentwidth/2. self.update_xcorrplot(update=True) #zoom out if(event.key == "o"): #find the current width in x currentwidth=self.tmpfitxcorr_prop["xmax"]-self.tmpfitxcorr_prop["xmin"] #zoom out by factor of 2 currentwidth=currentwidth*2 #zoom around selected wave self.tmpfitxcorr_prop["xmin"]=event.xdata-currentwidth/2. self.tmpfitxcorr_prop["xmax"]=event.xdata+currentwidth/2. self.update_xcorrplot(update=True) #pan left if(event.key == "["): #find the current width in x currentwidth=self.tmpfitxcorr_prop["xmax"]-self.tmpfitxcorr_prop["xmin"] #pan left self.tmpfitxcorr_prop["xmin"]=self.tmpfitxcorr_prop["xmin"]-currentwidth/2 self.tmpfitxcorr_prop["xmax"]=self.tmpfitxcorr_prop["xmax"]-currentwidth/2 self.update_xcorrplot(update=True) #pan right if(event.key == "]"): #find the current width in x currentwidth=self.tmpfitxcorr_prop["xmax"]-self.tmpfitxcorr_prop["xmin"] #pan right self.tmpfitxcorr_prop["xmin"]=self.tmpfitxcorr_prop["xmin"]+currentwidth/2 self.tmpfitxcorr_prop["xmax"]=self.tmpfitxcorr_prop["xmax"]+currentwidth/2 self.update_xcorrplot(update=True) #set reset plot if(event.key == "W"): self.tmpfitxcorr_prop["xmin"]=np.min(np.nan_to_num(self.xcorr_redax)) self.tmpfitxcorr_prop["xmax"]=np.max(np.nan_to_num(self.xcorr_redax)) self.tmpfitxcorr_prop["ymin"]=np.min(np.nan_to_num(self.xcorr_xcorr)) self.tmpfitxcorr_prop["ymax"]=np.max(np.nan_to_num(self.xcorr_xcorr)) self.update_xcorrplot(update=True) #mark new redshift if(event.key == "z"): #update relevent info self.xcorr_redshift=event.xdata self.redshifttemp.set("{}".format(self.xcorr_redshift)) #refresh plot self.update_xcorrplot(update=True) #display template self.displaytemplate() def spetrumPlot_events(self,event): """" Handle events of spectrum plot """ #set bottom plot if(event.key == "b"): self.spectrumPlot_prop["ymin"]=event.ydata self.update_spectrum(update=True) #set top plot if(event.key == "t"): self.spectrumPlot_prop["ymax"]=event.ydata self.update_spectrum(update=True) #set left plot if(event.key == "l"): self.spectrumPlot_prop["xmin"]=event.xdata self.update_spectrum(update=True) #update 2d spectra accordingly self.update_twodspec(update=True) self.update_twoderr(update=True) #set right plot if(event.key == "r"): self.spectrumPlot_prop["xmax"]=event.xdata self.update_spectrum(update=True) #update 2d spectra accordingly self.update_twodspec(update=True) self.update_twoderr(update=True) #zoom in if(event.key == "i"): #find the current width in x currentwidth=self.spectrumPlot_prop["xmax"]-self.spectrumPlot_prop["xmin"] #zoom in by factor of 2 currentwidth=currentwidth*0.5 #zoom around selected wave self.spectrumPlot_prop["xmin"]=event.xdata-currentwidth/2. self.spectrumPlot_prop["xmax"]=event.xdata+currentwidth/2. self.update_spectrum(update=True) #update 2d spectra accordingly self.update_twodspec(update=True) self.update_twoderr(update=True) #zoom out if(event.key == "o"): #find the current width in x currentwidth=self.spectrumPlot_prop["xmax"]-self.spectrumPlot_prop["xmin"] #zoom out by factor of 2 currentwidth=currentwidth*2 #zoom around selected wave self.spectrumPlot_prop["xmin"]=event.xdata-currentwidth/2. self.spectrumPlot_prop["xmax"]=event.xdata+currentwidth/2. self.update_spectrum(update=True) #update 2d spectra accordingly self.update_twodspec(update=True) self.update_twoderr(update=True) #pan left if(event.key == "["): #find the current width in x currentwidth=self.spectrumPlot_prop["xmax"]-self.spectrumPlot_prop["xmin"] #pan left self.spectrumPlot_prop["xmin"]=self.spectrumPlot_prop["xmin"]-currentwidth/2 self.spectrumPlot_prop["xmax"]=self.spectrumPlot_prop["xmax"]-currentwidth/2 self.update_spectrum(update=True) #update 2d spectra accordingly self.update_twodspec(update=True) self.update_twoderr(update=True) #pan right if(event.key == "]"): #find the current width in x currentwidth=self.spectrumPlot_prop["xmax"]-self.spectrumPlot_prop["xmin"] #pan right self.spectrumPlot_prop["xmin"]=self.spectrumPlot_prop["xmin"]+currentwidth/2 self.spectrumPlot_prop["xmax"]=self.spectrumPlot_prop["xmax"]+currentwidth/2 self.update_spectrum(update=True) #update 2d spectra accordingly self.update_twodspec(update=True) self.update_twoderr(update=True) #set reset plot if(event.key == "W"): self.spectrumPlot_prop["xmin"]=np.min(np.nan_to_num(self.fitwav1d)) self.spectrumPlot_prop["xmax"]=np.max(np.nan_to_num(self.fitwav1d)) self.spectrumPlot_prop["ymin"]=np.min(np.nan_to_num(self.fitspe1d)) self.spectrumPlot_prop["ymax"]=np.max(np.nan_to_num(self.fitspe1d)) self.update_spectrum(update=True) #update 2d spectra accordingly self.update_twodspec(update=True) self.update_twoderr(update=True) #smooth plot if(event.key == "S"): self.fitspe1d=signal.medfilt(self.fitspe1d,self.smooth) self.smooth=self.smooth+2 self.update_spectrum(update=True) #unsmooth smooth if(event.key == "U"): self.fitspe1d=self.fitspe1d_original self.smooth=3 self.update_spectrum(update=True) def lineselectorwidget(self,event): """ Control what happens when right-click on 1D spectrum - trigger construction of line list selector """ #refresh lines as needed self.displaylines() #lounch a new window self.lnsel=tkinter.Toplevel(self.tk) #pick z try: redsh=float(self.redshiftline.get()) except: redsh=0.0 #create line buttons for those visibles self.wlineselect = tkinter.DoubleVar() self.wlinepos = event.xdata i=0 for lw,lnam in self.infoline: lwplot=lw*(1+redsh) tkinter.Radiobutton(self.lnsel, text=lnam+"{}".format(int(lw)), variable=self.wlineselect, value=lw, command=self.pickedline).grid(row = i%30, column = i/30, sticky = "NWSE") i=i+1 self.tk.wait_window(self.lnsel) def pickedline(self): """ If one pick a line, find redshift """ #find the redshift redshift=self.wlinepos/self.wlineselect.get()-1 #set it - auto trigger refresh self.shwlinstate.set(1) self.redshiftline.set("{}".format(redshift)) #destroy window self.lnsel.destroy() def gauss(self,x, *p): """ Gaussian model for line fit """ A, mu, sigma, zero = p gg=A*np.exp(-1.*(x-mu)*(x-mu)/(2.*sigma*sigma))+zero return gg
def onCancel(self): if self.threads == 0: Tk().quit() else: showinfo(self.title, 'Cannot exit: %d threads running' % self.threads)
import Tkinter from Tkinter import Tk top = Tk() top.minsize(200, 200) top.mainloop()
def size(self): return self.lists[0].size() def see(self, index): for l in self.lists: l.see(index) def selection_anchor(self, index): for l in self.lists: l.selection_anchor(index) def selection_clear(self, first, last=None): for l in self.lists: l.selection_clear(first, last) def selection_includes(self, index): return self.lists[0].selection_includes(index) def selection_set(self, first, last=None): for l in self.lists: l.selection_set(first, last) if __name__ == '__main__': tk = Tk() Label(tk, text='MultiListbox').pack() mlb = MultiListbox(tk, (('Subject', 40), ('Sender', 20), ('Date', 10))) for i in range(1000): mlb.insert(END, ('Important Message: %d' % i, 'John Doe', '10/10/%04d' % (1900 + i))) mlb.pack(expand=YES, fill=BOTH) tk.mainloop()
class ContinuousTMPViewer(object): def __init__(self, suction_height, regions, tl_x=0, tl_y=0, width=400, height=200, title='Grid', background=BACKGROUND_COLOR): self.tk = Tk() # tk.geometry('%dx%d+%d+%d'%(width, height, 100, 0)) self.tk.withdraw() self.top = Toplevel(self.tk) self.top.wm_title(title) self.top.protocol('WM_DELETE_WINDOW', self.top.destroy) self.suction_height = suction_height self.regions = regions self.width = width self.height = height self.canvas = Canvas(self.top, width=self.width, height=self.height, background=background) self.canvas.pack() # self.center() self.move_frame(tl_x, tl_y) min_x = min(x1 for x1, _ in regions.values()) max_x = max(x2 for _, x2 in regions.values()) max_width = max_x - min_x self.dist_to_pixel = (self.width - 2 * PIXEL_BUFFER ) / max_width # Maintains aspect ratio self.dist_width = self.width / self.dist_to_pixel self.dist_height = self.height / self.dist_to_pixel self.ground_height = self.height - self.dist_to_pixel * ENV_HEIGHT self.robot_dist = self.dist_height / 2. self.dynamic = [] self.static = [] self.draw_environment() def center(self): self.top.update_idletasks() w = self.top.winfo_screenwidth() h = self.top.winfo_screenheight() size = tuple( int(_) for _ in self.top.geometry().split('+')[0].split('x')) x = w / 2 - size[0] / 2 y = h / 2 - size[1] / 2 self.top.geometry("%dx%d+%d+%d" % (size + (x, y))) def move_frame(self, x, y): self.top.update_idletasks() size = tuple( int(_) for _ in self.top.geometry().split('+')[0].split('x')) self.top.geometry("%dx%d+%d+%d" % (size + (x, y))) def scale_x(self, x): # x \in [-self.dist_width/2, self.dist_width/2] return self.width / 2. + self.dist_to_pixel * x def scale_y(self, y): # y \in [0, self.dist_height] return self.ground_height - self.dist_to_pixel * y def draw_block(self, x, y, width, height, name='', color='blue'): self.dynamic.extend([ self.canvas.create_rectangle(self.scale_x(x - width / 2.), self.scale_y(y), self.scale_x(x + width / 2.), self.scale_y(y + height), fill=color, outline='black', width=2), self.canvas.create_text(self.scale_x(x), self.scale_y(y + height / 2), text=name), ]) # def draw_holding(self, x, width, height, color='blue'): # self.holding = self.canvas.create_rectangle(self.scale_x(x - width / 2.), # self.scale_y(self.robot_dist - SUCTION_HEIGHT / 2 - height), # self.scale_x(x + width / 2.), # self.scale_y(self.robot_dist - SUCTION_HEIGHT / 2), # fill=color, outline='black', width=2) def draw_region(self, region, name=''): x1, x2 = map(self.scale_x, region) y1, y2 = self.ground_height, self.height color = COLOR_FROM_NAME.get(name, name) self.static.extend([ self.canvas.create_rectangle(x1, y1, x2, y2, fill=color, outline='black', width=2), self.canvas.create_text((x1 + x2) / 2, (y1 + y2) / 2, text=name), ]) def draw_environment(self): # TODO: automatically draw in order self.static = [] for name, region in sorted(self.regions.items(), key=lambda pair: get_width(pair[1]), reverse=True): self.draw_region(region, name=name) def draw_robot( self, x, y, name='', color='yellow' ): # TODO - could also visualize as top grasps instead of side grasps #y = self.robot_dist self.dynamic.extend([ self.canvas.create_rectangle( self.scale_x(x - SUCTION_WIDTH / 2.), self.scale_y(y - self.suction_height / 2.), self.scale_x(x + SUCTION_WIDTH / 2.), self.scale_y(y + self.suction_height / 2.), fill=color, outline='black', width=2), self.canvas.create_text(self.scale_x(x), self.scale_y(y), text=name), self.canvas.create_rectangle( self.scale_x(x - STEM_WIDTH / 2.), self.scale_y(y + self.suction_height / 2.), self.scale_x(x + STEM_WIDTH / 2.), self.scale_y(y + self.suction_height / 2. + STEM_HEIGHT), fill=color, outline='black', width=2), ]) def clear_state(self): for part in self.dynamic: self.canvas.delete(part) self.dynamic = [] def clear_all(self): self.canvas.delete('all') def save(self, filename): # TODO: screen recording based on location like I did before # TODO: only works on windows # self.canvas.postscript(file='%s.ps'%filename, colormode='color') #from PIL import ImageGrab try: import pyscreenshot as ImageGrab except ImportError: print('Unable to load pyscreenshot') return None # TODO: screenshot is in the wrong place x, y = self.top.winfo_x(), 2 * self.top.winfo_y() width, height = self.top.winfo_width(), self.top.winfo_height( ) # winfo_width, winfo_reqheight path = filename + '.png' print('Saved', path) ImageGrab.grab((x, y, x + width, y + height)).save(path) return path
def show_error(err): root = Tk() root.title('Error') try: root.call('wm', 'iconphoto', root._w, PhotoImage(file='ico.png')) except Exception: print 'Error loading icon' root.geometry('200x100+100+100') root.overrideredirect(True) Label(root, text=err).place(x=0, y=0, height=50, relwidth=1.0) Button(root, text='Ok', command=lambda: exit(root)).place(x=60, y=60, height=30, width=80) root.mainloop()
if c == '(': paren += 1 elif c == ')': paren -= 1 #if paren < 0: if paren != 0: print "LINE", lnum, ": SYNTAX ERROR 01" print line return if incomplete: print "LINE", lnum, ": SYNTAX ERROR 02" print line return""" root = Tk() root.withdraw() def readfile(pfile): global lines lines = pfile.readlines() #[l[:-1] for l in pfile.readlines()] # print lines def interpret(): #keep track of values
class ContinuousTMPViewer(object): def __init__(self, env_region, regions=[], tl_x=0, tl_y=0, width=500, height=250, title='Grid', background='tan'): self.tk = Tk() self.tk.withdraw() self.top = Toplevel(self.tk) self.top.wm_title(title) self.top.protocol('WM_DELETE_WINDOW', self.top.destroy) self.env_region = env_region self.regions = regions self.tl_x = tl_x self.tl_y = tl_y self.width = width self.height = height self.canvas = Canvas(self.top, width=self.width, height=self.height, background=background) self.canvas.pack() self.move_frame(self.tl_x, self.tl_y) self.dist_to_pixel = (self.width - 2 * PIXEL_BUFFER) / (self.env_region.w) self.dist_width = self.width / self.dist_to_pixel self.dist_height = self.height / self.dist_to_pixel self.ground_height = self.height - self.dist_to_pixel * ENV_HEIGHT self.robot_dist = self.dist_height / 2. self.robot = [] self.blocks = [] self.holding = None self.draw_environment() def center(self): self.top.update_idletasks() w = self.top.winfo_screenwidth() h = self.top.winfo_screenheight() size = tuple( int(_) for _ in self.top.geometry().split('+')[0].split('x')) x = w / 2 - size[0] / 2 y = h / 2 - size[1] / 2 self.top.geometry("%dx%d+%d+%d" % (size + (x, y))) def move_frame(self, x, y): self.top.update_idletasks() size = tuple( int(_) for _ in self.top.geometry().split('+')[0].split('x')) self.top.geometry("%dx%d+%d+%d" % (size + (x, y))) def t_x(self, x): return self.dist_to_pixel * (x + self.dist_width / 2.) def t_y(self, y): return self.ground_height - self.dist_to_pixel * y def draw_block(self, block, x): self.blocks.append( self.canvas.create_rectangle(self.t_x(x - block.w / 2.), self.t_y(0), self.t_x(x + block.w / 2.), self.t_y(block.h), fill=block.color, outline='black', width=2)) def draw_holding(self, block, x): self.holding = self.canvas.create_rectangle( self.t_x(x - block.w / 2.), self.t_y(self.robot_dist - SUCTION_HEIGHT / 2 - block.h), self.t_x(x + block.w / 2.), self.t_y(self.robot_dist - SUCTION_HEIGHT / 2), fill=block.color, outline='black', width=2) def draw_region(self, region): self.environment.append( self.canvas.create_rectangle(self.t_x(region.x - region.w / 2.), self.ground_height, self.t_x(region.x + region.w / 2.), self.height, fill='red', outline='black', width=2)) def draw_environment(self, table_color='lightgrey', bin_color='grey'): self.environment = [ self.canvas.create_rectangle(self.t_x(-self.env_region.w / 2), self.ground_height, self.t_x(self.env_region.w / 2), self.height, fill=table_color, outline='black', width=2) ] for region in self.regions: self.draw_region(region) def draw_robot(self, x, color='yellow'): self.robot = [ self.canvas.create_rectangle( self.t_x(x - SUCTION_WIDTH / 2.), self.t_y(self.robot_dist - SUCTION_HEIGHT / 2.), self.t_x(x + SUCTION_WIDTH / 2.), self.t_y(self.robot_dist + SUCTION_HEIGHT / 2.), fill=color, outline='black', width=2), self.canvas.create_rectangle( self.t_x(x - STEM_WIDTH / 2.), self.t_y(self.robot_dist + SUCTION_HEIGHT / 2.), self.t_x(x + STEM_WIDTH / 2.), self.t_y(self.robot_dist + SUCTION_HEIGHT / 2. + STEM_HEIGHT), fill=color, outline='black', width=2), ] def clear_state(self): for block in self.blocks: self.canvas.delete(block) for part in self.robot: self.canvas.delete(part) if self.holding is not None: self.canvas.delete(self.holding) def clear_all(self): self.canvas.delete('all') def save(self, filename): from PIL import ImageGrab ImageGrab.grab((0, 0, self.width, self.height)).save(filename + '.jpg')
def main(): print "main" root = Tk() env = Environment(root) root.geometry("500x200+300+300") root.mainloop()
def setUpClass(cls): requires('gui') from Tkinter import Tk, Text cls.Text = Text cls.root = Tk()
from Tkinter import Tk, Label, Entry, Button from tkMessageBox import showinfo my_app = Tk(className='coba-coba') L1 = Label(my_app, text="DATA DIRI", font=("Times New Roman", 20)) L1.grid(row=0, column=1) L2 = Label(my_app, text="nama") L2.grid(row=1, column=0) E2 = Entry(my_app) E2.grid(row=1, column=1) L3 = Label(my_app, text="nim ") L3.grid(row=2, column=0) E3 = Entry(my_app) E3.grid(row=2, column=1) L4 = Label(my_app, text="buku favorit ") L4.grid(row=3, column=0) E4 = Entry(my_app) E4.grid(row=3, column=1) L5 = Label(my_app, text="idola ") L5.grid(row=4, column=0) E5 = Entry(my_app) E5.grid(row=4, column=1) L6 = Label(my_app, text="motto ") L6.grid(row=5, column=0) E6 = Entry(my_app) E6.grid(row=5, column=1) def quit(): my_app.destroy()
def setUpClass(cls): requires('gui') cls.root = Tk() _initializeTkVariantTests(cls.root)
# -*- coding: utf8 -*- from Tkinter import Tk r = Tk() r.withdraw() r.clipboard_clear() r.clipboard_append('两两相忘') r.update() # now it stays on the clipboard after the window is closed r.destroy()
try: from Tkinter import Tk except ImportError: from tkinter import Tk from idlelib.TreeWidget import ScrolledCanvas, FileTreeItem, TreeNode import os root = Tk() root.title("Test TreeWidget") sc = ScrolledCanvas(root, bg="white", highlightthickness=0, takefocus=1) sc.frame.pack(expand=1, fill="both", side="left") item = FileTreeItem(os.getcwd()) node = TreeNode(sc.canvas, None, item) node.expand() root.mainloop()
# INPUTS # ------------------------------------------------- dir_path = os.path.abspath(os.path.dirname(__file__)) # Name base folder base = 'iPhone Files' # base = 'test II' src_dir = dir_path + os.sep + base + os.sep # Get path to iPhone photo files Files = glob.glob(src_dir + '*' + os.sep + '*.jpg*') if Files == []: # Get path from user Tk().withdraw( ) # we don't want a full GUI, so keep the root window from appearing filename = askdirectory( initialdir="/", title= "I can't find your iPhone photos. \nPlease show me where you keep them?" ) # show an "Open" dialog box and return the path to the selected file src_dir = str(filename) src_dir = src_dir.replace('/', '\\') base = src_dir[find_last(src_dir, '\\') + 1:] # Check that destination directories exist and create if not if not os.path.exists(dir_path + os.sep + base + "- Copy" + os.sep): os.makedirs(dir_path + os.sep + base + "- Copy" + os.sep) copy_dir = dir_path + os.sep + base + "- Copy" + os.sep if not os.path.exists(dir_path + os.sep + base + "- Timestamped" + os.sep): os.makedirs(dir_path + os.sep + base + "- Timestamped" + os.sep)
def __init__(self): self.root = Tk() self.show()
def rmshadows(humfile, sonpath, win, shadowmask, doplot, dissim, correl, contrast, energy, mn): ''' Remove dark shadows in scans caused by shallows, shorelines, and attenuation of acoustics with distance Manual or automated processing options available Works on the radiometrically corrected outputs of the correct module Syntax ---------- [] = PyHum.rmshadows(humfile, sonpath, win, shadowmask, doplot) Parameters ---------- humfile : str path to the .DAT file sonpath : str path where the *.SON files are win : int, *optional* [Default=100] window size (pixels) for the automated shadow removal algorithm shadowmask : int, *optional* [Default=0] 1 = do manual shadow masking, otherwise do automatic shadow masking doplot : int, *optional* [Default=1] 1 = make plots, otherwise do not Returns ------- sonpath+base+'_data_star_la.dat': memory-mapped file contains the starboard scan with water column removed and radiometrically corrected, and shadows removed sonpath+base+'_data_port_la.dat': memory-mapped file contains the portside scan with water column removed and radiometrically corrected, and shadows removed ''' # prompt user to supply file if no input file given if not humfile: print('An input file is required!!!!!!') Tk().withdraw( ) # we don't want a full GUI, so keep the root window from appearing humfile = askopenfilename(filetypes=[("DAT files", "*.DAT")]) # prompt user to supply directory if no input sonpath is given if not sonpath: print('A *.SON directory is required!!!!!!') Tk().withdraw( ) # we don't want a full GUI, so keep the root window from appearing sonpath = askdirectory() # print given arguments to screen and convert data type where necessary if humfile: print('Input file is %s' % (humfile)) if sonpath: print('Sonar file path is %s' % (sonpath)) if win: win = np.asarray(win, int) print('Window is %s square pixels' % (str(win))) if shadowmask: shadowmask = np.asarray(shadowmask, int) if shadowmask == 1: print('Shadow masking is manual') else: print('Shadow masking is auto') if doplot: doplot = int(doplot) if doplot == 0: print("Plots will not be made") if dissim: dissim = np.asarray(dissim, int) print('Threshold dissimilarity (shadow is <) is %s' % (str(dissim))) if correl: correl = np.asarray(correl, int) print('Threshold correlation (shadow is <) is %s' % (str(correl))) if contrast: contrast = np.asarray(contrast, int) print('Threshold contrast (shadow is <) is %s' % (str(contrast))) if energy: energy = np.asarray(energy, int) print('Threshold energy (shadow is >) is %s' % (str(energy))) if mn: mn = np.asarray(mn, int) print('Threshold mean intensity (shadow is <) is %s' % (str(mn))) # start timer if os.name == 'posix': # true if linux/mac or cygwin on windows start = time.time() else: # windows start = time.clock() # if son path name supplied has no separator at end, put one on if sonpath[-1] != os.sep: sonpath = sonpath + os.sep base = humfile.split('.DAT') # get base of file name for output base = base[0].split(os.sep)[-1] base = humutils.strip_base(base) meta = loadmat(os.path.normpath(os.path.join(sonpath, base + 'meta.mat'))) # load memory mapped scans shape_port = np.squeeze(meta['shape_port']) if shape_port != '': #port_fp = np.memmap(sonpath+base+'_data_port_la.dat', dtype='float32', mode='r', shape=tuple(shape_port)) with open( os.path.normpath( os.path.join(sonpath, base + '_data_port_la.dat')), 'r') as ff: port_fp = np.memmap(ff, dtype='float32', mode='r', shape=tuple(shape_port)) shape_star = np.squeeze(meta['shape_star']) if shape_star != '': #star_fp = np.memmap(sonpath+base+'_data_star_la.dat', dtype='float32', mode='r', shape=tuple(shape_star)) with open( os.path.normpath( os.path.join(sonpath, base + '_data_star_la.dat')), 'r') as ff: star_fp = np.memmap(ff, dtype='float32', mode='r', shape=tuple(shape_star)) dist_m = np.squeeze(meta['dist_m']) ft = 1 / (meta['pix_m']) extent = shape_star[1] if shadowmask == 1: #manual Zt = [] if len(np.shape(star_fp)) > 2: for p in range(len(star_fp)): raw_input( "Shore picking " + str(p + 1) + " of " + str(len(star_fp)) + " (starboard), are you ready? 60 seconds. Press Enter to continue..." ) shoreline_star = {} fig = plt.figure() ax = plt.gca() ax.imshow(star_fp[p], cmap='gray') #, origin = 'upper') #im = plt.axis('normal') plt.axis('tight') pts1 = plt.ginput( n=300, timeout=75) # it will wait for 200 clicks or 75 seconds x1 = map(lambda x: x[0], pts1) # map applies the function passed as y1 = map(lambda x: x[1], pts1) # first parameter to each element of pts shoreline_star = np.interp(np.r_[:np.shape(star_fp[p])[1]], x1, y1) plt.close() del fig star_mg = star_fp[p].copy() shoreline_star = np.asarray(shoreline_star, 'int') # shift proportionally depending on where the bed is for k in range(np.shape(star_mg)[1]): star_mg[shoreline_star[k]:, k] = np.nan del shoreline_star Zt.append(star_mg) else: raw_input( "Shore picking " + str(len(star_fp)) + " of " + str(len(star_fp)) + " (starboard), are you ready? 60 seconds. Press Enter to continue..." ) shoreline_star = {} fig = plt.figure() ax = plt.gca() ax.imshow(star_fp, cmap='gray') #, origin = 'upper') #im = plt.axis('normal') plt.axis('tight') pts1 = plt.ginput( n=300, timeout=75) # it will wait for 200 clicks or 75 seconds x1 = map(lambda x: x[0], pts1) # map applies the function passed as y1 = map(lambda x: x[1], pts1) # first parameter to each element of pts shoreline_star = np.interp(np.r_[:np.shape(star_fp)[1]], x1, y1) plt.close() del fig star_mg = star_fp.copy() shoreline_star = np.asarray(shoreline_star, 'int') # shift proportionally depending on where the bed is for k in range(np.shape(star_mg)[1]): star_mg[shoreline_star[k]:, k] = np.nan del shoreline_star Zt.append(star_mg) ## create memory mapped file for Z #p = np.memmap(sonpath+base+'_data_star_la.dat', dtype='float32', mode='w+', shape=np.shape(Zt)) #fp[:] = Zt[:] #del fp Zt = np.squeeze(Zt) # create memory mapped file for Zs #fp = np.memmap(sonpath+base+'_data_star_lar.dat', dtype='float32', mode='w+', shape=np.shape(Zs)) with open( os.path.normpath( os.path.join(sonpath, base + '_data_star_lar.dat')), 'w+') as ff: fp = np.memmap(ff, dtype='float32', mode='w+', shape=np.shape(Zt)) fp[:] = Zt[:] del fp del Zt #shutil.move(os.path.normpath(os.path.join(sonpath,base+'_data_star_lar.dat')), os.path.normpath(os.path.join(sonpath,base+'_data_star_la.dat'))) Zt = [] if len(np.shape(star_fp)) > 2: for p in range(len(port_fp)): raw_input( "Shore picking " + str(p + 1) + " of " + str(len(port_fp)) + " (port), are you ready? 60 seconds. Press Enter to continue..." ) shoreline_port = {} fig = plt.figure() ax = plt.gca() ax.imshow(port_fp[p], cmap='gray') #, origin = 'upper') #im = plt.axis('normal') plt.axis('tight') pts1 = plt.ginput( n=300, timeout=75) # it will wait for 200 clicks or 75 seconds x1 = map(lambda x: x[0], pts1) # map applies the function passed as y1 = map(lambda x: x[1], pts1) # first parameter to each element of pts shoreline_port = np.interp(np.r_[:np.shape(port_fp[p])[1]], x1, y1) plt.close() del fig port_mg = port_fp[p].copy() shoreline_port = np.asarray(shoreline_port, 'int') # shift proportionally depending on where the bed is for k in range(np.shape(port_mg)[1]): port_mg[shoreline_port[k]:, k] = np.nan del shoreline_port Zt.append(port_mg) else: raw_input( "Shore picking " + str(len(port_fp)) + " of " + str(len(port_fp)) + " (port), are you ready? 60 seconds. Press Enter to continue..." ) shoreline_port = {} fig = plt.figure() ax = plt.gca() ax.imshow(port_fp, cmap='gray') #, origin = 'upper') #im = plt.axis('normal') plt.axis('tight') pts1 = plt.ginput( n=300, timeout=75) # it will wait for 200 clicks or 75 seconds x1 = map(lambda x: x[0], pts1) # map applies the function passed as y1 = map(lambda x: x[1], pts1) # first parameter to each element of pts shoreline_port = np.interp(np.r_[:np.shape(port_fp)[1]], x1, y1) plt.close() del fig port_mg = port_fp.copy() shoreline_port = np.asarray(shoreline_port, 'int') # shift proportionally depending on where the bed is for k in range(np.shape(port_mg)[1]): port_mg[shoreline_port[k]:, k] = np.nan del shoreline_port Zt.append(port_mg) Zt = np.squeeze(Zt) ## create memory mapped file for Z #fp = np.memmap(sonpath+base+'_data_port_la.dat', dtype='float32', mode='w+', shape=np.shape(Zt)) #fp[:] = Zt[:] #del fp # create memory mapped file for Zp #fp = np.memmap(sonpath+base+'_data_port_lar.dat', dtype='float32', mode='w+', shape=np.shape(Zp)) with open( os.path.normpath( os.path.join(sonpath, base + '_data_port_lar.dat')), 'w+') as ff: fp = np.memmap(ff, dtype='float32', mode='w+', shape=np.shape(Zt)) fp[:] = Zt[:] del fp del Zt #shutil.move(os.path.normpath(os.path.join(sonpath,base+'_data_port_lar.dat')), os.path.normpath(os.path.join(sonpath,base+'_data_port_la.dat'))) else: #auto Zs = [] Zp = [] if len(np.shape(star_fp)) > 2: for p in range(len(star_fp)): merge = np.vstack((np.flipud(port_fp[p]), star_fp[p])) merge = np.asarray(merge, 'float64') merge_mask = np.vstack((np.flipud(port_fp[p]), star_fp[p])) merge[merge_mask == 0] = 0 del merge_mask mask = np.asarray(merge != 0, 'int8') # only 8bit precision needed merge[np.isnan(merge)] = 0 #Z,ind = humutils.sliding_window(merge,(win,win),(win/2,win/2)) Z, ind = humutils.sliding_window(merge, (win, win), (win, win)) #zmean = np.reshape(zmean, ( ind[0], ind[1] ) ) Ny, Nx = np.shape(merge) #zmean[np.isnan(zmean)] = 0 try: #parallel processing with all available cores w = Parallel(n_jobs=-1, verbose=0)(delayed(parallel_me)( Z[k], dissim, correl, contrast, energy, mn) for k in range(len(Z))) except: #fall back to serial w = Parallel(n_jobs=1, verbose=0)(delayed(parallel_me)( Z[k], dissim, correl, contrast, energy, mn) for k in range(len(Z))) zmean = np.reshape(w, (ind[0], ind[1])) del w M = humutils.im_resize(zmean, Nx, Ny) M[mask == 0] = 0 del zmean bw = M > 0.5 del M # erode and dilate to remove splotches of no data bw2 = binary_dilation(binary_erosion(bw, structure=np.ones( (3, 3))), structure=np.ones((13, 13))) #bw2 = binary_dilation(binary_erosion(bw,structure=np.ones((win/4,win/4))), structure=np.ones((win/4,win/4))) ##bw2 = binary_erosion(bw,structure=np.ones((win*2,win*2))) ## fill holes bw2 = binary_fill_holes(bw2, structure=np.ones( (win, win))).astype(int) merge2 = grey_erosion(merge, structure=np.ones((win, win))) #del bw #bw2 = np.asarray(bw2!=0,'int8') # we only need 8 bit precision bw2 = np.asarray(bw != 0, 'int8') # we only need 8 bit precision del bw merge[bw2 == 1] = 0 #blank out bad data merge[merge2 == np.min(merge2)] = 0 #blank out bad data del merge2 ## do plots of merged scans if doplot == 1: Zdist = dist_m[shape_port[-1] * p:shape_port[-1] * (p + 1)] fig = plt.figure() plt.imshow(merge, cmap='gray', extent=[ min(Zdist), max(Zdist), -extent * (1 / ft), extent * (1 / ft) ]) plt.ylabel('Range (m)'), plt.xlabel( 'Distance along track (m)') plt.axis('normal') plt.axis('tight') custom_save(sonpath, 'merge_corrected_rmshadow_scan' + str(p)) del fig Zp.append(np.flipud(merge[:shape_port[1], :])) Zs.append(merge[shape_port[1]:, :]) del merge, bw2 else: merge = np.vstack((np.flipud(port_fp), star_fp)) merge = np.asarray(merge, 'float64') merge_mask = np.vstack((np.flipud(port_fp), star_fp)) merge[merge_mask == 0] = 0 del merge_mask mask = np.asarray(merge != 0, 'int8') # only 8bit precision needed merge[np.isnan(merge)] = 0 #Z,ind = humutils.sliding_window(merge,(win,win),(win/2,win/2)) Z, ind = humutils.sliding_window(merge, (win, win), (win, win)) #zmean = np.reshape(zmean, ( ind[0], ind[1] ) ) Ny, Nx = np.shape(merge) #zmean[np.isnan(zmean)] = 0 try: #parallel processing with all available cores w = Parallel(n_jobs=-1, verbose=0)(delayed(parallel_me)( Z[k], dissim, correl, contrast, energy, mn) for k in range(len(Z))) except: #fall back to serial w = Parallel(n_jobs=1, verbose=0)(delayed(parallel_me)( Z[k], dissim, correl, contrast, energy, mn) for k in range(len(Z))) zmean = np.reshape(w, (ind[0], ind[1])) del w M = humutils.im_resize(zmean, Nx, Ny) M[mask == 0] = 0 del zmean bw = M > 0.5 del M # erode and dilate to remove splotches of no data bw2 = binary_dilation(binary_erosion(bw, structure=np.ones( (3, 3))), structure=np.ones((13, 13))) #bw2 = binary_dilation(binary_erosion(bw,structure=np.ones((win/4,win/4))), structure=np.ones((win/4,win/4))) ##bw2 = binary_erosion(bw,structure=np.ones((win*2,win*2))) ## fill holes bw2 = binary_fill_holes(bw2, structure=np.ones( (win, win))).astype(int) merge2 = grey_erosion(merge, structure=np.ones((win, win))) #del bw #bw2 = np.asarray(bw2!=0,'int8') # we only need 8 bit precision bw2 = np.asarray(bw != 0, 'int8') # we only need 8 bit precision del bw merge[bw2 == 1] = 0 #blank out bad data merge[merge2 == np.min(merge2)] = 0 #blank out bad data del merge2 # erode and dilate to remove splotches of no data #bw2 = binary_dilation(binary_erosion(bw,structure=np.ones((3,3))), structure=np.ones((13,13))) #bw2 = binary_dilation(binary_erosion(bw,structure=np.ones((win,win))), structure=np.ones((win*2,win*2))) #bw2 = binary_erosion(bw,structure=np.ones((win,win))) # fill holes #bw2 = binary_fill_holes(bw2, structure=np.ones((3,3))).astype(int) #del bw #bw2 = np.asarray(bw2!=0,'int8') # we only need 8 bit precision #merge[bw2==1] = 0 #blank out bad data ## do plots of merged scans if doplot == 1: Zdist = dist_m fig = plt.figure() plt.imshow(merge, cmap='gray', extent=[ min(Zdist), max(Zdist), -extent * (1 / ft), extent * (1 / ft) ]) plt.ylabel('Range (m)'), plt.xlabel('Distance along track (m)') plt.axis('normal') plt.axis('tight') custom_save(sonpath, 'merge_corrected_rmshadow_scan' + str(0)) del fig Zp.append(np.flipud(merge[:shape_port[0], :])) Zs.append(merge[shape_port[0]:, :]) del merge, bw2 Zp = np.squeeze(Zp) Zs = np.squeeze(Zs) # create memory mapped file for Zp #fp = np.memmap(sonpath+base+'_data_port_lar.dat', dtype='float32', mode='w+', shape=np.shape(Zp)) #with open(sonpath+base+'_data_port_lar.dat', 'w+') as f: with open( os.path.normpath( os.path.join(sonpath, base + '_data_port_lar.dat')), 'w+') as ff: fp = np.memmap(ff, dtype='float32', mode='w+', shape=np.shape(Zp)) fp[:] = Zp[:] del fp del Zp #shutil.move(sonpath+base+'_data_port_lar.dat', sonpath+base+'_data_port_la.dat') #shutil.move(os.path.normpath(os.path.join(sonpath,base+'_data_port_lar.dat')), os.path.normpath(os.path.join(sonpath,base+'_data_port_la.dat'))) # create memory mapped file for Zs #fp = np.memmap(sonpath+base+'_data_star_lar.dat', dtype='float32', mode='w+', shape=np.shape(Zs)) #with open(sonpath+base+'_data_star_lar.dat', 'w+') as f: with open( os.path.normpath( os.path.join(sonpath, base + '_data_star_lar.dat')), 'w+') as ff: fp = np.memmap(ff, dtype='float32', mode='w+', shape=np.shape(Zs)) fp[:] = Zs[:] del fp del Zs #shutil.move(sonpath+base+'_data_star_lar.dat', sonpath+base+'_data_star_la.dat') #shutil.move(os.path.normpath(os.path.join(sonpath,base+'_data_star_lar.dat')), os.path.normpath(os.path.join(sonpath,base+'_data_star_la.dat'))) if os.name == 'posix': # true if linux/mac elapsed = (time.time() - start) else: # windows elapsed = (time.clock() - start) print("Processing took " + str(elapsed) + "seconds to analyse") print("Done!") print("===================================================")
class ReversiView: ''' Creates window with the reversi board and controls the game using gui. ''' def __init__(self, boardSize=8, w=850, h=410): ''' :param w: width of the window :param h: height of the window ''' self.root = Tk() self.boardSize = boardSize self.stone_board = [-1] * self.boardSize for row in range(self.boardSize): self.stone_board[row] = [-1] * self.boardSize self.w = w self.h = h self.offx = 5 self.offy = 5 self.gridw = 410 self.gridh = 410 self.gridspacing = 50 self.ovalDiamPart = 0.8 self.colors = ["blue", "red"] self.root.title("Reversi") self.interactive_player_ids = [] self.interactivePlayers = [] self.interractivePlayerName = 'Interactive' self.possiblePlayers = { self.interractivePlayerName: -1, } self.wrong_move = False ws = self.root.winfo_screenwidth() hs = self.root.winfo_screenheight() x = (ws / 2) - (self.w / 2) y = (hs / 2) - (self.h / 2) self.root.geometry('%dx%d+%d+%d' % (self.w, self.h, x, y)) self.draw_game_grid() self.draw_game_info_grid() self.game_state = GameState.STOPPED def set_game(self, game): ''' Sets the game to the GUI. ''' self.game = game def set_board(self, board): ''' Sets the game board to the GUI. ''' self.board = board def draw_stone(self, x, y, color): ''' Draw stone on position [x,y] in gui :param x: x coordinate of the stone :param y: y coordinate of the stone :param color: 0 for blue, 1 fro red ''' x_coord = (self.gridspacing * x) + (1.0 - self.ovalDiamPart) * self.gridspacing y_coord = (self.gridspacing * y) + (1.0 - self.ovalDiamPart) * self.gridspacing diameter = self.ovalDiamPart * self.gridspacing self.clear_stone(x, y) self.stone_board[x][y] = self.grid.create_oval(x_coord, y_coord, x_coord + diameter, y_coord + diameter, fill=self.colors[color]) def clear_stone(self, x, y): ''' Delete stone on position [x,y] from the gui :param x: x coordinate of the stone :param y: y coordinate of the stone ''' if self.stone_board[x][y] != -1: self.grid.delete(self.stone_board[x][y]) self.stone_board[x][y] = -1 def draw_game_info_grid(self): ''' Draw control and inform part of game to right side of the window. ''' self.info = Canvas(self.root, height=self.h - self.gridh, width=self.w - self.gridw) self.info.pack(side="left") label_stones = Label(self.info, text="Current stones:", font=("Helvetica", 10)) label_stones.grid(row=1, column=0) label_max_time = Label(self.info, text="Max time:", font=("Helvetica", 10)) label_max_time.grid(row=2, column=0) label_scale = Label(self.info, text='Game speed [ms]:', font=("Helvetica", 10), foreground='black') label_scale.grid(row=5, column=0) helv36 = font.Font(family="helvetica", size=16, weight='bold') self.scale_var = IntVar() scale = Scale(self.info, variable=self.scale_var, command=self.sleep_time_change_handler, from_=0, to=1000, resolution=10, width="15", orient=HORIZONTAL, length="225") scale.set(200) scale.grid(row=5, column=1, columnspan=3) self.button = Button(self.info, text="Play", width="20", height="2", command=self.play_button_click_handler) self.button['font'] = helv36 self.button.grid(row=6, column=0, columnspan=4) # labels for num stones, max time of move, etc self.label_player_stones = [-1, -1] self.label_player_max_time = [-1, -1] self.labels_inform = [-1, -1] self.labels_player_name = [-1, -1] self.option_menus = [-1, -1] self.option_menus_vars = [-1, -1] for i in range(2): self.label_player_stones[i] = Label(self.info, text='2', font=("Helvetica", 10), foreground=self.colors[i]) self.label_player_stones[i].grid(row=1, column=2 * (i + 1) - 1, columnspan=2) self.label_player_max_time[i] = Label(self.info, text="%.2f [ms]" % 0.0, font=("Helvetica", 10), foreground=self.colors[i]) self.label_player_max_time[i].grid(row=2, column=2 * (i + 1) - 1, columnspan=2) self.labels_inform[i] = Label(self.info, text='', font=("Helvetica", 10), foreground='black') self.labels_inform[i].grid(row=i + 3, column=0, columnspan=4) self.labels_player_name[i] = Label(self.info, text="Player%d:" % (i), font=("Helvetica", 12), foreground=self.colors[i]) self.labels_player_name[i].grid(row=0, column=2 * i) self.option_menus_vars[i] = StringVar(self.root) self.option_menus_vars[i].set(self.interractivePlayerName) self.option_menus[i] = OptionMenu(self.info, self.option_menus_vars[i], *self.possiblePlayers) self.option_menus[i].grid(row=0, column=2 * i + 1) def draw_game_grid(self): ''' Draw empty 8x8 grid on the left side of the window. ''' self.grid = Canvas(self.root, bg="white", height=self.gridh, width=self.gridw) self.grid.bind("<Button 1>", self.place_stone_click_handler) gridsize = self.boardSize offy = self.offy offx = self.offx w = self.gridw h = self.gridh spacing = self.gridspacing # line around self.grid.create_line(offx, offy, offx, h - offy, w - offx, h - offy, w - offx, offy, offx, offx) for x in range(0, gridsize): for y in range(0, gridsize): arrayText = '[' + str(y) + ',' + str(x) + ']' self.grid.create_text(offx + (spacing * x) + spacing / 2, offy + (spacing * y) + spacing / 2, text=arrayText) # line rows for rowy in range(offy + spacing, h - offy, spacing): self.grid.create_line(offx, rowy, w - offx, rowy) # line columns for colx in range(offx + spacing, w - offx, spacing): self.grid.create_line(colx, offy, colx, h - offy) self.grid.pack(side="left") def sleep_time_change_handler(self, event): ''' Called after scale value change, updates the wait time between moves. :param event: slider change event ''' self.game.sleep_time_ms = self.scale_var.get() def play_button_click_handler(self): ''' Button listener for Play/Pause/RePlay etc. On button click prints slider value and start game. ''' # set the players from dropdown menu if game is stopped if self.game_state == GameState.STOPPED: print("game_state " + str(self.game_state)) self.interactive_player_ids = [] for i in range(2): print(self.option_menus_vars[i].get()) if self.option_menus_vars[i].get( ) == self.interractivePlayerName: self.interactive_player_ids.append(i) if i == 0: self.game.player1.name = self.interractivePlayerName else: self.game.player2.name = self.interractivePlayerName else: if i == 0: player_class = self.possiblePlayers[ self.option_menus_vars[i].get()] self.game.player1 = player_class( self.game.player1_color, self.game.player2_color) else: player_class = self.possiblePlayers[ self.option_menus_vars[i].get()] self.game.player2 = player_class( self.game.player2_color, self.game.player1_color) self.game.clear_game() self.game.current_player = self.game.player1 self.game.current_player_color = self.game.player1_color print('player1 ' + str(self.game.player1_color)) print('player2 ' + str(self.game.player2_color)) #play game or start game if interactive if len(self.interactive_player_ids) != 0: if self.game_state == GameState.STOPPED: if not self.board.can_play(self.game.current_player, self.game.current_player_color): self.game.clear_game() self.button['text'] = 'Play' else: self.game_state = GameState.RUNNING self.button['text'] = 'RePlay' print('can play ', self.interactive_player_ids) inform_str = 'Player%d plays' % ( self.interactive_player_ids[0]) self.inform(inform_str, 'green') if len(self.interactive_player_ids ) == 1 and self.interactive_player_ids[0] == 1: self.game.play_game(self.interactive_player_ids[0]) else: self.game_state = GameState.STOPPED self.button['text'] = 'Play' self.game.clear_game() # self.game.play_game(self.interactivePlayerId) else: if self.game_state == GameState.STOPPED or self.game_state == GameState.PAUSED: print('start') print('player1 ' + str(self.game.player1_color)) print('player2 ' + str(self.game.player2_color)) self.button['text'] = 'Pause' self.game.sleepTimeMS = self.scale_var.get() if self.game_state == GameState.STOPPED: self.game.clear_game() self.game.pause(False) self.game_state = GameState.RUNNING print('player1 ' + str(self.game.player1_color)) print('player2 ' + str(self.game.player2_color)) self.game.play_game() print('game exited') if self.board.can_play(self.game.current_player, self.game.current_player_color ) and not self.wrong_move: print('set pause state') self.button['text'] = 'Continue' self.game_state = GameState.PAUSED else: print('set stopped state') self.button['text'] = 'RePlay' self.game_state = GameState.STOPPED # self.game.clear_game() elif self.game_state == GameState.RUNNING: print('pause') self.game_state = GameState.PAUSED self.game.pause(True) def add_players(self, players): ''' Adds possible players to the gui. :param players: array of players to add. ''' for player_name in players.keys(): self.possiblePlayers[player_name] = players[player_name] for i in range(2): self.info.delete(self.option_menus[i]) self.option_menus[i] = OptionMenu(self.info, self.option_menus_vars[i], *self.possiblePlayers) self.option_menus[i].grid(row=0, column=2 * i + 1) self.root.update() def print_score(self): ''' Set number of stones for both players. ''' stones = self.board.get_score() self.print_player_num_stones(0, stones[0]) self.print_player_num_stones(1, stones[1]) def print_num_stones(self, stones): ''' Set number of stones for both players. :param stones: array of player number of stones ''' self.print_player_num_stones(0, stones[0]) self.print_player_num_stones(1, stones[1]) def print_player_num_stones(self, playerID, stones): ''' Set player number of stones. :param playerID: 0 for player 1, 1 for player 2 :param maxTime: maximal time of player ''' self.label_player_stones[playerID]['text'] = str(stones) self.root.update() def print_move_max_times(self, maxTimesMS): ''' Print maximal times for both players to the gui. :param max_times_ms: array of max time needed for move. ''' self.print_player_move_max_time(0, maxTimesMS[0]) self.print_player_move_max_time(1, maxTimesMS[1]) def print_player_move_max_time(self, playerID, maxTime): ''' Set player maximal time. :param playerID: 0 for player 1, 1 for player 2 :param maxTime: maximal time of player ''' self.label_player_max_time[playerID]['text'] = '%.2f [ms]' % maxTime self.root.update() def print_board_state(self): ''' Show the state of the board in gui. ''' # self.board.print_board() for y in range(self.board.board_size): for x in range(self.board.board_size): if self.board.board[y][x] == -1: self.clear_stone(x, y) else: self.draw_stone(x, y, self.board.board[y][x]) self.root.update() def place_stone_click_handler(self, event): ''' For interactive player places stone to mouse click position. :param event: mouse click event ''' if self.game_state != GameState.STOPPED and len( self.interactive_player_ids ) >= 1 and self.game.current_player_color in self.interactive_player_ids: pos_move = [ int((event.y - self.offy) / self.gridspacing), int((event.x - self.offx) / self.gridspacing) ] #print(type(pos_move)) #print(type(pos_move[0])) #print(type(pos_move[1])) if self.board.is_correct_move(pos_move, self.game.current_player, self.game.current_player_color): # print('correct move',pos_move) # self.inform('correct move to %d %d'%(pos_move[0],pos_move[1]), 'green') # self.board.pla next_player_id = self.game.play_move(pos_move) self.print_board_state() self.print_score() self.print_move_max_times(self.game.max_times_ms) inform_str = 'Player%d plays' % ( self.game.current_player_color) self.inform(inform_str, 'green') if len(self.interactive_player_ids) == 1: self.game.play_game(self.interactive_player_ids[0]) if next_player_id == -1: self.game_state = GameState.STOPPED self.button['text'] = 'RePlay' self.game.print_final_info() else: print('incorrect move', pos_move) self.inform( 'incorrect move to %d %d' % (pos_move[0], pos_move[1]), 'red') def inform(self, text_strs, color_str): ''' Show inform text in gui. :param text_strs: string or string array of size 2 that is shown in gui :param color_str: color of shown text_strs ''' inform_str_all = ['', ''] if not isinstance(text_strs, list): inform_str_all[0] = text_strs else: inform_str_all = text_strs # print(inform_str_all) for i in range(2): self.labels_inform[i]['text'] = inform_str_all[i] self.labels_inform[i]['foreground'] = color_str self.root.update()
def main(): root = Tk() ex = Walking(root) root.geometry("200x250+300+300") root.mainloop()