コード例 #1
0
ファイル: file_utils.py プロジェクト: wusui/toybox
def save(squares):
    """
    Handle the save key on the main window.
    """
    def save_button_hit():
        """
        Save key (on local window) was hit.  Save the file name entered.
        """
        text_in = save_entry.get().strip()
        if len(text_in) == 0:
            showwarning('Error', 'File name specified is empty.')
            return
        outfile = os.path.join(savedir, text_in)
        with open(outfile, 'w') as fyle:
            for sqr_info in save_squares:
                fyle.write('%d:%d:%s\n' % tuple(save_squares[sqr_info]))
        top.destroy()
    top = Toplevel()
    top.geometry('180x80+800+200')
    top.title('Save a layout')
    save_squares = squares
    savedir = getdir()
    label1 = Label(top, text='File name')
    save_entry = Entry(top)
    label1.grid(row=0)
    save_entry.grid(row=0, column=1, columnspan=2)
    save_entry.focus_set()
    save_button = Button(top, text='SAVE', pady=3,
            command=save_button_hit)
    sspace = Label(top)
    sspace.grid(row=1)
    save_button.grid(row=2, column=1)
    top.mainloop()
コード例 #2
0
class Reminder_Window():



    def start_window(self):
        self.reminder_window = Toplevel()
        self.reminder_window.grab_set()
        self.reminder_window.title('Reminder')
        self.reminder_window.geometry('400x200')
        big_font = tkFont.Font(size=10)
        self.reminder_text_1 = Tkinter.Label(self.reminder_window,
        text='Remind me', font=big_font)
        self.reminder_text_2 = Tkinter.Label(self.reminder_window, \
        text='day(s) before.', font=big_font)
        self.reminder_entry = Tkinter.Entry(self.reminder_window, width=3)
        self.ok_reminder_button = Tkinter.Button(self.reminder_window,
        text='OK', command=self.on_ok_button_press)
        self.back_reminder_button = Tkinter.Button(self.reminder_window, \
        text='Back', command=self.on_back_button_press)


        self.reminder_text_1.place(x=x_reminder_text_1_location, \
        y=y_reminder_texts_location)
        self.reminder_text_2.place(x=x_reminder_text_2_location, \
        y=y_reminder_texts_location)
        self.reminder_entry.place(x=x_reminder_entry_location, \
        y=y_reminder_entry_location)
        self.ok_reminder_button.place(x=x_ok_reminder_button_location, \
        y=y_ok_back_reminder_button_locations)
        self.back_reminder_button.place(x=x_back_reminder_button_location, \
        y=y_ok_back_reminder_button_locations)
        self.reminder_window.mainloop()

    def on_ok_button_press(self):
        entry_reminder_value = self.reminder_entry.get()
        try:
            int_entry_reminder_value = int(entry_reminder_value)
            #print 0 > int_entry_reminder_value, int_entry_reminder_value < 50
            if 0 > int_entry_reminder_value or int_entry_reminder_value > 50:
                print 'hi'
                tkMessageBox.showinfo("Error", \
                'Invalid Entry.  Please enter a number from 0-50')
                self.reminder_window.grab_set()
                self.reminder_window.lift()

            else:
                self.num_of_days_before_to_remind_int = int_entry_reminder_value
                self.reminder_window.destroy()

        except ValueError:
            tkMessageBox.showinfo("Error", \
            'Invalid Entry.  Please enter a number from 0-50')
            self.reminder_window.grab_set()
            self.reminder_window.lift()


    def on_back_button_press(self):
        self.num_of_days_before_to_remind_int = 0
        self.reminder_window.destroy()
コード例 #3
0
ファイル: gui.py プロジェクト: sangyf/ktailFSM
def callHelpdWindow():
    textvar='K-TAIL State Transition Software\nVersion:1.0\nAuthor:Lenz L Nerit\University:Victoria University of Wellington\n'
    helpWind=Toplevel()
    helpWind.resizable(width=FALSE, height=FALSE)
    frame=ttk.Frame(helpWind)
    frm=LabelFrame(frame,text='test')
    frm.pack()
    lbl=Label(frm,text="sampleStatus",width=10,bg='blue')
    lbl.pack(fill=BOTH)
    helpWind.mainloop()
コード例 #4
0
ファイル: tk_bankeditor.py プロジェクト: plewto/Llia
    def _edit_remarks(self):
        bnk = self.synth.bank()
        name = bnk.name
        filename = bnk.filename
        remarks = bnk.remarks
        dialog = Toplevel(self)
        frame = factory.frame(dialog, True)
        frame.pack(expand=True, fill="both")
        lab_title = factory.center_label(frame, "Bank Info")
        lab_name = factory.label(frame, "Bank name :  '%s'" % name)
        lab_filename = factory.label(frame, "Filename :  '%s'" % filename)
        frame_text = factory.label_frame(frame, "Remarks")
        lab_title.grid(row=0, column=0, columnspan=3,pady=12)
        lab_name.grid(row=1, column=0, sticky="w", padx=4)
        lab_filename.grid(row=2, column=0, sticky="w", padx=4)
        frame_text.grid(row=3, column=0, columnspan=3, padx=4, pady=8)
        text_widget = factory.text_widget(frame_text, "Bank remarks")
        text_widget.insert('end', remarks)
        text_widget.config(width=80, height=20)
        vsb = factory.scrollbar(frame_text, orientation="vertical")
        hsb = factory.scrollbar(frame_text, orientation="horizontal")
        text_widget.grid(row=0, column=0, rowspan=8, columnspan=8, ipadx=4, ipady=4)
        vsb.grid(row=0, column=8, rowspan=8, columnspan=1, sticky="ns")
        hsb.grid(row=8, column=0, rowspan=1, columnspan=8, sticky="ew")
        vsb.config(command=text_widget.yview)
        hsb.config(command=text_widget.xview)
        text_widget.config(yscrollcommand=vsb.set)
        text_widget.config(xscrollcommand=hsb.set)

        frame_toolbar = factory.frame(frame, True)
        frame_toolbar.grid(row=4, column=0, padx=4, pady=8)

        def clear():
            text_widget.delete(1.0, 'end')

        def accept():
            rem = text_widget.get(1.0, 'end')
            bnk.remarks = rem
            self.status("Bank remarks updated")
            dialog.destroy()

        def cancel():
            self.status("Change bank remarks canceld")
            dialog.destroy()
            
        b_clear = factory.clear_button(frame_toolbar, command=clear, ttip="Clear remarks")
        b_accept = factory.accept_button(frame_toolbar, command=accept)
        b_cancel = factory.cancel_button(frame_toolbar, command=cancel)
        b_clear.grid(row=0, column=0, padx=4, pady=8)
        b_accept.grid(row=0, column=1)
        b_cancel.grid(row=0, column=2)
        dialog.grab_set()
        dialog.mainloop()
コード例 #5
0
    def _edit_remarks(self):
        bnk = self.synth.bank()
        name = bnk.name
        filename = bnk.filename
        remarks = bnk.remarks
        dialog = Toplevel(self)
        frame = factory.frame(dialog, True)
        frame.pack(expand=True, fill="both")
        lab_title = factory.center_label(frame, "Bank Info")
        lab_name = factory.label(frame, "Bank name :  '%s'" % name)
        lab_filename = factory.label(frame, "Filename :  '%s'" % filename)
        frame_text = factory.label_frame(frame, "Remarks")
        lab_title.grid(row=0, column=0, columnspan=3,pady=12)
        lab_name.grid(row=1, column=0, sticky="w", padx=4)
        lab_filename.grid(row=2, column=0, sticky="w", padx=4)
        frame_text.grid(row=3, column=0, columnspan=3, padx=4, pady=8)
        text_widget = factory.text_widget(frame_text, "Bank remarks")
        text_widget.insert('end', remarks)
        text_widget.config(width=80, height=20)
        vsb = factory.scrollbar(frame_text, orientation="vertical")
        hsb = factory.scrollbar(frame_text, orientation="horizontal")
        text_widget.grid(row=0, column=0, rowspan=8, columnspan=8, ipadx=4, ipady=4)
        vsb.grid(row=0, column=8, rowspan=8, columnspan=1, sticky="ns")
        hsb.grid(row=8, column=0, rowspan=1, columnspan=8, sticky="ew")
        vsb.config(command=text_widget.yview)
        hsb.config(command=text_widget.xview)
        text_widget.config(yscrollcommand=vsb.set)
        text_widget.config(xscrollcommand=hsb.set)

        frame_toolbar = factory.frame(frame, True)
        frame_toolbar.grid(row=4, column=0, padx=4, pady=8)

        def clear():
            text_widget.delete(1.0, 'end')

        def accept():
            rem = text_widget.get(1.0, 'end')
            bnk.remarks = rem
            self.status("Bank remarks updated")
            dialog.destroy()

        def cancel():
            self.status("Change bank remarks canceld")
            dialog.destroy()
            
        b_clear = factory.clear_button(frame_toolbar, command=clear, ttip="Clear remarks")
        b_accept = factory.accept_button(frame_toolbar, command=accept)
        b_cancel = factory.cancel_button(frame_toolbar, command=cancel)
        b_clear.grid(row=0, column=0, padx=4, pady=8)
        b_accept.grid(row=0, column=1)
        b_cancel.grid(row=0, column=2)
        dialog.grab_set()
        dialog.mainloop()
コード例 #6
0
ファイル: ex7.py プロジェクト: omelhoro/python-coreapps
def enter_file(cur_file,label):
    print(cur_file.get())
    
    def read_file():
        try:
            with open(cur_file.get()) as f:
                label.config(text=f.read())
                fl_enter.destroy()
        except:
            label.config(text="No such file")

    fl_enter=Toplevel(top)
    qu_butts=[("Read",read_file),("Quit",lambda : fl_enter.destroy())]
    pack([Button(fl_enter,text=txt,command=f) for txt,f in qu_butts])
    pack([Entry(fl_enter,textvariable=cur_file)])
    fl_enter.mainloop()
コード例 #7
0
ファイル: tk_bankeditor.py プロジェクト: plewto/Llia
    def _fill_performance(self):
        bnk = self.synth.bank()
        dialog = Toplevel(self)
        frame = factory.frame(dialog, True)
        frame.pack(expand=True, fill="both")
        lab_title = factory.label(frame, "Fill Performance", modal=True)
        lab_start = factory.label(frame, "Starting slot", modal=True)
        lab_end = factory.label(frame, "Ending slot", modal=True)
        var_start = StringVar()
        var_end = StringVar()
        spin_start = factory.int_spinbox(frame, var_start, 0, len(bnk))
        spin_end = factory.int_spinbox(frame, var_end, 0, len(bnk))
        var_start.set(bnk.current_slot)
        var_end.set(bnk.current_slot+1)
        lab_title.grid(row=0, column=0, columnspan=3, padx=4, pady=8)
        lab_start.grid(row=1, column=0, sticky="w", padx=4)
        spin_start.grid(row=1, column=1, columnspan=2, padx=4)
        lab_end.grid(row=2, column=0, sticky="w", padx=4)
        spin_end.grid(row=2, column=1, columnspan=2, padx=4)

        def accept():
            try:
                a,b = int(var_start.get()), int(var_end.get())
                bnk.fill_performance(a,b)
                msg = "Performance filled slots [%3d, %3d]" % (a,b)
                self.status(msg)
                dialog.destroy()
            except ValueError:
                msg = "Invalid slot number"
                self.warning(msg)
            except KeyError as err:
                self.warning(err.message)
                

        def cancel():
            msg = "Performance fill canceld"
            self.status(msg)
            dialog.destroy()
            
        b_accept = factory.accept_button(frame, command=accept)
        b_cancel = factory.cancel_button(frame, command=cancel)
        b_accept.grid(row=3, column=1, padx=4, pady=8,sticky="ew")
        b_cancel.grid(row=3, column=2, padx=4, pady=8,sticky="ew")
        dialog.grab_set()
        dialog.mainloop()
コード例 #8
0
    def _fill_performance(self):
        bnk = self.synth.bank()
        dialog = Toplevel(self)
        frame = factory.frame(dialog, True)
        frame.pack(expand=True, fill="both")
        lab_title = factory.label(frame, "Fill Performance", modal=True)
        lab_start = factory.label(frame, "Starting slot", modal=True)
        lab_end = factory.label(frame, "Ending slot", modal=True)
        var_start = StringVar()
        var_end = StringVar()
        spin_start = factory.int_spinbox(frame, var_start, 0, len(bnk))
        spin_end = factory.int_spinbox(frame, var_end, 0, len(bnk))
        var_start.set(bnk.current_slot)
        var_end.set(bnk.current_slot+1)
        lab_title.grid(row=0, column=0, columnspan=3, padx=4, pady=8)
        lab_start.grid(row=1, column=0, sticky="w", padx=4)
        spin_start.grid(row=1, column=1, columnspan=2, padx=4)
        lab_end.grid(row=2, column=0, sticky="w", padx=4)
        spin_end.grid(row=2, column=1, columnspan=2, padx=4)

        def accept():
            try:
                a,b = int(var_start.get()), int(var_end.get())
                bnk.fill_performance(a,b)
                msg = "Performance filled slots [%3d, %3d]" % (a,b)
                self.status(msg)
                dialog.destroy()
            except ValueError:
                msg = "Invalid slot number"
                self.warning(msg)
            except KeyError as err:
                self.warning(err.message)
                

        def cancel():
            msg = "Performance fill canceld"
            self.status(msg)
            dialog.destroy()
            
        b_accept = factory.accept_button(frame, command=accept)
        b_cancel = factory.cancel_button(frame, command=cancel)
        b_accept.grid(row=3, column=1, padx=4, pady=8,sticky="ew")
        b_cancel.grid(row=3, column=2, padx=4, pady=8,sticky="ew")
        dialog.grab_set()
        dialog.mainloop()
