class PopupWindow(object):
    """This class creates a custom pop-up window to display and edit the data in an associated Log object"""

    #TODO: Refactor to pass "New Mission as a parameter"
    #TODO: Refactor to pass "add_mission(self.app, name)"
    def __init__(self, app, master, text):
        self.app = app
        self.top = Toplevel(master)
        self.top.title("New Mission")
        self.top.grab_set()             # freezes the app until the user enters or cancels

        # build the widgets
        self.label = ttk.Label(self.top, text=text, background='white')
        self.label.pack()
        self.e = ttk.Entry(self.top)
        self.e.pack()
        self.b = ttk.Button(self.top, text='Ok', command=self._cleanup)
        self.b.pack()
    #end init


    def _cleanup(self):
        """Clean up the window we created"""
        name = self.e.get()
        add_mission(self.app, name)
        self.top.grab_release()         # HAVE TO RELEASE
        self.top.destroy()
def compare(window: tk.Toplevel, image_path: str, scored_param_path: str,
            compare_num: int) -> bool:
    enhancer = ImageEnhancer(image_path)

    random.seed(0)
    player_list = [
        EnhancedPlayer(param, enhancer)
        for param in generate_random_param_list(compare_num)
    ]
    game = Tournament(player_list)

    data_writer_list = [DataWriter.ScoredParamWriter(scored_param_path)]

    canvas = CompareCanvasGroupFrame(window,
                                     game,
                                     data_writer_list=data_writer_list)
    canvas.pack()

    canvas.update_image()
    canvas.focus_set()

    window.grab_set()
    window.wait_window()

    return game.is_complete
Ejemplo n.º 3
0
class ProgressWindow:
    def __init__(self, parent, msg):
        self.parent = parent
        self.msg = msg
        self.window = None

    def start(self):
        self.window = Toplevel(self.parent.window)
        self.window.protocol('WM_DELETE_WINDOW', do_nothing)
        bar = Progressbar(self.window,
                          orient=tk.HORIZONTAL,
                          length=200,
                          mode='indeterminate')
        label = Label(self.window, text=self.msg)
        self.window.title('Proszę czekać')
        self.window.geometry('300x50')
        #self.window.lift(aboveThis=self.parent.window)
        self.window.attributes("-topmost", True)
        label.pack(side=tk.TOP)
        bar.pack(side=tk.TOP)
        bar.start(10)
        self.window.grab_set()

    def destroy(self):
        self.window.grab_release()
        self.window.destroy()
Ejemplo n.º 4
0
def ask_list_item(the_list, default_item_index=0, message=''):
    win = Toplevel()

    Label(win, text=message).pack()

    combo = Combobox(win, stat='readonly')
    combo['values'] = the_list
    combo.current(default_item_index)
    combo.pack()

    ret = [None]

    def on_ok():
        ret[0] = combo.get()
        win.quit()

    def on_cancel():
        win.quit()

    frame = Frame(win)
    frame.pack()
    Button(win, text='Cancel', command=on_cancel).pack(side='right')
    Button(win, text='Ok', command=on_ok).pack(side='right')

    win.protocol('WM_DELETE_WINDOW', win.quit)
    win.focus_set()
    win.grab_set()
    win.mainloop()
    win.destroy()

    return ret[0]
def GetAnswer(event):
    global clamp_1, clamp_2, ClampsWindow
    if clamp_num > 2:
        ClampsWindow = Toplevel(Resistor)
        ClampsWindow.grab_set()
        ClampsWindow.focus_force()
        ClampsWindow.minsize(width=200, height=160)
        ClampsWindow.maxsize(width=200, height=160)
        ClampsWindow.title('Choose clamps')

        clamp_1_info = Label(ClampsWindow,
                             text='Enter the number\nof the first clamp:')
        clamp_1_info.place(x=0, y=0, width=200, height=40)

        clamp_1 = Entry(ClampsWindow)
        clamp_1.place(x=0, y=40, width=200, height=20)

        clamp_2_info = Label(ClampsWindow,
                             text='Enter the number\nof the second clamp:')
        clamp_2_info.place(x=0, y=60, width=200, height=40)

        clamp_2 = Entry(ClampsWindow)
        clamp_2.place(x=0, y=100, width=200, height=20)

        clamp_OK_but = Button(ClampsWindow, text='OK')
        clamp_OK_but.place(x=0, y=120, width=200, height=40)
        clamp_OK_but.bind('<Button-1>', clamp_OK_action)
    else:
        GetAnswer_in_GetAnswer(0, 1)
Ejemplo n.º 6
0
 def JobFinished(self, messagePopup=True):
     self.isJobRunning = False
     self.isJobPaused = False
     self.lastSendCommandIndex = -1
     self.lastMove = None
     self.distanceTraveled = 0
     self.currentToolChange = 0
     self.currentToolPoint = 0
     self.currentColor = 'black'
     self.toolPointsLabel.config(
         text="%d/%d" % (self.currentToolPoint, self.toolPointsTotal))
     self.toolChangesLabel.config(
         text="%d/%d" % (self.currentToolChange, self.toolChangesTotal))
     self.UpdateTimeEstLabel()
     self.startButton.config(text="Start job")
     self.status.config(text="Job finished")
     timeTaken = time.time() - self.start
     # non blocking popup messagebox
     if messagePopup:
         tl = Toplevel(root)
         # this pop-up is always on top and other windows are deactivated
         tl.attributes('-topmost', 'true')
         tl.title("Job finished")
         tl.grab_set()
         frame = Frame(tl)
         frame.grid()
         Label(frame,
               text='Current job is finished and took %s.' %
               time.strftime("%H hours, %M minutes, %S seconds",
                             time.gmtime(timeTaken))).grid(row=0,
                                                           column=0,
                                                           sticky=N)
         Button(frame, text="OK", command=lambda: tl.destroy(),
                width=10).grid(row=1, column=0)
