Пример #1
0
def _io_binding(parent):  # htest #
    from tkinter import Toplevel, Text
    from idlelib.configHandler import idleConf

    root = Toplevel(parent)
    root.title("Test IOBinding")
    width, height, x, y = list(map(int, re.split('[x+]', parent.geometry())))
    root.geometry("+%d+%d"%(x, y + 150))
    class MyEditWin:
        def __init__(self, text):
            self.text = text
            self.flist = None
            self.text.bind("<Control-o>", self.open)
            self.text.bind("<Control-s>", self.save)
        def get_saved(self): return 0
        def set_saved(self, flag): pass
        def reset_undo(self): pass
        def open(self, event):
            self.text.event_generate("<<open-window-from-file>>")
        def save(self, event):
            self.text.event_generate("<<save-window>>")

    text = Text(root)
    text.pack()
    text.focus_set()
    editwin = MyEditWin(text)
    IOBinding(editwin)
Пример #2
0
    def __init__(self, master, text, *args, **kwargs):
        self.master = master
        Toplevel.__init__(self, master, *args, **kwargs)

        # Setup text box.
        self.text = Text(self, width=60, height=20, wrap=NONE)
        self.text.insert("1.0", text)
        self.text["state"] = "disabled"
        self.text.grid(row=0, column=0, sticky="NESW")

        # Create a vertical scrollbar.
        scrolly = Scrollbar(self, orient="vertical",
                            command=self.text.yview)
        scrolly.grid(row=0, column=1, sticky="NS")

        # Create a horizontal scrollbar.
        scrollx = Scrollbar(self, orient="horizontal",
                            command=self.text.xview)
        scrollx.grid(row=1, column=0, columnspan=2, sticky="EW")

        # Add the scroll bars.
        self.text.configure(yscrollcommand=scrolly.set,
                            xscrollcommand=scrollx.set)

        # Setup special configurings.
        self.transient(master)
        self.protocol("WM_DELETE_WINDOW", self.cancel)
        self.grab_set()
        self.focus_set()
        self.wait_window(self)
Пример #3
0
    def __init__(self, parent):
        Toplevel.__init__(self, parent)
        self.configure(borderwidth=0)
        self.geometry("+%d+%d" % (
                        parent.winfo_rootx()+30,
                        parent.winfo_rooty()+30))

        self.vbar = Scrollbar(self)
        self.text = Text(self, wrap='word', borderwidth='0p')
        self.vbar['command'] = self.text.yview
        self.vbar.pack(side=RIGHT, fill='y')
        self.text['yscrollcommand'] = self.vbar.set
        self.text.pack(expand=1, fill="both")
        try:
            f = open(README_PATH)
            self.text.delete(1.0)
            self.text.insert(1.0, f.read())
            self.text.delete('end - 1 chars')
        except:
            showerror("Error", "Cannot load README!")
        self.text.config(state='disabled')

        self.title('README')
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.parent = parent
        self.bind('<Escape>', self.close)
Пример #4
0
def _color_delegator(parent):  # htest #
    from tkinter import Toplevel, Text
    from idlelib.percolator import Percolator

    top = Toplevel(parent)
    top.title("Test ColorDelegator")
    x, y = map(int, parent.geometry().split('+')[1:])
    top.geometry("700x250+%d+%d" % (x + 20, y + 175))
    source = ("# Following has syntax errors\n"
        "if True: then int 1\nelif False: print 0\nelse: float(None)\n"
        "if iF + If + IF: 'keywork matching must respect case'\n"
        "# All valid prefixes for unicode and byte strings should be colored\n"
        "'x', '''x''', \"x\", \"\"\"x\"\"\"\n"
        "r'x', u'x', R'x', U'x', f'x', F'x', ur'is invalid'\n"
        "fr'x', Fr'x', fR'x', FR'x', rf'x', rF'x', Rf'x', RF'x'\n"
        "b'x',B'x', br'x',Br'x',bR'x',BR'x', rb'x'.rB'x',Rb'x',RB'x'\n")
    text = Text(top, background="white")
    text.pack(expand=1, fill="both")
    text.insert("insert", source)
    text.focus_set()

    color_config(text)
    p = Percolator(text)
    d = ColorDelegator()
    p.insertfilter(d)
Пример #5
0
    def __init__(self, master, **options):
        """ créer le Toplevel 'À propos de Sudoku-Tk' """
        Toplevel.__init__(self, master, class_="Sudoku-Tk", **options)

        self.title(_("About Sudoku-Tk"))
        self.transient(master)
        self.grab_set()
#        set_icon(self)
        self.image = open_image(ICONE_48)
        Label(self, image=self.image).grid(row=0, columnspan=2, pady=10)

        Label(self,
                  text=_("Sudoku-Tk %(version)s")
                  % ({"version": VERSION})).grid(row=1, columnspan=2)
        Label(self, text=_("Sudoku games and puzzle solver")).grid(row=2, columnspan=2, padx=10)
        Label(self, text="Copyright (C) Juliette Monsel 2016-2018").grid(row=3, columnspan=2)
        Label(self, text="*****@*****.**").grid(row=4, columnspan=2)
        Button(self, text=_("License"), command=self._license).grid(row=5, column=0, pady=(20, 10), padx=(10,4))
        Button(self, text=_("Close"), command=self._quitter).grid(row=5, column=1, pady=(20, 10), padx=(4,10))

        self.initial_focus = self

        self.protocol("WM_DELETE_WINDOW", self._quitter)
        self.resizable(0, 0)
        self.initial_focus.focus_set()
        self.wait_window(self)
Пример #6
0
    def __init__(self,parent):
        Toplevel.__init__(self) 
        self.transient(parent)
        self.focus()

        sw = parent.winfo_screenwidth()
        sh = parent.winfo_screenheight()
        self.geometry('%dx%d+%d+%d' % (sw/2, sh/2, sw/4, sh/4))
        self.grab_set()
        self.title("Settings")

        self.modeNotebook = Notebook(self)
        self.modeNotebook.pack(fill=BOTH, expand=True)

        self.addFrame = AddSettingsFrame(self.modeNotebook, self)
        self.addFrame.pack(fill=BOTH, expand=True)

        self.editFrame = EditSettingsFrame(self.modeNotebook, self)
        self.editFrame.pack(fill=BOTH, expand=True)

        self.deleteFrame = DeleteSettingsFrame(self.modeNotebook, self)
        self.deleteFrame.pack(fill=BOTH, expand=True)

        self.modeNotebook.add(self.addFrame, text='Add')
        self.modeNotebook.add(self.editFrame, text='Edit')
        self.modeNotebook.add(self.deleteFrame, text='Delete')

        self.addFrame.setupFrame()
        self.editFrame.setupFrame()
        
        self.wait_window()
Пример #7
0
    def __init__(self):
        Toplevel.__init__(self)
        self.focus_set()
        self.grab_set()

        self.result = None
        self.module_data = None
        self.mod_applis = None
        self.title(ugettext("Instance editor"))
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(0, weight=1)

        self.ntbk = ttk.Notebook(self)
        self.ntbk.grid(row=0, column=0, columnspan=1, sticky=(N, S, E, W))

        self.frm_general = Frame(self.ntbk, width=350, height=150)
        self.frm_general.grid_columnconfigure(0, weight=0)
        self.frm_general.grid_columnconfigure(1, weight=1)
        self._general_tabs()
        self.ntbk.add(self.frm_general, text=ugettext('General'))

        self.frm_database = Frame(self.ntbk, width=350, height=150)
        self.frm_database.grid_columnconfigure(0, weight=0)
        self.frm_database.grid_columnconfigure(1, weight=1)
        self._database_tabs()
        self.ntbk.add(self.frm_database, text=ugettext('Database'))

        btnframe = Frame(self, bd=1)
        btnframe.grid(row=1, column=0, columnspan=1)
        Button(btnframe, text=ugettext("OK"), width=10, command=self.apply).grid(
            row=0, column=0, sticky=(N, S, E))
        Button(btnframe, text=ugettext("Cancel"), width=10, command=self.destroy).grid(
            row=0, column=1, sticky=(N, S, W))
Пример #8
0
 def helpAbout(self):
     print("Digital Cookbook v1.0 - Theodore Lindsey")
     aboutDialog = Toplevel()
     aboutDialog.geometry("200x100+300+300")
     aboutDialog.title("About Digital Cookbook")
     Message(aboutDialog, text="Digital Cookbook v1.0\nTheodore Lindsey").pack(side=TOP, fill=BOTH, expand=1)
     Button(aboutDialog, text="Ok", command=aboutDialog.destroy).pack(side=TOP)
Пример #9
0
    def __init__(self, client):
        # Basic setup
        super(Preferences, self).__init__()
        self.client = client

        # Setup the variables used
        self.echo_input = BooleanVar()
        self.echo_input.set(self.client.config['UI'].getboolean('echo_input'))
        self.echo_input.trace("w", self.echo_handler)
        self.logging = BooleanVar()
        self.logging.set(self.client.config['logging'].getboolean('log_session'))
        self.logging.trace('w', self.logging_handler)
        self.log_dir = self.client.config['logging']['log_directory']

        # Build the actual window and widgets
        prefs = Toplevel(self)
        prefs.wm_title("Preferences")
        echo_input_label = Label(prefs, text="Echo Input:")
        logging_label = Label(prefs, text='Log to file:')
        echo_checkbox = Checkbutton(prefs, variable=self.echo_input)
        logging_checkbox = Checkbutton(prefs, variable=self.logging)
        logging_button_text = 'Choose file...' if self.log_dir == "" else self.log_dir
        logging_button = Button(prefs, text=logging_button_text, command=self.logging_pick_location)

        # Pack 'em in.
        echo_input_label.grid(row=0, column=0)
        echo_checkbox.grid(row=0, column=1)
        logging_label.grid(row=1, column=0)
        logging_checkbox.grid(row=1, column=1)
        logging_button.grid(row=1, column=2)
Пример #10
0
    def __init__(self, app, kind='', icon_file=None, center=True):
        Toplevel.__init__(self)
        self.__app = app
        self.configBorders(app, kind, icon_file)

        if center:
            pass
Пример #11
0
def _replace_dialog(parent):  # htest #
    from tkinter import Toplevel, Text
    from tkiter.ttk import Button

    box = Toplevel(parent)
    box.title("Test ReplaceDialog")
    x, y = map(int, parent.geometry().split('+')[1:])
    box.geometry("+%d+%d" % (x, y + 175))

    # mock undo delegator methods
    def undo_block_start():
        pass

    def undo_block_stop():
        pass

    text = Text(box, inactiveselectbackground='gray')
    text.undo_block_start = undo_block_start
    text.undo_block_stop = undo_block_stop
    text.pack()
    text.insert("insert","This is a sample sTring\nPlus MORE.")
    text.focus_set()

    def show_replace():
        text.tag_add(SEL, "1.0", END)
        replace(text)
        text.tag_remove(SEL, "1.0", END)

    button = Button(box, text="Replace", command=show_replace)
    button.pack()
Пример #12
0
def _io_binding(parent):  # htest #
    from tkinter import Toplevel, Text

    root = Toplevel(parent)
    root.title("Test IOBinding")
    x, y = map(int, parent.geometry().split('+')[1:])
    root.geometry("+%d+%d" % (x, y + 175))
    class MyEditWin:
        def __init__(self, text):
            self.text = text
            self.flist = None
            self.text.bind("<Control-o>", self.open)
            self.text.bind('<Control-p>', self.print)
            self.text.bind("<Control-s>", self.save)
            self.text.bind("<Alt-s>", self.saveas)
            self.text.bind('<Control-c>', self.savecopy)
        def get_saved(self): return 0
        def set_saved(self, flag): pass
        def reset_undo(self): pass
        def open(self, event):
            self.text.event_generate("<<open-window-from-file>>")
        def print(self, event):
            self.text.event_generate("<<print-window>>")
        def save(self, event):
            self.text.event_generate("<<save-window>>")
        def saveas(self, event):
            self.text.event_generate("<<save-window-as-file>>")
        def savecopy(self, event):
            self.text.event_generate("<<save-copy-of-window-as-file>>")

    text = Text(root)
    text.pack()
    text.focus_set()
    editwin = MyEditWin(text)
    IOBinding(editwin)
Пример #13
0
def _color_delegator(parent):  # htest #
    from tkinter import Toplevel, Text
    from idlelib.percolator import Percolator

    top = Toplevel(parent)
    top.title("Test ColorDelegator")
    x, y = map(int, parent.geometry().split('+')[1:])
    top.geometry("700x250+%d+%d" % (x + 20, y + 175))
    source = (
        "if True: int ('1') # keyword, builtin, string, comment\n"
        "elif False: print(0)\n"
        "else: float(None)\n"
        "if iF + If + IF: 'keyword matching must respect case'\n"
        "if'': x or''  # valid string-keyword no-space combinations\n"
        "# All valid prefixes for unicode and byte strings should be colored.\n"
        "'x', '''x''', \"x\", \"\"\"x\"\"\"\n"
        "r'x', u'x', R'x', U'x', f'x', F'x'\n"
        "fr'x', Fr'x', fR'x', FR'x', rf'x', rF'x', Rf'x', RF'x'\n"
        "b'x',B'x', br'x',Br'x',bR'x',BR'x', rb'x'.rB'x',Rb'x',RB'x'\n"
        "# Invalid combinations of legal characters should be half colored.\n"
        "ur'x', ru'x', uf'x', fu'x', UR'x', ufr'x', rfu'x', xf'x', fx'x'"
        )
    text = Text(top, background="white")
    text.pack(expand=1, fill="both")
    text.insert("insert", source)
    text.focus_set()

    color_config(text)
    p = Percolator(text)
    d = ColorDelegator()
    p.insertfilter(d)
Пример #14
0
    def __init__(self, parent, title=None):
        Toplevel.__init__(self, parent)
        self.transient(parent)

        if title:
            self.title(title)

        self.parent = parent
        self.result = None

        body = Frame(self)
        self.initial_focus = self.body(body)
        body.pack(padx=5, pady=5)
        self.buttonbox()
        self.grab_set()

        if not self.initial_focus:
            self.initial_focus = self

        self.protocol("WM_DELETE_WINDOW", self.cancel)
        self.geometry("+%d+%d" % (parent.winfo_rootx() + 50,
                                  parent.winfo_rooty() + 50))
        self.initial_focus.focus_set()

        self.wait_window(self)
Пример #15
0
    def __init__(self, parent, title=None, *, _htest=False, _utest=False):
        """Create popup, do not return until tk widget destroyed.

        parent - parent of this dialog
        title - string which is title of popup dialog
        _htest - bool, change box location when running htest
        _utest - bool, don't wait_window when running unittest
        """
        Toplevel.__init__(self, parent)
        self.configure(borderwidth=5)
        # place dialog below parent if running htest
        self.geometry("+%d+%d" % (
                        parent.winfo_rootx()+30,
                        parent.winfo_rooty()+(30 if not _htest else 100)))
        self.bg = "#bbbbbb"
        self.fg = "#000000"
        self.create_widgets()
        self.resizable(height=False, width=False)
        self.title(title or
                   f'About IDLE {python_version()} ({build_bits()} bit)')
        self.transient(parent)
        self.grab_set()
        self.protocol("WM_DELETE_WINDOW", self.ok)
        self.parent = parent
        self.button_ok.focus_set()
        self.bind('<Return>', self.ok)  # dismiss dialog
        self.bind('<Escape>', self.ok)  # dismiss dialog
        self._current_textview = None
        self._utest = _utest

        if not _utest:
            self.deiconify()
            self.wait_window()
Пример #16
0
 def __init__(self, parent, case, val_ou_pos, **options):
     """ créer le Toplevel 'À propos de Bracelet Generator' """
     Toplevel.__init__(self, parent, **options)
     self.withdraw()
     self.type = val_ou_pos  # clavier pour rentrer une valeur ou une possibilité
     self.overrideredirect(True)
     self.case = case
     self.transient(self.master)
     self.style = Style(self)
     self.style.configure("clavier.TButton", font="Arial 12")
     self.boutons = [[Button(self, text="1", width=2, style="clavier.TButton", command=lambda: self.entre_nb(1)),
                      Button(self, text="2", width=2, style="clavier.TButton", command=lambda: self.entre_nb(2)),
                      Button(self, text="3", width=2, style="clavier.TButton", command=lambda: self.entre_nb(3))],
                     [Button(self, text="4", width=2, style="clavier.TButton", command=lambda: self.entre_nb(4)),
                      Button(self, text="5", width=2, style="clavier.TButton", command=lambda: self.entre_nb(5)),
                      Button(self, text="6", width=2, style="clavier.TButton", command=lambda: self.entre_nb(6))],
                     [Button(self, text="7", width=2, style="clavier.TButton", command=lambda: self.entre_nb(7)),
                      Button(self, text="8", width=2, style="clavier.TButton", command=lambda: self.entre_nb(8)),
                      Button(self, text="9", width=2, style="clavier.TButton", command=lambda: self.entre_nb(9))]]
     for i in range(3):
         for j in range(3):
             self.boutons[i][j].grid(row=i, column=j)
     self.protocol("WM_DELETE_WINDOW", self.quitter)
     self.resizable(0, 0)
     self.attributes("-topmost", 0)