コード例 #9
0
ファイル: file_utils.py プロジェクト: wusui/toybox
def load():
    """
    Handle the load key on the main window.
    """
    def save_select():
        """
        Select key hit.  Set fname and exit if a field is high-lighted.
        """
        sel = mylist.curselection()
        if not sel:
            return
        fname.append(olist[int(sel[0])])
        top.quit()
    olist = sorted(os.listdir(getdir()))
    if len(olist) == 0:
        showwarning('Error', 'No files to load')
        return
    top = Toplevel()
    top.geometry('200x180+800+200')
    fname = []
    top.title('Sudoku Loader')
    tpart = Frame(top)
    tpart.pack(side=Tkinter.TOP)
    bpart = Frame(top)
    bpart.pack(side=Tkinter.BOTTOM)
    scrollbar = Scrollbar(tpart)
    scrollbar.pack(side=Tkinter.RIGHT, fill=Tkinter.Y)
    mylist = Listbox(tpart, yscrollcommand=scrollbar.set)
    for line in olist:
        mylist.insert(Tkinter.END, line)
    mylist.pack(side=Tkinter.LEFT, fill=Tkinter.BOTH)
    scrollbar.config(command=mylist.yview)
    picker = Button(bpart, text='SELECT', command=save_select)
    picker.pack(pady=5)
    top.mainloop()
    if fname:
        retvec = []
        fyle = '%s%s%s' % (getdir(), os.path.sep, fname[0])
        top.destroy()
        with open(fyle, 'r') as infile:
            inline = infile.readline()
            while inline:
                retvec.append(inline.split(':'))
                inline = infile.readline()
            return retvec
コード例 #10
0
ファイル: __main__.py プロジェクト: luigi230899/py-pdp8-tk
def run():
    """
    Esegue l'emulatore del pdp8
    """
    CD = pdp8()
    principale = Tk()
    principale.title("Pdp8 Emulator : Assembly Editor")
    emulatore = Toplevel()
    emulatore.title("Pdp8 Emulator")
    emulatore.geometry("1015x589")

    edit = Editor(principale, CD)

    scrollbar1 = AutoScrollbar(emulatore)
    scrollbar1.grid(row=0, column=1, sticky=N + S)
    scrollbar2 = AutoScrollbar(emulatore, orient=HORIZONTAL)
    scrollbar2.grid(row=1, column=0, sticky=E + W)

    finestra = Canvas(emulatore,
                      yscrollcommand=scrollbar1.set,
                      xscrollcommand=scrollbar2.set)
    finestra.grid(row=0, column=0, sticky=N + S + E + W)

    scrollbar1.config(command=finestra.yview)
    scrollbar2.config(command=finestra.xview)

    emulatore.grid_rowconfigure(0, weight=1)
    emulatore.grid_columnconfigure(0, weight=1)

    emul = Emulatore(finestra, edit, CD, emulatore)

    finestra.create_window(0, 0, anchor=NW, window=emul.master)

    emul.master.update_idletasks()

    finestra.config(scrollregion=finestra.bbox("all"))

    principale.protocol("WM_DELETE_WINDOW", edit.exit)
    emulatore.protocol("WM_DELETE_WINDOW", emul.exit)

    principale.mainloop()
    emulatore.mainloop()
コード例 #11
0
ファイル: __main__.py プロジェクト: Mappo23/py-pdp8-tk
def run():
    """
    Esegue l'emulatore del pdp8
    """
    CD = pdp8()
    principale = Tk()
    principale.title("Pdp8 Emulator : Assembly Editor")
    emulatore = Toplevel()
    emulatore.title("Pdp8 Emulator")
    emulatore.geometry("1015x589")

    edit = Editor(principale, CD)

    scrollbar1 = AutoScrollbar(emulatore)
    scrollbar1.grid(row=0, column=1, sticky=N + S)
    scrollbar2 = AutoScrollbar(emulatore, orient=HORIZONTAL)
    scrollbar2.grid(row=1, column=0, sticky=E + W)

    finestra = Canvas(emulatore,
                      yscrollcommand=scrollbar1.set,
                      xscrollcommand=scrollbar2.set)
    finestra.grid(row=0, column=0, sticky=N + S + E + W)

    scrollbar1.config(command=finestra.yview)
    scrollbar2.config(command=finestra.xview)

    emulatore.grid_rowconfigure(0, weight=1)
    emulatore.grid_columnconfigure(0, weight=1)

    emul = Emulatore(finestra, edit, CD, emulatore)

    finestra.create_window(0, 0, anchor=NW, window=emul.master)

    emul.master.update_idletasks()

    finestra.config(scrollregion=finestra.bbox("all"))

    principale.protocol("WM_DELETE_WINDOW", edit.exit)
    emulatore.protocol("WM_DELETE_WINDOW", emul.exit)

    principale.mainloop()
    emulatore.mainloop()
コード例 #12
0
ファイル: Examples.py プロジェクト: HunterAllman/kod
def cluster_tree():
    """Displays cluster trees for 2 elimination orders for Asia BN"""
    from Tkinter import Toplevel, Label
    from Utils import scrolled_frame, pretty_str_set
    top=scrolled_frame(Toplevel(),yscroll=500, height=400)
    bottom=Toplevel()
    for cpt in asia:
        cpt *= 1
    asia.gui_display(top)
    order1 = ('VisitAsia', 'Tuberculosis', 'XRay',  'Dyspnea', 'Bronchitis', 
              'Smoking', 'TbOrCa')
    order2 = ('TbOrCa', 'VisitAsia', 'Tuberculosis', 'XRay', 'Bronchitis', 
              'Smoking', 'Dyspnea')
    for order in (order1, order2):
        ac = asia.copy(True)
        cf = ac.variable_elimination_trace(order)
        cf.gui_display(bottom,pp_vertex=pretty_str_set,width=600,height=300)
        Label(bottom,text=order).pack()
    top.mainloop()
    bottom.mainloop()
コード例 #13
0
def subVentana(stringExpresionBooleana, ventanaPrincipal):
    ventanaHija = Toplevel(ventanaPrincipal)
    ventanaHija.geometry("300x250")
    ventanaHija.title("Mapa de Karnaugh")

    matrizExpresionBooleana, variables = generarMatrizExpresionBooleana(
        stringExpresionBooleana.get())
    mapaKarnaugh = llenarMapaKarnaugh(matrizExpresionBooleana)

    # print mapa
    if len(variables) == 4:
        mapa1 = str(mapaKarnaugh[0])
        mapa2 = str(mapaKarnaugh[1])
        mapa3 = str(mapaKarnaugh[2])
        mapa4 = str(mapaKarnaugh[3])
        Label(ventanaHija, text="Mapa de Karnaugh").grid(row=2, column=2)
        Label(ventanaHija, text=mapa1).grid(row=4, column=2)
        Label(ventanaHija, text=mapa2).grid(row=5, column=2)
        Label(ventanaHija, text=mapa3).grid(row=6, column=2)
        Label(ventanaHija, text=mapa4).grid(row=7, column=2)
    else:
        mapa1 = str(mapaKarnaugh[0])
        mapa2 = str(mapaKarnaugh[1])
        Label(ventanaHija, text="Mapa de Karnaugh").grid(row=2, column=2)
        Label(ventanaHija, text=mapa1).grid(row=4, column=2)
        Label(ventanaHija, text=mapa2).grid(row=5, column=2)

    #print expresion
    gruposDe1 = leerMapaKarnaugh(mapaKarnaugh)
    matrizCambioDeEstados = identificarEstados(gruposDe1, len(variables))
    expresionSimplificada = generarExpresionSimplificada(
        matrizCambioDeEstados, variables)
    Label(ventanaHija,
          text="expresion: " + expresionSimplificada).grid(row=8, column=2)

    ventanaHija.mainloop()
コード例 #14
0
    def help_about(self):

        """Shows an 'about' modal dialog.

        Callback method called by tk.

        """

        about_win = Toplevel(self.root)

        # Set up dialog

        lbl = Label(about_win, text="Video Poker")
        lbl.grid(row=0, column=0, padx=10, pady=(10, 0), sticky=W + N)
        lbl = Label(about_win, text="by Charles Raymond Smith")
        lbl.grid(row=1, column=0, padx=10, pady=(0, 7), sticky=W + N)
        lbl = Label(about_win, text="Adapted from video poker by Paul Griffiths")
        lbl.grid(row=2, column=0, padx=10, pady=(0, 7), sticky=W + N)
        lbl = Label(about_win, text="Written in Python, with tkinter.")
        lbl.grid(row=3, column=0, padx=10, pady=7, sticky=W + N)
        lbl = Label(about_win, text="Copyright 2017 Charles Raymond Smith")
        lbl.grid(row=4, column=0, padx=10, pady=(7, 0), sticky=W + N)
        lbl = Label(about_win, text="Email: [email protected]")
        lbl.grid(row=5, column=0, padx=10, pady=(0, 21), sticky=W + N)
        lbl = Label(about_win, text="This program is free software: you can " +
            "redistribute it and/or modify it under the terms")
        lbl.grid(row=6, column=0, columnspan=2,
                 padx=10, pady=0, sticky=W + N)
        lbl = Label(about_win, text="of the GNU General Public License as " +
            "published by the Free Software Foundation, either")
        lbl.grid(row=7, column=0, columnspan=2,
                 padx=10, pady=(0, 0), sticky=W + N)
        lbl = Label(about_win, text="version 3 of the License, or " +
            "(at your option) any later version.")
        lbl.grid(row=8, column=0, columnspan=2,
                 padx=10, pady=(0, 21), sticky=W + N)
        lbl = Label(about_win, text="This program is distributed in " +
            "the hope that it will be useful, but WITHOUT ANY WARRANTY;")
        lbl.grid(row=9, column=0, columnspan=2,
                 padx=10, pady=0, sticky=W + N)
        lbl = Label(about_win, text="without even the implied " +
            "warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR")
        lbl.grid(row=10, column=0, columnspan=2,
                 padx=10, pady=(0, 0), sticky=W + N)
        lbl = Label(about_win, text="PURPOSE. See the " +
            "GNU General Public License for more details.")
        lbl.grid(row=11, column=0, columnspan=2,
                 padx=10, pady=(0, 21), sticky=W + N)
        lbl = Label(about_win, text="You should have received a " +
            "copy of the GNU General Public License along with this")
        lbl.grid(row=12, column=0, columnspan=2,
                 padx=10, pady=(0, 0), sticky=W + N)
        lbl = Label(about_win, text="program. If not, see " +
            "<http://www.gnu.org/licenses/>.")
        lbl.grid(row=13, column=0, columnspan=2,
                 padx=10, pady=(0, 21), sticky=W + N)
        img = PhotoImage(file="{0}27.gif".format(self.gifdir))
        lbl = Label(about_win, image=img)
        lbl.grid(row=0, column=1, rowspan=5, padx=10, pady=10, sticky=N + E)

        btn = Button(about_win, text="OK", command=about_win.quit)
        btn.grid(row=14, column=0, columnspan=2,
                 padx=0, pady=(0, 10), ipadx=30, ipady=3)

        # Show dialog

        about_win.transient(self.root)
        about_win.parent = self.root
        about_win.protocol("WM_DELETE_WINDOW", about_win.destroy)
        about_win.geometry("+{0}+{1}".format(self.root.winfo_rootx() + 50,
                                           self.root.winfo_rooty() + 50))
        about_win.title("About Video Poker")
        about_win.focus_set()
        about_win.grab_set()
        about_win.mainloop()
        about_win.destroy()
コード例 #15
0
ファイル: toplevel0.py プロジェクト: adharmad/python-examples
import sys
from Tkinter import Toplevel, Button, Label

# two independant windows but part of the same process
win1 = Toplevel()
win2 = Toplevel()

Button(win1, text='Spam', command=sys.exit).pack()
Button(win2, text='SPAM', command=sys.exit).pack()

