示例#1
0
    def _addNeueMahlzeitFrame(self):
        self.fr_neue_mz = Frame(self.fr_mahlzeit)
        self.fr_neue_mz.grid_rowconfigure(2, weight=1)
        self.fr_neue_mz.grid(row=0, column=1, sticky="WSNE")
        
        lbl_name = Label(self.fr_neue_mz, text="Name:")
        lbl_name.grid(row=0, column=0, sticky="NW")
        
        self.en_name = Entry(self.fr_neue_mz)
        self.en_name.grid(row=0, column=1, columnspan=2, sticky="WNE")
        
        lbl_zutat = Label(self.fr_neue_mz, text="Zutaten:")
        lbl_zutat.grid(row=1, column=0, sticky="NW")
        

        self.lb_zutat = Listbox(self.fr_neue_mz)
        sb_zutat = Scrollbar(self.lb_zutat, orient=VERTICAL)
        self.lb_zutat.configure(yscrollcommand=sb_zutat.set)
        sb_zutat.configure(command=self.lb_zutat.yview)
        sb_zutat.pack(side="right", fill="both")
        self.lb_zutat.grid(row=2, column=0, columnspan=3, sticky="NWSE")
        
        self.var_zutat = StringVar(self.fr_neue_mz)
        
        self.opt_zutat = OptionMenu(self.fr_neue_mz, self.var_zutat, "Auswahl")
        self.opt_zutat.grid(row=3, column=0)
        
        self.en_menge = Entry(self.fr_neue_mz)
        self.en_menge.grid(row=3, column=1)
        
        self.btn_mahlzeit_hinzu = Button(self.fr_neue_mz, text="Hinzu")
        self.btn_mahlzeit_hinzu.grid(row=3, column=2, sticky="E")
示例#2
0
class CimReadme(Toplevel):
    def __init__(self, parent):
        Toplevel.__init__(self, parent)
        self.configure(borderwidth=0)
        self.geometry("+%d+%d" % (
                        parent.winfo_rootx()+30,
                        parent.winfo_rooty()+30))

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

        self.title('README')
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.parent = parent
        self.bind('<Escape>', self.close)

    def close(self, event=None):
        self.destroy()

    def show(parent):
        dlg = CimReadme(parent)
        dlg.lift()
        dlg.focus_set()
示例#3
0
    def __init__(self, parent):
        Notebook.__init__(self, parent, style='Type.TNotebook')
        logger = logging.getLogger(__name__)

        s = Style()
        s.configure('Type.TNotebook', tabposition="se")
        
        self.page_tiborcim = Frame(self)
        self.page_python = Frame(self)
        self.add(self.page_tiborcim, text='Tiborcim')
        self.add(self.page_python, text='Python')

        self.text_tiborcim = CimTiborcimText(self.page_tiborcim, self)

        self.vbar_python = Scrollbar(self.page_python, name='vbar_python')
        self.xbar_python = Scrollbar(self.page_python, name='xbar_python', orient="horizontal")
        self.text_python = Text(self.page_python, wrap="none", state="disabled", borderwidth='0p')
        self.vbar_python['command'] = self.text_python.yview
        self.vbar_python.pack(side="right", fill="y")
        self.text_python['yscrollcommand'] = self.vbar_python.set
        self.xbar_python['command'] = self.text_python.xview
        self.xbar_python.pack(side="bottom", fill="x")
        self.text_python['xscrollcommand'] = self.xbar_python.set
        self.text_python.pack(expand=1, fill="both")

        self.viewmode = "tiborcim"
        self.saved = True
        self.filename = None
示例#4
0
	def __init__(self,parent):
		
		Frame.__init__(self, master=parent)

		canvas = tkinter.Canvas(self, highlightthickness=0)
		self.innerFrame = Frame(canvas)

		myscrollbar = Scrollbar(self, orient="vertical")
		myscrollbar.configure(command=canvas.yview)

		def scrollbarSet(top, bottom):
			# Hides and shows the scroll frame depending on need
			if float(top) > 0 or float(bottom) < 1:
				myscrollbar.grid(row=0, column=1, sticky="NS")
			else:
				pass
				myscrollbar.grid_remove()
			myscrollbar.set(top, bottom)
		canvas.configure(yscrollcommand = scrollbarSet)


		configureFunc = lambda _ :  canvas.configure(scrollregion=canvas.bbox("all"))
		frameID = canvas.create_window((0,0), window=self.innerFrame, anchor='nw')
		self.innerFrame.bind("<Configure>",configureFunc)

		canvas.grid(row=0, column=0, sticky="NSEW")
		myscrollbar.grid(row=0, column=1, sticky="NS")
		self.grid_rowconfigure(0, weight=1)
		self.grid_columnconfigure(0, weight=0)


		#canvas.bind("<Configure>", lambda e : canvas.itemconfig(frameID, width=e.width))
		canvas.bind("<Configure>", lambda e : canvas.configure(width=self.innerFrame.winfo_width()))
示例#5
0
class TextViewer(Toplevel):
    "A simple text viewer dialog for IDLE."

    def __init__(self, parent, title, text, modal=True,
                 _htest=False, _utest=False):
        """Show the given text in a scrollable window with a 'close' button.

        If modal is left True, users cannot interact with other windows
        until the textview window is closed.

        _htest - bool; change box location when running htest.
        _utest - bool; don't wait_window when running unittest.
        """
        Toplevel.__init__(self, parent)
        self.configure(borderwidth=5)
        # Place dialog below parent if running htest.
        self.geometry("=%dx%d+%d+%d" % (750, 500,
                           parent.winfo_rootx() + 10,
                           parent.winfo_rooty() + (10 if not _htest else 100)))
        # TODO: get fg/bg from theme.
        self.bg = '#ffffff'
        self.fg = '#000000'

        self.CreateWidgets()
        self.title(title)
        self.protocol("WM_DELETE_WINDOW", self.Ok)
        self.parent = parent
        self.textView.focus_set()
        # Bind keys for closing this dialog.
        self.bind('<Return>',self.Ok)
        self.bind('<Escape>',self.Ok)
        self.textView.insert(0.0, text)
        self.textView.config(state=DISABLED)

        if modal:
            self.transient(parent)
            self.grab_set()
            if not _utest:
                self.wait_window()

    def CreateWidgets(self):
        "Create Frame with Text (with vertical Scrollbar) and Button."
        frameText = Frame(self, relief=SUNKEN, height=700)
        frameButtons = Frame(self)
        self.buttonOk = Button(frameButtons, text='Close',
                               command=self.Ok, takefocus=FALSE)
        self.scrollbarView = Scrollbar(frameText, orient=VERTICAL,
                                       takefocus=FALSE)
        self.textView = Text(frameText, wrap=WORD, highlightthickness=0,
                             fg=self.fg, bg=self.bg)
        self.scrollbarView.config(command=self.textView.yview)
        self.textView.config(yscrollcommand=self.scrollbarView.set)
        self.buttonOk.pack()
        self.scrollbarView.pack(side=RIGHT,fill=Y)
        self.textView.pack(side=LEFT,expand=TRUE,fill=BOTH)
        frameButtons.pack(side=BOTTOM,fill=X)
        frameText.pack(side=TOP,expand=TRUE,fill=BOTH)

    def Ok(self, event=None):
        self.destroy()
    def create_widgets(self):
        ''' Creates widgets of this object.
        '''
        yScrollbar = Scrollbar(self, orient=VERTICAL)
        yScrollbar.grid(row=2, column=3, sticky=N+S)

        canvas = StyledCanvas(self, height=HEIGHT_WITHOUT_CHECKBOXES,
                              yscrollcommand=yScrollbar.set)
        self.canvas = canvas
        canvas.grid(row=2, column=0, columnspan=3, sticky=N+E+W)

        self._config_columns(self)
        canvas.columnconfigure(0, weight=1)

        if self.add_headers:
            non_discr_lbl = Label(self, text='Non-\ndiscretionary')
            non_discr_lbl.grid(row=0, column=1, padx=3, pady=1)
            weakly_disp_lbl = Label(self, text='Weakly\ndisposable')
            weakly_disp_lbl.grid(row=0, column=2, padx=3, pady=1)
            sep = Separator(self)
            sep.grid(row=1, column=0, columnspan=3, sticky=E+W, pady=10, padx=3)

        self.frame_with_boxes = Frame(canvas)
        self._config_columns(self.frame_with_boxes)
        self.frame_with_boxes.grid(sticky=N+S+W+E, pady=15, padx=3)

        canvas.create_window(0, 0, window=self.frame_with_boxes, anchor=N+W)
        canvas.update_idletasks()

        canvas['scrollregion'] = (0, 0, 0, HEIGHT_WITHOUT_CHECKBOXES)
        yScrollbar['command'] = canvas.yview

        MouseWheel(self).add_scrolling(canvas, yscrollbar=yScrollbar)
示例#7
0
class TextViewer(Toplevel):
    """A simple text viewer dialog for IDLE

    """
    def __init__(self, parent, title, text, modal=True, _htest=False):
        """Show the given text in a scrollable window with a 'close' button

        If modal option set to False, user can interact with other windows,
        otherwise they will be unable to interact with other windows until
        the textview window is closed.

        _htest - bool; change box location when running htest.
        """
        Toplevel.__init__(self, parent)
        self.configure(borderwidth=5)
        # place dialog below parent if running htest
        self.geometry("=%dx%d+%d+%d" % (750, 500,
                           parent.winfo_rootx() + 10,
                           parent.winfo_rooty() + (10 if not _htest else 100)))
        #elguavas - config placeholders til config stuff completed
        self.bg = '#ffffff'
        self.fg = '#000000'

        self.CreateWidgets()
        self.title(title)
        self.protocol("WM_DELETE_WINDOW", self.Ok)
        self.parent = parent
        self.textView.focus_set()
        #key bindings for this dialog
        self.bind('<Return>',self.Ok) #dismiss dialog
        self.bind('<Escape>',self.Ok) #dismiss dialog
        self.textView.insert(0.0, text)
        self.textView.config(state=DISABLED)

        if modal:
            self.transient(parent)
            self.grab_set()
            self.wait_window()

    def CreateWidgets(self):
        frameText = Frame(self, relief=SUNKEN, height=700)
        frameButtons = Frame(self)
        self.buttonOk = Button(frameButtons, text='Close',
                               command=self.Ok, takefocus=FALSE)
        self.scrollbarView = Scrollbar(frameText, orient=VERTICAL,
                                       takefocus=FALSE)
        self.textView = Text(frameText, wrap=WORD, highlightthickness=0,
                             fg=self.fg, bg=self.bg)
        self.scrollbarView.config(command=self.textView.yview)
        self.textView.config(yscrollcommand=self.scrollbarView.set)
        self.buttonOk.pack()
        self.scrollbarView.pack(side=RIGHT,fill=Y)
        self.textView.pack(side=LEFT,expand=TRUE,fill=BOTH)
        frameButtons.pack(side=BOTTOM,fill=X)
        frameText.pack(side=TOP,expand=TRUE,fill=BOTH)

    def Ok(self, event=None):
        self.destroy()
示例#8
0
文件: dialog.py 项目: gokai/tim
class ListDialog(object):
    def __init__ (self, master, items, message, accept_func):
        self.accept_func = accept_func

        self.top = Toplevel(master)
        self.top.transient(master)
        self.top.rowconfigure(0, weight=1)
        self.top.rowconfigure(1, weight=3)
        self.top.rowconfigure(2, weight=0)
        self.top.columnconfigure(0, weight=1)
        self.top.columnconfigure(1, weight=1)
        self.top.resizable(width=True, height=True)

        self.frame = Frame(self.top)
        self.frame.rowconfigure(0, weight=1)
        self.frame.rowconfigure(1, weight=0)
        self.frame.columnconfigure(0, weight=1)
        self.frame.columnconfigure(1, weight=0)
        self.frame.grid(row=0, column=0, sticky=(N, S, W, E), columnspan=2)
        self.canvas = Canvas(self.frame)
        self.canvas.create_text(0, 0, text=message, anchor=NW)
        self.canvas.grid(row=0, column=0, sticky=(N, W, S, E))

        self.vscroll = Scrollbar(self.frame, command=self.canvas.yview)
        self.vscroll.grid(row=0, column=1, sticky=(N, S))
        self.canvas['yscrollcommand'] = self.vscroll.set

        self.hscroll = Scrollbar(self.frame, command=self.canvas.xview, orient=HORIZONTAL)
        self.hscroll.grid(row=1, column=0, sticky=(W, E), columnspan=2)
        self.canvas['xscrollcommand'] = self.hscroll.set

        self.canvas['scrollregion'] = self.canvas.bbox('all')
        self.canvas.bind('<Button-4>', self.scroll)
        self.canvas.bind('<Button-5>', self.scroll)
        self.canvas.bind('<MouseWheel>', self.scroll)

        self.view = NameView(self.top, sorted(items))
        self.view.widget.grid(row=1, column=0, columnspan=2, sticky=(N, W, E, S))

        self.delbutton = Button(self.top, text='Ok', command=self.accept )
        self.cancelbutton = Button(self.top, text='Cancel', command=self.cancel)
        self.delbutton.grid(row=2, column=0)
        self.cancelbutton.grid(row=2, column=1)
        self.view.widget.focus_set()

    def accept(self):
        self.accept_func(self.view.selection())
        self.top.destroy()

    def cancel(self):
        self.result = None
        self.top.destroy()

    def scroll(self, event):
        if event.num == 4 or event.delta > 0:
            self.canvas.yview(SCROLL, -1, UNITS)
        elif event.num == 5 or event.delta < 0:
            self.canvas.yview(SCROLL, 1, UNITS)
示例#9
0
 def progress( self ):
     o=os.popen("cd {0} && snakemake --dryrun --rerun-incomplete > {0}/Reports/checkpoint".format(self.workpath.get()))
     o.close()
     F=open("{0}/Reports/checkpoint".format(self.workpath.get()),"r").read()
     rules2={}
     rules=re.findall(r'rule .+:',F)
     for i in rules:
         i=re.sub("rule ","",i)
         i=re.sub(":","",i)
         rules2[i]=0
 
 
     F=open("{0}/Reports/{1}.dot".format(self.workpath.get(), self.Pipeline.get() ),"r").read()
     for i in rules2.keys():
         F=re.sub(r'('+i+')(\".+?)\".+?\"',r'\1_pending\2"0.0 0.0 0.0"',F)
 #        F=re.sub(i,"",F)
 
 
     G=open("{0}/Reports/{1}-{2}.dot".format(self.workpath.get(),self.Pipeline.get(),"progress"),"w")
     G.write(F)
     G.close()
 
     o=os.popen("cd {0}/Reports && dot -Tpng -o {0}/Reports/{1}-progress.png {0}/Reports/{1}-progress.dot;convert {0}/Reports/{1}-progress.png {0}/Reports/{1}-progress.gif".format(self.workpath.get(),self.Pipeline.get()))
 
 #    tkinter.messagebox.showerror("o",o)
 
     PL=self.Pipeline.get() #pipelineget()
     gf=Toplevel()
 
     gf.title("CCBR Pipeliner: {0} Progress Graph".format(PL))
     cgf = Canvas(gf,bg="white")
 #    gff=Frame(cgf,width=300,height=300)
     xscrollbar = Scrollbar(gf, orient=HORIZONTAL)
     xscrollbar.pack(side = BOTTOM, fill=X )
     xscrollbar.config(command=cgf.xview)
 
     yscrollbar = Scrollbar(gf,orient=VERTICAL)
     yscrollbar.pack(side = RIGHT, fill=Y )
     yscrollbar.config(command=cgf.yview)
 
     cgf.config(xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set)
     cgf.config(width=600,height=600)
     cgf.pack(expand=1,fill=BOTH,side=RIGHT)
     cgf.config(scrollregion=(0,0,1000,5000))
     try:
         time.sleep(5)
         img = PhotoImage(file="{0}/Reports/{1}-progress.gif".format(self.workpath.get(),PL))
     except:
         time.sleep(5)
         img = PhotoImage(file="{0}/Reports/{1}-progress.gif".format(self.workpath.get(),PL))
     cgf.create_image(0,0,image=img, anchor="nw")
     cgf.image=img
示例#10
0
文件: frame.py 项目: aphistic/copilot
class CopilotInnerFrame(CopilotBaseFrame):
    def __init__(self, master, config):
        super(CopilotInnerFrame, self).__init__(master, config)

        if config.full_screen:
            self._make_full(master)

        self.master.grid_rowconfigure(1, weight=1)
        self.master.grid_columnconfigure(1, weight=1)

        self._create_header()

        self._sb = Scrollbar(self._master, orient=VERTICAL)
        self._sb.grid(row=1, column=3, sticky='nse')

        self._next_hidden = False

    def _cmd_back(self):
        self._master.destroy()

    def _create_header(self):
        self.back_btn = Button(
            self._master,
            text='< Back',
            command=self._cmd_back
        )
        self.back_btn.grid(row=0, column=0, sticky='w')

        self._frame_lbl = Label(
            self.master,
            text='',
            anchor='center',
            font=self._config.item_font
        )
        self._frame_lbl.grid(row=0, column=1, sticky='ew')

        self._next_btn = Button(
            self.master,
            text='Next >'
        )
        self._next_btn.grid(row=0, column=2, sticky='e')

    def _hide_next(self):
        if not self._next_hidden:
            self._next_btn.grid_remove()
            self._next_hidden = True

    def _show_next(self):
        if self._next_hidden:
            self._next_btn.grid(row=0, column=2, sticky='e')
            self._next_hidden = False
示例#11
0
文件: tagview.py 项目: gokai/tim
 def __init__(self, master, names):
     self.widget = Frame(master)
     self._tree = Treeview(self.widget, columns='name')
     self._tree.grid(row=0,column=0, sticky=(N,S,W,E))
     self._tree.view = self
     self.widget.columnconfigure(0, weight=1)
     self.widget.rowconfigure(0,weight=1)
     self._tree.column('name', width=50)
     self._tree['show'] = 'tree'
     actions = {'edit': lambda e: self.edit(),
             'search': lambda e: self.search(),
             'focus_next': lambda e: self.focus_next(),
             'focus_prev': lambda e: self.focus_prev(),
             'select': lambda e: self._tree.selection_toggle(self._tree.focus()),
             'clear_selection': lambda e: self._tree.selection_set([])
             }
     kb.make_bindings(kb.tagview, actions, self._tree.bind)
     self._iids = dict()
     self._names = dict()
     logger.debug('Names: %s', names)
     self.widget.focus_set = self._tree.focus_set
     for name in sorted(names):
         iid = self._tree.insert('', 'end', text=name)
         self._names[iid] = name
         self._iids[name] = iid
     self._scroll = Scrollbar(self.widget, command=self._tree.yview)
     self._tree['yscrollcommand'] = self._scroll.set
     self._scroll.grid(row=0, column=1, sticky=(N, S))
     self.widget.columnconfigure(1, weight=0)
    def __init__( self, parentApp, internalBible ):
        """
        Given a collection name, try to open an empty Bible resource collection window.
        """
        if BibleOrgSysGlobals.debugFlag: print( "BibleReferenceCollectionWindow.__init__( {}, {} )".format( parentApp, internalBible.name ) )
        self.parentApp, self.internalBible = parentApp, internalBible
        BibleResourceWindow.__init__( self, self.parentApp, 'BibleReferenceCollectionWindow', internalBible.name )
        #ChildWindow.__init__( self, self.parentApp, 'BibleResource' )
        #self.winType = 'InternalBibleReferenceBox'

        self.geometry( INITIAL_REFERENCE_COLLECTION_SIZE )
        self.minimumSize, self.maximumSize = MINIMUM_REFERENCE_COLLECTION_SIZE, MAXIMUM_REFERENCE_COLLECTION_SIZE
        self.minsize( *parseWindowSize( self.minimumSize ) )
        self.maxsize( *parseWindowSize( self.maximumSize ) )

        # Get rid of the default widgets
        self.vScrollbar.destroy()
        self.textBox.destroy()

        # Make a frame inside a canvas inside our window (in order to get a scrollbar)
        self.canvas = tk.Canvas( self, borderwidth=0, background="#ffffff" )
        self.frame = Frame( self.canvas ) #, background="#ffffff" )
        self.vsb = Scrollbar( self, orient="vertical", command=self.canvas.yview )
        self.canvas.configure( yscrollcommand=self.vsb.set )
        self.vsb.pack( side="right", fill="y" )
        self.canvas.pack( side=tk.LEFT, fill=tk.BOTH, expand=True )
        self.canvas.create_window( (4,4), window=self.frame, anchor="nw", tags="self.frame" )
        self.frame.bind( "<Configure>", self.OnFrameConfigure )

        #self.BCVUpdateType = 'ReferencesMode' # Leave as default
        self.folderPath = self.filename = self.filepath = None
        self.referenceBoxes = BibleReferenceBoxes( self )
示例#13
0
    def __init__( self, parentWindow, filename=None ):
        """
        """
        if BibleOrgSysGlobals.debugFlag and debuggingThisModule:
            print( exp("HTMLWindow.__init__( {}, {} )").format( parentWindow, repr(filename) ) )
            assert( parentWindow )
        self.parentWindow, self.initialFilename = parentWindow, filename
        tk.Toplevel.__init__( self, self.parentWindow )
        ChildBox.__init__( self, self.parentWindow )
        self.protocol( "WM_DELETE_WINDOW", self.closeHTMLWindow )
        self.title( 'HTMLWindow' )
        self.genericWindowType = 'HTMLWindow'
        self.winType = 'HTMLWindow'
        self.moduleID = 'HTML'

        self.geometry( INITIAL_HTML_SIZE )
        self.minimumSize, self.maximumSize = MINIMUM_HTML_SIZE, MAXIMUM_HTML_SIZE
        self.minsize( *parseWindowSize( self.minimumSize ) )
        self.maxsize( *parseWindowSize( self.maximumSize ) )

        self._showStatusBarVar = tk.BooleanVar()
        self._showStatusBarVar.set( True )
        self._statusTextVar = tk.StringVar()
        self._statusTextVar.set( '' ) # first initial value

        self.createMenuBar()
        self.createToolBar()
        self.createContextMenu()
        if self._showStatusBarVar.get(): self.createStatusBar()

        self.viewMode = DEFAULT
        self.settings = None

        # Create a scroll bar to fill the right-hand side of the window
        self.vScrollbar = Scrollbar( self )
        self.vScrollbar.pack( side=tk.RIGHT, fill=tk.Y )

        #if 'textBox' in dir(self): # we have one already -- presumably a specialised one
            #halt # We have one already
        #else: # let's make one

        self.textBox = HTMLText( self, yscrollcommand=self.vScrollbar.set, state=tk.DISABLED )
        self.textBox['wrap'] = 'word'
        self.textBox.pack( expand=tk.YES, fill=tk.BOTH )
        self.vScrollbar.config( command=self.textBox.yview ) # link the scrollbar to the text box
        self.createStandardKeyboardBindings()
        self.textBox.bind( "<Button-1>", self.setFocus ) # So disabled text box can still do select and copy functions

        # Options for find, etc.
        self.optionsDict = {}
        self.optionsDict['caseinsens'] = True

        if filename:
            self.historyList = [ filename ]
            self.historyIndex = 1 # Number from the end (starting with 1)
            self.load( filename )
        else:
            self.historyList = []
            self.historyIndex = 0 # = None
示例#14
0
class Table(Frame):
    def __init__(self, parent, title, columns):
        Frame.__init__(self, parent)
        self.pack(expand=YES, fill=BOTH)

        self.title_lbl = Label(self, text=title, font=GENERAL_FONT)
        self.table_tree = Treeview(self, columns=columns)

        # добавить Scrollbar
        self.scroll = Scroll(self, orient=VERTICAL, command=self.table_tree.yview)
        self.table_tree['yscroll'] = self.scroll.set

        for i in range(len(columns)):
            self.table_tree.heading(columns[i], text=columns[i])

        self.place_widgets()

    def place_widgets(self):
        self.title_lbl.pack(side=TOP, fill=X, expand=YES)
        self.table_tree.pack(side=LEFT, fill=BOTH, expand=YES)
        self.scroll.pack(side=RIGHT, fill=Y, expand=YES)
示例#15
0
文件: tree.py 项目: 1st1/cpython
class ScrolledCanvas:
    def __init__(self, master, **opts):
        if 'yscrollincrement' not in opts:
            opts['yscrollincrement'] = 17
        self.master = master
        self.frame = Frame(master)
        self.frame.rowconfigure(0, weight=1)
        self.frame.columnconfigure(0, weight=1)
        self.canvas = Canvas(self.frame, **opts)
        self.canvas.grid(row=0, column=0, sticky="nsew")
        self.vbar = Scrollbar(self.frame, name="vbar")
        self.vbar.grid(row=0, column=1, sticky="nse")
        self.hbar = Scrollbar(self.frame, name="hbar", orient="horizontal")
        self.hbar.grid(row=1, column=0, sticky="ews")
        self.canvas['yscrollcommand'] = self.vbar.set
        self.vbar['command'] = self.canvas.yview
        self.canvas['xscrollcommand'] = self.hbar.set
        self.hbar['command'] = self.canvas.xview
        self.canvas.bind("<Key-Prior>", self.page_up)
        self.canvas.bind("<Key-Next>", self.page_down)
        self.canvas.bind("<Key-Up>", self.unit_up)
        self.canvas.bind("<Key-Down>", self.unit_down)
        #if isinstance(master, Toplevel) or isinstance(master, Tk):
        self.canvas.bind("<Alt-Key-2>", self.zoom_height)
        self.canvas.focus_set()
    def page_up(self, event):
        self.canvas.yview_scroll(-1, "page")
        return "break"
    def page_down(self, event):
        self.canvas.yview_scroll(1, "page")
        return "break"
    def unit_up(self, event):
        self.canvas.yview_scroll(-1, "unit")
        return "break"
    def unit_down(self, event):
        self.canvas.yview_scroll(1, "unit")
        return "break"
    def zoom_height(self, event):
        zoomheight.zoom_height(self.master)
        return "break"
示例#16
0
def scroll(view, vert=True, horiz=True, resize=True):
    """Sets up scrollbars on view's master.
    
    The view should not have any layout settings of its own."""
    
    kw = dict()
    if resize:
        if not horiz:
            kw.update(rowspan=2)
        if not vert:
            kw.update(colspan=2)
    view.grid(sticky=(tkinter.EW, tkinter.NS), **kw)
    
    view.master.rowconfigure(0, weight=1)
    view.master.columnconfigure(0, weight=1)
    
    if vert:
        scroll = Scrollbar(view.master, orient=tkinter.VERTICAL,
            command=view.yview)
        scroll.grid(row=0, column=1, sticky=(tkinter.W, tkinter.NS))
        view.configure(yscrollcommand=scroll.set)
    if horiz:
        scroll = Scrollbar(view.master, orient=tkinter.HORIZONTAL,
            command=view.xview)
        scroll.grid(row=1, column=0, sticky=(tkinter.N, tkinter.EW))
        view.configure(xscrollcommand=scroll.set)
    if resize:
        resize = Sizegrip(view.master)
        resize.grid(row=1, column=1, sticky=(tkinter.EW, tkinter.NS))
示例#17
0
    def set(self, lo, hi):
        """
        Set scrollbar slider's end positions.

        @param lo: Low end position. A float value between 0.0 and 1.0.

        @param hi: High end position. A float value between 0.0 and 1.0.

        @return: None.
        """
        # If scrollbar slider's both ends reached extreme position
        if float(lo) <= 0.0 and float(hi) >= 1.0:
            # Hide the scrollbar
            self.grid_remove()

        # If not scrollbar slider's both ends reached extreme position
        else:
            # Show the scrollbar
            self.grid()

        # Call super version
        Scrollbar.set(self, lo, hi)
        def __init__(self, parent, *args, **kw):
            Frame.__init__(self, parent, *args, **kw)

            # create a canvas object and a vertical scrollbar for scrolling it
            vscrollbar = Scrollbar(self, orient=VERTICAL)
            vscrollbar.pack(fill=Y, side=RIGHT, expand=False)
            self.canvas = canvas = StyledCanvas(
                self, bd=0, highlightthickness=0,
                yscrollcommand=vscrollbar.set)
            canvas.pack(side=LEFT, fill=BOTH, expand=True)
            vscrollbar.config(command=canvas.yview)

            # reset the view
            canvas.xview_moveto(0)
            canvas.yview_moveto(0)

            # create a frame inside the canvas which will be scrolled with it
            self.interior = interior = Frame(canvas)
            interior_id = canvas.create_window(0, 0, window=interior,
                                               anchor=N+W)

            # track changes to the canvas and frame width and sync them,
            # also updating the scrollbar
            def _configure_interior(event):
                # update the scrollbars to match the size of the inner frame
                size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
                canvas.config(scrollregion="0 0 %s %s" % size)
                if interior.winfo_reqwidth() != canvas.winfo_width():
                    # update the canvas's width to fit the inner frame
                    canvas.config(width=interior.winfo_reqwidth())
            interior.bind('<Configure>', _configure_interior)

            def _configure_canvas(event):
                if interior.winfo_reqwidth() != canvas.winfo_width():
                   # update the inner frame's width to fill the canvas
                    canvas.itemconfigure(interior_id,
                                         width=canvas.winfo_width())
            canvas.bind('<Configure>', _configure_canvas)
            MouseWheel(self).add_scrolling(canvas, yscrollbar=vscrollbar)