Ejemplo n.º 7
0
def inbox(text, numberonly=False):
    f = Toplevel()
    f.title(text)
    f.geometry('400x150')
    f.resizable(False, False)
    tkcenter(f)
    ttk.Label(f, text=text, font='None 15').pack(pady=10)
    sv = StringVar()

    def number_only(text):
        if str.isdigit(text):
            return True
        elif text == '':
            return True
        else:
            return False

    reg_fun = f.register(number_only)
    txt = ttk.Entry(f, font='None 15', width=35, textvariable=sv)
    if numberonly:
        txt.config(validate='key', validatecommand=(reg_fun, '%P'))
    txt.pack(pady=10)
    txt.bind('<Return>', lambda my: f.destroy())
    ttk.Style().configure('inbox.TButton', font='None 15')
    ttk.Button(f,
               text='ok',
               command=lambda: f.destroy(),
               style='inbox.TButton').pack(pady=10)
    f.grab_set()
    txt.focus()
    f.wait_window()
    return sv.get()
Ejemplo n.º 8
0
class Sobre:
    def __init__(self, master):
        self.master = master

        self.sobre_janela = Toplevel()
        self.sobre_janela.resizable(0, 0)

        self.sobre_janela.title("Sobre")
        self.sobre_janela.geometry("400x300")
        self.sobre_janela.protocol("WM_DELETE_WINDOW", self.on_close)

        self.sobre_janela.withdraw()
        self.sobre_janela.grid()
        self.sobre_janela.transient(self.master)
        self.sobre_janela.grab_set()

        sobre_frame = Frame(self.sobre_janela, relief=RAISED, borderwidth=1)
        sobre_frame.pack(fill=BOTH, expand=True)

        ok_btn = ttk.Button(self.sobre_janela, text="Ok", width=10, command=self.on_close)
        ok_btn.pack(side=RIGHT)

        # frame_kiri
        grid_frame = Frame(sobre_frame, bd=10)
        grid_frame.pack(fill=BOTH, expand=YES, side=LEFT)

        centro_(self.sobre_janela)

        self.sobre_janela.deiconify()
        self.master.wait_window(self.sobre_janela)

    def on_close(self):
        self.sobre_janela.destroy()
Ejemplo n.º 9
0
    def add_task(self):
        def ajoute(event=None):
            task = nom.get()
            if task and not CONFIG.has_option("Tasks", task):
                index = len(CONFIG.options("Tasks"))
                self.menu_tasks.insert_radiobutton(index,
                                                   label=task,
                                                   value=task,
                                                   variable=self.task)
                CONFIG.set("Tasks", task, CMAP[index % len(CMAP)])
                top.destroy()
                with open(PATH_CONFIG, "w") as file:
                    CONFIG.write(file)
                self.menu_tasks.invoke(index)
            else:
                nom.delete(0, "end")

        top = Toplevel(self)
        top.title(_("New task"))
        top.transient(self)
        top.grab_set()
        nom = Entry(top, width=20)
        nom.grid(row=0, columnspan=2, sticky="ew")
        nom.focus_set()
        nom.bind('<Key-Return>', ajoute)
        Button(top, text=_("Cancel"), command=top.destroy).grid(row=1,
                                                                column=0)
        Button(top, text=_("Ok"), command=ajoute).grid(row=1, column=1)
        top.wait_window(top)
Ejemplo n.º 10
0
def create_window_range_date():

    global date_start, date_end, top_widget
    top_widget = Toplevel()
    top_widget.geometry('300x130')
    top_widget.title('Введите период')
    #фокусируем наше окно
    #top.focus_set()
    #делаем его модальным(чтобы нельзя было переключиться на главное окно)
    top_widget.grab_set()
    #мы задаем приложению команду, что пока не будет закрыто окно top пользоваться другим окном будет нельзя.
    frame = Frame(top_widget)
    frame.pack(side=TOP, padx=10)
    user_confirmation = Button(top_widget,
                               text="Выбрать",
                               command=check_user_enter_date)
    user_confirmation.place(relx=0.45, rely=0.55)
    date_start = Entry(top_widget, width=10, font=('Arial', 10))
    date_end = Entry(top_widget, width=10, font=('Arial', 10))
    label_date_format = Label(top_widget,
                              text='Введите дату в формате: "ГОД.МЕСЯЦ.ДЕНЬ"',
                              font=('Arial', 10))
    label_from = Label(top_widget, text='От:')
    label_before = Label(top_widget, text='До:')
    date_start.place(relx=0.1, rely=0.3)
    date_end.place(relx=0.50, rely=0.3)
    label_date_format.place(relx=0.03, rely=0.10)
    label_from.place(relx=0.02, rely=0.3)
    label_before.place(relx=0.38, rely=0.3)
Ejemplo n.º 11
0
def ask_scatter_properties():
    win = Toplevel()
    win.title("Scatter Properties")

    widgets_desc = [common_prop_panel, scatter_prop_panel]
    widgets = hywidgets_to_tk(win, widgets_desc)

    color, marker, alpha = handle_common_properties(widgets)
    marker.set("o")

    widgets["ok_btn"]["command"] = win.quit

    win.protocol("WM_DELETE_WINDOW", win.quit)
    win.focus_set()
    win.grab_set()
    win.mainloop()
    win.destroy()

    marker = marker.get()

    return {
        "color": color[0],
        "marker": marker if marker else None,
        "alpha": alpha.get()
    }
Ejemplo n.º 12
0
    def file_switch(self, event=None):
        def ok(event):
            file = c.get()
            if file not in files:
                top.destroy()
            else:
                self.select(list(self.files.keys())[files.index(file)])
                top.destroy()

        def sel(event):
            self.select(list(self.files.keys())[files.index(c.get())])
            self.after(2, c.entry.focus_set)

        top = Toplevel(self)
        top.geometry('+%i+%i' % self.winfo_pointerxy())
        top.transient(self)
        top.title('File switcher')
        top.grab_set()

        files = [
            "{1} - {0}".format(*os.path.split(file))
            for file in self.files.values()
        ]
        c = AutoCompleteEntryListbox(top,
                                     completevalues=sorted(files),
                                     width=60)
        c.pack(fill='both', expand=True)
        c.entry.bind('<Escape>', lambda e: top.destroy())
        c.listbox.bind('<Escape>', lambda e: top.destroy())
        c.entry.bind('<Return>', ok)
        c.listbox.bind('<Return>', ok)
        c.bind('<<ItemSelect>>', sel)
        c.focus_set()
        return "break"