Label(text='Popups').pack()
win1.mainloop()
コード例 #16
0
ファイル: tk_bankeditor.py プロジェクト: plewto/Llia
    def _store_program(self):
        bnk = self.synth.bank()
        program = bnk[None]
        slot = bnk.current_slot
        var_name = StringVar()
        var_start = StringVar()
        var_name.set(program.name)
        var_start.set(slot)
        dialog = Toplevel()
        frame = factory.frame(dialog, True)
        frame.pack(expand=True, fill="both")
        lab_title = factory.label(frame, "Store Program", modal=True)
        lab_name = factory.label(frame, "Name", modal=True)
        lab_start = factory.label(frame, "Slot", modal=True)
        entry_name = factory.entry(frame, var_name, "Program name")
        spin_start = factory.int_spinbox(frame, var_start, 0, len(bnk), "Startng slot")
        frame_remarks = factory.label_frame(frame, "Remarks", True)
        text_remarks = factory.text_widget(frame_remarks, "Remarks text", modal=True)
        text_remarks.insert("end", program.remarks)
        vsb = factory.scrollbar(frame_remarks, orientation="vertical")
        hsb = factory.scrollbar(frame_remarks, orientation="horizontal")
        text_remarks.config(width=40, height=10)
        text_remarks.grid(row=0, column=0, rowspan=4, columnspan=4)
        vsb.grid(row=0, column=4, rowspan=4, sticky="ns")
        hsb.grid(row=4, column=0, columnspan=4, sticky="ew")
        vsb.config(command=text_remarks.yview)
        hsb.config(command=text_remarks.xview)
        text_remarks.config(yscrollcommand=vsb.set)
        text_remarks.config(xscrollcommand=hsb.set)
        lab_title.grid(row=0, column=0, columnspan=3, pady=8, padx=4)
        lab_name.grid(row=1, column=0, padx=4)
        entry_name.grid(row=1, column=1, columnspan=2)
        frame_remarks.grid(row=2, column=0, rowspan=4, columnspan=4, padx=4, pady=4)
        lab_start.grid(row=6, column=0, padx=4, sticky="w")
        spin_start.grid(row=6, column=1, columnspan=2, pady=4)
        b_accept = factory.accept_button(frame)
        b_cancel = factory.cancel_button(frame)
        b_accept.grid(row=8, column=1, pady=8, sticky="ew")
        b_cancel.grid(row=8, column=2, pady=8, sticky="ew")
        
        def accept():
            try:
                a = int(var_start.get())
                name = var_name.get()
                remarks = text_remarks.get(1.0, "end")
                program.name = name
                program.remarks = remarks
                bnk[a] = program
                msg = "Stored program '%s' to slots [%3d]" % (name, a)
                self.status(msg)
                dialog.destroy()
                self.sync()
            except ValueError:
                msg = "Invalid slot number"
                self.warning(msg)

        def cancel():
            msg = "Store program canceld"
            self.status(msg)
            dialog.destroy()

        b_accept.config(command=accept)
        b_cancel.config(command=cancel)
        dialog.grab_set()
        dialog.mainloop()
コード例 #17
0
ファイル: gui.py プロジェクト: sangyf/ktailFSM
def transitionSelection(tracelog,*args):
    # start of child window GUI code
    root = Toplevel()
    root.title("Manual Transition selection")
    root.resizable(width=FALSE, height=FALSE)
    
    # frame
    mainFrame = ttk.Frame(root, width="364", padding="4 4 8 8")
    mainFrame.grid(column=0, row=0)
    
    labelSource=ttk.Label(mainFrame,text="Source", justify=LEFT)
    labelSource.grid(column=0, row=0, sticky="e")
        
    srcState = ttk.Combobox(mainFrame,width=10)
    srcState.delete(0, END)
    srcState['values'] = ([k for k in tracelog])
    srcState.grid(column=1, row=0, sticky="e")        
    srcState.state(['readonly'])
       
    # Destination label
    labelDestination=ttk.Label(mainFrame,text="Destination",justify=LEFT)
    labelDestination.grid(column=0, row=1, sticky="e")
       
    # destination combobox
    destState = ttk.Combobox(mainFrame,width=10)
    destState.delete(0, END)
    destState['values'] = ([get_num(k) for k in tracelog])
    destState.grid(column=1, row=1, sticky="e")
    destState.state(['readonly'])
                  
    listFrame=ttk.LabelFrame(root)
    listFrame.grid(column=0,row=2,sticky="we")
    scrollBar = Scrollbar(listFrame)
    scrollBar.pack(side=RIGHT, fill=Y)
    listBoxTop = Listbox(listFrame, selectmode=SINGLE,width=20,height=10)
    listBoxTop.pack(fill=BOTH)
    scrollBar.config(command=listBoxTop.yview)
    listBoxTop.config(yscrollcommand=scrollBar.set)
                
    def addItemsToList():
        
        if len(srcState.get())==0:
            tkMessageBox.showerror("No Source Entry","Please select a source state first")
            root.focus()
            return
        else:
            st=get_apha(srcState.get())
            set_listTop(listBoxTop,str(get_num(srcState.get())) +'-->'+ str(destState.get()) + '[label='+st+']')
            manualMappingList.append(str(get_num(srcState.get())) +'-->'+ str(destState.get()))
            transitionDict[get_num(srcState.get())]=st
            
            generateFSMGraph()
        
    def removeMapFromList():
        try:
            if len(listBoxTop.get(0, END))==0 or listBoxTop.curselection() is None:
                tkMessageBox.showerror("Empty List", "The mapping list is empty")
                return
            else:
                selection=listBoxTop.curselection()
                value = listBoxTop.get(selection[0])
                
                        
                ch=''
                for c in value:
                    if c=='[': #Strip out characters after the symbol [
                        break
                    else:
                        ch +=c
            #when we remove an entry from the listbox, we also update the manual mapping list
            manualMappingList.remove(ch)
            listBoxTop.delete(selection) #remove the selected entry from listbox
            generateFSMGraph()
            transitionDict={} #reset the transition dictionary to capture updated entries from the listBox
            
        except (IndexError,AttributeError,ValueError):
            tkMessageBox.showerror("Error", "Please select an entry if exists or try again")
        
    
    def generateFSMGraph():
        if len(listBoxTop.get(0, END))==0:
            tkMessageBox.showerror("No entry","There is no mapping entry.Please add mapping entry first")
            return
        try:
            for e in transitionDict:
                print transitionDict[e]
                stateMap1[int(e)]={}
                for m in manualMappingList:
                    st=[int(s) for s in m.split('-->') if s.isdigit()] #extract digits in a mapping entry
                    if str(e)==str(st[0]) and str(e)==str(st[1]):    
                        stateMap1[int(e)][int(st[0])]=transitionDict[e]
                    elif str(e)!=str(st[1]) and str(e)==str(st[0]):
                        stateMap1[int(e)][int(st[1])]=transitionDict[e]
            #callback functions    
            drawStateTransitionGraph()
            loadFSMImage()
            
        except (ValueError,IndexError,GraphvizError,AttributeError):
            pass
        
    def closeWindowTop():
        root.destroy()
    
    #Add a button inside the tab
    btnAdd=ttk.Button(mainFrame,text="Add",width=10,command=addItemsToList)
    btnAdd.grid(column=2,row=0)                
    btnRemove=ttk.Button(mainFrame,text="Remove",width=10,command=removeMapFromList)
    btnRemove.grid(column=2,row=1)
    
    #Add frame to hold buttons
    btnFrame=ttk.LabelFrame(root)
    btnFrame.grid(column=0,row=3,sticky="we")
    btnCancel=ttk.Button(btnFrame,text="Close",width=13,command=closeWindowTop)
    btnCancel.pack(side=RIGHT,fill=X)
    btnOk=ttk.Button(btnFrame,text="Generate FSM",width=13,command=generateFSMGraph)
    btnOk.pack(side=RIGHT, fill=X)
  
    def set_listTop(Listbox,sMap):
            try:
                index=Listbox.curselection()[0]
                #Check if there is an existing entry in the listbox
            except IndexError:
                index=END
            for i,listbox_entry in enumerate(Listbox.get(0, END)):
                if listbox_entry == sMap:
                    tkMessageBox.showinfo("Entry", "There is already an entry for this transition.")
                    return
    
            Listbox.insert(index, sMap)
                
    def drawStateTransitionGraph():
        #Here we appy the state transitions to create a finite state machine
        ktail = FiniteStateMachine('K-TAIL')
        for nx,kvx in stateMap1.items():
                for c in kvx:
                    State(nx).update({kvx[c]:State(c)})
                    print 'State Transition: ' +str(nx) + '-->'+str(c) + '[label='+kvx[c] +']'
                #Define initial state    
                if nx==0:
                        nx=State(0, initial=True)
        #Create a state machine
        print '------------------------------------------------------------------------------------'
        #Check if there is existing graph data 
        try:
            graph=get_graph(ktail)
            if graph!=None:
                graph.draw('../graph/ktail.png', prog='dot')
                print graph
            else:
                pass
        except GraphvizError:
            tkMessageBox.ERROR
            
    # padding for widgets
    for child in mainFrame.winfo_children(): child.grid_configure(padx=4, pady=4)
                                    
    root.mainloop()
コード例 #18
0
    def _store_program(self):
        bnk = self.synth.bank()
        program = bnk[None]
        slot = bnk.current_slot
        var_name = StringVar()
        var_start = StringVar()
        var_name.set(program.name)
        var_start.set(slot)
        dialog = Toplevel()
        frame = factory.frame(dialog, True)
        frame.pack(expand=True, fill="both")
        lab_title = factory.label(frame, "Store Program", modal=True)
        lab_name = factory.label(frame, "Name", modal=True)
        lab_start = factory.label(frame, "Slot", modal=True)
        entry_name = factory.entry(frame, var_name, "Program name")
        spin_start = factory.int_spinbox(frame, var_start, 0, len(bnk), "Startng slot")
        frame_remarks = factory.label_frame(frame, "Remarks", True)
        text_remarks = factory.text_widget(frame_remarks, "Remarks text", modal=True)
        text_remarks.insert("end", program.remarks)
        vsb = factory.scrollbar(frame_remarks, orientation="vertical")
        hsb = factory.scrollbar(frame_remarks, orientation="horizontal")
        text_remarks.config(width=40, height=10)
        text_remarks.grid(row=0, column=0, rowspan=4, columnspan=4)
        vsb.grid(row=0, column=4, rowspan=4, sticky="ns")
        hsb.grid(row=4, column=0, columnspan=4, sticky="ew")
        vsb.config(command=text_remarks.yview)
        hsb.config(command=text_remarks.xview)
        text_remarks.config(yscrollcommand=vsb.set)
        text_remarks.config(xscrollcommand=hsb.set)
        lab_title.grid(row=0, column=0, columnspan=3, pady=8, padx=4)
        lab_name.grid(row=1, column=0, padx=4)
        entry_name.grid(row=1, column=1, columnspan=2)
        frame_remarks.grid(row=2, column=0, rowspan=4, columnspan=4, padx=4, pady=4)
        lab_start.grid(row=6, column=0, padx=4, sticky="w")
        spin_start.grid(row=6, column=1, columnspan=2, pady=4)
        b_accept = factory.accept_button(frame)
        b_cancel = factory.cancel_button(frame)
        b_accept.grid(row=8, column=1, pady=8, sticky="ew")
        b_cancel.grid(row=8, column=2, pady=8, sticky="ew")
        
        def accept():
            try:
                a = int(var_start.get())
                name = var_name.get()
                remarks = text_remarks.get(1.0, "end")
                program.name = name
                program.remarks = remarks
                bnk[a] = program
                msg = "Stored program '%s' to slots [%3d]" % (name, a)
                self.status(msg)
                dialog.destroy()
                self.sync()
            except ValueError:
                msg = "Invalid slot number"
                self.warning(msg)

        def cancel():
            msg = "Store program canceld"
            self.status(msg)
            dialog.destroy()

        b_accept.config(command=accept)
        b_cancel.config(command=cancel)
        dialog.grab_set()
        dialog.mainloop()