示例#19
0
    def workflow(self):
        PL=self.Pipeline.get() #pipelineget()
        gf=Toplevel()
        #MkaS=os.popen("./makeasnake.py 2>&1 | tee -a "+workpath.get()+"/Reports/makeasnake.log").read()
    
        gf.title("CCBR Pipeliner: "+ PL + " Workflow Graph")
        cgf = Canvas(gf,bg="white")
        #gff=Frame(cgf,width=300,height=300)
        xscrollbar = Scrollbar(gf, orient=HORIZONTAL)
        xscrollbar.pack(side = BOTTOM, fill=X )
        xscrollbar.config(command=cgf.xview)

        yscrollbar = Scrollbar(gf,orient=VERTICAL)
        yscrollbar.pack(side = RIGHT, fill=Y )
        yscrollbar.config(command=cgf.yview)

        cgf.config(xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set)
        cgf.config(width=600,height=600)
        cgf.pack(expand=1,fill=BOTH,side=RIGHT)
        cgf.config(scrollregion=(0,0,5000,20000))
        img = PhotoImage(file=self.workpath.get()+"/Reports/"+PL+".gif")
        cgf.create_image(0,0,image=img, anchor="nw")
        cgf.image=img
示例#20
0
    def create_widgets(self):
        ''' Creates all widgets.
        '''
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        xscrollbar = Scrollbar(self, orient=HORIZONTAL)
        xscrollbar.grid(row=1, column=0, sticky=E+W)

        yscrollbar = Scrollbar(self)
        yscrollbar.grid(row=0, column=1, sticky=N+S)

        self.text = Text(self, wrap=NONE,
                         xscrollcommand=xscrollbar.set,
                         yscrollcommand=yscrollbar.set)

        self.text.bind("<Control-Key-a>", self.select_all)
        self.text.bind("<Control-Key-A>", self.select_all)

        self.text.grid(row=0, column=0, sticky=N+S+E+W)

        xscrollbar.config(command=self.text.xview)
        yscrollbar.config(command=self.text.yview)
示例#21
0
文件: frame.py 项目: aphistic/copilot
    def __init__(self, master, config):
        super(CopilotInnerFrame, self).__init__(master, config)

        if config.full_screen:
            self._make_full(master)

        self.master.grid_rowconfigure(1, weight=1)
        self.master.grid_columnconfigure(1, weight=1)

        self._create_header()

        self._sb = Scrollbar(self._master, orient=VERTICAL)
        self._sb.grid(row=1, column=3, sticky='nse')

        self._next_hidden = False
示例#22
0
 def CreateWidgets(self):
     frameText = Frame(self, relief=SUNKEN, height=700)
     frameButtons = Frame(self)
     self.buttonOk = Button(frameButtons, text='Close',
                            command=self.Ok, takefocus=FALSE)
     self.scrollbarView = Scrollbar(frameText, orient=VERTICAL,
                                    takefocus=FALSE)
     self.textView = Text(frameText, wrap=WORD, highlightthickness=0,
                          fg=self.fg, bg=self.bg)
     self.scrollbarView.config(command=self.textView.yview)
     self.textView.config(yscrollcommand=self.scrollbarView.set)
     self.buttonOk.pack()
     self.scrollbarView.pack(side=RIGHT,fill=Y)
     self.textView.pack(side=LEFT,expand=TRUE,fill=BOTH)
     frameButtons.pack(side=BOTTOM,fill=X)
     frameText.pack(side=TOP,expand=TRUE,fill=BOTH)
示例#23
0
 def create_widgets(self):
     "Create Frame with Text (with vertical Scrollbar) and Button."
     frame = Frame(self, relief=SUNKEN, height=700)
     frame_buttons = Frame(self)
     self.button_ok = Button(frame_buttons, text='Close',
                             command=self.ok, takefocus=False)
     self.scrollbar = Scrollbar(frame, orient=VERTICAL, takefocus=False)
     self.text = Text(frame, wrap=WORD, highlightthickness=0,
                          fg=self.fg, bg=self.bg)
     self.scrollbar.config(command=self.text.yview)
     self.text.config(yscrollcommand=self.scrollbar.set)
     
     self.button_ok.pack()
     self.scrollbar.pack(side=RIGHT, fill=Y)
     self.text.pack(side=LEFT, expand=True, fill=BOTH)
     frame_buttons.pack(side=BOTTOM, fill=X)
     frame.pack(side=TOP, expand=True, fill=BOTH)
示例#24
0
    def __init__( self, parentApp, genericWindowType ):
        """
        The genericWindowType is set here,
            but the more specific winType is set later by the subclass.
        """
        if BibleOrgSysGlobals.debugFlag and debuggingThisModule:
            print( exp("ChildWindow.__init__( {} {} )").format( parentApp, repr(genericWindowType) ) )
            assert( parentApp )
            assert( genericWindowType in ('BibleResource','LexiconResource','TextEditor','BibleEditor',) )
        self.parentApp, self.genericWindowType = parentApp, genericWindowType
        tk.Toplevel.__init__( self, self.parentApp )
        ChildBox.__init__( self, self.parentApp )
        self.protocol( "WM_DELETE_WINDOW", self.closeChildWindow )

        self.geometry( INITIAL_RESOURCE_SIZE )
        self.minimumSize, self.maximumSize = MINIMUM_RESOURCE_SIZE, MAXIMUM_RESOURCE_SIZE
        self.minsize( *parseWindowSize( self.minimumSize ) )
        self.maxsize( *parseWindowSize( self.maximumSize ) )

        self.createMenuBar()
        self.createToolBar()
        self.createContextMenu()

        self.viewMode = DEFAULT
        self.settings = None

        # Create a scroll bar to fill the right-hand side of the window
        self.vScrollbar = Scrollbar( self )
        self.vScrollbar.pack( side=tk.RIGHT, fill=tk.Y )

        #if 'textBox' in dir(self): # we have one already -- presumably a specialised one
            #halt # We have one already
        #else: # let's make one

        self.textBox = tk.Text( self, yscrollcommand=self.vScrollbar.set, state=tk.DISABLED )
        self.textBox['wrap'] = 'word'
        self.textBox.pack( expand=tk.YES, fill=tk.BOTH )
        self.vScrollbar.config( command=self.textBox.yview ) # link the scrollbar to the text box
        self.createStandardKeyboardBindings()
        self.textBox.bind( "<Button-1>", self.setFocus ) # So disabled text box can still do select and copy functions

        # Options for find, etc.
        self.optionsDict = {}
        self.optionsDict['caseinsens'] = True

        self.refreshTitle() # Must be in superclass
    def __init__( self, parentApp, internalBible, defaultContextViewMode=BIBLE_CONTEXT_VIEW_MODES[0], defaultFormatViewMode=BIBLE_FORMAT_VIEW_MODES[0] ):
        """
        Given a collection name, try to open an empty Bible resource collection window.
        """
        if BibleOrgSysGlobals.debugFlag:
            print( "BibleReferenceCollectionWindow.__init__( {}, {} )".format( parentApp, internalBible.getAName() ) )
        self.internalBible = internalBible
        ChildWindow.__init__( self, parentApp, genericWindowType='BibleResource' )
        BibleResourceWindowAddon.__init__( self, 'BibleReferenceCollectionWindow', internalBible.getAName(), defaultContextViewMode, defaultFormatViewMode )

        self.geometry( INITIAL_REFERENCE_COLLECTION_SIZE )
        self.minimumSize, self.maximumSize = MINIMUM_REFERENCE_COLLECTION_SIZE, MAXIMUM_REFERENCE_COLLECTION_SIZE
        self.minsize( *parseWindowSize( self.minimumSize ) )
        self.maxsize( *parseWindowSize( self.maximumSize ) )

        # Get rid of the default widgets
        self.vScrollbar.destroy()
        self.textBox.destroy()

        # Make a frame inside a canvas inside our window (in order to get a scrollbar)
        self.canvas = tk.Canvas( self, borderwidth=0, background='pink' ) #background="#ffffff" )
        self.vsb = Scrollbar( self, orient='vertical', command=self.canvas.yview )
        self.canvas.configure( yscrollcommand=self.vsb.set )
        self.vsb.pack( side=tk.RIGHT, fill=tk.Y )
        self.canvas.pack( side=tk.LEFT, expand=tk.YES, fill=tk.BOTH )
        self.canvasFrame = Frame( self.canvas ) #, background="#ffffff" )
        #self.canvasFrame.columnconfigure( 0, weight=1 )
        #self.canvasFrame.rowconfigure( 0, weight=1 )
        self.window = self.canvas.create_window( (0,0), window=self.canvasFrame, anchor='nw', tags='self.canvasFrame' )
        #self.columnconfigure( 0, weight=1 )
        #self.rowconfigure( 0, weight=1 )
        #self.canvasFrame.bind( '<Configure>', self.OnFrameConfigure )
        self.canvas.bind('<Configure>', self.onCanvasConfigure )

        #self.BCVUpdateType = 'ReferencesMode' # Leave as default
        self.folderPath = self.filename = self.filepath = None
        self.referenceBoxes = BibleReferenceBoxes( self )

        if BibleOrgSysGlobals.debugFlag and debuggingThisModule:
            print( exp("BibleReferenceCollectionWindow.__init__ finished.") )
示例#26
0
    def create_rdfs_frame(self, master:Notebook):
        rdfsframe = Frame(master, padding = '3 3 3 3', width=600, height=400)
        Label(rdfsframe, text='RDFS Name:', padding='3 3 3 3').grid(row=0, column=0, padx=3, pady=3)
        rdfsNameLbl = Label(rdfsframe, textvariable=self.rdfsName,
                            background='#bbb', relief=SUNKEN, padding='3 0 3 3')
        rdfsNameLbl.grid(row=0, column=1, columnspan=3, sticky=EW, padx=3, pady=6)
        self.classtree.heading(column='#0', text='ClassTree')
        ysb = Scrollbar(rdfsframe, orient='vertical', command=self.classtree.yview)
        xsb = Scrollbar(rdfsframe, orient='horizontal', command=self.classtree.xview)
        self.classtree.configure(yscrollcommand=ysb.set)
        self.classtree.configure(xscrollcommand=xsb.set)
        self.classtree.bind('<<TreeviewSelect>>', self.update_classinfo)
        self.classtree.grid(row=1, column=0, columnspan=2, in_=rdfsframe, sticky=NSEW)
        self.classtree.lift(rdfsframe)
        self.classtree.tag_configure('include', foreground='black')
        self.classtree.tag_configure('notinclude', foreground='gray')
        ysb.grid(row=1, column=2, sticky=(NS))
        xsb.grid(row=2, column=0, columnspan=2, sticky=(EW))
        classinfoframe = Frame(rdfsframe, width=300, height=400)
        classinfoframe.grid(row=1, column=3, padx=3, pady=3, sticky=(NSEW))
        Label(classinfoframe, text='Class Name:',
              font='bold', padding='3 3 3 3').grid(row=1, column=0, sticky=NW)
        classNameLbl = Label(classinfoframe, textvariable=self.className,
                            background='#bbb', relief=SUNKEN, padding='3 3 3 3',
                             font='bold', width=25)
        classNameLbl.grid(row=1, column=1, sticky=EW)
        Label(classinfoframe, text='Description:',
              font='bold', padding='3 3 3 3').grid(row=2, column=0, sticky=NW)
        self.classDescrTxt.grid(row=2, column=1, in_=classinfoframe, sticky=EW)
        self.classDescrTxt.lift(classinfoframe)
        include_chk = Checkbutton(classinfoframe,
                                  text='include this class',
                                  variable=self.includeclass,
                                  command=self.include_class)
        include_chk.grid(row=3, column=1, sticky=E)
        Label(classinfoframe, text='Properties:',
              font='bold', padding='3 3 3 3').grid(row=5, column=0, sticky=NW)
        self.propertiesframe.grid(in_ = classinfoframe, row=5, column=1, sticky=(N+E+S+W))
        self.propertiesframe.lift(classinfoframe)

        classinfoframe.rowconfigure(5, weight=1)
        classinfoframe.columnconfigure(1, weight=1)
        rdfsframe.columnconfigure(1, weight=1)
        rdfsframe.columnconfigure(3, weight=3)
        rdfsframe.rowconfigure(1, weight=1)        
        master.add(rdfsframe, text='RDFS')
示例#27
0
文件: panel.py 项目: Lysovenko/bpc
 def body(self, frame):
     "Place panel widgets"
     frame.grid_columnconfigure(0, weight=1)
     frame.grid_rowconfigure(1, weight=1)
     top = Frame(frame)
     top.grid(column=0, row=0, sticky="ew")
     self.mounts = Combobox(top, takefocus=False, state="readonly")
     self.mounts["postcommand"] = self.get_places
     self.mounts.bind("<<ComboboxSelected>>", self.goto_place)
     self.mounts.pack(anchor="nw")
     pthl = Label(top, textvariable=self.pwd)
     pthl.pack(expand=True, anchor="w")
     self.tree = tree = Treeview(frame,
                                 columns=("size", "modified", "mode"))
     tree.grid(column=0, row=1, sticky="nwes")
     vsb = Scrollbar(frame, command=self.tree.yview, orient="vertical")
     vsb.grid(column=1, row=1, sticky="ns")
     tree["yscrollcommand"] = lambda f, l: autoscroll(vsb, f, l)
     hsb = Scrollbar(frame, command=self.tree.xview,
                     orient="horizontal")
     hsb.grid(column=0, row=2, sticky="ew")
     tree["xscrollcommand"] = lambda f, l: autoscroll(hsb, f, l)
     tree.column("size", width=70, anchor="center")
     tree.column("modified", width=70, anchor="center")
     tree.column("mode", width=70, anchor="center")
     tree.heading("#0", command=lambda: self.on_heading("name"))
     tree.heading("size", command=lambda: self.on_heading("size"))
     tree.heading("modified", command=lambda: self.on_heading("date"))
     tree.tag_configure("selected", foreground="red")
     for i in (("<Return>", self.enter_file),
               ("<Double-Button-1>", self.enter_file),
               ("<Right>", self.enter_file), ("<Left>", self.go_back),
               ("<Tab>", self.switch), ("<Home>", self.go_top),
               ("<Button-1>", self.activate),
               ("<Insert>", self.turn_selection),
               ("<Control-r>", self.refresh)):
         tree.bind(*i)
示例#28
0
 def _add_scrollbar_to_treeview(self):
     vsb = Scrollbar(self, orient="vertical", command=self.tw.yview)
     self.tw.configure(yscrollcommand=vsb.set)
     vsb.pack(side="right", **pkw)
示例#29
0
    def __init__(self, master: Widget, document: FileDocument, **kwargs) \
            -> None:
        """
        Creates a text editor widget.

        :param master: the parent widget
        :param document: the model for the current KnitScript document
        """
        super().__init__(master, **kwargs)
        self.pack_propagate(False)
        text = Text(self,
                    undo=True,
                    font=_get_fixed_font(),
                    wrap=WORD,
                    padx=5,
                    pady=5,
                    relief=FLAT,
                    highlightthickness=0)

        menu = _create_edit_menu(text)
        text.bind(_BUTTONS["context_menu"],
                  partial(_show_context_menu, menu),
                  add=True)

        scrollbar = Scrollbar(self, command=text.yview)
        text.configure(yscrollcommand=scrollbar.set)
        scrollbar.pack(side=RIGHT, fill=Y)
        text.pack(side=LEFT, expand=YES, fill=BOTH)
        self.bind("<FocusIn>", lambda event: text.focus_set())

        # TODO:
        #  This is kind of a hack to stop Ctrl-O from inserting a new line. :/
        if platform.system() != "Darwin":

            def on_open(_event: Event) -> str:
                self.master.open()
                return "break"

            text.bind("<Control-o>", on_open)

        def on_enter(_event: Event) -> str:
            # Keep the indent on the new line the same as the current line.
            line = text.get("insert linestart", "insert lineend")
            indent = " " * sum(1 for _ in takewhile(lambda c: c == " ", line))
            if text.tag_ranges(SEL) == ():
                text.insert(INSERT, "\n" + indent)
            else:
                text.replace(SEL_FIRST, SEL_LAST, "\n" + indent)
            return "break"

        text.bind("<Return>", on_enter)

        def on_change(operation: Callable[..., None], *args) -> None:
            operation(*args)
            document.text = _strip_trailing_newline(text.get("1.0", END))
            document.modified = text.edit_modified()

        redirector = WidgetRedirector(text)
        insert = redirector.register("insert", None)
        delete = redirector.register("delete", None)
        replace = redirector.register("replace", None)
        redirector.register("insert", partial(on_change, insert))
        redirector.register("delete", partial(on_change, delete))
        redirector.register("replace", partial(on_change, replace))

        def bind_text_modified() -> None:
            def on_text_modified(_event: Event) -> None:
                document.modified = text.edit_modified()

            text.edit_modified(False)
            text.bind("<<Modified>>", on_text_modified, add=True)

        text.insert("1.0", document.text)
        self.after_idle(bind_text_modified)

        def on_document_opened(_event: Event) -> None:
            text.replace("1.0", END, document.text)
            text.edit_modified(False)

        def on_document_modified(_event: Event) -> None:
            if document.modified != text.edit_modified():
                text.edit_modified(document.modified)

        document.bind("<<Opened>>", on_document_opened, add=True)
        document.bind("<<Modified>>", on_document_modified, add=True)