Пример #17
0
def display_image(title,image):
    win = Toplevel(root)
    photo = ImageTk.PhotoImage(image)
    win.title(title)
    label = Label(win,image=photo)
    label.image = photo #Kludge: keep a reference to avoid garbage collection!
    label.pack()
Пример #18
0
    def __init__(self, parent, title, message, *, _htest=False, _utest=False):  # Call from override.
        """Create popup, do not return until tk widget destroyed.

        Additional subclass init must be done before calling this.

        title - string, title of popup dialog
        message - string, informational message to display
        _htest - bool, change box location when running htest
        _utest - bool, leave window hidden and not modal
        """
        Toplevel.__init__(self, parent)
        self.configure(borderwidth=5)
        self.resizable(height=FALSE, width=FALSE)
        self.title(title)
        self.transient(parent)
        self.grab_set()
        self.bind("<Key-Return>", self.ok)
        self.protocol("WM_DELETE_WINDOW", self.cancel)
        self.parent = parent
        self.message = message
        self.create_widgets()
        self.update_idletasks()
        # needs to be done here so that the winfo_reqwidth is valid
        self.withdraw()  # Hide while configuring, especially geometry.
        self.geometry(
            "+%d+%d"
            % (
                parent.winfo_rootx() + (parent.winfo_width() / 2 - self.winfo_reqwidth() / 2),
                parent.winfo_rooty()
                + ((parent.winfo_height() / 2 - self.winfo_reqheight() / 2) if not _htest else 150),
            )
        )  # centre dialog over parent (or below htest box)
        if not _utest:
            self.deiconify()  # geometry set, unhide
            self.wait_window()
Пример #19
0
 def destroy(self):
     registry.delete(self)
     Toplevel.destroy(self)
     # If this is Idle's last window then quit the mainloop
     # (Needed for clean exit on Windows 98)
     if not registry.dict:
         self.quit()
Пример #20
0
def toplevel(parent, title):
    t = Toplevel(parent, borderwidth=8)
    t.title(title)
    x = parent.winfo_rootx()
    y = parent.winfo_rooty()
    t.geometry('+{}+{}'.format(x+4, y+4))
    return t
Пример #21
0
 def __init__(self, parent=None, title="", message="", button="Ok", image=None, **options):
     """
         Create a message box with one button:
             parent: parent of the toplevel window
             title: message box title
             message: message box text
             button: message displayed on the button
             image: image displayed at the left of the message
             **options: other options to pass to the Toplevel.__init__ method
     """
     Toplevel.__init__(self, parent, **options)
     self.transient(parent)
     self.resizable(False, False)
     self.title(title)
     if image:
         Label(self, text=message, wraplength=335,
               font="Sans 11", compound="left", image=image).grid(row=0, padx=10, pady=10)
     else:
         Label(self, text=message, wraplength=335,
               font="Sans 11").grid(row=0, padx=10, pady=10)
     b = Button(self, text=button, command=self.destroy)
     b.grid(row=1, padx=10, pady=10)
     self.grab_set()
     b.focus_set()
     self.wait_window(self)
Пример #22
0
    def __init__(self, string_var, *args, **kwargs):
        Toplevel.__init__(self, *args, **kwargs)

        self.wm_title('SUDO Password')

        Label(master = self,
              text   = 'Root password:'******'*')

        def set_pass(*args, **kwargs):
            string_var.set(input.get())
            self.destroy()

        input.bind('<KeyRelease-Return>', set_pass)
        #input.pack(side=TOP, fill=BOTH, expand=True)
        input.pack()
        input.focus_set()

        Button(master  = self,
               text    = 'Cancel',
               command = self.destroy).pack()

        Button(master  = self,
               text    = 'OK',
               command = set_pass).pack()
Пример #23
0
 def __init__(self, parent, filename, title):
     Toplevel.__init__(self, parent)
     self.wm_title(title)
     self.protocol("WM_DELETE_WINDOW", self.destroy)
     HelpFrame(self, filename).grid(column=0, row=0, sticky='nsew')
     self.grid_columnconfigure(0, weight=1)
     self.grid_rowconfigure(0, weight=1)
Пример #24
0
	def __init__( self, module ):
		Toplevel.__init__( self )
		self.attributes("-alpha", 0.5)
		self.module = module
		self.entry = Entry( self, text = module.id[0] )
		self.entry.grid()
		
		self.bind( "<Return>", self.submit )
Пример #25
0
 def __init__(self, trains, time, stop, master=None):
     Toplevel.__init__(self, master, bg="black")
     # self.title("CTA Train Tracker ")
     self.driv = driver.Driver()
     self.tra = trains
     self.tim = time
     self.stop = stop
     times.make_widgets(self)
Пример #26
0
 def __init__(self, dictionary, linein, master=None):
     Toplevel.__init__(self, master,  bg='black')
     #self.title("CTA Train Tracker ")
     self.driv = driver.Driver()
     self.linein = linein
     self.line = self.linein.split()
     self.stored = dictionary
     stops.make_widgets(self)
Пример #27
0
    def __init__(self, message, *args, **kwargs):
        Toplevel.__init__(self, *args, **kwargs)

        Label(master = self,
              text   = message).pack()
        Button(master  = self,
               text    = 'OK',
               command = self.destroy)
 def popWidget( self, function ):
     _geo = self.parent.geometry()
     _x = str( int( _geo.split('+')[1] ) + 200 )
     _y = str( int( _geo.split('+')[2] ) + 200 )
     return_val = list()
     entry_root = Toplevel()
     entry_root.geometry('+' + _x + '+' + _y )
     entry_widget = EntryWidget( entry_root, function )
class MailListWindow:
    def __init__(self, title, after_close):
        self.win = Toplevel()
        self.win.title(title)
        self.win.geometry('400x200')
        self.win.wm_attributes('-toolwindow', True)
        self.win.protocol("WM_DELETE_WINDOW", after_close)
        
        inner_frame = tk.Frame(self.win)#inner_frame = tk.Frame(canvas)
        inner_frame.pack(side='left', fill='both', expand = 1)
        scrollbar = tk.Scrollbar(self.win,orient="vertical",command=self.scrolly)
        scrollbar.pack(side='right', fill='y')
        
        self.btn_count = 0
        self.btns = []
        self.texts = []
        self.callbacks = []
        self.frame = inner_frame
        self.scrollbar = scrollbar
        self.btn_per_page = 4
        self.first_btn = 0
        self.scrolly('', '0.0')
        
    def scrolly(self, cmd, pos, what=''):
        if self.btn_per_page <= self.btn_count:
            bar_len = self.btn_per_page/self.btn_count
        else:
            bar_len=1
        self.first_btn = int(float(pos)*self.btn_count)
        pos = str(self.getScrollPos())
        self.scrollbar.set(pos, str(float(pos)+bar_len))
        for i in range(len(self.btns)):
            mail_index = i+self.first_btn
            self.btns[i].config(text=self.texts[mail_index], command=self.callbacks[mail_index])
    
    def insertButton(self, text, callback):
        if self.btn_count < self.btn_per_page:
            btn = tk.Button(self.frame, bg='#fafafa',text=text, command=callback)
            btn.pack(fill='both', expand=1)
            self.btns.append(btn)
            
        self.btn_count += 1
        self.texts.append(text) 
        self.callbacks.append(callback)
        self.scrolly('', self.getScrollPos())
        
    def getScrollPos(self):
        if self.btn_per_page >= self.btn_count:
            return 0.0
        if self.btn_count == 0:
            return 0.0
        return self.first_btn/self.btn_count
        
    def callback(self):
        print('click')
        
    def destroy(self):
        self.win.destroy()
Пример #30
0
 def __init__(self, parent, name):
     Toplevel.__init__(self)
     self.parent = parent
     self.title = name
     self.entries = {"Entry":{}, "Text":{}}
     self.resizable(0,0)
     self.frame = Frame(self)
     self.init_ui()
     self.frame.pack(side="right", fill="y", expand=True)
class InstallWindow:
    def __init__(self, setpath, installpath, systemwide, type='install'):
        global root
        self.setpath = setpath
        self.installpath = installpath
        self.systemwide = systemwide

        self.type = type

        self.master = Toplevel(root)
        self.master.withdraw()
        self.master.protocol('WM_DELETE_WINDOW', self.close)
        self.master.iconbitmap(imgdir)
        self.master.title('Adb & Fastboot installer - By @Pato05')
        self.master.geometry("600x400")
        self.master.resizable(False, False)
        frame = Frame(self.master, relief=FLAT)
        frame.pack(padx=10, pady=5, fill=BOTH)
        Label(frame, text='Please wait while Adb and Fastboot are getting %s...' % (
            'updated' if type == 'update' else 'installed on your PC')).pack(fill=X)
        self.mode = 'unksize'
        self.progressbar = Progressbar(
            frame, orient=HORIZONTAL, length=100, mode='indeterminate')
        self.progressbar.pack(fill=X)
        self.progressbar.start(20)
        self.downloaded = 0
        self.progressv = Text(frame, bd=0, insertborderwidth=0,
                              state='disabled', background='#f0f0ed', font=('Segoe UI', 10))
        self.progressv.pack(fill=BOTH, pady=(10, 5))
        self.master.deiconify()
        self.downloading = threading.Thread(target=self.download)
        self.downloading.start()

    def download_progress(self, count, block_size, total_size):
        if total_size != -1 and self.mode != 'ksize':
            self.mode = 'ksize'
            self.progressbar.stop()
            self.progressbar.configure(mode='determinate', maximum=total_size)
        elif total_size == -1 and self.mode != 'unksize':
            self.mode = 'unksize'
            self.progressbar.configure(mode='indeterminate')
        if self.mode == 'ksize':
            self.downloaded += block_size
            self.progressbar.step(block_size)
            if self.downloaded == total_size:
                self.progress('Download ended.')

    def download(self):
        self.pathres = False
        self.progress('Downloading Adb and Fastboot...', False)
        from urllib.request import urlretrieve
        import urllib.error
        workingdir = scriptdir
        download = os.path.join(workingdir, 'pt.zip')
        try:
            urlretrieve('https://dl.google.com/android/repository/platform-tools-latest-windows.zip',
                        download, self.download_progress)
        except (urllib.error.HTTPError, urllib.error.URLError) as e:
            messagebox.showerror(title='Adb & Fastboot Uninstaller',
                                 message='Failed while trying to download Adb and Fastboot. Are you connected to the internet?\nError: %s' % e)
            self.error_close()
            return False
        self.progressbar.configure(
            mode='indeterminate', maximum=150, length=400, value=0)
        self.progressbar.start(20)
        self.progress('Extracting Adb and Fastboot...')
        from zipfile import ZipFile
        with ZipFile(download) as z:
            z.extractall(workingdir)
        os.remove(download)
        self.progress('Moving Adb and Fastboot to destination folder...')
        if(os.path.isdir(self.installpath)):
            rmtree(self.installpath)
            sleep(0.1)
        os.mkdir(self.installpath)
        for file in ['adb.exe', 'AdbWinApi.dll', 'AdbWinUsbApi.dll', 'fastboot.exe']:
            self.progress("Moving %s..." % file)
            copyfile(os.path.join(workingdir, 'platform-tools', file), os.path.join(self.installpath, file))
        rmtree(os.path.join(workingdir, 'platform-tools'))
        if self.setpath == 1:
            self.progress('Adding Adb & Fastboot into %s\'s path' %
                          ('system' if self.systemwide == 1 else 'user'))
            self.pathres = addToPath(self.installpath, self.systemwide == 1)
            self.progress(
                'Successfully added Adb & Fastboot into path' if self.pathres else 'Failed to add Adb & Fastboot into path')
        self.progressbar.stop()
        self.finish()

    def finish(self):
        self.app = FinishWindow(
            self.setpath, self.pathres, self.installpath, self.type)
        self.master.destroy()

    def progress(self, what, lb=True):
        self.progressv.configure(state='normal')
        self.progressv.insert(END, ('\r\n' if lb else '')+what)
        self.progressv.configure(state='disabled')

    def error_close(self):
        global root
        root.destroy()

    def close(self):
        pass
Пример #32
0
    def __init__(self,
                 master,
                 font_dict={},
                 text="Abcd",
                 title="Font Chooser",
                 **kwargs):
        """
        Create a new FontChooser instance.

        Arguments:
            master: master window

            font_dict: dictionnary, like the one returned by the .actual
                       method of a Font object:

                        {'family': 'DejaVu Sans',
                         'overstrike': False,
                         'size': 12,
                         'slant': 'italic' or 'roman',
                         'underline': False,
                         'weight': 'bold' or 'normal'}

            text: text to be displayed in the preview label

            title: window title

            **kwargs: additional keyword arguments to be passed to
                      Toplevel.__init__
        """
        Toplevel.__init__(self, master, **kwargs)
        self.title(title)
        self.resizable(False, False)
        self.protocol("WM_DELETE_WINDOW", self.quit)
        self._validate_family = self.register(self.validate_font_family)
        self._validate_size = self.register(self.validate_font_size)

        # --- variable storing the chosen font
        self.res = ""

        style = Style(self)
        style.configure("prev.TLabel", background="white")
        bg = style.lookup("TLabel", "background")
        self.configure(bg=bg)

        # --- family list
        self.fonts = list(set(families()))
        self.fonts.append("TkDefaultFont")
        self.fonts.sort()
        for i in range(len(self.fonts)):
            self.fonts[i] = self.fonts[i].replace(" ", "\ ")
        max_length = int(2.5 * max([len(font) for font in self.fonts])) // 3
        self.sizes = [
            "%i" % i for i in (list(range(6, 17)) + list(range(18, 32, 2)))
        ]
        # --- font default
        font_dict["weight"] = font_dict.get("weight", "normal")
        font_dict["slant"] = font_dict.get("slant", "roman")
        font_dict["underline"] = font_dict.get("underline", False)
        font_dict["overstrike"] = font_dict.get("overstrike", False)
        font_dict["family"] = font_dict.get("family",
                                            self.fonts[0].replace('\ ', ' '))
        font_dict["size"] = font_dict.get("size", 10)

        # --- creation of the widgets
        # ------ style parameters (bold, italic ...)
        options_frame = Frame(self, relief='groove', borderwidth=2)
        self.font_family = StringVar(self, " ".join(self.fonts))
        self.font_size = StringVar(self, " ".join(self.sizes))
        self.var_bold = BooleanVar(self, font_dict["weight"] == "bold")
        b_bold = Checkbutton(options_frame,
                             text=TR["Bold"],
                             command=self.toggle_bold,
                             variable=self.var_bold)
        b_bold.grid(row=0, sticky="w", padx=4, pady=(4, 2))
        self.var_italic = BooleanVar(self, font_dict["slant"] == "italic")
        b_italic = Checkbutton(options_frame,
                               text=TR["Italic"],
                               command=self.toggle_italic,
                               variable=self.var_italic)
        b_italic.grid(row=1, sticky="w", padx=4, pady=2)
        self.var_underline = BooleanVar(self, font_dict["underline"])
        b_underline = Checkbutton(options_frame,
                                  text=TR["Underline"],
                                  command=self.toggle_underline,
                                  variable=self.var_underline)
        b_underline.grid(row=2, sticky="w", padx=4, pady=2)
        self.var_overstrike = BooleanVar(self, font_dict["overstrike"])
        b_overstrike = Checkbutton(options_frame,
                                   text=TR["Overstrike"],
                                   variable=self.var_overstrike,
                                   command=self.toggle_overstrike)
        b_overstrike.grid(row=3, sticky="w", padx=4, pady=(2, 4))
        # ------ Size and family
        self.var_size = StringVar(self)
        self.entry_family = Entry(self,
                                  width=max_length,
                                  validate="key",
                                  validatecommand=(self._validate_family, "%d",
                                                   "%S", "%i", "%s", "%V"))
        self.entry_size = Entry(self,
                                width=4,
                                validate="key",
                                textvariable=self.var_size,
                                validatecommand=(self._validate_size, "%d",
                                                 "%P", "%V"))
        self.list_family = Listbox(self,
                                   selectmode="browse",
                                   listvariable=self.font_family,
                                   highlightthickness=0,
                                   exportselection=False,
                                   width=max_length)
        self.list_size = Listbox(self,
                                 selectmode="browse",
                                 listvariable=self.font_size,
                                 highlightthickness=0,
                                 exportselection=False,
                                 width=4)
        scroll_family = Scrollbar(self,
                                  orient='vertical',
                                  command=self.list_family.yview)
        scroll_size = Scrollbar(self,
                                orient='vertical',
                                command=self.list_size.yview)
        self.preview_font = Font(self, **font_dict)
        if len(text) > 30:
            text = text[:30]
        self.preview = Label(self,
                             relief="groove",
                             style="prev.TLabel",
                             text=text,
                             font=self.preview_font,
                             anchor="center")

        # --- widget configuration
        self.list_family.configure(yscrollcommand=scroll_family.set)
        self.list_size.configure(yscrollcommand=scroll_size.set)

        self.entry_family.insert(0, font_dict["family"])
        self.entry_family.selection_clear()
        self.entry_family.icursor("end")
        self.entry_size.insert(0, font_dict["size"])

        try:
            i = self.fonts.index(self.entry_family.get().replace(" ", "\ "))
        except ValueError:
            # unknown font
            i = 0
        self.list_family.selection_clear(0, "end")
        self.list_family.selection_set(i)
        self.list_family.see(i)
        try:
            i = self.sizes.index(self.entry_size.get())
            self.list_size.selection_clear(0, "end")
            self.list_size.selection_set(i)
            self.list_size.see(i)
        except ValueError:
            # size not in list
            pass

        self.entry_family.grid(row=0,
                               column=0,
                               sticky="ew",
                               pady=(10, 1),
                               padx=(10, 0))
        self.entry_size.grid(row=0,
                             column=2,
                             sticky="ew",
                             pady=(10, 1),
                             padx=(10, 0))
        self.list_family.grid(row=1,
                              column=0,
                              sticky="nsew",
                              pady=(1, 10),
                              padx=(10, 0))
        self.list_size.grid(row=1,
                            column=2,
                            sticky="nsew",
                            pady=(1, 10),
                            padx=(10, 0))
        scroll_family.grid(row=1, column=1, sticky='ns', pady=(1, 10))
        scroll_size.grid(row=1, column=3, sticky='ns', pady=(1, 10))
        options_frame.grid(row=0,
                           column=4,
                           rowspan=2,
                           padx=10,
                           pady=10,
                           ipadx=10)

        self.preview.grid(row=2,
                          column=0,
                          columnspan=5,
                          sticky="eswn",
                          padx=10,
                          pady=(0, 10),
                          ipadx=4,
                          ipady=4)

        button_frame = Frame(self)
        button_frame.grid(row=3, column=0, columnspan=5, pady=(0, 10), padx=10)

        Button(button_frame, text="Ok", command=self.ok).grid(row=0,
                                                              column=0,
                                                              padx=4,
                                                              sticky='ew')
        Button(button_frame, text=TR["Cancel"],
               command=self.quit).grid(row=0, column=1, padx=4, sticky='ew')
        self.list_family.bind('<<ListboxSelect>>', self.update_entry_family)
        self.list_size.bind('<<ListboxSelect>>',
                            self.update_entry_size,
                            add=True)
        self.list_family.bind("<KeyPress>", self.keypress)
        self.entry_family.bind("<Return>", self.change_font_family)
        self.entry_family.bind("<Tab>", self.tab)
        self.entry_size.bind("<Return>", self.change_font_size)

        self.entry_family.bind("<Down>", self.down_family)
        self.entry_size.bind("<Down>", self.down_size)

        self.entry_family.bind("<Up>", self.up_family)
        self.entry_size.bind("<Up>", self.up_size)

        # bind Ctrl+A to select all instead of go to beginning
        self.bind_class("TEntry", "<Control-a>", self.select_all)

        self.wait_visibility(self)
        self.grab_set()
        self.entry_family.focus_set()
        self.lift()