コード例 #19
0
ファイル: cosview.py プロジェクト: justincely/astroraf
class App:

    def __init__(self, parent):
        # ----Variables----#
        self.show_gain = IntVar()
        self.show_illumination = IntVar()
        self.show_spectrum = IntVar()
        self.show_dark = IntVar()
        self.show_dq = IntVar()

        self.xmin = StringVar()
        self.xmax = StringVar()
        self.ymin = StringVar()
        self.ymax = StringVar()
        self.vmin = StringVar()
        self.vmax = StringVar()

        self.segment = StringVar()
        self.extract = StringVar()
        self.extract_offset = IntVar()
        self.cmap = StringVar()
        self.dq_show = StringVar()
        self.infile = StringVar()
        self.draw = StringVar()
        self.degrade_loc = StringVar()
        self.degrade_years = StringVar()
        self.degrade_width = StringVar()
        self.degrade_xshift = StringVar()
        self.degrade_array = IntVar()
        self.N_degraded = IntVar()
        self.grid_limits = IntVar()

        self.data_file = None
        self.Againmap = None
        self.Bgainmap = None
        self.Aexp = None
        self.Bexp = None
        self.Adark = None
        self.Bdark = None

        self.set_default_values()

        # ---End variables--- #

        self.myParent = parent
        self.myContainer = Frame(parent)
        self.myParent.bind('<Return>', self.update_plot)
        self.myParent.title('COS Layout Planner')

        # ------------Master draw button-----------#
        self.redraw = Button( self.myContainer,
                              text="Show Image",
                              command=self.draw_all)
        self.redraw.grid(row=1, column=0, sticky=N)

        # -----------Define Clear Plot Button--------#
        self.clear_button = Button( self.myContainer,
                                    text="Clear Plot",
                                    command=self.clear_axis)
        self.clear_button.grid(row=2, column=0)

        self.menubar = self.add_menubar( parent )

        # display the menu
        parent.config(menu=self.menubar)

        # ----Segment Button---#
        self.segment_selector_label = Label( self.myContainer,
                                             text='Segment Selector')
        self.segment_selector_label.config(fg='blue')
        self.segment_selector_label.grid(row=0, column=1, padx=3, pady=3)
        self.segment_selector = Radiobutton( self.myContainer,
                                             text="A",
                                             variable=self.segment,
                                             value='A',
                                             indicatoron=1).grid( row=1,
                                                                  column=1,
                                                                  padx=3,
                                                                  pady=3)
        self.segment_selector = Radiobutton( self.myContainer,
                                             text="B",
                                             variable=self.segment,
                                             value='B',
                                             indicatoron=1).grid( row=2,
                                                                  column=1,
                                                                  padx=3,
                                                                  pady=3)
                                             
        # -----------Define drawing boxes------------#
        self.drawing_label = Label(self.myContainer, text='Map to draw')
        self.drawing_label.config(fg='blue')
        self.drawing_label.grid(row=0, column=2, padx=3, pady=3)

        self.draw_what = OptionMenu( self.myContainer,
                                     self.draw,
                                     'Data File',
                                     'Modal Gain',
                                     'Deuterium Flats',
                                     'Summed Dark')
        self.draw_what.grid( row=1,
                             column=2,
                             sticky=W + E,
                             padx=3,
                             pady=3)

        self.toggle_degrade = Checkbutton( self.myContainer,
                                           text="Degrade Gain Map",
                                           variable=self.degrade_array)
        self.toggle_degrade.grid(row=2, column=2, sticky=W + E, padx=3, pady=3)

        self.degrade_loc_entry = Entry( self.myContainer,
                                        textvariable=self.degrade_loc)
        self.degrade_loc_entry.grid( row=3,
                                     column=2,
                                     sticky=W + E,
                                     padx=3,
                                     pady=3)
        self.degrade_loc_label = Label(self.myContainer, text='Y Loc')
        self.degrade_loc_label.config(fg='blue')
        self.degrade_loc_label.grid(row=3, column=1, sticky=E, padx=3, pady=3)

        self.degrade_years_entry = Entry(
            self.myContainer,
            textvariable=self.degrade_years)
        self.degrade_years_entry.grid(
            row=4,
            column=2,
            sticky=W + E,
            padx=3,
            pady=3)
        self.degrade_years_label = Label(self.myContainer, text='Years')
        self.degrade_years_label.config(fg='blue')
        self.degrade_years_label.grid(
            row=4,
            column=1,
            sticky=E,
            padx=3,
            pady=3)

        self.degrade_width_entry = Entry(
            self.myContainer,
            textvariable=self.degrade_width)
        self.degrade_width_entry.grid(
            row=5,
            column=2,
            sticky=W + E,
            padx=3,
            pady=3)
        self.degrade_width_label = Label(self.myContainer, text='Width')
        self.degrade_width_label.config(fg='blue')
        self.degrade_width_label.grid(
            row=5,
            column=1,
            sticky=E,
            padx=3,
            pady=3)

        self.degrade_xshift_entry = Entry(
            self.myContainer,
            textvariable=self.degrade_xshift)
        self.degrade_xshift_entry.grid(
            row=6,
            column=2,
            sticky=W + E,
            padx=3,
            pady=3)
        self.degrade_xshift_label = Label(self.myContainer, text='X shift')
        self.degrade_xshift_label.config(fg='blue')
        self.degrade_xshift_label.grid(
            row=6,
            column=1,
            sticky=E,
            padx=3,
            pady=3)

        # --------DQ flags to show-------#
        self.dq_show_label = Label(
            self.myContainer,
            text='DQ to plot (bitwise)')
        self.dq_show_label.config(fg='blue')
        self.dq_show_box = Entry(self.myContainer, textvariable=self.dq_show)

        self.dq_show_box.grid(
            row=4,
            column=3,
            sticky=W + E,
            padx=3,
            pady=3)
        self.dq_show_label.grid(
            row=0,
            column=3,
            sticky=W + E,
            padx=3,
            pady=3)
        self.dq_show_box.delete(0, END)
        self.dq_show_box.insert(0, 184)

        # ------------Master draw button-----------#
        self.draw_dq = Button(
            self.myContainer,
            text="Add DQ",
            command=self.add_dq)
        self.draw_dq.grid(row=1, column=3, sticky=N)

        # ---------------------------------------------------------------------#
        # assign two enter boxes for the low color bin and the high color bin #

        self.xmin_box_label = Label(self.myContainer, text='Xmin')
        self.xmin_box_label.config(fg='blue')
        self.xmin_box = Entry(self.myContainer, textvariable=self.xmin)

        self.xmax_box_label = Label(self.myContainer, text='Xmax')
        self.xmax_box_label.config(fg='blue')
        self.xmax_box = Entry(self.myContainer, textvariable=self.xmax)

        self.xmin_box.grid(
            row=1,
            column=6,
            sticky=W + E,
            padx=3,
            pady=3)
        self.xmax_box.grid(
            row=1,
            column=7,
            sticky=W + E,
            padx=3,
            pady=3)
        self.xmin_box_label.grid(
            row=0,
            column=6,
            sticky=W + E,
            padx=3,
            pady=3)
        self.xmax_box_label.grid(
            row=0,
            column=7,
            sticky=W + E,
            padx=3,
            pady=3)
        self.xmin_box.delete(0, END)
        self.xmax_box.delete(0, END)
        self.xmin_box.insert(0, 'ALL')
        self.xmax_box.insert(0, 'ALL')

        self.ymin_box_label = Label(self.myContainer, text='Ymin')
        self.ymin_box_label.config(fg='blue')
        self.ymin_box = Entry(self.myContainer, textvariable=self.ymin)

        self.ymax_box_label = Label(self.myContainer, text='Ymax')
        self.ymax_box_label.config(fg='blue')
        self.ymax_box = Entry(self.myContainer, textvariable=self.ymax)

        self.ymin_box.grid(
            row=3,
            column=6,
            sticky=W + E,
            padx=3,
            pady=3)
        self.ymax_box.grid(
            row=3,
            column=7,
            sticky=W + E,
            padx=3,
            pady=3)
        self.ymin_box_label.grid(
            row=2,
            column=6,
            sticky=W + E,
            padx=3,
            pady=3)
        self.ymax_box_label.grid(
            row=2,
            column=7,
            sticky=W + E,
            padx=3,
            pady=3)
        self.ymin_box.delete(0, END)
        self.ymax_box.delete(0, END)
        self.ymin_box.insert(0, 'ALL')
        self.ymax_box.insert(0, 'ALL')

        # self.ymin_box.grid_remove()
        # self.ymax_box.grid_remove()
        # self.ymin_box_label.grid_remove()
        # self.ymax_box_label.grid_remove()
        # self.xmin_box.grid_remove()
        # self.xmax_box.grid_remove()
        # self.xmin_box_label.grid_remove()
        # self.xmax_box_label.grid_remove()
        # ---show extraction region box-------#
        '''
        self.extract_label=Label(self.myContainer, text = 'SEG/OPT_ELEM/CENWAVE/APER')
        self.extract_label.config(fg = 'blue')
        self.extract_box=Entry(self.myContainer, textvariable=self.extract)

        self.extract_box.grid(row=5, column=5, sticky=W+E, padx = 3, pady = 3)
        self.extract_label.grid(row=4, column=5, sticky=W+E, padx = 3, pady = 3)
        self.extract_box.delete(0, END)
        self.extract_box.insert(0, 'None')


        #--------offset box-------#
        self.extract_offset_label=Label(self.myContainer, text = 'Offset extraction box (pixels)')
        self.extract_offset_label.config(fg = 'blue')
        self.extract_offset_box=Entry(self.myContainer, textvariable=self.extract_offset)

        self.extract_offset_box.grid(row=5, column=6, sticky=W+E, padx = 3, pady = 3)
        self.extract_offset_label.grid(row=4, column=6, sticky=W+E, padx = 3, pady = 3)
        self.extract_offset_box.delete(0, END)
        self.extract_offset_box.insert(0, 0)
        '''
        # --------vmin,vmax boxes---------#

        self.vmin_box_label = Label(self.myContainer, text='Contrast min')
        self.vmin_box_label.config(fg='blue')
        self.vmin_box = Entry(self.myContainer, textvariable=self.vmin)

        self.vmax_box_label = Label(self.myContainer, text='Contrast max')
        self.vmax_box_label.config(fg='blue')
        self.vmax_box = Entry(self.myContainer, textvariable=self.vmax)

        self.vmin_box.grid(
            row=5,
            column=6,
            sticky=W + E,
            padx=3,
            pady=3)
        self.vmax_box.grid(
            row=5,
            column=7,
            sticky=W + E,
            padx=3,
            pady=3)
        self.vmin_box_label.grid(
            row=4,
            column=6,
            sticky=W + E,
            padx=3,
            pady=3)
        self.vmax_box_label.grid(
            row=4,
            column=7,
            sticky=W + E,
            padx=3,
            pady=3)

        # -------Plots-------#
        init_plots()
        plt.ioff()
        self.fig = plt.figure(1, figsize=(20, 8.5))
        self.cax = self.fig.add_axes([.92, .1, .01, .82])
        self.ax = self.fig.add_axes()

        self.canvas = FigureCanvasTkAgg(self.fig, master=self.myContainer)
        self.canvas.show()
        self.canvas.get_tk_widget(
        ).grid(row=7,
               column=0,
               rowspan=10,
               columnspan=15,
               sticky=W + E + S)
        #self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)

        self.toolbar = NavigationToolbar2TkAgg(self.canvas, parent)
        self.toolbar.update()
        # self.canvas._tkcanvas.pack(side=TOP,fill=BOTH,expand=1)
        self.canvas._tkcanvas.grid(
            row=7,
            column=0,
            rowspan=10,
            columnspan=15,
            sticky=W + E + S)
        self.canvas.show()

        self.myContainer.pack()


    def set_default_values(self):
        """ Set variables and boxes to default """
        self.vmin.set(0)
        self.vmax.set(0)
        self.dq_show.set('184')
        self.segment.set('A')
        self.N_degraded.set(0)
        self.extract.set('None')
        self.draw.set('Modal Gain')
        self.extract_offset.set(0)
        self.cmap.set('gist_yarg')
        self.grid_limits.set(1)


    def add_menubar(self, parent):
        """ Add menubar to figure """
        menubar = Menu(parent)

        # create a pulldown menu, and add it to the menu bar
        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="Open", command=self.open_file)
        filemenu.add_command(label="Save", command=self.save_current)
        filemenu.add_separator()

        filemenu.add_command(label="Exit", command=self.exit)
        menubar.add_cascade(label="File", menu=filemenu)

        # create more pulldown menus
        toolmenu = Menu(menubar, tearoff=0)
        toolmenu.add_command(label="Open Toolbox", command=self.dq_tools)
        menubar.add_cascade(label="Tools", menu=toolmenu)

        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label="Show Help", command=self.help_file)
        menubar.add_cascade(label="Help", menu=helpmenu)

        # submenu
        cmapmenu = Menu(toolmenu, tearoff=0)
        cmapmenu.add_radiobutton(
            label='Grey',
            variable=self.cmap,
            value='gist_yarg')
        cmapmenu.add_radiobutton(
            label='Prism',
            variable=self.cmap,
            value='prism')
        cmapmenu.add_radiobutton(label='Jet', variable=self.cmap, value='jet')
        cmapmenu.add_radiobutton(
            label='Ncar',
            variable=self.cmap,
            value='gist_ncar')
        toolmenu.insert_cascade(index=2, label='Select Cmap', menu=cmapmenu)

        return menubar

    def add_dq(self, bpixtab='bpix.fits', **kwargs):
        """ Plot DQ regions """
        seg = self.segment.get()
        colors = {
            2: 'b',
            4: 'g',
            8: 'y',
            16: 'r',
            32: 'c',
            1024: 'gold',
            4096: 'm',
            8192: 'orange'}

        dq_to_show = int( self.dq_show.get() )
        bpix = pyfits.open( bpixtab )
        for line in bpix[1].data:
            if line[0] == 'FUV' + seg and (line[5] & dq_to_show):
                lx = line['LX']
                ly = line['LY']
                dx = line['DX']
                dy = line['DY']
                dq = line['DQ']
                x = [lx, lx + dx, lx + dx, lx, lx]
                y = [ly, ly, ly + dy, ly + dy, ly]
                plt.plot(x, y, color=colors[int(dq)], **kwargs)
                plt.annotate(str(dq), (lx, ly), color=colors[int(dq)])

        self.canvas.show()


    def clear_axis(self):
        """ Clear plot of all selections """
        plt.figure(1)
        plt.subplot(1, 1, 1)
        plt.cla()
        # self.toggle_dq.deselect()
        # self.toggle_spec.deselect()
        # self.canvas.delete(all)
        self.canvas.show()
        self.extract.set('None')
        # self.Againmap.close()
        # self.Bgainmap.close()
        self.Againmap = None
        self.Bgainmap = None
        self.N_degraded.set(0)


    def degrade(self, array):
        '''
        Adapted from code from D. Massa
        '''
        date0 = (55772.0 - 54983.0) / 365.25
        date1 = (56108.0 - 54983.0) / 365.25
        xlim_a = (1200, 15099)
        ylim_a = (335, 699)
        xlim_b = (950, 15049)
        ylim_b = (400, 749)
        limits = (300, 16300)
        seg = self.segment.get()
        # years=(56108-54983.0)/365.25
        years = float(self.degrade_years.get())
        width = int(self.degrade_width.get())
        y = int(self.degrade_loc.get())
        xshift = int(self.degrade_xshift.get())
        if seg == 'A':
            infile = os.path.join(data_dir, '12676-all-A-2.fits')
            y0 = 487
        elif seg == 'B':
            infile = os.path.join(data_dir, '12676-LV-B-2.fits')
            y0 = 546
        gain = pyfits.getdata(infile, 2)
        gain0 = pyfits.getdata(infile, 3)
        delta = (gain0 - gain) / date0
        if not self.N_degraded.get():
            degraded = gain0 - delta * date1
            self.N_degraded.set(1)
        else:
            degraded = array
        delta = numpy.roll(delta, shift=xshift)
        delta = numpy.roll(delta, shift=y - y0, axis=0)
        # degraded[y-(width-1)/2:y+(width-1)/2,:]-=delta[y0-(width-1)/2:y0+(width-1)/2,:]*years
        degraded -= delta * years

        hdu = pyfits.HDUList(pyfits.PrimaryHDU())
        hdu[0].header.update('TELESCOP', 'HST')
        hdu[0].header.update('INSTRUME', 'COS')
        hdu[0].header.update('DETECTOR', 'FUV')
        # hdu[0].header.update('OPT_ELEM','ANY')
        # hdu[0].header.update('FILETYPE','')
        # hdu[0].header.update('EXPTIME',exptime)
        # hdu[0].header.update('PHA_MIN',2)
        # hdu[0].header.update('PHA_MAX',30)
        hdu.append(pyfits.core.ImageHDU(data=degraded))
        hdu.writeto('gainmap.fits')

        return degraded

    def dq_tools(self):
        self.toolswindow = Toplevel()
        self.frame2 = Frame(master=self.toolswindow)
        self.toolswindow.title('DQ tools')
        # -----------variables------------------#
        self.height = StringVar()
        self.height.set('500')
        self.width = StringVar()
        self.width.set('20')
        self.draw_DQ = IntVar()
        self.draw_DQ.set(0)
        self.SDQFLAG = IntVar()
        self.SDQFLAG.set(184)
        self.affected_pixels = StringVar()
        self.affected_pixels.set('0')
        self.affected_columns = StringVar()
        self.affected_columns.set('0')

        # -----------Define Close Button--------#
        self.closebutton2 = Button(
            self.toolswindow,
            text="CLOSE",
            fg="red",
            command=self.toolswindow.destroy)
        self.closebutton2.grid(row=35, column=6)
        self.extractbutton = Button(
            self.toolswindow,
            text="EXTRACT",
            fg="blue",
            command=self.extract_dqs)
        self.extractbutton.grid(row=0, column=0)
        self.savebutton = Button(
            self.toolswindow,
            text="Save Fig",
            fg="blue",
            command=self.save_fig)
        self.savebutton.grid(row=35, column=0)

        # -----------Find Best Postition--------#
        self.findbest = Button(
            self.toolswindow,
            text="Find best",
            fg="blue",
            command=self.find_best)
        self.findbest.grid(row=0, column=1)

        # -----------Entry Box-------------------#
        self.SDQFLAG_label = Label(self.toolswindow, text='SDQFLAG')
        self.SDQFLAG_label.config(fg='blue')
        self.SDQFLAG_box = Entry(self.toolswindow, textvariable=self.SDQFLAG)

        self.SDQFLAG_box.grid(
            row=6,
            column=0,
            sticky=W + E,
            padx=3,
            pady=3)
        self.SDQFLAG_label.grid(
            row=5,
            column=0,
            sticky=W + E,
            padx=3,
            pady=3)
        self.SDQFLAG_box.delete(0, END)
        self.SDQFLAG_box.insert(0, 184)

        # -----------Extraction results---------------#
        self.results_label = Label(
            self.toolswindow,
            text='% affected Pixels')
        self.results_label.config(fg='blue')
        self.results_box = Entry(
            self.toolswindow,
            textvariable=self.affected_pixels)

        self.results_box.grid(
            row=6,
            column=1,
            sticky=W + E,
            padx=3,
            pady=3)
        self.results_label.grid(
            row=5,
            column=1,
            sticky=W + E,
            padx=3,
            pady=3)
        self.results_box.delete(0, END)
        self.results_box.insert(0, '0')

        self.Cresults_label = Label(
            self.toolswindow,
            text='% affected Columns')
        self.Cresults_label.config(fg='blue')
        self.Cresults_box = Entry(
            self.toolswindow,
            textvariable=self.affected_columns)

        self.Cresults_box.grid(
            row=6,
            column=2,
            sticky=W + E,
            padx=3,
            pady=3)
        self.Cresults_label.grid(
            row=5,
            column=2,
            sticky=W + E,
            padx=3,
            pady=3)
        self.Cresults_box.delete(0, END)
        self.Cresults_box.insert(0, '0')

        self.height_box_label = Label(self.toolswindow, text='Y Loc')
        self.height_box_label.config(fg='blue')
        self.height_box = Entry(self.toolswindow, textvariable=self.height)

        self.width_box_label = Label(self.toolswindow, text='Height')
        self.width_box_label.config(fg='blue')
        self.width_box = Entry(self.toolswindow, textvariable=self.width)

        self.height_box.grid(
            row=2,
            column=0,
            sticky=W + E,
            padx=3,
            pady=3)
        self.width_box.grid(
            row=2,
            column=1,
            sticky=W + E,
            padx=3,
            pady=3)
        self.height_box_label.grid(
            row=1,
            column=0,
            sticky=W + E,
            padx=3,
            pady=3)
        self.width_box_label.grid(
            row=1,
            column=1,
            sticky=W + E,
            padx=3,
            pady=3)
        self.height_box.delete(0, END)
        self.width_box.delete(0, END)
        self.height_box.insert(0, 500)
        self.width_box.insert(0, '20')

        matplotlib.rcParams['figure.subplot.left'] = .15
        matplotlib.rcParams['figure.subplot.right'] = .85
        matplotlib.rcParams['figure.subplot.top'] = .85
        matplotlib.rcParams['figure.subplot.bottom'] = .15
        self.fig2 = plt.figure(2, figsize=(4, 6))
        self.ax2 = self.fig2.add_axes()

        plt.figure(2)
        self.canvas2 = FigureCanvasTkAgg(self.fig2, master=self.toolswindow)
        self.canvas2.show()
        self.canvas2.get_tk_widget(
            ).grid(row=13,
                   column=0,
                   rowspan=17,
                   columnspan=17,
                   sticky=N + W + E + S)

        self.toolswindow.mainloop()

    def draw_all(self):
        # self.clear_axis()
        plt.figure(1)
        plt.cla()
        plt.subplot(1, 1, 1)
        plt.xlabel('X (Dispersion)')
        plt.ylabel('Y (Cross Dispersion)')
        show_which = self.draw.get()
        seg = self.segment.get()
        if (show_which == 'Data File'):
            vmin = int(self.vmin.get())
            vmax = int(self.vmax.get())
            if (vmin == 0 and vmax == 0):
                vmin = 1
            vmax = 15
            if vmin < 0:
                vmin = 0
            if vmax > 20:
                vmax = 20
            self.vmin.set(vmin)
            self.vmax.set(vmax)
            levels = range(vmin, vmax + 1)
            if seg == 'A':
                extension = 1
            elif seg == 'B':
                extension = 2

            C1 = plt.imshow(
                ttag_image( self.data_file),
                interpolation='nearest',
                aspect='auto',
                cmap=plt.get_cmap(self.cmap.get()))  # ,vmin=,vmax=vmax)
            plt.colorbar(C1, cax=self.cax)

        if show_which == 'Modal Gain':
            if self.Againmap is None:
                self.Againmap = pyfits.getdata(
                    os.path.join(data_dir, '12676-all-A-2.fits'), 2)
            if self.Bgainmap is None:
                self.Bgainmap = pyfits.getdata(
                    os.path.join(data_dir, '12676-LV-B-2.fits'), 2)
            vmin = int(self.vmin.get())
            vmax = int(self.vmax.get())
            if (vmin == 0 and vmax == 0):
                vmin = 1
                vmax = 15
            if vmin < 0:
                vmin = 0
            if vmax > 20:
                vmax = 20
            self.vmin.set(vmin)
            self.vmax.set(vmax)
            levels = range(vmin, vmax + 1)
            if seg == 'A':
                if self.degrade_array.get():
                    self.Againmap = self.degrade(self.Againmap)
                gainmap = self.Againmap
            if seg == 'B':
                if self.degrade_array.get():
                    self.Bgainmap = self.degrade(self.Bgainmap)
                gainmap = self.Bgainmap
            # if self.degrade_array.get():
            #    gainmap=self.degrade()
            levels = range(1, vmax + 1)
            C1 = plt.contourf(
                gainmap.clip(max=vmax),
                levels,
                cmap=plt.get_cmap(self.cmap.get()))
            # C1=plt.imshow(gainmap.astype('int32'),aspect='auto',cmap=plt.get_cmap(self.cmap.get()),vmin=vmin,vmax=vmax)
            plt.colorbar(C1, cax=self.cax)
            if seg == 'A':
                self.Againmap = gainmap
            elif seg == 'B':
                self.Bgainmap = gainmap
        if show_which == 'Summed Exposure':
            if self.Aexp is None:
                self.Aexp = pyfits.getdata(
                    os.path.join(data_dir, '12676-all-A-2.fits'), 1)
            if self.Bexp is None:
                self.Bexp = pyfits.getdata(
                    os.path.join(data_dir, '12676-LV-B-2.fits'), 1)
            vmin = int(self.vmin.get())
            vmax = int(self.vmax.get())
            if (vmin == 0 and vmax == 0):
                vmin = 0
                vmax = 400
            if vmin < 0:
                vmin = 0
            if vmax < 100:
                vmax = 400
            self.vmin.set(vmin)
            self.vmax.set(vmax)
            levels = [25, 50, 100, 200, 250, 300, 350, 400]
            if seg == 'A':
                exp = self.Aexp
            elif seg == 'B':
                exp = self.Bexp
            C1 = plt.imshow(
                exp,
                aspect='auto',
                vmin=vmin,
                vmax=vmax,
                cmap=plt.get_cmap(self.cmap.get()))
            # C1=plt.contourf(Aexp,levels)
            plt.colorbar(C1, cax=self.cax)
        if show_which == 'Summed Dark':
            if self.Adark is None:
                self.Adark = pyfits.getdata('all_pha_0.fits', 1)
            if self.Bdark is None:
                self.Bdark = pyfits.getdata('all_pha_0.fits', 2)
            vmin = int(self.vmin.get())
            vmax = int(self.vmax.get())
            if (vmin == 0 and vmax == 0):
                vmin = 0
                vmax = 4
            if vmin < 0:
                vmin = 0
            if vmax > 13:
                vmax = 4
            self.vmin.set(vmin)
            self.vmax.set(vmax)
            levels = [25, 50, 100, 200, 250, 300, 350, 400]
            if seg == 'A':
                dark = self.Adark
            if seg == 'B':
                dark = self.Bdark
            #dark = blur_image(dark,6,10)
            C1 = plt.imshow(
                dark,
                aspect='auto',
                vmin=vmin,
                vmax=vmax,
                cmap=plt.get_cmap(self.cmap.get()))
            # C1=plt.contourf(Aexp,levels)
            plt.colorbar(C1, cax=self.cax)
        if self.extract.get() != 'None':
            text = self.extract.get()
            offset = int(self.extract_offset.get())
            SEGMENT = text[:4]
            OPT_ELEM = text[5:10]
            CENWAVE = int(text[11:15])
            APERTURE = text[16:]
            XTRACTAB = pyfits.getdata('u8k1433nl_1dx.fits', 1)
            index = numpy.where((XTRACTAB['SEGMENT'] == SEGMENT) & (XTRACTAB['OPT_ELEM'] == OPT_ELEM) & (
                XTRACTAB['CENWAVE'] == CENWAVE) & (XTRACTAB['APERTURE'] == APERTURE))
            B_SPEC = XTRACTAB[index]['B_SPEC'] + offset
            HEIGHT = XTRACTAB[index]['HEIGHT']
            B_BKG1 = XTRACTAB[index]['B_BKG1'] + offset
            B_BKG2 = XTRACTAB[index]['B_BKG2'] + offset
            BHEIGHT = XTRACTAB[index]['BHEIGHT']

            plt.axhspan(
                B_SPEC - (HEIGHT - 1) / 2,
                B_SPEC + (HEIGHT - 1) / 2,
                facecolor='0.5',
                alpha=0.4)
            plt.axhspan(
                B_BKG1 - (BHEIGHT - 1) / 2,
                B_BKG1 + (BHEIGHT - 1) / 2,
                facecolor='0.2',
                alpha=0.4)
            plt.axhspan(
                B_BKG2 - (BHEIGHT - 1) / 2,
                B_BKG2 + (BHEIGHT - 1) / 2,
                facecolor='0.2',
                alpha=0.4)

        if self.show_spectrum.get():
            sample = pyfits.open('lbp102neq_corrtag_a.fits')
            im = ttag_image(sample[1].data)
            # plt.imshow(im,cmap=plt.get_cmap('gist_yarg'),aspect='auto',interpolation='nearest',alpha=.7)

        if self.xmin.get() != 'ALL' and self.xmax.get() != 'ALL':
            plt.xlim(int(self.xmin.get()), int(self.xmax.get()))
        if self.ymin.get() != 'ALL' and self.ymax.get() != 'ALL':
            plt.ylim(int(self.ymin.get()), int(self.ymax.get()))
        self.canvas.show()

    def exit(self):
        self.myContainer.quit()
        sys.exit(1)

    def extract_dqs(self):
        plt.figure(1)
        plt.subplot(1, 1, 1)
        xlim_a = (1200, 15099)
        ylim_a = (335, 699)
        xlim_b = (950, 15049)
        ylim_b = (400, 749)
        seg = self.segment.get()
        if seg == 'A':
            xlim = xlim_a
            ylim = ylim_a
        elif seg == 'B':
            xlim = xlim_b
            ylim = ylim_b
        dq_array = numpy.zeros((1024, 16384), int)
 
        seg = self.segment.get()
        bpix = pyfits.open('bpix.fits')
        for line in bpix[1].data:
            if line[0] == 'FUV' + seg:
                lx = line['LX']
                ly = line['LY']
                dx = line['DX'] - 1  # width, not delta
                dy = line['DY'] - 1
                dq = line['DQ']
                subarray = dq_array[ly:ly + dy, lx:lx + dx]
                index = numpy.where(subarray != dq)
                dq_array[ly:ly + dy, lx:lx + dx][index] += dq
  
        # plt.contourf(dq_array,aspect='auto',levels=[0,2,4,8,16,32,64,128,256])
        sdqflags = int(self.SDQFLAG.get())
        height = int(self.height.get())
        width = int(self.width.get())
        extracted = dq_array[
            height -
            width /
            2:height +
            width /
            2,
            xlim[
                0]:xlim[
                1]]
        index = numpy.where(sdqflags & extracted)
        xs = [xlim[0], xlim[1], xlim[1], xlim[0], xlim[0]]
        ys = [
            height - width / 2,
            height - width / 2,
            height + width / 2,
            height + width / 2,
            height - width / 2]
        plt.plot(xs, ys, 'b--', lw=3)
        total = extracted.shape[0] * extracted.shape[1]
        self.affected_columns.set(
            100 * len(set(index[1])) / float(xlim[1] - xlim[0]))
        self.affected_pixels.set(100 * len(index[0]) / float(total))
        self.canvas.show()
        self.histogram()

    def find_best(self):
        plt.figure(1)
        plt.subplot(1, 1, 1)
        number_affected = []
        index_affected = []
        hs = []
        sdqflags = int(self.SDQFLAG.get())
        height = int(self.height.get())
        width = int(self.width.get())
        xlim_a = (1200, 15099)
        ylim_a = (335, 699)
        xlim_b = (950, 15049)
        ylim_b = (400, 749)
        seg = self.segment.get()
        if seg == 'A':
            xlim = xlim_a
            ylim = ylim_a
        elif seg == 'B':
            xlim = xlim_b
            ylim = ylim_b
        dq_array = numpy.zeros((1024, 16384), int)

        seg = self.segment.get()
        bpix = pyfits.open('bpix.fits')
        for line in bpix[1].data:
            if line[0] == 'FUV' + seg:
                lx = line['LX']
                ly = line['LY']
                dx = line['DX'] - 1  # width, not delta
                dy = line['DY'] - 1  # width, not delta
                dq = line['DQ']
                subarray = dq_array[ly:ly + dy, lx:lx + dx]
                index = numpy.where(subarray != dq)
                dq_array[ly:ly + dy, lx:lx + dx][index] += dq

        sweep = range(height - 1 * width, height + 1 * width)
        for h in sweep:
            if (h - 1 * width > ylim[0]) & (h + 1 * width < ylim[1]):
                extracted = dq_array[
                    h -
                    width /
                    2:h +
                    width /
                    2,
                    xlim[
                        0]:xlim[
                        1]]
                index = numpy.where(sdqflags & extracted)
                hs.append(h)
                number_affected.append(len(index[1]))
        number_affected = numpy.array(number_affected)
        hs = numpy.array(hs)
        min_aff = number_affected[number_affected.argmin()]
        min_indexes = numpy.where(number_affected == min_aff)
        hs = hs[min_indexes]
        number_affected = number_affected[min_indexes]
        closest_index = (numpy.fabs(hs - height)).argmin()
        total = extracted.shape[0] * extracted.shape[1]
        self.affected_pixels.set(100 * (min_aff / float(total)))
        height = hs[closest_index]
        xs = [xlim[0], xlim[1], xlim[1], xlim[0], xlim[0]]
        ys = [
            height - width / 2,
            height - width / 2,
            height + width / 2,
            height + width / 2,
            height - width / 2]
        plt.plot(xs, ys, '-.', lw=6)
        extracted = dq_array[
            height -
            width / 2:height + width / 2, xlim[0]:xlim[1]
            ]
        index = numpy.where(sdqflags & extracted)
        self.height.set(height)
        self.affected_columns.set(
            100 * len(set(index[1])) / float(xlim[1] - xlim[0]))
        self.canvas.show()
        self.histogram(height, width)

    def help_file(self):
        self.helpwindow = Toplevel()
        self.frame3 = Frame(master=self.helpwindow)
        self.helpwindow.title('Help')
        self.closebutton3 = Button(
            self.helpwindow,
            text="CLOSE",
            fg="red",
            command=self.helpwindow.destroy)
        self.closebutton3.grid(row=12, column=0)

        self.text = ScrolledText(self.helpwindow)
        self.text.grid(row=0, column=0, sticky=W + E + N + S)
        help_file = open('help.txt')
        help_string = help_file.readlines()
        self.text.importfile('help.txt')
        # for line in help_file.readlines():

    def histogram(self, height=-99, width=-99):
        xlim_a = (1183, 15230)
        ylim_a = (301, 750)
        xlim_b = (993, 15015)
        ylim_b = (371, 771)
        caption = False
        seg = self.segment.get()
        if seg == 'A':
            xlim = xlim_a
            ylim = ylim_a
            gainmap = self.Againmap
        if seg == 'B':
            xlim = xlim_b
            ylim = ylim_b
            gainmap = self.Bgainmap
        if height == -99:
            height = int(self.height.get())
        if width == -99:
            width = int(self.width.get())
        gain_1d = (
            gainmap[height - (width - 1) / 2:height + (width - 1) / 2,
                    xlim[0]:xlim[1]].flatten())
        # index=numpy.where(gain_1d>0)
        plt.figure(2)
        plt.clf()
        if caption:
            ax2 = self.fig2.add_axes((.15, .37, .8, .5))
        else:
            ax2 = self.fig2.add_axes((.15, .15, .8, .7))
        plt.cla()
        plt.suptitle('Modal Gain')
        plt.title(
            'Segment= %s, Y=%s, dy=%s, years=%s, xshift=%s' % (self.segment.get(),
                                                               self.height.get(),
                                                               self.width.get(),
                                                               self.degrade_years.get(
                                                               ),
                                                               self.degrade_xshift.get(
                                                               )),
            fontsize=12)
        ax2.hist(gain_1d, normed=True, bins=range(20), align='mid', color='b')
        N_lte_3 = len(numpy.where(gain_1d <= 3)[0])
        N_tot = len(gain_1d)
        ys = plt.ylim()
        plt.text(
            1, ys[1] * .9, 'Pixels below gain=3:\n%d/%d' %
            (N_lte_3, N_tot), fontsize=12)
        try:
            ax2.locator_params(nbins=20, tight=True, axis='x')
        except:
            pass
        plt.xlabel('Gain')
        plt.ylabel('Normalized Counts')
        t = '''Modal Gain in extracted region of Segment %s.
At Y=%s, dy=%s and SDQFLAGS=%s, %1.3f percent of
pixels and %1.3f percent of colums will be flagged.''' % (self.segment.get(), self.height.get(), self.width.get(), self.SDQFLAG.get(), float(self.affected_pixels.get()), float(self.affected_columns.get()))

        if caption:
            self.fig2.text(.1, .1, t, fontsize=12)
        self.canvas2.show()

    def open_file(self):
        filename = tkFileDialog.askopenfilename(
            filetypes=[("allfiles", "*"), ("pythonfiles", "*.py")])
        print filename
        self.data_file = filename

    def save_current(self):
        """ Save file from menu """
        tkFileDialog.asksaveasfile()

    def save_fig(self):
        plt.figure(2)
        out_file = tkFileDialog.asksaveasfilename()
        plt.savefig(out_file)

    def set_cmap(self, cmap):
        """ Change the colormap of the image """
        if cmap == 'autumn':
            plt.autumn()
        elif cmap == 'spring':
            plt.spring()

        self.canvas.show()

    def update_plot(self, event):
        """ Redraw figure with new limits """
        print 'Trying to redraw'
        plt.figure( 1 )

        if self.xmin.get() != 'ALL' and self.xmax.get() != 'ALL':
            plt.xlim(int(self.xmin.get()), int(self.xmax.get()))
        else:
            plt.xlim(0, 16384)
        if self.ymin.get() != 'ALL' and self.ymax.get() != 'ALL':
            plt.ylim(int(self.ymin.get()), int(self.ymax.get()))
        else:
            plt.ylim(0, 1024)

        self.canvas.show()