Ejemplo n.º 13
0
class OnlineView:
    def __init__(self, controleur):
        self.control = controleur
        self.jeu = None

    def show(self, fenetre):
        self.jeu = Toplevel()
        print("test")
        cadre = Frame(self.jeu)
        cadre.pack(padx=5, pady=5)

        label = Label(cadre,
                      text="Recherche d'une partie en cours...",
                      background="white",
                      font=("Courier", 25)).pack(side=TOP)
        btnCallback = Button(
            self.jeu,
            text="Annuler",
            font=("Courier", 12),
            command=lambda: [self.anulation(),
                             self.jeu.destroy()]).pack(side=BOTTOM)

        self.jeu.transient(fenetre)  # Réduction popup impossible
        self.jeu.grab_set()
        fenetre.wait_window(self.jeu)

    def anulation(self):
        self.control.rollback()

    def fermeture(self):
        self.jeu.destroy()
Ejemplo n.º 14
0
class MessageManagerWindow:
    def __init__(self, parent):
        self.master = Toplevel(parent)
        self.master.withdraw()
        self.master.geometry('+{x}+{y}'.format(x=parent.winfo_x(), y=parent.winfo_y()))
        self.master.wm_attributes("-topmost", 1)
        self.master.focus_force()
        self.master.wm_title("StreamTicker Message Manager")
        self.master.iconbitmap("imagefiles/stIcon.ico")
        self.master.resizable(False, False)
        self.master.grab_set()

        self.window = parent

        self.cancelMessages = deepcopy(self.window.messages)
        self.messages = sorted(self.window.messages, key=lambda x: x.sortOrder)

        self.mlFrame = MessageManagerListFrame(self)
        self.mlFrame.frame.grid(row=0, column=1, padx=(4, 4), pady=4)

        self.mbFrame = MessageButtonFrame(self)
        self.mbFrame.frame.grid(row=0, column=0, padx=(4, 0), pady=4)

        self.okFrame = MessageOkCancelFrame(self)
        self.okFrame.frame.grid(row=1, column=1, padx=4, pady=4, sticky=E)

        self.master.deiconify()
        self.master.mainloop()
Ejemplo n.º 15
0
    def _waitbox(self, method):
        """
        Creates a waitbox while the app is running.
        This prevents the app from hanging.
        """
        # Basic tasks to set up the waitbox Toplevel widget.
        top = Toplevel(self.parent)
        top.title("Please wait...")
        top.resizable(0, 0)
        fr = Frame(top)
        fr.pack()

        # pack the Label with the correct working mode.
        ttk.Label(
            fr,
            text=messages.waitbox_msg.format(method=method),
        ).pack(anchor='center')

        if self.parent.iconname() is not None:
            top.iconbitmap(self.parent.iconname())

        # User cannot destroy windows manually while program is running
        top.protocol('WM_DELETE_WINDOW', lambda: None)
        self.parent.protocol('WM_DELETE_WINDOW', lambda: None)
        top.transient(self.parent)
        top.focus_set()
        top.grab_set()
        return top
class ModalWindow():
    def __init__(self, tab):
        self.toplevel = Toplevel(tab.tk)
        self.toplevel.transient(tab.tk)
        self.toplevel.withdraw()
        self.toplevel.grab_release()
        self.toplevel.protocol('WM_DELETE_WINDOW', self.hide)

    def show(self):
        self.centering()
        self.toplevel.deiconify()
        self.toplevel.tkraise()
        self.toplevel.grab_set()
        self.toplevel.focus_set()

    def hide(self):
        self.toplevel.grab_release()
        self.toplevel.withdraw()

    def centering(self):
        sw = self.toplevel.winfo_screenwidth()
        rw = self.toplevel.winfo_reqwidth()
        x = (sw - rw) // 2
        sw = self.toplevel.winfo_screenheight()
        rw = self.toplevel.winfo_reqheight()
        y = (sw - rw) // 2
        self.toplevel.wm_geometry('+%i+%i' % (x, y))
def score(root: Tk, user_name: str, image_name: str, image_number: str):
    image_dir_path = root_image_dir_path / image_name / image_number / 'random_enhance_10'

    if not image_dir_path.exists():
        raise FileNotFoundError
    elif not image_dir_path.is_dir():
        raise NotADirectoryError

    game = TournamentGame(list(map(str, image_dir_path.iterdir())),
                          ImageGenerator())

    scored_image_dir = get_save_dir_path(root_scored_image_dir_path, user_name,
                                         f'{image_name}/{image_number}')
    scored_param_dir = get_save_dir_path(root_scored_param_dir_path, user_name,
                                         f'{image_name}/{image_number}')
    scored_param_path = get_save_file_path(scored_param_dir,
                                           'scored_param.json')

    data_writer_list = [
        DW_scored_image.ScoredImageWriter(str(scored_image_dir)),
        DW_scored_param.ScoredParamWriter(str(scored_param_path))
    ]

    sub_win = Toplevel(root)
    canvas = CompareCanvasGroupFrame(sub_win,
                                     game,
                                     data_writer_list=data_writer_list)
    canvas.pack()

    canvas.disp_enhanced_image()
    canvas.focus_set()

    sub_win.grab_set()
    sub_win.wait_window()
Ejemplo n.º 18
0
def delete_sarathian():
        delete=Toplevel()
        delete.title('Delete')
        delete.geometry('500x100+250+300')
        delete.grab_set()
        delete_name=tk.Label(delete,text="Enter member id  below : ",font=('helvetica',20),fg='red')
        delete_name.pack()
        delete_entry=tk.Entry(delete,width=40,font=('times new roman',20),fg='blue')
        delete_entry.focus()
        delete_entry.pack()
        def on(event):
            value=delete_entry.get()
            delete_label['text']=value
            delete_entry.delete(0,'end')
            delete.destroy()
            delete_entry.bind("<Return>",on)
        def submit():
            id=delete_entry.get()
            try:
                strr = 'delete from membersdata where id = %s'
                my_cursor.execute(strr,(id))
                con.commit()
                m_box.showinfo('Notification',f'id {id} deleted successfull...')
            except NameError:
                delete.destroy()
                m_box.showerror('Error','Please connect to Database First')
        submit=tk.Button(delete,width=6,text='Delete',command=submit,fg='black',bg='sky blue',
                         font=('calibry',20))
        submit.pack()
