Esempio n. 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)
Esempio n. 2
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)
Esempio n. 3
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)
Esempio n. 4
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
Esempio n. 5
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()
Esempio n. 6
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)
Esempio n. 7
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)
Esempio n. 8
0
class InfoWindow:
    def __init__(self, model: World):
        self.model = model

        self.window = Toplevel()
        self.window.title('Информация об объектах и мире')
        self.window.geometry("640x600+250+200")

        self._inner_init()
        self.frame.pack()

        self.window.mainloop()

    def _inner_init(self):
        self.frame = Frame(self.window,
                           width=640,
                           height=600,
                           bd=2)
        self.frame.grid_bbox(2, 2)

        self._about_world()
        self._about_creatures()

    def _about_world(self):
        self.world_indo = self.model.info()

        TEXT = "Кол-во объектов: {cr_count}\n" \
               "Из них живые: {cr_alive}".format(**self.world_indo)
        Label(self.frame,
              text=TEXT).grid(row=1, column=1)

    def _about_creatures(self):
        lb = Listbox(self.frame,
                     height=15,
                     width=50,
                     selectmode=SINGLE)
        lb.bind('<<ListboxSelect>>', self._onselect)
        lb.grid(row=1, column=2)

        items = self.model.creatures.items()
        items = sorted(items, key=lambda k: k[0][0] * self.model.width + k[0][1])

        for (x, y), creature in items:
            lb.insert(END, [x, y, creature.life])

        self.canvas = NeuroCanvas(self.frame, (2, 2), 400, 300)

    def _onselect(self, evt):
        w = evt.widget
        index = int(w.curselection()[0])
        value = w.get(index)
        x, y, *_ = value[1:].split(",")
        x = int(x)
        y = int(y)
        cr = self.model.creatures[(x, y)]

        neuro = cr.genome

        self.canvas.draw(neuro)
 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()
Esempio n. 11
0
 def toolbox_window(self):
     """Creates the window which will host the toolbox buttons"""
     toolbox_root = Toplevel()
     toolbox_root.title("Toolbox")
     toolbox_root.geometry("455x256")
     toolbox_frame = Frame(toolbox_root)
     toolbox_frame.pack(fill=BOTH)
     
     
Esempio n. 12
0
 def lock(self):
     if self.lock_label.get() == 'LOCKED':
         window = Toplevel()
         window.geometry('318x550')
         self.keypad = Keypad(window, self, self.password)
     else:
         self.save_button.config(state='disabled')
         self.edit.lock()
         self.preferences.lock()
         self.lock_label.set('LOCKED')
         self.lock_button.config(image=self.locked_image)
Esempio n. 13
0
 def on_post_merge_sql(self, *args):
     # Show post-merge-SQL dialog
     _wdw = Toplevel()
     _wdw.geometry('+400+400')
     _wdw.e = TextExtension(_wdw, textvariable=self.post_execute_sql)
     _wdw.e.pack()
     _wdw.e.focus_set()
     _wdw.transient(self.parent)
     _wdw.grab_set()
     self.parent.wait_window(_wdw)
     _wdw.e.unhook()
     del (_wdw)
Esempio n. 14
0
class splash():
#    try:
    def __init__(self):
        moduleDir = dirname(__file__)
        moduleDir = moduleDir.rsplit('\\',2)[0]
        image = moduleDir+'\\resources\\sirbot\\splash.gif'
        self.root = Tk()
        self.root.withdraw()
        self.loadingSplash = Toplevel()
        splashimage = PhotoImage(file=image)
        self.loading = ttk.Label(self.loadingSplash,image=splashimage)
        self.loadingSplash.overrideredirect(True)
        self.loading.pack()

        h = self.loading.winfo_screenheight()
        w = self.loading.winfo_screenwidth()

        self.loadingSplash.wm_attributes('-alpha',0.75)
        self.loadingSplash.update_idletasks()
        self.loadingSplash.geometry('262x112+'+str(int(w/2)-131*1)+
                                    '+'+str(int(h/2)-56*1))
        self.loadingSplash.update_idletasks()
        self.loadingSplash.update()
        
#    except:
##        #log
##        loadingSplash = Tk()
##        #myfont = tkFont.families()[0]
##        loading = Label(loadingSplash,text='SirBot')
##        loadingSplash.overrideredirect(True)
##        loading.pack()
##
##        h = loading.winfo_screenheight()
##        w = loading.winfo_screenwidth()
##
##        loadingSplash.wm_attributes('-alpha',0.75)
##        loadingSplash.update_idletasks()
##        loadingSplash.geometry('262x112+'+str(int(w/2)-131*1)+
##                               '+'+str(int(h/2)-56*1))
##        loadingSplash.update_idletasks()
##        loadingSplash.update()

    def destroy(self):
        try:
            self.loadingSplash.destroy()
        except:
            #log
            pass

    def getroot(self):
        return(self.root)
Esempio n. 15
0
def _object_browser(parent):  # htest #
    import sys
    from tkinter import Toplevel
    top = Toplevel(parent)
    top.title("Test debug object browser")
    width, height, x, y = list(map(int, re.split('[x+]', parent.geometry())))
    top.geometry("+%d+%d"%(x + 100, y + 175))
    top.configure(bd=0, bg="yellow")
    top.focus_set()
    sc = ScrolledCanvas(top, bg="white", highlightthickness=0, takefocus=1)
    sc.frame.pack(expand=1, fill="both")
    item = make_objecttreeitem("sys", sys)
    node = TreeNode(sc.canvas, None, item)
    node.update()
Esempio n. 16
0
def _widget_redirector(parent):  # htest #
    from tkinter import Toplevel, Text

    top = Toplevel(parent)
    top.title("Test WidgetRedirector")
    x, y = map(int, parent.geometry().split('+')[1:])
    top.geometry("+%d+%d" % (x, y + 175))
    text = Text(top)
    text.pack()
    text.focus_set()
    redir = WidgetRedirector(text)
    def my_insert(*args):
        print("insert", args)
        original_insert(*args)
    original_insert = redir.register("insert", my_insert)
Esempio n. 17
0
def _widget_redirector(parent):  # htest #
    from tkinter import Toplevel, Text
    import re

    top = Toplevel(parent)
    top.title("Test WidgetRedirector")
    width, height, x, y = list(map(int, re.split('[x+]', parent.geometry())))
    top.geometry("+%d+%d"%(x, y + 150))
    text = Text(top)
    text.pack()
    text.focus_set()
    redir = WidgetRedirector(text)
    def my_insert(*args):
        print("insert", args)
        original_insert(*args)
    original_insert = redir.register("insert", my_insert)
Esempio n. 18
0
def _color_delegator(parent):  # htest #
    from tkinter import Toplevel, Text
    from idlelib.Percolator import Percolator

    top = Toplevel(parent)
    top.title("Test ColorDelegator")
    top.geometry("200x100+%d+%d" % (parent.winfo_rootx() + 200,
                  parent.winfo_rooty() + 150))
    source = "if somename: x = 'abc' # comment\nprint\n"
    text = Text(top, background="white")
    text.pack(expand=1, fill="both")
    text.insert("insert", source)
    text.focus_set()

    p = Percolator(text)
    d = ColorDelegator()
    p.insertfilter(d)
def _dyn_option_menu(parent):  # htest #
    from tkinter import Toplevel

    top = Toplevel()
    top.title("Tets dynamic option menu")
    top.geometry("200x100+%d+%d" % (parent.winfo_rootx() + 200,
                  parent.winfo_rooty() + 150))
    top.focus_set()

    var = StringVar(top)
    var.set("Old option set") #Set the default value
    dyn = DynOptionMenu(top,var, "old1","old2","old3","old4")
    dyn.pack()

    def update():
        dyn.SetMenu(["new1","new2","new3","new4"], value="new option set")
    button = Button(top, text="Change option set", command=update)
    button.pack()
Esempio n. 20
0
def _dyn_option_menu(parent):  # htest #
    from tkinter import Toplevel # + StringVar, Button

    top = Toplevel(parent)
    top.title("Tets dynamic option menu")
    x, y = map(int, parent.geometry().split('+')[1:])
    top.geometry("200x100+%d+%d" % (x + 250, y + 175))
    top.focus_set()

    var = StringVar(top)
    var.set("Old option set") #Set the default value
    dyn = DynOptionMenu(top,var, "old1","old2","old3","old4")
    dyn.pack()

    def update():
        dyn.SetMenu(["new1","new2","new3","new4"], value="new option set")
    button = Button(top, text="Change option set", command=update)
    button.pack()
Esempio n. 21
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("200x100+%d+%d" % (x + 250, y + 175))
    source = "if somename: x = 'abc' # comment\nprint\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)
Esempio n. 22
0
def _grep_dialog(parent):  # htest #
    from idlelib.pyshell import PyShellFileList
    from tkinter import Toplevel, Text, Button, SEL, END
    top = Toplevel(parent)
    top.title("Test GrepDialog")
    width, height, x, y = list(map(int, re.split('[x+]', parent.geometry())))
    top.geometry("+%d+%d"%(x, y + 150))

    flist = PyShellFileList(top)
    text = Text(top, height=5)
    text.pack()

    def show_grep_dialog():
        text.tag_add(SEL, "1.0", END)
        grep(text, flist=flist)
        text.tag_remove(SEL, "1.0", END)

    button = Button(top, text="Show GrepDialog", command=show_grep_dialog)
    button.pack()
Esempio n. 23
0
    def host_window(self):
        """Creates a host window to input the vraible needed"""
        self.port.set("25665")
        self.max_connections.set("5")
        
        host_root = Toplevel()
        host_root.title("Host Config")
        host_root.geometry("256x144")
        host_frame = Frame(host_root)
        host_frame.pack(fill=BOTH)

        Label(host_frame, text="Port :").grid(row=0, column=0)
        Label(host_frame, text="Maximum users").grid(row=1, column=0)
        
        Entry(host_frame, textvariable=self.port, width=30).grid(row=0, column=1)
        Entry(host_frame, textvariable=self.max_connections, width=30)\
        .grid(row=1, column=1)
        
        Button(host_frame, text="Host", command=self.host_connection)\
        .grid(row=2, column=1, columnspan=2)
Esempio n. 24
0
File: grep.py Progetto: 1st1/cpython
def _grep_dialog(parent):  # htest #
    from tkinter import Toplevel, Text, SEL, END
    from tkinter.ttk import Button
    from idlelib.pyshell import PyShellFileList
    top = Toplevel(parent)
    top.title("Test GrepDialog")
    x, y = map(int, parent.geometry().split('+')[1:])
    top.geometry(f"+{x}+{y + 175}")

    flist = PyShellFileList(top)
    text = Text(top, height=5)
    text.pack()

    def show_grep_dialog():
        text.tag_add(SEL, "1.0", END)
        grep(text, flist=flist)
        text.tag_remove(SEL, "1.0", END)

    button = Button(top, text="Show GrepDialog", command=show_grep_dialog)
    button.pack()
Esempio n. 25
0
def _search_dialog(parent):  # htest #
    "Display search test box."
    from tkinter import Toplevel, Text
    from tkinter.ttk import Button

    box = Toplevel(parent)
    box.title("Test SearchDialog")
    x, y = map(int, parent.geometry().split('+')[1:])
    box.geometry("+%d+%d" % (x, y + 175))
    text = Text(box, inactiveselectbackground='gray')
    text.pack()
    text.insert("insert","This is a sample string.\n"*5)

    def show_find():
        text.tag_add('sel', '1.0', 'end')
        _setup(text).open(text)
        text.tag_remove('sel', '1.0', 'end')

    button = Button(box, text="Search (selection ignored)", command=show_find)
    button.pack()
Esempio n. 26
0
def _multistatus_bar(parent):  # htest #
    from tkinter import Toplevel, Frame, Text, Button
    top = Toplevel(parent)
    x, y = map(int, parent.geometry().split('+')[1:])
    top.geometry("+%d+%d" %(x, y + 175))
    top.title("Test multistatus bar")
    frame = Frame(top)
    text = Text(frame, height=5, width=40)
    text.pack()
    msb = MultiStatusBar(frame)
    msb.set_label("one", "hello")
    msb.set_label("two", "world")
    msb.pack(side='bottom', fill='x')

    def change():
        msb.set_label("one", "foo")
        msb.set_label("two", "bar")

    button = Button(top, text="Update status", command=change)
    button.pack(side='bottom')
    frame.pack()
class MiniWindow:
    def __init__(self,root,list):
        self.list = list
        self.mini = Toplevel(root)
        self.mini.wm_title("Matches")
        print (root.winfo_screenwidth())
        self.mini.geometry("%dx%d+%d+%d" %(500,200,root.winfo_x()+root.winfo_width(),root.winfo_y()))
        self.filelist = Listbox(self.mini)
        for item in self.list:
            self.filelist.insert('end',str(item))
        self.filelist.bind("<<ListboxSelect>>",self.onClick)
        self.filelist.pack(fill="both")
    def onClick(self,event):
        print(self.filelist.curselection())
        index = int(self.filelist.curselection()[0])
        link = self.list[index]
        filedir = os.path.dirname(link)
        if os.name == 'nt':
            os.startfile(filedir)
        elif os.name == 'posix':
            subprocess.Popen(["xdg-open",filedir])
Esempio n. 28
0
def _undo_delegator(parent):  # htest #
    from tkinter import Toplevel, Text, Button
    from idlelib.percolator import Percolator
    undowin = Toplevel(parent)
    undowin.title("Test UndoDelegator")
    x, y = map(int, parent.geometry().split('+')[1:])
    undowin.geometry("+%d+%d" % (x, y + 175))

    text = Text(undowin, height=10)
    text.pack()
    text.focus_set()
    p = Percolator(text)
    d = UndoDelegator()
    p.insertfilter(d)

    undo = Button(undowin, text="Undo", command=lambda:d.undo_event(None))
    undo.pack(side='left')
    redo = Button(undowin, text="Redo", command=lambda:d.redo_event(None))
    redo.pack(side='left')
    dump = Button(undowin, text="Dump", command=lambda:d.dump_event(None))
    dump.pack(side='left')
Esempio n. 29
0
def _calltip_window(parent):  # htest #
    from tkinter import Toplevel, Text, LEFT, BOTH

    top = Toplevel(parent)
    top.title("Test calltips")
    top.geometry("200x100+%d+%d" % (parent.winfo_rootx() + 200,
                  parent.winfo_rooty() + 150))
    text = Text(top)
    text.pack(side=LEFT, fill=BOTH, expand=1)
    text.insert("insert", "string.split")
    top.update()
    calltip = CallTip(text)

    def calltip_show(event):
        calltip.showtip("(s=Hello world)", "insert", "end")
    def calltip_hide(event):
        calltip.hidetip()
    text.event_add("<<calltip-show>>", "(")
    text.event_add("<<calltip-hide>>", ")")
    text.bind("<<calltip-show>>", calltip_show)
    text.bind("<<calltip-hide>>", calltip_hide)
    text.focus_set()
Esempio n. 30
0
def _calltip_window(parent):  # htest #
    from tkinter import Toplevel, Text, LEFT, BOTH

    top = Toplevel(parent)
    top.title("Test call-tips")
    x, y = map(int, parent.geometry().split('+')[1:])
    top.geometry("250x100+%d+%d" % (x + 175, y + 150))
    text = Text(top)
    text.pack(side=LEFT, fill=BOTH, expand=1)
    text.insert("insert", "string.split")
    top.update()

    calltip = CalltipWindow(text)
    def calltip_show(event):
        calltip.showtip("(s='Hello world')", "insert", "end")
    def calltip_hide(event):
        calltip.hidetip()
    text.event_add("<<calltip-show>>", "(")
    text.event_add("<<calltip-hide>>", ")")
    text.bind("<<calltip-show>>", calltip_show)
    text.bind("<<calltip-hide>>", calltip_hide)

    text.focus_set()
        def editClient(new=True, old_name=None):
            def onProcessClientData():
                name = new_name.get()
                exchange = new_exchange.get()
                api_key = new_api_key.get()
                api_secret = new_api_secret.get()
                query_str = new_query_list.get()
                ## Check name
                try:
                    for s in name:
                        if s in "~!@#$%^&*()+-*/<>,.[]\/":
                            msg.set('Error: ' + "名稱勿含特殊符號")
                            return
                    for s in query_str:
                        if s in "~!@#$%^&*()+-*/<>.[]\/":
                            msg.set('Error: ' + 'Query List勿含除了","以外的特殊符號')
                            return
                    if len(name) > 15:
                        msg.set('Error: ' + '名稱勿超過15字')
                    elif name in self.clients.client_dict and new:
                        msg.set('Error: ' + '名字勿重複')
                    elif not len(api_key) or not len(api_secret) or not len(
                            name) or not len(exchange):
                        msg.set('Error: ' + "請輸入名稱、金錀或交易所")
                    elif exchange not in ['binance', 'ftx']:
                        msg.set('Error: ' + "目前交易所僅支援 binance 和 ftx")
                    else:
                        ## Add client to config
                        specialChars = " \n!\"#$%^&*()"
                        for specialChar in specialChars:
                            query_str = query_str.replace(specialChar, '')
                        client_data = {
                            'api_key': api_key,
                            'api_secret': api_secret,
                            'query_list': query_str.upper().split(','),
                            'exchange': exchange
                        }
                        if new:
                            client_data['index'] = self.clients.count
                            self.clients.count += 1
                            self.clients.process_client_data(name, client_data)
                            refreshAccountList()
                            messagebox.showinfo('Welcome', '成功增加帳戶 %s!' % name)
                        else:
                            self.clients.client_dict[name].info.setinfo(
                                client_data)
                            messagebox.showinfo('Welcome', '成功修改帳戶 %s!' % name)
                        self.clients.save_client_config(CONFIG_FILENAME)
                        window_add_client.destroy()

                except Exception as e:
                    msg.set('Error')
                    print(e)

            window_add_client = Toplevel(self.app)
            window_add_client.title("編輯您的帳戶資訊")
            window_add_client.geometry('400x300')
            try:
                window_add_client.iconphoto(
                    False, PhotoImage(file='icon/doge_icon.png'))
            except:
                pass
            setUIToCenter(window_add_client, 400, 300)
            new_name = StringVar()
            new_name.set('binance_Name')
            Label(window_add_client,
                  text='User name: ').place(x=10,
                                            y=10)  # 將`User name:`放置在座標(10,10)。
            entry_new_name = Entry(window_add_client,
                                   textvariable=new_name,
                                   width=35)  # 建立一個註冊名的`entry`,變數為`new_name`
            entry_new_name.place(x=130, y=10)  # `entry`放置在座標(150,10).

            new_exchange = StringVar()
            new_exchange.set('binance')
            Label(window_add_client, text='Exchange: ').place(x=10, y=50)
            entry_new_exchange = Entry(window_add_client,
                                       textvariable=new_exchange,
                                       width=35)
            entry_new_exchange.place(x=130, y=50)

            new_api_key = StringVar()
            Label(window_add_client, text='API key: ').place(x=10, y=90)
            entry_usr_api_key = Entry(window_add_client,
                                      textvariable=new_api_key,
                                      width=35)
            entry_usr_api_key.place(x=130, y=90)

            new_api_secret = StringVar()
            Label(window_add_client, text='Secret key: ').place(x=10, y=130)
            Entry(window_add_client, textvariable=new_api_secret, width=35) \
            .place(x=130, y=130)

            new_query_list = StringVar()
            new_query_list.set("ETH, BTC")
            Label(window_add_client, text='Query list: ').place(x=10, y=170)
            Entry(window_add_client, textvariable=new_query_list, width=35) \
            .place(x=130, y=170)

            msg = StringVar()
            Label(window_add_client, textvariable=msg, fg='red').place(x=20,
                                                                       y=210)
            btn_comfirm_sign_up = Button(window_add_client,
                                         text='確認',
                                         command=onProcessClientData)
            btn_comfirm_sign_up.place(x=180, y=250)

            if not new:
                entry_new_name['state'] = 'disabled'
                info = self.clients.client_dict[old_name].info
                new_name.set(old_name)
                new_exchange.set(info.exchange)
                new_api_key.set(info.api_key)
                new_api_secret.set(info.api_secret)
                new_query_list.set(','.join(info.query_list))