示例#30
0
    def __init__(self, mainWin, modulesWithNewerFileDates):
        super(DialogPluginManager, self).__init__(mainWin.parent)
        
        self.ENABLE = _("Enable")
        self.DISABLE = _("Disable")
        self.parent = mainWin.parent
        self.cntlr = mainWin
        
        # copy plugins for temporary display
        self.pluginConfig = PluginManager.pluginConfig
        self.pluginConfigChanged = False
        self.uiClassMethodsChanged = False
        self.modulesWithNewerFileDates = modulesWithNewerFileDates
        
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", self.parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))

        self.title(_("Plug-in Manager"))
        frame = Frame(self)
        
        # left button frame
        buttonFrame = Frame(frame, width=40)
        buttonFrame.columnconfigure(0, weight=1)
        addLabel = Label(buttonFrame, text=_("Find plug-in modules:"), wraplength=60, justify="center")
        addLocalButton = Button(buttonFrame, text=_("Locally"), command=self.findLocally)
        ToolTip(addLocalButton, text=_("File chooser allows selecting python module files to add (or reload) plug-ins, from the local file system."), wraplength=240)
        addWebButton = Button(buttonFrame, text=_("On Web"), command=self.findOnWeb)
        ToolTip(addWebButton, text=_("Dialog to enter URL full path to load (or reload) plug-ins, from the web or local file system."), wraplength=240)
        addLabel.grid(row=0, column=0, pady=4)
        addLocalButton.grid(row=1, column=0, pady=4)
        addWebButton.grid(row=2, column=0, pady=4)
        buttonFrame.grid(row=0, column=0, rowspan=2, sticky=(N, S, W), padx=3, pady=3)
        
        # right tree frame (plugins already known to arelle)
        modulesFrame = Frame(frame, width=700)
        vScrollbar = Scrollbar(modulesFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(modulesFrame, orient=HORIZONTAL)
        self.modulesView = Treeview(modulesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=7)
        self.modulesView.grid(row=0, column=0, sticky=(N, S, E, W))
        self.modulesView.bind('<<TreeviewSelect>>', self.moduleSelect)
        hScrollbar["command"] = self.modulesView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.modulesView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        modulesFrame.columnconfigure(0, weight=1)
        modulesFrame.rowconfigure(0, weight=1)
        modulesFrame.grid(row=0, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.modulesView.focus_set()

        self.modulesView.column("#0", width=120, anchor="w")
        self.modulesView.heading("#0", text=_("Name"))
        self.modulesView["columns"] = ("author", "ver", "status", "date", "update", "descr", "license")
        self.modulesView.column("author", width=100, anchor="w", stretch=False)
        self.modulesView.heading("author", text=_("Author"))
        self.modulesView.column("ver", width=50, anchor="w", stretch=False)
        self.modulesView.heading("ver", text=_("Version"))
        self.modulesView.column("status", width=50, anchor="w", stretch=False)
        self.modulesView.heading("status", text=_("Status"))
        self.modulesView.column("date", width=70, anchor="w", stretch=False)
        self.modulesView.heading("date", text=_("File Date"))
        self.modulesView.column("update", width=50, anchor="w", stretch=False)
        self.modulesView.heading("update", text=_("Update"))
        self.modulesView.column("descr", width=200, anchor="w", stretch=False)
        self.modulesView.heading("descr", text=_("Description"))
        self.modulesView.column("license", width=70, anchor="w", stretch=False)
        self.modulesView.heading("license", text=_("License"))

        classesFrame = Frame(frame)
        vScrollbar = Scrollbar(classesFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(classesFrame, orient=HORIZONTAL)
        self.classesView = Treeview(classesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=5)
        self.classesView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.classesView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.classesView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        classesFrame.columnconfigure(0, weight=1)
        classesFrame.rowconfigure(0, weight=1)
        classesFrame.grid(row=1, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.classesView.focus_set()
        
        self.classesView.column("#0", width=200, anchor="w")
        self.classesView.heading("#0", text=_("Class"))
        self.classesView["columns"] = ("modules")
        self.classesView.column("modules", width=500, anchor="w", stretch=False)
        self.classesView.heading("modules", text=_("Modules"))
        
        # bottom frame module info details
        moduleInfoFrame = Frame(frame, width=700)
        moduleInfoFrame.columnconfigure(1, weight=1)
        
        self.moduleNameLabel = Label(moduleInfoFrame, wraplength=600, justify="left", 
                                     font=font.Font(family='Helvetica', size=12, weight='bold'))
        self.moduleNameLabel.grid(row=0, column=0, columnspan=4, sticky=W)
        self.moduleAuthorHdr = Label(moduleInfoFrame, text=_("author:"), state=DISABLED)
        self.moduleAuthorHdr.grid(row=1, column=0, sticky=W)
        self.moduleAuthorLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleAuthorLabel.grid(row=1, column=1, columnspan=3, sticky=W)
        self.moduleDescrHdr = Label(moduleInfoFrame, text=_("description:"), state=DISABLED)
        self.moduleDescrHdr.grid(row=2, column=0, sticky=W)
        self.moduleDescrLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleDescrLabel.grid(row=2, column=1, columnspan=3, sticky=W)
        self.moduleClassesHdr = Label(moduleInfoFrame, text=_("classes:"), state=DISABLED)
        self.moduleClassesHdr.grid(row=3, column=0, sticky=W)
        self.moduleClassesLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleClassesLabel.grid(row=3, column=1, columnspan=3, sticky=W)
        ToolTip(self.moduleClassesLabel, text=_("List of classes that this plug-in handles."), wraplength=240)
        self.moduleUrlHdr = Label(moduleInfoFrame, text=_("URL:"), state=DISABLED)
        self.moduleUrlHdr.grid(row=4, column=0, sticky=W)
        self.moduleUrlLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleUrlLabel.grid(row=4, column=1, columnspan=3, sticky=W)
        ToolTip(self.moduleUrlLabel, text=_("URL of plug-in module (local file path or web loaded file)."), wraplength=240)
        self.moduleDateHdr = Label(moduleInfoFrame, text=_("date:"), state=DISABLED)
        self.moduleDateHdr.grid(row=5, column=0, sticky=W)
        self.moduleDateLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleDateLabel.grid(row=5, column=1, columnspan=3, sticky=W)
        ToolTip(self.moduleDateLabel, text=_("Date of currently loaded module file (with parenthetical node when an update is available)."), wraplength=240)
        self.moduleLicenseHdr = Label(moduleInfoFrame, text=_("license:"), state=DISABLED)
        self.moduleLicenseHdr.grid(row=6, column=0, sticky=W)
        self.moduleLicenseLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleLicenseLabel.grid(row=6, column=1, columnspan=3, sticky=W)
        self.moduleEnableButton = Button(moduleInfoFrame, text=self.ENABLE, state=DISABLED, command=self.moduleEnable)
        ToolTip(self.moduleEnableButton, text=_("Enable/disable plug in."), wraplength=240)
        self.moduleEnableButton.grid(row=7, column=1, sticky=E)
        self.moduleReloadButton = Button(moduleInfoFrame, text=_("Reload"), state=DISABLED, command=self.moduleReload)
        ToolTip(self.moduleReloadButton, text=_("Reload/update plug in."), wraplength=240)
        self.moduleReloadButton.grid(row=7, column=2, sticky=E)
        self.moduleRemoveButton = Button(moduleInfoFrame, text=_("Remove"), state=DISABLED, command=self.moduleRemove)
        ToolTip(self.moduleRemoveButton, text=_("Remove plug in from plug in table (does not erase the plug in's file)."), wraplength=240)
        self.moduleRemoveButton.grid(row=7, column=3, sticky=E)
        moduleInfoFrame.grid(row=2, column=0, columnspan=5, sticky=(N, S, E, W), padx=3, pady=3)
        moduleInfoFrame.config(borderwidth=4, relief="groove")
        
        okButton = Button(frame, text=_("Close"), command=self.ok)
        ToolTip(okButton, text=_("Accept and changes (if any) and close dialog."), wraplength=240)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        ToolTip(cancelButton, text=_("Cancel changes (if any) and close dialog."), wraplength=240)
        okButton.grid(row=3, column=3, sticky=(S,E), pady=3)
        cancelButton.grid(row=3, column=4, sticky=(S,E), pady=3, padx=3)
        
        self.loadTreeViews()

        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(0, weight=1)
        frame.columnconfigure(1, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)
        
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
示例#31
0
 def CreateWidgets(self):
     frameMain = Frame(self, borderwidth=2, relief=SUNKEN)
     frameMain.pack(side=TOP, expand=TRUE, fill=BOTH)
     frameButtons = Frame(self)
     frameButtons.pack(side=BOTTOM, fill=X)
     self.buttonOK = Button(frameButtons,
                            text='OK',
                            width=8,
                            command=self.OK)
     self.buttonOK.grid(row=0, column=0, padx=5, pady=5)
     self.buttonCancel = Button(frameButtons,
                                text='Cancel',
                                width=8,
                                command=self.Cancel)
     self.buttonCancel.grid(row=0, column=1, padx=5, pady=5)
     self.frameKeySeqBasic = Frame(frameMain)
     self.frameKeySeqAdvanced = Frame(frameMain)
     self.frameControlsBasic = Frame(frameMain)
     self.frameHelpAdvanced = Frame(frameMain)
     self.frameKeySeqAdvanced.grid(row=0,
                                   column=0,
                                   sticky=NSEW,
                                   padx=5,
                                   pady=5)
     self.frameKeySeqBasic.grid(row=0,
                                column=0,
                                sticky=NSEW,
                                padx=5,
                                pady=5)
     self.frameKeySeqBasic.lift()
     self.frameHelpAdvanced.grid(row=1, column=0, sticky=NSEW, padx=5)
     self.frameControlsBasic.grid(row=1, column=0, sticky=NSEW, padx=5)
     self.frameControlsBasic.lift()
     self.buttonLevel = Button(frameMain,
                               command=self.ToggleLevel,
                               text='Advanced Key Binding Entry >>')
     self.buttonLevel.grid(row=2, column=0, stick=EW, padx=5, pady=5)
     labelTitleBasic = Label(self.frameKeySeqBasic,
                             text="New keys for  '" + self.action + "' :")
     labelTitleBasic.pack(anchor=W)
     labelKeysBasic = Label(self.frameKeySeqBasic,
                            justify=LEFT,
                            textvariable=self.keyString,
                            relief=GROOVE,
                            borderwidth=2)
     labelKeysBasic.pack(ipadx=5, ipady=5, fill=X)
     self.modifier_checkbuttons = {}
     column = 0
     for modifier, variable in zip(self.modifiers, self.modifier_vars):
         label = self.modifier_label.get(modifier, modifier)
         check = Checkbutton(self.frameControlsBasic,
                             command=self.BuildKeyString,
                             text=label,
                             variable=variable,
                             onvalue=modifier,
                             offvalue='')
         check.grid(row=0, column=column, padx=2, sticky=W)
         self.modifier_checkbuttons[modifier] = check
         column += 1
     labelFnAdvice=Label(self.frameControlsBasic,justify=LEFT,
                         text=\
                         "Select the desired modifier keys\n"+
                         "above, and the final key from the\n"+
                         "list on the right.\n\n" +
                         "Use upper case Symbols when using\n" +
                         "the Shift modifier.  (Letters will be\n" +
                         "converted automatically.)")
     labelFnAdvice.grid(row=1, column=0, columnspan=4, padx=2, sticky=W)
     self.listKeysFinal = Listbox(self.frameControlsBasic,
                                  width=15,
                                  height=10,
                                  selectmode=SINGLE)
     self.listKeysFinal.bind('<ButtonRelease-1>', self.FinalKeySelected)
     self.listKeysFinal.grid(row=0, column=4, rowspan=4, sticky=NS)
     scrollKeysFinal = Scrollbar(self.frameControlsBasic,
                                 orient=VERTICAL,
                                 command=self.listKeysFinal.yview)
     self.listKeysFinal.config(yscrollcommand=scrollKeysFinal.set)
     scrollKeysFinal.grid(row=0, column=5, rowspan=4, sticky=NS)
     self.buttonClear = Button(self.frameControlsBasic,
                               text='Clear Keys',
                               command=self.ClearKeySeq)
     self.buttonClear.grid(row=2, column=0, columnspan=4)
     labelTitleAdvanced = Label(
         self.frameKeySeqAdvanced,
         justify=LEFT,
         text="Enter new binding(s) for  '" + self.action + "' :\n" +
         "(These bindings will not be checked for validity!)")
     labelTitleAdvanced.pack(anchor=W)
     self.entryKeysAdvanced = Entry(self.frameKeySeqAdvanced,
                                    textvariable=self.keyString)
     self.entryKeysAdvanced.pack(fill=X)
     labelHelpAdvanced = Label(
         self.frameHelpAdvanced,
         justify=LEFT,
         text="Key bindings are specified using Tkinter keysyms as\n" +
         "in these samples: <Control-f>, <Shift-F2>, <F12>,\n"
         "<Control-space>, <Meta-less>, <Control-Alt-Shift-X>.\n"
         "Upper case is used when the Shift modifier is present!\n\n" +
         "'Emacs style' multi-keystroke bindings are specified as\n" +
         "follows: <Control-x><Control-y>, where the first key\n" +
         "is the 'do-nothing' keybinding.\n\n" +
         "Multiple separate bindings for one action should be\n" +
         "separated by a space, eg., <Alt-v> <Meta-v>.")
     labelHelpAdvanced.grid(row=0, column=0, sticky=NSEW)
示例#32
0
class TextViewer(Toplevel):
    """A simple text viewer dialog for IDLE

    """
    def __init__(self, parent, title, text, modal=True, _htest=False):
        """Show the given text in a scrollable window with a 'close' button

        If modal option set to False, user can interact with other windows,
        otherwise they will be unable to interact with other windows until
        the textview window is closed.

        _htest - bool; change box location when running htest.
        """
        Toplevel.__init__(self, parent)
        self.configure(borderwidth=5)
        # place dialog below parent if running htest
        self.geometry(
            "=%dx%d+%d+%d" %
            (750, 500, parent.winfo_rootx() + 10, parent.winfo_rooty() +
             (10 if not _htest else 100)))
        #elguavas - config placeholders til config stuff completed
        self.bg = '#ffffff'
        self.fg = '#000000'

        self.CreateWidgets()
        self.title(title)
        self.protocol("WM_DELETE_WINDOW", self.Ok)
        self.parent = parent
        self.textView.focus_set()
        #key bindings for this dialog
        self.bind('<Return>', self.Ok)  #dismiss dialog
        self.bind('<Escape>', self.Ok)  #dismiss dialog
        self.textView.insert(0.0, text)
        self.textView.config(state=DISABLED)

        if modal:
            self.transient(parent)
            self.grab_set()
            self.wait_window()

    def CreateWidgets(self):
        frameText = Frame(self, relief=SUNKEN, height=700)
        frameButtons = Frame(self)
        self.buttonOk = Button(frameButtons,
                               text='Close',
                               command=self.Ok,
                               takefocus=FALSE)
        self.scrollbarView = Scrollbar(frameText,
                                       orient=VERTICAL,
                                       takefocus=FALSE)
        self.textView = Text(frameText,
                             wrap=WORD,
                             highlightthickness=0,
                             fg=self.fg,
                             bg=self.bg)
        self.scrollbarView.config(command=self.textView.yview)
        self.textView.config(yscrollcommand=self.scrollbarView.set)
        self.buttonOk.pack()
        self.scrollbarView.pack(side=RIGHT, fill=Y)
        self.textView.pack(side=LEFT, expand=TRUE, fill=BOTH)
        frameButtons.pack(side=BOTTOM, fill=X)
        frameText.pack(side=TOP, expand=TRUE, fill=BOTH)

    def Ok(self, event=None):
        self.destroy()
示例#33
0
class App_test(object):
    def __init__(self, master, fuc, query, next, pre, query_all_chapters, query_text):
        self.win = master
        self.win.title('笔趣阁阅读_v1.0   by: 孤月')
        # self.win.iconbitmap('./ico/gui_text_proce.ico')  # 指定界面图标
        curWidth = self.win.winfo_width()
        curHeight = self.win.winfo_height()
        scnWidth, scnHeight = self.win.maxsize()
        tmpcnf = '1340x640+500+300'  # % ((scnWidth - curWidth) / 2, (scnHeight - curHeight) / 2)
        self.win.geometry(tmpcnf)
        self.creat_res()
        self.set_position()
        self.list_box(query_all_chapters, query_text)
        # self.add_train_info()
        self.res_config(fuc, query, next, pre)
        self.train_message = {}
        self.gettime()  # 系统时间

    def creat_res(self):
        # self.v = IntVar()  # 书籍查询
        # self.v.set(True)
        self.temp = StringVar()  # 书名/作者 录入
        self.temp2 = StringVar()  # 章节名录入
        self.sys_time = StringVar()  # 系统时间

        self.E_startstation = Entry(self.win, textvariable=self.temp)
        # self.E_endstation = Entry(self.win, textvariable=self.temp2)

        self.La_startstation = Label(self.win, text="根据书名/作者搜索:")
        self.La_endstation = Label(self.win, text="书籍目录:")
        self.La_directory = Label(self.win, text="目录")
        self.La_text = Label(self.win, text="正文")
        self.La_sys_time = Label(self.win, textvariable=self.sys_time, fg='blue', font=("黑体", 20))  # 设置字体大小颜色
        self.La_pic = Label(self.win, bg="#E6E6FA")
        self.La_anthor = Label(self.win, bg="#E6E6FA")
        self.La_type = Label(self.win, bg="#E6E6FA")
        self.La_update_time = Label(self.win, bg="#E6E6FA")
        self.La_latest_chapter = Label(self.win, bg="#E6E6FA")

        self.B_search = Button(self.win, text="搜索")
        self.B_buy_tick = Button(self.win, text="阅读")
        self.B_pre_chapter = Button(self.win, text="上一章")
        self.B_next_chapter = Button(self.win, text="下一章")

        # self.R_site = Radiobutton(self.win, text="书名查询", variable=self.v, value=True)
        # self.R_price = Radiobutton(self.win, text="章节查询", variable=self.v, value=False)

        self.init_data_Text = Text(self.win)  # 原始数据录入框
        self.S_move = Scrollbar(self.win)  # 目录滚动条
        self.S_text_move = Scrollbar(self.win)  # 创建文本框滚动条

    # 设置位置
    def set_position(self):
        self.init_data_Text.place(x=430, y=40, width=870, height=550)
        self.E_startstation.place(x=10, y=50, width=145, height=30)
        self.E_startstation.insert(10, "星辰变")
        # self.E_endstation.place(x=10, y=140, width=145, height=30)
        # self.E_endstation.insert(10, "第一章 秦羽")
        self.La_startstation.place(x=10, y=10, width=130, height=30)
        self.La_endstation.place(x=10, y=100, width=60, height=30)
        self.La_sys_time.place(x=1150, y=600, width=160, height=30)
        self.La_pic.place(x=10, y=350, width=170, height=180)   # 图片
        self.La_anthor.place(x=10, y=545, width=170, height=30)
        self.La_type.place(x=10, y=575, width=170, height=30)
        self.La_update_time.place(x=10, y=605, width=170, height=30)
        self.La_latest_chapter.place(x=10, y=635, width=170, height=30)

        self.B_search.place(x=10, y=300, width=80, height=40)
        self.B_buy_tick.place(x=90, y=300, width=80, height=40)
        self.B_pre_chapter.place(x=950, y=600, width=80, height=40)
        self.B_next_chapter.place(x=1050, y=600, width=80, height=40)
        self.S_move.place(x=380, y=40, width=30, height=550)
        self.S_text_move.place(x=1300, y=40, width=30, height=550)
        # self.R_site.place(x=10, y=180, width=90, height=30)
        # self.R_price.place(x=100, y=180, width=90, height=30)
        self.La_directory.place(x=180, y=7, width=90, height=30)
        self.La_text.place(x=420, y=7, width=70, height=30)

    # 为按钮绑定事件
    def res_config(self, fuc, query, next_, pre):
        self.B_search.config(command=fuc)  # 搜索
        self.B_buy_tick.config(command=query)  # 阅读
        self.B_pre_chapter.config(command=pre)  # 上一章
        self.B_next_chapter.config(command=next_)  # 下一章
        self.S_move.config(command=self.Ls_box_ct.yview)  # 目录滚动条
        self.Ls_box_ct.config(yscrollcommand=self.S_move.set)
        self.S_text_move.config(command=self.init_data_Text.yview)  # 文本框滚动条
        self.init_data_Text.config(yscrollcommand=self.S_text_move.set)

    # def printlist(self,event):
    #     print(self.Ls_box.get(self.Ls_box.curselection()))

    def list_box(self, query_all_chapters, query_text):
        self.Ls_box = Listbox(self.win, selectmode=EXTENDED, fg='blue')
        self.Ls_box.place(x=10, y=140, width=170, height=150)
        self.Ls_box.bind('<Double-Button-1>', query_all_chapters)   # 鼠标双击  更多事件请看http://www.cnblogs.com/hackpig/p/8195678.html
        self.Ls_box.insert(END, "请输入书名&作者进行查询")

        self.Ls_box_ct = Listbox(self.win, selectmode=EXTENDED, fg='blue')
        self.Ls_box_ct.place(x=200, y=40, width=180, height=550)
        self.Ls_box_ct.bind('<Double-Button-1>', query_text)

    def add_train_info(self):
        lis_train = ["C" + str(x) for x in range(0, 2)]
        tuple_train = tuple(lis_train)
        self.tree = Treeview(self.win, columns=tuple_train, height=30, show="headings")
        self.tree.place(x=200, y=40, width=180, height=550)
        train_info = [' 书名 ', ' 作者 ']
        for i in range(0, len(lis_train)):
            self.tree.column(lis_train[i], width=len(train_info[i]) * 11,
                             anchor='w')  # must be n, ne, e, se, s, sw, w, nw, or center
            self.tree.heading(lis_train[i], text=train_info[i])

    # 实时显示时钟
    def gettime(self):
        # 获取当前时间
        self.sys_time.set(time.strftime("%H:%M:%S"))
        # 每隔一秒调用函数自身获取时间
        self.win.after(1000, self.gettime)
示例#34
0
class SearchApplication(GenericFrame):
    FAVICON = "../assets/favicon.ico"

    def __init__(self, parent=None, app_window=None):
        self.lastValue = None
        self.category_option = StringVar("")
        self.column_id = [
            'ProductDescription', 'ManufacturerName', 'ManufacturerPartNumber',
            'DigiKeyPartNumber', 'Category'
        ]
        Frame.__init__(self, parent)
        self.pack()
        self.parent = parent
        self.app_window = app_window
        self.selectedField = None

        self.parent.title("Partlocater - Advanced Database Search")
        self.parent.iconbitmap(self.FAVICON)
        self.menubar = Frame(self, background='white')

        self.menubar.pack(side=TOP, fill=X, expand=YES)
        self.win_frame = Frame(self)
        self.win_frame.pack(side=TOP, fill=BOTH, expand=YES)
        self.editbutton = Menubutton(self.menubar,
                                     text='Edit',
                                     background='grey98')
        self.editbutton.pack(side=LEFT, fill=X)
        self.editmenu = Menu(self.editbutton, tearoff=0)
        self.editbutton.config(menu=self.editmenu)
        self.copySourcesMenu = Menu(self.editbutton, tearoff=0)
        self.editmenu.add_cascade(label='Copy', menu=self.copySourcesMenu)
        self.copySourcesMenu.add_command(label='Part Number',
                                         state=DISABLED,
                                         command=self.on_copy_partnumber)
        self.partnumber_index = 0
        self.copySourcesMenu.add_command(label='Selected Parameter',
                                         state=DISABLED,
                                         command=self.on_copy_parameters)
        self.selectedParameter_index = 1
        self.copySourcesMenu.add_command(label='Selected Part All Parameters',
                                         state=DISABLED,
                                         command=self.on_copy_all_parameters)
        self.allParameters_index = 2
        self.editmenu.add_command(label='Delete Part',
                                  state=DISABLED,
                                  command=self.on_delete)

        self.searchLF = LabelFrame(self.win_frame, text="Search")
        self.searchLF.pack(side=LEFT, fill=X, expand=YES, pady=4, padx=6)
        self.searchLeftF = Frame(self.searchLF)
        self.searchLeftF.pack(side=LEFT, anchor=W)
        self.searchRightF = Frame(self.searchLF)
        self.searchRightF.pack(side=LEFT, anchor=N)
        self.searchLabelWidth = 20
        self.catF = Frame(self.searchLeftF)
        self.catF.pack(side=TOP, anchor=W)
        self.catL = Label(self.catF,
                          text='Category',
                          width=self.searchLabelWidth,
                          anchor=W,
                          justify=LEFT)
        self.catL.pack(side=LEFT, fill=X, expand=YES)
        self.cat = StringVar()
        self.catE = Entry(self.catF,
                          textvariable=self.cat,
                          width=50,
                          state=DISABLED)
        self.catE.config(disabledbackground=self.catE.cget("bg"))
        self.catE.config(disabledforeground=self.catE.cget("fg"))
        self.catE.pack(side=LEFT, fill=X, expand=YES, pady=4)
        self.category_option = StringVar()
        self.cat.set("All")
        option_list = ['All', 'All'] + Config().tables
        self.catM = OptionMenu(self.searchRightF,
                               self.category_option,
                               *option_list,
                               command=self.on_category)
        self.catM.pack(side=TOP, anchor=N, fill=X, expand=YES)

        self.manF = Frame(self.searchLeftF)
        self.manF.pack(side=TOP, anchor=W)
        self.manL = Label(self.manF,
                          text='ManufacturerName',
                          width=self.searchLabelWidth,
                          anchor=W,
                          justify=LEFT)
        self.manL.pack(side=LEFT, fill=X, expand=YES, pady=4)
        self.man = StringVar()
        self.manE = Entry(self.manF, width=50, textvariable=self.man)
        self.manE.pack(side=LEFT, fill=X, expand=YES, pady=4)

        self.mpnF = Frame(self.searchLeftF)
        self.mpnF.pack(side=TOP, anchor=W)
        self.mpnL = Label(self.mpnF,
                          text='ManufacturerPartNumber',
                          width=self.searchLabelWidth,
                          anchor=W,
                          justify=LEFT)
        self.mpnL.pack(side=LEFT, fill=X, expand=YES, pady=4)
        self.mpn = StringVar()
        self.mpnE = Entry(self.mpnF, width=50, textvariable=self.mpn)
        self.mpnE.pack(side=LEFT, fill=X, expand=YES, pady=4)

        self.spnF = Frame(self.searchLeftF)
        self.spnF.pack(side=TOP, anchor=W)
        self.spnL = Label(self.spnF,
                          text='DigiKeyPartNumber',
                          width=self.searchLabelWidth,
                          anchor=W,
                          justify=LEFT)
        self.spnL.pack(side=LEFT, fill=X, expand=YES, pady=4)
        self.spn = StringVar()
        self.spnE = Entry(self.spnF, width=50, textvariable=self.spn)
        self.spnE.pack(side=LEFT, fill=X, expand=YES, pady=4)

        self.descF = Frame(self.searchLeftF)
        self.descF.pack(side=TOP, anchor=W)
        self.descL = Label(self.descF,
                           text='ProductDescription',
                           width=self.searchLabelWidth,
                           anchor=W,
                           justify=LEFT)
        self.descL.pack(side=LEFT, fill=X, expand=YES, pady=4)
        self.desc = StringVar()
        self.descE = Entry(self.descF, width=50, textvariable=self.desc)
        self.descE.pack(side=LEFT, fill=X, expand=YES, pady=4)
        self.descE.focus_force()

        self.findF = Frame(self.searchLeftF)
        self.findF.pack(side=TOP, anchor=E)
        self.findB = ttk.Button(self.findF,
                                text="Find",
                                width=12,
                                command=lambda event=None: self.do_find(event))
        self.findB.pack(side=LEFT, pady=4)
        self.clearB = ttk.Button(self.findF,
                                 text="Clear",
                                 width=6,
                                 command=self.on_clear_search)
        self.clearB.pack(side=LEFT, pady=4)

        self.partsLF = LabelFrame(self, text="Found Components")
        self.partsLF.pack(side=TOP, fill=X, expand=YES, pady=4, padx=4)
        self.partsF = Frame(self.partsLF)
        self.partsF.pack(side=TOP, pady=4, padx=4)
        # change treeview for search here
        self.partsTV = Treeview(self.partsF,
                                selectmode=BROWSE,
                                show='tree headings',
                                columns=self.column_id)

        self.partsTV.bind('<Double-Button-1>', self.on_edit_item)
        self.partsTV.bind('<<TreeviewSelect>>', self.fieldChanged)
        self.partsTV.bind('<Escape>', self.clearSelection)
        self.partsTV.bind('<MouseWheel>', self.mousewheel)
        self.partsTV.bind('<Button-4>', self.mousewheel)
        self.partsTV.bind('<Button-5>', self.mousewheel)
        vcmd = (self.register(self.validateEntry), '%P')
        self.editfield = ttk.Entry(self.partsTV,
                                   validate='key',
                                   validatecommand=vcmd)
        self.editfield.bind('<Return>', self.updateField)
        self.editfield.bind('<Escape>', self.clearSelection)

        self.partsTV.bind('<Control-c>', self.on_copy_element)
        self.partsTV.column("#0", minwidth=0, width=18, stretch=NO)
        for t in self.column_id:
            self.partsTV.heading(t, text=Config().parameter[t])
        self.partsTV.column('Category', width=60)
        self.scrollbar = Scrollbar(self.partsF,
                                   orient='vertical',
                                   command=self.partsTV.yview)
        self.scrollbar.pack(side=RIGHT, fill=Y, expand=YES, anchor=E)
        self.partsTV.configure(yscroll=self.scrollbar.set)
        self.scrollbar.config(command=self.yview)

        self.partsTV.pack(side=TOP, anchor=W, fill=X, expand=YES)
        self.partsTV.delete(*self.partsTV.get_children())
        # end change of treeview
        # change the following to menu item
        #self.part_buttonF = Frame(self.partsLF)
        #self.delete_partB = ttk.Button(self.partsLF, text="Delete Part from Database", command=self.on_delete,
        #state=DISABLED)
        #self.delete_partB.pack(side=RIGHT, anchor=W, expand=NO, pady=4, padx=6)
        #self.partsB = ttk.Button(self.partsLF, text="Copy Selected To Part Find", command=self.on_copy, state=DISABLED)
        #self.partsB.pack(side=RIGHT, anchor=W, expand=NO, pady=4, padx=6)
        #self.part_buttonF.pack(side=BOTTOM)
        # start remove vvv
        #self.element_labelframe = LabelFrame(self, text="Modify Name/Value")
        #self.element_labelframe.pack(side=TOP, fill=X, expand=YES, pady=4, padx=6)
        #self.element_frame = Frame(self.element_labelframe)
        #self.element_frame.pack(side=TOP)

        #self.element_name = StringVar()
        #self.element_label = Label(self.element_frame, textvariable=self.element_name, width=30, anchor=W, justify=LEFT)
        #self.element_label.pack(side=LEFT, anchor=W, fill=X, expand=YES, pady=4)
        #self.element_value = StringVar()
        #self.element_entry = Entry(self.element_frame, width=50, textvariable=self.element_value)
        #self.element_entry.pack(side=LEFT, fill=X, expand=YES, pady=4)
        #self.default_color = self.element_entry.cget('background')

        #self.element_update = ttk.Button(self.element_frame, text="Update", command=self.on_update_element,
        #state=DISABLED)
        #self.element_update.pack(side=LEFT, fill=X, expand=YES, pady=4)
        #self.element_cancel = ttk.Button(self.element_frame, text="Cancel", command=self.on_clear_element,
        #state=DISABLED)
        #self.element_cancel.pack(side=LEFT, fill=X, expand=YES, pady=4)
        # end remove ^^^

        self.statusLF = LabelFrame(self, text="Status")
        self.statusLF.pack(side=BOTTOM, fill=X, expand=YES, pady=4, padx=6)
        self.statusF = Frame(self.statusLF)
        self.statusF.pack(side=TOP, fill=X, expand=YES, padx=6)
        self.status = self.StatusBar(self.statusF, self)

    def validateEntry(self, P):
        if (len(P) <= 120):
            return True
        else:
            self.bell()
            return False

    # scroll bar event
    def yview(self, *args):
        if self.selectedField is not None:
            self.editfield.place_forget()
            self.selectedField = None
        self.partsTV.yview(*args)

    # mousewheel and button4/5 event
    def mousewheel(self, event):
        if self.selectedField is not None:
            self.editfield.place_forget()
            self.selectedField = None

    # escape event in treeview or editfield
    def clearSelection(self, event):
        self.editfield.place_forget()
        self.selectedField = None
        self.partsTV.selection_remove(self.partsTV.selection())
        self.status.set("")

    # double button event
    def on_edit_item(self, event):
        if self.partsTV.parent(self.partsTV.selection()
                               ) == '':  # testing should not edit a parent
            self.selectedField = None
            return
        if (self.partsTV.identify_region(event.x, event.y) == 'cell'):
            self.selectedField = self.partsTV.identify_row(event.y)
            x, y, width, height = self.partsTV.bbox(self.selectedField, '#2')
            v = self.partsTV.set(self.selectedField, 1)
            self.editfield.pack()
            self.editfield.delete(0, len(self.editfield.get()))
            self.editfield.insert(0, v)
            self.editfield.selection_range(0, 'end')
            self.editfield.focus_force()
            self.editfield.place(x=x, y=y, width=width, height=height)

    # find button event
    def on_find(self):
        category = self.cat.get()
        search_list = []
        col_list = []
        search_str = self.man.get()
        if not (validate(search_str)):
            raise Exception("Invalid Manufacture Name")
        search_list.append(search_str)
        col_list.append(Config().parameter['ManufacturerName'])
        search_str = self.mpn.get()
        if not (validate(search_str)):
            raise Exception("Invalid Manufacture Part Number")
        search_list.append(search_str)
        col_list.append(Config().parameter['ManufacturerPartNumber'])
        search_str = self.spn.get()
        if not (validate(search_str)):
            raise Exception("Invalid Supplier Part Number")
        search_list.append(search_str)
        col_list.append(Config().parameter['DigiKeyPartNumber'])
        search_str = self.desc.get().split()
        if not (validate(search_str)):
            raise Exception("Invalid Description")
        search_list += search_str
        col_list.append(Config().parameter['ProductDescription'])
        select = "SELECT * FROM `" + Config().loaded_db.name + "`."
        where = "WHERE"
        like = ""
        i = 0
        for item in search_list:
            if len(item) > 0:
                item = item.replace('%', '\\%')
                item = item.replace('"', '')
                item = item.replace("'", "")
                if i < 3:
                    like += where + " `" + col_list[
                        i] + "` LIKE '" + item + "%'"
                else:
                    like += where + " (`" + col_list[i] + "` LIKE '" + item + "%' OR `" + \
                            col_list[i] + "` LIKE '% " + item + "%')"
                where = " AND"
            i = i + 1 if (i < 3) else i
        self.partsTV.delete(*self.partsTV.get_children())
        count = 0
        if category == "All":
            for table in Config().tables:
                qry = select + "`" + table + "` " + like
                result = Config().loaded_db.query(qry)
                for record in result:
                    v = []
                    spn = record[Config().parameter['DigiKeyPartNumber']]
                    count += 1
                    for id in self.column_id:
                        if id == 'Category':
                            v.append(table)
                        else:
                            v.append(record[Config().parameter[id]])
                    id = self.partsTV.insert('',
                                             'end',
                                             iid=spn,
                                             text=spn,
                                             values=v)
                    for params in record:
                        if record[params] is not None:
                            self.partsTV.insert(id,
                                                'end',
                                                text=spn,
                                                values=(params,
                                                        record[params]))
        else:
            qry = select + "`" + category + "` " + like
            result = Config().loaded_db.query(qry)
            for record in result:
                v = []
                count += 1
                spn = record[Config().parameter['DigiKeyPartNumber']]
                for id in self.column_id:
                    if id == 'Category':
                        v.append(category)
                    else:
                        v.append(record[Config().parameter[id]])
                id = self.partsTV.insert('',
                                         'end',
                                         iid=spn,
                                         text=spn,
                                         values=v)
                for params in record:
                    if record[params] is not None:
                        self.partsTV.insert(id,
                                            'end',
                                            text=spn,
                                            values=(params, record[params]))
        self.status.set(("No" if count == 0 else str(count)) + " items found")

    # return event
    def updateField(self, event):
        value = self.editfield.get()
        self.editfield.place_forget()
        name = self.partsTV.item(self.selectedField, "text")
        if not validate(value):
            self.status.seterror("Invalid value, must not have quotes")
            return
        self.partsTV.set(self.selectedField, "#2", value)
        key = self.partsTV.set(self.selectedField, "#1")
        self.editfield.place_forget()
        element_parent = self.partsTV.parent(self.selectedField)
        table_name = self.partsTV.item(
            element_parent, "values")[self.column_id.index('Category')]
        part_number = self.partsTV.item(
            element_parent,
            "values")[self.column_id.index('DigiKeyPartNumber')]
        set_param = "SET `" + key + "` = '" + value + "' "
        where = "WHERE `" + Config(
        ).parameter['DigiKeyPartNumber'] + "` = '" + part_number + "'"
        qry = "UPDATE `" + Config(
        ).loaded_db.name + "`.`" + table_name + "` " + set_param + where
        print(qry)
        try:
            Config().loaded_db.query(qry)
        except Exception as e:
            self.status.seterror("Database query failed: %s", e)
            return
        self.status.set("Changed " + key + " to " + value + " for part " +
                        part_number + ".")
        self.partsTV.see(self.selectedField)

    # clear button in search frame
    def on_clear_search(self):
        self.man.set("")
        self.mpn.set("")
        self.spn.set("")
        self.desc.set("")
        self.cat.set("All")
        self.category_option.set("All")
        self.partsTV.delete(*self.partsTV.get_children())

    def do_flash(self):
        current_color = self.element_entry.cget("background")
        if current_color == self.default_color:
            self.element_entry.config(background="red")
        else:
            self.element_entry.config(background=self.default_color)
            return
        self.after(250, self.do_flash)

    # category option menu
    def on_category(self, value):
        self.catE.config(state=NORMAL)
        self.cat.set(value)
        self.catE.config(state=DISABLED)

    #def on_copy(self):
    #selected = self.partsTV.selection()[0]
    #key = self.partsTV.item(selected, "values")[self.column_id.index('DigiKeyPartNumber')]
    #self.app_window.part_num_string.set(key)
    #self.status.set("Part Number '" + key + "' copied to Part Find")
    # Edit -> Delete menu
    def on_delete(self):
        selected = self.partsTV.selection()[0]
        key = self.partsTV.item(
            selected, "values")[self.column_id.index('DigiKeyPartNumber')]
        table = self.partsTV.item(selected,
                                  "values")[self.column_id.index('Category')]
        if messagebox.askokcancel(
                "Delete", "Click OK if you really want to delete '" + key +
                "' from database?"):
            Config().loaded_db.query("DELETE FROM `" + table + "` WHERE `" +
                                     Config().parameter['DigiKeyPartNumber'] +
                                     "` = '" + key + "'")
            self.status.set("Part Number '" + key + "' deleted from database")

    # treeview select event
    def fieldChanged(self, event):
        selected = self.partsTV.selection()
        if len(selected) > 0:
            self.copySourcesMenu.entryconfig(self.partnumber_index,
                                             state=NORMAL)
            self.copySourcesMenu.entryconfig(self.allParameters_index,
                                             state=NORMAL)
        else:
            self.copySourcesMenu.entryconfig(self.partnumber_index,
                                             state=DISABLED)
            self.copySourcesMenu.entryconfig(self.allParameters_index,
                                             state=DISABLED)
            return
        if self.partsTV.parent(selected) == '':
            self.copySourcesMenu.entryconfig(self.selectedParameter_index,
                                             state=DISABLED)
        else:
            self.copySourcesMenu.entryconfig(self.selectedParameter_index,
                                             state=NORMAL)
        if selected != self.selectedField:
            self.editfield.place_forget()
            self.selectedField = None

    def on_copy_parameters(self):
        selected = self.partsTV.selection()
        if len(selected) == 0 or self.partsTV.parent(selected) == '':
            return
        try:
            property = self.partsTV.item(selected, "values")
            self.parent.clipboard_clear()
            self.parent.clipboard_append(property[0] + '\t' + property[1])
            self.parent.update()
            self.status.set(property[0] + ' ' + property[1] +
                            " copied to clipboard")
        except Exception as e:
            pass

    def on_copy_partnumber(self):
        selected = self.partsTV.selection()
        if len(selected) == 0 or self.partsTV.parent(selected) == '':
            return
        try:
            if self.partsTV.parent(selected) != '':
                selected = self.partsTV.parent(selected)
            partnumber = self.partsTV.item(
                selected, "values")[self.column_id.index('DigiKeyPartNumber')]
            self.parent.clipboard_clear()
            self.parent.clipboard_append(partnumber)
            self.parent.update()
            self.status.set(" '" + partnumber + "' copied to clipboard")
        except Exception as e:
            pass

    def on_copy_all_parameters(self):
        selected = self.partsTV.selection()
        if len(selected) == 0:
            return
        try:
            if self.partsTV.parent(selected) != '':
                selected = self.partsTV.parent(selected)
            partnumber = self.partsTV.item(
                selected, "values")[self.column_id.index('DigiKeyPartNumber')]
            elements = self.partsTV.get_children(selected)
            self.parent.clipboard_clear()
            self.parent.clipboard_clear()
            for i in elements:
                element = self.partsTV.item(i, "values")
                self.parent.clipboard_append(element[0] + "\t" + element[1] +
                                             "\n")
            self.parent.update()
            self.status.set("All properties of " + partnumber +
                            " copied to clipboard")
        except Exception as e:
            pass

        # deprecate
    def on_copy_element(self, event):
        try:
            selected = self.partsTV.selection()[0]
            if self.partsTV.parent(selected) == '':
                partnumber = self.partsTV.item
                elements = self.partsTV.get_children(selected)
                self.parent.clipboard_clear()
                for i in elements:
                    element = self.partsTV.item(i, "values")
                    self.parent.clipboard_append(element[0] + "\t" +
                                                 element[1] + "\n")
                self.parent.update()
                self.status.set("All properties of " +
                                self.partsTV.item(selected, "values")[3] +
                                " copied to clipboard")
            else:
                key = self.partsTV.item(selected, "values")[0]
                val = self.partsTV.item(selected, "values")[1]
                self.parent.clipboard_clear()
                self.parent.clipboard_append(val)
                self.parent.update()
                self.status.set(key + " '" + val + "' copied to clipboard")
        except Exception as e:
            pass

    def do_find(self, event):
        try:
            self.on_find()
        except Exception as e:
            self.status.seterror(e)
示例#35
0
            ('green', '#00FF00', (0,255,0)),
            ('magenta', '#FF00FF', (255,0,255)),
            ('cyan', '#00FFFF', (0,255,255)),
            ('foo', 'bar', 'bong', 'ding a ling ping'))

backg = ["white",'#f0f0ff']

fr0 = Frame(root)
fr0.pack(fill='both', expand=False)  #grid(column=0, row=0, sticky='nsew')  #

# create Treeview widget
tree = Treeview(fr0, column=tree_columns, show='headings',style='font.Treeview')
tree.grid(column=0, row=0, sticky='nsew')
tree.bind("<<TreeviewSelect>>", select_item)

vsb = Scrollbar(fr0,orient="vertical", command=tree.yview)
vsb.grid(column=1, row=0, sticky='ns')
hsb = Scrollbar(fr0,orient="horizontal", command=tree.xview)
hsb.grid(column=0, row=1,  sticky='ew')

tree.configure(xscrollcommand=hsb.set,yscrollcommand=vsb.set)
fr0.grid_columnconfigure(0, weight=1)
fr0.grid_rowconfigure(0, weight=1)

# insert header, data and tag configuration
for ix,col in enumerate(tree_columns):
    tree.heading(col, text=col.title(),
       command=lambda c=col: sort_by(tree, c, 0))
    #tree.column(col,stretch=True)
    #tree.column(col,width=font.nametofont('TkHeadingFont').measure(col.title()),
                #stretch=False)
    def __init__(self, mainWin, packageNamesWithNewerFileDates):
        super(DialogPackageManager, self).__init__(mainWin.parent)
        
        self.ENABLE = _("Enable")
        self.DISABLE = _("Disable")
        self.parent = mainWin.parent
        self.cntlr = mainWin
        
        # copy plugins for temporary display
        self.packagesConfig = PackageManager.packagesConfig
        self.packagesConfigChanged = False
        self.packageNamesWithNewerFileDates = packageNamesWithNewerFileDates
        
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", self.parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))

        self.title(_("Taxonomy Packages Manager"))
        frame = Frame(self)
        
        # left button frame
        buttonFrame = Frame(frame, width=40)
        buttonFrame.columnconfigure(0, weight=1)
        addLabel = Label(buttonFrame, text=_("Find taxonomy packages:"), wraplength=64, justify="center")
        addLocalButton = Button(buttonFrame, text=_("Locally"), command=self.findLocally)
        ToolTip(addLocalButton, text=_("File chooser allows selecting taxonomy packages to add (or reload), from the local file system.  "
                                       "Select either a taxonomy package zip file, or a taxonomy manifest (.taxonomyPackage.xml) within an unzipped taxonomy package.  "), wraplength=240)
        addWebButton = Button(buttonFrame, text=_("On Web"), command=self.findOnWeb)
        ToolTip(addWebButton, text=_("Dialog to enter URL full path to load (or reload) package, from the web or local file system.  "
                                     "URL may be either a taxonomy package zip file, or a taxonomy manifest (.taxonomyPackage.xml) within an unzipped taxonomy package.  "), wraplength=240)
        manifestNameButton = Button(buttonFrame, text=_("Manifest"), command=self.manifestName)
        ToolTip(manifestNameButton, text=_("Provide non-standard archive manifest file name pattern (e.g., *taxonomyPackage.xml).  "
                                           "Uses unix file name pattern matching.  "
                                           "Multiple manifest files are supported in archive (such as oasis catalogs).  "
                                           "(Replaces search for either .taxonomyPackage.xml or catalog.xml).  "), wraplength=240)
        self.manifestNamePattern = ""
        addLabel.grid(row=0, column=0, pady=4)
        addLocalButton.grid(row=1, column=0, pady=4)
        addWebButton.grid(row=2, column=0, pady=4)
        manifestNameButton.grid(row=3, column=0, pady=4)
        buttonFrame.grid(row=0, column=0, rowspan=3, sticky=(N, S, W), padx=3, pady=3)
        
        # right tree frame (packages already known to arelle)
        packagesFrame = Frame(frame, width=700)
        vScrollbar = Scrollbar(packagesFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(packagesFrame, orient=HORIZONTAL)
        self.packagesView = Treeview(packagesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=7)
        self.packagesView.grid(row=0, column=0, sticky=(N, S, E, W))
        self.packagesView.bind('<<TreeviewSelect>>', self.packageSelect)
        hScrollbar["command"] = self.packagesView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.packagesView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        packagesFrame.columnconfigure(0, weight=1)
        packagesFrame.rowconfigure(0, weight=1)
        packagesFrame.grid(row=0, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.packagesView.focus_set()

        self.packagesView.column("#0", width=120, anchor="w")
        self.packagesView.heading("#0", text=_("Name"))
        self.packagesView["columns"] = ("ver", "status", "date", "update", "descr")
        self.packagesView.column("ver", width=150, anchor="w", stretch=False)
        self.packagesView.heading("ver", text=_("Version"))
        self.packagesView.column("status", width=50, anchor="w", stretch=False)
        self.packagesView.heading("status", text=_("Status"))
        self.packagesView.column("date", width=170, anchor="w", stretch=False)
        self.packagesView.heading("date", text=_("File Date"))
        self.packagesView.column("update", width=50, anchor="w", stretch=False)
        self.packagesView.heading("update", text=_("Update"))
        self.packagesView.column("descr", width=200, anchor="w", stretch=False)
        self.packagesView.heading("descr", text=_("Description"))

        remappingsFrame = Frame(frame)
        vScrollbar = Scrollbar(remappingsFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(remappingsFrame, orient=HORIZONTAL)
        self.remappingsView = Treeview(remappingsFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=5)
        self.remappingsView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.remappingsView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.remappingsView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        remappingsFrame.columnconfigure(0, weight=1)
        remappingsFrame.rowconfigure(0, weight=1)
        remappingsFrame.grid(row=1, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.remappingsView.focus_set()
        
        self.remappingsView.column("#0", width=200, anchor="w")
        self.remappingsView.heading("#0", text=_("Prefix"))
        self.remappingsView["columns"] = ("remapping")
        self.remappingsView.column("remapping", width=500, anchor="w", stretch=False)
        self.remappingsView.heading("remapping", text=_("Remapping"))
        
        # bottom frame package info details
        packageInfoFrame = Frame(frame, width=700)
        packageInfoFrame.columnconfigure(1, weight=1)
        
        self.packageNameLabel = Label(packageInfoFrame, wraplength=600, justify="left", 
                                      font=font.Font(family='Helvetica', size=12, weight='bold'))
        self.packageNameLabel.grid(row=0, column=0, columnspan=6, sticky=W)
        self.packageVersionHdr = Label(packageInfoFrame, text=_("version:"), state=DISABLED)
        self.packageVersionHdr.grid(row=1, column=0, sticky=W)
        self.packageVersionLabel = Label(packageInfoFrame, wraplength=600, justify="left")
        self.packageVersionLabel.grid(row=1, column=1, columnspan=5, sticky=W)
        self.packageDescrHdr = Label(packageInfoFrame, text=_("description:"), state=DISABLED)
        self.packageDescrHdr.grid(row=2, column=0, sticky=W)
        self.packageDescrLabel = Label(packageInfoFrame, wraplength=600, justify="left")
        self.packageDescrLabel.grid(row=2, column=1, columnspan=5, sticky=W)
        self.packagePrefixesHdr = Label(packageInfoFrame, text=_("prefixes:"), state=DISABLED)
        self.packagePrefixesHdr.grid(row=3, column=0, sticky=W)
        self.packagePrefixesLabel = Label(packageInfoFrame, wraplength=600, justify="left")
        self.packagePrefixesLabel.grid(row=3, column=1, columnspan=5, sticky=W)
        ToolTip(self.packagePrefixesLabel, text=_("List of prefixes that this package remaps."), wraplength=240)
        self.packageUrlHdr = Label(packageInfoFrame, text=_("URL:"), state=DISABLED)
        self.packageUrlHdr.grid(row=4, column=0, sticky=W)
        self.packageUrlLabel = Label(packageInfoFrame, wraplength=600, justify="left")
        self.packageUrlLabel.grid(row=4, column=1, columnspan=5, sticky=W)
        ToolTip(self.packageUrlLabel, text=_("URL of taxonomy package (local file path or web loaded file)."), wraplength=240)
        self.packageDateHdr = Label(packageInfoFrame, text=_("date:"), state=DISABLED)
        self.packageDateHdr.grid(row=5, column=0, sticky=W)
        self.packageDateLabel = Label(packageInfoFrame, wraplength=600, justify="left")
        self.packageDateLabel.grid(row=5, column=1, columnspan=5, sticky=W)
        ToolTip(self.packageDateLabel, text=_("Date of currently loaded package file (with parenthetical node when an update is available)."), wraplength=240)
        self.packageEnableButton = Button(packageInfoFrame, text=self.ENABLE, state=DISABLED, command=self.packageEnable)
        ToolTip(self.packageEnableButton, text=_("Enable/disable package."), wraplength=240)
        self.packageEnableButton.grid(row=6, column=1, sticky=E)
        self.packageMoveUpButton = Button(packageInfoFrame, text=_("Move Up"), state=DISABLED, command=self.packageMoveUp)
        ToolTip(self.packageMoveUpButton, text=_("Move package up (above other remappings)."), wraplength=240)
        self.packageMoveUpButton.grid(row=6, column=2, sticky=E)
        self.packageMoveDownButton = Button(packageInfoFrame, text=_("Move Down"), state=DISABLED, command=self.packageMoveDown)
        ToolTip(self.packageMoveDownButton, text=_("Move package down (below other remappings)."), wraplength=240)
        self.packageMoveDownButton.grid(row=6, column=3, sticky=E)
        self.packageReloadButton = Button(packageInfoFrame, text=_("Reload"), state=DISABLED, command=self.packageReload)
        ToolTip(self.packageReloadButton, text=_("Reload/update package."), wraplength=240)
        self.packageReloadButton.grid(row=6, column=4, sticky=E)
        self.packageRemoveButton = Button(packageInfoFrame, text=_("Remove"), state=DISABLED, command=self.packageRemove)
        ToolTip(self.packageRemoveButton, text=_("Remove package from packages table (does not erase the package file)."), wraplength=240)
        self.packageRemoveButton.grid(row=6, column=5, sticky=E)
        packageInfoFrame.grid(row=2, column=0, columnspan=5, sticky=(N, S, E, W), padx=3, pady=3)
        packageInfoFrame.config(borderwidth=4, relief="groove")
        
        okButton = Button(frame, text=_("Close"), command=self.ok)
        ToolTip(okButton, text=_("Accept and changes (if any) and close dialog."), wraplength=240)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        ToolTip(cancelButton, text=_("Cancel changes (if any) and close dialog."), wraplength=240)
        okButton.grid(row=3, column=3, sticky=(S,E), pady=3)
        cancelButton.grid(row=3, column=4, sticky=(S,E), pady=3, padx=3)
        
        self.loadTreeViews()

        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(0, weight=0)
        frame.columnconfigure(1, weight=1)
        frame.rowconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        window.rowconfigure(0, weight=1)
        
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)
        
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
    def create_widgets(self, weight_name):
        ''' Creates all widgets.
        '''
        constraints_lbl = Label(
            self, text='Enter {0} weight restrictions:'.format(weight_name))
        constraints_lbl.grid(padx=10, pady=2, sticky=N + W)
        examples_lbl = Label(self, text='e.g. {0}'.format(self.examples))
        examples_lbl.grid(row=1, column=0, padx=10, pady=5, sticky=N + W)

        errors_lbl = Label(self,
                           textvariable=self.errors_strvar,
                           foreground='red',
                           anchor=W,
                           justify=LEFT,
                           wraplength=80)
        errors_lbl.grid(row=2, column=2, sticky=N + W, padx=5, pady=5)

        self.grid_rowconfigure(2, weight=1)
        self.grid_columnconfigure(0, weight=1)

        xscrollbar = Scrollbar(self, orient=HORIZONTAL)
        xscrollbar.grid(row=3, column=0, sticky=E + W)

        yscrollbar = Scrollbar(self)
        yscrollbar.grid(row=2, column=1, sticky=N + S)

        self.text = Text(self,
                         wrap=NONE,
                         width=TEXT_WIDTH_VAL,
                         height=TEXT_HEIGHT_VAL,
                         xscrollcommand=xscrollbar.set,
                         yscrollcommand=yscrollbar.set)

        self.text.grid(row=2, column=0, sticky=N + S + E + W)

        xscrollbar.config(command=self.text.xview)
        yscrollbar.config(command=self.text.yview)
示例#38
0
文件: main.py 项目: theseana/farcry
                                                           columnspan=2,
                                                           sticky=W + E)
# #################################################################### #
Label(s_search, text='Name').grid(row=0, column=0)
search_name = StringVar()
Entry(s_search, textvariable=search_name).grid(row=0, column=1)

Label(s_search, text='Family').grid(row=1, column=0)
search_family = StringVar()
Entry(s_search, textvariable=search_family).grid(row=1, column=1)

Button(s_search, text='Search', command=student_search).grid(row=0,
                                                             column=2,
                                                             rowspan=2)
tree = Treeview(s_search)
vsb = Scrollbar(s_search, orient="vertical", command=tree.yview)
vsb.grid(row=2, column=3)
tree.configure(yscrollcommand=vsb.set)
tree["columns"] = ("one", "two", "three")
tree.column("#0", width=30)
tree.column("one", width=80)
tree.column("two", width=100)
tree.column("three", width=90)
#############################################  update treeview --- serach select baham --- editable treeview
tree.heading("#0", text="ID", anchor=W)
tree.heading("one", text="Name")
tree.heading("two", text="Family")
tree.heading("three", text="Code", anchor=W)
persons = StudentSelect().get()
for person in persons:
    tree.insert("",
示例#39
0
    def __init__(self):
        self.root = Tk()
        self.root.title("PyCube")
        
        self.session = Session()
        
        # init UI
        self.initMenu()
        self.leftframe = Frame(self.root)
        self.leftframe.pack(side=LEFT, fill=BOTH, expand=1)
        
        self.rightframe = Frame(self.root)
        self.rightframe.pack(side=RIGHT, fill=BOTH, expand=1)
        
        self.cubesize = 3
        scrambler.parse(self.cubesize, 30, False, False)
        scrambler.scramble()
        self.scramble = Label(self.leftframe, text=scrambler.scramblestring(0))
        self.scramble.pack()

        self.time_label = Label(self.leftframe, text="0.000")
        self.time_label.pack()
        
        self.plus2_button = Button(self.leftframe, text="+2", command=self.plus2)
        self.plus2_button.pack()
        
        self.dnf_button = Button(self.leftframe, text="DNF", command=self.dnf)
        self.dnf_button.pack()
        
        self.delete_button = Button(self.leftframe, text="Delete", command=self.delete)
        self.delete_button.pack()
        
        self.scramble_img = Label(self.leftframe)
        self.scramble_img.pack()
        self.update_image()
        
        self.grid = Treeview(self.rightframe)
        self.grid["columns"] = ("times", "avg5", "avg12", "mean", "sd")
        self.grid.heading("#0", text='Time', anchor='w')
        self.grid.column("#0", stretch=NO, width=0, anchor="w")
        self.grid.heading("times", text="Times")
        self.grid.column('times', anchor='center', width=70)
        self.grid.heading("avg5", text="Avg. of 5")
        self.grid.column('avg5', anchor='center', width=70)
        self.grid.heading("avg12", text="Avg. of 12")
        self.grid.column('avg12', anchor='center', width=70)
        self.grid.heading("mean", text="Session mean")
        self.grid.column('mean', anchor='center', width=80)
        self.grid.heading("sd", text="SD")
        self.grid.column('sd', anchor='center', width=70)
        
        self.gridscroll = Scrollbar()
        self.gridscroll.configure(command=self.grid.yview)
        
        self.grid.configure(yscrollcommand=self.gridscroll.set)
        self.grid.pack(side=TOP)
        
        self.root.bind("<KeyRelease-space>", self.start_inspection)
        self._job = None
        self.running = False
        
        self.root.mainloop()
示例#40
0
class PyCube:
    
    def __init__(self):
        self.root = Tk()
        self.root.title("PyCube")
        
        self.session = Session()
        
        # init UI
        self.initMenu()
        self.leftframe = Frame(self.root)
        self.leftframe.pack(side=LEFT, fill=BOTH, expand=1)
        
        self.rightframe = Frame(self.root)
        self.rightframe.pack(side=RIGHT, fill=BOTH, expand=1)
        
        self.cubesize = 3
        scrambler.parse(self.cubesize, 30, False, False)
        scrambler.scramble()
        self.scramble = Label(self.leftframe, text=scrambler.scramblestring(0))
        self.scramble.pack()

        self.time_label = Label(self.leftframe, text="0.000")
        self.time_label.pack()
        
        self.plus2_button = Button(self.leftframe, text="+2", command=self.plus2)
        self.plus2_button.pack()
        
        self.dnf_button = Button(self.leftframe, text="DNF", command=self.dnf)
        self.dnf_button.pack()
        
        self.delete_button = Button(self.leftframe, text="Delete", command=self.delete)
        self.delete_button.pack()
        
        self.scramble_img = Label(self.leftframe)
        self.scramble_img.pack()
        self.update_image()
        
        self.grid = Treeview(self.rightframe)
        self.grid["columns"] = ("times", "avg5", "avg12", "mean", "sd")
        self.grid.heading("#0", text='Time', anchor='w')
        self.grid.column("#0", stretch=NO, width=0, anchor="w")
        self.grid.heading("times", text="Times")
        self.grid.column('times', anchor='center', width=70)
        self.grid.heading("avg5", text="Avg. of 5")
        self.grid.column('avg5', anchor='center', width=70)
        self.grid.heading("avg12", text="Avg. of 12")
        self.grid.column('avg12', anchor='center', width=70)
        self.grid.heading("mean", text="Session mean")
        self.grid.column('mean', anchor='center', width=80)
        self.grid.heading("sd", text="SD")
        self.grid.column('sd', anchor='center', width=70)
        
        self.gridscroll = Scrollbar()
        self.gridscroll.configure(command=self.grid.yview)
        
        self.grid.configure(yscrollcommand=self.gridscroll.set)
        self.grid.pack(side=TOP)
        
        self.root.bind("<KeyRelease-space>", self.start_inspection)
        self._job = None
        self.running = False
        
        self.root.mainloop()
        
    def initMenu(self):
        menubar = Menu(self.root)
        self.root.config(menu=menubar)
        
        fileMenu = Menu(menubar)
        fileMenu.add_command(label="New", command=self.session_new)
        fileMenu.add_separator()
        fileMenu.add_command(label="Import", command=self.session_import)
        fileMenu.add_command(label="Export", command=self.session_export)
        menubar.add_cascade(label="File", menu=fileMenu)
        
    def start_timer(self, event=None):
        if not self.running:
            self.root.after_cancel(self._job)
            self._job = None
            self.t0 = float("%.3f" % time.time())
            self.update_timer()
            self.running = True
            self.root.bind("<KeyPress-space>", self.reset_timer)
    
    def reset_timer(self, event=None):
        if self.running:
            self.root.after_cancel(self._job)
            self._job = None
            self.running = False
            self.root.bind("<KeyRelease-space>", self.rebind)
            
            t = self.time_label.cget("text")
            if ":" in str(t):
                mins, secs = t.split(":")
                t = (mins * 60) + secs
            self.session.addtime(t, 0, scrambler.scramblestring(0))
            
            entry = self.session.data[-1][1:]
            self.grid.insert("", "end", values=(entry))
            
            scrambler.parse(self.cubesize, 30, False, False)
            scrambler.scramble()
            scramblestr = scrambler.scramblestring(0)
            self.scramble.configure(text=scramblestr)
            self.update_image()
            
    def rebind(self, event=None):
        self.root.bind("<KeyRelease-space>", self.start_inspection)
        
    def update_timer(self):
        now = float("%.3f" % (time.time() - self.t0))
        if now > 60:
            mins = math.floor(now / 60)
            secs = now - (mins * 60)
            now = f"{mins}:{secs}"
        self.time_label.configure(text=now, fg="black")
        self._job = self.root.after(10, self.update_timer)
    
    def start_inspection(self, event=None):
        self.inspect_time = 16
        self.root.bind("<KeyRelease-space>", self.start_timer)
        self.update_inspection()
    
    def update_inspection(self):
        if self.inspect_time == 0:
            self.time_label.configure(text="DNF", fg="red")
            
            # Really ugly was to add a straight DNF, should fix later
            # NOTE: Known bug when first time is DNF. MUST FIX
            self.session.addtime(0, 2, scrambler.scramblestring(0))
            entry = self.session.data[-1][1:]
            self.grid.insert("", "end", values=(entry))
            self.dnf()
        else:
            self.inspect_time -= 1
            self.time_label.configure(text=self.inspect_time, fg="red")
            self._job = self.root.after(1000, self.update_inspection)
        
    def update_image(self):
        img = ImageTk.PhotoImage(genimage(scrambler.imagestring(0), self.cubesize))
        self.scramble_img.configure(image=img)
        self.scramble_img.image = img
    
    def delete(self, event=None):
        if len(self.session.data) > 0:
            last = self.session.getlastitemid()
            self.grid.delete(last)
            self.session.removetime(last) 
    
    def plus2(self, event=None):
        if len(self.session.data) > 0:
            last = self.session.getlastitemid()
            index = len(self.session.data) - 1
            entry = self.session.data[index]
            
            # Check if time isn't already +2 or DNF9
            if entry[6] != 0:
                return
            
            entry[1] = float("%.3f" % (entry[1] + 2))
            entry[6] = 1
            entry = self.session.calcstats()
            vals = entry[1:] + [scrambler.scramblestring(0)]
            vals[0] = str(vals[0]) + "(+2)"
            self.grid.item(last, values=(vals))
            
    def dnf(self, event=None):
        if len(self.session.data) > 0:
            last = self.session.getlastitemid()
            index = len(self.session.data) - 1
            entry = self.session.data[index]
            
            entry[1] = "DNF"
            entry[6] = 2
            
            entry = self.session.calcstats()
            vals = entry[1:]
            self.grid.item(last, values=(vals))
            
    def session_new(self):
        self.session.clear()
        self.grid.delete(*self.grid.get_children())
    
    def session_import(self):
        f = filedialog.askopenfilename(initialdir="../data/",
                                       title="Import session",
                                       filetypes=(("Text Documents", "*.txt"), ("All Files", "*.*")))
        if f == '':
            return
        with open(f) as file:
            self.session_new()
            self.session = Session(file.read())
            
            for entry in self.session.data:
                self.grid.insert("", "end", values=(entry[1:]))
    
    def session_export(self):
        if not os.path.isdir("../data/"):
            os.makedirs("../data/")
            
        name = str(datetime.now())[:-7].replace('-', '').replace(':', '').replace(' ', '')
        f = filedialog.asksaveasfilename(initialfile=name,
                                         initialdir="../data/",
                                         defaultextension="*.txt",
                                         title="Export session",
                                         filetypes=(("Text Documents","*.txt"), ("All Files","*.*")))
        if f == '':
            return
        with open(f, 'w') as file:
            file.write(str(self.session))
示例#41
0
    def init_kmerquery_guitab(self, master):
        row_gen = NumGenerator()

        irow = row_gen.get()
        infile_label, infile_entry, infile_button = gen_pickel_file_entry(
            master, 'Result File', 'Open file')
        infile_label.grid(row=irow, column=0, sticky='w')
        infile_entry.grid(row=irow, column=1, sticky='w')
        infile_button.grid(row=irow, column=2, sticky='w')

        irow = row_gen.get()
        kmer_info_label = Label(master, text='Input kmer list')
        kmer_info_label.grid(row=irow, column=0, sticky='w')

        irow = row_gen.get()
        kmer_input_txt = Text(master, width=32, height=10)
        kmer_input_txt.grid(row=irow,
                            column=0,
                            columnspan=3,
                            sticky="nsew",
                            padx=2,
                            pady=2)
        kmer_input_txt.insert(END, 'Input kmers here (one kmer per line)')

        # create a Scrollbar and associate it with txt
        kmer_scrollb = Scrollbar(master, command=kmer_input_txt.yview)
        kmer_scrollb.grid(row=irow, column=3, sticky='nsew')
        kmer_input_txt['yscrollcommand'] = kmer_scrollb.set

        irow = row_gen.get()
        output_info_label = Label(master, text='Output')
        output_info_label.grid(row=irow, column=0, sticky='w')

        # create a Text widget
        irow = row_gen.get()
        txt = Text(master, width=32, height=10)
        txt.grid(row=irow,
                 column=0,
                 columnspan=3,
                 sticky="nsew",
                 padx=2,
                 pady=2)

        # create a Scrollbar and associate it with txt
        scrollb = Scrollbar(master, command=txt.yview)
        scrollb.grid(row=irow, column=3, sticky='nsew')
        txt['yscrollcommand'] = scrollb.set

        def run_analysis():
            file = infile_entry.get()
            with open(file, 'rb') as f:
                fp = pickle.load(f)
            kc = fp.kmer_counter

            tmpstr = kmer_input_txt.get("1.0", "end-1c")
            kmer_list = tmpstr.split("\n")
            str_list = []
            for i, kmer in enumerate(kmer_list):
                tmpstr = f'line {i}, '
                if len(kmer) != kc.k:
                    tmpstr += f'{kmer}, kmer length must be {kc.k}. Return!'
                    txt.delete('1.0', END)
                    txt.insert(END, tmpstr)
                    return

            str_list = kc.disp_kmer_info(kmer_list=kmer_list)
            txt.delete('1.0', END)
            txt.insert(END, "\n".join(str_list))

        irow = row_gen.get()
        self.run_button = Button(master, text="RUN", command=run_analysis)
        self.run_button.grid(row=irow, column=1, pady=20, sticky='w')

        quit_button = Button(master, text="QUIT", command=self.master.destroy)
        quit_button.grid(row=irow, column=2, pady=20, sticky='w')

        master.columnconfigure(0, weight=5)
        master.columnconfigure(1, weight=10)
        master.columnconfigure(2, weight=5)
        master.columnconfigure(3, weight=1)
        master.rowconfigure(0, weight=1)
        master.rowconfigure(1, weight=1)
        master.rowconfigure(2, weight=3)
        master.rowconfigure(3, weight=1)
        master.rowconfigure(4, weight=3)
        master.rowconfigure(5, weight=1)
示例#42
0
    def create_widgets(self):
        self.frame = frame = Frame(self, borderwidth=2, relief='sunken')
        frame.pack(side='top', expand=True, fill='both')

        frame_buttons = Frame(self)
        frame_buttons.pack(side='bottom', fill='x')

        self.button_ok = Button(frame_buttons,
                                text='OK',
                                width=8,
                                command=self.ok)
        self.button_ok.grid(row=0, column=0, padx=5, pady=5)
        self.button_cancel = Button(frame_buttons,
                                    text='Cancel',
                                    width=8,
                                    command=self.cancel)
        self.button_cancel.grid(row=0, column=1, padx=5, pady=5)

        # Basic entry key sequence.
        self.frame_keyseq_basic = Frame(frame, name='keyseq_basic')
        self.frame_keyseq_basic.grid(row=0,
                                     column=0,
                                     sticky='nsew',
                                     padx=5,
                                     pady=5)
        basic_title = Label(self.frame_keyseq_basic,
                            text=f"New keys for '{self.action}' :")
        basic_title.pack(anchor='w')

        basic_keys = Label(self.frame_keyseq_basic,
                           justify='left',
                           textvariable=self.key_string,
                           relief='groove',
                           borderwidth=2)
        basic_keys.pack(ipadx=5, ipady=5, fill='x')

        # Basic entry controls.
        self.frame_controls_basic = Frame(frame)
        self.frame_controls_basic.grid(row=1, column=0, sticky='nsew', padx=5)

        # Basic entry modifiers.
        self.modifier_checkbuttons = {}
        column = 0
        for modifier, variable in zip(self.modifiers, self.modifier_vars):
            label = self.modifier_label.get(modifier, modifier)
            check = Checkbutton(self.frame_controls_basic,
                                command=self.build_key_string,
                                text=label,
                                variable=variable,
                                onvalue=modifier,
                                offvalue='')
            check.grid(row=0, column=column, padx=2, sticky='w')
            self.modifier_checkbuttons[modifier] = check
            column += 1

        # Basic entry help text.
        help_basic = Label(self.frame_controls_basic,
                           justify='left',
                           text="Select the desired modifier keys\n" +
                           "above, and the final key from the\n" +
                           "list on the right.\n\n" +
                           "Use upper case Symbols when using\n" +
                           "the Shift modifier.  (Letters will be\n" +
                           "converted automatically.)")
        help_basic.grid(row=1, column=0, columnspan=4, padx=2, sticky='w')

        # Basic entry key list.
        self.list_keys_final = Listbox(self.frame_controls_basic,
                                       width=15,
                                       height=10,
                                       selectmode='single')
        self.list_keys_final.insert('end', *AVAILABLE_KEYS)
        self.list_keys_final.bind('<ButtonRelease-1>', self.final_key_selected)
        self.list_keys_final.grid(row=0, column=4, rowspan=4, sticky='ns')
        scroll_keys_final = Scrollbar(self.frame_controls_basic,
                                      orient='vertical',
                                      command=self.list_keys_final.yview)
        self.list_keys_final.config(yscrollcommand=scroll_keys_final.set)
        scroll_keys_final.grid(row=0, column=5, rowspan=4, sticky='ns')
        self.button_clear = Button(self.frame_controls_basic,
                                   text='Clear Keys',
                                   command=self.clear_key_seq)
        self.button_clear.grid(row=2, column=0, columnspan=4)

        # Advanced entry key sequence.
        self.frame_keyseq_advanced = Frame(frame, name='keyseq_advanced')
        self.frame_keyseq_advanced.grid(row=0,
                                        column=0,
                                        sticky='nsew',
                                        padx=5,
                                        pady=5)
        advanced_title = Label(
            self.frame_keyseq_advanced,
            justify='left',
            text=f"Enter new binding(s) for '{self.action}' :\n" +
            "(These bindings will not be checked for validity!)")
        advanced_title.pack(anchor='w')
        self.advanced_keys = Entry(self.frame_keyseq_advanced,
                                   textvariable=self.key_string)
        self.advanced_keys.pack(fill='x')

        # Advanced entry help text.
        self.frame_help_advanced = Frame(frame)
        self.frame_help_advanced.grid(row=1, column=0, sticky='nsew', padx=5)
        help_advanced = Label(
            self.frame_help_advanced,
            justify='left',
            text="Key bindings are specified using Tkinter keysyms as\n" +
            "in these samples: <Control-f>, <Shift-F2>, <F12>,\n"
            "<Control-space>, <Meta-less>, <Control-Alt-Shift-X>.\n"
            "Upper case is used when the Shift modifier is present!\n\n" +
            "'Emacs style' multi-keystroke bindings are specified as\n" +
            "follows: <Control-x><Control-y>, where the first key\n" +
            "is the 'do-nothing' keybinding.\n\n" +
            "Multiple separate bindings for one action should be\n" +
            "separated by a space, eg., <Alt-v> <Meta-v>.")
        help_advanced.grid(row=0, column=0, sticky='nsew')

        # Switch between basic and advanced.
        self.button_level = Button(frame,
                                   command=self.toggle_level,
                                   text='<< Basic Key Binding Entry')
        self.button_level.grid(row=2, column=0, stick='ew', padx=5, pady=5)
        self.toggle_level()
示例#43
0
def run(*tests):
    root = tk.Tk()
    root.title('IDLE htest')
    root.resizable(0, 0)

    # a scrollable Label like constant width text widget.
    frameLabel = tk.Frame(root, padx=10)
    frameLabel.pack()
    text = tk.Text(frameLabel, wrap='word')
    text.configure(bg=root.cget('bg'), relief='flat', height=4, width=70)
    scrollbar = Scrollbar(frameLabel, command=text.yview)
    text.config(yscrollcommand=scrollbar.set)
    scrollbar.pack(side='right', fill='y', expand=False)
    text.pack(side='left', fill='both', expand=True)

    test_list = []  # List of tuples of the form (spec, callable widget)
    if tests:
        for test in tests:
            test_spec = globals()[test.__name__ + '_spec']
            test_spec['name'] = test.__name__
            test_list.append((test_spec, test))
    else:
        for k, d in globals().items():
            if k.endswith('_spec'):
                test_name = k[:-5]
                test_spec = d
                test_spec['name'] = test_name
                mod = import_module('idlelib.' + test_spec['file'])
                test = getattr(mod, test_name)
                test_list.append((test_spec, test))

    test_name = tk.StringVar(root)
    callable_object = None
    test_kwds = None

    def next_test():

        nonlocal test_name, callable_object, test_kwds
        if len(test_list) == 1:
            next_button.pack_forget()
        test_spec, callable_object = test_list.pop()
        test_kwds = test_spec['kwds']
        test_kwds['parent'] = root
        test_name.set('Test ' + test_spec['name'])

        text.configure(state='normal')  # enable text editing
        text.delete('1.0', 'end')
        text.insert("1.0", test_spec['msg'])
        text.configure(state='disabled')  # preserve read-only property

    def run_test(_=None):
        widget = callable_object(**test_kwds)
        try:
            print(widget.result)
        except AttributeError:
            pass

    def close(_=None):
        root.destroy()

    button = tk.Button(root,
                       textvariable=test_name,
                       default='active',
                       command=run_test)
    next_button = tk.Button(root, text="Next", command=next_test)
    button.pack()
    next_button.pack()
    next_button.focus_set()
    root.bind('<Key-Return>', run_test)
    root.bind('<Key-Escape>', close)

    next_test()
    root.mainloop()
示例#44
0
    def __init__(self,
                 parent,
                 openType,
                 filesource,
                 filenames,
                 title,
                 colHeader,
                 showAltViewButton=False,
                 multiselect=False):
        if isinstance(parent, Cntlr):
            cntlr = parent
            parent = parent.parent  # parent is cntlrWinMain
        else:  # parent is a Toplevel dialog
            cntlr = parent.cntlr
        super(DialogOpenArchive, self).__init__(parent)
        self.parent = parent
        self.showAltViewButton = showAltViewButton
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)",
                                  parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)

        frame = Frame(self)

        treeFrame = Frame(frame, width=500)
        vScrollbar = Scrollbar(treeFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL)
        self.treeView = Treeview(treeFrame,
                                 xscrollcommand=hScrollbar.set,
                                 yscrollcommand=vScrollbar.set)
        self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
        self.treeView.config(
            selectmode="extended" if multiselect else "browse")
        hScrollbar["command"] = self.treeView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E, W))
        vScrollbar["command"] = self.treeView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N, S))
        treeFrame.columnconfigure(0, weight=1)
        treeFrame.rowconfigure(0, weight=1)
        treeFrame.grid(row=0,
                       column=0,
                       columnspan=4,
                       sticky=(N, S, E, W),
                       padx=3,
                       pady=3)
        self.treeView.focus_set()

        if openType not in (PLUGIN, PACKAGE):
            cntlr.showStatus(_("loading archive {0}").format(filesource.url))
        self.filesource = filesource
        self.filenames = filenames
        self.selection = filesource.selection
        self.hasToolTip = False
        self.multiselect = multiselect
        selectedNode = None

        if openType == ENTRY_POINTS:
            try:
                metadataFiles = filesource.taxonomyPackageMetadataFiles
                ''' take first for now
                if len(metadataFiles) != 1:
                    raise IOError(_("Taxonomy package contained more than one metadata file: {0}.")
                                  .format(', '.join(metadataFiles)))
                '''
                metadataFile = metadataFiles[0]
                metadata = filesource.url + os.sep + metadataFile
                self.metadataFilePrefix = os.sep.join(
                    os.path.split(metadataFile)[:-1])
                if self.metadataFilePrefix:
                    self.metadataFilePrefix += "/"  # zip contents have /, never \ file seps
                self.taxonomyPkgMetaInf = '{}/META-INF/'.format(
                    os.path.splitext(os.path.basename(filesource.url))[0])

                self.taxonomyPackage = parsePackage(
                    cntlr, filesource, metadata,
                    os.sep.join(os.path.split(metadata)[:-1]) + os.sep)

                if self.taxonomyPackage["entryPoints"]:
                    # may have instance documents too
                    self.packageContainedInstances = []
                    self.packageContainedIXDSes = defaultdict(list)
                    packageContentInstanceCounts = {}
                    packageContentTypeCounts = {}
                    for suffix in (
                            ".xhtml", ".htm", ".html"
                    ):  # try for suffixes in order of likelihood to have instance
                        for potentialInstance in filesource.dir:
                            if potentialInstance.endswith(suffix):
                                m = reportIxdsPattern.match(
                                    potentialInstance)  # IXDS
                                if multiselect and m:  # only in ixds multiselect mode
                                    _type = "Inline Doc Set"
                                    self.packageContainedIXDSes[m.group(
                                        1)].append(potentialInstance)
                                    potentialInstance = m.group(
                                        1)  # use package name only
                                else:
                                    _type = "Inline Instance"
                                if not self.packageContainedInstances or self.packageContainedInstances[
                                        -1][0] != potentialInstance:
                                    self.packageContainedInstances.append(
                                        [potentialInstance, _type])
                                    packageContentInstanceCounts[
                                        potentialInstance] = packageContentInstanceCounts.get(
                                            potentialInstance, 0) + 1
                                    packageContentTypeCounts[
                                        _type] = packageContentTypeCounts.get(
                                            _type, 0) + 1
                        if self.packageContainedInstances:
                            break
                    if self.packageContainedInstances:  # add sequences to any duplicated entry types
                        for _type, count in packageContentTypeCounts.items():
                            if count > 1:
                                _dupNo = 0
                                for i in range(
                                        len(self.packageContainedInstances)):
                                    if self.packageContainedInstances[i][
                                            1] == _type:
                                        _dupNo += 1
                                        self.packageContainedInstances[i][
                                            1] = "{} {}".format(_type, _dupNo)
                        for _instance, count in packageContentInstanceCounts.items(
                        ):
                            if count > 1:
                                _dupNo = 0
                                for i in range(
                                        len(self.packageContainedInstances)):
                                    if self.packageContainedInstances[i][
                                            0] == _instance:
                                        _dupNo += 1
                                        self.packageContainedInstances[i][
                                            0] = "{} {}".format(
                                                _instance, _dupNo)

                else:
                    # may be a catalog file with no entry oint names
                    openType = ARCHIVE  # no entry points to show, just archive
                    self.showAltViewButton = False
            except Exception as e:
                self.close()
                err = _(
                    "Failed to parse metadata; the underlying error was: {0}"
                ).format(e)
                messagebox.showerror(_("Malformed taxonomy package"), err)
                cntlr.addToLog(err)
                return

        if openType not in (PLUGIN, PACKAGE):
            cntlr.showStatus(None)

        if openType in (DISCLOSURE_SYSTEM, PLUGIN, PACKAGE):
            y = 3
        else:
            y = 1

        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=2, sticky=(S, E, W), pady=3)
        cancelButton.grid(row=y, column=3, sticky=(S, E, W), pady=3, padx=3)

        if self.showAltViewButton:
            self.altViewButton = Button(frame, command=self.showAltView)
            self.altViewButton.grid(row=y,
                                    column=0,
                                    sticky=(S, W),
                                    pady=3,
                                    padx=3)

        self.loadTreeView(openType, colHeader, title)

        self.geometry("+{0}+{1}".format(dialogX + 50, dialogY + 100))
        frame.grid(row=0, column=0, sticky=(N, S, E, W))
        frame.columnconfigure(0, weight=1)
        frame.rowconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        window.rowconfigure(0, weight=1)

        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)

        self.toolTipText = StringVar()
        if self.hasToolTip:
            self.treeView.bind("<Motion>", self.motion, '+')
            self.treeView.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.treeView,
                                   textvariable=self.toolTipText,
                                   wraplength=640,
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipRowId = None

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()

        self.wait_window(self)