Ejemplo n.º 19
0
class SetupPopUp:
    """A TopLevel popup that will lock the main App and allow users to set up
    the required environmental paths to the SDSS data before unlocking the App
    again.

    Without those paths the createjobs module will likely not be able to create
    jobs.
    """
    def __init__(self, parent):
        self.top = Toplevel(parent)
        self.top.wm_title("Envionment not set up properly!")
        txt = (
            "Environment is missing BOSS and/or PHOTO_REDUX env variables.\n"
            "Please provide the PHOTO_REDUX path. See"
            "help(createjobs.setup.) for details.")

        self.explainLabel = ttk.Label(self.top, text=txt)
        self.explainLabel.pack()

        self.photoreduxSV = StringVar()
        self.pathEntry = ttk.Entry(self.top)
        self.pathEntry.pack(padx=5)

        self.okButton = ttk.Button(self.top, text="OK", command=self.ok)
        self.okButton.pack(pady=5)
        self.top.grab_set()

    def ok(self):
        """A callback function that will call the createjobs setup function,
        unlock the main app and destroy the popup.
        """
        cj.setup(self.photoreduxSV.get())
        self.top.grab_release()
        self.top.destroy()
Ejemplo n.º 20
0
def inbox1(text,
           isnumber=False
           ):  # False mean  this  function is off only work when insert True.
    f = Toplevel()
    f.title(text)
    f.geometry('400x150')
    f.resizable(False, False)
    tkcenter(f)
    ttk.Label(f, text=text, font='None 15').pack(pady=10)
    sv = StringVar()

    def onlynumber(text):
        if str.isdigit(text):
            return True
        elif text == '':
            True
        else:
            return False

    reg = f.register(onlynumber)

    txt = ttk.Entry(f, font='None 15', width=35, textvariable=sv)
    if isnumber:
        txt.config(validate='key', validatecommand=(reg, '%P'))
    txt.pack(pady=10)
    txt.bind('<Return>', lambda my: f.destroy())

    ttk.Style().configure(
        'Ali.TButton',
        font='None=15')  # setting name.TButton to custmize font when applying.
    ttk.Button(f, text='OK', command=lambda: f.destroy(), style='Ali.TButton')
    f.grab_set()
    txt.focus()
    f.wait_window()  #This method for make sure closing window before return.
    return sv.get()
Ejemplo n.º 21
0
    def messageWindow(self, title, prompt, opts=None, height=8, width=52):
        win = Toplevel(self)
        win.title(title)
        win.geometry("+%d+%d" % (self.text.winfo_rootx() + 50, self.text.winfo_rooty() + 50))
        f = Frame(win)
        # pack the button first so that it doesn't disappear with resizing
        b = Button(win, text=_('OK'), width=10, command=win.destroy, default='active', pady=2)
        b.pack(side='bottom', fill=tkinter.NONE, expand=0, pady=0)
        win.bind('<Return>', (lambda e, b=b: b.invoke()))
        win.bind('<Escape>', (lambda e, b=b: b.invoke()))
        tkfixedfont = tkFont.nametofont("TkFixedFont")
        if 'fontsize_fixed' in self.loop.options and self.loop.options['fontsize_fixed']:
            tkfixedfont.configure(size=self.loop.options['fontsize_fixed'])

        t = ReadOnlyText(
            f, wrap="word", padx=2, pady=2, bd=2, relief="sunken",
            font=tkfixedfont,
            height=height,
            width=width,
            takefocus=False)
        t.insert("0.0", prompt)
        t.pack(side='left', fill=tkinter.BOTH, expand=1, padx=0, pady=0)
        if height > 1:
            ysb = ttk.Scrollbar(f, orient='vertical', command=t.yview)
            ysb.pack(side='right', fill=tkinter.Y, expand=0, padx=0, pady=0)
            t.configure(state="disabled", yscroll=ysb.set)
            t.configure(yscroll=ysb.set)
        f.pack(padx=2, pady=2, fill=tkinter.BOTH, expand=1)

        win.focus_set()
        win.grab_set()
        win.transient(self)
        win.wait_window(win)
Ejemplo n.º 22
0
    def __init__(self, controleur, fenetre):
        self.control = controleur

        jeu = Toplevel()

        cadre = Frame(jeu)
        cadre.pack(padx=5, pady=5)

        etiquette = Label(cadre, text='temps ')
        etiquette.pack(padx=5, pady=5, side=LEFT)
        var_texte = IntVar()
        self.entree = Entry(cadre, textvariable=var_texte, width=50)

        self.entree.pack(padx=5, pady=5, side=LEFT)
        self.entree.focus_force()

        btnAffiche = Button(
            jeu,
            text='ok',
            command=lambda: [self.afficheZoneSaisie(),
                             jeu.destroy()])
        btnAffiche.pack(padx=5, pady=5)
        jeu.transient(fenetre)  # Réduction popup impossible
        jeu.grab_set()
        fenetre.wait_window(jeu)
Ejemplo n.º 23
0
def about():
    # Put the help window in front of text window
    win = Toplevel(takefocus=True)
    win.grab_set()
    # Set size and undesirable and title
    win.geometry("450x250")
    win.resizable(0, 0)
    win.wm_title("About")
    # Create the title of the About window
    title = Label(win, text=NAME, font=('Helvetica', 30), width=10)
    title.pack(fill=X)
    # Create the text under the title
    title_sub = Label(win, text=("©", NAME, "2019"), font=('Helvetica', 8))
    title_sub.pack(fill=X)
    # Add some space between header and body
    space = Label(win, text="")
    space.pack(fill=X)
    # Add the body message of the About window
    text = Label(win,
                 text=(NAME + ''' is a simple Text editor made in python.
        Please consider supporting me ♥
    '''))
    text.pack(fill=X)
    # Add a button to close the window
    button = ttk.Button(win, text="Close", command=win.destroy)
    button.pack(side='bottom', pady=20)