コード例 #20
0
ファイル: toplevel0.py プロジェクト: thanggc/libros
import sys
from Tkinter import Toplevel, Button, Label

win1 = Toplevel()  # two independent windows
win2 = Toplevel()  # but part of same process

Button(win1, text='Spam', command=sys.exit).pack()
Button(win2, text='SPAM', command=sys.exit).pack()

Label(text='Popups').pack()  # on default Tk( ) root window
win2.mainloop()
コード例 #21
0
ファイル: ui_engine.py プロジェクト: an-o/Sub
class UIEngine(Thread, Notify):
    """
        Handle a Tk Interface

    """

    interface_id = -1

    def __init__(self):
        UIEngine.interface_id += 1
        Notify.__init__(self)
        Thread.__init__(self)
        # This condition will notify the main thread when init is over
        self._wait_init_event = Event()
        # Run the UI thread
        self.start()
        # Wait for the initialisation of the ui
        #   to continue
        self._wait_init_event.wait(10)


    def _init_tk_window(self):
        """
            Initialize the window for the Tk Interface

        """
        # Create the instance
        if UIEngine.interface_id == 0:
            self._root = Tk() 
        else:
            self._root = Toplevel() 
        # Resize the window
        # compute h according to the table
        h = UITable.TABLE_HEIGHT
        # fixed size for the width
        w = 1200
        # translate it in string
        dim = str(w) + "x" + str(h)
        self._root.geometry(dim)


    def _init_table(self):
        """
            Init the table frame
            This part is responsible for all

        """
        self._table = UITable(self._root)
        self._table.set_method(CONSOLE_RED, \
                               lambda msg, c=True: self.add_message(msg, c)) 


    def _init_side_pannel(self):
        """
            The side pannel 
        
        """
        self._side_pannel = UISidePannel(self._root)
        # Initialize the quit callback
        quit_callback = lambda: self._event[EVT_UI_PLAYER_LEFT]( \
                                 self._table.interface_player)
        self._side_pannel.set_method(EVT_CONTROL_QUIT, quit_callback) 


    def _init_ui(self):
        """
            Sets the interface and enter the tk mainloop

        """
        # Init the interface
        self._init_tk_window()
        # Init the game parts 
        self._init_table()
        # Init the other part
        self._init_side_pannel()


    def run(self):
        """
            This method will be called when the UI thread starts.
            It initialise and launch the UI. 

        """
        # Launch the initialisation
        self._init_ui()
        # Notify the end of the initialisation 
        self._wait_init_event.set()
        # Release the condition, now useless
        self._wait_init_event.clear()
        # Enter the infinite loop, see you lata
        if UIEngine.interface_id == 0: 
            self._root.mainloop()

    
    def set_reference_player(self, p):
        """
            Reference player is the player who manage the interface
            Will be positioned South
            @param p    future reference player 
            
        """
        self._table.interface_player = p


    def new_round(self):
        """
            Notification for the beginning of a new round

        """
        self._table.new_round()


    def new_bid(self, bid):
        """
            A new bid has been made, need to forward it to the table

        """
        self._table.new_bid(bid)


    def new_deal(self):
        """
            Notification for the beginning of a deal 

        """
        self._table.new_deal()


    def card_played(self, p, c):
        """

            Notification that the card c has been played by player p
            @param c    tuple (val, col) of the card played
            @param p    id of the player that played the card

        """
        self._table.card_played(p, c)


    def end_of_trick(self, p):
        """
            Notification that the current trick is finished 
            (it should reasonnably mean that four cards have
            been played since the beginning of the trick)
            @param p    id of the player that wins the trick

        """
        self._table.end_of_trick(p)


    def get_card(self, p, playable):
        """
            Wait for the user p to choose a card between
            the possible ones given in playable
            @param p            id of the player expected to play
            @param playable     list of cards that can be played

        """
        return self._table.get_card(p, playable)


    def get_coinche(self):
        """
            Wait for the user to coinche. 

        """
        return self._table.get_coinche()


    def get_bid(self, p, bidded, bid_list):
        """
            Wait for the user p to bid 
            the possible ones given in bid list 
            @param p            id of the player expected to play
            @param bidded       last 4 bids
            @param bid_list     list of possible bids

        """
        return self._table.get_bid(p, bidded, bid_list)


    def new_hand(self, player, hand):
        """
            Set a new hand hand for player player
            Method called by an event engine to refresh display
            @param player   id of the player that is given the hand
            @param hand list of tuples (val, col) composing the hand

        """
        self._table.new_hand(player, hand)


    def end_bidding(self):
        self._table.end_bidding()


    def add_player(self, p):
        """
            Add a player handled by the UI
            @param p    player handled  

        """
        self._table.add_player(p)


    def add_message(self, msg, red = False):
        """
            Add a message to the UIConsole

        """
        self._side_pannel.add_message(msg, red)


    def get_consoles(self):
        """
            Return the list of the consoles for this UI

        """
        return [self._side_pannel._console]


    def update_score(self, score):
        """
            Update the score in ui_table
            @param score    the new score

        """
        self._table.update_score(score)


    def belote(self, pid):
        """

        """
        self._table.belote(pid)

    def rebelote(self, pid):
        """

        """
        self._table.rebelote(pid)
         

    def set_method(self, evt_id, method):
        """
            Overwrite set_method
            Because UIEngine is only an entry-point, set_method need
                to be called on every child of UIEngine

        """
        self._event[evt_id] = method
        self._side_pannel.set_method(evt_id, method)
        self._table.set_method(evt_id, method)