示例#45
0
    def __init__(self,
                 parent,
                 openType,
                 filesource,
                 filenames,
                 title,
                 colHeader,
                 showAltViewButton=False):
        if isinstance(parent, Cntlr):
            cntlr = parent
            parent = parent.parent  # parent is cntlrWinMain
        else:  # parent is a Toplevel dialog
            cntlr = parent.cntlr
        super(DialogOpenArchive, self).__init__(parent)
        self.parent = parent
        self.showAltViewButton = showAltViewButton
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)",
                                  parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)

        frame = Frame(self)

        treeFrame = Frame(frame, width=500)
        vScrollbar = Scrollbar(treeFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL)
        self.treeView = Treeview(treeFrame,
                                 xscrollcommand=hScrollbar.set,
                                 yscrollcommand=vScrollbar.set)
        self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.treeView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E, W))
        vScrollbar["command"] = self.treeView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N, S))
        treeFrame.columnconfigure(0, weight=1)
        treeFrame.rowconfigure(0, weight=1)
        treeFrame.grid(row=0,
                       column=0,
                       columnspan=4,
                       sticky=(N, S, E, W),
                       padx=3,
                       pady=3)
        self.treeView.focus_set()

        if openType not in (PLUGIN, PACKAGE):
            cntlr.showStatus(_("loading archive {0}").format(filesource.url))
        self.filesource = filesource
        self.filenames = filenames
        self.selection = filesource.selection
        self.hasToolTip = False
        selectedNode = None

        if openType == ENTRY_POINTS:
            try:
                metadataFiles = filesource.taxonomyPackageMetadataFiles
                ''' take first for now
                if len(metadataFiles) != 1:
                    raise IOError(_("Taxonomy package contained more than one metadata file: {0}.")
                                  .format(', '.join(metadataFiles)))
                '''
                metadataFile = metadataFiles[0]
                metadata = filesource.url + os.sep + metadataFile
                self.metadataFilePrefix = os.sep.join(
                    os.path.split(metadataFile)[:-1])
                if self.metadataFilePrefix:
                    self.metadataFilePrefix += "/"  # zip contents have /, never \ file seps
                self.taxonomyPkgMetaInf = '{}/META-INF/'.format(
                    os.path.splitext(os.path.basename(filesource.url))[0])

                self.taxonomyPackage = parsePackage(
                    cntlr, filesource, metadata,
                    os.sep.join(os.path.split(metadata)[:-1]) + os.sep)

                # may be a catalog file with no entry oint names
                if not self.taxonomyPackage["entryPoints"]:
                    openType = ARCHIVE  # no entry points to show, just archive
                    self.showAltViewButton = False
            except Exception as e:
                self.close()
                err = _(
                    "Failed to parse metadata; the underlying error was: {0}"
                ).format(e)
                messagebox.showerror(_("Malformed taxonomy package"), err)
                cntlr.addToLog(err)
                return

        if openType not in (PLUGIN, PACKAGE):
            cntlr.showStatus(None)

        if openType in (DISCLOSURE_SYSTEM, PLUGIN, PACKAGE):
            y = 3
        else:
            y = 1

        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=2, sticky=(S, E, W), pady=3)
        cancelButton.grid(row=y, column=3, sticky=(S, E, W), pady=3, padx=3)

        if self.showAltViewButton:
            self.altViewButton = Button(frame, command=self.showAltView)
            self.altViewButton.grid(row=y,
                                    column=0,
                                    sticky=(S, W),
                                    pady=3,
                                    padx=3)

        self.loadTreeView(openType, colHeader, title)

        self.geometry("+{0}+{1}".format(dialogX + 50, dialogY + 100))
        frame.grid(row=0, column=0, sticky=(N, S, E, W))
        frame.columnconfigure(0, weight=1)
        frame.rowconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        window.rowconfigure(0, weight=1)

        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)

        self.toolTipText = StringVar()
        if self.hasToolTip:
            self.treeView.bind("<Motion>", self.motion, '+')
            self.treeView.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.treeView,
                                   textvariable=self.toolTipText,
                                   wraplength=640,
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipRowId = None

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()

        self.wait_window(self)