Ejemplo n.º 24
0
        def askSpan(orient='v'):
            win = Toplevel()
            pxmin = LabeledEntry(win)
            pxmin.pack()
            pxmin.label_text = 'xmin' if orient == 'v' else 'ymin'
            pxmax = LabeledEntry(win)
            pxmax.pack()
            pxmax.label_text = 'xmax' if orient == 'v' else 'ymax'

            def formatter(val):
                val = float(val)
                val /= 100.
                return '{0:0.2f}'.format(val)

            alphaScale = LabeledScale(win,
                                      from_=0,
                                      to=100,
                                      name='alpha',
                                      formatter=formatter)
            alphaScale.set(50.0)
            alphaScale.pack()
            win.protocol('WM_DELETE_WINDOW', win.quit)
            win.focus_set()
            win.grab_set()
            win.mainloop()
            xmin = pxmin.entry.get()
            xmax = pxmax.entry.get()
            alpha = alphaScale.get() / 100.
            win.destroy()
            return map(float, (xmin, xmax, alpha))
Ejemplo n.º 25
0
def show_predicted_results(win_percent, draw_percent, loss_percent, home_name,
                           home_color, away_name, away_color):
    msg_results = Toplevel()
    msg_results.grab_set()
    msg_results.wm_title('Prediction results')

    canvas_bars = Canvas(msg_results, width=300, height=200)

    bar_height_factor = 2
    bottom_line = 160

    canvas_bars.create_line(20, bottom_line, 280, bottom_line)

    canvas_bars.create_rectangle(20,
                                 bottom_line,
                                 80,
                                 bottom_line - win_percent * bar_height_factor,
                                 fill=home_color)
    canvas_bars.create_text(50,
                            bottom_line - win_percent * bar_height_factor - 10,
                            font='Times 10 bold',
                            text='%.2f%%' % win_percent)
    canvas_bars.create_text(50,
                            bottom_line + 10,
                            font='Times 10 bold',
                            text=home_name)

    canvas_bars.create_rectangle(120,
                                 bottom_line,
                                 180,
                                 bottom_line -
                                 draw_percent * bar_height_factor,
                                 fill='#dedede')
    canvas_bars.create_text(150,
                            bottom_line - draw_percent * bar_height_factor -
                            10,
                            font='Times 10 bold',
                            text='%.2f%%' % draw_percent)
    canvas_bars.create_text(150,
                            bottom_line + 10,
                            font='Times 10 bold',
                            text='Draw')

    canvas_bars.create_rectangle(220,
                                 bottom_line,
                                 280,
                                 bottom_line -
                                 loss_percent * bar_height_factor,
                                 fill=away_color)
    canvas_bars.create_text(250,
                            bottom_line - loss_percent * bar_height_factor -
                            10,
                            font='Times 10 bold',
                            text='%.2f%%' % loss_percent)
    canvas_bars.create_text(250,
                            bottom_line + 10,
                            font='Times 10 bold',
                            text=away_name)

    canvas_bars.pack()
Ejemplo n.º 26
0
    def change_key_mapping(self):
        def onPress(key):
            try:
                newkey = key.char
            except AttributeError:
                newkey = key.name
            if newkey == "esc":
                okVar.set(1)
                return
            if newkey == "f1":
                self.configure(text="NONE")
                okVar.set(1)
                return
            self.configure(text=newkey)
            okVar.set(1)

        def onRelease(key):
            listener.stop()

        okVar = IntVar()
        win = Toplevel()
        win.lift()
        win.focus_force()
        win.grab_set()
        win.grab_release()
        Label(
            win,
            text=
            "Press wanted Button or\nPress ESC to exit or\n Press F1 to set to none",
        ).pack()
        listener = keyboard.Listener(on_press=onPress, on_release=onRelease)
        listener.start()
        win.wait_variable(okVar)
        win.destroy()
Ejemplo n.º 27
0
    def PausePopup(self, newColor="black", trim=False):
        tl = Toplevel(root)
        tl.attributes('-topmost', 'true')
        tl.grab_set()

        tl.title("Tool change")
        msg = "change the tool for a next color"
        if trim:
            tl.title("Thread trim")
            msg = "cut the thread"

        frame = Frame(tl)
        frame.grid()

        canvas = Canvas(frame, width=64, height=64)
        canvas.grid(row=2, column=0)
        canvas.create_rectangle(0, 0, 65, 65, fill=newColor)
        msgbody = Label(
            frame,
            text=
            "There is the moment to %s. Resume the current job after change." %
            msg)
        msgbody.grid(row=1, column=0, sticky=N)

        okbttn = Button(frame,
                        text="OK",
                        command=lambda: tl.destroy(),
                        width=10)
        okbttn.grid(row=2, column=2)
Ejemplo n.º 28
0
def inbox (text,is_number_only=False):
    f = Toplevel()
    f.title(text)
    f.geometry('400x150')
    f.resizable(False,False)
    tkcenter(f)
    ttk.Label(f,text=text,font='None 15').pack(pady=10)
    sv = StringVar()
    
    def number_only (text):
         if str.isdigit(text):# fixed
             return True
         elif text is '': # يمسح اخر رقم
              return True
         else:
              return False
    reg_fun = f.register(number_only) #reg_fun not fixed

     
    txt = ttk.Entry(f,font='None 15',width=35,textvariable=sv)
    if is_number_only:

        txt.config(validate='key',validatecommand=(reg_fun, '%P'))
    txt.pack(pady=10)
    txt.bind('<Return>',lambda my:f.destroy())
    ttk.Style().configure('inbox.TButton',font='None 15') 
    ttk.Button(f,text='OK',command=lambda:f.destroy(),style='inbox.TButton').pack(pady=10)
    f.grab_set()
    txt.focus()# عشان يركز على النص اول مايغتح الشاشة
    f.wait_window()# استنى الشاشة لما تقفل
    return sv.get()#مايرجع القيمة الا بعد ما الشاشة تقفل