Esempio n. 32
0
class Transfer_window:
    #Build transfer window
    def start_transfer_window(self, home_screen, account_id, username):
        self.account_id = account_id
        self.transfer_window = Toplevel(home_screen)
        self.transfer_window.geometry('480x160')
        self.transfer_window.title('Transfer [{}]'.format(username))

        self.temp_username = StringVar()
        self.temp_amount = StringVar()

        #Labels
        detail_label = Label(self.transfer_window,
                             text='Please enter a username and the amount',
                             font=('Calibri', 20))
        detail_label.grid(row=0, column=0, sticky='N')

        username_lable = Label(self.transfer_window,
                               text='username',
                               font=('Calibri', 16))
        username_lable.grid(row=1, column=0, sticky='W')

        amount_lable = Label(self.transfer_window,
                             text='Amount',
                             font=('Calibri', 16))
        amount_lable.grid(row=2, column=0, sticky='W')

        #hidden label
        self.hidden_label = Label(self.transfer_window, font=('Calibri', 12))
        self.hidden_label.grid(row=5, sticky='N')

        #Error label
        self.error_label = Label(self.transfer_window, font=('Calibri', 12))
        self.error_label.grid(row=4, sticky='N')

        #Entries
        self.username_entry = Entry(self.transfer_window,
                                    textvariable=self.temp_username)
        self.username_entry.grid(row=1, column=0)

        self.amount_entry = Entry(self.transfer_window,
                                  textvariable=self.temp_amount)
        self.amount_entry.grid(row=2, column=0)

        #Buttons
        ok_button = Button(self.transfer_window,
                           text='Ok',
                           font=('Calibri', 16),
                           width=10,
                           command=lambda: self.start_transfer())
        ok_button.grid(row=3, column=0, sticky='E')

        go_back_button = Button(self.transfer_window,
                                text='Go back',
                                font=('Calibri', 16),
                                width=10,
                                command=lambda: self.transfer_window.destroy())
        go_back_button.grid(row=3, column=0, sticky='W', padx=5)
        #Note to self, add function to close all windows on logout

    def start_transfer(self):
        username = self.temp_username.get()
        amount = self.temp_amount.get()
        if (self.check_user_input(username, amount)):
            self.finish_transfer(username, amount)

    def finish_transfer(self, username, amount):
        target_id = Bank_system().get_target_account_id(username)
        Bank_system().transfer_assets(self.account_id, target_id, amount)
        self.username_entry.delete(0, 'end')
        self.amount_entry.delete(0, 'end')
        self.transfer_window.geometry('480x160')
        self.error_label.config(fg='green',
                                text='The transfer was successfully made')
        #Note to self, add function to check if the deposit was succesful

    def check_user_input(self, username, amount):
        lower_bound = '180'
        horozontal_bound = '480'
        if ((" " in username) or (" " in amount)):
            print('Spaces are not allowed')
            self.transfer_window.geometry('{}x{}'.format(
                horozontal_bound, lower_bound))
            self.error_label.config(fg='red', text='Spaces are not allowed')
            return False
        elif (username == '' and amount == ''):
            self.transfer_window.geometry('{}x{}'.format(
                horozontal_bound, lower_bound))
            self.error_label.config(
                fg='red', text='Please enter a username and the amount')
            return False
        elif (username == ''):
            self.transfer_window.geometry('{}x{}'.format(
                horozontal_bound, lower_bound))
            self.error_label.config(fg='red', text='Please enter a username')
            return False
        elif (username == '' and amount == ''):
            self.transfer_window.geometry('{}x{}'.format(
                horozontal_bound, lower_bound))
            self.error_label.config(fg='red', text='Please enter the amount')
            return False
        elif (not (amount.isdecimal())):
            self.transfer_window.geometry('{}x{}'.format(
                horozontal_bound, lower_bound))
            self.error_label.config(
                fg='red', text='The ammount has to be given in numbers')
            return False
        elif (Bank_system().check_target_user(username)):
            return True
        else:
            self.transfer_window.geometry('{}x{}'.format(
                horozontal_bound, lower_bound))
            self.error_label.config(fg='red', text='The user does not exist')
            return False
Esempio n. 33
0
class SubMenu:

    def __init__(self, loader, name, w, h, checker, addElements, maxNum):
        self.__loader = loader
        self.__loader.subMenus.append(self)
        self.__loader.subMenuDict[name] = self
        self.__name = name

        if len(self.__loader.subMenus)>maxNum:
            from threading import Thread
            t = Thread(target=self.killOther)
            t.daemon = True
            t.start()

        self.stopThread = False
        self.__loader.stopThreads.append(self)

        self.__config = self.__loader.config
        self.__dictionaries = self.__loader.dictionaries
        self.__screenSize = self.__loader.screenSize

        self.__topLevel = Toplevel()
        self.__topLevel.title(self.__dictionaries.getWordFromCurrentLanguage(name))
        self.__topLevel.geometry("%dx%d+%d+%d" % (w, h, (self.__screenSize[0]/2-w/2), (self.__screenSize[1]/2-h/2-50)))
        self.__topLevel.resizable(False, False)

        self.__topLevel.config(bg=self.__loader.colorPalettes.getColor("window"))
        #self.__topLevel.protocol('WM_DELETE_WINDOW', self.__closeWindow)

        try:
            self.__topLevel.iconbitmap("others/img/"+name+".ico")
        except:
            self.__topLevel.iconbitmap("others/img/icon.ico")

        self.__loader.topLevels.append(self.__topLevel)
        self.__topLevel.deiconify()
        self.__topLevel.focus()

        from threading import Thread
        if checker!=None:
            self.__checker = checker
            check = Thread(target=self.__checker)
            check.daemon = True
            check.start()

        if addElements!=None:
            self.__addElements = addElements
            add = Thread(target=self.__addElements, args=[self])
            add.daemon=True
            add.start()

        self.changeWindowState(True, maxNum-1)
        self.__topLevel.wait_window()
        try:
            self.changeWindowState(False, maxNum-1)
        except:
            pass

        try:
            self.__loader.subMenus.pop(-1)
            self.__loader.subMenus.remove(self)
        except Exception as e:
            self.__loader.logger.errorLog(e)

        from threading import Thread

        t = Thread(target=self.__killIfKilled)
        t.daemon = True
        t.start()

    def changeWindowState(self, state, last):
        self.__loader.mainWindow.editor.attributes('-disabled', state)
        if last > 0:
            for num in range(last):
                self.__loader.topLevels[num].attributes('-disabled', state)

        if state == False:
            if last == 0:
                self.__loader.mainWindow.editor.deiconify()
                self.__loader.mainWindow.editor.focus()
            else:
                self.__loader.topLevels[last-1].deiconify()
                self.__loader.topLevels[last-1].focus()


    def __killIfKilled(self):
        from time import sleep
        while self.__topLevel.winfo_exists():
            sleep(0.0005)
        del self.__loader.subMenuDict[self.__name]

    def killOther(self):
        num = 10

        from time import sleep

        while num > 0:
            sleep(1)

            try:
                self.__loader.subMenus[-2].dead = True
                self.__loader.subMenus[-2].getTopLevel().destroy()
                self.__loader.subMenus.pop(-2)
                num = 0
            except:
                num -= 1


    def getTopLevel(self):
        return(self.__topLevel)

    def getTopLevelDimensions(self):
        return(self.__topLevel.winfo_width(), self.__topLevel.winfo_height())

    #def __closeWindow(self):

    #    self.__topLevel.destroy()
Esempio n. 34
0
        self.p2.lift();
        self.cancelButton.config(text = "cancel", command=exit);
        self.closeP6.place_forget();
        self.progressLabel["text"] = "Working, this might take a couple of minutes...";
        self.progress["mode"] = 'indeterminate';
        
if __name__ == "__main__":
    root = Tk();
    root.withdraw();
    
    screen_width = root.winfo_screenwidth();
    screen_height = root.winfo_screenheight();

    # calculate position x and y coordinates
    x = (screen_width/2) - (framewidth/2);
    y = (screen_height/2) - (frameheight/2);
    
    window = Toplevel(root);
    window.geometry("%dx%d+%d+%d" %(framewidth, frameheight, x, y));
    window.resizable(False, False);
    
    window.iconbitmap(resource_path("elslogo.ico"));    
    
    main = MainView(window);
    main.pack(side="top", fill="both", expand=True);
    
    window.attributes("-topmost", 1);
    
    window.mainloop();
    
    root.destroy();
def updatestudent():
    def updateadd():
        id = idval.get()
        name = nameval.get()
        mobile = mobileval.get()
        email = emailval.get()
        address = addressval.get()
        gender = genderval.get()
        dob = dobval.get()
        date = dateval.get()
        time = timeval.get()

        strr = 'update studentdata set name=%s,mobile=%s,email=%s,address=%s,gender=%s,dob=%s,date=%s,time=%s where id=%s'
        mycursor.execute(
            strr, (name, mobile, email, address, gender, dob, date, time, id))
        con.commit()
        messagebox.showinfo('Notification',
                            'id {} Modified sucessfuly...'.format(id),
                            parent=updateroot)
        strr = 'select *from studentdata'
        mycursor.execute(strr)
        datas = mycursor.fetchall()
        studenttable.delete(*studenttable.get_children())
        for i in datas:
            vv = [i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]]
            studenttable.insert('', END, values=vv)

    updateroot = Toplevel(master=DataEntryFrame)
    updateroot.grab_set()
    updateroot.iconbitmap('max.ico')
    updateroot.geometry('470x580+60+50')
    updateroot.title('update Student')
    updateroot.resizable(False, False)
    updateroot.config(bg='lightblue')
    # =====================================================================================
    idlabel = Label(updateroot,
                    text="Update Id:",
                    bg="lightgreen",
                    anchor='w',
                    font=('arial', 15, 'bold'),
                    relief=GROOVE,
                    borderwidth=3,
                    width=12)
    idlabel.place(x=10, y=10)
    namelabel = Label(updateroot,
                      text="Update Name:",
                      bg="lightgreen",
                      anchor='w',
                      font=('arial', 15, 'bold'),
                      relief=GROOVE,
                      borderwidth=3,
                      width=12)
    namelabel.place(x=10, y=60)
    mobilelabel = Label(updateroot,
                        text="Update Mobile:",
                        bg="lightgreen",
                        anchor='w',
                        font=('arial', 15, 'bold'),
                        relief=GROOVE,
                        borderwidth=3,
                        width=12)
    mobilelabel.place(x=10, y=110)
    emaillabel = Label(updateroot,
                       text="Update Email:",
                       bg="lightgreen",
                       anchor='w',
                       font=('arial', 15, 'bold'),
                       relief=GROOVE,
                       borderwidth=3,
                       width=12)
    emaillabel.place(x=10, y=160)
    addresslabel = Label(updateroot,
                         text="Update Address:",
                         bg="lightgreen",
                         anchor='w',
                         font=('arial', 15, 'bold'),
                         relief=GROOVE,
                         borderwidth=3,
                         width=12)
    addresslabel.place(x=10, y=210)
    genderlabel = Label(updateroot,
                        text="Update Gender:",
                        bg="lightgreen",
                        anchor='w',
                        font=('arial', 15, 'bold'),
                        relief=GROOVE,
                        borderwidth=3,
                        width=12)
    genderlabel.place(x=10, y=260)
    doblabel = Label(updateroot,
                     text="Update D.O.B.:",
                     bg="lightgreen",
                     anchor='w',
                     font=('arial', 15, 'bold'),
                     relief=GROOVE,
                     borderwidth=3,
                     width=12)
    doblabel.place(x=10, y=310)
    datelabel = Label(updateroot,
                      text="Update Date:",
                      bg="lightgreen",
                      anchor='w',
                      font=('arial', 15, 'bold'),
                      relief=GROOVE,
                      borderwidth=3,
                      width=12)
    datelabel.place(x=10, y=370)
    timelabel = Label(updateroot,
                      text="Update Time:",
                      bg="lightgreen",
                      anchor='w',
                      font=('arial', 15, 'bold'),
                      relief=GROOVE,
                      borderwidth=3,
                      width=12)
    timelabel.place(x=10, y=430)
    # ==============================================================================================
    idval = StringVar()
    nameval = StringVar()
    mobileval = StringVar()
    emailval = StringVar()
    addressval = StringVar()
    genderval = StringVar()
    dobval = StringVar()
    dateval = StringVar()
    timeval = StringVar()
    identry = Entry(updateroot,
                    font=('roman', 15, 'bold'),
                    bd=2,
                    bg="lightgreen",
                    textvariable=idval)
    identry.place(x=200, y=10)
    nameentry = Entry(updateroot,
                      font=('roman', 15, 'bold'),
                      bd=2,
                      bg="lightgreen",
                      textvariable=nameval)
    nameentry.place(x=200, y=60)
    mobileentry = Entry(updateroot,
                        font=('roman', 15, 'bold'),
                        bd=2,
                        bg="lightgreen",
                        textvariable=mobileval)
    mobileentry.place(x=200, y=110)
    emailentry = Entry(updateroot,
                       font=('roman', 15, 'bold'),
                       bd=2,
                       bg="lightgreen",
                       textvariable=emailval)
    emailentry.place(x=200, y=160)
    addressentry = Entry(updateroot,
                         font=('roman', 15, 'bold'),
                         bd=2,
                         bg="lightgreen",
                         textvariable=addressval)
    addressentry.place(x=200, y=210)
    genderentry = Entry(updateroot,
                        font=('roman', 15, 'bold'),
                        bd=2,
                        bg="lightgreen",
                        textvariable=genderval)
    genderentry.place(x=200, y=260)
    dobentry = Entry(updateroot,
                     font=('roman', 15, 'bold'),
                     bd=2,
                     bg="lightgreen",
                     textvariable=dobval)
    dobentry.place(x=200, y=310)
    dateentry = Entry(updateroot,
                      font=('roman', 15, 'bold'),
                      bd=2,
                      bg="lightgreen",
                      textvariable=dateval)
    dateentry.place(x=200, y=370)
    timeentry = Entry(updateroot,
                      font=('roman', 15, 'bold'),
                      bd=2,
                      bg="lightgreen",
                      textvariable=timeval)
    timeentry.place(x=200, y=430)
    updaterootbutton = Button(updateroot,
                              text='Submit',
                              command=updateadd,
                              font=('arial', 20, 'bold'),
                              bg='red',
                              bd=3,
                              activebackground='blue',
                              activeforeground="white")
    updaterootbutton.place(x=150, y=490)
    cc = studenttable.focus()
    content = studenttable.item(cc)
    pp = content['values']
    if len(pp) != 0:
        idval.set(pp[0])
        nameval.set(pp[1])
        mobileval.set(pp[2])
        emailval.set(pp[3])
        addressval.set(pp[4])
        genderval.set(pp[5])
        dobval.set(pp[6])
        dateval.set(pp[7])
        timeval.set(pp[8])
    updateroot.mainloop()