class ScrolledWindow(Frame):
    """
    1. Master widget gets scrollbars and a canvas. Scrollbars are connected 
    to canvas scrollregion.

    2. self.scrollwindow is created and inserted into canvas

    Usage Guideline:
    Assign any widgets as children of <ScrolledWindow instance>.scrollwindow
    to get them inserted into canvas

    __init__(self, parent, canv_w = 400, canv_h = 400, *args, **kwargs)
    docstring:
    Parent = master of scrolled window
    canv_w - width of canvas
    canv_h - height of canvas

    """
    def __init__(self, parent, *args, **kwargs):
        """Parent = master of scrolled window
        canv_w - width of canvas
        canv_h - height of canvas

       """
        super().__init__(parent, *args, **kwargs)
        self.parent = parent
        self.canv_w = kwargs.get("width", 10)
        self.canv_h = kwargs.get("height", 10)
        # creating a scrollbars
        self.yscrlbr = Scrollbar(self.parent)
        self.yscrlbr.grid(column=1, row=0, sticky='ns')
        # creating a canvas
        self.canv = Canvas(self.parent)
        self.canv.config(relief='flat',
                         width=self.canv_w,
                         heigh=self.canv_h,
                         bd=2)
        # placing a canvas into frame
        self.canv.grid(column=0, row=0, sticky='nsew')
        # accociating scrollbar comands to canvas scroling
        self.yscrlbr.config(command=self.canv.yview)

        # creating a frame to inserto to canvas
        self.scrollwindow = Frame(self.parent)

        self.canv.create_window(0, 0, window=self.scrollwindow, anchor='nw')

        self.canv.config(yscrollcommand=self.yscrlbr.set,
                         scrollregion=(0, 0, self.canv_w, self.canv_h))

        self.yscrlbr.lift(self.scrollwindow)
        self.scrollwindow.bind('<Configure>', self._configure_window)
        self.scrollwindow.bind('<Enter>', self._bound_to_mousewheel)
        self.scrollwindow.bind('<Leave>', self._unbound_to_mousewheel)

        return

    def _bound_to_mousewheel(self, event):
        self.canv.bind_all("<MouseWheel>", self._on_mousewheel)

    def _unbound_to_mousewheel(self, event):
        self.canv.unbind_all("<MouseWheel>")

    def _on_mousewheel(self, event):
        self.canv.yview_scroll(int(-1 * (event.delta / 120)), "units")

    def _configure_window(self, event):
        # update the scrollbars to match the size of the inner frame
        size = (self.scrollwindow.winfo_reqwidth(),
                self.scrollwindow.winfo_reqheight())
        try:
            self.canv.config(scrollregion='0 0 %s %s' % size)
        except:
            return
        if self.scrollwindow.winfo_reqwidth() != self.canv.winfo_width():
            # update the canvas's width to fit the inner frame
            self.canv.config(
                width=min(self.scrollwindow.winfo_reqwidth(), self.canv_w))
        s_h = self.scrollwindow.winfo_reqheight()
        if s_h != self.canv.winfo_height():
            # update the canvas's width to fit the inner frame
            self.canv.config(height=min(s_h, self.canv_h))
示例#47
0
    def init_ui(self):
        self._win = tk.Tk()
        self._win.title("zk-client")
        self._win.geometry('900x700+500+300')
        self._win.resizable(height=False, width=False)
        tree_wrapper = tk.Frame(self._win, bg='red', width=300)
        tree_wrapper.pack(side=tk.LEFT, fill=tk.Y)

        canvas = self._tree_canvas = tk.Canvas(tree_wrapper,
                                               width=300,
                                               height=700,
                                               scrollregion=(0, 0, 300, 700),
                                               bg='gray')  # 创建canvas
        canvas.place(x=0, y=0)  # 放置canvas的位置

        frame = tk.Frame(canvas)  # 把frame放在canvas里
        # frame.place(width=180, height=600)  # frame的长宽,和canvas差不多的
        vbar = Scrollbar(canvas, orient=tk.VERTICAL)  # 竖直滚动条
        vbar.place(x=281, width=20, height=700)
        vbar.configure(command=canvas.yview)
        hbar = Scrollbar(canvas, orient=tk.HORIZONTAL)  # 水平滚动条
        hbar.place(x=0, y=680, width=280, height=20)
        hbar.configure(command=canvas.xview)
        canvas.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set)  # 设置
        canvas.bind_all(
            "<MouseWheel>", lambda event: canvas.yview_scroll(
                int(-1 * (event.delta / 120)), "units"))

        self._tree_frame_id = canvas.create_window(
            0, 0, window=frame, anchor='nw')  # create_window)

        self._root = Treeview(frame)
        #
        self._root.pack(expand=True, fill=tk.BOTH)
        # self._root.bind("<Button-1>", self.clear_pre_selected)
        # self._root.bind("<< TreeviewClose>>", self.clear_pre_selected)
        self._root.bind("<<TreeviewOpen>>", self.open_node)
示例#48
0
 def set(self, lo, hi):
     if float(lo) <= 0.0 and float(hi) >= 1.0:
         self.grid_remove()
     else:
         self.grid()
     Scrollbar.set(self, lo, hi)
示例#49
0
    def __init__(self, parent=None, app_window=None):
        self.lastValue = None
        self.category_option = StringVar("")
        self.column_id = [
            'ProductDescription', 'ManufacturerName', 'ManufacturerPartNumber',
            'DigiKeyPartNumber', 'Category'
        ]
        Frame.__init__(self, parent)
        self.pack()
        self.parent = parent
        self.app_window = app_window
        self.selectedField = None

        self.parent.title("Partlocater - Advanced Database Search")
        self.parent.iconbitmap(self.FAVICON)
        self.menubar = Frame(self, background='white')

        self.menubar.pack(side=TOP, fill=X, expand=YES)
        self.win_frame = Frame(self)
        self.win_frame.pack(side=TOP, fill=BOTH, expand=YES)
        self.editbutton = Menubutton(self.menubar,
                                     text='Edit',
                                     background='grey98')
        self.editbutton.pack(side=LEFT, fill=X)
        self.editmenu = Menu(self.editbutton, tearoff=0)
        self.editbutton.config(menu=self.editmenu)
        self.copySourcesMenu = Menu(self.editbutton, tearoff=0)
        self.editmenu.add_cascade(label='Copy', menu=self.copySourcesMenu)
        self.copySourcesMenu.add_command(label='Part Number',
                                         state=DISABLED,
                                         command=self.on_copy_partnumber)
        self.partnumber_index = 0
        self.copySourcesMenu.add_command(label='Selected Parameter',
                                         state=DISABLED,
                                         command=self.on_copy_parameters)
        self.selectedParameter_index = 1
        self.copySourcesMenu.add_command(label='Selected Part All Parameters',
                                         state=DISABLED,
                                         command=self.on_copy_all_parameters)
        self.allParameters_index = 2
        self.editmenu.add_command(label='Delete Part',
                                  state=DISABLED,
                                  command=self.on_delete)

        self.searchLF = LabelFrame(self.win_frame, text="Search")
        self.searchLF.pack(side=LEFT, fill=X, expand=YES, pady=4, padx=6)
        self.searchLeftF = Frame(self.searchLF)
        self.searchLeftF.pack(side=LEFT, anchor=W)
        self.searchRightF = Frame(self.searchLF)
        self.searchRightF.pack(side=LEFT, anchor=N)
        self.searchLabelWidth = 20
        self.catF = Frame(self.searchLeftF)
        self.catF.pack(side=TOP, anchor=W)
        self.catL = Label(self.catF,
                          text='Category',
                          width=self.searchLabelWidth,
                          anchor=W,
                          justify=LEFT)
        self.catL.pack(side=LEFT, fill=X, expand=YES)
        self.cat = StringVar()
        self.catE = Entry(self.catF,
                          textvariable=self.cat,
                          width=50,
                          state=DISABLED)
        self.catE.config(disabledbackground=self.catE.cget("bg"))
        self.catE.config(disabledforeground=self.catE.cget("fg"))
        self.catE.pack(side=LEFT, fill=X, expand=YES, pady=4)
        self.category_option = StringVar()
        self.cat.set("All")
        option_list = ['All', 'All'] + Config().tables
        self.catM = OptionMenu(self.searchRightF,
                               self.category_option,
                               *option_list,
                               command=self.on_category)
        self.catM.pack(side=TOP, anchor=N, fill=X, expand=YES)

        self.manF = Frame(self.searchLeftF)
        self.manF.pack(side=TOP, anchor=W)
        self.manL = Label(self.manF,
                          text='ManufacturerName',
                          width=self.searchLabelWidth,
                          anchor=W,
                          justify=LEFT)
        self.manL.pack(side=LEFT, fill=X, expand=YES, pady=4)
        self.man = StringVar()
        self.manE = Entry(self.manF, width=50, textvariable=self.man)
        self.manE.pack(side=LEFT, fill=X, expand=YES, pady=4)

        self.mpnF = Frame(self.searchLeftF)
        self.mpnF.pack(side=TOP, anchor=W)
        self.mpnL = Label(self.mpnF,
                          text='ManufacturerPartNumber',
                          width=self.searchLabelWidth,
                          anchor=W,
                          justify=LEFT)
        self.mpnL.pack(side=LEFT, fill=X, expand=YES, pady=4)
        self.mpn = StringVar()
        self.mpnE = Entry(self.mpnF, width=50, textvariable=self.mpn)
        self.mpnE.pack(side=LEFT, fill=X, expand=YES, pady=4)

        self.spnF = Frame(self.searchLeftF)
        self.spnF.pack(side=TOP, anchor=W)
        self.spnL = Label(self.spnF,
                          text='DigiKeyPartNumber',
                          width=self.searchLabelWidth,
                          anchor=W,
                          justify=LEFT)
        self.spnL.pack(side=LEFT, fill=X, expand=YES, pady=4)
        self.spn = StringVar()
        self.spnE = Entry(self.spnF, width=50, textvariable=self.spn)
        self.spnE.pack(side=LEFT, fill=X, expand=YES, pady=4)

        self.descF = Frame(self.searchLeftF)
        self.descF.pack(side=TOP, anchor=W)
        self.descL = Label(self.descF,
                           text='ProductDescription',
                           width=self.searchLabelWidth,
                           anchor=W,
                           justify=LEFT)
        self.descL.pack(side=LEFT, fill=X, expand=YES, pady=4)
        self.desc = StringVar()
        self.descE = Entry(self.descF, width=50, textvariable=self.desc)
        self.descE.pack(side=LEFT, fill=X, expand=YES, pady=4)
        self.descE.focus_force()

        self.findF = Frame(self.searchLeftF)
        self.findF.pack(side=TOP, anchor=E)
        self.findB = ttk.Button(self.findF,
                                text="Find",
                                width=12,
                                command=lambda event=None: self.do_find(event))
        self.findB.pack(side=LEFT, pady=4)
        self.clearB = ttk.Button(self.findF,
                                 text="Clear",
                                 width=6,
                                 command=self.on_clear_search)
        self.clearB.pack(side=LEFT, pady=4)

        self.partsLF = LabelFrame(self, text="Found Components")
        self.partsLF.pack(side=TOP, fill=X, expand=YES, pady=4, padx=4)
        self.partsF = Frame(self.partsLF)
        self.partsF.pack(side=TOP, pady=4, padx=4)
        # change treeview for search here
        self.partsTV = Treeview(self.partsF,
                                selectmode=BROWSE,
                                show='tree headings',
                                columns=self.column_id)

        self.partsTV.bind('<Double-Button-1>', self.on_edit_item)
        self.partsTV.bind('<<TreeviewSelect>>', self.fieldChanged)
        self.partsTV.bind('<Escape>', self.clearSelection)
        self.partsTV.bind('<MouseWheel>', self.mousewheel)
        self.partsTV.bind('<Button-4>', self.mousewheel)
        self.partsTV.bind('<Button-5>', self.mousewheel)
        vcmd = (self.register(self.validateEntry), '%P')
        self.editfield = ttk.Entry(self.partsTV,
                                   validate='key',
                                   validatecommand=vcmd)
        self.editfield.bind('<Return>', self.updateField)
        self.editfield.bind('<Escape>', self.clearSelection)

        self.partsTV.bind('<Control-c>', self.on_copy_element)
        self.partsTV.column("#0", minwidth=0, width=18, stretch=NO)
        for t in self.column_id:
            self.partsTV.heading(t, text=Config().parameter[t])
        self.partsTV.column('Category', width=60)
        self.scrollbar = Scrollbar(self.partsF,
                                   orient='vertical',
                                   command=self.partsTV.yview)
        self.scrollbar.pack(side=RIGHT, fill=Y, expand=YES, anchor=E)
        self.partsTV.configure(yscroll=self.scrollbar.set)
        self.scrollbar.config(command=self.yview)

        self.partsTV.pack(side=TOP, anchor=W, fill=X, expand=YES)
        self.partsTV.delete(*self.partsTV.get_children())
        # end change of treeview
        # change the following to menu item
        #self.part_buttonF = Frame(self.partsLF)
        #self.delete_partB = ttk.Button(self.partsLF, text="Delete Part from Database", command=self.on_delete,
        #state=DISABLED)
        #self.delete_partB.pack(side=RIGHT, anchor=W, expand=NO, pady=4, padx=6)
        #self.partsB = ttk.Button(self.partsLF, text="Copy Selected To Part Find", command=self.on_copy, state=DISABLED)
        #self.partsB.pack(side=RIGHT, anchor=W, expand=NO, pady=4, padx=6)
        #self.part_buttonF.pack(side=BOTTOM)
        # start remove vvv
        #self.element_labelframe = LabelFrame(self, text="Modify Name/Value")
        #self.element_labelframe.pack(side=TOP, fill=X, expand=YES, pady=4, padx=6)
        #self.element_frame = Frame(self.element_labelframe)
        #self.element_frame.pack(side=TOP)

        #self.element_name = StringVar()
        #self.element_label = Label(self.element_frame, textvariable=self.element_name, width=30, anchor=W, justify=LEFT)
        #self.element_label.pack(side=LEFT, anchor=W, fill=X, expand=YES, pady=4)
        #self.element_value = StringVar()
        #self.element_entry = Entry(self.element_frame, width=50, textvariable=self.element_value)
        #self.element_entry.pack(side=LEFT, fill=X, expand=YES, pady=4)
        #self.default_color = self.element_entry.cget('background')

        #self.element_update = ttk.Button(self.element_frame, text="Update", command=self.on_update_element,
        #state=DISABLED)
        #self.element_update.pack(side=LEFT, fill=X, expand=YES, pady=4)
        #self.element_cancel = ttk.Button(self.element_frame, text="Cancel", command=self.on_clear_element,
        #state=DISABLED)
        #self.element_cancel.pack(side=LEFT, fill=X, expand=YES, pady=4)
        # end remove ^^^

        self.statusLF = LabelFrame(self, text="Status")
        self.statusLF.pack(side=BOTTOM, fill=X, expand=YES, pady=4, padx=6)
        self.statusF = Frame(self.statusLF)
        self.statusF.pack(side=TOP, fill=X, expand=YES, padx=6)
        self.status = self.StatusBar(self.statusF, self)