Ejemplo n.º 29
0
    def add_link(self):
        def ok(eveny=None):
            lien = link.get()
            txt = text.get()
            if lien:
                if not txt:
                    txt = lien
                self.nb_links += 1
                if self.txt.tag_ranges("sel"):
                    index = self.txt.index("sel.first")
                    self.txt.delete('sel.first', 'sel.last')
                else:
                    index = "current"
                tags = self.txt.tag_names(index) + ("link",
                                                    "link#%i" % self.nb_links)
                self.txt.insert("current", txt, tags)
                if not lien[:4] == "http":
                    lien = "http://" + lien
                self.links[self.nb_links] = lien
                self.txt.tag_bind("link#%i" % self.nb_links, "<Button-1>",
                                  lambda e: open_url(lien))
            top.destroy()

        top = Toplevel(self)
        top.transient(self)
        top.update_idletasks()
        top.geometry("+%i+%i" % top.winfo_pointerxy())
        top.grab_set()
        top.resizable(True, False)
        top.title(_("Link"))
        top.columnconfigure(1, weight=1)
        text = Entry(top)
        link = Entry(top)
        if self.txt.tag_ranges('sel'):
            txt = self.txt.get('sel.first', 'sel.last')
        else:
            txt = ''
        text.insert(0, txt)
        text.icursor("end")
        Label(top, text=_("Text")).grid(row=0,
                                        column=0,
                                        sticky="e",
                                        padx=4,
                                        pady=4)
        Label(top, text=_("Link")).grid(row=1,
                                        column=0,
                                        sticky="e",
                                        padx=4,
                                        pady=4)
        text.grid(row=0, column=1, sticky="ew", padx=4, pady=4)
        link.grid(row=1, column=1, sticky="ew", padx=4, pady=4)
        Button(top, text="Ok", command=ok).grid(row=2,
                                                columnspan=2,
                                                padx=4,
                                                pady=4)

        text.focus_set()
        text.bind("<Return>", ok)
        link.bind("<Return>", ok)
Ejemplo n.º 30
0
    def test_chuc_nang_tach_tu(self, event):
        top_level = Toplevel(self.root)
        tach_tu = TestTachTu(top_level, self.disk_db, self.memory_db)
        tach_tu.pack()

        top_level.grab_set()
        top_level.wait_window()
        top_level.grab_release()
Ejemplo n.º 31
0
 def on_post_merge_sql(self, *args):
     # Show post-merge-SQL dialog
     _wdw = Toplevel()
     _wdw.geometry('+400+400')
     _wdw.e = TextExtension(_wdw, textvariable=self.post_execute_sql)
     _wdw.e.pack()
     _wdw.e.focus_set()
     _wdw.transient(self.parent)
     _wdw.grab_set()
     self.parent.wait_window(_wdw)
     _wdw.e.unhook()
     del (_wdw)
Ejemplo n.º 32
0
 def __init__(self, root):
     top = Toplevel(master = root)
     top.title('Create a new HDF Datastore')
     frames = {'SelectFilename'     : 0,
               'SelectDatasetTypes' : 1,
               'SelectSearchPath'   : 2,
               'SelectParser'       : 3,
               'Options'            : 4,
               'BuildButton'        : 5}
     Grid.rowconfigure(top, frames['SelectDatasetTypes'], weight = 1)
     Grid.rowconfigure(top, frames['BuildButton'],        weight = 0)
     Grid.columnconfigure(top, 0, weight=1)
 
     # Select filename and path    
     f = self.Frame_SelectFilename(
         master = top, padx = 5, pady = 5,
         text = 'Path and filename for the new datastore')
     f.grid(row = frames['SelectFilename'], sticky = E+W)
     
     # Select dataset types
     t = self.Frame_SelectDatasetTypes(
         master = top, padx = 5, pady = 5,
         text = 'Select dataset types and configure the file reader')
     t.grid(row = frames['SelectDatasetTypes'], sticky = N+S+E+W)
     
     # Select search path
     s = self.Frame_SelectSearchPath(
         master = top, padx = 5, pady = 5,
         text = 'Directory containing input data files')
     s.grid(row = frames['SelectSearchPath'], sticky = E+W)
     
     # Select parser
     p = self.Frame_SelectParser(
         master = top, padx = 5, pady = 5,
         text = 'Select and configure the filename parser')
     p.grid(row = frames['SelectParser'], sticky = E+W)
     
     # Optional arguments for readingFromFiles
     o = self.Frame_SelectOptions(
         master = top, padx = 5, pady = 5,
         text = 'Miscellaneous build options')
     o.grid(row = frames['Options'], sticky = E+W)
     
     frameParams = (f, t, s, p, o)
     build = Button(
         master = top, text = 'Build',
         command=lambda: self._buildDatabase(self, top, frameParams))
     build.grid(row = frames['BuildButton'])
     
     # Make this window modal
     top.transient(root)
     top.grab_set()
     root.wait_window(top)
class AddRestrictionDialog:
    def __init__(self, parent):
        self.parent = parent
        self.gui = Toplevel(parent.guiRoot)
        self.gui.grab_set()
        self.gui.focus()

        self.gui.columnconfigure(0, weight=1)
        self.gui.columnconfigure(1, weight=1)

        Label(self.gui, text="Enzyme:").grid(row=0, column=0, sticky="e", padx=5)
        self.entryEnzyme = Entry(self.gui)
        self.entryEnzyme.grid(row=0, column=1, sticky="w", padx=5, pady=10)
        self.frameButtonGroup = Frame(self.gui)
        self.frameButtonGroup.grid(row=1, column=0, columnspan=2, pady=10)
        self.buttonOK = Button(self.frameButtonGroup, text=" OK ")
        self.buttonCancel = Button(self.frameButtonGroup, text=" Cancel ")
        self.buttonOK.grid(row=0, column=1, sticky="w", padx=5)
        self.buttonCancel.grid(row=0, column=0, sticky="e", padx=5)

        # Set (minimum + max) Window size
        self.gui.update()
        self.gui.minsize(self.gui.winfo_width(), self.gui.winfo_height())
        self.gui.maxsize(self.gui.winfo_width(), self.gui.winfo_height())

        self.entryEnzyme.focus()

        self.buttonOK.bind("<ButtonRelease>", self.actionOK)
        self.buttonCancel.bind("<ButtonRelease>", self.actionCancel)
        self.entryEnzyme.bind("<Return>", self.actionOK)

        self.gui.mainloop()

    #         self.gui.grab_release()
    #         self.gui.destroy()

    def actionOK(self, event):
        enzymeString = self.entryEnzyme.get()
        if enzymeString in rest_dict.keys():

            if enzymeString in self.parent.optimizer.restrictionEnzymeList:
                showinfo("", (enzymeString + " was already added to the list"))
                return

            self.parent.optimizer.restrictionEnzymeList.append(enzymeString)
            self.parent.guiRoot.event_generate("<<Update>>", when="tail")
            self.gui.destroy()
        else:
            showinfo("", (enzymeString + " is not a valid restriction enzyme"))

    def actionCancel(self, event):
        self.gui.destroy()