コード例 #22
0
ファイル: toplevel0.py プロジェクト: Topidesta/libros
import sys
from Tkinter import Toplevel, Button, Label

win1 = Toplevel( )                  # two independent windows
win2 = Toplevel( )                  # but part of same process

Button(win1, text='Spam', command=sys.exit).pack( )
Button(win2, text='SPAM', command=sys.exit).pack( )

Label(text='Popups').pack()          # on default Tk( ) root window
win2.mainloop( )

コード例 #23
0
ファイル: videopoker.py プロジェクト: JaegyuC/oakland
    def help_about(self):

        """Shows an 'about' modal dialog.

        Callback method called by tk.

        """

        about_win = Toplevel(self.root)

        # Set up dialog

        lbl = Label(about_win, text="Video Poker")
        lbl.grid(row=0, column=0, padx=10, pady=(10, 0), sticky=W + N)
        lbl = Label(about_win, text="by Paul Griffiths")
        lbl.grid(row=1, column=0, padx=10, pady=(0, 7), sticky=W + N)
        lbl = Label(about_win, text="Written in Python, with tkinter.")
        lbl.grid(row=2, column=0, padx=10, pady=7, sticky=W + N)
        lbl = Label(about_win, text="Copyright 2013 Paul Griffiths")
        lbl.grid(row=4, column=0, padx=10, pady=(7, 0), sticky=W + N)
        lbl = Label(about_win, text="Email: [email protected]")
        lbl.grid(row=5, column=0, padx=10, pady=(0, 21), sticky=W + N)
        lbl = Label(about_win, text="This program is free software: you can " +
            "redistribute it and/or modify it under the terms")
        lbl.grid(row=6, column=0, columnspan=2,
                 padx=10, pady=0, sticky=W + N)
        lbl = Label(about_win, text="of the GNU General Public License as " +
            "published by the Free Software Foundation, either")
        lbl.grid(row=7, column=0, columnspan=2,
                 padx=10, pady=(0, 0), sticky=W + N)
        lbl = Label(about_win, text="version 3 of the License, or " +
            "(at your option) any later version.")
        lbl.grid(row=8, column=0, columnspan=2,
                 padx=10, pady=(0, 21), sticky=W + N)
        lbl = Label(about_win, text="This program is distributed in " +
            "the hope that it will be useful, but WITHOUT ANY WARRANTY;")
        lbl.grid(row=9, column=0, columnspan=2,
                 padx=10, pady=0, sticky=W + N)
        lbl = Label(about_win, text="without even the implied " +
            "warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR")
        lbl.grid(row=10, column=0, columnspan=2,
                 padx=10, pady=(0, 0), sticky=W + N)
        lbl = Label(about_win, text="PURPOSE. See the " +
            "GNU General Public License for more details.")
        lbl.grid(row=11, column=0, columnspan=2,
                 padx=10, pady=(0, 21), sticky=W + N)
        lbl = Label(about_win, text="You should have received a " +
            "copy of the GNU General Public License along with this")
        lbl.grid(row=12, column=0, columnspan=2,
                 padx=10, pady=(0, 0), sticky=W + N)
        lbl = Label(about_win, text="program. If not, see " +
            "<http://www.gnu.org/licenses/>.")
        lbl.grid(row=13, column=0, columnspan=2,
                 padx=10, pady=(0, 21), sticky=W + N)
        img = PhotoImage(file="{0}27.gif".format(self.gifdir))
        lbl = Label(about_win, image=img)
        lbl.grid(row=0, column=1, rowspan=5, padx=10, pady=10, sticky=N + E)

        btn = Button(about_win, text="OK", command=about_win.quit)
        btn.grid(row=14, column=0, columnspan=2,
                 padx=0, pady=(0, 10), ipadx=30, ipady=3)

        # Show dialog

        about_win.transient(self.root)
        about_win.parent = self.root
        about_win.protocol("WM_DELETE_WINDOW", about_win.destroy)
        about_win.geometry("+{0}+{1}".format(self.root.winfo_rootx() + 50,
                                           self.root.winfo_rooty() + 50))
        about_win.title("About Video Poker")
        about_win.focus_set()
        about_win.grab_set()
        about_win.mainloop()
        about_win.destroy()