Пример #33
0
 def _cb(cb_self, cb_type, cb_state):
     new_window = Toplevel(cb_self._master)
     cb_type(new_window, self._config, cb_state)
Пример #34
0
class System(Login_window):
    def __init__(self, master, colour):
        try:
            os.mkdir("Employee")
            os.mkdir("Department")
        except FileExistsError:
            print("Directory already exists")
        else:
            pass
        self.__logged = Toplevel(master)
        First.__init__(self, self.__logged, colour)
        self.frame1 = LabelFrame(self.__logged)
        self.frame1.pack()

        self.employee_name = StringVar()
        self.mail = StringVar()
        self.employee_code = StringVar()
        self.department_code = StringVar()
        self.department_name = StringVar()
        self.employee_surname = StringVar()

        frame = Frame(self.__logged, padx=15, pady=15)
        frame.place(x=400, y=200)
        Button(frame, text="Employee Details", font=("Calibri", 13), width=20, pady=15,
               command=lambda: (self.frame1.destroy(), frame.pack(side="left"), System.detail_employee(self))).pack()
        Button(frame, text="Add Employee", font=("Calibri", 13), width=20, pady=15,
               command=lambda: (self.frame1.destroy(), frame.pack(side="left"), System.add_employee(self))).pack()
        Button(frame, text="Department Details", font=("Calibri", 13), width=20, pady=15,
               command=lambda: (
                   self.frame1.destroy(), frame.pack(side="left"), System.detail_department(self))).pack()
        Button(frame, text="Add Department", font=("Calibri", 13), width=20, pady=15,
               command=lambda: (self.frame1.destroy(), frame.pack(side="left"), System.add_department(self))).pack()

        Button(self.__logged, text="Back", width=15, pady=10,
               command=lambda: (main.deiconify(), self.__logged.destroy())).pack()

    def add_employee(self):
        self.frame1 = Frame(self.__logged, width="400", height="400", padx=10, pady=10)
        Label(self.frame1, text="Add Employee", bg="Red", fg="Light Grey", height="3", font=("Didot", 13)).grid(
            row=0, column=0, columnspan=2, sticky=W + E)

        Label(self.frame1, text="First Name").grid(row=1, column=0, pady=10)
        self.employeename = Entry(self.frame1, textvariable=self.employee_name)
        self.employeename.grid(row=1, column=1, pady=10)

        Label(self.frame1, text="Last Name").grid(row=2, column=0, pady=10)
        self.employeesurname = Entry(self.frame1, textvariable=self.employee_surname)
        self.employeesurname.grid(row=2, column=1, pady=10)
        Label(self.frame1, text="Email").grid(row=3, column=0, pady=10)
        self.email = Entry(self.frame1, textvariable=self.mail)
        self.email.grid(row=3, column=1, pady=10)

        Label(self.frame1, text="Employee Code").grid(row=4, column=0, pady=10)
        self.employeecode = Entry(self.frame1, textvariable=self.employee_code)
        self.employeecode.grid(row=4, column=1, pady=10)

        Label(self.frame1, text="Department Code").grid(row=5, column=0, pady=10)
        self.departmentcode = Entry(self.frame1, textvariable=self.department_code)
        self.departmentcode.grid(row=5, column=1, pady=10)

        Label(self.frame1, text="Department Name").grid(row=6, column=0, pady=10)
        self.department = Entry(self.frame1, textvariable=self.department_name)
        self.department.grid(row=6, column=1, pady=10)
        print("adding employee")

        System.reset(self)

        Button(self.frame1, text="Submit",
               command=lambda: System.submit(self, self.employee_name.get(), self.employee_surname.get(),
                                             self.employee_code.get(), self.mail.get(),
                                             self.department_name.get(), self.department_code.get())).grid(row=7,
                                                                                                           column=0,
                                                                                                           columnspan=2)
        Button(self.frame1, text="Reset", command=lambda: System.reset(self)).grid(row=8, column=0, columnspan=2)

        self.frame1.pack(side="left", padx=100)

    def detail_employee(self):
        self.frame1 = LabelFrame(self.__logged, width="700", height="600", padx=5, pady=5)

        Label(self.frame1, text="First Name").grid(row=0, column=0)
        Label(self.frame1, text="Last Name").grid(row=0, column=1)
        Label(self.frame1, text="Employee Code").grid(row=0, column=2)
        Label(self.frame1, text="Email Address").grid(row=0, column=3)
        Label(self.frame1, text="Department Name").grid(row=0, column=4)
        Label(self.frame1, text="Department Code").grid(row=0, column=5)

        list_department = os.listdir("Employee/")
        x = 0
        for i in list_department:
            x += 1
            __file = open("Employee/" + i, "r")
            Label(self.frame1, text=__file.readline().replace("First Name:", "")).grid(row=x, column=0)
            Label(self.frame1, text=__file.readline().replace("Last Name:", "")).grid(row=x, column=1)
            Label(self.frame1, text=__file.readline().replace("Code:", "")).grid(row=x, column=2)
            Label(self.frame1, text=__file.readline().replace("Email:", "")).grid(row=x, column=3)
            Label(self.frame1, text=__file.readline().replace("Department:", "")).grid(row=x, column=4)
            Label(self.frame1, text=__file.readline().replace("Department Code:", "")).grid(row=x, column=5)
            __file.close()

        self.frame1.pack(side="left", padx=75, pady=15, fill=BOTH)

    def add_department(self):
        self.frame1 = Frame(self.__logged, width="400", height="400", padx=10, pady=10)
        Label(self.frame1, text="Add Department", bg="Red", fg="Light Grey", height="3", font=("Didot", 13)).grid(
            row=0, column=0, columnspan=2, sticky=W + E)

        Label(self.frame1, text="Department Code").grid(row=1, column=0, pady=10)
        self.departmentcode = Entry(self.frame1, textvariable=self.department_code)
        self.departmentcode.delete(0, END)
        self.departmentcode.insert(0, "*")
        self.departmentcode.grid(row=1, column=1, pady=10)

        Label(self.frame1, text="Department Name").grid(row=2, column=0, pady=10)
        self.department = Entry(self.frame1, textvariable=self.department_name)
        self.department.delete(0, END)
        self.department.insert(0, "*")
        self.department.grid(row=2, column=1, pady=10)

        Button(self.frame1, text="Submit",
               command=lambda: System.submit(self, department_name=self.department_name.get(),
                                             department_code=self.department_code.get())).grid(row=3, column=0,
                                                                                               columnspan=2)
        Button(self.frame1, text="Reset", command=lambda: System.clear(self)).grid(row=4, column=0, columnspan=2)

        self.frame1.pack(side="left", padx=100)

        print("adding department")

    def detail_department(self):
        self.frame1 = LabelFrame(self.__logged, width="700", height="600", padx=5, pady=5)

        Label(self.frame1, text="Department Code").grid(row=0, column=0)
        Label(self.frame1, text="Department Name").grid(row=0, column=1)

        list_department = os.listdir("Department/")
        x = 0
        for i in list_department:
            x += 1
            Label(self.frame1, text=i[:-4]).grid(row=x, column=0)
            __file = open("Department/" + i, "r")
            Label(self.frame1, text=__file.readline().replace("Department:", "")).grid(row=x, column=1)
            __file.close()

        self.frame1.pack(side="left", padx=200, pady=15, fill=BOTH)

        print("detailing department")

    def clear(self):
        self.departmentcode.delete(0, END)
        self.department.delete(0, END)
        self.departmentcode.insert(0, "*")
        self.department.insert(0, "*")

    def reset(self):
        self.employeename.delete(0, END)
        self.employeesurname.delete(0, END)
        self.employeecode.delete(0, END)
        self.email.delete(0, END)
        self.departmentcode.delete(0, END)
        self.department.delete(0, END)
        self.employeename.insert(0, "*")
        self.employeesurname.insert(0, "*")
        self.employeecode.insert(0, "*")
        self.email.insert(0, "*")
        self.departmentcode.insert(0, "*")
        self.department.insert(0, "*")

    def submit(self, employee_name=None, employee_surname=None, employee_code=None, mail=None, department_name=None,
               department_code=None):

        try:
            department_code = int(department_code)
        except ValueError:
            messagebox.showerror("String Input", "Cant input string in code section")
        else:
            dic = {
                "First Name": employee_name,
                "Last Name": employee_surname,
                "Code": employee_code,
                "Email": mail,
                "Department": department_name,
                "Department Code": department_code
            }
            if dic['Code'] is None:
                try:
                    dep = open(r"Department/" + str(department_code) + ".txt", "x")
                except FileExistsError:
                    messagebox.showerror("Duplicate Department", "The department code already exists")
                else:
                    for i, j in dic.items():
                        if j is not None:
                            dep.write("{}:{}\n".format(i, j))
                    messagebox.showinfo("Department Added", "Department has been added")
                finally:
                    System.clear(self)
            else:
                try:
                    dep = open(r"Employee/" + str(employee_code) + ".txt", "x")
                except FileExistsError:
                    messagebox.showerror("Duplicate Employee", "The employee code already exists")
                else:
                    for i, j in dic.items():
                        if j is not None:
                            dep.write("{}:{}\n".format(i, j))
                    messagebox.showinfo("Employee Added", "Employee has been added")
                finally:
                    System.reset(self)
Пример #35
0
class CanvasTooltip:
    '''
    It creates a tooltip for a given canvas tag or id as the mouse is
    above it.

    This class has been derived from the original Tooltip class I updated
    and posted back to StackOverflow at the following link:

    https://stackoverflow.com/questions/3221956/
           what-is-the-simplest-way-to-make-tooltips-in-tkinter/
           41079350#41079350

    Alberto Vassena on 2016.12.10.
    '''

    def __init__(self, canvas, tag_or_id,
                 *,
                 bg='#FFFFEA',
                 pad=(5, 3, 5, 3),
                 text='canvas info',
                 waittime=400,
                 wraplength=250):
        self.waittime = waittime  # in miliseconds, originally 500
        self.wraplength = wraplength  # in pixels, originally 180
        self.canvas = canvas
        self.text = text
        self.canvas.tag_bind(tag_or_id, "<Enter>", self.onEnter)
        self.canvas.tag_bind(tag_or_id, "<Leave>", self.onLeave)
        self.canvas.tag_bind(tag_or_id, "<ButtonPress>", self.onLeave)
        self.bg = bg
        self.pad = pad
        self.id = None
        self.tw = None

    def onEnter(self, event=None):
        self.schedule()

    def onLeave(self, event=None):
        self.unschedule()
        self.hide()

    def schedule(self):
        self.unschedule()
        self.id = self.canvas.after(self.waittime, self.show)

    def unschedule(self):
        id_ = self.id
        self.id = None
        if id_:
            self.canvas.after_cancel(id_)

    def show(self, event=None):
        def tip_pos_calculator(canvas, label,
                               *,
                               tip_delta=(10, 5), pad=(5, 3, 5, 3)):

            c = canvas

            s_width, s_height = c.winfo_screenwidth(), c.winfo_screenheight()

            width, height = (pad[0] + label.winfo_reqwidth() + pad[2],
                             pad[1] + label.winfo_reqheight() + pad[3])

            mouse_x, mouse_y = c.winfo_pointerxy()

            x1, y1 = mouse_x + tip_delta[0], mouse_y + tip_delta[1]
            x2, y2 = x1 + width, y1 + height

            x_delta = x2 - s_width
            if x_delta < 0:
                x_delta = 0
            y_delta = y2 - s_height
            if y_delta < 0:
                y_delta = 0

            offscreen = (x_delta, y_delta) != (0, 0)

            if offscreen:

                if x_delta:
                    x1 = mouse_x - tip_delta[0] - width

                if y_delta:
                    y1 = mouse_y - tip_delta[1] - height

            offscreen_again = y1 < 0  # out on the top

            if offscreen_again:
                # No further checks will be done.

                # TIP:
                # A further mod might automagically augment the
                # wraplength when the tooltip is too high to be
                # kept inside the screen.
                y1 = 0

            return x1, y1

        bg = self.bg
        pad = self.pad
        canvas = self.canvas

        # creates a toplevel window
        self.tw = Toplevel(canvas.master)

        # Leaves only the label and removes the app window
        self.tw.wm_overrideredirect(True)

        win = Frame(self.tw,
                       # background=bg,
                       borderwidth=0)
        label = Label(win,
                          text=self.text,
                          justify='left',
                          background=bg,
                          relief="solid",
                          borderwidth=0,
                          wraplength=self.wraplength)

        label.grid(padx=(pad[0], pad[2]),
                   pady=(pad[1], pad[3]),
                   sticky='nsew')
        win.grid()

        x, y = tip_pos_calculator(canvas, label)

        self.tw.wm_geometry("+%d+%d" % (x, y))

    def hide(self):
        if self.tw:
            self.tw.destroy()
        self.tw = None
Пример #36
0
def toplevel(geometry='350x200', title=None, is_center=True):
    f = Toplevel()
    f.geometry(geometry)
    f.title(title)
    if is_center: tkcenter(f)
    return f