Ejemplo n.º 34
0
        def askgridprop():
            win = Toplevel()
            color = ['#000000', '#000000']

            propvars = [StringVar() for i in range(4)]
            guidata = (
                {
                    'linestyle': ('Major Line Style', propvars[0], None),
                    'linewidth': ('Major Line Width', propvars[1], check_nonnegative_float)
                },
                {
                    'linestyle': ('Minor Line Style', propvars[2], None),
                    'linewidth': ('Minor Line Width', propvars[3], check_nonnegative_float)
                }
            )

            for d in guidata:
                for key in d:
                    pitem = LabeledEntry(win)
                    pitem.pack()
                    pitem.label_text = d[key][0]
                    pitem.entry['textvariable'] = d[key][1]
                    if d[key][2]:
                        pitem.checker_function = d[key][2]

            def setmajorcolor():
                c = askcolor()
                color[0] = c[1]

            def setminorcolor():
                c = askcolor()
                color[1] = c[1]
                
            Button(win, text='Major Line Color', command=setmajorcolor).pack()
            Button(win, text='Minor Line Color', command=setminorcolor).pack()

            win.protocol('WM_DELETE_WINDOW', win.quit)
            win.focus_set()
            win.grab_set()
            win.mainloop()
            win.destroy()
            
            c_major = StringVar(); c_major.set(color[0])
            c_minor = StringVar(); c_minor.set(color[1])
            guidata[0]['color'] = ('Major Line Color', c_major, None)
            guidata[1]['color'] = ('Minor Line Color', c_minor, None)
            return guidata
Ejemplo n.º 35
0
    def _license(self):
        """ affiche la licence dans une nouvelle fenêtre """
        def close():
            """ ferme la fenêtre """
            self.focus_set()
            fen.destroy()

        fen = Toplevel(self)
        fen.title(_("License"))
        fen.transient(self)
        fen.protocol("WM_DELETE_WINDOW", close)
        fen.resizable(0, 0)
        fen.grab_set()
#        set_icon(fen)
        texte = Text(fen, width=50, height=18)
        texte.pack()
        texte.insert("end",
                     _("Sudoku-Tk is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\n"))
        texte.insert("end",
                     _("Sudoku-Tk is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\n"))
        texte.insert("end",
                     _("You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/."))

        i = int(texte.index("5.end").split(".")[1])
        texte.tag_add("link", "5.%i" % (i - 29), "5.%i" % (i - 1))
        texte.tag_configure("link", foreground="#0000ff", underline=1)
        texte.tag_bind("link", "<Button - 1>",
                       lambda event: webOpen("http://www.gnu.org/licenses/"))
        texte.tag_bind("link", "<Enter>",
                       lambda event: texte.config(cursor="hand1"))
        texte.tag_bind("link",
                       "<Leave>", lambda event: texte.config(cursor=""))
        texte.configure(state="disabled", wrap="word")

        b_close = Button(fen, text=_("Close"), command=close)
        b_close.pack(side="bottom")
        b_close.focus_set()
        fen.wait_window(fen)
Ejemplo n.º 36
0
    def show_stat(self):
        """ show best times """
        def reset():
            """ reset best times """
            for level in ["easy", "medium", "difficult"]:
                CONFIG.set("Statistics", level, "")
            top.destroy()

        if self.chrono_on:
            self.play_pause()
        top = Toplevel(self)
        top.transient(self)
        top.columnconfigure(1, weight=1)
        top.resizable(0, 0)

        top.title(_("Statistics"))
        top.grab_set()

        Label(top, text=_("Best times"), font="Sans 12 bold").grid(row=0, columnspan=2,
                                                                   padx=30, pady=10)

        for i, level in enumerate(["easy", "medium", "difficult"]):
            Label(top, text=_(level.capitalize()),
                  font="Sans 10 bold").grid(row=i + 1, column=0, padx=(20, 4),
                                            pady=4, sticky="e")
            tps = CONFIG.get("Statistics", level)
            if tps:
                tps = int(tps)
                m = tps // 60
                s = tps % 60
                Label(top, text=" %i min %i s" % (m, s),
                      font="Sans 10").grid(row=i + 1, column=1,
                                           sticky="w", pady=4,
                                           padx=(4, 20))
        Button(top, text=_("Close"), command=top.destroy).grid(row=4, column=0, padx=(10, 4), pady=10)
        Button(top, text=_("Clear"), command=reset).grid(row=4, column=1, padx=(4, 10), pady=10)
Ejemplo n.º 37
0
 def askSpan(orient='v'):
     win = Toplevel()
     pxmin = LabeledEntry(win)
     pxmin.pack()
     pxmin.label_text = 'xmin' if orient=='v' else 'ymin'
     pxmax = LabeledEntry(win)
     pxmax.pack()
     pxmax.label_text = 'xmax' if orient=='v' else 'ymax'
     def formatter(val):
         val = float(val)
         val /= 100.
         return '{0:0.2f}'.format(val)
     alphaScale = LabeledScale(win, from_=0, to=100, name='alpha', formatter=formatter)
     alphaScale.set(50.0)
     alphaScale.pack()
     win.protocol('WM_DELETE_WINDOW', win.quit)
     win.focus_set()
     win.grab_set()
     win.mainloop()
     xmin    = pxmin.entry.get()
     xmax    = pxmax.entry.get()
     alpha   = alphaScale.get() / 100.
     win.destroy()
     return map(float, (xmin, xmax, alpha))