Esempio n. 36
0
class Application(Frame):

    className = []
    prob = []

    #image_path_temporary = "D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images"

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.window_init()
        self.grid()

    def window_init(self):
        self.master.title('Eagle')
        screenwidth = self.winfo_screenwidth()
        screenheight = self.winfo_screenheight(
        )  # 设置界面宽度为530,高度为365像素,并且基于屏幕居中
        width = 500
        height = 400
        size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2,
                                (screenheight - height) / 2)
        self.master.geometry(size)
        self.grid()
        self.create_widgets_initial()

    def create_widgets_initial(self):
        #self.frame = Frame(self)
        #self.frame.grid()
        self.tabControl = ttk.Notebook(self)
        self.tab1 = Frame(self.tabControl)
        self.tabControl.add(self.tab1, text='企业用户')
        self.tab2 = Frame(self.tabControl)
        self.tabControl.add(self.tab2, text='个人用户')
        self.tabControl.pack(expand=1, fill="both")
        self.create_widgets_user()
        self.create_widgets()

    def create_widgets(self):
        #self.frame.destroy()
        #self.frame1 = Frame(self)
        #self.frame1.grid()
        #self.frame2 = Frame(self)
        #self.frame2.grid()
        self.chooseLabel = Label(self.tab1, text='请选择进行所需图片的语义信息')
        self.chooseLabel.grid(column=1, row=1, sticky='W')
        #comvalue.append(print("comvalue" + str(i)))
        #comboxlist.append(print("comboxlist" + str(i)))
        #self.comvalue = StringVar()  # 窗体自带的文本,新建一个值
        self.comboxlist = ttk.Combobox(self.tab1,
                                       textvariable='',
                                       state="readonly")  #初始化
        self.comboxlist["values"] = ("房屋占地率(%)", "绿化率(%)", "车辆数目", "篮球场数目")
        #self.comboxlist["values"] = ("first", "second", "third", "fourth")
        self.comboxlist.current(0)
        self.comboxlist.bind(
            "<<ComboboxSelected>>",
            print(self.comboxlist.get()))  #绑定事件,(下拉列表框被选中时,绑定go()函数)
        self.comboxlist.grid(row=2, column=0)
        self.spinBox1 = Spinbox(self.tab1, from_=0, to=100, increment=1)
        self.spinBox1.grid(row=2, column=1)
        self.spinBox2 = Spinbox(self.tab1, from_=0, to=100, increment=1)
        self.spinBox2.grid(row=2, column=2)
        self.addButton = Button(self.tab1,
                                text='确定并增加条件',
                                command=self.add_condition)
        self.addButton.grid(row=3, column=1)
        self.cancelButton = Button(self.tab1,
                                   text='条件输入有误,重新输入',
                                   command=self.delete_condition)
        self.cancelButton.grid(row=4, column=1)
        self.confirmButton = Button(self.tab1,
                                    text='完成所有条件',
                                    command=self.check)
        self.confirmButton.grid(row=5, column=1)
        #self.backButton = Button(self.tab1, text='返回初始界面', command=self.create_widgets_initial)
        #self.backButton.grid()
        self.quitButton = Button(self.tab1, text='Quit', command=self._quit)
        self.quitButton.grid(row=6, column=1)

    def add_condition(self):
        self.confirm_condition()
        self.addButton.destroy()
        self.cancelButton.destroy()
        self.confirmButton.destroy()
        self.quitButton.destroy()
        #self.comvalue = StringVar()  # 窗体自带的文本,新建一个值
        self.comboxlist = ttk.Combobox(self.tab1, textvariable='')  # 初始化
        self.comboxlist["values"] = ("房屋占地率(%)", "绿化率(%)", "车辆数目", "篮球场数目")
        #self.comboxlist["values"] = ("first", "second", "third", "fourth")
        self.comboxlist.current(0)
        self.comboxlist.bind(
            "<<ComboboxSelected>>",
            print(self.comboxlist.get()))  # 绑定事件,(下拉列表框被选中时,绑定go()函数)
        self.comboxlist.grid(row=len(self.className) + 2, column=0)
        self.spinBox1 = Spinbox(self.tab1, from_=0, to=100, increment=1)
        self.spinBox1.grid(row=len(self.className) + 2, column=1)
        self.spinBox2 = Spinbox(self.tab1, from_=0, to=100, increment=1)
        self.spinBox2.grid(row=len(self.className) + 2, column=2)
        self.addButton = Button(self.tab1,
                                text='确定并增加条件',
                                command=self.add_condition)
        self.addButton.grid(row=len(self.className) + 3, column=1)
        self.cancelButton = Button(self.tab1,
                                   text='条件输入有误,重新输入',
                                   command=self.delete_condition)
        self.cancelButton.grid(row=len(self.className) + 4, column=1)
        self.confirmButton = Button(self.tab1,
                                    text='完成所有条件',
                                    command=self.check)
        self.confirmButton.grid(row=len(self.className) + 5, column=1)
        # self.backButton = Button(self.tab1, text='返回初始界面', command=self.create_widgets_initial)
        # self.backButton.grid()
        self.quitButton = Button(self.tab1, text='Quit', command=self._quit)
        self.quitButton.grid(row=len(self.className) + 6, column=1)
        #self.addButton.grid(row=len(self.className)+1, column=2)

    def confirm_condition(self):
        #print("confirm")
        if (self.comboxlist.get() in self.className):
            self._msgbox("条件已存在,请重新选择")
            return 0
        else:
            self.className.append(self.comboxlist.get())
            self.prob.append(self.spinBox1.get())
            self.prob.append(self.spinBox2.get())
            return 1

    def delete_condition(self):
        if (messagebox.askyesno(message='确定清除所有条件吗')):
            for i in range(0, len(self.className)):
                self.className.clear()
                self.prob.clear()
            # self.comboxlist.destroy()
            # self.spinBox.destroy()
            # self.addButton.destroy()
            #self.lab1.destroy()
            self.tab1.destroy()
            self.tab2.destroy()
            #self.tab1 = Frame(self.tabControl)
            #self.tabControl.add(self.tab1, text='企业用户')
            self.create_widgets_initial()

    def check(self):
        if (self.confirm_condition() == 0):
            self.comboxlist = ttk.Combobox(self.tab1, textvariable='')  # 初始化
            self.comboxlist["values"] = ("房屋占地率(%)", "绿化率(%)", "车辆数目", "篮球场数目")
            #self.comboxlist["values"] = ("first", "second", "third", "fourth")
            self.comboxlist.current(0)
            self.comboxlist.bind(
                "<<ComboboxSelected>>",
                print(self.comboxlist.get()))  # 绑定事件,(下拉列表框被选中时,绑定go()函数)
            self.comboxlist.grid(row=len(self.className) + 1, column=0)
            self.spinBox1 = Spinbox(self.tab1, from_=0, to=100, increment=1)
            self.spinBox1.grid(row=len(self.className) + 1, column=1)
            self.spinBox2 = Spinbox(self.tab1, from_=0, to=100, increment=1)
            self.spinBox2.grid(row=len(self.className) + 1, column=2)
            self.addButton = Button(self.tab1,
                                    text='确定并增加条件',
                                    command=self.add_condition)
            self.addButton.grid(row=len(self.className) + 2,
                                column=1,
                                columnspan=2)
        else:
            self.addButton.destroy()
            self.confirmButton.destroy()
            self.cancelButton.destroy()
            self.quitButton.destroy()
            self.cancelButton = Button(self.tab1,
                                       text='条件输入有误,重新输入',
                                       command=self.delete_condition)
            self.cancelButton.grid(row=len(self.className) + 2, column=1)
            self.runButton = Button(self.tab1, text='开始运行', command=self.run)
            self.runButton.grid(row=len(self.className) + 3, column=1)
            self.quitButton = Button(self.tab1,
                                     text='Quit',
                                     command=self._quit)
            self.quitButton.grid(row=len(self.className) + 4, column=1)

    def run(self):
        self.addButton.destroy()
        self.cancelButton["text"] = "清除所有条件"
        self.info = []

        #合成命令

        #激活环境并运行
        self.info.append(
            "cd venv\Scripts\&activate.bat&cd ..&cd ..&python connection_local.py"
        )
        #个人用户电脑信息
        self.info.append(" --hostname " + myaddr + " --port " + myport +
                         " --username " + myname + " --passcode " + mypasscode)
        #需要提取的信息条件
        for i in range(0, len(self.className)):
            self.info.append(" --" + self.className[i] + " " +
                             self.prob[2 * i] + "," + self.prob[2 * i + 1])
        self.info_str = ''.join(self.info)
        #print(self.info)
        print(self.info_str)
        self.info_str = self.info_str.replace("房屋占地率(%)", "first")
        self.info_str = self.info_str.replace("绿化率(%)", "second")
        self.info_str = self.info_str.replace("车辆数目", "third")
        self.info_str = self.info_str.replace("篮球场数目", "fourth")
        print(self.info_str)

        path = 'D:\study\Eagle\DB\DB'
        for i in os.listdir(path):
            path_file1 = os.path.join(path, i)
            if os.path.isfile(path_file1):
                os.remove(path_file1)
        #清空路径下的文件

        output = os.popen(self.info_str)
        op = output.read()
        print(op)
        img_path = []
        for line in op.splitlines():
            img_path.append(line)
            if img_path[len(img_path) - 1] == "finish":
                print(img_path)
                img_path1 = os.path.abspath(os.path.dirname(img_path[0]))
                img_path1 = img_path1.replace('\mnt\d', '')
                self.result(img_path1)
                self.pic_win.resultLabel[
                    "text"] = "满足条件图片已保存在本地文件夹:\n" + img_path1
                self.pic_win.canvas = Canvas(self.pic_win)
                self.pic_win.canvas.pack()
                self.pic_win.checkButton = Button(
                    self.pic_win,
                    text="查看图片",
                    command=lambda: self.pic_preview(img_path1))
                self.pic_win.checkButton.pack()
        img_path = [
            'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-021.png',
            'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-035.png',
            'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-038.png',
            'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-040.png',
            'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-021.png',
            'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-035.png',
            'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-038.png',
            'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-040.png',
            'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-021.png',
            'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-035.png',
            'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-038.png',
            'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-040.png',
            'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-021.png',
            'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-035.png',
            'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-038.png',
            'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-040.png',
            'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-021.png',
            'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-035.png',
            'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-038.png',
            'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-040.png'
        ]
        img_path1 = 'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images'
        self.result(img_path1)

    def result(self, img_path1):
        self.pic_win = Toplevel()
        screenwidth = self.pic_win.winfo_screenwidth()
        screenheight = self.pic_win.winfo_screenheight(
        )  # 设置界面宽度为530,高度为365像素,并且基于屏幕居中
        width = 1500
        height = 800
        size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2,
                                (screenheight - height) / 2)
        self.pic_win.geometry(size)
        self.pic_win.grid()
        self.pic_win.title("结果")
        self.pic_win.resultLabel = Label(self.pic_win,
                                         text="满足条件图片已保存在本地文件夹:\n" + img_path1)
        self.pic_win.resultLabel.pack()
        self.pic_win.checkButton = Button(
            self.pic_win,
            text="查看图片",
            command=lambda: self.pic_preview(img_path1))
        self.pic_win.checkButton.pack()
        self.listBox = Listbox(self.pic_win)
        self.scrollbar = Scrollbar(self.listBox, orient=HORIZONTAL)
        self.scrollbar.pack(side=BOTTOM, fill="x")
        self.listBox.config(xscrollcommand=self.scrollbar.set)
        self.scrollbar.set(0.6, 0)
        self.scrollbar.config(command=self.listBox.xview())
        gifsdict = {}
        self.listBox.pack(expand=YES)
        self.pic_win.infoLabel = Label(self.pic_win,
                                       text='info:',
                                       justify=LEFT)
        self.pic_win.infoLabel.pack()

    def pic_preview(self, img_path1):  #父窗口可以在主窗口之前关的问题为解决
        self.pic_win.wm_attributes('-topmost', 1)
        self.pic_win.wm_attributes('-topmost', 0)
        #print("sssss"+img_path1)
        self.filePath = filedialog.askopenfilename(parent=self,
                                                   initialdir=img_path1,
                                                   title='Choose an image.')
        odFilePath = str(self.filePath).replace('RGB', 'OD')
        ssFilePath = str(self.filePath).replace('RGB', 'SS')
        infoFilePath = str(self.filePath).replace('RGB.png', 'INFO.txt')
        img = Image.open(self.filePath)
        filename = ImageTk.PhotoImage(img)
        odImg = Image.open(odFilePath)
        odFilename = ImageTk.PhotoImage(odImg)
        ssImg = Image.open(ssFilePath)
        ssFilename = ImageTk.PhotoImage(ssImg)
        self.pic_win.wm_attributes('-topmost', 1)
        #Label_image = Image.open(self.filePath)
        #Label_image.show()
        #self.pic_win.canvas.image = filename  # <--- keep reference of your image
        #self.pic_win.canvas.create_image(0, 0, anchor='nw', image=filename)
        self.imageLabel = Label(self.listBox, imag=filename)
        self.imageLabel.pack(side="left", fill="both", expand="yes")
        self.odLabel = Label(self.listBox, imag=odFilename)
        self.odLabel.pack(side="left", fill="both", expand="yes")
        self.ssLabel = Label(self.listBox, imag=ssFilename)
        self.ssLabel.pack(side="left", fill="both", expand="yes")
        infoFile = open(infoFilePath, encoding='UTF-8')
        infoList = []
        for line in infoFile.readlines():
            infoList.append(line)
        info = ''.join(infoList)
        print(info)
        self.pic_win.infoLabel = Label(self.pic_win, text=info, justify=LEFT)
        self.pic_win.infoLabel.pack()
        self.listBox.insert(ACTIVE, self.imageLabel)
        self.listBox.insert(ACTIVE, self.odLabel)
        self.listBox.insert(self.ssLabel)
        #self.listBox.insert(END, self.infoLabel)
        self.listBox.pack()
        self.pic_win.checkButton["text"] = "查看下一张图片"

    def _msgbox(self, msg):
        messagebox.showinfo('提示', msg)

    def create_widgets_user(self):
        #self.frame.destroy()
        #self.frame3 = Frame(self)
        #self.frame3.grid()
        self.chooseLabel = Label(self.tab2, text='请选择进行目标检测和语义分割的图片')
        self.chooseLabel.pack()
        self.canvas = Canvas(self.tab2, height=200, width=200)
        self.canvas.pack()
        self.pathLabel = Label(self.tab2, text='Image Path')
        self.pathLabel.pack()
        self.chooseButton = Button(self.tab2,
                                   text='Choose',
                                   command=self.pic_choose_user)
        self.chooseButton.pack()
        self.detectButton = Button(self.tab2,
                                   text='Detect',
                                   command=self.detect_user)
        self.detectButton.pack()
        self.quitButton = Button(self.tab2, text='Quit', command=self._quit)
        self.quitButton.pack()

    def pic_choose_user(self):
        self.filePath = filedialog.askopenfilename(parent=self,
                                                   initialdir="C:/",
                                                   title='Choose an image.')
        #self.filePath = filedialog.askopenfilename(parent=self, initialdir=self.image_path_temporary, title='Choose an image.')
        img = Image.open(self.filePath)
        img_width = img.size[0]
        img_height = img.size[1]
        rate = img_width / img_height
        if rate > 1:
            rate1 = img_width / 200
            img_width = 200
            img_height = img_height / rate1
        else:
            rate1 = float(img_height) / 200.0
            img_height = 200
            img_width = img_width / rate1
        img_new = img.resize((int(img_width), int(img_height)))
        filename = ImageTk.PhotoImage(img_new)
        self.canvas.image = filename  # <--- keep reference of your image
        self.canvas.create_image(0, 0, anchor='nw', image=filename)

    def detect_user(self):
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname=ServerHostname,
                    port=ServerPort,
                    username=ServerUsername,
                    password=ServerPassword)

        folder = '/server_space/jiangyl/dlink_potsdam_normto1/remote'  # folder has script
        file = 'predict_remote.py'

        sftp = ssh.open_sftp()
        sftp.put(self.filePath, folder + 'test.png')

        stdin, stdout, stderr = ssh.exec_command('cd %s; python %s ' %
                                                 (folder, file))
        for s in stdout:
            if s == "finish":
                self.pic_preview_user()

        ssh.close()

        self.pic_preview_user(
            "D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images/001.png"
        )

    def pic_preview_user(self, filePath):
        self.pic_win_user = Toplevel()
        self.pic_win_user.wm_attributes('-topmost', 1)
        self.pic_win_user.wm_attributes('-topmost', 0)
        self.listBox_user = Listbox(self.pic_win_user)
        self.scrollbar_user = Scrollbar(self.listBox_user, orient=HORIZONTAL)
        self.scrollbar_user.pack(side=BOTTOM, fill="x")
        self.listBox_user.config(xscrollcommand=self.scrollbar_user.set)
        self.scrollbar_user.set(0.6, 0)
        self.scrollbar_user.config(command=self.listBox_user.xview())
        gifsdict = {}
        self.listBox_user.pack(expand=YES)
        odFilePath = filePath.replace('RGB', 'OD')
        ssFilePath = filePath.replace('RGB', 'SS')
        infoFilePath = filePath.replace('RGB.png', 'INFO.txt')
        print(filePath)
        img = Image.open(filePath)
        filename = ImageTk.PhotoImage(img)
        odImg = Image.open(odFilePath)
        odFilename = ImageTk.PhotoImage(odImg)
        ssImg = Image.open(ssFilePath)
        ssFilename = ImageTk.PhotoImage(ssImg)
        self.pic_win_user.wm_attributes('-topmost', 1)
        self.imageLabel_user = Label(self.listBox_user, imag=filename)
        self.imageLabel_user.pack(side="left", fill="both", expand="yes")
        self.odLabel_user = Label(self.listBox_user, imag=odFilename)
        self.odLabel_user.pack(side="left", fill="both", expand="yes")
        self.ssLabel_user = Label(self.listBox_user, imag=ssFilename)
        self.ssLabel_user.pack(side="left", fill="both", expand="yes")
        infoFile = open(infoFilePath)
        infoList = []
        for line in infoFile.readlines():
            infoList.append(line)
        info = ''.join(infoList)
        print(info)
        self.infoLabel_user = Label(self.pic_win_user, text=info, justify=LEFT)
        self.infoLabel_user.pack()
        self.listBox_user.insert(ACTIVE, self.imageLabel_user)
        self.listBox_user.insert(ACTIVE, self.odLabel_user)
        self.listBox_user.insert(self.ssLabel_user)
        # self.listBox_user.insert(END, self.infoLabel)
        self.listBox_user.pack()

    def _quit(self):
        self.quit()
        self.destroy()
        exit()
Esempio n. 37
0
    save_image(img, name)

# Create a window environment on the computer
image_window = Tk()

# Window requieres no frame
image_window.attributes("-alpha", 0.0)
image_window.iconify()

# Create a window on the screen of the SLM monitor
window_slm = Toplevel(image_window)
window_slm_geometry = str("{:}".format(width) + 'x' + "{:}".format(height) +
                          '+' + "{:}".format(begin_slm_horizontal) + '+' +
                          "{:}".format(begin_slm_vertical))
print(window_slm_geometry)
window_slm.geometry(window_slm_geometry)
window_slm.overrideredirect(1)

# # Open the created image with the SLM pattern
photo = ImageTk.PhotoImage(img)

# # Load the opened image into the window of the SLM monitor
window_slm_label = Label(window_slm, image=photo)
window_slm_label.pack()

# Termination command for the code
image_window.bind("<Escape>", lambda e: image_window.destroy())

# Run the loop for the window environment
image_window.mainloop()
Esempio n. 38
0
def startSignup():
    global root
    root = Toplevel()
    root.attributes('-topmost', True)
    root.title("  Signup")
    root.geometry("330x620")
    # root.resizable(0,0)
    root.configure(bg="white")
    root.iconphoto(True, PhotoImage(file=assetpath + 'login.png'))
    root.tk.call('tk', 'scaling', 1.6)

    style = Style()
    style.configure("TLabel", background="white")

    Label(root,
          text="CREATE AN ACCOUNT",
          font=("ARIAL", 15, 'bold', 'italic'),
          bg="dodger blue",
          fg="white").pack(pady=(20, 20), ipadx=10, ipady=10)
    mainf = Frame(root, bg="white")
    mainf.pack(padx=30, pady=(20, 5), ipadx=30, ipady=20)

    #making the form
    Label(mainf, text="Username :"******"Arial", 8, 'bold'),
          bg="white").pack(anchor=W)
    userb = Frame(mainf, bg="dodger blue", bd=2)
    userb.pack(anchor=W)
    usere = Entry(userb, width=30)
    usere.pack(anchor=W, ipadx=5, ipady=5)

    Label(mainf, text="Email :", font=("Arial", 8, 'bold'),
          bg="white").pack(anchor=W)
    mailb = Frame(mainf, bg="dodger blue", bd=2)
    mailb.pack(anchor=W)
    maile = Entry(mailb, width=30)
    maile.pack(anchor=W, ipadx=5, ipady=5)

    Label(mainf,
          text="Choose Password :"******"Arial", 8, 'bold'),
          bg="white").pack(anchor=W)
    passb = Frame(mainf, bg="dodger blue", bd=2)
    passb.pack(anchor=W)
    passe = Entry(passb, width=30, show="*")
    passe.pack(anchor=W, ipadx=5, ipady=5)

    Label(mainf,
          text="Confirm Password :"******"Arial", 8, 'bold'),
          bg="white").pack(anchor=W)
    passcb = Frame(mainf, bg="dodger blue", bd=2)
    passcb.pack(anchor=W)
    passce = Entry(passcb, width=30, show="*")
    passce.pack(anchor=W, ipadx=5, ipady=5)

    #a curated set of security questions
    sec_ques = [
        "What is your pet name?",
        "What was the first company that you worked for?",
        "Where did you meet your spouse?",
        "Where did you go to high school/college?",
        "What city were you born in?"
    ]

    Label(mainf,
          text="Security Question :",
          font=("Arial", 8, 'bold'),
          bg="white").pack(anchor=W)
    combo = Combobox(mainf, values=sec_ques, width=29, state='readonly')
    combo.pack(anchor=W, pady=(10, 10))
    combo.current(0)
    quesb = Frame(mainf, bg="dodger blue", bd=2)
    quesb.pack(anchor=W)
    quese = Entry(quesb, width=30)
    quese.pack(anchor=W, ipadx=5, ipady=5)

    Label(
        mainf,
        text=
        "The security question will help you\n login if you forget your password",
        bg="white").pack(pady=(20, 10))
    createb = Button(mainf,
                     width=30,
                     text="Create Account",
                     font=('ARIAL', 10, 'bold'),
                     bd=0,
                     fg="white",
                     bg="dodger blue",
                     activebackground="dodger blue",
                     activeforeground="white")
    createb.pack(ipadx=5, ipady=5, padx=10, pady=20)

    root.mainloop()
Esempio n. 39
0
 def winSuccess(self):
     subScreen = Toplevel(self.screen)
     subScreen.geometry("150x90")
     subScreen.title("Error:")
     Label(subScreen, text="Mail Sent Successfully", fg="red").pack()
     Button(subScreen, text="OK", command=subScreen.destroy).pack()
Esempio n. 40
0
# hashtag Call game timer
gametime()

# hashtag  Bind the controls for the game
window.bind("<KeyPress>", onkeypress)

# hashtag  create window that is shown when the player finishes the maze
top_victory = Toplevel(padx=10, pady=10,
                       bg='black')  # hashtag  initialize a TopLevel widget
top_victory.title('Victory')  # hashtag  set the title
top_victory.resizable(False, False)
top_victory.protocol(
    'WM_DELETE_WINDOW', close_victory
)  # hashtag  set the command for when the user wants to exit the window
top_victory.geometry('%dx%d+%d+%d' %
                     (window.winfo_screenwidth(), window.winfo_screenheight(),
                      0, 0))  # hashtag  place the window
top_victory.withdraw()  # hashtag  withdraw the other windows so that this win
myFont2 = font.Font(family="Comic Sans MS", size=6, weight="bold")
img = PhotoImage(
    file='images/victory.png')  # hashtag  create the celebration picture
lblImg = Label(top_victory, image=img)  # hashtag  put the image in a label
lblImg.place(x=2000, y=2000, height=720,
             width=1280)  # hashtag  place the label
lblVictory = Label(
    top_victory,
    text=
    'You completed! Please zoom in and look carefully here for your prize!',
    fg='white',
    font=myFont2,
    bg='black')
def addstudent():
    def submitadd():
        id = idval.get()
        name = nameval.get()
        mobile = mobileval.get()
        email = emailval.get()
        address = addressval.get()
        gender = genderval.get()
        dob = dobval.get()
        addedtime = time.strftime("%H:%M:%S")
        addeddate = time.strftime("%d/%m/%Y")
        try:
            strr = 'insert into studentdata values(%s,%s,%s,%s,%s,%s,%s,%s,%s)'
            mycursor.execute(strr, (id, name, mobile, email, address, gender,
                                    dob, addeddate, addedtime))
            con.commit()
            res = messagebox.askyesnocancel(
                'Notification',
                'Id {} Name {} Added sucessfully... and want to clear the form'
                .format(id, name),
                parent=addroot)
            if res == True:
                idval.set('')
                nameval.set('')
                mobileval.set('')
                emailval.set('')
                addressval.set('')
                genderval.set('')
                dobval.set('')
        except:
            messagebox.showerror('Notification',
                                 'id Already Exist pls Try another id.....',
                                 parent=addroot)
        strr = 'select *from studentdata'
        mycursor.execute(strr)
        datas = mycursor.fetchall()
        studenttable.delete(*studenttable.get_children())
        for i in datas:
            vv = [i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]]
            studenttable.insert('', END, values=vv)

    addroot = Toplevel(master=DataEntryFrame)
    addroot.grab_set()
    addroot.iconbitmap('max.ico')
    addroot.geometry('470x470+150+150')
    addroot.title('Add Student')
    addroot.resizable(False, False)
    addroot.config(bg='lightblue')
    #=====================================================================================
    idlabel = Label(addroot,
                    text="Enter Id:",
                    bg="lightgreen",
                    anchor='w',
                    font=('arial', 15, 'bold'),
                    relief=GROOVE,
                    borderwidth=3,
                    width=12)
    idlabel.place(x=10, y=10)
    namelabel = Label(addroot,
                      text="Enter Name:",
                      bg="lightgreen",
                      anchor='w',
                      font=('arial', 15, 'bold'),
                      relief=GROOVE,
                      borderwidth=3,
                      width=12)
    namelabel.place(x=10, y=60)
    mobilelabel = Label(addroot,
                        text="Enter Mobile:",
                        bg="lightgreen",
                        anchor='w',
                        font=('arial', 15, 'bold'),
                        relief=GROOVE,
                        borderwidth=3,
                        width=12)
    mobilelabel.place(x=10, y=110)
    emaillabel = Label(addroot,
                       text="Enter Email:",
                       bg="lightgreen",
                       anchor='w',
                       font=('arial', 15, 'bold'),
                       relief=GROOVE,
                       borderwidth=3,
                       width=12)
    emaillabel.place(x=10, y=160)
    addresslabel = Label(addroot,
                         text="Enter Address:",
                         bg="lightgreen",
                         anchor='w',
                         font=('arial', 15, 'bold'),
                         relief=GROOVE,
                         borderwidth=3,
                         width=12)
    addresslabel.place(x=10, y=210)
    genderlabel = Label(addroot,
                        text="Enter Gender:",
                        bg="lightgreen",
                        anchor='w',
                        font=('arial', 15, 'bold'),
                        relief=GROOVE,
                        borderwidth=3,
                        width=12)
    genderlabel.place(x=10, y=260)
    doblabel = Label(addroot,
                     text="Enter D.O.B.:",
                     bg="lightgreen",
                     anchor='w',
                     font=('arial', 15, 'bold'),
                     relief=GROOVE,
                     borderwidth=3,
                     width=12)
    doblabel.place(x=10, y=310)
    #==============================================================================================
    idval = StringVar()
    nameval = StringVar()
    mobileval = StringVar()
    emailval = StringVar()
    addressval = StringVar()
    genderval = StringVar()
    dobval = StringVar()

    identry = Entry(addroot,
                    font=('roman', 15, 'bold'),
                    bd=2,
                    textvariable=idval,
                    bg="lightgreen")
    identry.place(x=200, y=10)
    nameentry = Entry(addroot,
                      font=('roman', 15, 'bold'),
                      bd=2,
                      textvariable=nameval,
                      bg="lightgreen")
    nameentry.place(x=200, y=60)
    mobileentry = Entry(addroot,
                        font=('roman', 15, 'bold'),
                        bd=2,
                        textvariable=mobileval,
                        bg="lightgreen")
    mobileentry.place(x=200, y=110)
    emailentry = Entry(addroot,
                       font=('roman', 15, 'bold'),
                       bd=2,
                       textvariable=emailval,
                       bg="lightgreen")
    emailentry.place(x=200, y=160)
    addressentry = Entry(addroot,
                         font=('roman', 15, 'bold'),
                         bd=2,
                         textvariable=addressval,
                         bg="lightgreen")
    addressentry.place(x=200, y=210)
    genderentry = Entry(addroot,
                        font=('roman', 15, 'bold'),
                        bd=2,
                        textvariable=genderval,
                        bg="lightgreen")
    genderentry.place(x=200, y=260)
    dobentry = Entry(addroot,
                     font=('roman', 15, 'bold'),
                     bd=2,
                     textvariable=dobval,
                     bg="lightgreen")
    dobentry.place(x=200, y=310)
    addrootbutton = Button(addroot,
                           text='Submit',
                           command=submitadd,
                           font=('arial', 20, 'bold'),
                           bg='red',
                           bd=3,
                           activebackground='blue',
                           activeforeground="white")
    addrootbutton.place(x=150, y=380)
    addroot.mainloop()