コード例 #24
0
ファイル: DialogTemplate.py プロジェクト: tylerjw/jim_tracker
class Dialog:
    def __init__(self, master, title, class_=None, relx=0.5, rely=0.3):
        self.master = master
        self.title = title
        self.class_ = class_
        self.relx = relx
        self.rely = rely

    def setup(self):
        if self.class_:
            self.root = Toplevel(self.master, class_=self.class_)
        else:
            self.root = Toplevel(self.master)

        self.root.title(self.title)
        self.root.iconname(self.title)

    def change_title(self,title):
        self.title = title
        self.root.title(self.title)
        self.root.iconname(self.title)

    def enable(self):
        ### enable
        self.root.protocol('WM_DELETE_WINDOW', self.wm_delete_window)
        self._set_transient(self.relx, self.rely)
        self.root.wait_visibility()
        self.root.grab_set()
        self.root.mainloop()
        self.root.destroy()

    def _set_transient(self, relx=0.5, rely=0.3):
        widget = self.root
        widget.withdraw() # Remain invisible while we figure out the geometry
        widget.transient(self.master)
        widget.update_idletasks() # Actualize geometry information
        if self.master.winfo_ismapped():
            m_width = self.master.winfo_width()
            m_height = self.master.winfo_height()
            m_x = self.master.winfo_rootx()
            m_y = self.master.winfo_rooty()
        else:
            m_width = self.master.winfo_screenwidth()
            m_height = self.master.winfo_screenheight()
            m_x = m_y = 0
        w_width = widget.winfo_reqwidth()
        w_height = widget.winfo_reqheight()
        x = m_x + (m_width - w_width) * relx
        y = m_y + (m_height - w_height) * rely
        if x+w_width > self.master.winfo_screenwidth():
            x = self.master.winfo_screenwidth() - w_width
        elif x < 0:
            x = 0
        if y+w_height > self.master.winfo_screenheight():
            y = self.master.winfo_screenheight() - w_height
        elif y < 0:
            y = 0
        widget.geometry("+%d+%d" % (x, y))
        widget.deiconify() # Become visible at the desired location

    def wm_delete_window(self):
        self.root.quit() 
コード例 #25
0
ファイル: topleve10.py プロジェクト: vivion-git/nymph
import sys
from Tkinter import Toplevel,Button,Label
win1=Toplevel()
win2=Toplevel()
Button(win1,text='spam',command=sys.exit).pack()

Button(win2,text='SPAM',command=sys.exit).pack()
Label(text='Popups').pack()
win1.mainloop()