Пример #37
0
class FilterWindow:
    def __init__(self, parent, filters):
        self.window = Toplevel(parent.window)
        self.window.withdraw()
        self.parent = parent
        self.filters = deepcopy(filters)
        self.filterFrame = Frame(self.window)
        self.buttonFrame = Frame(self.window)

        self.filterGameListbox = None
        self.filterStreamListbox = None
        self.filterCombinedListbox = None

        WindowHelper.initializeWindow(self.window, self.parent, 460, 630, 30, 50, LabelConstants.FILTER_WINDOW)
        self.gridFrames()
        self.addFilterListbox()
        self.addButtons()
        WindowHelper.finalizeWindow(self.window, self.parent)

    def gridFrames(self):
        self.filterFrame.grid(row=0, sticky=NSEW, padx=4, pady=4)
        self.buttonFrame.grid(row=1, sticky=NSEW, padx=4, pady=4)

    def addFilterListbox(self):
        labelFilterGameListbox = Label(self.filterFrame, text=LabelConstants.FILTER_GAME_LISTBOX)
        labelFilterGameListbox.grid(row=0, column=0, sticky=W, padx=4, pady=4)
        scrollbarGame = Scrollbar(self.filterFrame)
        scrollbarGame.grid(row=1, column=1, sticky="NWS")
        self.filterGameListbox = Listbox(self.filterFrame, selectmode=MULTIPLE, yscrollcommand=scrollbarGame.set, activestyle=NONE, width=70)
        scrollbarGame.config(command=self.filterGameListbox.yview)
        self.filterGameListbox.grid(row=1, column=0, sticky=NSEW, padx=(4, 0))
        self.filterGameListbox.configure(exportselection=False)
        descriptions = []
        for f in self.filters["filters"]["game"]:
            descriptions.append(f["description"])
        for desc in sorted(descriptions, key=str.casefold):
            self.filterGameListbox.insert(END, desc)

        labelFilterStreamerListbox = Label(self.filterFrame, text=LabelConstants.FILTER_STREAMER_LISTBOX)
        labelFilterStreamerListbox.grid(row=2, column=0, sticky=W, padx=4, pady=4)
        scrollbarStreamer = Scrollbar(self.filterFrame)
        scrollbarStreamer.grid(row=3, column=1, sticky="NWS")
        self.filterStreamListbox = Listbox(self.filterFrame, selectmode=MULTIPLE, yscrollcommand=scrollbarStreamer.set, activestyle=NONE, width=70)
        scrollbarGame.config(command=self.filterStreamListbox.yview)
        self.filterStreamListbox.grid(row=3, column=0, sticky=NSEW, padx=(4, 0))
        self.filterStreamListbox.configure(exportselection=False)
        descriptions = []
        for f in self.filters["filters"]["streamer"]:
            descriptions.append(f["description"])
        for desc in sorted(descriptions, key=str.casefold):
            self.filterStreamListbox.insert(END, desc)

        labelFilterCombinedListbox = Label(self.filterFrame, text=LabelConstants.FILTER_COMBINED_LISTBOX)
        labelFilterCombinedListbox.grid(row=4, column=0, sticky=W, padx=4, pady=4)
        scrollbarCombined = Scrollbar(self.filterFrame)
        scrollbarCombined.grid(row=5, column=1, sticky="NWS")
        self.filterCombinedListbox = Listbox(self.filterFrame, selectmode=MULTIPLE, yscrollcommand=scrollbarCombined.set, activestyle=NONE, width=70)
        scrollbarCombined.config(command=self.filterGameListbox.yview)
        self.filterCombinedListbox.grid(row=5, column=0, sticky=NSEW, padx=(4, 0))
        self.filterCombinedListbox.configure(exportselection=False)
        descriptions = []
        for f in self.filters["filters"]["combined"]:
            descriptions.append(f["description"])
        for desc in sorted(descriptions, key=str.casefold):
            self.filterCombinedListbox.insert(END, desc)

    def addButtons(self):
        buttonNewFilter = Button(self.buttonFrame, text=LabelConstants.NEW_FILTER, width=13, command=lambda: NewFilterWindow(self))
        buttonNewFilter.grid(row=0, column=0, sticky=NSEW, padx=(8, 4), pady=4)
        buttonRemove = Button(self.buttonFrame, text=LabelConstants.DELETE, width=13, command=lambda: self.delete())
        buttonRemove.grid(row=0, column=1, sticky=NSEW, padx=4, pady=4)
        buttonOk = Button(self.buttonFrame, text=LabelConstants.OK, width=13, command=lambda: self.ok())
        buttonOk.grid(row=0, column=2, sticky=NSEW, padx=4, pady=4)
        buttonCancel = Button(self.buttonFrame, text=LabelConstants.CANCEL, width=13, command=lambda: self.window.destroy())
        buttonCancel.grid(row=0, column=3, sticky=NSEW, padx=4, pady=4)

    def delete(self):
        self.deleteByListbox(self.filterGameListbox, LabelConstants.FILTER_KEY_GAME)
        self.deleteByListbox(self.filterStreamListbox, LabelConstants.FILTER_KEY_STREAMER)
        self.deleteByListbox(self.filterCombinedListbox, LabelConstants.FILTER_KEY_COMBINED)

    def deleteByListbox(self, listbox: Listbox, key: str):
        descriptions = []
        for f in reversed(listbox.curselection()):
            descriptions.append(listbox.get(f))
            listbox.delete(f)
        self.filters["filters"][key] = [x for x in self.filters["filters"][key] if x["description"] not in descriptions]

    def ok(self):
        self.parent.scrollableFrame.setFilters(self.filters)
        self.window.destroy()

    def addFilter(self, key: str, newFilter: dict):
        self.filters["filters"][key].append(newFilter)
        description = newFilter["description"]
        if key == LabelConstants.FILTER_KEY_GAME:
            alphabeticallyInsert(self.filterGameListbox, description)
        elif key == LabelConstants.FILTER_KEY_STREAMER:
            alphabeticallyInsert(self.filterStreamListbox, description)
        elif key == LabelConstants.FILTER_KEY_COMBINED:
            alphabeticallyInsert(self.filterCombinedListbox, description)
Пример #38
0
    def create_widgets(self):
        '''Create basic 3 row x 3 col search (find) dialog.

        Other dialogs override subsidiary create_x methods as needed.
        Replace and Find-in-Files add another entry row.
        '''
        top = Toplevel(self.root)
        top.bind("<Return>", self.default_command)
        top.bind("<Escape>", self.close)
        top.protocol("WM_DELETE_WINDOW", self.close)
        top.wm_title(self.title)
        top.wm_iconname(self.icon)
        self.top = top

        self.row = 0
        self.top.grid_columnconfigure(0, pad=2, weight=0)
        self.top.grid_columnconfigure(1, pad=2, minsize=100, weight=100)

        self.create_entries()  # row 0 (and maybe 1), cols 0, 1
        self.create_option_buttons()  # next row, cols 0, 1
        self.create_other_buttons()  # next row, cols 0, 1
        self.create_command_buttons()  # col 2, all rows