Esempio n. 42
0
def signup():
    global sign
    sign = Toplevel()
    sign.title("Registration Form")
    sign.iconbitmap('images/logo.ico')
    sign.geometry("1500x800+0+0")

    ################################ VARIABLE FOR ENTRIES DROP DOWN AND RADIO BUTTONS ######################

    ################################## VARIABLE FOR ENTRIES DROP DOWN AND RADIO BUTTONS ######################

    ####################################    BACKGROUND IMAGE ##########################
    # bg_picture = ImageTk.PhotoImage(file = "images/seeba.jpg")
    # label = Label(sign,image = bg_picture)
    # label.pack()
    sign.configure(bg='lightgrey')
    ####################################    BACKGROUND IMAGE ##########################
    global label_one
    global label_two
    global label_three

    label_one = StringVar()
    label_two = StringVar()
    label_three = StringVar()

    label_val_name = Label(sign,
                           textvariable=label_one,
                           fg='red',
                           bg='lightgrey',
                           font="calibiri 14 bold italic")
    label_val_name.place(x=605, y=120)

    label_val_password = Label(sign,
                               textvariable=label_two,
                               fg='red',
                               bg='lightgrey',
                               font="calibiri 14 bold italic")
    label_val_password.place(x=605, y=120)

    label_val_contact = Label(sign,
                              textvariable=label_three,
                              fg='red',
                              bg='lightgrey',
                              font="calibiri 14 bold italic")
    label_val_contact.place(x=605, y=120)
    #####################################   first main frame start########################
    frame_main = Frame(sign, bg='white')
    frame_main.place(x=480, y=180, width=430, height=400)
    #####################################   first main frame end  ########################

    #####################################  registration heading start  #################
    label_heading = Label(frame_main,
                          text="Registration Form",
                          bg='white',
                          fg='green',
                          font=("Goudy old style", 30, "bold", "italic"))
    label_heading.place(x=0, y=0, width=410, height=50)
    #####################################  registration heading END #################

    ####################################### LABEL AND ENTRIES FOR NAME ############################
    label_name = Label(frame_main,
                       text='Name:',
                       bg='white',
                       fg='black',
                       font=("Goudy old style", 20, "bold"))
    label_name.place(x=5, y=58)
    global label_name_entry
    label_name_entry = Entry(frame_main,
                             bg='lightgray',
                             fg='black',
                             font=("Helvetica", 16))
    label_name_entry.place(x=125, y=65, width=260, height=25)
    ####################################### LABEL AND ENTRIES FOR NAME ############################

    ####################################### LABEL AND ENTRIES FOR UserName ############################

    label_user = Label(frame_main,
                       text='UserName:'******'white',
                       fg='black',
                       font=("Goudy old style", 18, "bold"))
    label_user.place(x=5, y=110)
    global label_user_entry
    label_user_entry = Entry(frame_main,
                             bg='lightgray',
                             fg='black',
                             font=("Helvetica", 16))
    label_user_entry.place(x=125, y=117, width=260, height=25)
    ####################################### LABEL AND ENTRIES FOR UserName ############################

    ####################################### LABEL AND ENTRIES FOR PASSWORD ############################

    label_password = Label(frame_main,
                           text='Password:'******'white',
                           fg='black',
                           font=("Goudy old style", 20, "bold"))
    label_password.place(x=5, y=162)
    global label_password_entry
    label_password_entry = Entry(frame_main,
                                 bg='lightgray',
                                 fg='black',
                                 font=("Helvetica", 16))
    label_password_entry.place(x=125, y=169, width=260, height=25)
    ####################################### LABEL AND ENTRIES FOR PASSWORD ############################

    ####################################### LABEL AND RADIO BUTTONS OF GENDER ############################
    label_gender = Label(frame_main,
                         text='Gender:',
                         bg='white',
                         fg='black',
                         font=("Goudy old style", 20, "bold"))
    label_gender.place(x=5, y=214)
    global genderval
    genderval = StringVar()
    male_radio = Radiobutton(frame_main,
                             text="Male",
                             value="Male",
                             variable=genderval,
                             fg='black',
                             bg='white',
                             font=("Helvetica", 15))
    male_radio.place(x=120, y=218)

    female_radio = Radiobutton(frame_main,
                               text="Female",
                               value="Female",
                               variable=genderval,
                               fg='black',
                               bg='white',
                               font=("Helvetica", 15))
    female_radio.place(x=240, y=218)
    ####################################### LABEL AND RADIO BUTTONS OF GENDER ############################

    ####################################### LABEL AND ENTRIES FOR CONTACT ############################
    label_contact = Label(frame_main,
                          text='Contact:',
                          bg='white',
                          fg='black',
                          font=("Goudy old style", 20, "bold"))
    label_contact.place(x=5, y=267)
    global label_contact_entry
    label_contact_entry = Entry(frame_main,
                                bg='lightgray',
                                fg='black',
                                font=("Helvetica", 16))
    label_contact_entry.place(x=125, y=273, width=260, height=25)
    ####################################### LABEL AND ENTRIES FOR CONTACT ############################

    ####################################### LABEL AND DROP DOWN FOR STREAM ############################

    label_contact = Label(frame_main,
                          text='Stream:',
                          bg='white',
                          fg='black',
                          font=("Goudy old style", 20, "bold"))
    label_contact.place(x=5, y=325)

    options = ["Computer", "Science", "Commerce"]
    global variabledropdown
    variabledropdown = StringVar()
    variabledropdown.set(options[0])
    w = OptionMenu(frame_main, variabledropdown, *options)
    w.place(x=125, y=331, width=260, height=25)

    ####################################### LABEL AND DROP DOWN FOR STREAM ############################

    button_register = Button(sign,
                             text="Register",
                             bg='green',
                             fg='white',
                             command=register,
                             width=10,
                             cursor="hand2",
                             font=("calibiri", 20, "bold"))
    button_register.place(x=600, y=560)

    # button_login = Button(sign,text='Login',bg='#d77337',fg='white',bd=0,width=9,cursor="hand2",font=("times new roman", 18))
    # button_login.place(x=420,y=540)

    # button_login.place(x=430, y=550)

    sign.mainloop()
Esempio n. 43
0
class MinecraftLauncher(Tk):

    def __init__(self):
        try:
            Tk.__init__(self)
        except:
            log_err('no display, exit')
            exit(1)
        self.title(get_lang('launcher.title'))
        if settings['use-theme'] != 'ttk':
            theme_path = os.path.dirname(os.path.abspath(__file__)) + '/theme/' + settings['use-theme']
            self.tk.eval('lappend auto_path {%s}' % theme_path)
            ttk.Style().theme_use(settings['use-theme'])
        # 小部件
        self.new_button = ttk.Button(self, text=get_lang('launcher.new'), command=self.new)
        self.start_button = ttk.Button(self, text=get_lang('launcher.start'), command=self.start_game)
        self.exit_button = ttk.Button(self, text=get_lang('launcher.exit'),  command=lambda: exit())
        self.game_item_list = Listbox(self, height=12)
        self.vscroll = ttk.Scrollbar(self, orient='vertical', command=self.game_item_list.yview)
        self.game_item_list.configure(yscrollcommand=self.vscroll.set)
        self.repair_button = ttk.Button(self, text=get_lang('launcher.repair'), command=self.repair)
        self.del_button = ttk.Button(self, text=get_lang('launcher.delete'), command=self.delete)
        self.rename_button = ttk.Button(self, text=get_lang('launcher.rename'), command=self.rename)
        # 显示
        self.new_button.grid(column=0, row=0, padx=5, pady=5)
        self.start_button.grid(column=1, row=0, padx=5, pady=5)
        self.exit_button.grid(column=2, row=0, padx=5, pady=5)
        self.game_item_list.grid(column=0, columnspan=4, row=1, padx=3, pady=5, sticky='news')
        self.vscroll.grid(column=4, row=1, padx=2, pady=5, sticky='nes')
        self.repair_button.grid(column=0, row=2, padx=5, pady=5)
        self.del_button.grid(column=1, row=2, padx=5, pady=5)
        self.rename_button.grid(column=2, row=2, padx=5, pady=5)
        self.resizable(False, False)
        self.refresh()

    def delete(self, event=None):
        # 删除世界
        if self.game_item_list.curselection() == ():
            select = self.game_item_list.get(0)
        else:
            select = self.game_item_list.get(self.game_item_list.curselection()[0])
        if messagebox.askyesno(message=get_lang('launcher.dialog.text.delete') % select,
                title=get_lang('launcher.dialog.title.delete')):
            shutil.rmtree(os.path.join(path['save'], select))
        self.refresh()

    def new(self, event=None):
        # 新的世界对话框
        self.new_dialog = Toplevel(self)
        self.new_dialog.title(get_lang('launcher.dialog.title.new'))
        self.new_dialog_label_name = ttk.Label(self.new_dialog, text=get_lang('launcher.dialog.text.name'))
        self.new_dialog_entry_name = ttk.Entry(self.new_dialog)
        self.new_dialog_label_seed = ttk.Label(self.new_dialog, text=get_lang('launcher.dialog.text.seed'))
        self.new_dialog_entry_seed = ttk.Entry(self.new_dialog)
        self.new_dialog_label_type = ttk.Label(self.new_dialog, text='Type:')
        self.new_dialog_combobox_type = ttk.Combobox(self.new_dialog, values = ('flat', 'random'), width=8)
        self.new_dialog_combobox_type.state(['readonly'])
        self.new_dialog_button_ok = ttk.Button(self.new_dialog,
                text=get_lang('launcher.dialog.text.ok'), command=self.new_world
                                               )
        self.new_dialog_label_name.grid(column=0, row=0, padx=5, pady=5)
        self.new_dialog_entry_name.grid(column=1, row=0, columnspan=2, padx=5,
                                        pady=5)
        self.new_dialog_label_seed.grid(column=0, row=1, padx=5, pady=5)
        self.new_dialog_entry_seed.grid(column=1, row=1, columnspan=2, padx=5,
                                        pady=5)
        self.new_dialog_label_type.grid(column=0, row=2, padx=5, pady=5)
        self.new_dialog_combobox_type.grid(column=1, row=2, pady=5)
        self.new_dialog_button_ok.grid(column=2, row=3, padx=5, pady=5)
        self.new_dialog.resizable(False, False)
        self.new_dialog.geometry('+%d+%d' % (self.winfo_x() + 50,
                                 self.winfo_y() + 50))
        self.new_dialog.transient(self)
        self.new_dialog.deiconify()
        self.new_dialog.grab_set()
        self.new_dialog.wait_window()
        self.new_dialog.mainloop()

    def new_world(self, event=None):
        # 创建一个新的世界
        name = self.new_dialog_entry_name.get()
        seed = s = self.new_dialog_entry_seed.get()
        if seed == '':
            seed = hash(time.ctime())
        else:
            seed = hash(seed)
        if name == '':
            log_err('invalid world name')
        elif s == '_server' and not ([s for s in list(punctuation) if s in name] == []):
            log_err('invalid world name')
        else:
            if not os.path.isdir(os.path.join(path['save'], name)):
                os.mkdir(os.path.join(path['save'], name))
                world = open(os.path.join(path['save'], name, 'world.json'), 'w+')
                world.write('{\n}\n')
                world.close()
                info = {'seed': seed, 'type': self.new_dialog_combobox_type.get(), 'time': 400, 'weather':
                        {'now': 'clear', 'duration': 600}}
                json.dump(info, open(os.path.join(path['save'], name, 'info.json'), 'w+'))
                player = {'position': '0.0', 'respawn': '0.0', 'now_block': 0}
                json.dump(player, open(os.path.join(path['save'], name, 'player.json'), 'w+'))
                self.new_dialog.destroy()
                log_info('create world successfully')
        self.refresh()

    def refresh(self):
        # 刷新
        self.game_item_list.delete(0, 'end')
        for item in [i for i in os.listdir(path['save']) if is_game_restore(i)]:
            self.game_item_list.insert('end', item)

    def rename(self):
        # 重命名对话框
        self.rename_dialog = Toplevel(self)
        self.rename_dialog.title(get_lang('launcher.dialog.title.rename'))
        self.rename_dialog_label = ttk.Label(self.rename_dialog,
            style='TLabel', text=get_lang('launcher.dialog.text.name'))
        self.rename_dialog_entry = ttk.Entry(self.rename_dialog)
        name = self.game_item_list.curselection()
        name = self.game_item_list.get(0) if name == () else self.game_item_list.get(name)
        self.rename_dialog_entry.insert(0, name)

        def send_name():
            self.rename_world(name)

        self.old = os.path.join(path['save'], self.rename_dialog_entry.get())
        self.rename_dialog_button = ttk.Button(self.rename_dialog,
                text=get_lang('launcher.dialog.text.ok'), command=send_name)
        self.rename_dialog_label.grid(column=0, row=0, padx=5, pady=5)
        self.rename_dialog_entry.grid(column=1, row=0, columnspan=2, padx=5, pady=5)
        self.rename_dialog_button.grid(column=2, row=1, padx=5, pady=5)
        self.rename_dialog.resizable(False, False)
        self.rename_dialog.geometry('+%d+%d' % (self.winfo_x() + 50, self.winfo_y() + 50))
        self.rename_dialog.transient(self)
        self.rename_dialog.deiconify()
        self.rename_dialog.grab_set()
        self.rename_dialog.wait_window()
        self.rename_dialog.mainloop()

    def rename_world(self, name):
        # 重命名世界
        shutil.move(os.path.join(path['save'], name), os.path.join(path['save'], self.rename_dialog_entry.get()))
        self.rename_dialog.destroy()
        self.refresh()

    def repair(self, event=None):
        select =self.game_item_list.curselection()
        if select == ():
            log_warn('no world selected')
            return
        select = self.game_item_list.get(select[0])
        repair_archive(select)

    def start_game(self, event=None):
        # 启动游戏
        select = self.game_item_list.curselection()
        if  select == ():
            log_warn('no world selected')
            return
        select = self.game_item_list.get(select[0])
        self.destroy()
        try:
            data = load_window()
            game = Game(width=data['width'], height=data['height'], caption='Minecraft', resizable=True)
            game.set_name(select)
            setup()
            pyglet.app.run()
        except SystemExit:
            pass
        except:
            name = '%d.log' % int(time.time())
            log_err('catch error, saved in: log/%s' % name)
            # err_log = open(os.path.join(path['log'], name), 'a+')
            # err_log.write('Minecraft version: %s\n' % VERSION['str'])
            # err_log.write('time: %s\n' % time.ctime())
            # err_log.write('save: %s\n' % select)
            # err_log.write('traceback:\n' + '=' * 34 + '\n')
            traceback.print_exc()
            # err_log.write('=' * 34 + '\n')
            # err_log.flush()
            # err_log.close()
            exit(1)
Esempio n. 44
0
    def hiya(self):
        if not self.nand_mode:
            showinfo(
                'Info',
                'Now you will be asked to choose the SD card path that will be used '
                'for installing the custom firmware (or an output folder).\n\nIn order to avoid '
                'boot errors please assure it is empty before continuing.')
            self.sd_path = askdirectory()

            # Exit if no path was selected
            if self.sd_path == '':
                return

        # If adding a No$GBA footer, check if CID and ConsoleID values are OK
        elif self.nand_operation.get() == 1:
            cid = self.cid.get()
            console_id = self.console_id.get()

            # Check lengths
            if len(cid) != 32:
                showerror('Error', 'Bad eMMC CID')
                return

            elif len(console_id) != 16:
                showerror('Error', 'Bad Console ID')
                return

            # Parse strings to hex
            try:
                cid = bytearray.fromhex(cid)

            except ValueError:
                showerror('Error', 'Bad eMMC CID')
                return

            try:
                console_id = bytearray(reversed(bytearray.fromhex(console_id)))

            except ValueError:
                showerror('Error', 'Bad Console ID')
                return

        dialog = Toplevel(self)
        # Open as dialog (parent disabled)
        dialog.grab_set()
        dialog.title('Status')
        # Disable maximizing
        dialog.resizable(0, 0)

        frame = Frame(dialog, bd=2, relief=SUNKEN)

        scrollbar = Scrollbar(frame)
        scrollbar.pack(side=RIGHT, fill=Y)

        self.log = ThreadSafeText(frame,
                                  bd=0,
                                  width=52,
                                  height=20,
                                  yscrollcommand=scrollbar.set)
        self.log.pack()

        scrollbar.config(command=self.log.yview)

        frame.pack()

        if sysname == 'Darwin' and getattr(sys, 'frozen', False):
            Label(dialog, text='Close').pack(side='top', pady=(10, 0))
            Button(dialog, text='Close', command=dialog.destroy,
                   width=16).pack(pady=(0, 10))
        else:
            Button(dialog, text='Close', command=dialog.destroy,
                   width=16).pack(pady=10)

        # Center in window
        dialog.update_idletasks()
        width = dialog.winfo_width()
        height = dialog.winfo_height()
        dialog.geometry(
            '%dx%d+%d+%d' %
            (width, height, root.winfo_x() + (root.winfo_width() / 2) -
             (width / 2), root.winfo_y() + (root.winfo_height() / 2) -
             (height / 2)))

        # Check if we'll be adding a No$GBA footer
        if self.nand_mode and self.nand_operation.get() == 1:
            Thread(target=self.add_footer, args=(cid, console_id)).start()

        else:
            Thread(target=self.check_nand).start()