示例#50
0
class GraphicalUserInterface(Frame):
    """
    Graphical User Interface class
    """
    # constant tag names
    STRONG = "STRONG"
    ITALIC = "ITALIC"
    HIGHLIGHT = "HIGHLIGHT"

    window_title = "DiAnnotator"  # window title

    padding = config.get_int("padding", 25)  # padding for text area")
    wrap_length = config.get_int(
        "wrap_length", 960)  # max length of labels before automatic newline")

    # text parameters
    text_font_family = config.get_string("text_font_family", "mono")
    text_font_size = config.get_int("text_font_size", 12)
    text_font_weight = config.get_string("text_font_weight", "normal")
    text_foreground = config.get_string("text_foreground", "#ffffff")
    text_background = config.get_string("text_background", "#171717")

    # label parameters
    label_font_family = config.get_string("label_font_family", "mono")
    label_font_size = config.get_int("label_font_size", 12)
    label_font_weight = config.get_string("label_font_weight", "normal")

    # entry parameters
    entry_font_family = config.get_string("entry_font_family", "TkDefaultFont")
    entry_font_size = config.get_int("entry_font_size", 14)
    entry_font_weight = config.get_string("entry_font_weight", "normal")

    # menu parameters
    menu_font_family = config.get_string("menu_font_family", "modern")

    # button parameters
    button_font_family = config.get_string("button_font_family", "modern")

    # special button parameters
    special_button_font_family = config.get_string(
        "special_button_font_family", "mono")
    special_button_font_size = config.get_int("special_button_font_size", 11)
    special_button_font_weight = config.get_string(
        "special_button_font_weight", "bold")
    special_button_active = config.get_string("special_button_active",
                                              "#353131")

    # prompt parameters
    prompt_font_family = config.get_string("prompt_font_family", "modern")
    prompt_font_size = config.get_int("prompt_font_size", 12)
    prompt_font_weight = config.get_string("prompt_font_weight", "bold")

    # selection parameters
    select_background = config.get_string("select_background", "#332f2f")

    # highlight parameters
    highlight_background = config.get_string("highlight_background", "#332f2f")

    special_button_style = "Special.TButton"

    def __init__(self):
        """
        Initializes the graphical user interface
        """
        # main interface object
        self.parent = Tk()
        self.parent.state = False

        # strings manager
        strings = Strings()
        self._ = strings.get

        # theme
        style = ThemedStyle(self.parent)
        style.set_theme("arc")

        # button style
        style.configure("TButton", font=self.button_font_family)

        # special button style
        style.configure(self.special_button_style,
                        font=(self.special_button_font_family,
                              self.special_button_font_size,
                              self.special_button_font_weight))

        # make buttons change foreground when hovered
        style.map("TButton",
                  foreground=[("active", self.special_button_active)])

        # root window initialization
        Frame.__init__(self, self.parent)

        w = config.get_int("minimum_window_width",
                           1280)  # minimum width for the Tk parent
        h = config.get_int("minimum_window_height",
                           800)  # minimum height for the Tk parent

        # get screen width and height
        ws = self.parent.winfo_screenwidth()  # width of the screen
        hs = self.parent.winfo_screenheight()  # height of the screen

        self.parent.geometry("%dx%d+0+0" %
                             (ws, hs))  # set the dimensions of the window
        self.parent.minsize(w, h)  # minimum size of the window

        # window title
        self.parent.title(self.window_title)

        # menu bar
        self.menu_bar = Menu(self.parent, font=self.menu_font_family)

        self.file_menu = Menu(self.menu_bar,
                              tearoff=0,
                              font=self.menu_font_family)
        self.menu_bar.add_cascade(label=self._("menu.cascade.file"),
                                  menu=self.file_menu)

        self.edit_menu = Menu(self.menu_bar,
                              tearoff=0,
                              font=self.menu_font_family)
        self.menu_bar.add_cascade(label=self._("menu.cascade.edit"),
                                  menu=self.edit_menu)

        self.view_menu = Menu(self.menu_bar,
                              tearoff=0,
                              font=self.menu_font_family)
        self.menu_bar.add_cascade(label=self._("menu.cascade.view"),
                                  menu=self.view_menu)
        self.view_menu.add_command(label=self._("menu.zoom_in"),
                                   accelerator="Ctrl++",
                                   command=self.zoom_in)
        self.view_menu.add_command(label=self._("menu.zoom_out"),
                                   accelerator="Ctrl+-",
                                   command=self.zoom_out)

        self.filter_menu = Menu(self.menu_bar,
                                tearoff=0,
                                font=self.menu_font_family)
        self.menu_bar.add_cascade(label=self._("menu.cascade.filter"),
                                  menu=self.filter_menu)

        self.taxonomy_menu = Menu(self.menu_bar,
                                  tearoff=0,
                                  font=self.menu_font_family)
        self.menu_bar.add_cascade(label=self._("menu.cascade.taxonomy"),
                                  menu=self.taxonomy_menu)

        self.parent.config(menu=self.menu_bar)

        # make the frame take the whole window
        self.pack(fill=BOTH, expand=1)

        # input frame
        self.input_frame = None

        # output frame
        self.output_frame = Frame(self)
        self.output_frame.pack(fill=BOTH, anchor=N, expand=1)
        self.output_frame.grid_propagate(False)  # ensure a consistent GUI size
        self.output_frame.grid_rowconfigure(
            0, weight=30)  # implement stretchability
        self.output_frame.grid_rowconfigure(
            1, weight=1)  # implement stretchability
        self.output_frame.grid_columnconfigure(0, weight=1)
        self.text = Text(self.output_frame,
                         borderwidth=3,
                         relief=SUNKEN,
                         cursor="arrow",
                         selectbackground=self.select_background,
                         inactiveselectbackground=self.select_background)

        # Text widget
        self.text.grid(row=0,
                       column=0,
                       sticky="nsew",
                       padx=self.padding,
                       pady=(self.padding, 0))
        self.text.config(font=(self.text_font_family, self.text_font_size),
                         undo=True,
                         wrap=WORD,
                         bg=self.text_background,
                         fg=self.text_foreground,
                         state=DISABLED)

        # create a Scrollbar and associate it with text
        self.scrollbar = Scrollbar(self.output_frame, command=self.text.yview)
        self.scrollbar.grid(row=0, rowspan=3, column=1, sticky=NSEW)
        self.text["yscrollcommand"] = self.scrollbar.set

        # status bar
        self.status = Label(self.output_frame,
                            font=(self.label_font_family, self.label_font_size,
                                  "bold"))
        self.status.grid(row=1, column=0, pady=0)

        # binds any typing to the command input field to the update_commands method
        sv = StringVar()
        sv.trace("w", lambda name, index, mode, sv=sv: self.update_commands())

        # input frame
        self.input_frame = Frame(self)
        self.input_frame.pack(fill=X, side=BOTTOM)

        # makes the command input field
        self.entry = Entry(self.input_frame,
                           font=(self.entry_font_family, self.entry_font_size),
                           textvariable=sv,
                           state=DISABLED)
        self.entry.bind(
            "<Return>", self.return_pressed
        )  # binds the Return key to the return_pressed() method
        self.entry.bind(
            "<KP_Enter>", self.return_pressed
        )  # binds the Return key to the return_pressed() method
        self.entry.bind(
            "<Tab>",
            self.tab_pressed)  # binds the Tab key to the tab_pressed() method
        self.entry.pack(fill=X, side=BOTTOM, padx=2,
                        pady=2)  # places the input field
        self.entry.focus_set()  # sets the focus on the input field

        # creates the frame containing buttons
        self.commands = Frame(self.input_frame)
        self.commands.pack(fill=X, side=BOTTOM)

        self.prompt = StringVar()
        self.prompt_label = Label(self.commands,
                                  font=(self.prompt_font_family,
                                        self.prompt_font_size,
                                        self.prompt_font_weight),
                                  textvariable=self.prompt)
        self.prompt_label.pack(side=LEFT, padx=(10, 15), pady=10)

        # creates the frame containing special buttons
        self.special_commands = Frame(self.input_frame)
        self.special_commands.pack(fill=X, side=BOTTOM)

        # default bindings
        self.parent.bind(config.get_string("toggle_fullscreen", "<F11>"),
                         lambda event: self.toggle_fullscreen())
        self.parent.bind(config.get_string("exit_prompt", "<Escape>"),
                         lambda event: self.exit_prompt())
        self.parent.bind(config.get_string("zoom_in", "<Control-KP_Add>"),
                         lambda event: self.zoom_in())
        self.parent.bind(
            config.get_string("zoom_out", "<Control-KP_Subtract>"),
            lambda event: self.zoom_out())

        # binding mouse clicks and movement
        self.text.bind("<Button-1>", self.record_click)
        self.text.bind("<Button-2>", self.record_click)
        self.clickable_text_tag = "clickable_text_tag"
        self.text.bind("<ButtonRelease-1>", self.mouse_left_click)
        self.text.bind("<ButtonRelease-3>", self.mouse_right_click)
        self.text.bind("<Motion>", self.mouse_motion)

        self.last_click_index = "1.0"
        self.last_release_index = "1.0"

        self.command_list = []  # list of potential commands

        self.action = None  # default command action
        self.default_action = None  # default command action

        self.free_input = False  # sets whether it's possible to input anything in the entry

        # basic text tags

        self.add_tag(GraphicalUserInterface.STRONG, font_weight="bold")
        self.add_tag(GraphicalUserInterface.ITALIC, font_weight="italic")
        self.add_tag(GraphicalUserInterface.HIGHLIGHT,
                     background=self.highlight_background)

        self.text.tag_raise(SEL)  # makes sure the selection is fisible

    ############################
    # MOUSE MANAGEMENT METHODS #
    ############################

    def record_click(self, event):
        """
        Records last click index
        """
        index = self.text.index("@%s,%s" % (event.x, event.y))
        self.last_click_index = index

    def record_release(self, event):
        """
        Records last click release index
        """
        index = self.text.index("@%s,%s" % (event.x, event.y))
        self.last_release_index = index

    def mouse_motion(self, event):
        """
        Returns data when the cursor is on a clickable element
        """
        start, end, text = self.examine_mouse_position(event)
        self.manage_motion(start, end, text)

    def mouse_left_click(self, event):
        """
        Returns data when the user left clicks on a clickable element
        """
        self.record_release(event)

        start, end, text = self.examine_mouse_position(event)
        self.manage_left_click(start, end, event.x_root, event.y_root, text)

    def mouse_right_click(self, event):
        """
        Returns data when the user right clicks on a clickable element
        """
        self.record_release(event)

        start, end, text = self.examine_mouse_position(event)
        self.manage_right_click(start, end, event.x_root, event.y_root, text)

    def examine_mouse_position(self, event):
        """
        Examines the mouse position and returns data if a clickable element is hovered
        """
        # get the index of the mouse click
        index = self.text.index("@%s,%s" % (event.x, event.y))

        # get the indices of all clickable text tags
        tag_indices = list(self.text.tag_ranges(self.clickable_text_tag))

        # iterate them pairwise (start and end index)
        for start, end in zip(tag_indices[0::2], tag_indices[1::2]):
            # check if the tag matches the mouse click index
            if self.text.compare(start, '<=', index) and self.text.compare(
                    index, '<', end):
                # deals with string between tag start and end
                return start, end, self.text.get(start, end)

        return None, None, None

    def manage_motion(self, start, end, text):
        """
        Mouse motion management
        """
        pass  # pass on purpose

    def manage_left_click(self, start, end, x, y, text):
        """
        Mouse left click management
        """
        pass  # pass on purpose

    def manage_right_click(self, start, end, x, y, text):
        """
        Mouse right click management
        """
        pass  # pass on purpose

    ###############################
    # KEYBOARD MANAGEMENT METHODS #
    ##############################

    def return_pressed(self, e):
        """
        Handles presses of the Return key
        """
        focus = self.parent.focus_get()

        if focus == self.entry:
            # if the input is free, the entry content is captured; else the only corresponding command is captured
            if self.free_input:
                text = self.entry.get()
                self.entry.delete(0, END)  # clears the entry field
                self.process_input(text)
            elif len(self.entry.get()) == 0:
                self.default_action()  # default action
            else:
                # list of buttons in the button list
                commands = self.commands.winfo_children()

                # if there is only one button (plus label), invokes it's function
                if len(commands) == 2:
                    self.commands.winfo_children()[1].invoke()
        else:
            for button in self.commands.winfo_children():
                if focus == button:
                    self.button_pressed(button.cget("text"))

    def tab_pressed(self, e):
        """
        Handles presses of the Tab key
        """
        self.entry.focus_set()  # sets the focus on the input field

    ############################
    # INPUT MANAGEMENT METHODS #
    ############################

    def button_pressed(self, b):
        """
        Activates command buttons
        """
        self.entry.delete(0, END)  # clears the entry field
        self.process_input(
            b
        )  # processes input corresponding to the button to the output canvas

    def process_input(self, t):
        """
        Processes user input
        """
        self.free_input = False
        self.action(t)

    ##############################
    # DISPLAY MANAGEMENT METHODS #
    ##############################

    def update_status_message(self, text):
        """
        Status message
        """
        self.status.config(text=text)

    def update_commands(self):
        """
        Updates the command button list
        """
        for element in self.commands.winfo_children():
            if isinstance(element, Button):
                element.destroy()

        input_text = self.entry.get()

        match = None

        for cmd in self.command_list:
            if cmd.lower() == input_text.lower():
                match = cmd

        # if only one match
        if match:
            self.make_button(match)
        else:
            chunks = input_text.split(" ")

            for s in self.command_list:
                # only if the input text can correspond to the command
                if len([c for c in chunks
                        if c.lower() in s.lower()]) == len(chunks):
                    self.make_button(s)

    def make_button(self, text, disabled=False):
        b = Button(self.commands,
                   text=text,
                   command=lambda n=text: self.button_pressed(n))
        b.bind("<Return>", self.return_pressed
               )  # binds the Return key to the return_pressed method
        b.pack(side=LEFT)

        if disabled:
            b.config(state=DISABLED)

    def toggle_fullscreen(self):
        """
        Toggles between windowed and fullscreen
        """
        self.parent.state = not self.parent.state  # Just toggling the boolean
        self.parent.attributes("-fullscreen", self.parent.state)

        return "break"

    def exit_prompt(self):
        """
        Show an exit prompt
        """
        if messagebox.askyesno(self._("box.title.quit"),
                               self._("box.text.quit")):
            self.parent.destroy()

    ###########################
    # TEXT MANAGEMENT METHODS #
    ###########################

    def select(self, start, end):
        """
        Selects text
        """
        self.text.tag_add(SEL, start, end)
        self.text.mark_set(INSERT, "1.0")

    def zoom_in(self):
        """
        Increases Text widget font
        """
        if self.text_font_size < 20:
            self.text_font_size += 1
            self.update_font_size()

    def zoom_out(self):
        """
        Decreases Text widget font
        """
        if self.text_font_size > 8:
            self.text_font_size -= 1
            self.update_font_size()

    def update_font_size(self):
        """
        Updates Text widget font size
        """
        self.text.config(font=(self.text_font_family, self.text_font_size))
        self.text.tag_config(GraphicalUserInterface.STRONG,
                             font=(self.text_font_family, self.text_font_size,
                                   "bold"))
        self.text.tag_config(GraphicalUserInterface.ITALIC,
                             font=(self.text_font_family, self.text_font_size,
                                   "italic"))

    def clear_screen(self):
        """
        Clears the text widget
        """
        self.text.config(state=NORMAL)  # makes the text editable
        self.text.delete("1.0", self.text.index(END))
        self.text.config(state=DISABLED)  # makes the text editable

    def clear_last_line(self):
        """
        Clears the last line
        """
        self.text.config(state=NORMAL)  # makes the text editable
        self.text.delete("end-{}c linestart".format(self.previous_line_length),
                         self.text.index(END))
        self.text.config(state=DISABLED)  # makes the text editable

        self.add_blank_lines(1)

    def highlight_last_line(self):
        """
        Highlights the last line
        """
        start = "{}.{}".format(int(self.text.index(END).split(".")[0]) - 2,
                               0)  # start position of the line to output
        end = "{}.{}".format(int(self.text.index(END).split(".")[0]) - 1, 0)
        # adds style to the text
        self.text.tag_add(GraphicalUserInterface.HIGHLIGHT, start, end)

    def add_text(self, text, style=None, offset=0):
        """
        Adds text to the text widget
        """
        line_number = int(self.text.index(END).split(
            ".")[0]) - 1  # line number relative to the rest of the text

        self.text.config(state=NORMAL)  # makes the text editable
        self.text.insert(END, text + "\n")  # inserts text

        start = "{}.{}".format(line_number, 0 +
                               offset)  # start position of the line to output
        end = "{}.{}".format(
            line_number,
            len(text) + offset)  # end position of the line that was outputted

        # adds style to the text
        if text and style:
            if isinstance(style, list):
                for s in style:
                    self.text.tag_add(s, start, end)
            else:
                self.text.tag_add(style, start, end)

        self.text.config(state=DISABLED)  # disabe the text field

        self.previous_tag_name = style
        self.previous_line_length = len(text)

    def add_to_last_line(self, text, style=None, offset=0):
        """
        Adds text to the end of the previous line
        """
        self.text.config(state=NORMAL)  # makes the text editable
        self.text.delete("end-2c lineend", self.text.index(END))
        self.text.config(state=DISABLED)  # makes the text uneditable

        self.add_text(text, style=style, offset=offset)

    def add_blank_lines(self, n):
        """
        Adds blank lines to the text widget
        """
        if n > 0:
            self.add_text("" + "\n" * (n - 1))

    def add_tag(self,
                name,
                foreground=None,
                background=None,
                justify=None,
                font_weight=None):
        """
        Creates a new tag
        """
        if foreground:
            self.text.tag_config(name, foreground=foreground)

        if background:
            self.text.tag_config(name, background=background)

        if justify:
            self.text.tag_config(name, justify=justify)

        if font_weight:
            self.text.tag_config(name,
                                 font=(self.text_font_family,
                                       self.text_font_size, font_weight))

    #########################
    # IO MANAGEMENT METHODS #
    #########################

    def input(self,
              prompt,
              commands,
              action,
              free=False,
              sort=True,
              placeholder=""):
        """
        Manages user input
        """
        self.prompt.set(self._(prompt).title() + ":" if prompt else "")
        self.free_input = free
        self.action = action

        commands = sorted(list(commands)) if sort else list(
            commands)  # sort commands alphabetically if necessary

        command_list = [str(c) for c in commands]

        if command_list != self.command_list:
            self.command_list = [str(c) for c in commands]
            self.update_commands()

        self.entry.delete(0, END)  # clears the entry field
        self.entry.insert(0, placeholder)  # inserts the placeholder
        self.entry.config(state=NORMAL)
        self.entry.focus_set()  # sets the focus on the input field

    def output(self, message, style=None, blank_before=0, blank_after=0):
        """
        Adds formatted text to the output buffer
        """
        # convert numbers in the message to words
        self.add_blank_lines(blank_before)  # blank lines before the output

        for line in message.split("\n"):
            self.add_text(line, style=style)

        self.add_blank_lines(blank_after)  # blank lines after the output
示例#51
0
    def __init__(self):
        """
        Initializes the graphical user interface
        """
        # main interface object
        self.parent = Tk()
        self.parent.state = False

        # strings manager
        strings = Strings()
        self._ = strings.get

        # theme
        style = ThemedStyle(self.parent)
        style.set_theme("arc")

        # button style
        style.configure("TButton", font=self.button_font_family)

        # special button style
        style.configure(self.special_button_style,
                        font=(self.special_button_font_family,
                              self.special_button_font_size,
                              self.special_button_font_weight))

        # make buttons change foreground when hovered
        style.map("TButton",
                  foreground=[("active", self.special_button_active)])

        # root window initialization
        Frame.__init__(self, self.parent)

        w = config.get_int("minimum_window_width",
                           1280)  # minimum width for the Tk parent
        h = config.get_int("minimum_window_height",
                           800)  # minimum height for the Tk parent

        # get screen width and height
        ws = self.parent.winfo_screenwidth()  # width of the screen
        hs = self.parent.winfo_screenheight()  # height of the screen

        self.parent.geometry("%dx%d+0+0" %
                             (ws, hs))  # set the dimensions of the window
        self.parent.minsize(w, h)  # minimum size of the window

        # window title
        self.parent.title(self.window_title)

        # menu bar
        self.menu_bar = Menu(self.parent, font=self.menu_font_family)

        self.file_menu = Menu(self.menu_bar,
                              tearoff=0,
                              font=self.menu_font_family)
        self.menu_bar.add_cascade(label=self._("menu.cascade.file"),
                                  menu=self.file_menu)

        self.edit_menu = Menu(self.menu_bar,
                              tearoff=0,
                              font=self.menu_font_family)
        self.menu_bar.add_cascade(label=self._("menu.cascade.edit"),
                                  menu=self.edit_menu)

        self.view_menu = Menu(self.menu_bar,
                              tearoff=0,
                              font=self.menu_font_family)
        self.menu_bar.add_cascade(label=self._("menu.cascade.view"),
                                  menu=self.view_menu)
        self.view_menu.add_command(label=self._("menu.zoom_in"),
                                   accelerator="Ctrl++",
                                   command=self.zoom_in)
        self.view_menu.add_command(label=self._("menu.zoom_out"),
                                   accelerator="Ctrl+-",
                                   command=self.zoom_out)

        self.filter_menu = Menu(self.menu_bar,
                                tearoff=0,
                                font=self.menu_font_family)
        self.menu_bar.add_cascade(label=self._("menu.cascade.filter"),
                                  menu=self.filter_menu)

        self.taxonomy_menu = Menu(self.menu_bar,
                                  tearoff=0,
                                  font=self.menu_font_family)
        self.menu_bar.add_cascade(label=self._("menu.cascade.taxonomy"),
                                  menu=self.taxonomy_menu)

        self.parent.config(menu=self.menu_bar)

        # make the frame take the whole window
        self.pack(fill=BOTH, expand=1)

        # input frame
        self.input_frame = None

        # output frame
        self.output_frame = Frame(self)
        self.output_frame.pack(fill=BOTH, anchor=N, expand=1)
        self.output_frame.grid_propagate(False)  # ensure a consistent GUI size
        self.output_frame.grid_rowconfigure(
            0, weight=30)  # implement stretchability
        self.output_frame.grid_rowconfigure(
            1, weight=1)  # implement stretchability
        self.output_frame.grid_columnconfigure(0, weight=1)
        self.text = Text(self.output_frame,
                         borderwidth=3,
                         relief=SUNKEN,
                         cursor="arrow",
                         selectbackground=self.select_background,
                         inactiveselectbackground=self.select_background)

        # Text widget
        self.text.grid(row=0,
                       column=0,
                       sticky="nsew",
                       padx=self.padding,
                       pady=(self.padding, 0))
        self.text.config(font=(self.text_font_family, self.text_font_size),
                         undo=True,
                         wrap=WORD,
                         bg=self.text_background,
                         fg=self.text_foreground,
                         state=DISABLED)

        # create a Scrollbar and associate it with text
        self.scrollbar = Scrollbar(self.output_frame, command=self.text.yview)
        self.scrollbar.grid(row=0, rowspan=3, column=1, sticky=NSEW)
        self.text["yscrollcommand"] = self.scrollbar.set

        # status bar
        self.status = Label(self.output_frame,
                            font=(self.label_font_family, self.label_font_size,
                                  "bold"))
        self.status.grid(row=1, column=0, pady=0)

        # binds any typing to the command input field to the update_commands method
        sv = StringVar()
        sv.trace("w", lambda name, index, mode, sv=sv: self.update_commands())

        # input frame
        self.input_frame = Frame(self)
        self.input_frame.pack(fill=X, side=BOTTOM)

        # makes the command input field
        self.entry = Entry(self.input_frame,
                           font=(self.entry_font_family, self.entry_font_size),
                           textvariable=sv,
                           state=DISABLED)
        self.entry.bind(
            "<Return>", self.return_pressed
        )  # binds the Return key to the return_pressed() method
        self.entry.bind(
            "<KP_Enter>", self.return_pressed
        )  # binds the Return key to the return_pressed() method
        self.entry.bind(
            "<Tab>",
            self.tab_pressed)  # binds the Tab key to the tab_pressed() method
        self.entry.pack(fill=X, side=BOTTOM, padx=2,
                        pady=2)  # places the input field
        self.entry.focus_set()  # sets the focus on the input field

        # creates the frame containing buttons
        self.commands = Frame(self.input_frame)
        self.commands.pack(fill=X, side=BOTTOM)

        self.prompt = StringVar()
        self.prompt_label = Label(self.commands,
                                  font=(self.prompt_font_family,
                                        self.prompt_font_size,
                                        self.prompt_font_weight),
                                  textvariable=self.prompt)
        self.prompt_label.pack(side=LEFT, padx=(10, 15), pady=10)

        # creates the frame containing special buttons
        self.special_commands = Frame(self.input_frame)
        self.special_commands.pack(fill=X, side=BOTTOM)

        # default bindings
        self.parent.bind(config.get_string("toggle_fullscreen", "<F11>"),
                         lambda event: self.toggle_fullscreen())
        self.parent.bind(config.get_string("exit_prompt", "<Escape>"),
                         lambda event: self.exit_prompt())
        self.parent.bind(config.get_string("zoom_in", "<Control-KP_Add>"),
                         lambda event: self.zoom_in())
        self.parent.bind(
            config.get_string("zoom_out", "<Control-KP_Subtract>"),
            lambda event: self.zoom_out())

        # binding mouse clicks and movement
        self.text.bind("<Button-1>", self.record_click)
        self.text.bind("<Button-2>", self.record_click)
        self.clickable_text_tag = "clickable_text_tag"
        self.text.bind("<ButtonRelease-1>", self.mouse_left_click)
        self.text.bind("<ButtonRelease-3>", self.mouse_right_click)
        self.text.bind("<Motion>", self.mouse_motion)

        self.last_click_index = "1.0"
        self.last_release_index = "1.0"

        self.command_list = []  # list of potential commands

        self.action = None  # default command action
        self.default_action = None  # default command action

        self.free_input = False  # sets whether it's possible to input anything in the entry

        # basic text tags

        self.add_tag(GraphicalUserInterface.STRONG, font_weight="bold")
        self.add_tag(GraphicalUserInterface.ITALIC, font_weight="italic")
        self.add_tag(GraphicalUserInterface.HIGHLIGHT,
                     background=self.highlight_background)

        self.text.tag_raise(SEL)  # makes sure the selection is fisible