コード例 #26
0
ファイル: toplevel.py プロジェクト: Elzei/show-off
import sys
from Tkinter import Toplevel, Button, Label
windows1 = Toplevel()
windows2 = Toplevel()
Button(windows1, text=u'Okno 1', command=sys.exit).pack()
Button(windows2, text=u'Okno 2', command=sys.exit).pack()
Label(text=u'Wyskakujace').pack()
# domyslnie dla okna "root"
windows1.mainloop()  # wtarczy mainloop()
# dla ktoregokolwiek z okien
コード例 #27
0
class AddCatalogSourcesDialog():
    """Class to gather input values for loading catalog sources

    This class presents a dialog box to the user allowing them to input values
    for the various filenames, model names, and other values needed to extract
    the Fermi Source Catalog sources from the relevant files and add them to
    their model.

    Usage:
         dialog = AddCatalogSourceDialog()
         data = dialog.getData()

    The getData() method returns a dictionary of the data values entered by the
    user.  The dictionary keys are listed below in the description of the values
    the user is prompted for.  If the dialog is canceled, it returns a None
    object.

    The user is prompted to input the following values
        - Source Catalog file (key => 'catalogFile') - This is the FITS file
          of the Fermi Source catalog.  This can be the 1FGL, 2FGL, or 3FGL (once
          published) catalog file.  This contains the sources to be added to the
          model.
        - LAT Event File (key => 'eventFile') - This is a valid FT1 LAT event
          FITS file.  This file is used to extract the region of interest (ROI)
          information to determine which sources should be selected from the
          catalog.
        - Source Significance Limit (key => 'sigLimit') - This is the significance
          limit threshold for selecting sources from the catalog.  Sources with
          significance values less than this limit will not be added to the model.
        - Galactic Diffuse Model file (key => 'galDiffFile') - This is the file
          containing the galactic diffuse model to use.  By default it points to
          the standard file provided with the Science Tools.
        - Galactic Diffuse Model Name (key => 'gdModelName') - This is the name
          of the model to use from the galactic diffuse model file.  By default
          it is set to ????????????.
        - Isotropic Template file (key => 'iosTempFile') - The name of the
          file containing the isotropic diffuse templates.  By default this is
          set to the standard file provided with the Science Tools.
        - Isotropic Template Name (key => 'isoTempName') - The name of the
          isotropic template to use.  By default this is set to ????????????.
        - Variable Source Radius - radius within which all sources should be set
          to allow their parameters to vary.  Outside of this radius parameters
          will be fixed to catalog values.  Values less than 0 are treated as
          meaning that the radius is the same as the extraction radius in the FT1
          event file.  Default is -1
        - Force Point Source flag - If set all extended sources in the catalog
          will be treated as point sources.  Default is false.
        - Extended Source Template Directory - Directory containing the extended
          source model files.  This is only needed if the Force Point Source flag
          is no.
    """
    def __init__(self):
        """Initialize the class

        Parameters:
        - self - This AddCatalogSourcesDialog object

        Return value:
        - none

        Description:
        This method simply creates the top level Tk window for holding the dialog box and
        initializes an empty dictionary to hold the return values.
        """
        self.win = Toplevel()
        self.win.title("Add Catalog Sources")
        #        self.win.minsize(500, 100)
        self.values = {}
        # need access to these outside their creation function
        self.l9 = Label()
        self.b7 = Button()

    def _draw(self):
        """Create the dialog box

        Parameters:
        - self - This AddCatalogSourcesDialog object

        Return value:
        - none

        Description:
        This method creates the dialog box to be presented to the user.  It also creates
        the internal EntryField variables to hold the data values entered by the user.
        """
        labelWidth = 32

        msg = Label(
            self.win,
            width=60,
            pady=5,
            text=
            "To load catalog sources please provide the following information:"
        )
        msg.pack(side=TOP)

        scFrame = Frame(self.win)
        l1 = Label(scFrame,
                   text="Source Catalog File:",
                   width=labelWidth,
                   anchor=E)
        l1.pack(side=LEFT)
        self._catalogFileField = Pmw.EntryField(scFrame, value="")
        self._catalogFileField.pack(side=LEFT, expand=YES, fill=X)
        b1 = Button(scFrame,
                    text="Browse...",
                    command=(lambda: self._getFile(self._catalogFileField)))
        b1.pack(side=LEFT)
        scFrame.pack(side=TOP, expand=YES, fill=X)

        ft1Frame = Frame(self.win)
        l2 = Label(ft1Frame,
                   text="Event File (for ROI):",
                   width=labelWidth,
                   anchor=E)
        l2.pack(side=LEFT)
        self._eventFileField = Pmw.EntryField(ft1Frame, value="")
        self._eventFileField.pack(side=LEFT, expand=YES, fill=X)
        b2 = Button(ft1Frame,
                    text="Browse...",
                    command=(lambda: self._getFile(self._eventFileField)))
        b2.pack(side=LEFT)
        ft1Frame.pack(side=TOP, expand=YES, fill=X)

        sigFrame = Frame(self.win)
        l3 = Label(sigFrame,
                   text="Source Significance Limit:",
                   width=labelWidth,
                   anchor=E)
        l3.pack(side=LEFT)
        self._sigLimitField = Pmw.EntryField(sigFrame, value=4)
        self._sigLimitField.pack(side=LEFT)
        sigFrame.pack(side=TOP, expand=YES, fill=X)

        galDiffFrame = Frame(self.win)
        l4 = Label(galDiffFrame,
                   text="Galactic Diffuse Model File:",
                   width=labelWidth,
                   anchor=E)
        l4.pack(side=LEFT)
        self._galDiffFileField = Pmw.EntryField(
            galDiffFrame,
            value=FERMI_DIR + "/refdata/fermi/galdiffuse/gll_iem_v06.fits")
        self._galDiffFileField.pack(side=LEFT, expand=YES, fill=X)
        b4 = Button(galDiffFrame,
                    text="Browse...",
                    command=(lambda: self._getFile(self._galDiffFileField)))
        b4.pack(side=LEFT)
        galDiffFrame.pack(side=TOP, expand=YES, fill=X)

        gdModelFrame = Frame(self.win)
        l5 = Label(gdModelFrame,
                   text="Galactic Diffuse Model Name:",
                   width=labelWidth,
                   anchor=E)
        l5.pack(side=LEFT)
        self._gdModelNameField = Pmw.EntryField(gdModelFrame, value="GAL_v06")
        self._gdModelNameField.pack(side=LEFT)
        gdModelFrame.pack(side=TOP, expand=YES, fill=X)

        isoTempFrame = Frame(self.win)
        l6 = Label(isoTempFrame,
                   text="Isotropic Template File:",
                   width=labelWidth,
                   anchor=E)
        l6.pack(side=LEFT)
        self._isoTempFileField = Pmw.EntryField(
            isoTempFrame,
            value=FERMI_DIR +
            "/refdata/fermi/galdiffuse/isotrop_4years_P7_v9_repro_source_v1.txt"
        )
        self._isoTempFileField.pack(side=LEFT, expand=YES, fill=X)
        b6 = Button(isoTempFrame,
                    text="Browse...",
                    command=(lambda: self._getFile(self._isoTempFileField)))
        b6.pack(side=LEFT)
        isoTempFrame.pack(side=TOP, expand=YES, fill=X)

        itNameFrame = Frame(self.win)
        l7 = Label(itNameFrame,
                   text="Isotropic Template Name:",
                   width=labelWidth,
                   anchor=E)
        l7.pack(side=LEFT)
        self._isoTempNameField = Pmw.EntryField(itNameFrame,
                                                value="Extragalactic Diffuse")
        self._isoTempNameField.pack(side=LEFT)
        itNameFrame.pack(side=TOP, expand=YES, fill=X)

        radFrame = Frame(self.win)
        l8 = Label(radFrame,
                   text="Variable Source Radius:",
                   width=labelWidth,
                   anchor=E)
        l8.pack(side=LEFT)
        self._radLimitField = Pmw.EntryField(radFrame, value=-1)
        self._radLimitField.pack(side=LEFT)
        radFrame.pack(side=TOP, expand=YES, fill=X)

        extTempFrame = Frame(self.win)
        self.l9 = Label(extTempFrame,
                        text="Extended Source Template Directory:",
                        width=labelWidth,
                        anchor=E,
                        state=DISABLED)
        self.l9.pack(side=LEFT)
        self._extTempFileField = Pmw.EntryField(extTempFrame,
                                                value="",
                                                entry_state=DISABLED)
        self._extTempFileField.pack(side=LEFT, expand=YES, fill=X)
        self.b7 = Button(
            extTempFrame,
            text="Browse...",
            command=(lambda: self._getDir(self._extTempFileField)),
            state=DISABLED)
        self.b7.pack(side=LEFT)

        psFrame = Frame(self.win)
        l10 = Label(psFrame,
                    text="Force Point Sources ",
                    width=labelWidth,
                    anchor=E)
        l10.pack(side=LEFT)
        self._psFlagField = Pmw.RadioSelect(
            psFrame,
            buttontype='radiobutton',
            command=self._checkForcePointSource)
        self._psFlagField.pack(side=LEFT)
        self._psFlagField.add('Yes')
        self._psFlagField.add('No')
        self._psFlagField.invoke('No')
        psFrame.pack(side=TOP, expand=YES, fill=X)

        extTempFrame.pack(side=TOP, expand=YES, fill=X)

        buttonFrame = Frame(self.win, pady=5)
        b10 = Button(buttonFrame,
                     text="Cancel",
                     command=(lambda: self._cancel()))
        b10.pack(side=LEFT)
        b8 = Button(buttonFrame,
                    text="Reset Fields",
                    command=(lambda: self._resetFields()))
        b8.pack(side=LEFT)
        b9 = Button(buttonFrame,
                    text="Import Sources",
                    command=(lambda: self._importSources()))
        b9.pack(side=RIGHT)
        buttonFrame.pack(side=TOP, expand=YES, fill=X)

    def _checkForcePointSource(self, tag):
        if ("Yes" == tag):
            self.l9.config(state=ACTIVE)
            self.b7.config(state=ACTIVE)
            self._extTempFileField.configure(entry_state=NORMAL)
        else:
            self.l9.config(state=DISABLED)
            self.b7.config(state=DISABLED)
            self._extTempFileField.configure(entry_state=DISABLED)

    def _cancel(self):
        """Cancels the dialog

        Paramters:
        - self - This AddCatalogSources Dialog object

        Return value:
        - none

        Description:
        This method simply sets the self.values variable to a None object to
        signify that no action was taken and then destroys the dialog window
        causing the getData() method to return the None object to the caller.
        """
        self.values = None
        self.win.withdraw()
        self.win.quit()

    def _getFile(self, e):
        """Fill filename field using Open File dialog

        Parameters:
        - self - This AddCatalogSourcesDialog object
        - e - The EntryField object to store the filename in

        Return value:
        - none

        Description:
        This method uses the standard Tkinter Open File dialog to allow the user
        to select a file name to associate with the passed in entry field.  If the
        user selects a file, it is store in the field.  If not file is selected, the
        entry field is not updated.
        """
        f = e.getvalue()
        if ("" == f):
            d = "."
        else:
            d = dirname(f)
        filename = askopenfilename(initialfile=f, initialdir=d)
        if (() != filename):
            e.setvalue(filename)

    def _getDir(self, e):
        """Fill directory name using Open Directory dialog

        Parameters:
        - self - This AddCatalogSourcesDialog object
        - e - The EntryField object to store the directory in

        Return value:
        - none

        Description:
        This method uses the standard Tkinter Open File dialog to allow the user
        to select a file name to associate with the passed in entry field.  If the
        user selects a file, it is store in the field.  If not file is selected, the
        entry field is not updated.
        """
        d = e.getvalue()
        if ("" == d):
            d = "."
        dirName = askdirectory(initialdir=d)
        if (() != dirName):
            e.setvalue(dirName)

    def _resetFields(self):
        """Resets all the user field values

        Parameters:
        - self - This AddCatalogSourcesDialog object

        Return value:
        - none

        Description:
        This method clears all user input and resets them to their default values.
        This method is the click handler for the "Reset Fields" button on the
        dialog box and is invoked when the button is pressed.
        """
        self._catalogFileField.setvalue("")
        self._eventFileField.setvalue("")
        self._sigLimitField.setvalue(4)
        self._galDiffFileField.setvalue(
            FERMI_DIR + "/refdata/fermi/galdiffuse/gll_iem_v06.fits")
        self._gdModelNameField.setvalue("GAL_v06")
        self._isoTempFileField.setvalue(
            FERMI_DIR +
            "/refdata/fermi/galdiffuse/isotrop_4years_P7_v9_repro_source_v1.txt"
        )
        self._isoTempNameField.setvalue("Extragalactic Diffuse")
        self._radLimitField.setvalue(-1)
        self._psFlagField.invoke('No')
        self._extTempFileField.setvalue("")

    def _importSources(self):
        """Prepares data for return to calling program

        Parameters:
        - self - This AddCatalogSourcesDialog object

        Return value:
        - none

        Description:
        This method reads the values of all the entry fields in the dialog and
        stores their values in the internal data dictionary.  It also validates
        the entries to see that 1) files exist and 2) other entries make sense.
        Validation is limited, however, and relies on upstream checking of data
        before final use.  Once the data is stored, this method closes the dialog
        box allowing the data to be returned.  This method is the click handler
        for the "Import Sources" button.
        """
        # Validate entries to make sure the files at least exist.  This should
        # only be a problem if the user typed in the entry instead of using the
        # file browser.
        validCF = isfile(self._catalogFileField.getvalue())
        validEF = isfile(self._eventFileField.getvalue())
        validGF = isfile(self._galDiffFileField.getvalue()) or (
            "" == self._galDiffFileField.getvalue())  #these are optional
        validIF = isfile(self._isoTempFileField.getvalue()) or (
            "" == self._isoTempFileField.getvalue())
        validETD = not (not isdir(self._extTempFileField.getvalue()) and
                        ("Yes" == self._psFlagField.getvalue()))
        if (validCF and validEF and validGF and validIF):
            # They are all good so load up the values and return
            self.values["catalogFile"] = self._catalogFileField.getvalue()
            self.values["eventFile"] = self._eventFileField.getvalue()
            self.values["sigLimit"] = self._sigLimitField.getvalue()
            self.values["galDiffFile"] = self._galDiffFileField.getvalue()
            self.values["gdModelName"] = self._gdModelNameField.getvalue()
            self.values["isoTempFile"] = self._isoTempFileField.getvalue()
            self.values["isTempName"] = self._isoTempNameField.getvalue()
            self.values["radiusLimit"] = self._radLimitField.getvalue()
            flag = self._psFlagField.getvalue()
            if ('Yes' == flag):
                self.values["forcePointSource"] = True
            else:
                self.values["forcePointSource"] = False
            self.values["extTempDir"] = self._extTempFileField.getvalue()

            self.win.withdraw()
            self.win.quit()
        else:
            msg = "The files listed in the following fields do not exist.  Please correct them.\n\n"
            if (not validCF):
                msg += "Source Catalog File\n"
            if (not validEF):
                msg += "Event File\n"
            if (not validGF):
                msg += "Galactic Diffuse Model File\n"
            if (not validIF):
                msg += "Isotropic Template File\n"
            if (not validETD):
                msg += "Extended Source Template Directory\n"
            Pmw.MessageDialog(self.win, message_text=msg)

    def getData(self):
        """Public method to invoke the dialog

        Parameters:
        - self - This AddCatalogSourcesDialog object

        Return value:
        - self.values - a dictionary containing all the user entered (or default)
          values for the parameters needed to import sources from the Fermi LAT
          catalogs into the current model.

        Description:
        This method invokes the _draw() method to create the dialog box, starts it
        running, and returns the data values once the dialog is closed.
        """
        self._draw()
        self.win.mainloop()
        return self.values
コード例 #28
0
def Delete_click(root, Listbox):
    if (Listbox.curselection() != ()):
        root.grab_release()
        print("Delete click")
        popup = Toplevel()
        popup.resizable(False, False)
        popup.geometry("200x100+700+300")
        popup.grab_set()

        def Cancle():
            popup.grab_release()
            root.grab_set()
            popup.destroy()

        def OK(Listbox):
            print('feature_support.OK_click')

            newrow = []
            selected = Listbox.get(ACTIVE)
            os.remove("./data/%s.mp3" % selected.split(' ----- ')[1])
            for line in fileinput.input("./data/database.csv", inplace=True):
                if line == '\n':
                    continue
                if int(line[0]) < int(selected[0]):
                    print line,
                if int(line[0]) > int(selected[0]):
                    newline = line.split()
                    newline[0] = str(int(newline[0]) - 1)
                    print " ".join(newline)
                    print '\n',
            fileinput.close()
            with open('./data/list_person.txt', 'rb') as lpfile:
                row_count = sum(1 for row in lpfile)
            os.remove('./model/net%d.xml' % int(selected[0]))
            if (row_count > 1) or (int(selected[0]) != row_count):
                for i in range(int(selected[0]) + 1, row_count + 1):
                    os.rename('./model/net%d.xml' % i,
                              './model/net%d.xml' % (i - 1))
            with open('./data/list_person.txt', 'rb') as lpfile:
                for row in lpfile:
                    if (row != []):
                        row = row.split()
                        if (int(row[0]) < int(selected[0])):
                            newrow.append(row)
                        if (int(row[0]) > int(selected[0])):
                            row[0] = int(row[0]) - 1
                            newrow.append(row)
            Listbox.delete(0, END)
            with open('./data/list_person.txt', 'wb') as lpfile:
                i = 0
                for row in newrow:
                    Listbox.insert(i, "%d ----- %s" % (int(row[0]), row[1]))
                    lpfile.write("%s %s\n" % (row[0], row[1]))
                    i += 1
            NeuralNetwork.remove_model(int(selected[0]))
            popup.destroy()
            root.grab_set()

        popup.wm_title("Delete")
        l1 = Label(popup, text="Bạn có muốn xóa !")
        b1 = Button(popup, text="OK", width=7, command=lambda: OK(Listbox))
        b2 = Button(popup, text="Cancle", width=7, command=Cancle)
        l1.place(relx=0.25, rely=0.2)
        b1.place(relx=0.18, rely=0.6)
        b2.place(relx=0.52, rely=0.6)
        popup.mainloop()
    else:
        tkMessageBox.showinfo("Error", "Vui lòng chọn đối tượng")