Ejemplo n.º 38
0
def ask_class_name():
    win = Toplevel()
    
    module_name  = StringVar()
    class_name   = StringVar()
    
    module_item  = LabeledEntry(win)
    module_item.label_text    = 'Module Name'
    module_item.pack()
    module_item.entry_variable     = module_name
    
    class_item   = LabeledEntry(win)
    class_item.label_text     = 'Class Name'
    class_item.pack()
    class_item.entry_variable      = class_name
    
    Button(win, text='OK', command=win.quit).pack()

    win.protocol('WM_DELETE_WINDOW', win.quit)
    win.focus_set()
    win.grab_set()
    win.mainloop()
    win.destroy()
    return module_name.get(), class_name.get()
class SpeciesSearchDialog:
    def __init__(self, parent, caller):
        # main window
        self.parent = parent
        # dialog that called this second dialog
        self.caller = caller
        self.gui = Toplevel(parent.guiRoot)
        self.gui.grab_set()
        self.gui.focus()

        self.gui.columnconfigure(0, weight=1)
        self.gui.rowconfigure(1, weight=1)

        self.entrySearch = Entry(self.gui)

        self.buttonSearch = Button(self.gui, text=" Search ")
        self.buttonAdd = Button(self.gui, text=" Add Species ")
        self.buttonClose = Button(self.gui, text=" Close Window ")

        self.frameResults = Frame(self.gui)
        self.frameResults.columnconfigure(0, weight=1)
        self.frameResults.rowconfigure(0, weight=1)
        self.scrollResults = Scrollbar(self.frameResults, orient="vertical")
        self.scrollResults.grid(row=0, column=1, sticky="ns")
        self.listResults = Listbox(self.frameResults, width=70, height=20)
        self.listResults.grid(row=0, column=0, sticky="nswe")

        self.listResults.config(yscrollcommand=self.scrollResults.set)
        self.scrollResults.config(command=self.listResults.yview)

        self.entrySearch.grid(row=0, column=0, columnspan=2, sticky="we", padx=5, pady=5)
        self.frameResults.grid(row=1, column=0, columnspan=3, sticky="nswe", padx=5, pady=5)
        self.buttonSearch.grid(row=0, column=2, padx=5, pady=5, sticky="e")
        self.buttonAdd.grid(row=2, column=1, padx=5, pady=5, sticky="e")
        self.buttonClose.grid(row=2, column=2, padx=5, pady=5, sticky="e")

        self.gui.protocol("WM_DELETE_WINDOW", self.actionClose)
        self.buttonClose.bind("<ButtonRelease>", self.actionClose)
        self.buttonAdd.bind("<ButtonRelease>", self.actionAdd)
        self.buttonSearch.bind("<ButtonRelease>", self.actionSearch)
        self.entrySearch.bind("<Return>", self.actionSearch)

        self.gui.update()
        self.gui.minsize(self.gui.winfo_width(), self.gui.winfo_height())

        self.gui.mainloop()

    def actionAdd(self, event):
        try:
            selection = self.listResults.selection_get()
            selectionSplit = selection.split(":\t", 1)
            selectionSplit2 = selectionSplit[1].split("\t")
            if not (selectionSplit[0], selectionSplit2[0]) in self.parent.optimizer.speciesList:
                self.parent.optimizer.speciesList.append((selectionSplit[0], selectionSplit2[0].strip()))
            self.caller.gui.event_generate("<<Update>>")
        except tkinter.TclError:
            # no selection
            pass

    def actionSearch(self, event):
        query = self.entrySearch.get()
        if query:

            self.listResults.delete(0, "end")

            results = self.parent.optimizer.SPSUMHandler.search(query)
            # sort results by nr of CDS
            results = sorted(results.items(), reverse=True, key=lambda x: (int(x[1][1])))
            for name, (taxid, ncs) in results:
                self.listResults.insert("end", taxid + ":\t " + name + " \t(" + ncs + " CDS)")

    def actionClose(self, event=None):
        self.caller.gui.event_generate("<<Update>>", when="tail")
        self.gui.destroy()
Ejemplo n.º 40
-1
class SpeciesListDialog:
    def __init__(self, parent):
        self.parent = parent
        self.gui = Toplevel(parent.guiRoot)
        self.gui.grab_set()
        self.gui.focus()

        self.gui.columnconfigure(0, weight=1)
        self.gui.rowconfigure(1, weight=1)

        Label(self.gui, text="Registered Species:").grid(row=0, column=0, pady=5, padx=5, sticky="w")
        self.listRegisteredSpecies = Listbox(self.gui, width=70)
        self.buttonAdd = Button(self.gui, text=" + ")
        self.buttonDel = Button(self.gui, text=" - ")
        self.listRegisteredSpecies.grid(row=1, column=0, columnspan=3, sticky="nswe", pady=5, padx=5)
        self.buttonAdd.grid(row=2, column=1, pady=5, padx=5)
        self.buttonDel.grid(row=2, column=2, pady=5, padx=5)

        # Set (minimum + max) Window size
        self.gui.update()
        self.gui.minsize(self.gui.winfo_width(), self.gui.winfo_height())
        #         self.gui.maxsize(self.gui.winfo_width(), self.gui.winfo_height())

        self.actionUpdate(None)
        self.gui.bind("<<Update>>", self.actionUpdate)
        self.gui.protocol("WM_DELETE_WINDOW", self.actionClose)

        self.buttonDel.bind("<ButtonRelease>", self.actionDel)
        self.buttonAdd.bind("<ButtonRelease>", self.actionAdd)

        self.gui.mainloop()

    def actionClose(self):
        self.parent.guiRoot.event_generate("<<Update>>", when="tail")
        self.gui.destroy()

    def actionUpdate(self, event):
        self.listRegisteredSpecies.delete(0, "end")
        for (taxid, name) in self.parent.optimizer.speciesList:
            self.listRegisteredSpecies.insert("end", taxid + ": " + name)

    def actionDel(self, event):
        try:
            selection = self.listRegisteredSpecies.selection_get()
            selectionSplit = selection.split(": ")
            self.parent.optimizer.speciesList.remove((selectionSplit[0], selectionSplit[1]))
            self.gui.event_generate("<<Update>>")
        except tkinter.TclError:
            # no selection
            pass

    def actionAdd(self, Event):
        SpeciesSearchDialog(self.parent, self)