示例#52
0
class DbHandler:

    # def table_builder(self, name):
    #     self.tree.delete(*self.tree.get_children())
    #     res_dr = self.curs.execute('pragma table_info(' + name + ');').fetchall()
    #     indexes = tuple(map(lambda x: ''.join(['#', str(x)]),
    #                         range(len(res_dr))))
    #     self.tree['columns'] = indexes
    #     for item in res_dr:
    #         self.tree.column(indexes[item[0]], width=150)
    #         self.tree.heading(indexes[item[0]], text=item[1])
    #
    # def drawing_tree(self):
    #
    #     res = self.curs.execute('''SELECT name FROM sqlite_master
    #                             WHERE TYPE = "table"''').fetchall()
    #     table_names = [item[0] for item in res]
    #
    #     try:
    #         self.table_menu.destroy()
    #     except AttributeError:
    #         pass
    #     else:
    #         self.the_menu.delete(2)
    #
    #     self.table_menu = Menu(self.the_menu, tearoff=0)
    #     for name in table_names:
    #         self.table_menu.add_command(label=name,
    #                                     command=lambda: self.table_builder(name))
    #     self.the_menu.add_cascade(label='Выбор таблицы', menu=self.table_menu)
    def draw(self, event=None):
        name = self.list_box.get(self.list_box.curselection())
        self.tree.delete(*self.tree.get_children())
        res_dr = self.curs.execute('pragma table_info(' + name + ');').fetchall()
        indexes = tuple(map(lambda x: ''.join(['#', str(x)]),
                            range(len(res_dr))))
        self.tree['columns'] = indexes[1:]
        for item in res_dr:
            self.tree.column(indexes[item[0]], width=150)
            self.tree.heading(indexes[item[0]], text=item[1])
        self.tree.pack(fill=BOTH, expand=1)

    def quit_app(self, event=None):
        try:
            self.conn.close()
        except AttributeError:
            pass
        finally:
            ask = messagebox.askyesno('Выход', "Действительно выйти?")
            if ask:
                self.root.destroy()
            return

    def load_bd(self, event=None):
        fn = filedialog.Open(self.root, filetypes=[('*.db files', '.db')]).show()
        if fn == '':
            return
        try:
            self.conn = sq3.connect(fn)
            self.curs = self.conn.cursor()
        except:
            return

    def save_bd(self, event=None):
        try:
            self.conn.commit()
        except AttributeError:
            pass

    def create_db(self, event=None):
        fn = filedialog.SaveAs(self.root, filetypes=[('*.db files', '.db')]).show()
        if fn == '':
            return
        if not fn.endswith('.db'):
            fn += '.db'
        db_creation(fn)
        self.conn = sq3.connect(fn)
        self.curs = self.conn.cursor()

    def set_menu(self):
        self.the_menu = Menu(self.root)
        self.file_menu = Menu(self.the_menu, tearoff=0)
        self.file_menu.add_command(label='Создать', command=self.create_db)
        self.file_menu.add_command(label='Открыть', command=self.load_bd)
        self.file_menu.add_command(label='Сохранить', command=self.save_bd)
        self.file_menu.add_separator()
        self.file_menu.add_command(label='Выйти', command=self.quit_app)
        self.the_menu.add_cascade(label='Файл', menu=self.file_menu)
        self.root.config(menu=self.the_menu)

    def set_top_frame(self):
        self.top_frame = Frame(self.root, height=360, bg='gray')
        self.top_frame.pack(side=TOP, fill=BOTH)
        self.tree_scroll = Scrollbar(self.top_frame)
        self.tree_scroll.pack(side=RIGHT, fill=Y)
        self.tree = Treeview(self.top_frame, yscrollcommand=self.tree_scroll)
        self.tree_scroll.configure(command=self.tree.yview)
        self.tree.configure(yscrollcommand=self.tree_scroll.set)
        self.tree.pack(fill=BOTH, expand=1)
        self.tree.column('#0', width=798)

    def set_bot_frame(self):
        self.bot_frame = Frame(self.root, height=200, bg='yellow')
        self.bot_frame.pack(side=BOTTOM, fill=BOTH)

    def list_for_select(self):
        try:
            res = self.curs.execute('''SELECT name FROM sqlite_master
                                    WHERE TYPE = "table"''').fetchall()
        except AttributeError:
            return
        else:
            for item in res:
                self.list_box.insert(END, item[0])


    def select_db(self):
        self.form = Toplevel(self.root)
        self.form.minsize(400, 400)
        self.form.title('Выберете БД')
        self.list_box = Listbox(self.form, selectmode=SINGLE)
        self.list_box.pack(side=LEFT, fill=BOTH, expand=1)
        self.list_for_select()
        btn_exit = Button(self.form, text='Закрыть', command=self.form.destroy)
        btn_load = Button(self.form, text='Выбрать', command=self.draw)
        btn_load.pack()
        btn_exit.pack()
        self.form.transient(self.root)
        self.form.grab_set()
        self.root.wait_window(self.form)



    def create_terminal(self):
        ''' Создание дочернего окна
        '''
        pass


    def __init__(self):
        self.root = Tk()
        self.root.title('Blue Mesa')
        self.set_menu()
        self.set_top_frame()
        self.set_bot_frame()
        # buttons = ManageButtons(self.bot_frame, {'insert': self.not_implemented,
        #                                          'update': self.not_implemented,
        #                                          'delete': self.not_implemented,
        #                                          'select': self.not_implemented,
        #                                          'magic': self.create_terminal,
        #                                          })
        buttons = ManageButtons(self.bot_frame, {'select': self.select_db,
                                                 'magic': self.create_terminal
                                                 })
        self.root.mainloop()
示例#53
0
class Movie_app:
    def __init__(self):
        self.win=Tk()
        self.win.title(" VIP视频破解工具")
        self.creat_res()
        self.creat_radiores()
        self.config()
        self.page=1
        self.p=Pro()
        self.win.resizable(0,0) #防止用户调整尺寸
        curWidth = 600
        curHight = 520
        # 获取屏幕宽度和高度
        scn_w, scn_h = self.win.maxsize()
        # 计算中心坐标
        cen_x = (scn_w - curWidth) / 2
        cen_y = (scn_h - curHight) / 2
        # 设置窗口初始大小和位置
        size_xy = '%dx%d+%d+%d' % (curWidth, curHight, cen_x, cen_y)
        self.win.geometry(size_xy)
        self.win.mainloop()


    def creat_res(self):
        #Menu菜单
        menu = tk.Menu(self.win)
        self.win.config(menu = menu)
        moviemenu = tk.Menu(menu,tearoff = 0)
        menu.add_cascade(label = '友情链接', menu = moviemenu)
        downmenu = tk.Menu(menu,tearoff = 0)
        #各个网站链接
        moviemenu.add_command(label = '网易公开课',command = lambda :webbrowser.open('http://open.163.com/'))
        moviemenu.add_command(label = '腾讯视频',command = lambda :webbrowser.open('http://v.qq.com/'))
        moviemenu.add_command(label = '搜狐视频',command = lambda :webbrowser.open('http://tv.sohu.com/'))
        moviemenu.add_command(label = '芒果TV',command = lambda :webbrowser.open('http://www.mgtv.com/'))
        moviemenu.add_command(label = '爱奇艺',command = lambda :webbrowser.open('http://www.iqiyi.com/'))
        moviemenu.add_command(label = 'PPTV',command = lambda :webbrowser.open('http://www.bilibili.com/'))
        moviemenu.add_command(label = '优酷',command = lambda :webbrowser.open('http://www.youku.com/'))
        moviemenu.add_command(label = '乐视',command = lambda :webbrowser.open('http://www.le.com/'))
        moviemenu.add_command(label = '土豆',command = lambda :webbrowser.open('http://www.tudou.com/'))
        moviemenu.add_command(label = 'A站',command = lambda :webbrowser.open('http://www.acfun.tv/'))
        moviemenu.add_command(label = 'B站',command = lambda :webbrowser.open('http://www.bilibili.com/'))

        self.temp=StringVar()#url地址
        self.temp2=StringVar()
        self.search=StringVar()#搜索
        self.t1=StringVar()#通道
        self.t3=StringVar()#爱奇艺,优酷,PPTV
        self.La_title=Label(self.win,text="第三方视频地址:")
        self.La_way=Label(self.win,text="选择视频解码通道:")
        self.La_mc=Label(self.win,text="关键字搜索:")
        #控件内容设置
        self.numberChosen = Combobox(self.win,width=20)
        self.numberChosen['values']=('通道一','通道二','通道三','通道四','通道五','通道六','通道七','通道八','通道九','通道十')
        self.numberChosen.config(state='readonly')
        self.numberChosen.current(0)

        self.B_play=Button(self.win,text="播放▶")
        self.B_searchSimple=Button(self.win,text="关键字搜索")
        self.B_uppage=Button(self.win,text="上页")
        self.B_nextpage=Button(self.win,text="下页")
        self.B_search=Button(self.win,text="搜索全站")
        self.La_page=Label(self.win,bg="#BFEFFF")
        self.S_croll=Scrollbar(self.win)
        self.L_box=Listbox(self.win,bg="#BFEFFF",selectmode=SINGLE)
        self.E_address=Entry(self.win,textvariable=self.temp)
        self.E_search=Entry(self.win,textvariable=self.search)
        self.label_explain = Label(self.win, fg = 'red', font = ('楷体',12), text = '\n注意:支持大部分主流视频网站的视频播放!\n此软件仅用于交流学习,请勿用于任何商业用途!\n在上面输入框输入现在主流视频网站网页地址\n点击播放弹出浏览器可以解码播放')
        self.label_explain.place(x=10,y=90,width=360,height=90)
        self.La_title.place(x=1,y=50,width=90,height=30)
        self.E_address.place(x=100,y=50,width=200,height=30)
        self.B_play.place(x=310,y=50,width=60,height=30)
        self.La_way.place(x=10,y=10,width=100,height=30)
        self.numberChosen.place(x=120,y=10,width=180,height=30)
        self.E_search.place(x=90,y=200,width=160,height=30)
        self.B_searchSimple.place(x=280,y=200,width=80,height=30)
        self.La_mc.place(x=10,y=200,width=70,height=30)
        self.B_search.place(x=252,y=240,width=100,height=30)
        self.L_box.place(x=10,y=280,width=252,height=230)
        self.S_croll.place(x=260,y=280,width=20,height=230)
        self.B_uppage.place(x=10,y=240,width=50,height=30)
        self.B_nextpage.place(x=180,y=240,width=50,height=30)
        self.La_page.place(x=80,y=240,width=90,height=28)

    def creat_radiores(self):
        self.movie=StringVar()#电影
        self.S_croll2=Scrollbar()#分集
        self.La_pic=Label(self.win,bg="#E6E6FA")
        self.La_movie_message=Listbox(self.win,bg="#7EC0EE")
        self.R_movie=Radiobutton(self.win,text="电影",variable=self.movie,value="m")
        self.tv=Radiobutton(self.win,text="电视剧",variable=self.movie,value="t")
        self.zhongyi=Radiobutton(self.win,text="综艺",variable=self.movie,value="z")
        self.dongman=Radiobutton(self.win,text="动漫",variable=self.movie,value="d")
        self.jilupian=Radiobutton(self.win,text="排行榜",variable=self.movie,value="j")
        self.movie.set('m')
        self.B_view=Button(self.win,text="查看")
        self.B_info=Button(self.win,text="使用说明")
        self.B_clearbox=Button(self.win,text="清空列表")
        self.B_add=Button(self.win,text="打开浏览器观看")
        self.R_movie.place(x=290,y=280,width=80,height=30)
        self.B_view.place(x=290,y=430,width=70,height=30)
        self.B_add.place(x=370,y=255,width=100,height=30)
        self.B_clearbox.place(x=500,y=255,width=70,height=30)
        self.tv.place(x=290,y=310,width=80,height=30)
        self.zhongyi.place(x=290,y=340,width=80,height=30)
        self.dongman.place(x=290,y=370,width=80,height=30)
        self.jilupian.place(x=290,y=400,width=80,height=30)
        self.La_movie_message.place(x=370,y=290,width=200,height=220)
        self.La_pic.place(x=370,y=10,width=200,height=240)
        self.B_info.place(x=290,y=470,width=70,height=30)
        self.S_croll2.place(x=568,y=290,width=20,height=220)

    def show_info(self):
        msg="""
        1.输入视频播放地址,即可播放
          下拉选择可切换视频源
        2.选择视频网,选择电视剧或者电影,
          搜索全网后选择想要看得影片,点
          查看,在右方list里选择分集视频
          添加到播放列表里点选播放
        3.复制网上视频连接
          点击播放即可(VIP视频也可以免费播放)
        4.此软件仅用于交流学习
          请勿用于任何商业用途!
        5.此软件内容来源于互联网
          此软件不承担任何由于内容的合法性及
          健康性所引起的争议和法律责任。
        6.欢迎大家对此软件内容侵犯版权等
          不合法和不健康行为进行监督和举报
        """
        messagebox.showinfo(title="使用说明",message=msg)

    def config(self):
        self.t1.set(True)
        self.B_play.config(command=self.play_url_movie)
        self.B_search.config(command=self.search_full_movie)
        self.B_info.config(command=self.show_info)
        self.S_croll.config(command=self.L_box.yview)
        self.L_box['yscrollcommand']=self.S_croll.set
        self.S_croll2.config(command=self.La_movie_message.yview)
        self.La_movie_message['yscrollcommand']=self.S_croll2.set
        self.B_view.config(command=self.view_movies)
        self.B_add.config(command=self.add_play_list)
        self.B_clearbox.config(command=self.clear_lisbox2)
        self.B_uppage.config(command=self.uppage_)
        self.B_nextpage.config(command=self.nextpage_)
        self.B_searchSimple.config(command=self.searchSimple)

    def uppage_(self):
        print('---------上一页---------')
        self.page-=1
        print(self.page)
        if self.page<1:
            self.page=1
        self.search_full_movie()
    def nextpage_(self):
        print('----------下一页--------')
        self.page+=1
        print(self.page)
        self.search_full_movie()

    def clear_lisbox(self):
        self.L_box.delete(0,END)

    def clear_lisbox2(self):
        self.La_movie_message.delete(0,END)

    def search_full_movie(self):
        print("-----search----")
        self.La_page.config(text="当前页:{}".format(self.page))
        self.clear_lisbox()
        try:
            movie_url, movie_title, movie_src_pic=self.p.get_movie_res(self.t3.get(),self.movie.get(),self.page)
            self.movie_dic={}
            for i,j,k in zip(movie_title,movie_url,movie_src_pic):
                self.movie_dic[i]=[j,k]
            for title in movie_title:
                self.L_box.insert(END,title)
            print(self.movie_dic)
            return self.movie_dic
        except:
            messagebox.showerror(title='警告',message='请选择电影或者电视剧')

    def add_play_list(self):
        print('---------playlist----------')
        # print(self.movie_dic)
        if self.La_movie_message.get(self.La_movie_message.curselection())=="":
            messagebox.showwarning(title="警告",message='请在列表选择影片')
        else:
            print("电影名字:",self.La_movie_message.get(self.La_movie_message.curselection()))
            # self.temp.set('http://www.133kp.com' + self.new_more_dic[self.La_movie_message.get(self.La_movie_message.curselection())])
            webbrowser.open('http://www.133kp.com' + self.new_more_dic[self.La_movie_message.get(self.La_movie_message.curselection())])


    def view_pic(self,pic_url):
        print('--------viewpic---------')
        pa_url_check=r'//.+[.]jpg'
        if re.match(pa_url_check,pic_url):
            print("ok")
            pic_url="http:"+pic_url
        print(pic_url)
        data=requests.get(pic_url).content
        # data=urlopen(pic_url).read()
        io_data=io.BytesIO(data)
        self.img=Image.open(io_data)
        self.u=ImageTk.PhotoImage(self.img)
        self.La_pic.config(image=self.u)

    def view_movies(self):
        print("--------viewmovie----------")
        self.clear_lisbox2()
        cur_index=self.L_box.curselection()
        print(self.L_box.get(cur_index))
        self.new_more_dic=self.p.get_more_tv_urls(self.movie_dic[self.L_box.get(cur_index)][0],self.t3.get(),self.movie.get())
        print(self.new_more_dic)
        for i,fenji_url in self.new_more_dic.items():
            self.La_movie_message.insert(END, i)
        self.view_pic(self.movie_dic[self.L_box.get(self.L_box.curselection())][1])#加载图片

    def play_url_movie(self):
        print("--------ok-----------")
        # print(type(self.t1.get()),self.t1.get())
        if self.temp.get()=="":
            messagebox.showwarning(title="警告",message="请先输入视频地址")
        else:
            if self.numberChosen.get()!="":
                self.p.play_movie(self.temp.get(),self.numberChosen.get())
            else:
                messagebox.showwarning(title='警告',message='请选择通道')
    def searchSimple(self):
        if self.search.get()=="":
            messagebox.showwarning(title="警告",message="请先输入搜索关键字")
        else:    
            self.clear_lisbox()  
            url = 'https://www.133kp.com//index.php?m=vod-search&wd={}'.format(self.search.get())
            res=requests.get(url=url,headers=self.p.header).content.decode('utf-8')
            html=etree.HTML(res)
            movie_size=html.xpath('//input[@class="pagego"]/@size')
            list = [] 
            for s in range(0, int(movie_size[0])):
                url = 'https://www.133kp.com/vod-search-pg-{}-wd-{}.html'.format(s+1,self.search.get())
                list.append(self.p.simpleSearch(url)) 
            # movie_url, movie_title, movie_src_pic=self.p.simpleSearch(self.search.get())
            self.movie_dic={}
            i = 0
            for b in list:
                for i,j,k in zip(b[0],b[1],b[2]):
                    self.movie_dic[i]=[j,re.findall(r'[(](.*?)[)]', k)[0]]
                for title in b[0]:
                    self.L_box.insert(END,title)
            print(self.movie_dic)
示例#54
0
    def __init__(self, master, cnf={}, **kw):
        super().__init__(master, cnf, **kw)

        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)
        self.grid_columnconfigure(1, weight=1)
        self.grid_columnconfigure(2, weight=1)

        system_info_frame = LabelFrame(self,
                                       text="System Information",
                                       pady=5,
                                       font=load_font(RelativeSize.normal))
        system_info_frame.grid_rowconfigure(0, weight=1)
        system_info_frame.grid_columnconfigure(0, weight=1)
        system_info_frame.grid(row=0, column=0, sticky="nsew")

        self.system_info_tree = AutosizeTreeview(system_info_frame,
                                                 columns="value")
        self.system_info_tree.heading("#0", text="command")
        self.system_info_tree.column("#0", stretch=True, width=50)
        self.system_info_tree.heading("#1", text="result")
        self.system_info_tree.column("#1", stretch=True, width=50)
        self.system_info_tree.grid(row=0, column=0, sticky="nsew")

        system_info_xscroll = Scrollbar(system_info_frame,
                                        orient="horizontal",
                                        command=self.system_info_tree.xview)
        system_info_yscroll = Scrollbar(system_info_frame,
                                        orient="vertical",
                                        command=self.system_info_tree.yview)
        system_info_xscroll.grid(row=1, column=0, sticky="nsew")
        system_info_yscroll.grid(row=0, column=1, sticky="nsew")
        self.system_info_tree.configure(xscroll=system_info_xscroll.set,
                                        yscroll=system_info_yscroll.set)

        connection_status_frame = LabelFrame(self,
                                             text="Connection Status",
                                             font=load_font(
                                                 RelativeSize.normal))
        connection_status_frame.grid_rowconfigure(0, weight=1)
        connection_status_frame.grid_rowconfigure(1, weight=1)
        connection_status_frame.grid_rowconfigure(2, weight=1)
        connection_status_frame.grid_columnconfigure(0, weight=1)
        connection_status_frame.grid_columnconfigure(1, weight=1)
        connection_status_frame.grid_columnconfigure(2, weight=1)
        connection_status_frame.grid(row=0, column=1, sticky="nsew")

        self.signal_status_bar = Progressbar(connection_status_frame,
                                             orient="vertical",
                                             mode="determinate")
        self.signal_status_bar.grid(row=1, column=1, sticky="nsew")
        self.signal_status_text = Label(connection_status_frame)
        self.signal_status_text.grid(row=1, column=1)

        battery_status_frame = LabelFrame(self,
                                          text="Battery Status",
                                          font=load_font(RelativeSize.normal))
        battery_status_frame.grid_rowconfigure(0, weight=1)
        battery_status_frame.grid_rowconfigure(1, weight=1)
        battery_status_frame.grid_rowconfigure(2, weight=1)
        battery_status_frame.grid_columnconfigure(0, weight=1)
        battery_status_frame.grid_columnconfigure(1, weight=1)
        battery_status_frame.grid_columnconfigure(2, weight=1)
        battery_status_frame.grid(row=0, column=2, sticky="nsew")

        self.battery_status_bar = Progressbar(battery_status_frame,
                                              orient="vertical",
                                              mode="determinate")
        self.battery_status_bar.grid(row=1, column=1, sticky="nsew")
        self.battery_status_text = Label(battery_status_frame)
        self.battery_status_text.grid(row=1, column=1)
示例#55
0
文件: tution.py 项目: charles-an/nppy
class Tution:
    def __init__(self):
        self.file_name = 'tution.json'

        self.master = Tk()
        self.master.title('TUTION')

        self.add_details_frame = Frame(self.master, bg='silver')

        self.entry_name_var = StringVar()
        self.entry_name_style = ttk.Style()
        self.entry_name_style.configure('EntryName.TEntry', foreground='grey')
        self.entry_name = ttk.Entry(self.add_details_frame,
                                    width=50,
                                    justify=CENTER,
                                    style='EntryName.TEntry',
                                    textvariable=self.entry_name_var)
        self.entry_name.insert(END, 'Name of Student')
        self.entry_name.pack(ipady=4, pady=5)

        self.entry_fee_var = StringVar()
        self.entry_fee_style = ttk.Style()
        self.entry_fee_style.configure('EntryFee.TEntry', foreground='grey')
        self.entry_fee = ttk.Entry(self.add_details_frame,
                                   width=50,
                                   justify=CENTER,
                                   style='EntryFee.TEntry',
                                   textvariable=self.entry_fee_var)
        self.entry_fee.insert(END, 'Fee')
        self.entry_fee.pack(ipady=4)

        self.months = [
            'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
            'Oct', 'Nov', 'Dec'
        ]
        self.date_frame = Frame(self.add_details_frame, bg='silver')
        self.month_combobox = ttk.Combobox(self.date_frame,
                                           values=self.months,
                                           width=8,
                                           height=12)
        self.month_combobox.set('Month')
        self.month_combobox.pack(side=LEFT, padx=5)

        self.day_combobox = ttk.Combobox(self.date_frame,
                                         values=list(range(1, 33)),
                                         width=5,
                                         height=12)
        self.day_combobox.set('Day')
        self.day_combobox.pack(side=LEFT, padx=5)

        self.submit_button = ttk.Button(self.date_frame,
                                        text='Submit',
                                        cursor='hand2',
                                        command=self.submit_button_command)
        self.submit_button.pack(ipadx=10)

        self.style = ttk.Style()
        self.style.configure('EntryFee.TRadiobutton',
                             background='silver',
                             foreground='black')
        self.radio_var = IntVar()
        self.radio_buttonframe = Frame(self.add_details_frame, bg='silver')
        self.add_radiobutton = ttk.Radiobutton(self.radio_buttonframe,
                                               text='ADD',
                                               value=1,
                                               variable=self.radio_var,
                                               cursor='hand2',
                                               style='EntryFee.TRadiobutton')
        self.add_radiobutton.pack(side=LEFT)

        self.remove_radiobutton = ttk.Radiobutton(
            self.radio_buttonframe,
            text='REMOVE',
            value=2,
            variable=self.radio_var,
            cursor='hand2',
            style='EntryFee.TRadiobutton')
        self.remove_radiobutton.pack(side=LEFT)

        self.date_frame.pack(pady=10)
        self.radio_buttonframe.pack()
        self.add_details_frame.pack(pady=10)

        self.container_frame = Frame(self.master, bg='silver')
        self.container_frame.pack(padx=3)

        # Creating text-widgets and labels
        self.student_name = Widgets(self.container_frame, 'NAME', 18)
        self.student_fee = Widgets(self.container_frame, 'FEE', 10)
        self.join_date = Widgets(self.container_frame, 'JOINED')
        self.prev_pay = Widgets(self.container_frame, 'PREV PAY')
        self.next_pay = Widgets(self.container_frame, 'NEXT PAY')
        self.left = Widgets(self.container_frame, 'LEFT')
        self.late = Widgets(self.container_frame, 'LATE PAY')

        # Adding scrollbar
        self.text_widgets = [
            self.student_name.text_widget, self.student_fee.text_widget,
            self.join_date.text_widget, self.prev_pay.text_widget,
            self.next_pay.text_widget, self.left.text_widget,
            self.late.text_widget
        ]

        self.scrollbar = Scrollbar(self.late.text_frame,
                                   orient="vertical",
                                   command=self.multiple_yview)
        self.scrollbar.pack(side=LEFT, fill='y')

        for widgets in self.text_widgets:  # Setting scrollbar for all text_widgets
            widgets.config(yscrollcommand=self.scrollbar.set)

        self.master.bind('<Button-1>', self.widgets_bindings)
        self.entry_name.bind('<FocusIn>', self.widgets_bindings)
        self.entry_fee.bind('<FocusIn>', self.widgets_bindings)
        self.entry_fee.bind('<FocusOut>',
                            lambda event, focus_out=True: self.
                            widgets_bindings(event, focus_out))

        self.master.after(0, self.center_window)
        self.master.config(bg='silver')
        self.master.mainloop()

    def center_window(self):
        '''Set position of the window to the center of the screen when user open the program'''

        self.master.withdraw()
        self.master.update()

        self.master.resizable(0, 0)
        self.master.iconbitmap(self.resource_path('included_files\\icon.ico'))
        width, height = self.master.winfo_width(
        ), self.master.winfo_height() + 5
        screenwidth, screenheight = self.master.winfo_screenwidth(
        ) // 2, self.master.winfo_screenheight() // 2
        self.master.geometry(
            f'{width}x{height}+{screenwidth - width // 2}+{screenheight - height // 2}'
        )

        self.insert_at_first()
        self.master.deiconify()

    def widgets_bindings(self, event, focus_out=False):
        '''Remove or Add the default text when user clicks in or out of the entry widget'''

        name = self.entry_name_var.get().strip()
        fee = self.entry_fee_var.get().strip()

        if event.widget == self.entry_name or focus_out:
            if name == 'Name of Student' and not focus_out:
                self.entry_name_style.configure('EntryName.TEntry',
                                                foreground='black')
                self.entry_name_var.set('')

            if not fee:
                self.entry_fee_var.set('Fee')
                self.entry_fee_style.configure('EntryFee.TEntry',
                                               foreground='grey')

        elif event.widget == self.entry_fee:
            if fee == 'Fee':
                self.entry_fee_var.set('')
                self.entry_fee_style.configure('EntryFee.TEntry',
                                               foreground='black')

            if not name:
                self.entry_name_var.set('Name of Student')
                self.entry_name_style.configure('EntryName.TEntry',
                                                foreground='grey')

        elif event.widget not in [self.entry_name, self.entry_fee]:
            if not name:
                self.entry_name_var.set('Name of Student')
                self.entry_name_style.configure('EntryName.TEntry',
                                                foreground='grey')

            if not fee:
                self.entry_fee_var.set('Fee')
                self.entry_fee_style.configure('EntryFee.TEntry',
                                               foreground='grey')

            self.master.focus()

    def multiple_yview(self, *args):
        '''Creating commands of y-view for  all the TEXT widget'''

        for widgets in self.text_widgets:
            widgets.yview(*args)

    def read_json(self):
        '''Reading data from the .json file.'''

        try:
            with open(self.file_name, 'r') as f:
                contents = json.load(f)

                if not contents:
                    contents = {}

        except FileNotFoundError:
            with open(self.file_name, 'w'):
                contents = {}

        except json.decoder.JSONDecodeError:
            messagebox.showerror(
                'JSON Error',
                'You json file is either empty or corrupted so we could not load the data'
            )
            contents = {}

        return contents

    def write_json(self, contents):
        '''Storing data to the .json file'''

        with open(self.file_name, 'w') as f:
            json.dump(contents, f, indent=4)

    def get_next_payment_date(self, joined_str, opt=False):
        '''Calculate next payment date when user adds data for the first time or when user gets monthly payment'''

        days = 0
        today = datetime.date.today().month
        joined_obj = datetime.datetime.strptime(joined_str, '%Y-%b-%d')
        difference = joined_obj - datetime.timedelta(days=joined_obj.day)
        _from = joined_obj.month

        if opt or _from == today:
            _to = today + 1

        else:
            _to = today

        if _from == 12:
            month_list = [12]

        else:
            month_list = list(range(_from, _to))

        for month in month_list:
            days += calendar.monthrange(joined_obj.year, month)[1]

        next_payment = difference + datetime.timedelta(days=days +
                                                       joined_obj.day)

        return f'{next_payment.year}-{calendar.month_abbr[next_payment.month]}-{str(next_payment.day).zfill(2)}'

    def add_command(self, name, fee, month, day, var):
        '''When user selects REMOVE check-button and clicks SUBMIT button'''

        joined_str = f'{datetime.date.today().year}-{month}-{str(day).zfill(2)}'
        next_pay = self.get_next_payment_date(joined_str)

        head = self.read_json()

        if name in head:
            messagebox.showerror('Exists', f'{name} is already in the file')

        else:
            tails = {
                name: {
                    'fee': fee,
                    'joined': joined_str,
                    'prev_pay': [],
                    'late_pay': {},
                    'next_pay': next_pay
                }
            }

            head.update(tails)
            return head

    def remove_command(self, name):
        '''When user selects ADD check-button and clicks SUBMIT button'''

        contents = self.read_json()

        try:
            contents.pop(name)

            return contents

        except KeyError:
            messagebox.showerror('Invalid Value',
                                 f'{name.upper()} not found in the file')

    def submit_button_command(self):
        '''When user clicks SUBMIT button '''

        var = self.radio_var.get()
        fee = self.entry_fee_var.get().strip()
        name = self.entry_name_var.get().strip()
        day = self.day_combobox.get().strip()
        month = self.month_combobox.get().strip()

        if name in ['Name of Student', '']:
            messagebox.showerror('Invalid Name', 'Name of Student is invalid.')

        elif var not in [1, 2]:
            messagebox.showerror(
                'Invalid button',
                'You must select either ADD or REMOVE as per your intentions.')

        elif var == 2:
            contents = self.remove_command(name)

        elif not fee.isdigit():
            messagebox.showerror('Invalid Fee', 'Fee is expected in numbers.')

        elif month not in self.months:
            messagebox.showerror('Invalid Month',
                                 'Month is expected between Jan-Dec.')

        elif not day.isdigit() or int(day) > 32:
            messagebox.showerror('Invalid Day',
                                 'Day is expected between 1-32.')

        elif var == 1:
            contents = self.add_command(name, fee, month, day, var)

        try:
            if contents:
                self.write_json(contents)

                self.reset()
                self.insert_at_first()

        except UnboundLocalError:
            pass

    def reset(self):
        '''Reset entries buttons and radio-button to initial state'''

        self.entry_fee_style.configure('EntryFee.TEntry', foreground='silver')
        self.entry_name_style.configure('EntryName.TEntry',
                                        foreground='silver')

        for widget, text in {
                self.entry_name: 'Name of Student',
                self.entry_fee: 'Fee'
        }.items():
            widget.delete(0, END)
            widget.insert(END, text)

        self.day_combobox.set('Day')
        self.month_combobox.set('Month')

        self.radio_var.set(0)
        self.master.focus()

    def config_text_widget(self, state, clear=False):
        '''Enabling TEXT widgets to insert data and Disabling them after all data has been inserted'''

        for widget in self.text_widgets:
            widget.config(state=state, cursor='arrow')

            if clear:
                widget.delete('1.0', END)

    def insert_at_first(self):
        '''Inserts data from .json file to the TEXT widgets and also calculated the next payment date as well as the number of date left for the payment'''

        contents = self.read_json()
        self.config_text_widget(state=NORMAL, clear=True)

        for key, value in contents.items():
            name = key
            fee = value['fee']
            joined = value['joined']
            prev_pay = value['prev_pay']
            next_pay = value['next_pay']

            today = datetime.date.today()
            next_pay_obj = datetime.datetime.strptime(next_pay, '%Y-%b-%d')
            next_pay_obj = datetime.date(year=next_pay_obj.year,
                                         month=next_pay_obj.month,
                                         day=next_pay_obj.day)

            left = (next_pay_obj - today).days

            if prev_pay:
                prev_pay = prev_pay[-1]

            else:
                prev_pay = 'Not Yet'

            if left <= 0:  # When its the day to get pay
                late_pay = (today - next_pay_obj).days

                if messagebox.askyesno('Got Payment?',
                                       f'Did you get paid from {name}?'):
                    prev_pay = f'{today.year}-{calendar.month_abbr[today.month]}-{str(today.day).zfill(2)}'
                    contents[name]['prev_pay'].append(prev_pay)

                    next_pay = self.get_next_payment_date(joined, opt=True)
                    next_pay_obj = datetime.datetime.strptime(
                        next_pay, '%Y-%b-%d')
                    next_pay_obj = datetime.date(year=next_pay_obj.year,
                                                 month=next_pay_obj.month,
                                                 day=next_pay_obj.day)
                    left = (next_pay_obj - today).days

                    contents[name]['next_pay'] = next_pay
                    contents[name]['late_pay'][str(today)] = f'{late_pay} days'

                    late_pay = contents[name]['late_pay'][str(today)]

                if left < 0:  # When user does not get paid then it becomes late_pay where left becomes negative. So, in that case left becomes 0
                    left = '0'

            else:  # When its not the time to get pay
                if contents[name][
                        'late_pay']:  # If there is last payment in the file
                    last_key = list(contents[name]['late_pay'].keys())[-1]
                    late_pay = contents[name]['late_pay'][last_key]

                else:  # If there is not last payment in the file
                    late_pay = '0 days'

            # Creating dictionary of text_widgets and its corresponding values for insertion
            values = [
                name, fee, joined, prev_pay, next_pay, f'{left} days', late_pay
            ]
            _dict = {
                widget: values[index]
                for index, widget in enumerate(self.text_widgets)
            }

            for widget, text in _dict.items():
                widget.insert(END, f'{text}\n')

        self.master.focus()
        self.write_json(contents)
        self.config_text_widget(state=DISABLED)

    def resource_path(self, relative_path):
        '''Get absolute path to resource from temporary directory

        In development:
            Gets path of files that are used in this script like icons, images or file of any extension from current directory

        After compiling to .exe with pyinstaller and using --add-data flag:
            Gets path of files that are used in this script like icons, images or file of any extension from temporary directory'''

        try:
            base_path = sys._MEIPASS  # PyInstaller creates a temporary directory and stores path of that directory in _MEIPASS

        except AttributeError:
            base_path = os.path.abspath(".")

        return os.path.join(base_path, relative_path)