Пример #39
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()

        texte = Text(fen, width=50, height=18)
        texte.pack()
        texte.insert(
            "end",
            _("FolderSync 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",
            _("FolderSync 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)
Пример #40
0
 def __init__(self, parent) -> None:
     self.parent = parent
     del parent
     self.main_window: ClassVar = Toplevel(self.parent)
     self.disallowed_windows: list = [self.main_window.winfo_id()]
     # hide window
     self.main_window.withdraw()
     # window style
     self.main_window.configure(background='#212121')
     self.main_theme: ClassVar = ttk.Style()
     self.main_theme.theme_use('clam')
     self.main_theme.layout(
         'debugger.TEntry',
         [('Entry.padding', {
             'children': [('Entry.textarea', {
                 'sticky': 'nswe'
             })],
             'sticky': 'nswe'
         })])
     self.main_theme.configure('debugger.TEntry',
                               background='#111',
                               foreground='#fff',
                               fieldbackground='#111',
                               selectforeground='#fff',
                               selectbackground='#333')
     self.main_theme.configure('debugger.small.TButton',
                               background='#111',
                               relief='flat',
                               font=('Consolas', 9),
                               foreground='#fff')
     self.main_theme.map('debugger.small.TButton',
                         background=[('pressed', '!disabled', '#111'),
                                     ('active', '#151515')])
     self.main_theme.configure('debugger.TButton',
                               background='#111',
                               relief='flat',
                               font=('Consolas', 12),
                               foreground='#fff')
     self.main_theme.map('debugger.TButton',
                         background=[('pressed', '!disabled', '#111'),
                                     ('active', '#151515')])
     self.main_theme.configure('debugger.Vertical.TScrollbar',
                               gripcount=0,
                               relief='flat',
                               background='#333',
                               darkcolor='#111',
                               lightcolor='#111',
                               troughcolor='#111',
                               bordercolor='#111',
                               arrowcolor='#333')
     self.main_theme.layout('debugger.Vertical.TScrollbar',
                            [('Vertical.Scrollbar.trough', {
                                'children': [('Vertical.Scrollbar.thumb', {
                                    'expand': '1',
                                    'sticky': 'nswe'
                                })],
                                'sticky':
                                'ns'
                            })])
     self.main_theme.map('debugger.Vertical.TScrollbar',
                         background=[('pressed', '!disabled', '#313131'),
                                     ('disabled', '#111'),
                                     ('active', '#313131'),
                                     ('!active', '#333')])
     # window attributes
     self.main_window.attributes("-topmost", True)
     self.main_window.title(f'DEBUGGING: {self.parent.title()}')
     # self.main_window.geometry('665x800')
     self.main_window.minsize(665, 500)
     self.main_window.protocol('WM_DELETE_WINDOW', self.close_debugger)
     # variables
     self.widget: ClassVar = None
     self.highlighted_elements: dict = {}
     self.inspecting: bool = False
     self.allow_self_debug = False
     self.blank_photo: ClassVar = PhotoImage(height=16, width=16)
     self.blank_photo.blank()
     self.main_window.iconphoto(False, self.blank_photo)
     # content
     top_frame: ClassVar = Frame(self.main_window,
                                 background=self.main_window['background'])
     # inspect button
     self.inspect_button: ClassVar = ttk.Button(top_frame,
                                                text='INSPECT ELEMENT',
                                                takefocus=False,
                                                style='debugger.TButton',
                                                command=self.toggle_inspect)
     self.inspect_button.pack(side='left', padx=(10, 0), pady=10)
     self.inspect_next_button: ClassVar = ttk.Button(
         top_frame,
         text='INSPECT NEXT',
         takefocus=False,
         style='debugger.TButton',
         command=self.inspect_next)
     self.inspect_next_button.state(['disabled'])
     self.inspect_next_button.pack(side='left', padx=(10, 0), pady=10)
     self.widgets_label: ClassVar = Label(
         top_frame,
         text=f'{len(self.get_all_widgets(self.parent))} WIDGETS',
         background='#111',
         foreground='#fff',
         font=('Consolas', 12))
     self.widgets_label.pack(side='left',
                             padx=(10, 0),
                             pady=10,
                             ipady=5,
                             ipadx=5)
     self.refresh_button: ClassVar = ttk.Button(
         top_frame,
         text='REFRESH',
         takefocus=False,
         style='debugger.TButton',
         command=lambda: self.inspect_widget(self.widget))
     self.refresh_button.state(['disabled'])
     self.refresh_button.pack(side='left', padx=(10, 0))
     self.mode_label: ClassVar = Label(top_frame,
                                       text='NORMAL',
                                       background='#111',
                                       foreground='#fff',
                                       font=('Consolas', 12))
     self.mode_label.pack(side='left', padx=10, ipady=5, ipadx=5)
     top_frame.pack(side='top', fill='x')
     mid_frame: ClassVar = Frame(self.main_window,
                                 background=self.main_window['background'])
     widget_frame: ClassVar = Frame(mid_frame, background='#333')
     Label(widget_frame,
           text='WIDGET CLASS, NAME',
           background=widget_frame['background'],
           foreground='#fff',
           font=('Consolas', 12),
           anchor='w').pack(side='top', fill='x', padx=5, pady=(5, 0))
     self.widget_name: ClassVar = Label(widget_frame,
                                        text='',
                                        background='#111',
                                        foreground='#fff',
                                        anchor='w',
                                        font=('Consolas', 12))
     self.widget_name.pack(side='top', fill='x', padx=5, pady=5)
     Label(widget_frame,
           text='WIDGET DIMENTIONS',
           background=widget_frame['background'],
           foreground='#fff',
           font=('Consolas', 12),
           anchor='w').pack(side='top', fill='x', padx=5, pady=(5, 0))
     self.widget_dimensions: ClassVar = Label(widget_frame,
                                              text='',
                                              background='#111',
                                              foreground='#fff',
                                              anchor='w',
                                              font=('Consolas', 12))
     self.widget_dimensions.pack(side='top', fill='x', padx=5, pady=5)
     Label(widget_frame,
           text='WIDGET MANAGER',
           background=widget_frame['background'],
           foreground='#fff',
           font=('Consolas', 12),
           anchor='w').pack(side='top', fill='x', padx=5, pady=(5, 0))
     self.widget_manager: ClassVar = Label(widget_frame,
                                           text='',
                                           background='#111',
                                           foreground='#fff',
                                           anchor='w',
                                           font=('Consolas', 12))
     self.widget_manager.pack(side='top', fill='x', padx=5, pady=5)
     Label(widget_frame,
           text='MANAGER CONFIG',
           background=widget_frame['background'],
           foreground='#fff',
           font=('Consolas', 12),
           anchor='w').pack(side='top', fill='x', padx=5, pady=(5, 0))
     self.manager_config: ClassVar = Label(widget_frame,
                                           text='',
                                           background='#111',
                                           foreground='#fff',
                                           anchor='w',
                                           font=('Consolas', 12))
     self.manager_config.pack(side='top', fill='x', padx=5, pady=5)
     Label(widget_frame,
           text='WIDGET PARENT',
           background=widget_frame['background'],
           foreground='#fff',
           font=('Consolas', 12),
           anchor='w').pack(side='top', fill='x', padx=5, pady=(5, 0))
     parent_frame: ClassVar = Frame(widget_frame,
                                    background=widget_frame['background'])
     self.widget_perent: ClassVar = Label(parent_frame,
                                          text='',
                                          background='#111',
                                          foreground='#fff',
                                          anchor='w',
                                          font=('Consolas', 12))
     self.widget_perent.pack(side='left', fill='x', expand=True)
     self.inspect_perent: ClassVar = ttk.Button(
         parent_frame,
         text='INSPECT',
         takefocus=False,
         style='debugger.small.TButton',
         command=lambda: self.inspect_widget(
             self.widget._nametowidget(self.widget.winfo_parent())))
     self.inspect_perent.state(['disabled'])
     self.inspect_perent.pack(side='left', fill='x', padx=5)
     parent_frame.pack(side='top', fill='x', padx=5, pady=(5, 0))
     Label(widget_frame,
           text='WIDGET BINDINGS',
           background=widget_frame['background'],
           foreground='#fff',
           font=('Consolas', 12),
           anchor='w').pack(side='top', fill='x', padx=5, pady=(5, 0))
     self.widget_bindings: ClassVar = Label(widget_frame,
                                            text='',
                                            background='#111',
                                            foreground='#fff',
                                            anchor='w',
                                            font=('Consolas', 12))
     self.widget_bindings.pack(side='top', fill='x', padx=5, pady=5)
     Label(widget_frame,
           text='WIDGET PROPERTIES',
           background=widget_frame['background'],
           foreground='#fff',
           font=('Consolas', 12),
           anchor='w').pack(side='top', fill='x', padx=5, pady=(5, 0))
     properties_frame: ClassVar = Frame(
         widget_frame, background=widget_frame['background'])
     properties_text: ClassVar = Frame(
         properties_frame, background=properties_frame['background'])
     Label(properties_text,
           text='WIDGET TEXT:',
           background='#111',
           foreground='#fff',
           anchor='w',
           font=('Consolas', 12)).pack(side='left', fill='x')
     self.entry: ClassVar = ttk.Entry(properties_text,
                                      style='debugger.TEntry',
                                      font=('Consolas', 12))
     self.entry.state(['disabled'])
     self.entry.pack(side='left',
                     fill='x',
                     ipady=2,
                     expand=True,
                     padx=(5, 0))
     self.apply_button: ClassVar = ttk.Button(
         properties_text,
         text='APPLY',
         takefocus=False,
         style='debugger.small.TButton',
         command=self.apply_changes)
     self.apply_button.state(['disabled'])
     self.apply_button.pack(side='left', fill='x', padx=5)
     properties_text.pack(side='top', fill='x', pady=(0, 5))
     properties_image: ClassVar = Frame(
         properties_frame, background=properties_frame['background'])
     Label(properties_image,
           text='WIDGET IMG:',
           background='#111',
           foreground='#fff',
           anchor='w',
           font=('Consolas', 12)).pack(side='left', fill='x')
     self.widget_image: ClassVar = ttk.Button(
         properties_image,
         text='OPEN IMAGE',
         takefocus=False,
         style='debugger.small.TButton',
         command=self.open_image)
     self.widget_image.state(['disabled'])
     self.widget_image.pack(side='left', fill='x', padx=5)
     properties_image.pack(side='top', fill='x', pady=(0, 5))
     properties_function: ClassVar = Frame(
         properties_frame, background=properties_frame['background'])
     Label(properties_function,
           text='WIDGET FUNCTION:',
           background='#111',
           foreground='#fff',
           anchor='w',
           font=('Consolas', 12)).pack(side='left', fill='x')
     self.widget_function: ClassVar = ttk.Button(
         properties_function,
         text='CALL FUNCTION',
         takefocus=False,
         style='debugger.small.TButton',
         command=self.call_function)
     self.widget_function.state(['disabled'])
     self.widget_function.pack(side='left', fill='x', padx=5)
     properties_function.pack(side='top', fill='x')
     properties_frame.pack(side='top', fill='x', padx=5, pady=(5, 0))
     Label(widget_frame,
           text='WIDGET CHILDRENS',
           background=widget_frame['background'],
           foreground='#fff',
           font=('Consolas', 12),
           anchor='w').pack(side='top', fill='x', padx=5, pady=(5, 0))
     canvas_frame: ClassVar = Frame(widget_frame,
                                    background=widget_frame['background'])
     scrollbar: ClassVar = ttk.Scrollbar(
         canvas_frame, style='debugger.Vertical.TScrollbar')
     self.canvas: ClassVar = Canvas(canvas_frame,
                                    borderwidth=0,
                                    highlightthickness=0,
                                    background='#111',
                                    yscrollcommand=scrollbar.set)
     scrollbar.configure(command=self.canvas.yview)
     self.canvas_cards: ClassVar = Frame(
         self.canvas, background=self.canvas['background'])
     self.canvas_cards.bind(
         '<Configure>', lambda _: self.canvas.configure(scrollregion=self.
                                                        canvas.bbox('all')))
     self.canvas_window: ClassVar = self.canvas.create_window(
         (0, 0), window=self.canvas_cards, anchor='nw')
     self.canvas.bind(
         '<Configure>', lambda _: self.canvas.itemconfigure(
             self.canvas_window,
             width=self.canvas.winfo_width(),
             height=len(self.canvas_cards.winfo_children()) * 51))
     self.canvas.pack(side='left',
                      fill='both',
                      expand=True,
                      padx=10,
                      pady=10)
     scrollbar.pack(side='right', fill='y', pady=10, padx=(0, 10))
     canvas_frame.pack(side='top', fill='both', expand=True)
     widget_frame.pack(side='top', fill='both', expand=True, padx=10)
     mid_frame.pack(side='top', fill='both', expand=True)
     Label(self.main_window,
           text='DEBUGGER BY MATEUSZ PERCZAK (Łosiek)',
           background='#111',
           foreground='#fff',
           font=('Consolas', 12),
           anchor='w').pack(side='top', fill='x', padx=10, pady=(10, 0))
     # show window
     self.main_window.bind('<MouseWheel>', self.on_mouse)
     self.entry.bind('<KeyRelease>', self.entry_diff)
     self.main_window.after(100, self.init_img_window)
     self.main_window.after(150, lambda: self.inspect_widget(self.parent))
     self.check_bind_collisions()
     self.main_window.deiconify()
     self.show_window()
     self.main_window.mainloop()
Пример #41
0
def gp_login(master):
    """Tkinter window for gp login.
    :param master: initial programme window.
    :return: request_gp_sign_in.
    """
    gp_login_screen = Toplevel()
    gp_login_screen.title("Login to your account")
    gp_login_screen.geometry("400x250")
    Label(gp_login_screen, text="Please enter your username and password").pack()

    gp_username_label = Label(gp_login_screen, text="Username:"******"Password:"******"*")
    gp_password_entry.pack()

    def request_gp_sign_in(username, password):
        """Login to the GP home screen.
        :param username: input username created from registration.
        :param password: input password created from registration.
        :return: userportal.gp_portal.
        """
        gp_username_entry.delete(0, END)
        gp_password_entry.delete(0, END)

        gp_database = json.load(open('gp_database.json'))

        if username in gp_database:
            if gp_database[username]["password"] == password:
                if gp_database[username]["Verified"] is False:
                    logging.info("Admin needs to verify gp.")
                    messagebox.showinfo("Information", "Still awaiting verification by admin")
                else:
                    gp_login_screen.destroy()

                    gp = GP(gp_database[username]["username"],
                            gp_database[username]["First Name"],
                            gp_database[username]["Last Name"],
                            gp_database[username]["password"],
                            gp_database[username]["GMC_Number"],
                            gp_database[username]["assigned_patients"],
                            gp_database[username]["Verified"],
                            gp_database[username]["Availability"]["Monday Start"],
                            gp_database[username]["Availability"]["Monday End"],
                            gp_database[username]["Availability"]["Tuesday Start"],
                            gp_database[username]["Availability"]["Tuesday End"],
                            gp_database[username]["Availability"]["Wednesday Start"],
                            gp_database[username]["Availability"]["Wednesday End"],
                            gp_database[username]["Availability"]["Thursday Start"],
                            gp_database[username]["Availability"]["Thursday End"],
                            gp_database[username]["Availability"]["Friday Start"],
                            gp_database[username]["Availability"]["Friday End"])

                    logging.info("gp login successful.")
                    gp_login_screen.destroy()
                    master.destroy()
                    gp_portal.gp_portal(gp)
            if gp_database[username]["password"] != password:
                Label(gp_login_screen, text="Your username or password was incorrect. Please try again.").pack()
                logging.warning("Incorrect gp login details entered.")
        else:
            Label(gp_login_screen, text="Your username or password was incorrect. Please try again.").pack()
            logging.warning("Incorrect gp login details entered.")

    login_click = Button(gp_login_screen, text="Sign in", command=lambda: request_gp_sign_in(gp_username_entry.get(),
                                                                                             gp_password_entry.get()))
    login_click.pack(pady=10)
Пример #42
0
    def __init__(self, master, a_copier, a_supp, a_supp_avant_cp, original,
                 sauvegarde):
        Toplevel.__init__(self, master)
        self.geometry("%ix%i" %
                      (self.winfo_screenwidth(), self.winfo_screenheight()))
        self.rowconfigure(1, weight=1)
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=1)
        self.title("Confirmation")

        self.a_copier = a_copier
        self.a_supp = a_supp
        self.a_supp_avant_cp = a_supp_avant_cp

        h = max(len(a_supp), len(a_copier))

        style = Style(self)
        style.configure("text.TFrame", background="white", relief="sunken")

        Label(self,
              text="Synchronisation de %s vers %s" %
              (original, sauvegarde)).grid(row=0,
                                           columnspan=2,
                                           padx=10,
                                           pady=10)
        paned = PanedWindow(self, orient='horizontal')
        paned.grid(row=1, columnspan=2, sticky="eswn", padx=(10, 4), pady=4)
        paned.columnconfigure(0, weight=1)
        paned.columnconfigure(1, weight=1)
        paned.rowconfigure(1, weight=1)
        frame_copie = Frame(paned)
        frame_copie.columnconfigure(0, weight=1)
        frame_copie.rowconfigure(1, weight=1)
        paned.add(frame_copie, weight=1)
        Label(frame_copie, text="À copier :").grid(row=0,
                                                   columnspan=2,
                                                   padx=(10, 4),
                                                   pady=4)
        f_copie = Frame(frame_copie, style="text.TFrame", borderwidth=1)
        f_copie.columnconfigure(0, weight=1)
        f_copie.rowconfigure(0, weight=1)
        f_copie.grid(row=1, column=0, sticky="ewsn")
        txt_copie = Text(f_copie,
                         height=h,
                         wrap="none",
                         highlightthickness=0,
                         relief="flat")
        txt_copie.grid(row=0, column=0, sticky="eswn")
        scrollx_copie = Scrollbar(frame_copie,
                                  orient="horizontal",
                                  command=txt_copie.xview)
        scrolly_copie = Scrollbar(frame_copie,
                                  orient="vertical",
                                  command=txt_copie.yview)
        scrollx_copie.grid(row=2, column=0, sticky="ew")
        scrolly_copie.grid(row=1, column=1, sticky="ns")
        txt_copie.configure(yscrollcommand=scrolly_copie.set,
                            xscrollcommand=scrollx_copie.set)
        txt_copie.insert("1.0", "\n".join(a_copier))
        txt_copie.configure(state="disabled")

        frame_supp = Frame(paned)
        frame_supp.columnconfigure(0, weight=1)
        frame_supp.rowconfigure(1, weight=1)
        paned.add(frame_supp, weight=1)
        Label(frame_supp, text="À supprimer :").grid(row=0,
                                                     columnspan=2,
                                                     padx=(4, 10),
                                                     pady=4)
        f_supp = Frame(frame_supp, style="text.TFrame", borderwidth=1)
        f_supp.columnconfigure(0, weight=1)
        f_supp.rowconfigure(0, weight=1)
        f_supp.grid(row=1, column=0, sticky="ewsn")
        txt_supp = Text(f_supp,
                        height=h,
                        wrap="none",
                        highlightthickness=0,
                        relief="flat")
        txt_supp.grid(row=0, column=0, sticky="eswn")
        scrollx_supp = Scrollbar(frame_supp,
                                 orient="horizontal",
                                 command=txt_supp.xview)
        scrolly_supp = Scrollbar(frame_supp,
                                 orient="vertical",
                                 command=txt_supp.yview)
        scrollx_supp.grid(row=2, column=0, sticky="ew")
        scrolly_supp.grid(row=1, column=1, sticky="ns")
        txt_supp.configure(yscrollcommand=scrolly_supp.set,
                           xscrollcommand=scrollx_supp.set)
        txt_supp.insert("1.0", "\n".join(a_supp))
        txt_supp.configure(state="disabled")

        Button(self, command=self.ok, text="Ok").grid(row=3,
                                                      column=0,
                                                      sticky="e",
                                                      padx=(10, 4),
                                                      pady=(4, 10))
        Button(self, text="Annuler", command=self.destroy).grid(row=3,
                                                                column=1,
                                                                sticky="w",
                                                                padx=(4, 10),
                                                                pady=(4, 10))
        self.grab_set()
Пример #43
0
 def _new_state_window(self, frame_type, state):
     new_window = Toplevel(self._master)
     frame_type(new_window, self._config, state)
from openpyxl.utils import get_column_letter
import dictionary_img

#in case we are running this on a computer
#that doesn't have updated Python
try:
    from PIL import Image
except ModuleNotFoundError:
    import Image

#root window
root = Tk()

#initialize windows
#welcome window
welcome_w = Toplevel(root)
width_value = welcome_w.winfo_screenwidth()
height_value = welcome_w.winfo_screenheight()
welcome_w.configure(bg='white')
welcome_w.attributes('-fullscreen', True)
welcome_w.resizable(width=False, height=False)
welcome_w.title('Welcome')

#info windows
info1_w = Toplevel(root)
width_value = info1_w.winfo_screenwidth()
height_value = info1_w.winfo_screenheight()
info1_w.configure(bg='white')
info1_w.attributes('-fullscreen', True)
info1_w.resizable(width=False, height=False)
info1_w.title('User Information (1/2)')
class MessageComponentWindow:
    def __init__(self, parent, messagePart: MessagePart, index: int):
        self.parent = parent
        self.parentWindow = parent.window.master
        self.master = Toplevel(self.parentWindow)
        self.master.withdraw()
        self.existingMessagePart = messagePart
        self.messagePart = deepcopy(messagePart)
        self.index = index
        self.master.geometry('+{x}+{y}'.format(
            x=self.parentWindow.winfo_x() + 10,
            y=self.parentWindow.winfo_y() + 10))
        self.master.wm_attributes("-topmost", 1)
        self.master.focus_force()
        self.master.wm_title("StreamTicker Message Component")
        self.master.iconbitmap("imagefiles/stIcon.ico")
        self.master.resizable(False, False)
        self.master.grab_set()
        self.master.protocol("WM_DELETE_WINDOW", self.deleteWindow)

        self.componentFrame = MessageComponentFrame(self)
        self.componentFrame.frame.grid(row=0, sticky=NSEW, padx=4, pady=4)

        self.okCancelFrame = MessageComponentOkCancelFrame(self)
        self.okCancelFrame.frame.grid(row=2,
                                      column=0,
                                      padx=4,
                                      pady=4,
                                      sticky=E)

        self.master.deiconify()
        self.master.mainloop()

    def deleteWindow(self):
        self.master.destroy()
        self.parentWindow.lift()
        self.parentWindow.wm_attributes("-topmost", 1)
        self.parentWindow.grab_set()

    def returnMessageComponent(self):
        if validate(self.componentFrame, self.master):
            if self.existingMessagePart:
                self.parent.messageMakerPartFrame.parent.message.parts[
                    self.index] = MessagePart(
                        self.componentFrame.componentType.get(), self.index,
                        self.componentFrame.getValue())
            else:
                self.existingMessagePart = MessagePart(
                    self.componentFrame.componentType.get(), self.index,
                    self.componentFrame.getValue())
                self.parent.messageMakerPartFrame.parent.message.parts.append(
                    self.existingMessagePart)
            self.parent.populateListbox(
                self.parent.messageMakerPartFrame.parent.message.parts)
            self.deleteWindow()
class MainWindow:
    def __init__(self):
        global root
        self.master = Toplevel(root)
        self.master.withdraw()
        self.master.protocol('WM_DELETE_WINDOW', root.destroy)
        self.master.iconbitmap(imgdir)
        self.master.geometry("400x150")
        self.master.resizable(False, False)
        self.master.title("Adb & Fastboot Installer - By @Pato05")
        estyle = Style()
        estyle.element_create("plain.field", "from", "clam")
        estyle.layout("White.TEntry",
                      [('Entry.plain.field', {'children': [(
                          'Entry.background', {'children': [(
                              'Entry.padding', {'children': [(
                                  'Entry.textarea', {'sticky': 'nswe'})],
                                  'sticky': 'nswe'})], 'sticky': 'nswe'})],
                          'border': '4', 'sticky': 'nswe'})])
        estyle.configure("White.TEntry",
                         background="white",
                         foreground="black",
                         fieldbackground="white")
        window = Frame(self.master, relief=FLAT)
        window.pack(padx=10, pady=5, fill=BOTH)
        Label(window, text='Installation path:').pack(fill=X)
        self.syswide = IntVar()
        self.instpath = StringVar()
        self.e = Entry(window, state='readonly',
                       textvariable=self.instpath, style='White.TEntry')
        self.e.pack(fill=X)
        self.toggleroot()
        Label(window, text='Options:').pack(pady=(10, 0), fill=X)
        inst = Checkbutton(window, text="Install Adb and Fastboot system-wide?",
                           variable=self.syswide, command=self.toggleroot)
        inst.pack(fill=X)
        self.path = IntVar(window, value=1)
        Checkbutton(window, text="Put Adb and Fastboot in PATH?",
                    variable=self.path).pack(fill=X)
        Button(window, text='Install', command=self.install).pack(anchor='se')
        self.master.deiconify()

    def toggleroot(self):
        if self.syswide.get() == 0:
            self.instpath.set(installpaths['user'])
        elif self.syswide.get() == 1:
            self.instpath.set(installpaths['system'])

    def install(self):
        self.app = InstallWindow(setpath=self.path.get(
        ), installpath=self.instpath.get(), systemwide=self.syswide.get())
        self.master.destroy()
Пример #47
0
class App:
    def __init__(self,
                 master,
                 window_title='cropping tool',
                 dataset_path='dataset/'):
        self.window = master
        self.window.title(window_title)
        self.center(self.window)
        self.popup_switch = 0
        self.popup_flag = 0
        self.dataset_path = dataset_path + 'xray/'
        self.csv_file = dataset_path + 'xray/annotation.csv'
        self.json_file = dataset_path + 'xray/coordinates.json'

        def get_img_list():
            DATASET_DIR = Path().cwd() / 'dataset' / 'CHD'
            DATASET_DIR_LIST = list(DATASET_DIR.glob('*'))
            img_list = list()

            for data_dir in sorted(DATASET_DIR_LIST):
                img_id = data_dir.stem
                img_name = img_id + '_VD'
                img_name_de = img_id + '_VDanno'
                img_list += sorted(
                    list(
                        set(data_dir.glob(img_name + '*')) -
                        set(data_dir.glob(img_name_de + '*'))))
            #print(str(img_list[0].absolute()))
            return img_list

        def get_xray_list():
            DATASET_DIR = Path().cwd() / 'dataset' / 'xray'
            dataList = sorted(list(DATASET_DIR.glob('*.jpg')))
            return dataList

        # Get whole X-ray list by going through dataset and get the starting information by checking CSV file.
        self.xray_list = get_xray_list()
        self.df, self.startIndex = self.read_todoList(self.csv_file)
        self.img_path = str(self.xray_list[self.startIndex].absolute())
        self.img_id = self.xray_list[self.startIndex].stem

        #[Frame] Including upper half
        self.upframe = tkinter.Frame(self.window)
        self.upframe.pack()

        self.entry_id_var = tkinter.StringVar(self.upframe)
        self.entry_id_var.set(self.img_id)
        self.entry_id = tkinter.Entry(self.upframe,
                                      textvariable=self.entry_id_var,
                                      state='disabled')
        self.entry_id.config(disabledforeground='red',
                             disabledbackground='yellow')
        self.entry_id.pack(anchor=tkinter.N)

        #[ENTRY] Creat a entry where user can decide the cropping size
        self.crop_height = tkinter.StringVar(self.upframe)
        self.crop_width = tkinter.StringVar(self.upframe)
        self.height = 400
        self.width = 400
        self.crop_height.set("400")  # default size 100*100
        self.crop_width.set("400")
        vcmd = (self.upframe.register(self.validate), '%d', '%i', '%P', '%s',
                '%S', '%v', '%V', '%W')
        self.entry_height = tkinter.Entry(self.upframe,
                                          validate='key',
                                          validatecommand=vcmd,
                                          textvariable=self.crop_height)
        self.entry_width = tkinter.Entry(self.upframe,
                                         validate='key',
                                         validatecommand=vcmd,
                                         textvariable=self.crop_width)
        self.entry_height.pack(anchor=tkinter.N)
        self.entry_width.pack(anchor=tkinter.N)

        #[BUTTON] Button for determining the crop size and image starting id
        self.btn_crop_size = tkinter.Button(self.upframe,
                                            text="OK",
                                            width=10,
                                            command=self.crop_size)
        self.btn_crop_size.pack(anchor=tkinter.N, expand=True)

        #[Frame] Including lower half
        self.downframe = tkinter.Frame(self.window, width=800, height=800)
        self.downframe.pack()

        #[Scrollbar]
        self.yscrollbar = Scrollbar(self.downframe,
                                    orient='vertical',
                                    width=20)
        self.yscrollbar.pack(side='right', fill='y')
        self.xscrollbar = Scrollbar(self.downframe,
                                    orient='horizontal',
                                    width=20)
        self.xscrollbar.pack(side='bottom', fill='x')

        #[MOUSEWHEEL][CALLBACK]
        def bound_to_mousewheel(event):
            self.canvas.bind_all("<MouseWheel>", func=on_mousewheel)

        #[MOUSEWHEEL][CALLBACK]
        def unbound_to_mousewheel(event):
            self.canvas.unbind_all("<MouseWheel>")

        #[MOUSEWHEEL][CALLBACK]
        def on_mousewheel(event):
            self.canvas.yview_scroll(-1 * (event.delta), "units")

        #[CANVAS] Create a canvas to fit a image
        self.canvas_height = 600
        self.canvas_width = 800
        self.canvas = tkinter.Canvas(self.downframe,
                                     width=self.canvas_width,
                                     height=self.canvas_height,
                                     xscrollcommand=self.xscrollbar.set,
                                     yscrollcommand=self.yscrollbar.set)
        self.xscrollbar.config(command=self.canvas.xview)
        self.yscrollbar.config(command=self.canvas.yview)
        self.yscrollbar.bind('<Enter>', func=bound_to_mousewheel)
        self.yscrollbar.bind('<Leave>', func=unbound_to_mousewheel)
        self.set_canvas()

        #[MASK][CALLBACK] Draw a rectangle mask which follows the mouse
        def mask(event):
            if self.popup_flag == 1:
                return
            self.img = self.cv_img.copy()
            self.overlay = self.cv_img.copy()
            self.opacity = 0.3
            self.canvasx = event.x
            self.canvasy = event.y
            cv2.rectangle(
                self.overlay,
                (int(self.canvas.canvasx(event.x)) - int(self.width / 2),
                 int(self.canvas.canvasy(event.y)) - int(self.height / 2)),
                (int(self.canvas.canvasx(event.x)) + int(self.width / 2),
                 int(self.canvas.canvasy(event.y)) + int(self.height / 2)),
                (255, 255, 0), -1)

            cv2.addWeighted(self.overlay, self.opacity, self.img,
                            1 - self.opacity, 0, self.img)

            if hasattr(self, 'img'):
                self.canvas.delete("all")
            self.image = PIL.Image.fromarray(self.img)
            self.photo = PIL.ImageTk.PhotoImage(self.image)
            self.canvas.create_image(0, 0, image=self.photo, anchor=tkinter.NW)
            # debug only
            #print('{},{}'.format(self.canvas.canvasx(event.x),self.canvas.canvasy(event.y)))

        self.canvas.bind("<Motion>", func=mask)

        #[CLICK][CALLBACK] Capture click position
        def click(event):
            self.currentx = int(self.canvas.canvasx(event.x))
            self.currenty = int(self.canvas.canvasy(event.y))
            print("clicked at", self.currentx, self.currenty)
            new_page(self)

        self.canvas.bind("<Button-1>", func=click)

        #[CLICK][CALLBACK] Create pop-up window
        def new_page(self):
            self.popup_flag = 1
            # Left bone
            if self.popup_switch == 0:
                self.popup = Toplevel(self.window)
                self.popup.title("Sure?")
                self.popup_label = tkinter.Label(self.popup,
                                                 text="Left hand side",
                                                 fg="black")
                self.popup_label.config(width=20)
                self.popup_label.config(font=("Courier", 14))
                self.popup.geometry("%dx%d" % (200, 200))
                self.center(self.popup)
                self.popup_label.pack()

                self.btn_popup1 = tkinter.Button(self.popup,
                                                 text="OK",
                                                 height=5,
                                                 width=5,
                                                 command=self.popup_ok)
                self.btn_popup2 = tkinter.Button(self.popup,
                                                 text="CANCLE",
                                                 height=5,
                                                 width=5,
                                                 command=self.popup_cancle)
                self.btn_popup1.pack(side=tkinter.RIGHT)
                self.btn_popup2.pack(side=tkinter.LEFT)
            # Right bone
            else:
                self.popup = Toplevel(self.window)
                self.popup.title("Sure?")
                self.popup_label = tkinter.Label(self.popup,
                                                 text="Right hand side",
                                                 fg="black")
                self.popup_label.config(width=20)
                self.popup_label.config(font=("Courier", 14))
                self.popup.geometry("%dx%d" % (200, 200))
                self.center(self.popup)
                self.popup_label.pack()

                self.btn_popup1 = tkinter.Button(self.popup,
                                                 text="OK",
                                                 height=5,
                                                 width=5,
                                                 command=self.popup_ok)
                self.btn_popup2 = tkinter.Button(self.popup,
                                                 text="CANCLE",
                                                 height=5,
                                                 width=5,
                                                 command=self.popup_cancle)
                self.btn_popup1.pack(side=tkinter.RIGHT)
                self.btn_popup2.pack(side=tkinter.LEFT)

        self.window.mainloop()

    # Set window on the center
    def center(self, toplevel):
        toplevel.update_idletasks()

        # Tkinter way to find the screen resolution
        # screen_width = toplevel.winfo_screenwidth()
        # screen_height = toplevel.winfo_screenheight()

        # PyQt way to find the screen resolution
        app = QApplication([])
        screen_width = app.desktop().screenGeometry().width()
        screen_height = app.desktop().screenGeometry().height()

        size = tuple(
            int(_) for _ in toplevel.geometry().split('+')[0].split('x'))
        x = screen_width / 2 - size[0] / 2
        y = screen_height / 2 - size[1] / 2

        toplevel.geometry("+%d+%d" % (x, y))
        #toplevel.title("Centered!")

    def set_canvas(self):
        self.cv_img = cv2.cvtColor(cv2.imread(self.img_path),
                                   cv2.COLOR_BGR2RGB)
        self.photo = PIL.ImageTk.PhotoImage(
            image=PIL.Image.fromarray(self.cv_img))
        self.canvas.create_image(0, 0, image=self.photo, anchor=tkinter.NW)
        self.canvas.pack(side='left', fill='both')
        self.canvas.config(scrollregion=self.canvas.bbox('all'))

        self.entry_id_var.set(self.img_id)

    # Read CSV file
    def read_todoList(self, csv_file):
        df = pd.read_csv(csv_file)
        df_notCrop = df[df['Cropped'] != 'Y']
        #todoList = df_notCrop.iloc[0:]['PatientID'].tolist()
        startIndex = np.where(df['Cropped'] != 'Y')[0].tolist()[0]
        #print('******', df.at[startIndex,'Cropped'])
        #print("whole list = ",df.iloc[0:]['PatientID'].tolist())

        return df, startIndex

    # Update csv whenever finishing an image.
    def write_csv(self, df, row, column, path):
        df.to_csv(path + 'annotation_prev.csv', index=0)
        df2 = df
        df2.at[row, column] = 'Y'
        df2.at[row, 'Time'] = time.strftime("%b/%d/%X", time.localtime())
        df2.to_csv(path + 'annotation.csv', index=0)

    # Save cropped mask
    def save_mask(self, side='L'):
        left_x = self.currentx - int(self.width / 2) - 50
        left_y = self.currenty - int(self.height / 2) - 50
        right_x = self.currentx + int(self.width / 2) + 50
        right_y = self.currenty + int(self.height / 2) + 50

        if side == 'L':
            if not os.path.exists(self.dataset_path + 'crop_L/'):
                os.makedirs(self.dataset_path + 'crop_L/')
            file_name = self.dataset_path + 'crop_L/' + self.img_id + '_' + side + '.jpg'
        else:
            if not os.path.exists(self.dataset_path + 'crop_R/'):
                os.makedirs(self.dataset_path + 'crop_R/')
            file_name = self.dataset_path + 'crop_R/' + self.img_id + '_' + side + '.jpg'

        self.image.crop((left_x, left_y, right_x, right_y)).save(file_name)

    # Valid list for entry object to restrict some characters.
    def validate(self, action, index, value_if_allowed, prior_value, text,
                 validation_type, trigger_type, widget_name):
        if text in '0123456789':
            try:
                float(value_if_allowed)
                return True
            except ValueError:
                return False
        else:
            return False

    #[BUTTON][CALLBACK] Callback for btn_crop_size or "OK" button
    def crop_size(self):
        self.height = int(self.crop_height.get())
        self.width = int(self.crop_width.get())

    #[BUTTON][CALLBACK] Callback for new_page popup "OK" button
    def popup_ok(self):
        # Left bone is finished
        if self.popup_switch == 0:
            self.popup_switch = 1
            self.left_x = int(self.currentx - self.width / 2)
            self.left_y = int(self.currenty - self.height / 2)
            self.left_height = self.height
            self.left_width = self.width
            self.save_mask(side='L')

        # Right bone is finished
        else:
            self.popup_switch = 0
            self.write_csv(self.df,
                           row=self.startIndex,
                           column='Cropped',
                           path=self.dataset_path)

            first_data = [{
                'patientID': self.img_id,
                'left_x': self.left_x,
                'left_y': self.left_y,
                'left_width': self.left_width,
                'left_height': self.left_height,
                'right_x': int(self.currentx - self.width / 2),
                'right_y': int(self.currenty - self.height / 2),
                'right_width': self.width,
                'right_height': self.height
            }]

            data = {
                'patientID': self.img_id,
                'left_x': self.left_x,
                'left_y': self.left_y,
                'left_width': self.left_width,
                'left_height': self.left_height,
                'right_x': int(self.currentx - self.width / 2),
                'right_y': int(self.currenty - self.height / 2),
                'right_width': self.width,
                'right_height': self.height
            }

            self.save_mask(side='R')

            if Path(self.json_file).exists():
                with open(self.json_file, 'r') as f:
                    self.json_data = json.load(f)
                    self.json_data.append(data)

                with open(self.json_file, 'w') as f:
                    json.dump(self.json_data, f)
            else:
                with open(self.json_file, 'w') as f:
                    json.dump(first_data, f)

            self.startIndex += 1
            self.img_path = str(self.xray_list[self.startIndex].absolute())
            self.img_id = self.xray_list[self.startIndex].stem

            self.set_canvas()

        self.popup.destroy()
        self.popup_flag = 0

    #[BUTTON][CALLBACK] Callback for new_page popup "CANCLE" button
    def popup_cancle(self):
        self.popup.destroy()
        self.popup_flag = 0
class UninstallWindow:
    def __init__(self, installpath, installtype):
        global root
        self.installpath = installpath
        self.installtype = installtype
        self.master = Toplevel(root)
        self.master.withdraw()
        self.master.iconbitmap(imgdir)
        self.master.protocol('WM_DELETE_WINDOW', root.destroy)
        self.master.title('Adb & Fastboot uninstaller - By @Pato05')
        self.master.resizable(False, False)
        self.master.geometry('400x100+100+100')
        frame = Frame(self.master, relief=FLAT)
        frame.pack(padx=10, pady=5, fill=BOTH)
        Label(frame, text='Found an installation of Adb & Fastboot.',
              font=('Segoe UI', 12)).pack(fill=X)
        Label(frame, text='What do you want to do?',
              font=('Segoe UI', 12)).pack(fill=X)
        btnframe = Frame(frame, relief=FLAT)
        btnframe.pack(fill=X, pady=(10, 0))
        Button(btnframe, text='Uninstall', command=self.uninstall).pack(
            side=LEFT, anchor='w', expand=1)
        Button(btnframe, text='Update', command=self.update).pack(
            side=RIGHT, anchor='e', expand=1)
        self.master.deiconify()

    def uninstall(self):
        self.app = FinishWindow(True, self.remove(True), None, 'uninstall')
        self.master.destroy()

    def remove(self, removePath=True):
        from subprocess import call as subcall
        subcall([os.path.join(self.installpath, "adb.exe"), 'kill-server'], creationflags=0x00000008)
        rmtree(self.installpath)
        if removePath:
            return clearPath(self.installpath, self.installtype == 'system')
        else:
            return True

    def update(self):
        self.remove(False)
        self.app = InstallWindow(
            False, self.installpath, self.installtype == 'system', 'update')
        self.master.destroy()
Пример #49
0
 def __init__(self, master=None):
     Toplevel.__init__(self, master)
     self.createWidgets()
Пример #50
0
class Manage_staff:
    def __init__(self):
        self.top = Toplevel()
        self.top.title("Manage Employees")
        self.top.geometry("1301x820+250+130")
        self.top.resizable(False, False)

        main_heading = ttk.Label(self.top,
                                 text="Staff Management",
                                 foreground="red",
                                 font=("arial", 30, "bold italic"))
        main_heading.pack(padx=300)

        self.tv = ttk.Treeview(self.top, height=32)
        self.tv.pack()
        self.tv["columns"] = ("first_name", "last_name")
        self.tv.heading("#0", text="Id")
        self.tv.heading("first_name", text="First Name")
        self.tv.heading("last_name", text="Last Name")

        self.tv.column("#0", width=410)
        self.tv.column("first_name", width=410)
        self.tv.column("last_name", width=410)

        with connection_pool.getconn() as connection:
            with connection.cursor() as cursor:
                cursor.execute(
                    "select id as total, frist_name, last_name from users order by total asc"
                )
                for item in list(cursor):
                    self.tv.insert('',
                                   "end",
                                   text=f"{item[0]}",
                                   values=(f'{item[1]}', f'{item[2]}'))

        self.tv.column("#0", anchor="center")
        self.tv.column("first_name", anchor="center")
        self.tv.column("last_name", anchor="center")

        style = ttk.Style()
        style.configure(style="frame.TFrame")

        self.frame_buttons = ttk.Frame(self.top)
        self.frame_buttons.configure(width=1301, height=75)
        self.frame_buttons.pack(side="bottom", pady=10)

        self.button_add_staff = Button(self.frame_buttons,
                                       text="Add New Staff",
                                       command=self.Add_new_employee,
                                       bg="blue",
                                       fg="white")
        self.button_add_staff.grid(ipadx=30, ipady=20, padx=10)

        self.button_edit_staff = Button(self.frame_buttons,
                                        text="Edit Staff",
                                        bg="blue",
                                        fg="white",
                                        command=self.edit)
        self.button_edit_staff.grid(ipadx=30,
                                    ipady=20,
                                    row=0,
                                    column=1,
                                    padx=10)

        self.button_delete_staff = Button(self.frame_buttons,
                                          text="Delete Staff",
                                          bg="blue",
                                          fg="white",
                                          command=self.delete)
        self.button_delete_staff.grid(ipadx=30,
                                      ipady=20,
                                      row=0,
                                      column=2,
                                      padx=10)

        self.button_refresh = Button(self.frame_buttons,
                                     text="   Refresh    ",
                                     bg="blue",
                                     fg="white",
                                     command=self.refresh)
        self.button_refresh.grid(ipadx=30, ipady=20, row=0, column=3, padx=10)

    def refresh(self):
        self.tv.delete(*self.tv.get_children())
        with connection_pool.getconn() as connection:
            with connection.cursor() as cursor:
                cursor.execute(
                    "select id as total, frist_name, last_name from users order by total asc"
                )
                for item in list(cursor):
                    self.tv.insert('',
                                   "end",
                                   text=f"{item[0]}",
                                   values=(f'{item[1]}', f'{item[2]}'))

    def delete(self):
        ci = self.tv.focus()
        table_value = self.tv.item(ci)
        if len(table_value["text"]) == 0 or len(table_value["values"]) == 0:
            messagebox.showerror(
                "please select something",
                "Select the user which one should you went to delete")
        else:
            popup = messagebox.askyesno(
                title="asking", message="Do you went to delete this user")
            if popup:
                with connection_pool.getconn() as connection:
                    with connection.cursor() as cursor:
                        cursor.execute("delete from users Where id=%s",
                                       (table_value['text'], ))

    def edit(self):

        ci = self.tv.focus()
        table_value = self.tv.item(ci)

        if len(table_value["text"]) == 0 or len(table_value["values"]) == 0:
            messagebox.showerror(
                "warning", "Select any user which one should you went to edit")
        else:
            self.top_1 = Toplevel()
            self.top_1.title("Add New Menu Item")
            self.top_1.geometry("620x455+550+230")
            self.top_1.resizable(False, False)

            label_id = ttk.Label(
                self.top_1,
                text="Staff id :                            "
                "                                                   ",
                font=("arial", 15))
            label_id.pack()

            strvar1 = StringVar()

            self.entry_id_one = Entry(self.top_1,
                                      width=50,
                                      font=("arial", 15),
                                      textvariable=strvar1)
            self.entry_id_one.pack(pady=30)
            self.entry_id_one.insert(0, table_value['text'])
            self.entry_id_one.config(state="disable")

            label_id = ttk.Label(
                self.top_1,
                text="Staff first name :                       "
                "                                             ",
                font=("arial", 15))
            label_id.pack()

            strvar2 = StringVar()

            self.entry_first_name_one = Entry(self.top_1,
                                              width=50,
                                              font=("arial", 15),
                                              textvariable=strvar2)
            self.entry_first_name_one.insert(0, table_value['values'][0])
            self.entry_first_name_one.pack(pady=30)

            label_id = ttk.Label(
                self.top_1,
                text="Staff last name :                "
                "                                                     ",
                font=("arial", 15))
            label_id.pack()

            strvar3 = StringVar()

            self.entry_last_name_one = Entry(self.top_1,
                                             width=50,
                                             font=("arial", 15),
                                             textvariable=strvar3)
            self.entry_last_name_one.insert(0, table_value['values'][1])
            self.entry_last_name_one.pack(pady=30)

            style = ttk.Style()
            style.configure(style="frame.TFrame", background="blue")

            frame_buttons_1 = ttk.Frame(self.top_1)
            frame_buttons_1.pack()
            frame_buttons_1.configure(width=550, height=60)

            button_save1 = Button(frame_buttons_1,
                                  text="Save",
                                  bg="blue",
                                  fg="#FFD5C6",
                                  height=3,
                                  width=15,
                                  command=self.Update)
            button_save1.grid(row=0, column=0, padx=40, ipadx=20, ipady=10)
            button_cancel = Button(frame_buttons_1,
                                   text="Cancel",
                                   bg="blue",
                                   fg="#FFD5C6",
                                   height=3,
                                   width=15,
                                   command=self.cancel)
            button_cancel.grid(row=0, column=1, padx=40, ipadx=20, ipady=10)

    def cancel(self):
        self.top_1.destroy()

    def Add_new_employee(self):
        self.top_2 = Toplevel()
        self.top_2.title("Add Staff Item")
        self.top_2.geometry("620x495+550+230")
        self.top_2.resizable(False, False)

        self.strvar1 = StringVar()

        label_id = ttk.Label(
            self.top_2,
            text=
            "Staff Id :                                                                               ",
            font=("arial", 15))

        label_id.pack(pady=5)
        self.entry_id = ttk.Entry(self.top_2,
                                  width=50,
                                  font=("arial", 15),
                                  textvariable=self.strvar1)
        self.entry_id.pack(pady=20)

        label_id = ttk.Label(
            self.top_2,
            text=
            "Staff First Name :                                                                  ",
            font=("arial", 15))
        label_id.pack(pady=5)

        self.strvar2 = StringVar()

        self.entry_first_name = ttk.Entry(self.top_2,
                                          width=50,
                                          font=("arial", 15),
                                          textvariable=self.strvar2)
        self.entry_first_name.pack(pady=20)

        label_id = ttk.Label(
            self.top_2,
            text=
            "Staff Last Name :                                                                   ",
            font=("arial", 15))
        label_id.pack(pady=5)

        self.strvar3 = StringVar()

        self.entry_last_name = ttk.Entry(self.top_2,
                                         width=50,
                                         font=("arial", 15),
                                         textvariable=self.strvar3)
        self.entry_last_name.pack(pady=20)

        label_id = ttk.Label(
            self.top_2,
            text=
            "Password :                                                       "******"                  "
            "   ",
            font=("arial", 15))
        label_id.pack(pady=5)

        self.strvar4 = StringVar()

        self.entry_password = ttk.Entry(self.top_2,
                                        font=("arial", 15),
                                        width=50,
                                        textvariable=self.strvar4)
        self.entry_password.config(show="*")

        self.entry_password.pack()

        self.frame_buttons_1 = ttk.Frame(self.top_2)
        self.frame_buttons_1.configure(width=550,
                                       height=60,
                                       style="frame.TFrame")
        self.frame_buttons_1.pack(pady=20)

        self.button_save = Button(self.frame_buttons_1,
                                  text="Save",
                                  command=self.Save,
                                  bg="blue",
                                  fg="#FFD5C6",
                                  height=3,
                                  width=15)

        self.button_new = Button(self.frame_buttons_1,
                                 text="New",
                                 command=self.New,
                                 bg="blue",
                                 fg="#FFD5C6",
                                 height=3,
                                 width=15)

        self.button_cancel = Button(self.frame_buttons_1,
                                    text="Cancel",
                                    command=self.Cancel,
                                    bg="blue",
                                    fg="#FFD5C6",
                                    height=3,
                                    width=15)

        self.button_save.grid(row=0, column=0, padx=5, ipadx=10)
        self.button_new.grid(row=0, column=1, padx=5, ipadx=10)
        self.button_cancel.grid(row=0, column=2, padx=5, ipadx=10)

    def Cancel(self):
        self.top_2.destroy()

    def Update(self):
        popup = messagebox.askyesno(title="asking",
                                    message="Do you went to update this user")
        if popup:
            if len(self.entry_id_one.get()) == 0 or \
                    len(self.entry_last_name_one.get()) == 0 or \
                    len(self.entry_last_name_one.get()) == 0:
                messagebox.showerror("warning",
                                     "text boxes empty please fill it.")

            else:
                with connection_pool.getconn() as connection:
                    with connection.cursor() as cursor:
                        cursor.execute(
                            "Update users set frist_name=%s, last_name=%s Where id=%s",
                            (self.entry_first_name_one.get(),
                             self.entry_last_name_one.get(),
                             self.entry_id_one.get()))

                        connection.commit()
                        cursor.close()
                        messagebox.showinfo(title="success",
                                            message="successfully")

    def Save(self):
        if len(self.entry_id.get()) == 0 or \
                len(self.entry_first_name.get()) == 0 or \
                len(self.entry_last_name.get()) == 0 or len(self.entry_password.get()) == 0:
            messagebox.showerror(
                "warning", "Those entry fields are empty please fill it.")

        else:
            with connection_pool.getconn() as connection:
                with connection.cursor() as cursor:
                    qu = f"insert into users(id, frist_name, last_name, password) values('{self.strvar1.get()}', '{self.strvar2.get()}', '{self.strvar3.get()}', '{self.strvar4.get()}')"
                    print(qu.strip())
                    cursor.execute(qu)

                    connection.commit()
                    cursor.close()
                    messagebox.showinfo(title="success",
                                        message="successfully")

    def New(self):
        self.entry_id.delete()
        self.entry_first_name.delete()
        self.entry_last_name.delete()
        self.entry_password.delete()
Пример #51
0
class CFGEditor:
    """
    A dialog window for creating and editing context free grammars.
    ``CFGEditor`` imposes the following restrictions:

    - All nonterminals must be strings consisting of word
      characters.
    - All terminals must be strings consisting of word characters
      and space characters.
    """

    # Regular expressions used by _analyze_line.  Precompile them, so
    # we can process the text faster.
    ARROW = SymbolWidget.SYMBOLS["rightarrow"]
    _LHS_RE = re.compile(r"(^\s*\w+\s*)(->|(" + ARROW + "))")
    _ARROW_RE = re.compile(r"\s*(->|(" + ARROW + r"))\s*")
    _PRODUCTION_RE = re.compile(r"(^\s*\w+\s*)" + "(->|("  # LHS
                                + ARROW + r"))\s*" +
                                r"((\w+|'[\w ]*'|\"[\w ]*\"|\|)\s*)*$"  # arrow
                                )  # RHS
    _TOKEN_RE = re.compile("\\w+|->|'[\\w ]+'|\"[\\w ]+\"|(" + ARROW + ")")
    _BOLD = ("helvetica", -12, "bold")

    def __init__(self, parent, cfg=None, set_cfg_callback=None):
        self._parent = parent
        if cfg is not None:
            self._cfg = cfg
        else:
            self._cfg = CFG(Nonterminal("S"), [])
        self._set_cfg_callback = set_cfg_callback

        self._highlight_matching_nonterminals = 1

        # Create the top-level window.
        self._top = Toplevel(parent)
        self._init_bindings()

        self._init_startframe()
        self._startframe.pack(side="top", fill="x", expand=0)
        self._init_prodframe()
        self._prodframe.pack(side="top", fill="both", expand=1)
        self._init_buttons()
        self._buttonframe.pack(side="bottom", fill="x", expand=0)

        self._textwidget.focus()

    def _init_startframe(self):
        frame = self._startframe = Frame(self._top)
        self._start = Entry(frame)
        self._start.pack(side="right")
        Label(frame, text="Start Symbol:").pack(side="right")
        Label(frame, text="Productions:").pack(side="left")
        self._start.insert(0, self._cfg.start().symbol())

    def _init_buttons(self):
        frame = self._buttonframe = Frame(self._top)
        Button(frame, text="Ok", command=self._ok, underline=0,
               takefocus=0).pack(side="left")
        Button(frame,
               text="Apply",
               command=self._apply,
               underline=0,
               takefocus=0).pack(side="left")
        Button(frame,
               text="Reset",
               command=self._reset,
               underline=0,
               takefocus=0).pack(side="left")
        Button(frame,
               text="Cancel",
               command=self._cancel,
               underline=0,
               takefocus=0).pack(side="left")
        Button(frame,
               text="Help",
               command=self._help,
               underline=0,
               takefocus=0).pack(side="right")

    def _init_bindings(self):
        self._top.title("CFG Editor")
        self._top.bind("<Control-q>", self._cancel)
        self._top.bind("<Alt-q>", self._cancel)
        self._top.bind("<Control-d>", self._cancel)
        # self._top.bind('<Control-x>', self._cancel)
        self._top.bind("<Alt-x>", self._cancel)
        self._top.bind("<Escape>", self._cancel)
        # self._top.bind('<Control-c>', self._cancel)
        self._top.bind("<Alt-c>", self._cancel)

        self._top.bind("<Control-o>", self._ok)
        self._top.bind("<Alt-o>", self._ok)
        self._top.bind("<Control-a>", self._apply)
        self._top.bind("<Alt-a>", self._apply)
        self._top.bind("<Control-r>", self._reset)
        self._top.bind("<Alt-r>", self._reset)
        self._top.bind("<Control-h>", self._help)
        self._top.bind("<Alt-h>", self._help)
        self._top.bind("<F1>", self._help)

    def _init_prodframe(self):
        self._prodframe = Frame(self._top)

        # Create the basic Text widget & scrollbar.
        self._textwidget = Text(self._prodframe,
                                background="#e0e0e0",
                                exportselection=1)
        self._textscroll = Scrollbar(self._prodframe,
                                     takefocus=0,
                                     orient="vertical")
        self._textwidget.config(yscrollcommand=self._textscroll.set)
        self._textscroll.config(command=self._textwidget.yview)
        self._textscroll.pack(side="right", fill="y")
        self._textwidget.pack(expand=1, fill="both", side="left")

        # Initialize the colorization tags.  Each nonterminal gets its
        # own tag, so they aren't listed here.
        self._textwidget.tag_config("terminal", foreground="#006000")
        self._textwidget.tag_config("arrow", font="symbol")
        self._textwidget.tag_config("error", background="red")

        # Keep track of what line they're on.  We use that to remember
        # to re-analyze a line whenever they leave it.
        self._linenum = 0

        # Expand "->" to an arrow.
        self._top.bind(">", self._replace_arrows)

        # Re-colorize lines when appropriate.
        self._top.bind("<<Paste>>", self._analyze)
        self._top.bind("<KeyPress>", self._check_analyze)
        self._top.bind("<ButtonPress>", self._check_analyze)

        # Tab cycles focus. (why doesn't this work??)
        def cycle(e, textwidget=self._textwidget):
            textwidget.tk_focusNext().focus()

        self._textwidget.bind("<Tab>", cycle)

        prod_tuples = [(p.lhs(), [p.rhs()]) for p in self._cfg.productions()]
        for i in range(len(prod_tuples) - 1, 0, -1):
            if prod_tuples[i][0] == prod_tuples[i - 1][0]:
                if () in prod_tuples[i][1]:
                    continue
                if () in prod_tuples[i - 1][1]:
                    continue
                print(prod_tuples[i - 1][1])
                print(prod_tuples[i][1])
                prod_tuples[i - 1][1].extend(prod_tuples[i][1])
                del prod_tuples[i]

        for lhs, rhss in prod_tuples:
            print(lhs, rhss)
            s = "%s ->" % lhs
            for rhs in rhss:
                for elt in rhs:
                    if isinstance(elt, Nonterminal):
                        s += " %s" % elt
                    else:
                        s += " %r" % elt
                s += " |"
            s = s[:-2] + "\n"
            self._textwidget.insert("end", s)

        self._analyze()

    #         # Add the producitons to the text widget, and colorize them.
    #         prod_by_lhs = {}
    #         for prod in self._cfg.productions():
    #             if len(prod.rhs()) > 0:
    #                 prod_by_lhs.setdefault(prod.lhs(),[]).append(prod)
    #         for (lhs, prods) in prod_by_lhs.items():
    #             self._textwidget.insert('end', '%s ->' % lhs)
    #             self._textwidget.insert('end', self._rhs(prods[0]))
    #             for prod in prods[1:]:
    #                 print '\t|'+self._rhs(prod),
    #                 self._textwidget.insert('end', '\t|'+self._rhs(prod))
    #             print
    #             self._textwidget.insert('end', '\n')
    #         for prod in self._cfg.productions():
    #             if len(prod.rhs()) == 0:
    #                 self._textwidget.insert('end', '%s' % prod)
    #         self._analyze()

    #     def _rhs(self, prod):
    #         s = ''
    #         for elt in prod.rhs():
    #             if isinstance(elt, Nonterminal): s += ' %s' % elt.symbol()
    #             else: s += ' %r' % elt
    #         return s

    def _clear_tags(self, linenum):
        """
        Remove all tags (except ``arrow`` and ``sel``) from the given
        line of the text widget used for editing the productions.
        """
        start = "%d.0" % linenum
        end = "%d.end" % linenum
        for tag in self._textwidget.tag_names():
            if tag not in ("arrow", "sel"):
                self._textwidget.tag_remove(tag, start, end)

    def _check_analyze(self, *e):
        """
        Check if we've moved to a new line.  If we have, then remove
        all colorization from the line we moved to, and re-colorize
        the line that we moved from.
        """
        linenum = int(self._textwidget.index("insert").split(".")[0])
        if linenum != self._linenum:
            self._clear_tags(linenum)
            self._analyze_line(self._linenum)
            self._linenum = linenum

    def _replace_arrows(self, *e):
        """
        Replace any ``'->'`` text strings with arrows (char \\256, in
        symbol font).  This searches the whole buffer, but is fast
        enough to be done anytime they press '>'.
        """
        arrow = "1.0"
        while True:
            arrow = self._textwidget.search("->", arrow, "end+1char")
            if arrow == "":
                break
            self._textwidget.delete(arrow, arrow + "+2char")
            self._textwidget.insert(arrow, self.ARROW, "arrow")
            self._textwidget.insert(arrow, "\t")

        arrow = "1.0"
        while True:
            arrow = self._textwidget.search(self.ARROW, arrow + "+1char",
                                            "end+1char")
            if arrow == "":
                break
            self._textwidget.tag_add("arrow", arrow, arrow + "+1char")

    def _analyze_token(self, match, linenum):
        """
        Given a line number and a regexp match for a token on that
        line, colorize the token.  Note that the regexp match gives us
        the token's text, start index (on the line), and end index (on
        the line).
        """
        # What type of token is it?
        if match.group()[0] in "'\"":
            tag = "terminal"
        elif match.group() in ("->", self.ARROW):
            tag = "arrow"
        else:
            # If it's a nonterminal, then set up new bindings, so we
            # can highlight all instances of that nonterminal when we
            # put the mouse over it.
            tag = "nonterminal_" + match.group()
            if tag not in self._textwidget.tag_names():
                self._init_nonterminal_tag(tag)

        start = "%d.%d" % (linenum, match.start())
        end = "%d.%d" % (linenum, match.end())
        self._textwidget.tag_add(tag, start, end)

    def _init_nonterminal_tag(self, tag, foreground="blue"):
        self._textwidget.tag_config(tag,
                                    foreground=foreground,
                                    font=CFGEditor._BOLD)
        if not self._highlight_matching_nonterminals:
            return

        def enter(e, textwidget=self._textwidget, tag=tag):
            textwidget.tag_config(tag, background="#80ff80")

        def leave(e, textwidget=self._textwidget, tag=tag):
            textwidget.tag_config(tag, background="")

        self._textwidget.tag_bind(tag, "<Enter>", enter)
        self._textwidget.tag_bind(tag, "<Leave>", leave)

    def _analyze_line(self, linenum):
        """
        Colorize a given line.
        """
        # Get rid of any tags that were previously on the line.
        self._clear_tags(linenum)

        # Get the line line's text string.
        line = self._textwidget.get(
            repr(linenum) + ".0",
            repr(linenum) + ".end")

        # If it's a valid production, then colorize each token.
        if CFGEditor._PRODUCTION_RE.match(line):
            # It's valid; Use _TOKEN_RE to tokenize the production,
            # and call analyze_token on each token.
            def analyze_token(match, self=self, linenum=linenum):
                self._analyze_token(match, linenum)
                return ""

            CFGEditor._TOKEN_RE.sub(analyze_token, line)
        elif line.strip() != "":
            # It's invalid; show the user where the error is.
            self._mark_error(linenum, line)

    def _mark_error(self, linenum, line):
        """
        Mark the location of an error in a line.
        """
        arrowmatch = CFGEditor._ARROW_RE.search(line)
        if not arrowmatch:
            # If there's no arrow at all, highlight the whole line.
            start = "%d.0" % linenum
            end = "%d.end" % linenum
        elif not CFGEditor._LHS_RE.match(line):
            # Otherwise, if the LHS is bad, highlight it.
            start = "%d.0" % linenum
            end = "%d.%d" % (linenum, arrowmatch.start())
        else:
            # Otherwise, highlight the RHS.
            start = "%d.%d" % (linenum, arrowmatch.end())
            end = "%d.end" % linenum

        # If we're highlighting 0 chars, highlight the whole line.
        if self._textwidget.compare(start, "==", end):
            start = "%d.0" % linenum
            end = "%d.end" % linenum
        self._textwidget.tag_add("error", start, end)

    def _analyze(self, *e):
        """
        Replace ``->`` with arrows, and colorize the entire buffer.
        """
        self._replace_arrows()
        numlines = int(self._textwidget.index("end").split(".")[0])
        for linenum in range(1, numlines + 1):  # line numbers start at 1.
            self._analyze_line(linenum)

    def _parse_productions(self):
        """
        Parse the current contents of the textwidget buffer, to create
        a list of productions.
        """
        productions = []

        # Get the text, normalize it, and split it into lines.
        text = self._textwidget.get("1.0", "end")
        text = re.sub(self.ARROW, "->", text)
        text = re.sub("\t", " ", text)
        lines = text.split("\n")

        # Convert each line to a CFG production
        for line in lines:
            line = line.strip()
            if line == "":
                continue
            productions += _read_cfg_production(line)
            # if line.strip() == '': continue
            # if not CFGEditor._PRODUCTION_RE.match(line):
            #    raise ValueError('Bad production string %r' % line)
            #
            # (lhs_str, rhs_str) = line.split('->')
            # lhs = Nonterminal(lhs_str.strip())
            # rhs = []
            # def parse_token(match, rhs=rhs):
            #    token = match.group()
            #    if token[0] in "'\"": rhs.append(token[1:-1])
            #    else: rhs.append(Nonterminal(token))
            #    return ''
            # CFGEditor._TOKEN_RE.sub(parse_token, rhs_str)
            #
            # productions.append(Production(lhs, *rhs))

        return productions

    def _destroy(self, *e):
        if self._top is None:
            return
        self._top.destroy()
        self._top = None

    def _ok(self, *e):
        self._apply()
        self._destroy()

    def _apply(self, *e):
        productions = self._parse_productions()
        start = Nonterminal(self._start.get())
        cfg = CFG(start, productions)
        if self._set_cfg_callback is not None:
            self._set_cfg_callback(cfg)

    def _reset(self, *e):
        self._textwidget.delete("1.0", "end")
        for production in self._cfg.productions():
            self._textwidget.insert("end", "%s\n" % production)
        self._analyze()
        if self._set_cfg_callback is not None:
            self._set_cfg_callback(self._cfg)

    def _cancel(self, *e):
        try:
            self._reset()
        except:
            pass
        self._destroy()

    def _help(self, *e):
        # The default font's not very legible; try using 'fixed' instead.
        try:
            ShowText(
                self._parent,
                "Help: Chart Parser Demo",
                (_CFGEditor_HELP).strip(),
                width=75,
                font="fixed",
            )
        except:
            ShowText(
                self._parent,
                "Help: Chart Parser Demo",
                (_CFGEditor_HELP).strip(),
                width=75,
            )
Пример #52
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()
Пример #53
0
    def show(self, event=None):
        def tip_pos_calculator(canvas, label,
                               *,
                               tip_delta=(10, 5), pad=(5, 3, 5, 3)):

            c = canvas

            s_width, s_height = c.winfo_screenwidth(), c.winfo_screenheight()

            width, height = (pad[0] + label.winfo_reqwidth() + pad[2],
                             pad[1] + label.winfo_reqheight() + pad[3])

            mouse_x, mouse_y = c.winfo_pointerxy()

            x1, y1 = mouse_x + tip_delta[0], mouse_y + tip_delta[1]
            x2, y2 = x1 + width, y1 + height

            x_delta = x2 - s_width
            if x_delta < 0:
                x_delta = 0
            y_delta = y2 - s_height
            if y_delta < 0:
                y_delta = 0

            offscreen = (x_delta, y_delta) != (0, 0)

            if offscreen:

                if x_delta:
                    x1 = mouse_x - tip_delta[0] - width

                if y_delta:
                    y1 = mouse_y - tip_delta[1] - height

            offscreen_again = y1 < 0  # out on the top

            if offscreen_again:
                # No further checks will be done.

                # TIP:
                # A further mod might automagically augment the
                # wraplength when the tooltip is too high to be
                # kept inside the screen.
                y1 = 0

            return x1, y1

        bg = self.bg
        pad = self.pad
        canvas = self.canvas

        # creates a toplevel window
        self.tw = Toplevel(canvas.master)

        # Leaves only the label and removes the app window
        self.tw.wm_overrideredirect(True)

        win = Frame(self.tw,
                       # background=bg,
                       borderwidth=0)
        label = Label(win,
                          text=self.text,
                          justify='left',
                          background=bg,
                          relief="solid",
                          borderwidth=0,
                          wraplength=self.wraplength)

        label.grid(padx=(pad[0], pad[2]),
                   pady=(pad[1], pad[3]),
                   sticky='nsew')
        win.grid()

        x, y = tip_pos_calculator(canvas, label)

        self.tw.wm_geometry("+%d+%d" % (x, y))
class FinishWindow:
    def __init__(self, setpath, pathres, installpath, type='install'):
        global root
        self.master = Toplevel(root)
        self.master.withdraw()
        self.master.protocol('WM_DELETE_WINDOW', root.destroy)
        self.master.iconbitmap(imgdir)
        self.master.title('Adb & Fastboot installer - By @Pato05')
        self.master.resizable(False, False)
        frame = Frame(self.master, relief=FLAT)
        frame.pack(padx=10, pady=5, fill=BOTH)
        Label(frame, text=('Adb & Fastboot were successfully %s!' % (
            'updated' if type == 'update' else type+'ed')), font=('Segoe UI', 15)).pack(fill=X)
        if installpath is not None:
            Label(frame, text='Installation path: %s' %
                  installpath, font=('Segoe UI', 12)).pack(fill=X)
        if setpath == 1 and pathres:
            Label(frame, text='You might need to restart applications to update PATH.', font=(
                'Segoe UI', 12)).pack(fill=X)
        elif setpath == 1 and not pathres:
            Style().configure('Red.TLabel', foreground='red')
            Label(frame, text='Failed to put Adb & Fastboot into path.',
                  font=('Segoe UI', 12), style='Red.TLabel').pack(fill=X)
        self.master.deiconify()
Пример #55
0
def donothing():
    filewin = Toplevel(layar)
    button = Button(master=filewin,
                    text="Do Nothing Button",
                    command=filewin.destroy)
    button.pack()
Пример #56
0
                  label=name,
                  orient=HORIZONTAL,
                  from_=lo,
                  to=hi,
                  resolution=0.01,
                  command=self.update)
        s.set(self.value)
        s.pack()

    def update(self, value):
        self.value = eval(value)
        self.tkim.paste(self.enhancer.enhance(self.value))


#
# main

root = Tk()

im = Image.open(sys.argv[1])

im.thumbnail((200, 200))

Enhance(root, im, "Color", ImageEnhance.Color, 0.0, 4.0).pack()
Enhance(Toplevel(), im, "Sharpness", ImageEnhance.Sharpness, -2.0, 2.0).pack()
Enhance(Toplevel(), im, "Brightness", ImageEnhance.Brightness, -1.0,
        3.0).pack()
Enhance(Toplevel(), im, "Contrast", ImageEnhance.Contrast, -1.0, 3.0).pack()

root.mainloop()
Пример #57
0
    def __init__(self):
        self.top = Toplevel()
        self.top.title("Manage Employees")
        self.top.geometry("1301x820+250+130")
        self.top.resizable(False, False)

        main_heading = ttk.Label(self.top,
                                 text="Staff Management",
                                 foreground="red",
                                 font=("arial", 30, "bold italic"))
        main_heading.pack(padx=300)

        self.tv = ttk.Treeview(self.top, height=32)
        self.tv.pack()
        self.tv["columns"] = ("first_name", "last_name")
        self.tv.heading("#0", text="Id")
        self.tv.heading("first_name", text="First Name")
        self.tv.heading("last_name", text="Last Name")

        self.tv.column("#0", width=410)
        self.tv.column("first_name", width=410)
        self.tv.column("last_name", width=410)

        with connection_pool.getconn() as connection:
            with connection.cursor() as cursor:
                cursor.execute(
                    "select id as total, frist_name, last_name from users order by total asc"
                )
                for item in list(cursor):
                    self.tv.insert('',
                                   "end",
                                   text=f"{item[0]}",
                                   values=(f'{item[1]}', f'{item[2]}'))

        self.tv.column("#0", anchor="center")
        self.tv.column("first_name", anchor="center")
        self.tv.column("last_name", anchor="center")

        style = ttk.Style()
        style.configure(style="frame.TFrame")

        self.frame_buttons = ttk.Frame(self.top)
        self.frame_buttons.configure(width=1301, height=75)
        self.frame_buttons.pack(side="bottom", pady=10)

        self.button_add_staff = Button(self.frame_buttons,
                                       text="Add New Staff",
                                       command=self.Add_new_employee,
                                       bg="blue",
                                       fg="white")
        self.button_add_staff.grid(ipadx=30, ipady=20, padx=10)

        self.button_edit_staff = Button(self.frame_buttons,
                                        text="Edit Staff",
                                        bg="blue",
                                        fg="white",
                                        command=self.edit)
        self.button_edit_staff.grid(ipadx=30,
                                    ipady=20,
                                    row=0,
                                    column=1,
                                    padx=10)

        self.button_delete_staff = Button(self.frame_buttons,
                                          text="Delete Staff",
                                          bg="blue",
                                          fg="white",
                                          command=self.delete)
        self.button_delete_staff.grid(ipadx=30,
                                      ipady=20,
                                      row=0,
                                      column=2,
                                      padx=10)

        self.button_refresh = Button(self.frame_buttons,
                                     text="   Refresh    ",
                                     bg="blue",
                                     fg="white",
                                     command=self.refresh)
        self.button_refresh.grid(ipadx=30, ipady=20, row=0, column=3, padx=10)
Пример #58
0
    def Add_new_employee(self):
        self.top_2 = Toplevel()
        self.top_2.title("Add Staff Item")
        self.top_2.geometry("620x495+550+230")
        self.top_2.resizable(False, False)

        self.strvar1 = StringVar()

        label_id = ttk.Label(
            self.top_2,
            text=
            "Staff Id :                                                                               ",
            font=("arial", 15))

        label_id.pack(pady=5)
        self.entry_id = ttk.Entry(self.top_2,
                                  width=50,
                                  font=("arial", 15),
                                  textvariable=self.strvar1)
        self.entry_id.pack(pady=20)

        label_id = ttk.Label(
            self.top_2,
            text=
            "Staff First Name :                                                                  ",
            font=("arial", 15))
        label_id.pack(pady=5)

        self.strvar2 = StringVar()

        self.entry_first_name = ttk.Entry(self.top_2,
                                          width=50,
                                          font=("arial", 15),
                                          textvariable=self.strvar2)
        self.entry_first_name.pack(pady=20)

        label_id = ttk.Label(
            self.top_2,
            text=
            "Staff Last Name :                                                                   ",
            font=("arial", 15))
        label_id.pack(pady=5)

        self.strvar3 = StringVar()

        self.entry_last_name = ttk.Entry(self.top_2,
                                         width=50,
                                         font=("arial", 15),
                                         textvariable=self.strvar3)
        self.entry_last_name.pack(pady=20)

        label_id = ttk.Label(
            self.top_2,
            text=
            "Password :                                                       "******"                  "
            "   ",
            font=("arial", 15))
        label_id.pack(pady=5)

        self.strvar4 = StringVar()

        self.entry_password = ttk.Entry(self.top_2,
                                        font=("arial", 15),
                                        width=50,
                                        textvariable=self.strvar4)
        self.entry_password.config(show="*")

        self.entry_password.pack()

        self.frame_buttons_1 = ttk.Frame(self.top_2)
        self.frame_buttons_1.configure(width=550,
                                       height=60,
                                       style="frame.TFrame")
        self.frame_buttons_1.pack(pady=20)

        self.button_save = Button(self.frame_buttons_1,
                                  text="Save",
                                  command=self.Save,
                                  bg="blue",
                                  fg="#FFD5C6",
                                  height=3,
                                  width=15)

        self.button_new = Button(self.frame_buttons_1,
                                 text="New",
                                 command=self.New,
                                 bg="blue",
                                 fg="#FFD5C6",
                                 height=3,
                                 width=15)

        self.button_cancel = Button(self.frame_buttons_1,
                                    text="Cancel",
                                    command=self.Cancel,
                                    bg="blue",
                                    fg="#FFD5C6",
                                    height=3,
                                    width=15)

        self.button_save.grid(row=0, column=0, padx=5, ipadx=10)
        self.button_new.grid(row=0, column=1, padx=5, ipadx=10)
        self.button_cancel.grid(row=0, column=2, padx=5, ipadx=10)
Пример #59
0
    def edit(self):

        ci = self.tv.focus()
        table_value = self.tv.item(ci)

        if len(table_value["text"]) == 0 or len(table_value["values"]) == 0:
            messagebox.showerror(
                "warning", "Select any user which one should you went to edit")
        else:
            self.top_1 = Toplevel()
            self.top_1.title("Add New Menu Item")
            self.top_1.geometry("620x455+550+230")
            self.top_1.resizable(False, False)

            label_id = ttk.Label(
                self.top_1,
                text="Staff id :                            "
                "                                                   ",
                font=("arial", 15))
            label_id.pack()

            strvar1 = StringVar()

            self.entry_id_one = Entry(self.top_1,
                                      width=50,
                                      font=("arial", 15),
                                      textvariable=strvar1)
            self.entry_id_one.pack(pady=30)
            self.entry_id_one.insert(0, table_value['text'])
            self.entry_id_one.config(state="disable")

            label_id = ttk.Label(
                self.top_1,
                text="Staff first name :                       "
                "                                             ",
                font=("arial", 15))
            label_id.pack()

            strvar2 = StringVar()

            self.entry_first_name_one = Entry(self.top_1,
                                              width=50,
                                              font=("arial", 15),
                                              textvariable=strvar2)
            self.entry_first_name_one.insert(0, table_value['values'][0])
            self.entry_first_name_one.pack(pady=30)

            label_id = ttk.Label(
                self.top_1,
                text="Staff last name :                "
                "                                                     ",
                font=("arial", 15))
            label_id.pack()

            strvar3 = StringVar()

            self.entry_last_name_one = Entry(self.top_1,
                                             width=50,
                                             font=("arial", 15),
                                             textvariable=strvar3)
            self.entry_last_name_one.insert(0, table_value['values'][1])
            self.entry_last_name_one.pack(pady=30)

            style = ttk.Style()
            style.configure(style="frame.TFrame", background="blue")

            frame_buttons_1 = ttk.Frame(self.top_1)
            frame_buttons_1.pack()
            frame_buttons_1.configure(width=550, height=60)

            button_save1 = Button(frame_buttons_1,
                                  text="Save",
                                  bg="blue",
                                  fg="#FFD5C6",
                                  height=3,
                                  width=15,
                                  command=self.Update)
            button_save1.grid(row=0, column=0, padx=40, ipadx=20, ipady=10)
            button_cancel = Button(frame_buttons_1,
                                   text="Cancel",
                                   bg="blue",
                                   fg="#FFD5C6",
                                   height=3,
                                   width=15,
                                   command=self.cancel)
            button_cancel.grid(row=0, column=1, padx=40, ipadx=20, ipady=10)
Пример #60
0
def start_k177():
    ''' Start the GUI for Keithely 177 Digital Multimeter
    '''
    k177_window = Toplevel(root)
    k177_gui = keithley_gui(k177_window, model_number=177)
    return