Esempio n. 45
0
class End(object):
    def __init__(self, master, gen, start_cell, score, max_score):
        self.end = Toplevel(master)
        self.end.transient(master)
        self.end.title('THE END')

        self.wid = 200
        self.hei = 170
        x = master.winfo_x()
        y = master.winfo_y()
        smw = master.winfo_width() // 2
        smh = master.winfo_height() // 2
        tplft = (x + smw - self.wid // 2, y + smh - self.hei // 2)
        self.end.geometry(f'{self.wid}x{self.hei}+{tplft[0]}+{tplft[1]}')
        # self.end.resizable(width=False, height=False)
        self.end.overrideredirect(True)

        self.end.gen = str(gen - 1)
        self.end.start = str(start_cell)
        # because they are out of the cycle
        self.end.score = str(score + start_cell)
        self.end.max = str(max_score)

        self.end.label_univ = Label(self.end, text='EMPTY UNIVERSUM')
        self.end.label_univ.pack(side=TOP, fill=BOTH, pady=10)

        self.end.label_cyc = Label(self.end,
                                   text='LIFE EXIST ' + self.end.gen +
                                   ' CYCLES')
        self.end.label_cyc.pack(side=TOP, fill=BOTH)

        self.end.label_cell = Label(self.end,
                                    text='POPULATION ' + self.end.score +
                                    ' CELLS')
        self.end.label_cell.pack(side=TOP, fill=BOTH)

        self.end.label_cell = Label(self.end,
                                    text='SEEDS ' + self.end.start + ' CELLS')
        self.end.label_cell.pack(side=TOP, fill=BOTH)

        self.end.label_maxcell = Label(self.end,
                                       text='MAXIMUM ' + self.end.max +
                                       ' CELLS')
        self.end.label_maxcell.pack(side=TOP, fill=BOTH)

        self.end.frameButt = Frame(self.end, bd=5)
        self.end.frameButt.pack(side=BOTTOM)

        self.end.exit = Button(self.end.frameButt,
                               text='END LIFE',
                               width=7,
                               command=self.exit_life)
        self.end.exit.pack(side=LEFT, padx=5)

        self.end.new = Button(self.end.frameButt,
                              text='NEW LIFE',
                              width=7,
                              command=self.new_life)
        self.end.new.pack(side=LEFT, padx=5)

    def answer(self):
        # to prevent error when close main window
        self.answer = None

        self.end.grab_set()
        self.end.wait_window()
        return self.answer

    def exit_life(self):
        self.answer = False
        self.end.destroy()

    def new_life(self):
        self.answer = True
        self.end.destroy()
class Register_window:
    def register(self, home_screen):
        print('register function')

        #Temp varibles
        self.temp_username = StringVar()
        self.temp_password = StringVar()

        self.register_screen = Toplevel(home_screen)
        self.register_screen.geometry('450x160')
        self.register_screen.title('Register')

        #Labels
        self.details_label = Label(self.register_screen,
                                   text='Please enter yor details below',
                                   font=('Calibri', 26))
        self.details_label.grid(row=0, column=0, sticky='N')

        self.username_lable = Label(self.register_screen,
                                    text='Username',
                                    font=('Calibri', 16))
        self.username_lable.grid(row=1, column=0, sticky='W')

        self.password_lable = Label(self.register_screen,
                                    text='Password',
                                    font=('Calibri', 16))
        self.password_lable.grid(row=2, column=0, sticky='W')

        #Error label
        self.error_label = Label(self.register_screen, font=('Calibri', 12))
        self.error_label.grid(row=4, sticky='N')

        #Entries
        self.username_entry = Entry(self.register_screen,
                                    textvariable=self.temp_username)
        self.username_entry.grid(row=1, column=0)

        self.password_entry = Entry(self.register_screen,
                                    textvariable=self.temp_password,
                                    show='*')
        self.password_entry.grid(row=2, column=0)

        #Buttons
        self.ok_button = Button(self.register_screen,
                                text='Ok',
                                font=('Calibri', 16),
                                width=10,
                                command=lambda: self.register_user())
        self.ok_button.grid(row=3, column=0, sticky='E')

        #self.cancel_button = Button(self.register_screen, text='Cancel', font=('Calibri', 16), width=10,command=self.register_screen.destroy)
        self.cancel_button = Button(
            self.register_screen,
            text='Cancel',
            font=('Calibri', 16),
            width=10,
            command=lambda: self.register_screen.destroy())
        self.cancel_button.grid(row=3, column=0, sticky='W', padx=5)

    def close(self):
        print("close")
        #button.place_forget()
        self.register_screen.destroy()

    def remove_button(self, button):
        print("remove_button")
        #button.place_forget()

    def register_user(self):
        import time
        username = self.temp_username.get()
        password = self.temp_password.get()
        lower_bound = '180'
        self.register_screen.geometry('450x{}'.format(lower_bound))
        if ((" " in username) or (" " in password)):
            self.error_label.config(fg='red', text='Spaces are not allowed')
        elif (username == '' and password == ''):
            self.error_label.config(
                fg='red', text='Please enter a username and a password')
        elif (username == ''):
            self.error_label.config(fg='red', text='Please enter a username')
        elif (password == ''):
            self.error_label.config(fg='red', text='Please enter a password')
        elif (Bank_system().check_username(username)):
            self.error_label.config(fg='red', text='Username is already taken')
        elif (not (Bank_system().check_username(username))):
            Bank_system().add_user_to_db(username, password)
            self.remove_register_GUI()
            self.register_screen.update()
            time.sleep(1)
            self.close()

    def remove_register_GUI(self):
        self.details_label.config(fg='green', text='Register complete')
        self.ok_button.destroy()
        self.cancel_button.destroy()
        self.username_lable.destroy()
        self.password_lable.destroy()
        self.username_entry.destroy()
        self.password_entry.destroy()
        self.error_label.destroy()
Esempio n. 47
0
# top level window
root.title('Toplevel Window')
root.geometry('300x300')
Label(
    root,
    text='I am the Main Toplevel window\n All other windows here are my children'
).pack()

# child toplevel
child_toplevel = Toplevel(root)
Label(
    child_toplevel,
    text=
    'I am a child of root\n If i loose focus, I may hide below the top level, \n I am destroyed, if root is destroyed'
).pack()
child_toplevel.geometry('400x100+300+300')

# transient window
transient_toplevel = Toplevel(root)
Label(
    transient_toplevel,
    text=
    'I am a transient window of root\n I always stay on top of my parent\n I get hidden if my parent window is minimized'
).pack()
transient_toplevel.transient(root)

# no window decoration
no_window_decoration = Toplevel(root, bg='black')
Label(no_window_decoration,
      text=
      'I am a top-level with no window manager\n I cannot be resized or moved',
Esempio n. 48
0
class CheckUpdates():
    def __init__(self, versao_safira, interface_idioma, idioma, master, design,
                 icon):

        self.versao_safira = versao_safira
        self.interface_idioma = interface_idioma
        self.idioma = idioma
        self.master = master
        self.design = design
        self.icon = icon

        # Destino dos Downloads e Backups
        self.__tp_atualizacao = None
        data = str(datetime.now()).split('.')[0]
        data = data.replace(' ', '-')
        data = data.replace(':', '-')

        dest_download = os_path.join(os_getcwd(), 'AtualizarSafira')
        dest_backup = os_path.join(os_getcwd(), 'backups', data)

        # Instância de Upgrades
        self.__up = Upgrade.Upgrade(dest_download, dest_backup)

    def verificar_atualizacoes(self, primeira_vez=False):
        """Verifica se existe uma versão mais recente disponível """
        try:
            # Obter todas as versões
            dic_versoes = self.__up.obter_informacoes_versao()

            if dic_versoes.get('erro'):
                print(dic_versoes['erro'])

                messagebox.showinfo(
                    "Erro ao buscar versões",
                    "Aconteceu um erro quando a Safira tentou buscar as versões disponíveis. Este foi o erro: {}"
                    .format(dic_versoes['erro']))
            else:
                # Obter ultima versão
                recente = max(dic_versoes.keys())
                if float(self.versao_safira) < float(recente):

                    print('A versão {} disponível, deseja atualizar?'.format(
                        recente))
                    self.__aviso_versao(recente)

                else:
                    # Não é necessário avisar que está atualizado
                    # Se a interface estiver iniciando
                    if not primeira_vez:
                        self.__aviso_versao_atualizada()

        except Exception as erro:
            if not primeira_vez:
                messagebox.showinfo(
                    "ops",
                    self.interface_idioma["erro_generico"][self.idioma] +
                    str(erro))

    def __aviso_versao(self, recente):
        """ Aviso, existe uma nova versão disponível """

        self.__tp_atualizacao = Toplevel(
            self.master, self.design.dic["aviso_versao_top_level"])
        self.__tp_atualizacao.withdraw()
        self.__tp_atualizacao.focus_force()
        self.__tp_atualizacao.resizable(False, False)
        self.__tp_atualizacao.tk.call('wm', 'iconphoto',
                                      self.__tp_atualizacao._w, self.icon)
        self.__tp_atualizacao.grid_columnconfigure(1, weight=1)
        self.__tp_atualizacao.title(
            self.interface_idioma["titulo_aviso_atualizacao"][self.idioma])

        # Objetos da interface
        fr_atualizaca = Frame(self.__tp_atualizacao)
        lb_versao_dev = Label(
            fr_atualizaca,
            text=self.interface_idioma["versao_nova_disponivel"][self.idioma])
        lb_versao_tex = Message(
            fr_atualizaca,
            text='{}'.format(self.interface_idioma["texto_update_disponivel"][
                self.idioma]).format(recente))
        fr_botoes = Frame(fr_atualizaca)

        bt_cancela = Button(
            fr_botoes,
            text=self.interface_idioma["versao_nao_quero"][self.idioma])
        bt_atualiza = Button(
            fr_botoes,
            text=self.interface_idioma["atualizar_agora"][self.idioma])

        # Configurações de desingn
        fr_atualizaca.configure(self.design.dic["aviso_versao_fr_atualizacao"])
        lb_versao_dev.configure(self.design.dic["aviso_versao_lb_dev"])
        lb_versao_tex.configure(self.design.dic["aviso_versao_ms"])
        fr_botoes.configure(self.design.dic["aviso_versao_btn"])
        bt_cancela.configure(self.design.dic["aviso_versao_btn_cancela"],
                             relief=FLAT)
        bt_atualiza.configure(self.design.dic["aviso_versao_btn_atualiza"],
                              relief=FLAT)

        # Eventos
        bt_atualiza.configure(
            command=lambda rec=recente: self.__aviso_aguarde_instalando(rec))
        bt_cancela.configure(
            command=lambda event=None: self.__tp_atualizacao.destroy())

        # Posicionamento de itens
        fr_atualizaca.grid_columnconfigure(1, weight=1)
        fr_botoes.grid_columnconfigure(1, weight=1)
        fr_botoes.grid_columnconfigure(2, weight=1)
        fr_atualizaca.grid(row=1, column=1, sticky=NSEW)
        lb_versao_dev.grid(row=1, column=1)
        lb_versao_tex.grid(row=2, column=1, sticky=NSEW)
        fr_botoes.grid(row=3, column=1, sticky=NSEW)
        bt_cancela.grid(row=1, column=1)
        bt_atualiza.grid(row=1, column=2)

        # Posicionando a tela
        j_width = self.__tp_atualizacao.winfo_reqwidth()
        j_height = self.__tp_atualizacao.winfo_reqheight()
        t_width = self.master.winfo_screenwidth()
        t_heigth = self.master.winfo_screenheight()

        self.__tp_atualizacao.geometry("+{}+{}".format(
            int(t_width / 2) - int(j_width / 2),
            int(t_heigth / 2) - int(j_height / 2)))
        self.__tp_atualizacao.deiconify()
        self.__tp_atualizacao.update()

    def __aviso_aguarde_instalando(self, recente):
        """ Realizando a atualização """

        if self.__tp_atualizacao is not None:
            self.__tp_atualizacao.destroy()

        self.__tp_atualizacao = Toplevel(None)
        self.__tp_atualizacao.withdraw()
        self.__tp_atualizacao.focus_force()
        self.__tp_atualizacao.resizable(False, False)
        self.__tp_atualizacao.tk.call('wm', 'iconphoto',
                                      self.__tp_atualizacao._w, self.icon)
        self.__tp_atualizacao.configure(
            self.design.dic["aviso_versao_top_level"])
        self.__tp_atualizacao.grid_columnconfigure(1, weight=1)
        self.__tp_atualizacao.title('Atualizando.... Não feche a Safira!')

        fr_atualizaca = Frame(self.__tp_atualizacao)
        lb_versao_dev = Label(fr_atualizaca,
                              text='{:^30}'.format('Aguarde Atualizando!'))
        lb_versao_tex = Message(fr_atualizaca, text=' ' * 50, width=200)
        fr_botoes = Frame(fr_atualizaca)
        bt_atualiza = Button(fr_botoes)

        fr_atualizaca.configure(self.design.dic["aviso_versao_fr_atualizacao"])
        lb_versao_dev.configure(self.design.dic["aviso_versao_lb_dev"])
        lb_versao_tex.configure(self.design.dic["aviso_versao_ms"])
        fr_botoes.configure(self.design.dic["aviso_versao_btn"])
        bt_atualiza.configure(self.design.dic["aviso_versao_btn_atualiza"],
                              relief=FLAT)

        fr_atualizaca.grid_columnconfigure(1, weight=1)
        fr_botoes.grid_columnconfigure(1, weight=1)
        fr_botoes.grid_columnconfigure(2, weight=1)
        fr_atualizaca.grid(row=1, column=1, sticky=NSEW)
        lb_versao_dev.grid(row=1, column=1)
        lb_versao_tex.grid(row=2, column=1, sticky=NSEW)
        fr_botoes.grid(row=3, column=1, sticky=NSEW)

        j_width = self.__tp_atualizacao.winfo_reqwidth()
        j_height = self.__tp_atualizacao.winfo_reqheight()
        t_width = self.master.winfo_screenwidth()
        t_heigth = self.master.winfo_screenheight()

        self.__tp_atualizacao.geometry("+{}+{}".format(
            int(t_width / 2) - int(j_width / 2),
            int(t_heigth / 2) - int(j_height / 2)))
        self.__tp_atualizacao.deiconify()
        self.__tp_atualizacao.update()

        th = Thread(
            target=lambda ver=recente, lb=lb_versao_tex, bt_at=bt_atualiza,
            lb_2=lb_versao_dev: self.__aplica_versao(ver, lb, bt_at, lb_2))
        th.start()

    def __log(self, label, texto):
        label['text'] = label['text'] + '\n{}'.format(texto)

    def __aplica_versao(self, versao: str, lb_versao_tex: object,
                        bt_atualiza: object(), lb_versao_dev):
        """Baixa, faz o download e atualiza a Safira"""

        self.__log(lb_versao_tex, "Baixando Versão {}".format(versao))

        atualizar = self.__up.baixar_versao(versao)
        sucesso, msg, arquivo = atualizar

        # Baixou com sucesso
        if sucesso:
            self.__log(lb_versao_tex, msg)
            self.__log(lb_versao_tex,
                       "Extraindo: {}".format(self.__up.dest_download))

            # Extraiu com sucesso
            sucesso, msg = self.__up.extrair_versao(arquivo)
            if sucesso:
                self.__log(lb_versao_tex, msg)
                self.__log(lb_versao_tex, "Fazendo Backup")

                # Backup da versão atual
                sucesso_bkup, msg_bpk = self.__up.fazer_backup_versao()
                if sucesso_bkup:
                    self.__log(lb_versao_tex, msg_bpk)
                    self.__log(lb_versao_tex, "Atualizando Versão")

                    # Atualizar a versão
                    sucesso_atualizar, msg_atualizar = self.__up.atualizar_arquivos(
                        versao)
                    if sucesso_atualizar:
                        self.__log(lb_versao_tex, msg_atualizar)
                        self.__log(lb_versao_tex, "Sucesso!")

                        lb_versao_dev.configure(
                            text='{:^30}'.format('Atualizado com sucesso!'),
                            fg='green')
                        self.__tp_atualizacao.title('Safira Atualizada!')

                    else:
                        self.__log(lb_versao_tex, msg_atualizar)
                        self.__log(lb_versao_tex, "\nRestaurando")

                        sucesso_restaurar, msg_restaurar = self.__up.restaurar_versao(
                        )

                        self.__log(lb_versao_tex, sucesso_restaurar[1])
                        lb_versao_dev.configure(text='{:^30}'.format(
                            sucesso_restaurar[1]),
                                                fg='orange')
                        self.__tp_atualizacao.title('Safira Não Atualizada!')

                else:
                    self.__log(lb_versao_tex, msg_bpk)

                    lb_versao_dev.configure(
                        text='{:^30}'.format('Erro ao fazer Backup'),
                        fg='orange')
                    self.__tp_atualizacao.title('Safira Não Atualizada!')

            else:
                self.__log(lb_versao_tex, msg)

                lb_versao_dev.configure(
                    text='{:^30}'.format('Erro ao Extrair os arquivos'),
                    fg='orange')
                self.__tp_atualizacao.title('Safira Não Atualizada!')

        else:
            self.__log(lb_versao_tex, msg)

            lb_versao_dev.configure(
                text='{:^30}'.format('Erro ao fazer Baixar Safira'),
                fg='orange')
            self.__tp_atualizacao.title('Safira Não Atualizada!')

        bt_atualiza.configure(command=lambda event=None: self.__fechar_tudo())

        bt_atualiza['text'] = 'Reinicie a Safira!'
        bt_atualiza.grid(row=1, column=2)

    def __fechar_tudo(self):
        self.master.destroy()

    def __abrir_site(self, url: str):
        self.__tp_atualizacao.destroy()

        th = Thread(target=lambda url=url: webbrowser_open(url))
        th.start()

    def __aviso_versao_atualizada(self):
        self.__tp_atualizacao = Toplevel(
            self.master, self.design.dic["aviso_versao_tp_atualizada"])
        self.__tp_atualizacao.withdraw()
        self.__tp_atualizacao.focus_force()
        self.__tp_atualizacao.resizable(False, False)
        self.__tp_atualizacao.tk.call('wm', 'iconphoto',
                                      self.__tp_atualizacao._w, self.icon)
        self.__tp_atualizacao.grid_columnconfigure(1, weight=1)

        j_width = self.__tp_atualizacao.winfo_reqwidth()
        j_height = self.__tp_atualizacao.winfo_reqheight()
        t_width = self.master.winfo_screenwidth()
        t_heigth = self.master.winfo_screenheight()

        self.__tp_atualizacao.title(
            self.interface_idioma["titulo_aviso_atualizado"][self.idioma])

        fr_atualizaca = Frame(self.__tp_atualizacao)
        lb_versao_dev = Label(
            fr_atualizaca,
            text=self.interface_idioma["atualizado_versao_ultima"][
                self.idioma])
        lb_versao_tex = Message(
            fr_atualizaca,
            text='{}'.format(
                self.interface_idioma["texto_atualizado"][self.idioma]).format(
                    self.versao_safira),
            relief=FLAT)
        fr_botoes = Frame(fr_atualizaca)
        bt_cancela = Button(
            fr_botoes,
            text=self.interface_idioma["texto_nao_quero"][self.idioma],
            relief=FLAT)
        bt_facebook = Button(
            fr_botoes,
            self.design.dic["aviso_versao_bt_facebook_atualizada"],
            text=self.interface_idioma["atualizado_facebook"][self.idioma],
            relief=FLAT)
        bt_blogger_ = Button(
            fr_botoes,
            self.design.dic["aviso_versao_bt_blog_atualizada"],
            text=self.interface_idioma["atualizado_blog"][self.idioma],
            relief=FLAT)

        # Configurações de desingn
        fr_atualizaca.configure(self.design.dic["aviso_versao_fr_atualizacao"])
        lb_versao_dev.configure(self.design.dic["aviso_versao_lb_dev"])
        lb_versao_tex.configure(self.design.dic["aviso_versao_ms"])
        fr_botoes.configure(self.design.dic["aviso_versao_btn"])
        bt_cancela.configure(self.design.dic["aviso_versao_btn_cancela"],
                             relief=FLAT)

        bt_cancela.configure(
            command=lambda event=None: self.__tp_atualizacao.destroy())
        bt_facebook.configure(command=lambda event=None: self.__abrir_site(
            "https://www.facebook.com/safiralang/"))
        bt_blogger_.configure(command=lambda event=None: self.__abrir_site(
            "https://safiralang.blogspot.com/"))

        fr_atualizaca.grid_columnconfigure(1, weight=1)
        fr_botoes.grid_columnconfigure(1, weight=1)
        fr_botoes.grid_columnconfigure(2, weight=1)
        fr_botoes.grid_columnconfigure(3, weight=1)

        fr_atualizaca.grid(row=1, column=1, sticky=NSEW)
        lb_versao_dev.grid(row=1, column=1)
        lb_versao_tex.grid(row=2, column=1, sticky=NSEW)
        fr_botoes.grid(row=3, column=1, sticky=NSEW)
        bt_cancela.grid(row=1, column=1)
        bt_facebook.grid(row=1, column=2)
        bt_blogger_.grid(row=1, column=3)

        x, y = int(t_width / 2) - int(j_width / 2), int(t_heigth / 2) - int(
            j_height / 2)

        self.__tp_atualizacao.geometry("+{}+{}".format(x, y))
        self.__tp_atualizacao.update()
        self.__tp_atualizacao.deiconify()
class Deposit_window:
    def start_deposit_window(self, home_screen, account_id, username):
        self.account_id = account_id
        self.deposit_window = Toplevel(home_screen)
        self.deposit_window.geometry('400x125')
        self.deposit_window.title('Deposit [{}]'.format(username))

        self.temp_deposit_value = StringVar()

        #Labels
        details_label = Label(self.deposit_window,
                              text='How much do you want to deposit?',
                              font=('Calibri', 20))
        details_label.grid(row=0, column=0, sticky='N')

        amount_lable = Label(self.deposit_window,
                             text='Amount',
                             font=('Calibri', 16))
        amount_lable.grid(row=1, column=0, sticky='W')

        #hidden label
        self.hidden_label = Label(self.deposit_window, font=('Calibri', 12))
        self.hidden_label.grid(row=4, sticky='N')

        #Entries
        self.deposit_entry = Entry(self.deposit_window,
                                   textvariable=self.temp_deposit_value)
        self.deposit_entry.grid(row=1, column=0)

        #Buttons
        ok_button = Button(self.deposit_window,
                           text='Ok',
                           font=('Calibri', 16),
                           width=10,
                           command=lambda: self.start_deposit())
        ok_button.grid(row=2, column=0, sticky='E')

        go_back_button = Button(self.deposit_window,
                                text='Go back',
                                font=('Calibri', 16),
                                width=10,
                                command=lambda: self.deposit_window.destroy())
        go_back_button.grid(row=2, column=0, sticky='W', padx=5)
        #Note to self, add function to close all windows on logout

    def start_deposit(self):
        amount = self.temp_deposit_value.get()
        if (self.check_user_input(amount)):
            self.finish_deposit(amount)

    def finish_deposit(self, amount):
        Bank_system().deposit(self.account_id, amount)
        self.deposit_entry.delete(0, 'end')
        self.deposit_window.geometry('400x150')
        self.hidden_label.config(fg='green',
                                 text='The deposit was successfully made')
        #Note to self, add function to check if the deposit was succesful

    def check_user_input(self, amount):
        lower_bound = '150'
        horozontal_bound = '400'
        if (" " in amount):
            self.deposit_window.geometry('{}x{}'.format(
                horozontal_bound, lower_bound))
            self.hidden_label.config(fg='red', text='Spaces are not allowed')
            return False
        elif (amount == ''):
            self.deposit_window.geometry('{}x{}'.format(
                horozontal_bound, lower_bound))
            self.hidden_label.config(fg='red', text='Please enter the amount')
            return False
        elif (not (amount.isdecimal())):
            self.deposit_window.geometry('{}x{}'.format(
                horozontal_bound, lower_bound))
            self.hidden_label.config(
                fg='red', text='The ammount has to be given in numbers')
            return False
        else:
            self.deposit_window.geometry('{}x{}'.format(
                horozontal_bound, lower_bound))
            self.hidden_label.config(fg='red', text='')
            return True
    def ask_for_detection_options(self):

        window = Toplevel(self.root)
        window.wm_title("Detection options")
        window.resizable(width=False, height=False)
        window.geometry('{}x{}'.format(300, 650))
        window.attributes('-topmost', True)

        label1 = Label(window, text="Choose detection methods?")
        label1.grid(row=0, sticky=W)
        tmp = 0
        for i, (key, value) in enumerate(self.detection_methods.items()):
            c = Checkbutton(window,
                            text=key,
                            variable=value,
                            onvalue=1,
                            offvalue=0)
            c.grid(row=i + 1, sticky=W)
            tmp = i + 1

        Label(window, text="HOG-SVM winStride min:").grid(row=tmp + 1,
                                                          sticky=W)
        Label(window, text="HOG-SVM winStride max:").grid(row=tmp + 2,
                                                          sticky=W)
        e1 = Entry(window)
        e2 = Entry(window)
        e1.insert(5, self.winStride[0])
        e2.insert(5, self.winStride[1])
        e1.grid(row=tmp + 1, column=1)
        e2.grid(row=tmp + 2, column=1)

        Label(window, text="HOG-SVM roi_padding min:").grid(row=tmp + 3,
                                                            sticky=W)
        Label(window, text="HOG-SVM roi_padding max:").grid(row=tmp + 4,
                                                            sticky=W)
        e3 = Entry(window)
        e4 = Entry(window)
        e3.insert(5, self.roi_padding[0])
        e4.insert(5, self.roi_padding[1])
        e3.grid(row=tmp + 3, column=1)
        e4.grid(row=tmp + 4, column=1)

        Label(window, text="HOG-SVM pyramid_scale (>1.00):").grid(row=tmp + 5,
                                                                  sticky=W)
        e5 = Entry(window)
        e5.insert(5, self.pyramid_scale)
        e5.grid(row=tmp + 5, column=1)

        Label(window, text="Haar Cascade min size x:").grid(row=tmp + 7,
                                                            sticky=W)
        Label(window, text="Haar Cascade min size y:").grid(row=tmp + 8,
                                                            sticky=W)
        e7 = Entry(window)
        e8 = Entry(window)
        e7.insert(5, self.haar_min_size[0])
        e8.insert(5, self.haar_min_size[1])
        e7.grid(row=tmp + 7, column=1)
        e8.grid(row=tmp + 8, column=1)

        Label(window, text="Haar Cascade max size x:").grid(row=tmp + 9,
                                                            sticky=W)
        Label(window, text="Haar Cascade max size y:").grid(row=tmp + 10,
                                                            sticky=W)
        e11 = Entry(window)
        e12 = Entry(window)
        e11.insert(5, self.haar_max_size[0])
        e12.insert(5, self.haar_max_size[1])
        e11.grid(row=tmp + 9, column=1)
        e12.grid(row=tmp + 10, column=1)

        Label(window,
              text="Haar Cascade scale_factor (>1.00):").grid(row=tmp + 11,
                                                              sticky=W)
        e9 = Entry(window)
        e9.insert(5, self.haar_scale_factor)
        e9.grid(row=tmp + 11, column=1)

        Label(window, text="Haar Cascade min_neighbors:").grid(row=tmp + 12,
                                                               sticky=W)
        e10 = Entry(window)
        e10.insert(5, self.haar_min_neighbors)
        e10.grid(row=tmp + 12, column=1)

        btn1 = Button(
            window,
            text="Set",
            command=lambda *args: self.set_detection_methods(
                window, e1.get(), e2.get(), e3.get(), e4.get(), e5.get(),
                e9.get(), e10.get(), e7.get(), e8.get(), e11.get(), e12.get()))
        btn1.grid(row=tmp + 13)

        self.root.wait_window(window)
Esempio n. 51
0
class HILConfigDialog:
    def __init__(self, parent):

        self.top = Toplevel(parent)
        self.top.resizable(width=False, height=False)
        self.top.wm_title("HIL Config")
        self.parent = parent
        x_pos = self.parent.parent.winfo_x() + 250
        y_pos = self.parent.parent.winfo_y() + 250

        self.top.geometry("%dx%d%+d%+d" % (230, 50, x_pos, y_pos))

        device_lbl = tk.Label(self.top, text="HIL Device")
        device_lbl.grid(row=0, column=0)

        self.device_cb = tk.ttk.Combobox(
            self.top,
            values=["HIL 402", "HIL 602", "HIL 602+", "HIL 603", "HIL 604"])
        self.device_cb.current(self.device_cb["values"].index(
            self.parent.device))

        self.device_cb.bind("<<ComboboxSelected>>",
                            self.on_device_cb_selection_changed)
        self.device_cb.grid(row=0, column=1)

        config_lbl = tk.Label(self.top, text="Configuration")
        config_lbl.grid(row=1, column=0)
        self.config_cb = tk.ttk.Combobox(self.top)
        self.on_device_cb_selection_changed(None)
        self.config_cb.current(self.config_cb["values"].index(
            self.parent.configuration_id))

        self.config_cb.bind("<<ComboboxSelected>>",
                            self.on_config_cb_selection_changed)
        self.config_cb.grid(row=1, column=1)

    def on_device_cb_selection_changed(self, event):

        configs_list = ["1", "2", "3", "4"]
        self.parent.device = self.device_cb.get()
        if self.device_cb.get() == "HIL 402":
            configs_list.append("5")
            configs_list.append("6")
            self.config_cb["values"] = configs_list
        elif self.device_cb.get() == "HIL 602":
            self.config_cb["values"] = configs_list
        elif self.device_cb.get() == "HIL 602+":
            configs_list.append("5")
            self.config_cb["values"] = configs_list
        elif self.device_cb.get() == "HIL 603":
            configs_list.append("5")
            self.config_cb["values"] = configs_list
        elif self.device_cb.get() == "HIL 604":
            configs_list.append("5")
            self.config_cb["values"] = configs_list
        if self.parent.configuration_id not in configs_list:
            self.config_cb.current(0)
            self.parent.configuration_id = self.config_cb.get()

    def on_config_cb_selection_changed(self, event):
        self.parent.configuration_id = self.config_cb.get()
    def onViewClient(self):
        def refreshAccountList():
            account_list.set(value=[name for name in self.clients.client_dict])

        def onOpenFile():
            old_path = new_directory.get()
            dir_path = filedialog.askdirectory(
                initialdir=self.clients.meta_save_path, title="請選擇要報告輸出的資料夾")
            new_directory.set(dir_path if dir_path != '' else old_path)

        def editClient(new=True, old_name=None):
            def onProcessClientData():
                name = new_name.get()
                exchange = new_exchange.get()
                api_key = new_api_key.get()
                api_secret = new_api_secret.get()
                query_str = new_query_list.get()
                ## Check name
                try:
                    for s in name:
                        if s in "~!@#$%^&*()+-*/<>,.[]\/":
                            msg.set('Error: ' + "名稱勿含特殊符號")
                            return
                    for s in query_str:
                        if s in "~!@#$%^&*()+-*/<>.[]\/":
                            msg.set('Error: ' + 'Query List勿含除了","以外的特殊符號')
                            return
                    if len(name) > 15:
                        msg.set('Error: ' + '名稱勿超過15字')
                    elif name in self.clients.client_dict and new:
                        msg.set('Error: ' + '名字勿重複')
                    elif not len(api_key) or not len(api_secret) or not len(
                            name) or not len(exchange):
                        msg.set('Error: ' + "請輸入名稱、金錀或交易所")
                    elif exchange not in ['binance', 'ftx']:
                        msg.set('Error: ' + "目前交易所僅支援 binance 和 ftx")
                    else:
                        ## Add client to config
                        specialChars = " \n!\"#$%^&*()"
                        for specialChar in specialChars:
                            query_str = query_str.replace(specialChar, '')
                        client_data = {
                            'api_key': api_key,
                            'api_secret': api_secret,
                            'query_list': query_str.upper().split(','),
                            'exchange': exchange
                        }
                        if new:
                            client_data['index'] = self.clients.count
                            self.clients.count += 1
                            self.clients.process_client_data(name, client_data)
                            refreshAccountList()
                            messagebox.showinfo('Welcome', '成功增加帳戶 %s!' % name)
                        else:
                            self.clients.client_dict[name].info.setinfo(
                                client_data)
                            messagebox.showinfo('Welcome', '成功修改帳戶 %s!' % name)
                        self.clients.save_client_config(CONFIG_FILENAME)
                        window_add_client.destroy()

                except Exception as e:
                    msg.set('Error')
                    print(e)

            window_add_client = Toplevel(self.app)
            window_add_client.title("編輯您的帳戶資訊")
            window_add_client.geometry('400x300')
            try:
                window_add_client.iconphoto(
                    False, PhotoImage(file='icon/doge_icon.png'))
            except:
                pass
            setUIToCenter(window_add_client, 400, 300)
            new_name = StringVar()
            new_name.set('binance_Name')
            Label(window_add_client,
                  text='User name: ').place(x=10,
                                            y=10)  # 將`User name:`放置在座標(10,10)。
            entry_new_name = Entry(window_add_client,
                                   textvariable=new_name,
                                   width=35)  # 建立一個註冊名的`entry`,變數為`new_name`
            entry_new_name.place(x=130, y=10)  # `entry`放置在座標(150,10).

            new_exchange = StringVar()
            new_exchange.set('binance')
            Label(window_add_client, text='Exchange: ').place(x=10, y=50)
            entry_new_exchange = Entry(window_add_client,
                                       textvariable=new_exchange,
                                       width=35)
            entry_new_exchange.place(x=130, y=50)

            new_api_key = StringVar()
            Label(window_add_client, text='API key: ').place(x=10, y=90)
            entry_usr_api_key = Entry(window_add_client,
                                      textvariable=new_api_key,
                                      width=35)
            entry_usr_api_key.place(x=130, y=90)

            new_api_secret = StringVar()
            Label(window_add_client, text='Secret key: ').place(x=10, y=130)
            Entry(window_add_client, textvariable=new_api_secret, width=35) \
            .place(x=130, y=130)

            new_query_list = StringVar()
            new_query_list.set("ETH, BTC")
            Label(window_add_client, text='Query list: ').place(x=10, y=170)
            Entry(window_add_client, textvariable=new_query_list, width=35) \
            .place(x=130, y=170)

            msg = StringVar()
            Label(window_add_client, textvariable=msg, fg='red').place(x=20,
                                                                       y=210)
            btn_comfirm_sign_up = Button(window_add_client,
                                         text='確認',
                                         command=onProcessClientData)
            btn_comfirm_sign_up.place(x=180, y=250)

            if not new:
                entry_new_name['state'] = 'disabled'
                info = self.clients.client_dict[old_name].info
                new_name.set(old_name)
                new_exchange.set(info.exchange)
                new_api_key.set(info.api_key)
                new_api_secret.set(info.api_secret)
                new_query_list.set(','.join(info.query_list))

        def onImportClient():
            file_path = filedialog.askopenfile(
                initialdir=self.clients.meta_save_path,
                title="請選擇要匯入的key.txt").name
            self.clients.init_client_from_key(file_path, CONFIG_FILENAME)
            refreshAccountList()
            new_directory.set(self.clients.meta_save_path)

        def onEditClient():
            index = accountListBox.curselection()
            if len(index) == 0: return
            old_name = accountListBox.get(index)
            editClient(new=False, old_name=old_name)

        def onDeleteClient():
            index = accountListBox.curselection()
            if len(index) == 0: return
            name = accountListBox.get(index)
            self.clients.delete_client(name)
            refreshAccountList()

        def onViewConfirm():
            self.clients.owner = new_name.get()
            self.clients.meta_save_path = new_directory.get()
            self.clients.save_client_config(CONFIG_FILENAME)
            close()

        def close():
            self.app.deiconify()
            window_view_client.destroy()

        self.app.withdraw()
        window_view_client = Toplevel(self.app)
        window_view_client.title("Edit your infomation")
        window_view_client.geometry('400x300')
        window_view_client.resizable(0, 0)
        try:
            window_view_client.iconphoto(False,
                                         PhotoImage(file='icon/eth_icon.png'))
        except:
            pass
        window_view_client.protocol("WM_DELETE_WINDOW", close)
        setUIToCenter(window_view_client, 400, 300)

        new_name = StringVar()
        new_name.set(self.clients.owner)
        Label(window_view_client, text='英文名稱: ').place(x=10, y=10, height=25)
        Entry(window_view_client, textvariable=new_name,
              width=35).place(x=70, y=10, height=25)

        new_directory = StringVar()
        new_directory.set(self.clients.meta_save_path)
        Label(window_view_client, text='儲存目錄: ').place(x=10, y=40, height=25)
        Entry(window_view_client, textvariable=new_directory,
              width=35).place(x=70, y=40, height=25)
        Button(window_view_client, text='瀏覽目錄', command=onOpenFile, width=EDIT_CLIENT_BUTTON_WIDTH) \
        .place(x=330, y=40, height=25)

        Button(window_view_client, text='增加帳戶', command=lambda: editClient(new = True), width=EDIT_CLIENT_BUTTON_WIDTH) \
        .place(x=330, y=70, height=25)

        account_list = StringVar()
        account_list.set(value=[name for name in self.clients.client_dict])
        accountListBox = Listbox(window_view_client,
                                 listvariable=account_list,
                                 width=44,
                                 height=14)
        accountListBox.place(x=10, y=70)

        Button(window_view_client, text='編輯帳戶', command=onEditClient, width=EDIT_CLIENT_BUTTON_WIDTH) \
        .place(x=330, y=100, height=25)

        Button(window_view_client, text='匯入帳戶', command=onImportClient, width=EDIT_CLIENT_BUTTON_WIDTH) \
        .place(x=330, y=130, height=25)

        Button(window_view_client, text='刪除帳戶', command=onDeleteClient, width=EDIT_CLIENT_BUTTON_WIDTH) \
        .place(x=330, y=160, height=25)

        Button(window_view_client, text='確認', command=onViewConfirm, width=EDIT_CLIENT_BUTTON_WIDTH) \
        .place(x=330, y=270, height=25)
def connectdb():
    def submitdb():
        global con, mycursor
        host = hostval.get()
        user = userval.get()
        password = passwdval.get()

        try:
            con = pymysql.connect(host=host, user=user, password=password)
            mycursor = con.cursor()
        except:
            messagebox.showerror('Notification',
                                 'Data is incorrect pls try again')
            return
        try:
            strr = 'create database studentmanagementsystem'
            mycursor.execute(strr)
            strr = 'use studentmanagementsystem'
            mycursor.execute(strr)
            strr = 'create table studentdata(id int,name varchar(20),mobile varchar(12),email varchar(30),address varchar(100),gender varchar(50),dob varchar(50),date varchar(50),time varchar(50))'
            mycursor.execute(strr)
            strr = 'alter table studentdata modify column id int not null'
            mycursor.execute(strr)
            strr = 'alter table studentdata modify column id int primary key'
            mycursor.execute(strr)
            messagebox.showinfo(
                'Notification',
                'database connected and now you are connected to the database...',
                parent=dbroot)
        except:
            strr = 'use studentmanagementsystem'
            mycursor.execute(strr)
            messagebox.showinfo('Notification',
                                'Now you are connected to the database...',
                                parent=dbroot)
        dbroot.destroy()

    dbroot = Toplevel()
    dbroot.grab_set()
    dbroot.resizable(False, False)
    dbroot.config(bg="lightblue")
    dbroot.geometry('470x250+450+230')

    # ===================================
    hostlabel = Label(dbroot,
                      text="Enter host:",
                      bg="lightgreen",
                      anchor='w',
                      font=('arial', 15, 'bold'),
                      relief=GROOVE,
                      borderwidth=3,
                      width=12)
    hostlabel.place(x=10, y=10)
    userlabel = Label(dbroot,
                      text="Enter User:"******"lightgreen",
                      anchor='w',
                      font=('arial', 15, 'bold'),
                      relief=GROOVE,
                      borderwidth=3,
                      width=12)
    userlabel.place(x=10, y=70)
    passwdlabel = Label(dbroot,
                        text="Enter Passwd:",
                        bg="lightgreen",
                        anchor='w',
                        font=('arial', 15, 'bold'),
                        relief=GROOVE,
                        borderwidth=3,
                        width=12)
    passwdlabel.place(x=10, y=130)
    # ===========================================================
    hostval = StringVar()
    userval = StringVar()
    passwdval = StringVar()

    hostentry = Entry(dbroot,
                      font=('roman', 15, 'bold'),
                      bd=2,
                      bg="lightgreen",
                      textvariable=hostval)
    hostentry.place(x=200, y=10)
    userentry = Entry(dbroot,
                      font=('roman', 15, 'bold'),
                      bd=2,
                      bg="lightgreen",
                      textvariable=userval)
    userentry.place(x=200, y=70)
    passwdentry = Entry(dbroot,
                        font=('roman', 15, 'bold'),
                        bd=2,
                        bg="lightgreen",
                        textvariable=passwdval)
    passwdentry.place(x=200, y=130)

    dbbutton = Button(dbroot,
                      text="Submit",
                      bg='red',
                      font=('roman', 15, 'bold'),
                      width=20,
                      activebackground="blue",
                      activeforeground="white",
                      command=submitdb)
    dbbutton.place(x=150, y=200)

    dbroot.mainloop()
Esempio n. 54
0
class Controlador:

    def setVista(self, vista):
        """ Define la vista que será controlada """
        self.vista = vista
        self.recurso = None

    def cargarurl(self):
        """
            Método encargado de llamar al método cargarInfo en un
             hilo distinto
         """
        self.vista.button.config(state=DISABLED)
        self.vista.bvideo.config(state=DISABLED)
        self.vista.baudio.config(state=DISABLED)
        self.vista.bborrar.config(state=DISABLED)

        if platform.system() == 'Windows':
            self.vista.config(cursor="wait")

        if "facebook" in self.vista.url.get():
            self.t = threading.Thread(target=self.cargarFB)
            self.t.start()
        else:
            try:
                self.recursoPL = pafy.get_playlist(self.vista.url.get())
                self.t = threading.Thread(target=self.cargarPlayList)
                self.t.start()
            except ValueError as e:
                try:
                    self.recurso = pafy.new(self.vista.url.get())
                    self.t = threading.Thread(target=self.cargarInfo)
                    self.t.start()
                except ValueError as e:
                    mensaje = "La url es inválida o no se encuentra conectado "
                    mensaje += "a internet, intentelo nuevamente."
                    msg.showerror("Error", mensaje)
                    self.vista.button.config(state=NORMAL)
                    self.vista.bvideo.config(state=NORMAL)
                    self.vista.baudio.config(state=NORMAL)
                    self.vista.bborrar.config(state=NORMAL)
                    self.vista.config(cursor="")

    def cargarInfo(self):
        self.vista.notebook.select(self.vista.tab1)
        """ Método encargado de obtener información dela url ingresada """
        info = ""
        info += "■Título: " + self.recurso.title+"\n"
        info += "■Duración: " + self.recurso.duration+"\n"
        info += "■Autor: " + self.recurso.author+"\n"

        try:
            info += "■Categoría: " + self.recurso.category+"\n"
        except:
            info += "■Categoría: No disponible\n"
            pass

        info += "■Likes: " + str(self.recurso.likes)+"\n"
        info += "■Dislikes: " + str(self.recurso.dislikes)+"\n"
        mejor = self.recurso.getbest()
        info += "■Mejor resolución: " + mejor.resolution+"\n"
        info += "■Mejor formato: " + mejor.extension
        if self.recurso.bigthumb != '':
            response = requests.get(self.recurso.bigthumb)
            img_data = response.content
            img = ImageTk.PhotoImage(opp(BytesIO(img_data)))
            self.vista.imagen.config(text="", image=img)
            self.vista.imagen.image = img

        self.vista.text.config(state=NORMAL)
        self.vista.text.delete(1.0, END)
        self.vista.text.insert(INSERT, info)
        self.vista.text.config(state=DISABLED)
        self.cargarLista()
        self.vista.button.config(state=NORMAL)
        self.vista.bvideo.config(state=NORMAL)
        self.vista.baudio.config(state=NORMAL)
        self.vista.bborrar.config(state=NORMAL)
        self.vista.config(cursor="")

    def cargarLista(self):
        """
            Método encargado de obtener los formatos disponibles del
            video que se busca
        """

        self.streams = self.recurso.streams
        self.vista.listbox.delete(0, END)
        i = 0
        texto_a_insertar = "{}) Resolución: {}, Extensión: {}, Tamaño: {}"
        for s in self.streams:
            i += 1
            tamanio = str("%.2f MB." % (s.get_filesize()/(1024**2)))
            self.vista.listbox.insert(END, texto_a_insertar.format(
                i, s.resolution, s.extension, tamanio))

    def descargaVideo(self):
        """
            Método encargado de llamar al método __descargaVideo, 
            según lo seleccionado por el usuario además que
            se ejecuta en un hilo distinto    
        """
        index = self.vista.listbox.curselection()
        if len(index) > 0:
            self.seleccion = self.streams[index[0]]
            self.size = self.seleccion.get_filesize()
            self.mostrarDialogo()
            t = threading.Thread(target=self.__descargarVideo)
            t.start()

            self.vista.button.config(state=DISABLED)
            self.vista.bvideo.config(state=DISABLED)
            self.vista.baudio.config(state=DISABLED)
            self.vista.bborrar.config(state=DISABLED)
        else:
            msg.showerror("Error", "Se debe seleccionar un video de la lista.")

    def __descargarVideo(self):
        """ Método que descarga el video seleccionado y muestra la carga """
        self.d = True
        try:
            file = self.seleccion.download(
                quiet=True, filepath=self.vista.path.get(),
                callback=self.callback)

        except Exception as e:
            raise e
            msg.showerror("Error", "El archivo ya existe.")

        self.top.destroy()
        self.d = False
        msg.showinfo("Mensaje", "Archivo descargado correctamente")
        self.vista.text.config(state=NORMAL)
        self.vista.text.delete(1.0, END)
        self.vista.text.config(state=DISABLED)
        self.vista.listbox.delete(0, END)
        self.vista.url.set("")
        self.vista.imagen.config(text="No disponible", image='')
        self.vista.imagen.image = ''
        self.vista.button.config(state=NORMAL)
        self.vista.bvideo.config(state=NORMAL)
        self.vista.baudio.config(state=NORMAL)
        self.vista.bborrar.config(state=NORMAL)
        self.vista.config(cursor="")

    def descargaAudio(self):
        """
            Método encargado de llamar al método __descargaAudio, 
            que descarga la mejor resolución de audio, además que
            se ejecuta en un hilo distinto    
        """
        if self.recurso != None:
            t = threading.Thread(target=self.__descargaAudio)
            t.start()
            self.vista.button.config(state=DISABLED)
            self.vista.bvideo.config(state=DISABLED)
            self.vista.baudio.config(state=DISABLED)
            self.vista.bborrar.config(state=DISABLED)
            self.mostrarDialogo()

    def __descargaAudio(self):
        """ Método que descarga el video seleccionado y muestra la carga """
        self.bestaudio = self.recurso.getbestaudio(preftype='m4a')
        if self.bestaudio != None:
            self.d = True
            self.fileaudio = self.bestaudio.title+".m4a"
            self.size = self.bestaudio.get_filesize()
            try:
                self.bestaudio.download(
                    quiet=True, callback=self.callback,
                    filepath=self.vista.path.get())

                msg.showinfo("Mensaje", "Archivo descargado correctamente.")

            except Exception as e:
                msg.showerror("Error", "El archivo ya existe.")

        self.top.destroy()
        self.d = False
        self.vista.text.config(state=NORMAL)
        self.vista.text.delete(1.0, END)
        self.vista.text.config(state=DISABLED)
        self.vista.listbox.delete(0, END)
        self.vista.url.set("")
        self.vista.imagen.config(text="No disponible", image='')
        self.vista.imagen.image = ''
        self.vista.button.config(state=NORMAL)
        self.vista.bvideo.config(state=NORMAL)
        self.vista.baudio.config(state=NORMAL)
        self.vista.bborrar.config(state=NORMAL)
        self.vista.config(cursor="")

    def mostrarDialogo(self):
        """ Método que muestra la GUI de descarga del archivo """
        self.top = Toplevel(self.vista)
        self.top.resizable(0, 0)
        geometry = "400x250+"
        geometry += str(int(self.vista.ancho/2)-150)+"+"
        geometry += str(int(self.vista.alto/2)-50)
        self.top.geometry(geometry)
        self.top.title("Descarga en progreso...")
        self.top.iconbitmap('descarga.ico')
        self.progress = IntVar()
        self.progress.set(0)
        self.progressbar = ttk.Progressbar(self.top, variable=self.progress)
        self.label = ttk.Label(self.top, text="Descargando: ", font=("Arial", 14))
        self.label.place(x=5, y=15)
        self.label2 = ttk.Label(self.top, text="Tiempo restante: ", font=("Arial", 14))
        self.label2.place(x=5, y=65)
        self.label3 = ttk.Label(self.top, text="Velocidad: ", font=("Arial", 14))
        self.label3.place(x=5, y=115)
        
        self.progressbar.place(x=30, y=160, width=320)
        if platform.system() == 'Windows':
            self.vista.config(cursor="wait")

        self.bcancelar = ttk.Button(self.top, text="cancelar", command=self.cancelar)
        self.bcancelar.place(x=150,y=200)
        self.top.transient(self.vista)
        self.top.config(bg="#4C4C4D")

    def iniciar(self):
        """ Método que muestra la GUI """
        self.vista.mainloop()

    def cancelar(self):
        pass

    def borrarurl(self):
        """ Método borra la url ingresada """
        self.vista.url.set("")

    def callback(self, total, recvd, ratio, rate, eta):
        """ Método que controla la descarga del archivo """
        carga = int(ratio*100)
        self.progressbar.step(carga - self.progress.get())
        self.progress.set(carga)
        self.label.config(text="Descarga: "+str(carga)+" %")
        self.label2.config(text="Tiempo restante: "+str("%.0f" % (eta))+" segundos")
        self.label3.config(text="Velocidad: "+str("%.2f" % (rate/1024))+" Mb/s")
        

    def cambiaPath(self):
        """ Método para cambiar la carpeta destino """
        path = filedialog.askdirectory()
        if path != None and path != '':
            self.vista.path.set(path)

    def copia(self, event):
        """ Método que pega la url del portapapeles """
        self.vista.url.set(self.vista.clipboard_get())

    def cargarPlayList(self):
        self.vista.notebook.select(self.vista.tabPL)
        self.disponibles = self.recursoPL['items']
        self.vista.listPL.delete(0, END)
        i = 0
        texto_a_insertar = "{}) Título: {}, Duración: {}"
        for s in self.disponibles:
            i += 1
            insertar = texto_a_insertar.format(i, s['pafy'].title[:40]+"...", s['pafy'].duration)
            try:
                self.vista.listPL.insert(END,insertar)
            except TclError as e:
                pass

        self.vista.button.config(state=NORMAL)
        self.vista.bvideo.config(state=NORMAL)
        self.vista.baudio.config(state=NORMAL)
        self.vista.bborrar.config(state=NORMAL)
        self.vista.config(cursor="")

    def cargarInfoDesdePL(self):

        index = self.vista.listPL.curselection()

        if len(index) > 0:

            if platform.system() == 'Windows':
                self.vista.config(cursor="wait")

            self.recurso = self.recursoPL['items'][index[0]]['pafy']
            self.vista.button.config(state=DISABLED)
            self.vista.bvideo.config(state=DISABLED)
            self.vista.baudio.config(state=DISABLED)
            self.vista.bborrar.config(state=DISABLED)
            self.t = threading.Thread(target=self.cargarInfo)
            self.t.start()

        else:
            msg.showerror("Error", "Se debe seleccionar un video de la lista.")

    def cargarFB(self):

        try:
            rpta = msg.askyesno("Pregunta", "No se puede obtener información "+
                "de un video de facebook, desea continuar con la descarga?")

            if rpta:
                path = filedialog.asksaveasfilename()
                os.popen("facebook-dl.py {} hd {}".format(self.vista.url.get(),path))
                msg.showinfo("Mensaje", "Archivo descargado correctamente.")
                
        except:
            msg.showerror("Error", "El video no es público, o la url es inválida.")

        self.vista.button.config(state=NORMAL)
        self.vista.bvideo.config(state=NORMAL)
        self.vista.baudio.config(state=NORMAL)
        self.vista.bborrar.config(state=NORMAL)
        self.vista.config(cursor="")
        
Esempio n. 55
0
def toplevel (geometry='350x200',title='', is_center=True): # we adde tkinter Tk for this
    f= Toplevel()
    f.geometry(geometry)
    f.title(title) # لاضافة العنوان عن طريق نفس سطر الجيومتري نعرفه فوق في الجيومتري وهنا
    if is_center:tkcenter(f)
    return f
Esempio n. 56
0
class Task(Frame):  # pylint: disable=too-many-ancestors
    WORKING = 1
    RESTING = 0
    # needs to be 1000 so display update intervals are consistent when
    # resting
    CHK_INT = 95  # milliseconds

    # keyed by sys.platform or "default" to return a method that checks
    # for mouse/keyboard activity
    activity_dispatch = {}

    def __init__(self, master=None, work=WORK_TM, rest=REST_TM, debug=0):
        """create the task widget and get things started"""

        # various inits
        self.log = logging.getLogger(__name__)
        self.mouse_pos = None
        self.old_work = 0.0
        self.then = 0
        self.state = self.WORKING
        self.cancel_rest = 0
        self.resttext = ""
        self.mouse_counts = 0
        self.lid_state = "open"
        self.lid_time = time.time()
        self.interrupt_count = 0

        Frame.__init__(*(self, master))

        self.style = StringVar()
        self.style.set("fascist")  # or "friendly"

        # create main interactor window
        self.workmeter = Meter(self, background="grey50")
        self.workmeter.pack()

        f1 = Frame(self)
        f1.pack()
        Label(f1, text="Work time:").pack(side=LEFT)
        self.work_scl = Scale(f1,
                              orient=HORIZONTAL,
                              from_=1,
                              to=max(45, work),
                              command=self.reset_duration)
        self.work_scl.set(work)
        self.work_scl.pack(side=LEFT)

        f2 = Frame(self)
        f2.pack()
        Label(f2, text="Rest time:").pack(side=LEFT)
        self.rest_scl = Scale(f2,
                              orient=HORIZONTAL,
                              from_=1,
                              to=max(15, rest),
                              command=self.reset_duration)
        self.rest_scl.set(rest)
        self.rest_scl.pack(side=LEFT)

        f3 = Frame(self)
        f3.pack()
        dictator = Radiobutton(f3,
                               text="Fascist",
                               variable=self.style,
                               value="fascist")
        friend = Radiobutton(f3,
                             text="Friendly",
                             variable=self.style,
                             value="friendly")
        dictator.pack(side=LEFT)
        friend.pack(side=LEFT)

        f4 = Frame(self)
        f4.pack()
        restb = Button(f4, text="Rest", command=self.rest)
        restb.pack(side=LEFT)
        stop = Button(f4, text="Quit", command=self.quit)
        stop.pack(side=LEFT)
        help_ = Button(f4, text="Help", command=self.help_)
        help_.pack(side=LEFT)

        # create the cover window
        self.cover = Toplevel(background="black")
        self.cover.withdraw()
        # user can't resize it
        self.cover.resizable(0, 0)
        (w, h) = (self.winfo_screenwidth(), self.winfo_screenheight())
        if debug:
            # just a small window when debugging
            (w, h) = (w // 8, h // 8)
        self.cover.geometry("%dx%d+0+0" % (w, h))

        # and it's undecorated
        self.cover.overrideredirect(1)

        # cover contains a frame with rest message and meter
        f = Frame(self.cover, background="black")
        self.restnote = Label(f, background="black", foreground="white")
        self.restmeter = Meter(f, background="grey50", height=10, width=200)
        self.restnote.pack(pady=2)
        self.restmeter.pack(fill="x", expand=1, pady=2)
        self.cancel_button = Button(f, text="Cancel Rest", command=self.cancel)
        f.pack()

        # initialize interrupt information
        self.interrupt_time = time.time()
        self.interrupts = self.get_interrupts()

        self.bgcolor = self["background"]

        # start the ball rolling
        self.work()
        self.check_interval = self.CHK_INT
        self.after(self.check_interval, self.tick)

    def reset_duration(self, _dummy):
        """reset work/rest interval lengths to current scale values"""
        wtime = self.work_scl.get()
        self.workmeter.set_range(self.workmeter.min,
                                 self.workmeter.min + wtime * 60)
        self.restmeter.set_range(self.restmeter.min,
                                 self.restmeter.min + self.rest_scl.get() * 60)
        # only time the user can fiddle the work/rest meters is during
        # the work phase, so the only scale change that matters for extending
        # or contracting the end of the interval is the work scale
        if self.old_work:
            delta = wtime - self.old_work
        else:
            delta = 0
        self.then += delta * 60
        self.old_work = wtime

    #uncomment for Python 1.4
    #def winfo_pointerxy(self):
    #   return self._getints(self.tk.call('winfo', 'pointerxy', self._w))

    def which_state(self):
        if self.state == self.WORKING:
            return "working"
        return "resting"

    def work(self):
        """start the work period"""
        self.reset_warning()
        self.restmeter.reset()
        self.state = self.WORKING
        now = time.time()
        self.then = now + self.work_scl.get() * 60
        self.workmeter.set_range(now, self.then)
        self.workmeter.set(now)
        self.cover.withdraw()

        self.log.debug(
            __("work: state: {} now: {} then: {}", self.which_state(),
               hhmm(now), hhmm(self.then)))

    def warn_work_end(self):
        """alert user that work period is almost up"""
        self.set_background("yellow")

    def reset_warning(self):
        """back to plain old grey bg"""
        self.set_background(self.bgcolor)

    def set_background(self, color):
        for w in (self, self.work_scl, self.rest_scl, self.dictator,
                  self.friend, self.button_frame, self.stopb, self.restb,
                  self.helpb, self.work_frame, self.rest_frame,
                  self.radio_frame, self.work_label, self.rest_label,
                  self.meter_label, self.meter_frame):
            w["background"] = color

    def rest(self):
        """overlay the screen with a window, preventing typing"""
        self.cancel_rest = 0
        self.workmeter.reset()
        self.state = self.RESTING
        now = time.time()
        self.then = now + self.rest_scl.get() * 60
        self.cover.deiconify()
        self.cover.tkraise()
        self.resttext = ("Rest for %dm00s please..." % self.rest_scl.get())
        self.restnote.configure(text=self.resttext)
        self.restmeter.set_range(now, self.then)
        self.restmeter.set(now)
        if self.style.get() == "friendly":
            self.cancel_button.pack(pady=2)
        else:
            self.cancel_button.pack_forget()

        self.log.debug(
            __("rest: state: {} now: {} then: {}", self.which_state(),
               hhmm(now), hhmm(self.then)))

    def help_(self):
        d = simpledialog.SimpleDialog(self.master,
                                      text=usageText(),
                                      buttons=["Done"],
                                      default=0,
                                      title="Help")
        d.go()

    def get_interrupts(self):
        """get mouse/keyboard activity info

        where possible, call platform-dependent routine to get mouse and
        keyboard info, otherwise, just return mouse info

        in all cases, the value returned should be a value that increases
        monotonically with activity
        """
        count = (self.activity_dispatch.get(sys.platform)
                 or self.activity_dispatch["default"])(self)
        self.log.debug(__("interrupts: {}", count))
        return count

    def get_mouseinfo(self):
        if self.lid_state == "closed":
            return self.mouse_counts
        ptr_xy = self.winfo_pointerxy()
        if self.mouse_pos is None:
            self.mouse_pos = ptr_xy
        mouse_pos = ptr_xy
        if mouse_pos != self.mouse_pos:
            self.mouse_pos = mouse_pos
            self.mouse_counts += 1
        return self.mouse_counts

    activity_dispatch["default"] = get_mouseinfo

    def get_linux_interrupts(self):
        if self.lid_state == "closed":
            return self.interrupt_count
        count = 0
        # Can't seem to find mouse interrupts, so for now, just watch
        # keyboard and mix add get_mouseinfo() output as a substitute for
        # mouse interrupts.
        for line in open("/proc/interrupts"):
            fields = line.split()
            if fields[0] == "1:":
                count = sum(int(fields[n]) for n in range(1, 8))
                self.interrupt_count = count
                break
        return self.interrupt_count + self.get_mouseinfo()

    activity_dispatch["linux"] = get_linux_interrupts

    def check_lid_state(self):
        if os.path.exists(LID_STATE):
            for line in open(LID_STATE):
                fields = line.strip().split()
                if fields[0] == "state:":
                    state = fields[1]
                    if state != self.lid_state:
                        self.log.debug(__("lid state changed: {}", state))
                        self.lid_state = state
                        self.lid_time = time.time()

    def tick(self):
        """perform periodic checks for activity or state switch"""
        # check for mouse or keyboard activity
        now = time.time()
        self.check_lid_state()
        interrupts = self.get_interrupts()
        if interrupts > self.interrupts:
            self.interrupt_time = now
            self.interrupts = interrupts

            self.log.debug(
                __("tick (1): state: {} now: {} then: {}", self.which_state(),
                   hhmm(now), hhmm(self.then)))

        if self.state == self.RESTING:
            # if there is an input interrupt since the start of the rest
            # interval extend the interval by 10 seconds
            if self.interrupt_time > self.restmeter.min:
                self.then = self.then + 10
                self.restmeter.set_range(self.restmeter.min, self.then)
                self.restmeter.set(now)
                self.interrupt_time = self.restmeter.min

                self.log.debug(
                    __("tick (2): state: {} start: {}"
                       " now: {} then: {}", self.which_state(),
                       hhmm(self.restmeter.min), hhmm(now), hhmm(self.then)))

            if self.cancel_rest or now > self.then:
                self.state = self.WORKING
                self.work()
            else:
                self.cover.tkraise()

                # update message to reflect rest time remaining
                timeleft = int(self.then - now)
                minleft = timeleft / 60
                secleft = timeleft % 60
                self.resttext = ("Rest for %dm%02ds please..." %
                                 (minleft, secleft))
                self.log.debug(self.resttext)
                self.restnote.configure(text=self.resttext)

                self.log.debug(__("tick (4): state: {}", self.which_state()))

        else:
            # if it's been at least the length of the rest interval
            # since new interrupt, reset the work interval
            if self.interrupt_time + self.rest_scl.get() * 60 < now:
                self.work()

            if self.interrupt_time < now:
                # work interval can extend for long periods of time during
                # idle periods, so back off on the check interval to a
                # maximum of once every five seconds as long as there is no
                # activity
                self.check_interval = int(min(self.check_interval * 1.3, 5000))
            else:
                self.check_interval = self.CHK_INT

            if now > self.then:
                # work period expired
                self.state = self.RESTING
                # reset the check interval since we may have extended it
                # during the just ending work interval
                self.check_interval = self.CHK_INT
                self.rest()
            elif now + 60 > self.then:
                # work period nearly expired - warn user
                self.warn_work_end()

        self.restmeter.set(now)
        self.workmeter.set(now)
        self.after(self.check_interval, self.tick)

    def cancel(self):
        self.cancel_rest = 1
Esempio n. 57
0
def update():
    updatebook = Toplevel(window)
    updatebook.title("Update Book")
    updatebook.geometry("400x100")
    u1 = Label(updatebook, text="Edit Book Details Using ID: ").pack()
    u2 = Label(updatebook, text="").pack()
    search = StringVar()
    edit = Entry(updatebook, textvariable=search)
    edit.pack()
    u3 = Label(updatebook, text="").pack()

    def edit1():
        editbook = Toplevel(updatebook)
        editbook.title("EDIT")
        editbook.geometry("450x300")
        bl1 = Label(editbook, text="EDIT RECORD")
        bl1.pack()
        bl2 = Label(editbook, text="")
        bl2.pack()
        bl3 = Label(editbook, text="Enter Book Name: ")
        bl3.pack()
        name = StringVar()
        author = StringVar()
        year = StringVar()
        e1 = Entry(editbook, textvariable=name)
        e1.pack()
        bl4 = Label(editbook, text="")
        bl4.pack()
        bl5 = Label(editbook, text="Enter Author's Name: ")
        bl5.pack()
        e2 = Entry(editbook, textvariable=author)
        e2.pack()
        bl6 = Label(editbook, text="")
        bl6.pack()
        bl7 = Label(editbook, text="Enter Year: ")
        bl7.pack()
        e3 = Entry(editbook, textvariable=year)
        e3.pack()

        def exe():
            l = (name.get(), author.get(), year.get(), search.get())
            insert = "UPDATE BOOK SET BOOK_NAME = %s,AUTHOR = %s,YEAR = %s WHERE ID = %s"
            cur.execute(insert, l)
            mydb.commit()

        def destroy():
            editbook.destroy()
            updatebook.destroy()
            master = Tk()
            w = Message(master, text="Records Have Been Updated!!!")
            w.pack()
            mainloop()

        bl8 = Label(editbook, text="")
        bl8.pack()
        b4 = Button(editbook,
                    text="UPDATE",
                    command=combine_funcs(exe, destroy))
        b4.pack()
        editbook.mainloop()

    bu1 = Button(updatebook, text="Edit", command=edit1)
    bu1.pack()
    bl9 = Label(updatebook, text="")
    bl9.pack()
    updatebook.mainloop()
Esempio n. 58
0
def add():
    addbook = Toplevel(window)
    addbook.title("Add Book")
    addbook.geometry("300x360")
    a1 = Label(addbook, text="Please Enter Book Details: ")
    a1.pack()
    a2 = Label(addbook, text="")
    a2.pack()
    name = StringVar()
    author = StringVar()
    isbn = StringVar()
    year = StringVar()
    a3 = Label(addbook, text="Name Of The Book: ")
    a3.pack()
    a = Entry(addbook, textvariable=name)
    a.pack()
    a4 = Label(addbook, text="")
    a4.pack()
    a5 = Label(addbook, text="Author: ")
    a5.pack()
    b = Entry(addbook, textvariable=author)
    b.pack()
    a6 = Label(addbook, text="")
    a6.pack()
    a7 = Label(addbook, text="ISBN:")
    a7.pack()
    c = Entry(addbook, textvariable=isbn)
    c.pack()
    a8 = Label(addbook, text="")
    a8.pack()
    a9 = Label(addbook, text="Year Of Publishment:")
    a9.pack()
    d = Entry(addbook, textvariable=year)
    d.pack()
    a10 = Label(addbook, text="")
    a10.pack()

    def submit():
        name1 = name.get()
        author1 = author.get()
        year1 = year.get()
        isbn1 = isbn.get()
        l = (name1, author1, isbn1, year1)
        insert = "INSERT INTO BOOK (Book_Name,Author,ISBN,Year) VALUES(%s, %s, %s, %s)"
        cur.execute(insert, l)
        mydb.commit()

    def clear():
        a.delete(0, END)
        b.delete(0, END)
        c.delete(0, END)
        d.delete(0, END)

    def adddestroy():
        addbook.destroy()

    ab1 = Button(addbook,
                 text="ADD BOOK",
                 command=combine_funcs(submit, clear))
    ab1.pack()
    a11 = Label(addbook, text="")
    a11.pack()
    ab2 = Button(addbook, text="EXIT", command=adddestroy)
    ab2.pack()
    a12 = Label(addbook, text="")
    a12.pack()
    addbook.mainloop()
Esempio n. 59
0
def consultation_help(window):

    """

    Gives three options of Framingham heart failure risk, depression diagnostics and COVID-19 diagnostics.

    Arguments:
        window where the function roots
        entries in each function

    Returns:
        messagebox (COVID checker)
        label update (Framingham heart failure risk, depression diagnostics)

    """

    # sets up the window and fonts
    root = Toplevel(window)
    root.geometry("350x520")
    root.title('Consultation help tools')
    fontStyle2 = tkFont.Font(family="Lucida Grande", size=13)

    def f_calc():

        """
        Opens a window with 14 checkboxes for the symptoms, user chooses and then runs the calculate_hf_risk to return
        the label with positive/negative heart failure diagnosis

        Arguments:
            local scope variables: major1-major8, minor1-minor6 (integer 0/1 variables)

        Returns:
            label indicating positive/ negative HF diagnosis
        """

        # destroys the previous grid (instead of new window opening)
        f_calc_button.destroy()
        COVID_calc_button.destroy()
        depress_calc_button.destroy()

        # criteria saved as major, integer variables
        Label(root, text="Major Criteria", font=fontStyle2, pady=10).grid(row=0, column=0)
        major1 = IntVar()
        c = Checkbutton(root, text="Acute Pulmonary edema", variable=major1)
        c.grid(row=1, column=0, sticky=W)
        major2 = IntVar()
        c = Checkbutton(root, text="Cardiomegaly", variable=major2)
        c.grid(row=2, column=0, sticky=W)
        major3 = IntVar()
        c = Checkbutton(root, text="Hepatojugular reflux", variable=major3)
        c.grid(row=3, column=0, sticky=W)
        major4 = IntVar()
        c = Checkbutton(root, text="Neck vein distention", variable=major4)
        c.grid(row=4, column=0, sticky=W)
        major5 = IntVar()
        c = Checkbutton(root, text="Paroxysmal nocturnal dyspnea or orthopnea", variable=major5)
        c.grid(row=5, column=0, sticky=W)
        major6 = IntVar()
        c = Checkbutton(root, text="Pulmonary rales", variable=major6)
        c.grid(row=6, column=0, sticky=W)
        major7 = IntVar()
        c = Checkbutton(root, text="Third heart sound", variable=major7)
        c.grid(row=7, column=0, sticky=W)
        major8 = IntVar()
        c = Checkbutton(root, text="Weight loss >4.5kg in 5 days in response to treatment", variable=major8)
        c.grid(row=8, column=0, sticky=W)

        # criteria saved as minor, integer variables
        Label(root, text="Minor Criteria", font=fontStyle2, pady=10).grid(row=9, column=0)
        minor1 = IntVar()
        c = Checkbutton(root, text="Ankle Edema", variable=minor1)
        c.grid(row=10, column=0, sticky=W)
        minor2 = IntVar()
        c = Checkbutton(root, text="Dyspnea on exertion", variable=minor2)
        c.grid(row=11, column=0, sticky=W)
        minor3 = IntVar()
        c = Checkbutton(root, text="Hepatomegaly", variable=minor3)
        c.grid(row=12, column=0, sticky=W)
        minor4 = IntVar()
        c = Checkbutton(root, text="Nocturnal Cough", variable=minor4)
        c.grid(row=13, column=0, sticky=W)
        minor5 = IntVar()
        c = Checkbutton(root, text="Pleural effusion", variable=minor5)
        c.grid(row=14, column=0, sticky=W)
        minor6 = IntVar()
        c = Checkbutton(root, text="Tachycardia (HR>120)", variable=minor6)
        c.grid(row=15, column=0, sticky=W, pady=(0, 10))

        # submits the checkbox information (major + minor variables) into calculate_hf_risk function
        submit_button = Button(root, text="Evaluate heart failure diagnosis", command=lambda: calculate_hf_risk(minor1,
                                                                                                                minor2,
                                                                                                                minor3,
                                                                                                                minor4,
                                                                                                                minor5,
                                                                                                                minor6,
                                                                                                                major1,
                                                                                                                major2,
                                                                                                                major3,
                                                                                                                major4,
                                                                                                                major5,
                                                                                                                major6,
                                                                                                                major7,
                                                                                                                major8,
                                                                                                                major8))
        submit_button.grid(row=16, column=0)

        # returns back to the help tools selection
        return_button = Button(root, text='Return', command=lambda: (root.destroy(), consultation_help(window)))
        return_button.place(relx=0.9, rely=0.05, anchor=CENTER)

    # Takes IntVariables, converts into 0/1, sums up and calculates the full score, updates label with diagnosis
    def calculate_hf_risk(*args):
        minor = 0
        major = 0

        for i in range(6):
            minor += args[i].get()      # adds up the 0/1 to a final minor score
        for i in range(6, 14):
            major += args[i].get()      # adds up the 0/1 to a final major score

        if major >= 2 or (major == 1 and minor >= 2):       # criterion for positive diagnostics
            label = Label(root, text="Positive for Heart Failure", font=fontStyle2)
            label.grid(row=21, column=0)
            logger.info("HF diagnosis evaluated")
        else:
            label = Label(root, text="Negative for Heart Failure", font=fontStyle2)
            label.grid(row=21, column=0)
            logger.info("HF diagnosis evaluated")

    def depress_calc():

        """
        Opens a window with 8 checkboxes for the symptoms, user chooses and then runs the calculate_depressionrisk to
        return the label with positive/negative depression diagnosis

        Arguments:
            local scope variables: major1-major2, minor1-minor6 (integer 0/1 variables)

        Returns:
            label indicating positive/ negative depression diagnosis
        """

        root.geometry("320x370")

        # destroys the previous grid (instead of new window opening)
        f_calc_button.destroy()
        COVID_calc_button.destroy()
        depress_calc_button.destroy()

        # criteria saved as major, integer variables
        Label(root, text="Major criteria (past 2 weeks)", font=fontStyle2, pady=10).grid(row=0, column=0)
        major1 = IntVar()
        Checkbutton(root, text="Depressed mood most of the day", variable=major1).grid(row=1, column=0, sticky=W)
        major2 = IntVar()
        Checkbutton(root, text="Loss of interest or pleasure", variable=major2).grid(row=2, column=0, sticky=W)

        # criteria saved as minor, integer variables
        Label(root, text="Minor Criteria (past 2 weeks)", font=fontStyle2, pady=10).grid(row=9, column=0)
        minor1 = IntVar()
        Checkbutton(root, text="Significant weight loss/weight gain", variable=minor1).grid(row=10, column=0, sticky=W)
        minor2 = IntVar()
        Checkbutton(root, text="Slowing down of thought/physical movement", variable=minor2).grid(
            row=11, column=0, sticky=W)
        minor3 = IntVar()
        Checkbutton(root, text="Fatigue", variable=minor3).grid(row=12, column=0, sticky=W)
        minor4 = IntVar()
        Checkbutton(root, text="Feeling of worthlessness/guilt", variable=minor4).grid(row=13, column=0, sticky=W)
        minor5 = IntVar()
        Checkbutton(root, text="Diminished ability to think", variable=minor5).grid(row=14, column=0, sticky=W)
        minor6 = IntVar()
        Checkbutton(root, text="Suicidal ideation", variable=minor6).grid(row=15, column=0, sticky=W, pady=(0, 10))

        # submits the checkbox information (major + minor variables) into calculate_depressionrisk function
        Button(root, text="Evaluate depression diagnosis",
               command=lambda: calculate_depressrisk(minor1, minor2, minor3, minor4, minor5, minor6,
                                                     major1, major2)).grid(row=16, column=0)

        # returns back to the help tools selection
        return_button = Button(root, text='Return', command=lambda: (root.destroy(), consultation_help(window)))
        return_button.place(relx=0.9, rely=0.05, anchor=CENTER)

    # Takes IntVariables, converts into 0/1, sums up and calculates the full score, updates label with diagnosis
    def calculate_depressrisk(*args):
        minor = 0
        major = 0

        for i in range(6):
            minor += args[i].get()      # adds up the 0/1 to a final minor score
        for i in range(6, 8):
            major += args[i].get()      # adds up the 0/1 to a final minor score
        if ((major == 1) and (minor >= 4)) or ((major == 2) and (minor >= 3)):      # criteria for positive diagnosis
            Label(root, text="Positive diagnosis of clinical depression", font=fontStyle2).grid(row=21, column=0)
            logger.info("Depression diagnosis evaluated")
        else:
            Label(root, text="Negative diagnosis of clinical depression", font=fontStyle2).grid(row=21, column=0)
            logger.info("Depression diagnosis evaluated")

    def check_covid(root):

        """
        Opens a window with 5 checkboxes for the symptoms, user chooses and then runs the covid_submit to return the
        messagebox with COVID-19 positive or negative symptoms.

        Arguments:
            window where check_covid originates
            local scope variables: var1-var5 (integer 0/1 variables indicating presence of COVID symptoms)

        Returns:
            messagebox with recommendation to take a test/ stay alert
        """

        # sets up the window
        window = Toplevel(root)
        window.title('COVID symptoms')
        window.geometry('340x220')
        fontStyle2 = tkFont.Font(family="Lucida Grande", size=16)
        Label(window, text="Check what applies to the patient:", font=fontStyle2, pady=10).grid(row=0, column=0)

        # introduces the variables and checkboxes, IntVar = integer variable of 0/1 based on being checked/unchecked
        var1 = IntVar()
        c = Checkbutton(window, text="New persistent cough", variable=var1)
        c.grid(row=1, column=0, sticky=W)
        var2 = IntVar()
        c = Checkbutton(window, text="Loss of smell", variable=var2)
        c.grid(row=2, column=0, sticky=W)
        var3 = IntVar()
        c = Checkbutton(window, text="Loss of taste", variable=var3)
        c.grid(row=3, column=0, sticky=W)
        var4 = IntVar()
        c = Checkbutton(window, text="High temperature", variable=var4)
        c.grid(row=4, column=0, sticky=W)
        var5 = IntVar()
        c = Checkbutton(window, text="They had contact with COVID-19 positive person", variable=var5)
        c.grid(row=5, column=0, sticky=W, pady=(0, 10))

        # submit button that calls the covid_submit function with all the IntVariables above + destroys the window
        submit_button = Button(window, text="Submit",
                               command=lambda: (covid_submit(var1, var2, var3, var4, var5), window.destroy()))
        submit_button.grid(row=16, column=0)

        window.mainloop()

    # Takes IntVariables, converts into 0/1, sums up and calculates the full score, raises a messagebox of
    # symptom indication
    def covid_submit(*args):
        full_score = 0
        for i in range(5):
            full_score += args[i].get()     # adds up the 0/1 to a final score
        if full_score >= 1:     # checking any box indicates that the person should get tested
            messagebox.showinfo("COVID-19", "Patient is likely to have COVID-19. Please, sign them up for a test: "
                                            "https://www.gov.uk/get-coronavirus-test.")
            logger.info("COVID diagnosis evaluated")
        else:
            messagebox.showinfo("COVID-19", "At the moment they do not have indications of COVID-19.")
            logger.info("COVID diagnosis evaluated")

    # helper tools buttons selection
    f_calc_button = Button(root, text="Calculate Framingham score", command=f_calc)
    f_calc_button.place(relx=0.5, rely=0.4, anchor=CENTER)
    COVID_calc_button = Button(root, text='Check COVID symptoms', command=lambda: check_covid(root))
    COVID_calc_button.place(relx=0.5, rely=0.5, anchor=CENTER)
    depress_calc_button = depress_calc_button = Button(root, text="Check depression symptoms", command=depress_calc)
    depress_calc_button.place(relx=0.5, rely=0.6, anchor=CENTER)

    root.mainloop()
def searchstudent():
    def searchadd():
        id = idval.get()
        name = nameval.get()
        mobile = mobileval.get()
        email = emailval.get()
        address = addressval.get()
        gender = genderval.get()
        dob = dobval.get()
        addeddate = time.strftime("%d/%m/%Y")
        if id != '':
            strr = 'select *from studentdata where id=%s'
            mycursor.execute(strr, (id))
            datas = mycursor.fetchall()
            studenttable.delete(*studenttable.get_children())
            for i in datas:
                vv = [i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]]
                studenttable.insert('', END, values=vv)
        elif name != '':
            strr = 'select *from studentdata where name=%s'
            mycursor.execute(strr, (name))
            datas = mycursor.fetchall()
            studenttable.delete(*studenttable.get_children())
            for i in datas:
                vv = [i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]]
                studenttable.insert('', END, values=vv)
        elif mobile != '':
            strr = 'select *from studentdata where mobile=%s'
            mycursor.execute(strr, (mobile))
            datas = mycursor.fetchall()
            studenttable.delete(*studenttable.get_children())
            for i in datas:
                vv = [i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]]
                studenttable.insert('', END, values=vv)
        elif email != '':
            strr = 'select *from studentdata where email=%s'
            mycursor.execute(strr, (email))
            datas = mycursor.fetchall()
            studenttable.delete(*studenttable.get_children())
            for i in datas:
                vv = [i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]]
                studenttable.insert('', END, values=vv)
        elif address != '':
            strr = 'select *from studentdata where address=%s'
            mycursor.execute(strr, (address))
            datas = mycursor.fetchall()
            studenttable.delete(*studenttable.get_children())
            for i in datas:
                vv = [i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]]
                studenttable.insert('', END, values=vv)
        elif gender != '':
            strr = 'select *from studentdata where gender=%s'
            mycursor.execute(strr, (gender))
            datas = mycursor.fetchall()
            studenttable.delete(*studenttable.get_children())
            for i in datas:
                vv = [i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]]
                studenttable.insert('', END, values=vv)
        elif dob != '':
            strr = 'select *from studentdata where dob=%s'
            mycursor.execute(strr, (dob))
            datas = mycursor.fetchall()
            studenttable.delete(*studenttable.get_children())
            for i in datas:
                vv = [i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]]
                studenttable.insert('', END, values=vv)
        elif addeddate != '':
            strr = 'select *from studentdata where addeddate=%s'
            mycursor.execute(strr, (addeddate))
            datas = mycursor.fetchall()
            studenttable.delete(*studenttable.get_children())
            for i in datas:
                vv = [i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]]
                studenttable.insert('', END, values=vv)

    searchroot = Toplevel(master=DataEntryFrame)
    searchroot.grab_set()
    searchroot.iconbitmap('max.ico')
    searchroot.geometry('470x540+150+150')
    searchroot.title('Search Student')
    searchroot.title('Search Student')
    searchroot.resizable(False, False)
    searchroot.config(bg='lightblue')
    # =====================================================================================
    idlabel = Label(searchroot,
                    text="Search Id:",
                    bg="lightgreen",
                    anchor='w',
                    font=('arial', 15, 'bold'),
                    relief=GROOVE,
                    borderwidth=3,
                    width=12)
    idlabel.place(x=10, y=10)
    namelabel = Label(searchroot,
                      text="Search Name:",
                      bg="lightgreen",
                      anchor='w',
                      font=('arial', 15, 'bold'),
                      relief=GROOVE,
                      borderwidth=3,
                      width=12)
    namelabel.place(x=10, y=60)
    mobilelabel = Label(searchroot,
                        text="Search Mobile:",
                        bg="lightgreen",
                        anchor='w',
                        font=('arial', 15, 'bold'),
                        relief=GROOVE,
                        borderwidth=3,
                        width=12)
    mobilelabel.place(x=10, y=110)
    emaillabel = Label(searchroot,
                       text="Search Email:",
                       bg="lightgreen",
                       anchor='w',
                       font=('arial', 15, 'bold'),
                       relief=GROOVE,
                       borderwidth=3,
                       width=12)
    emaillabel.place(x=10, y=160)
    addresslabel = Label(searchroot,
                         text="Search Address:",
                         bg="lightgreen",
                         anchor='w',
                         font=('arial', 15, 'bold'),
                         relief=GROOVE,
                         borderwidth=3,
                         width=12)
    addresslabel.place(x=10, y=210)
    genderlabel = Label(searchroot,
                        text="Search Gender:",
                        bg="lightgreen",
                        anchor='w',
                        font=('arial', 15, 'bold'),
                        relief=GROOVE,
                        borderwidth=3,
                        width=12)
    genderlabel.place(x=10, y=260)
    doblabel = Label(searchroot,
                     text="Search D.O.B.:",
                     bg="lightgreen",
                     anchor='w',
                     font=('arial', 15, 'bold'),
                     relief=GROOVE,
                     borderwidth=3,
                     width=12)
    doblabel.place(x=10, y=310)
    datelabel = Label(searchroot,
                      text="Search Date:",
                      bg="lightgreen",
                      anchor='w',
                      font=('arial', 15, 'bold'),
                      relief=GROOVE,
                      borderwidth=3,
                      width=12)
    datelabel.place(x=10, y=370)
    # ==============================================================================================
    idval = StringVar()
    nameval = StringVar()
    mobileval = StringVar()
    emailval = StringVar()
    addressval = StringVar()
    genderval = StringVar()
    dobval = StringVar()
    dateval = StringVar()
    identry = Entry(searchroot,
                    font=('roman', 15, 'bold'),
                    bd=2,
                    bg="lightgreen",
                    textvariable=idval)
    identry.place(x=200, y=10)
    nameentry = Entry(searchroot,
                      font=('roman', 15, 'bold'),
                      bd=2,
                      bg="lightgreen",
                      textvariable=nameval)
    nameentry.place(x=200, y=60)
    mobileentry = Entry(searchroot,
                        font=('roman', 15, 'bold'),
                        bd=2,
                        bg="lightgreen",
                        textvariable=mobileval)
    mobileentry.place(x=200, y=110)
    emailentry = Entry(searchroot,
                       font=('roman', 15, 'bold'),
                       bd=2,
                       bg="lightgreen",
                       textvariable=emailval)
    emailentry.place(x=200, y=160)
    addressentry = Entry(searchroot,
                         font=('roman', 15, 'bold'),
                         bd=2,
                         bg="lightgreen",
                         textvariable=addressval)
    addressentry.place(x=200, y=210)
    genderentry = Entry(searchroot,
                        font=('roman', 15, 'bold'),
                        bd=2,
                        bg="lightgreen",
                        textvariable=genderval)
    genderentry.place(x=200, y=260)
    dobentry = Entry(searchroot,
                     font=('roman', 15, 'bold'),
                     bd=2,
                     bg="lightgreen",
                     textvariable=dobval)
    dobentry.place(x=200, y=310)
    dateentry = Entry(searchroot,
                      font=('roman', 15, 'bold'),
                      bd=2,
                      bg="lightgreen",
                      textvariable=dateval)
    dateentry.place(x=200, y=370)
    searchrootbutton = Button(searchroot,
                              text='Submit',
                              command=searchadd,
                              font=('arial', 20, 'bold'),
                              bg='red',
                              bd=3,
                              activebackground='blue',
                              activeforeground="white")
    searchrootbutton.place(x=150, y=420)
    searchroot.mainloop()