示例#56
0
    rgb.configure(state="disable")
    brightness.configure(state="disable")
    temp.configure(state="disable")
    color.configure(state="disable")
    brightness.unbind("<ButtonRelease-1>")
    temp.unbind("<ButtonRelease-1>")
    color.unbind("<ButtonRelease-1>")


search_frame = Frame(main, bg=bg_color, width=200, height=400)
control_frame = Frame(main, width=300, height=400)
devices_frame = Frame(search_frame, bg=bg_color, width=180)
devices_canvas = Canvas(devices_frame, bg=bg_color, bd=0, highlightthickness=0, width=180, height=188)
s = Style()
s.configure('Vertical.TScrollbar', background="green")
devices_scrollbar = Scrollbar(devices_frame, style="Vertical.TScrollbar", orient="vertical", command=devices_canvas.yview)
devices = Frame(devices_canvas, bg=bg_color, width=160)
devices.bind(
    "<Configure>",
    lambda e: devices_canvas.configure(
        scrollregion=devices_canvas.bbox("all")
    )
)
devices_canvas.create_window((0,0), window=devices, anchor="nw")
devices_canvas.configure(yscrollcommand=devices_scrollbar.set)

search_button = Button(search_frame, text="SEARCH", width=8,
                       command=lambda: ipPopulate(discoverIp()))
add_button = Button(search_frame, text="ADD", width=8,
                    state="disable", command=addDevice)
ip_list = Listbox(search_frame, width=29, height=6, relief="flat")
示例#57
0
    def init_project_frame( self ) :
        projframe = Frame(self)
        
        ######################
        #The Project Entry Form
        #
        #Current design inherited from others
        #is very bad. It should have been made as
        #json or dictionary as is in this point
        #then the subsequent coding will be much
        #eaiser.
        #BK
        ######################
        BS=StringVar()

        self.eprojectid = eprojectid= StringVar()
        self.eorganism = eorganism=StringVar()
        self.eanalyst = eanalyst=StringVar()
        self.epoc = epoc=StringVar()
        self.epi = epi=StringVar()
        self.euser = euser=StringVar()
        self.eflowcell = eflowcell=StringVar()
        self.eplatform = eplatform=StringVar()
        eplatform.set("Illumina")
        self.technique = technique=StringVar()
        self.pipehome = pipehome=StringVar()
        pipehome.set(PIPELINER_HOME)

        editframe = Frame( self )
        editframe.grid( column=0, row=3, columnspan=3 )
        
        projpanel1 = LabelFrame(editframe,text="Project Information") 
        #,fg=textLightColor,bg=baseColor)
        projpanel1.pack( side = TOP, fill=X, padx=10, pady=5, expand=YES )
        
        pipeline_panel = LabelFrame(editframe, text="Global Settings")
        pipeline_panel.pack( side=TOP, fill=X, padx=10, pady=5, expand=YES )
        
        l=Label( pipeline_panel, text="Genome:" )
        l.grid(row=1,column=3,sticky=W,padx=0,pady=5)
        l = Label( pipeline_panel, text="Pipeline Family:" )
        l.grid(row=1,column=1,sticky=W,padx=0,pady=5)
        
        annotations=['hg19','mm10','mm9','hg38','GRCh38']
        self.annotation = annotation = StringVar()
        annotation.set(annotations[0])
        #annotation.trace('w', lambda *_ :settargets(annotation) )
        
        om = OptionMenu(pipeline_panel, annotation, *annotations, command=self.set_pipeline)
        #, command=lambda _:makejson("refsets"))
        om.config() #bg = widgetBgColor,fg=widgetFgColor)
        om["menu"].config() #bg = widgetBgColor,fg=widgetFgColor)
        om.grid(row=1,column=4,sticky=W,padx=10,pady=10)
        
        pfamilys = ['exomeseq', 'rnaseq', 'genomeseq', 'mirseq', 'ChIPseq', 'scrnaseq']
        self.pfamily = pfamily = StringVar()
        pfamily.set('Select a pipeline')
        om = OptionMenu(pipeline_panel, pfamily, *pfamilys, command=self.set_pipeline)
        #, command=lambda _:makejson(pfamily.get()))
        om.config() #bg = widgetBgColor,fg=widgetFgColor)
        om["menu"].config() #bg = widgetBgColor,fg=widgetFgColor)
        om.grid(row=1,column=2,sticky=W,padx=10,pady=5)
        #add_button = Button( pipeline_panel, 
        #                    text="Set a pipeline", 
        #                    command=self.add_pipeline
        #                   )
        #add_button.grid(row=1, column=5, sticky=W, padx=10, pady=5)
        
        self.notebook = notebook = Notebook( editframe )
        self.pipelineframe = None #the pipeline frame in the notebook frame!
        
        projpanel2 = Frame(notebook) #,fg=textLightColor,bg=baseColor)
        projpanel2.pack( side = LEFT, fill=BOTH, padx=10, pady=5, expand=YES )
        notebook.add( projpanel2, text="Project Description" )
        notebook.pack( side=LEFT, fill=BOTH, padx=10, pady=5, expand=YES )

        Dscrollbar = Scrollbar(projpanel2)
        Dscrollbar.grid(row=2,column=4,rowspan=40)
        
        self.description =description= Text(projpanel2,
                           width=75,
                           height=28,
                           #bg=commentBgColor,
                           #fg=commentFgColor,
                           font=("nimbus mono bold","10"),
                           yscrollcommand = Dscrollbar.set)  
        
        description.delete("1.0", END)
        description.insert(INSERT, "Enter CCBR Project Description and Notes here.")
        #description.bind('<FocusOut>',lambda _:makejson("none"))
        description.grid(row=2,column=3,sticky="e",padx=10,pady=5)
        Dscrollbar['command']=description.yview
        
        L=Label(projpanel1, text="Project Id", anchor="ne" )
        #,bg=baseColor,fg=textLightColor)
        E = Entry(projpanel1, 
                  bd =2, 
                  width=20, 
                  #bg=entryBgColor, 
                  #fg=entryFgColor, 
                  textvariable=eprojectid 
                 )
        #L.pack(pady=5,padx=5)
        #E.pack(pady=1,padx=5)
        L.grid(row=0, column=0, sticky=W, padx=10, pady=5)
        E.grid(row=0, column=2, sticky=W, padx=10, pady=5)
        eprojectid.set("project")
        #eprojectid.trace('w', makejson)
        L2=Label(projpanel1,
                 text = "(Examples: CCBR-nnn,Labname or short project name)",
                 anchor="ne"
                )#,bg="firebrick",fg="white")
        L2.grid(row=0, column=3, padx=10, pady=5, sticky="w")

        L=Label( projpanel1,
                text="Email address",
                anchor="ne")#,bg=baseColor,fg=textLightColor)
        
        E = Entry( projpanel1, 
                  bd =2, 
                  width=20, 
                  #bg=entryBgColor, 
                  #fg=entryFgColor,
                  textvariable=euser)
        
        L3 = Label(projpanel1,
                   text ="(Mandatory field: must use @nih.gov email address)",
                   anchor="ne")
        L3.grid(row=1,column=3,padx=10,pady=5,sticky="w")
        L.grid(row=1,column=0,sticky=W,padx=10,pady=5)
        E.grid(row=1,column=2,sticky=W,padx=10,pady=5)

        #euser.trace('w', makejson)

        L=Label(projpanel1,text="Flow Cell ID",anchor="ne")
        E = Entry(projpanel1, bd =2, width=20, textvariable=eflowcell )#, bg=entryBgColor)
        L4=Label( projpanel1,
                 text="(Examples: FlowCellID, Labname, date or short project name)",
                 anchor="ne" 
                )#,bg="firebrick",fg="white")
        L4.grid(row=2,column=3,padx=10,pady=5,sticky="w")
        L.grid(row=2,column=0,sticky=W,padx=10,pady=5)
        E.grid(row=2,column=2,sticky=W,padx=10,pady=5)
        eflowcell.set("stats")
        #eflowcell.trace('w', makejson)

        Projscrollbar = Scrollbar(projframe)
        Projscrollbar.grid(row=2,column=4,rowspan=30 )
        self.jsonconf = jsonconf = Text( projframe,
                        width=80,
                        height=30,
                        #bg=projectBgColor,
                        #fg=projectFgColor,
                        font=("nimbus mono bold","11"),
                        yscrollcommand = Projscrollbar.set)
        
        Projscrollbar['command']=jsonconf.yview
        jsonconf.grid(row=3,column=0,sticky="e",padx=10,pady=5)
示例#58
0
文件: tution.py 项目: charles-an/nppy
    def __init__(self):
        self.file_name = 'tution.json'

        self.master = Tk()
        self.master.title('TUTION')

        self.add_details_frame = Frame(self.master, bg='silver')

        self.entry_name_var = StringVar()
        self.entry_name_style = ttk.Style()
        self.entry_name_style.configure('EntryName.TEntry', foreground='grey')
        self.entry_name = ttk.Entry(self.add_details_frame,
                                    width=50,
                                    justify=CENTER,
                                    style='EntryName.TEntry',
                                    textvariable=self.entry_name_var)
        self.entry_name.insert(END, 'Name of Student')
        self.entry_name.pack(ipady=4, pady=5)

        self.entry_fee_var = StringVar()
        self.entry_fee_style = ttk.Style()
        self.entry_fee_style.configure('EntryFee.TEntry', foreground='grey')
        self.entry_fee = ttk.Entry(self.add_details_frame,
                                   width=50,
                                   justify=CENTER,
                                   style='EntryFee.TEntry',
                                   textvariable=self.entry_fee_var)
        self.entry_fee.insert(END, 'Fee')
        self.entry_fee.pack(ipady=4)

        self.months = [
            'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
            'Oct', 'Nov', 'Dec'
        ]
        self.date_frame = Frame(self.add_details_frame, bg='silver')
        self.month_combobox = ttk.Combobox(self.date_frame,
                                           values=self.months,
                                           width=8,
                                           height=12)
        self.month_combobox.set('Month')
        self.month_combobox.pack(side=LEFT, padx=5)

        self.day_combobox = ttk.Combobox(self.date_frame,
                                         values=list(range(1, 33)),
                                         width=5,
                                         height=12)
        self.day_combobox.set('Day')
        self.day_combobox.pack(side=LEFT, padx=5)

        self.submit_button = ttk.Button(self.date_frame,
                                        text='Submit',
                                        cursor='hand2',
                                        command=self.submit_button_command)
        self.submit_button.pack(ipadx=10)

        self.style = ttk.Style()
        self.style.configure('EntryFee.TRadiobutton',
                             background='silver',
                             foreground='black')
        self.radio_var = IntVar()
        self.radio_buttonframe = Frame(self.add_details_frame, bg='silver')
        self.add_radiobutton = ttk.Radiobutton(self.radio_buttonframe,
                                               text='ADD',
                                               value=1,
                                               variable=self.radio_var,
                                               cursor='hand2',
                                               style='EntryFee.TRadiobutton')
        self.add_radiobutton.pack(side=LEFT)

        self.remove_radiobutton = ttk.Radiobutton(
            self.radio_buttonframe,
            text='REMOVE',
            value=2,
            variable=self.radio_var,
            cursor='hand2',
            style='EntryFee.TRadiobutton')
        self.remove_radiobutton.pack(side=LEFT)

        self.date_frame.pack(pady=10)
        self.radio_buttonframe.pack()
        self.add_details_frame.pack(pady=10)

        self.container_frame = Frame(self.master, bg='silver')
        self.container_frame.pack(padx=3)

        # Creating text-widgets and labels
        self.student_name = Widgets(self.container_frame, 'NAME', 18)
        self.student_fee = Widgets(self.container_frame, 'FEE', 10)
        self.join_date = Widgets(self.container_frame, 'JOINED')
        self.prev_pay = Widgets(self.container_frame, 'PREV PAY')
        self.next_pay = Widgets(self.container_frame, 'NEXT PAY')
        self.left = Widgets(self.container_frame, 'LEFT')
        self.late = Widgets(self.container_frame, 'LATE PAY')

        # Adding scrollbar
        self.text_widgets = [
            self.student_name.text_widget, self.student_fee.text_widget,
            self.join_date.text_widget, self.prev_pay.text_widget,
            self.next_pay.text_widget, self.left.text_widget,
            self.late.text_widget
        ]

        self.scrollbar = Scrollbar(self.late.text_frame,
                                   orient="vertical",
                                   command=self.multiple_yview)
        self.scrollbar.pack(side=LEFT, fill='y')

        for widgets in self.text_widgets:  # Setting scrollbar for all text_widgets
            widgets.config(yscrollcommand=self.scrollbar.set)

        self.master.bind('<Button-1>', self.widgets_bindings)
        self.entry_name.bind('<FocusIn>', self.widgets_bindings)
        self.entry_fee.bind('<FocusIn>', self.widgets_bindings)
        self.entry_fee.bind('<FocusOut>',
                            lambda event, focus_out=True: self.
                            widgets_bindings(event, focus_out))

        self.master.after(0, self.center_window)
        self.master.config(bg='silver')
        self.master.mainloop()
    def __init__(self, mainWin, modulesWithNewerFileDates):
        super(DialogPluginManager, self).__init__(mainWin.parent)
        
        self.ENABLE = _("Enable")
        self.DISABLE = _("Disable")
        self.parent = mainWin.parent
        self.cntlr = mainWin
        
        # copy plugins for temporary display
        self.pluginConfig = PluginManager.pluginConfig
        self.pluginConfigChanged = False
        self.uiClassMethodsChanged = False
        self.modelClassesChanged = False
        self.disclosureSystemTypesChanged = False
        self.hostSystemFeaturesChanged = False
        self.modulesWithNewerFileDates = modulesWithNewerFileDates
        
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", self.parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))

        self.title(_("Plug-in Manager"))
        frame = Frame(self)
        
        # left button frame
        buttonFrame = Frame(frame, width=40)
        buttonFrame.columnconfigure(0, weight=1)
        addLabel = Label(buttonFrame, text=_("Find plug-in modules:"), wraplength=60, justify="center")
        addLocalButton = Button(buttonFrame, text=_("Locally"), command=self.findLocally)
        ToolTip(addLocalButton, text=_("File chooser allows selecting python module files to add (or reload) plug-ins, from the local file system."), wraplength=240)
        addWebButton = Button(buttonFrame, text=_("On Web"), command=self.findOnWeb)
        ToolTip(addWebButton, text=_("Dialog to enter URL full path to load (or reload) plug-ins, from the web or local file system."), wraplength=240)
        addLabel.grid(row=0, column=0, pady=4)
        addLocalButton.grid(row=1, column=0, pady=4)
        addWebButton.grid(row=2, column=0, pady=4)
        buttonFrame.grid(row=0, column=0, rowspan=2, sticky=(N, S, W), padx=3, pady=3)
        
        # right tree frame (plugins already known to arelle)
        modulesFrame = Frame(frame, width=700)
        vScrollbar = Scrollbar(modulesFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(modulesFrame, orient=HORIZONTAL)
        self.modulesView = Treeview(modulesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=7)
        self.modulesView.grid(row=0, column=0, sticky=(N, S, E, W))
        self.modulesView.bind('<<TreeviewSelect>>', self.moduleSelect)
        hScrollbar["command"] = self.modulesView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.modulesView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        modulesFrame.columnconfigure(0, weight=1)
        modulesFrame.rowconfigure(0, weight=1)
        modulesFrame.grid(row=0, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.modulesView.focus_set()

        self.modulesView.column("#0", width=120, anchor="w")
        self.modulesView.heading("#0", text=_("Name"))
        self.modulesView["columns"] = ("author", "ver", "status", "date", "update", "descr", "license")
        self.modulesView.column("author", width=100, anchor="w", stretch=False)
        self.modulesView.heading("author", text=_("Author"))
        self.modulesView.column("ver", width=50, anchor="w", stretch=False)
        self.modulesView.heading("ver", text=_("Version"))
        self.modulesView.column("status", width=50, anchor="w", stretch=False)
        self.modulesView.heading("status", text=_("Status"))
        self.modulesView.column("date", width=70, anchor="w", stretch=False)
        self.modulesView.heading("date", text=_("File Date"))
        self.modulesView.column("update", width=50, anchor="w", stretch=False)
        self.modulesView.heading("update", text=_("Update"))
        self.modulesView.column("descr", width=200, anchor="w", stretch=False)
        self.modulesView.heading("descr", text=_("Description"))
        self.modulesView.column("license", width=70, anchor="w", stretch=False)
        self.modulesView.heading("license", text=_("License"))

        classesFrame = Frame(frame)
        vScrollbar = Scrollbar(classesFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(classesFrame, orient=HORIZONTAL)
        self.classesView = Treeview(classesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=5)
        self.classesView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.classesView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.classesView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        classesFrame.columnconfigure(0, weight=1)
        classesFrame.rowconfigure(0, weight=1)
        classesFrame.grid(row=1, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.classesView.focus_set()
        
        self.classesView.column("#0", width=200, anchor="w")
        self.classesView.heading("#0", text=_("Class"))
        self.classesView["columns"] = ("modules",)
        self.classesView.column("modules", width=500, anchor="w", stretch=False)
        self.classesView.heading("modules", text=_("Modules"))
        
        # bottom frame module info details
        moduleInfoFrame = Frame(frame, width=700)
        moduleInfoFrame.columnconfigure(1, weight=1)
        
        self.moduleNameLabel = Label(moduleInfoFrame, wraplength=600, justify="left", 
                                     font=font.Font(family='Helvetica', size=12, weight='bold'))
        self.moduleNameLabel.grid(row=0, column=0, columnspan=4, sticky=W)
        self.moduleAuthorHdr = Label(moduleInfoFrame, text=_("author:"), state=DISABLED)
        self.moduleAuthorHdr.grid(row=1, column=0, sticky=W)
        self.moduleAuthorLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleAuthorLabel.grid(row=1, column=1, columnspan=3, sticky=W)
        self.moduleDescrHdr = Label(moduleInfoFrame, text=_("description:"), state=DISABLED)
        self.moduleDescrHdr.grid(row=2, column=0, sticky=W)
        self.moduleDescrLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleDescrLabel.grid(row=2, column=1, columnspan=3, sticky=W)
        self.moduleClassesHdr = Label(moduleInfoFrame, text=_("classes:"), state=DISABLED)
        self.moduleClassesHdr.grid(row=3, column=0, sticky=W)
        self.moduleClassesLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleClassesLabel.grid(row=3, column=1, columnspan=3, sticky=W)
        ToolTip(self.moduleClassesLabel, text=_("List of classes that this plug-in handles."), wraplength=240)
        self.moduleUrlHdr = Label(moduleInfoFrame, text=_("URL:"), state=DISABLED)
        self.moduleUrlHdr.grid(row=4, column=0, sticky=W)
        self.moduleUrlLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleUrlLabel.grid(row=4, column=1, columnspan=3, sticky=W)
        ToolTip(self.moduleUrlLabel, text=_("URL of plug-in module (local file path or web loaded file)."), wraplength=240)
        self.moduleDateHdr = Label(moduleInfoFrame, text=_("date:"), state=DISABLED)
        self.moduleDateHdr.grid(row=5, column=0, sticky=W)
        self.moduleDateLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleDateLabel.grid(row=5, column=1, columnspan=3, sticky=W)
        ToolTip(self.moduleDateLabel, text=_("Date of currently loaded module file (with parenthetical node when an update is available)."), wraplength=240)
        self.moduleLicenseHdr = Label(moduleInfoFrame, text=_("license:"), state=DISABLED)
        self.moduleLicenseHdr.grid(row=6, column=0, sticky=W)
        self.moduleLicenseLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleLicenseLabel.grid(row=6, column=1, columnspan=3, sticky=W)
        self.moduleImportsHdr = Label(moduleInfoFrame, text=_("imports:"), state=DISABLED)
        self.moduleImportsHdr.grid(row=7, column=0, sticky=W)
        self.moduleImportsLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleImportsLabel.grid(row=7, column=1, columnspan=3, sticky=W)
        self.moduleEnableButton = Button(moduleInfoFrame, text=self.ENABLE, state=DISABLED, command=self.moduleEnable)
        ToolTip(self.moduleEnableButton, text=_("Enable/disable plug in."), wraplength=240)
        self.moduleEnableButton.grid(row=8, column=1, sticky=E)
        self.moduleReloadButton = Button(moduleInfoFrame, text=_("Reload"), state=DISABLED, command=self.moduleReload)
        ToolTip(self.moduleReloadButton, text=_("Reload/update plug in."), wraplength=240)
        self.moduleReloadButton.grid(row=8, column=2, sticky=E)
        self.moduleRemoveButton = Button(moduleInfoFrame, text=_("Remove"), state=DISABLED, command=self.moduleRemove)
        ToolTip(self.moduleRemoveButton, text=_("Remove plug in from plug in table (does not erase the plug in's file)."), wraplength=240)
        self.moduleRemoveButton.grid(row=8, column=3, sticky=E)
        moduleInfoFrame.grid(row=2, column=0, columnspan=5, sticky=(N, S, E, W), padx=3, pady=3)
        moduleInfoFrame.config(borderwidth=4, relief="groove")
        
        okButton = Button(frame, text=_("Close"), command=self.ok)
        ToolTip(okButton, text=_("Accept and changes (if any) and close dialog."), wraplength=240)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        ToolTip(cancelButton, text=_("Cancel changes (if any) and close dialog."), wraplength=240)
        okButton.grid(row=3, column=3, sticky=(S,E), pady=3)
        cancelButton.grid(row=3, column=4, sticky=(S,E), pady=3, padx=3)
        
        enableDisableFrame = Frame(frame)
        enableDisableFrame.grid(row=3, column=1, sticky=(S,W), pady=3)
        enableAllButton = Button(enableDisableFrame, text=_("Enable All"), command=self.enableAll)
        ToolTip(enableAllButton, text=_("Enable all plug ins."), wraplength=240)
        disableAllButton = Button(enableDisableFrame, text=_("Disable All"), command=self.disableAll)
        ToolTip(disableAllButton, text=_("Disable all plug ins."), wraplength=240)
        enableAllButton.grid(row=1, column=1)
        disableAllButton.grid(row=1, column=2)
        
        self.loadTreeViews()

        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(0, weight=0)
        frame.columnconfigure(1, weight=1)
        frame.rowconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        window.rowconfigure(0, weight=1)
        
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)
        
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
示例#60
0
    def show_window(self, comp_lists, index, complete, mode, userWantsWin):
        """Show the autocomplete list, bind events.

        If complete is True, complete the text, and if there is exactly
        one matching completion, don't open a list.
        """
        # Handle the start we already have
        self.completions, self.morecompletions = comp_lists
        self.mode = mode
        self.startindex = self.widget.index(index)
        self.start = self.widget.get(self.startindex, "insert")
        if complete:
            completed = self._complete_string(self.start)
            start = self.start
            self._change_start(completed)
            i = self._binary_search(completed)
            if self.completions[i] == completed and \
               (i == len(self.completions)-1 or
                self.completions[i+1][:len(completed)] != completed):
                # There is exactly one matching completion
                return completed == start
        self.userwantswindow = userWantsWin
        self.lasttypedstart = self.start

        # Put widgets in place
        self.autocompletewindow = acw = Toplevel(self.widget)
        # Put it in a position so that it is not seen.
        acw.wm_geometry("+10000+10000")
        # Make it float
        acw.wm_overrideredirect(1)
        try:
            # This command is only needed and available on Tk >= 8.4.0 for OSX
            # Without it, call tips intrude on the typing process by grabbing
            # the focus.
            acw.tk.call("::tk::unsupported::MacWindowStyle", "style", acw._w,
                        "help", "noActivates")
        except TclError:
            pass
        self.scrollbar = scrollbar = Scrollbar(acw, orient=VERTICAL)
        self.listbox = listbox = Listbox(acw,
                                         yscrollcommand=scrollbar.set,
                                         exportselection=False)
        for item in self.completions:
            listbox.insert(END, item)
        self.origselforeground = listbox.cget("selectforeground")
        self.origselbackground = listbox.cget("selectbackground")
        scrollbar.config(command=listbox.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        listbox.pack(side=LEFT, fill=BOTH, expand=True)
        acw.update_idletasks()  # Need for tk8.6.8 on macOS: #40128.
        acw.lift()  # work around bug in Tk 8.5.18+ (issue #24570)

        # Initialize the listbox selection
        self.listbox.select_set(self._binary_search(self.start))
        self._selection_changed()

        # bind events
        self.hideaid = acw.bind(HIDE_VIRTUAL_EVENT_NAME, self.hide_event)
        self.hidewid = self.widget.bind(HIDE_VIRTUAL_EVENT_NAME,
                                        self.hide_event)
        acw.event_add(HIDE_VIRTUAL_EVENT_NAME, HIDE_FOCUS_OUT_SEQUENCE)
        for seq in HIDE_SEQUENCES:
            self.widget.event_add(HIDE_VIRTUAL_EVENT_NAME, seq)

        self.keypressid = self.widget.bind(KEYPRESS_VIRTUAL_EVENT_NAME,
                                           self.keypress_event)
        for seq in KEYPRESS_SEQUENCES:
            self.widget.event_add(KEYPRESS_VIRTUAL_EVENT_NAME, seq)
        self.keyreleaseid = self.widget.bind(KEYRELEASE_VIRTUAL_EVENT_NAME,
                                             self.keyrelease_event)
        self.widget.event_add(KEYRELEASE_VIRTUAL_EVENT_NAME,
                              KEYRELEASE_SEQUENCE)
        self.listupdateid = listbox.bind(LISTUPDATE_SEQUENCE,
                                         self.listselect_event)
        self.is_configuring = False
        self.winconfigid = acw.bind(WINCONFIG_SEQUENCE, self.winconfig_event)
        self.doubleclickid = listbox.bind(DOUBLECLICK_SEQUENCE,
                                          self.doubleclick_event)
        return None