コード例 #1
0
ファイル: mjolnir3.py プロジェクト: jsartisohn/krpc_scripts
class Mjolnir3(KRCCModule):
  def __init__(self, root):
    super().__init__()
    self.root = root
    self.exception = None

    self.list_string = StringVar()
    self.listbox = Listbox(root, listvariable=self.list_string,
                           font='TkFixedFont', width=300)

    self.load()

  def establish_connection_and_run(self):
    error = None
    dots = 0
    connection = None
    while not self.terminate:
      try:
        if connection is None:
          connection = krpc.connect(name=self.name)
        self.run_with_connection(connection)
        error = None
        dots = 0
      except Exception as e:
        if error != e.args[0]:
          error = e.args[0]
          print('\n')
          print(traceback.format_exc())
          sys.stdout.write('Retrying...\n')
        if dots > 80:
          dots = 0
          sys.stdout.write('\n')
        sys.stdout.write('.')
        dots += 1
        sys.stdout.flush()
        time.sleep(1)
    if connection is not None:
      connection.close()

  def run_with_connection(self, connection):
    logging.debug('KRPC connection established')
    strategy = PreLaunch(connection)
    while not self.terminate:
      strategy = strategy.update()
      self.list_string.set(tuple(strategy.display()))

  def run(self):
    try:
      self.establish_connection_and_run()
      self.listbox.destroy()
    except RuntimeError:
      # Should only happen when KeyboardInterrupt is thrown in the MainThread.
      pass

  @property
  def name(self):
    return 'Mjolnir 3'

  def load(self):
    self.listbox.pack(side=LEFT, fill=BOTH)
コード例 #2
0
class FileChooser:
    def __init__(self):
        self.filechooser = Tk()
        self.filechooser.geometry('500x500+0+0')
        self.button  = Button(self.filechooser,text="Add Directory",command=self.addDir)
        self.listview = Listbox(self.filechooser)
        self.closebutton = Button(self.filechooser,text="Scan",command=self.Done)
        self.listview.pack(fill="both")
        self.button.pack(fill='x')
        helptext = """Select directories by pressing the "Add Directory" Button, then press Scan.
                        \n When the file tree appears, red text means the file or folder is a duplicate.
                        \n purple means the folder contains duplicates but itself is not a duplicate.
                        \n Double Click on red text entries to view matches"""
        self.instructions = Label(self.filechooser, text=helptext)
        self.instructions.pack(fill='both')
        self.closebutton.pack()


        self.filechooser.mainloop()
    def Done(self):
        self.filechooser.destroy()
    def addDir(self):
        dir = askdirectory()
        if os.path.isdir(dir):
            dirlist.append(dir)
            self.listview.insert('end',str(dir))
コード例 #3
0
class FeasDisp(ttk.Frame):
    """Widget for displaying all of the feasible states in the conflict."""

    def __init__(self, master=None, conflict=None, *args):
        """Initialize the widget."""
        ttk.Frame.__init__(self, master, padding=5)
        self.columnconfigure(1, weight=1)
        self.rowconfigure(2, weight=1)

        self.conflict = conflict

        self.dispFormat = StringVar(value='pattern')
        self.dispList = StringVar()
        self.feasList = []

        self.fmts = {'Pattern': 'YN-', 'List (YN)': 'YN',
                     'List (ordered and [decimal])': 'ord_dec'}
        cBoxOpts = ('Pattern', 'List (YN)', 'List (ordered and [decimal])')
        self.feasText = ttk.Label(self, text='Feasible States')
        self.feasText.grid(row=0, column=0, columnspan=3)
        self.cBox = ttk.Combobox(self, textvariable=self.dispFormat,
                                 values=cBoxOpts, state='readonly')
        self.cBoxLb = ttk.Label(self, text='Format:')
        self.feasLBx = Listbox(self, listvariable=self.dispList)
        self.scrl = ttk.Scrollbar(self, orient=VERTICAL,
                                  command=self.feasLBx.yview)

        # ###########
        self.cBoxLb.grid(column=0, row=1, sticky=NSEW, pady=3)
        self.cBox.grid(column=1, row=1, columnspan=2, sticky=NSEW, pady=3)
        self.feasLBx.grid(column=0, row=2, columnspan=2, sticky=NSEW)
        self.scrl.grid(column=2, row=2, sticky=NSEW)

        self.cBox.bind('<<ComboboxSelected>>', self.fmtSel)
        self.feasLBx.configure(yscrollcommand=self.scrl.set)

        self.dispFormat.set('Pattern')
        self.fmtSel()

    def fmtSel(self, *args):
        """Action on selection of a new format."""
        self.refreshList()

    def setFeas(self, feasList):
        """Change the list of feasible states to be displayed."""
        self.feasList = feasList
        self.refreshList()

    def refreshList(self):
        """Update the list of feasible states displayed and the format."""
        fmt = self.fmts[self.dispFormat.get()]
        if fmt == "YN-":
            feas = self.conflict.feasibles.dash
        if fmt == "YN":
            feas = self.conflict.feasibles.yn
        if fmt == "ord_dec":
            feas = self.conflict.feasibles.ordDec
        self.dispList.set(tuple(feas))
コード例 #4
0
ファイル: non_interactive.py プロジェクト: amahabal/PySeqsee
  def __init__(self, *, multiple_runner_class, input_spec, left_name,
               right_name):
    """Sets up windows and the instance of RunMultipleTimes that will do the actual work."""
    #: The input_spec is an iterable of
    #: :py:class:`farg.core.read_input_spec.SpecificationForOneRun`.
    self.input_spec = input_spec
    #: Class responsible for the actual running multiple times.
    self.multiple_runner_class = multiple_runner_class
    #: Main window
    self.mw = mw = Tk()
    #: Statistics thus far, grouped by input.
    self.stats = AllStats(left_name=left_name, right_name=right_name)

    #: Are we in the process of quitting?
    self.quitting = False

    self.status_label = Label(
        mw, text='Not Started', font=('Times', 20), foreground='#000000')
    self.status_label_text = self.status_label.cget('text')
    self.status_label.pack(side=TOP, expand=True, fill=X)

    #: Has a run started? Used to ensure single run.
    self.run_started = False

    details_frame = Frame(mw)
    details_frame.pack(side=TOP)
    #: listbox on left listing inputs.
    frame = Frame(details_frame)
    scrollbar = Scrollbar(frame, orient=VERTICAL)
    listbox = Listbox(
        frame,
        yscrollcommand=scrollbar.set,
        height=25,
        width=70,
        selectmode=SINGLE)
    scrollbar.config(command=listbox.yview)
    scrollbar.pack(side=RIGHT, fill=Y)
    listbox.pack(side=LEFT, fill=BOTH, expand=1)
    listbox.bind('<ButtonRelease-1>', self.SelectForDisplay, '+')
    frame.pack(side=LEFT)
    self.listbox = listbox
    #: Canvas on right for details
    self.canvas = Canvas(
        details_frame,
        width=kCanvasWidth,
        height=kCanvasHeight,
        background='#FFFFFF')
    self.canvas.pack(side=LEFT)
    #: which input are we displaying the details of?
    self.display_details_for = None

    #: Thread used for running
    self.thread = None
    self.mw.bind('<KeyPress-q>', lambda e: self.Quit())
    self.mw.bind('<KeyPress-r>', lambda e: self.KickOffRun())
    self.Refresher()
    self.mw.after(1000, self.KickOffRun)
コード例 #5
0
ファイル: gui.py プロジェクト: Monk-/PyMeno
 def __init__(self, parent, db, pab, alg):
     """init"""
     Frame.__init__(self, parent)
     self.right_list = Listbox(parent)
     self.left_list = Listbox(parent)
     self.parent = parent
     self.db_creator = db
     self.path_and_bag = pab
     self.alg_do = alg
     self.menu_bar = Menu(self.parent)
     self.init_ui()
コード例 #6
0
ファイル: File.py プロジェクト: dvargas2013/MainPythons
 def __init__(self,master,place='./'):
     Listbox.__init__(self, master,selectmode="SINGLE")
     self.grid(row=0,column=len(master.lists),sticky="NSWE")
     master.columnconfigure(len(master.lists),weight=1)
     master.rowconfigure(0,weight=1)
     self.master = master
     self.pwd = place
     master.lists.append(self)
     for i in sorted(show(place,master.files),key=lambda z: '!'+z if z.endswith('/') else z): self.insert("end",i)
     self.bind("<Button-1>",lambda e: self.click())
     self.bind("<Button-2>",lambda e: self.master.menu.post(e.x_root,e.y_root))
コード例 #7
0
	def initialize(self):
		amount_label = Label(self, width=8, text="Amount")
		amount_label.grid(row=0, column=0)

		ingredients_label = Label(self, width=35, text="Item Name")
		ingredients_label.grid(row=0, column=1)

		self.amounts_list = Listbox(self, width=8, selectmode="single")
		self.amounts_list.bind("<Double-Button-1>", self.edit)
		self.amounts_list.grid(row=1, column=0, sticky="E")

		self.ingredients_list = Listbox(self, width=35, selectmode="single")
		self.ingredients_list.bind("<Double-Button-1>", self.edit)
		self.ingredients_list.grid(row=1, column=1)

		add_button = Button(self, width=7, text="Add", command=self.add)
		self.bind("<Control-+>", self.add)
		self.bind("<Insert>", self.add)
		add_button.grid(row=2, column=1, sticky="E")

		remove_button = Button(self, text="Remove", command=self.remove)
		self.bind("<Delete>", self.remove)
		remove_button.grid(row=2, column=0)

		produces_label = Label(self, text="Produces: ")
		produces_label.grid(row=3, column=0, sticky="W")

		self.produces_box = Entry(self, width=5)
		self.produces_box.insert(0, "1")
		self.produces_box.grid(row=3, column=1, sticky="W")

		machine_label = Label(self, text="Machine: ")
		machine_label.grid(row=4, column=0, sticky="W")

		self.machine_box = Entry(self)
		self.machine_box.grid(row=4, column=1, sticky="EW")

		info_label = Label(self, text="Extra Info: ")
		info_label.grid(row=5, column=0, sticky="W")

		self.info_box = Entry(self)
		self.info_box.grid(row=5, column=1, sticky="EW")

		cancel_button = Button(self, text="Cancel", width=7, command=self.cancel)
		self.bind("<Escape>", self.cancel)
		cancel_button.grid(row=6, column=0, pady=10)

		ok_button = Button(self, text="OK", width=7, command=self.ok)
		self.bind("<Return>", self.ok)
		ok_button.grid(row=6, column=1, pady=10, sticky="E")

		self.bind("<<ListboxSelect>>", self.sync)
コード例 #8
0
ファイル: scrolltest.py プロジェクト: shawncx/LogParser
class   Application(Frame): 
    def __init__(self,  master=None):
        Frame.__init__(self, master)    
        self.grid(sticky=N+S+E+W)   
        self.mainframe()

    def mainframe(self):                
        self.data = Listbox(self, bg='red')
        self.scrollbar = Scrollbar(self.data, orient=VERTICAL)
        self.data.config(yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.data.yview)

        for i in range(1000):
            self.data.insert(END, str(i))

        self.run = Button(self, text="run")
        self.stop = Button(self, text="stop")
    
        self.data.grid(row=0, column=0, rowspan=4,
                       columnspan=2, sticky=N+E+S+W)
        self.data.columnconfigure(0, weight=1)
    
        self.run.grid(row=4,column=0,sticky=EW)
        self.stop.grid(row=4,column=1,sticky=EW)
    
        self.scrollbar.grid(column=2, sticky=N+S)
コード例 #9
0
ファイル: logui.py プロジェクト: shawncx/LogParser
 def _initjoincondpanel(self):
     frame = Frame(self)
     frame.grid(row=0, column=2, sticky=E + W + S + N, padx=5)
     
     label = Label(frame, text="Join Condition: ")
     label.grid(sticky=N + W)
     
     self.joincondlist = Listbox(frame)
     self.joincondlist.grid(row=1, rowspan=1, columnspan=3, sticky=E + W + S + N)
     
     vsl = Scrollbar(frame, orient=VERTICAL)
     vsl.grid(row=1, column=3, rowspan=1, sticky=N + S + W)
     
     hsl = Scrollbar(frame, orient=HORIZONTAL)
     hsl.grid(row=2, column=0, columnspan=3, sticky=W + E + N)
     
     self.joincondlist.config(yscrollcommand=vsl.set, xscrollcommand=hsl.set)
     
     hsl.config(command=self.joincondlist.xview)
     vsl.config(command=self.joincondlist.yview)
     
     newbtn = Button(frame, text="New", width=7, command=self._addjoincondition)
     newbtn.grid(row=3, column=0, padx=5, pady=5, sticky=E)
     
     delbtn = Button(frame, text="Delete", width=7, command=self._deletejoincondition)
     delbtn.grid(row=3, column=1, sticky=E)
     
     modbtn = Button(frame, text="Update", width=7, command=self._modifyjoincondition)
     modbtn.grid(row=3, column=2, padx=5, pady=5, sticky=W)
コード例 #10
0
ファイル: logui.py プロジェクト: shawncx/LogParser
 def _initfilepanel(self):
     frame = Frame(self)
     frame.grid(row=0, column=0, sticky=E + W + S + N)
     
     label = Label(frame, text="File List: ")
     label.grid(sticky=N + W)
     
     self.filelist = Listbox(frame, width=40)
     self.filelist.grid(row=1, column=0, rowspan=2, columnspan=3)
     
     vsl = Scrollbar(frame, orient=VERTICAL)
     vsl.grid(row=1, column=3, rowspan=2, sticky=N + S + W)
     
     hsl = Scrollbar(frame, orient=HORIZONTAL)
     hsl.grid(row=3, column=0, columnspan=3, sticky=W + E + N)
     
     self.filelist.config(yscrollcommand=vsl.set, xscrollcommand=hsl.set)
     self.filelist.bind('<<ListboxSelect>>', self._onfilelistselection)
     
     hsl.config(command=self.filelist.xview)
     vsl.config(command=self.filelist.yview)
     
     upbtn = Button(frame, text="Up", width=7, command=self._upfile)
     upbtn.grid(row=1, column=4, padx=5, pady=5)
     
     downbtn = Button(frame, text="Down", width=7, command=self._downfile)
     downbtn.grid(row=2, column=4, padx=5, pady=5)
     
     newbtn = Button(frame, text="New", width=7, command=self._addfile)
     newbtn.grid(row=4, column=1, pady=5, sticky=E + S)
     
     delbtn = Button(frame, text="Delete", width=7, command=self._deletefile)
     delbtn.grid(row=4, column=2, padx=5, pady=5, sticky=W + S)
コード例 #11
0
    def __init__(self, parent):
        self.parent = parent
        self.gui = Toplevel(parent.guiRoot)
        self.gui.grab_set()
        self.gui.focus()

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

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

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

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

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

        self.gui.mainloop()
コード例 #12
0
ファイル: lucterios_gui.py プロジェクト: povtux/core
 def _general_tabs(self):
     Label(self.frm_general, text=ugettext("Name")).grid(
         row=0, column=0, sticky=(N, W), padx=5, pady=3)
     self.name = Entry(self.frm_general)
     self.name.grid(row=0, column=1, sticky=(N, S, E, W), padx=5, pady=3)
     Label(self.frm_general, text=ugettext("Appli")).grid(
         row=1, column=0, sticky=(N, W), padx=5, pady=3)
     self.applis = ttk.Combobox(
         self.frm_general, textvariable=StringVar(), state=READLONY)
     self.applis.bind("<<ComboboxSelected>>", self.appli_selection)
     self.applis.grid(row=1, column=1, sticky=(N, S, E, W), padx=5, pady=3)
     Label(self.frm_general, text=ugettext("Modules")).grid(
         row=2, column=0, sticky=(N, W), padx=5, pady=3)
     self.modules = Listbox(self.frm_general, selectmode=EXTENDED)
     self.modules.configure(exportselection=False)
     self.modules.grid(row=2, column=1, sticky=(N, S, E, W), padx=5, pady=3)
     Label(self.frm_general, text=ugettext("Language")).grid(
         row=3, column=0, sticky=(N, W), padx=5, pady=3)
     self.language = ttk.Combobox(
         self.frm_general, textvariable=StringVar(), state=READLONY)
     self.language.grid(
         row=3, column=1, sticky=(N, S, E, W), padx=5, pady=3)
     Label(self.frm_general, text=ugettext("CORE-connectmode")
           ).grid(row=4, column=0, sticky=(N, W), padx=5, pady=3)
     self.mode = ttk.Combobox(
         self.frm_general, textvariable=StringVar(), state=READLONY)
     self.mode.bind("<<ComboboxSelected>>", self.mode_selection)
     self.mode.grid(row=4, column=1, sticky=(N, S, E, W), padx=5, pady=3)
     Label(self.frm_general, text=ugettext("Password")).grid(
         row=5, column=0, sticky=(N, W), padx=5, pady=3)
     self.password = Entry(self.frm_general, show="*")
     self.password.grid(
         row=5, column=1, sticky=(N, S, E, W), padx=5, pady=3)
コード例 #13
0
ファイル: gui.py プロジェクト: valdecar/faceRepresentWithHoG
    def __init__(self, parent):
       
        # super(createSets,self).__init__(parent)
        Frame.__init__(self, parent)
        self.parent = parent
        self.grid(row=0, column=0)

        self.parentWindow = 0

        self.listBox = Listbox(self, selectmode=EXTENDED)
        self.listBox.grid(row=1, column=1)
        for item in ["one", "two", "three", "four"]:
            self.listBox.insert(END, item)
        
        self.buttonDel = Button(self,
                                text="delite selected class",
                                command=self.del_selected)  # lambda ld=self.listBox:ld.delete(ANCHOR))
        self.buttonDel.grid(row=0, column=0)
            
        self.entry = Entry(self, state=NORMAL)
        # self.entry.focus_set()
        self.entry.insert(0, "default")
        self.entry.grid(row=1, column=0)
        
        self.buttonInsert = Button(self, text="add new class",
                                   command=self.add)
        self.buttonInsert.grid(row=0, column=1)
        
        self.buttonDone = Button(self, text="done", command=self.done)
        self.buttonDone.grid(row=2, column=0)
コード例 #14
0
    def _init_exampleListbox(self, parent):
        self._exampleFrame = listframe = Frame(parent)
        self._exampleFrame.pack(fill='both', side='left', padx=2)
        self._exampleList_label = Label(self._exampleFrame, font=self._boldfont,
                                     text='Examples')
        self._exampleList_label.pack()
        self._exampleList = Listbox(self._exampleFrame, selectmode='single',
                                 relief='groove', background='white',
                                 foreground='#909090', font=self._font,
                                 selectforeground='#004040',
                                 selectbackground='#c0f0c0')

        self._exampleList.pack(side='right', fill='both', expand=1)

        for example in self._examples:
            self._exampleList.insert('end', ('  %s' % example))
        self._exampleList.config(height=min(len(self._examples), 25), width=40)

        # Add a scrollbar if there are more than 25 examples.
        if len(self._examples) > 25:
            listscroll = Scrollbar(self._exampleFrame,
                                   orient='vertical')
            self._exampleList.config(yscrollcommand = listscroll.set)
            listscroll.config(command=self._exampleList.yview)
            listscroll.pack(side='left', fill='y')

        # If they select a example, apply it.
        self._exampleList.bind('<<ListboxSelect>>', self._exampleList_select)
コード例 #15
0
    def _init_readingListbox(self, parent):
        self._readingFrame = listframe = Frame(parent)
        self._readingFrame.pack(fill="both", side="left", padx=2)
        self._readingList_label = Label(self._readingFrame, font=self._boldfont, text="Readings")
        self._readingList_label.pack()
        self._readingList = Listbox(
            self._readingFrame,
            selectmode="single",
            relief="groove",
            background="white",
            foreground="#909090",
            font=self._font,
            selectforeground="#004040",
            selectbackground="#c0f0c0",
        )

        self._readingList.pack(side="right", fill="both", expand=1)

        # Add a scrollbar if there are more than 25 examples.
        listscroll = Scrollbar(self._readingFrame, orient="vertical")
        self._readingList.config(yscrollcommand=listscroll.set)
        listscroll.config(command=self._readingList.yview)
        listscroll.pack(side="right", fill="y")

        self._populate_readingListbox()
コード例 #16
0
    def __init__(self, master=None, conflict=None, *args):
        """Initialize the widget."""
        ttk.Frame.__init__(self, master, padding=5)
        self.columnconfigure(1, weight=1)
        self.rowconfigure(2, weight=1)

        self.conflict = conflict

        self.dispFormat = StringVar(value='pattern')
        self.dispList = StringVar()
        self.feasList = []

        self.fmts = {'Pattern': 'YN-', 'List (YN)': 'YN',
                     'List (ordered and [decimal])': 'ord_dec'}
        cBoxOpts = ('Pattern', 'List (YN)', 'List (ordered and [decimal])')
        self.feasText = ttk.Label(self, text='Feasible States')
        self.feasText.grid(row=0, column=0, columnspan=3)
        self.cBox = ttk.Combobox(self, textvariable=self.dispFormat,
                                 values=cBoxOpts, state='readonly')
        self.cBoxLb = ttk.Label(self, text='Format:')
        self.feasLBx = Listbox(self, listvariable=self.dispList)
        self.scrl = ttk.Scrollbar(self, orient=VERTICAL,
                                  command=self.feasLBx.yview)

        # ###########
        self.cBoxLb.grid(column=0, row=1, sticky=NSEW, pady=3)
        self.cBox.grid(column=1, row=1, columnspan=2, sticky=NSEW, pady=3)
        self.feasLBx.grid(column=0, row=2, columnspan=2, sticky=NSEW)
        self.scrl.grid(column=2, row=2, sticky=NSEW)

        self.cBox.bind('<<ComboboxSelected>>', self.fmtSel)
        self.feasLBx.configure(yscrollcommand=self.scrl.set)

        self.dispFormat.set('Pattern')
        self.fmtSel()
コード例 #17
0
ファイル: rdparser_app.py プロジェクト: GloriousFt/TextBlob
    def _init_grammar(self, parent):
        # Grammar view.
        self._prodframe = listframe = Frame(parent)
        self._prodframe.pack(fill="both", side="left", padx=2)
        self._prodlist_label = Label(self._prodframe, font=self._boldfont, text="Available Expansions")
        self._prodlist_label.pack()
        self._prodlist = Listbox(
            self._prodframe,
            selectmode="single",
            relief="groove",
            background="white",
            foreground="#909090",
            font=self._font,
            selectforeground="#004040",
            selectbackground="#c0f0c0",
        )

        self._prodlist.pack(side="right", fill="both", expand=1)

        self._productions = list(self._parser.grammar().productions())
        for production in self._productions:
            self._prodlist.insert("end", ("  %s" % production))
        self._prodlist.config(height=min(len(self._productions), 25))

        # Add a scrollbar if there are more than 25 productions.
        if len(self._productions) > 25:
            listscroll = Scrollbar(self._prodframe, orient="vertical")
            self._prodlist.config(yscrollcommand=listscroll.set)
            listscroll.config(command=self._prodlist.yview)
            listscroll.pack(side="left", fill="y")

        # If they select a production, apply it.
        self._prodlist.bind("<<ListboxSelect>>", self._prodlist_select)
コード例 #18
0
    def initUI(self):
      
        self.lineCounter = 0
      
        # create a custom font
        self.customFontHeader = font.Font(family="Calibri", slant = "italic") #family="Helvetica", weight="bold", slant="italic")
        self.customFontMessage = font.Font(family="Calibri")
        
        self.parent.title("Python Chat") 
        
        frame = Frame(self.parent)
        frame.pack(fill=BOTH, expand=1, side=LEFT)
        
        self.box = ScrolledText(frame, wrap=WORD, relief = GROOVE, width=30, height=18, font=self.customFontMessage)
        self.box.insert(END, 'Welcome to Python Chat!')
        self.box.config(state=DISABLED)
        self.box.pack(expand="yes", fill=BOTH, side=TOP)
        
        self.textarea = Text(frame, width=30, height=5)
        #self.textarea.insert(END, "")
        self.textarea.bind("<KeyRelease-Return>", self.gettext) #Se metto on press, rimane una newline in piu
        self.textarea.pack(expand="yes", fill=BOTH, side=TOP)

        
        okButton = Button(frame, text="Panic Button", activebackground="red", command=self.sendFile) 
        okButton.pack(expand="no", fill=BOTH, side=TOP)
        
        self.usersFrame = Frame(self.parent)
        self.usersFrame.pack(fill=BOTH, expand=1, side=RIGHT)
        
        self.userListbox = Listbox(self.usersFrame, width=3)
        self.userListbox.pack(fill=BOTH, expand=1)
            
        self.updateUsersFrame()
コード例 #19
0
    def _init_exampleListbox(self, parent):
        self._exampleFrame = listframe = Frame(parent)
        self._exampleFrame.pack(fill="both", side="left", padx=2)
        self._exampleList_label = Label(self._exampleFrame, font=self._boldfont, text="Examples")
        self._exampleList_label.pack()
        self._exampleList = Listbox(
            self._exampleFrame,
            selectmode="single",
            relief="groove",
            background="white",
            foreground="#909090",
            font=self._font,
            selectforeground="#004040",
            selectbackground="#c0f0c0",
        )

        self._exampleList.pack(side="right", fill="both", expand=1)

        for example in self._examples:
            self._exampleList.insert("end", ("  %s" % example))
        self._exampleList.config(height=min(len(self._examples), 25), width=40)

        # Add a scrollbar if there are more than 25 examples.
        if len(self._examples) > 25:
            listscroll = Scrollbar(self._exampleFrame, orient="vertical")
            self._exampleList.config(yscrollcommand=listscroll.set)
            listscroll.config(command=self._exampleList.yview)
            listscroll.pack(side="left", fill="y")

        # If they select a example, apply it.
        self._exampleList.bind("<<ListboxSelect>>", self._exampleList_select)
コード例 #20
0
ファイル: lucterios_gui.py プロジェクト: povtux/core
    def create_instance_panel(self):
        frm_inst = Frame(self.ntbk)
        frm_inst.grid_columnconfigure(0, weight=1)
        frm_inst.grid_rowconfigure(0, weight=1)
        frm_inst.grid_columnconfigure(1, weight=3)
        frm_inst.grid_rowconfigure(1, weight=0)
        self.instance_list = Listbox(frm_inst, width=20)
        self.instance_list.bind('<<ListboxSelect>>', self.select_instance)
        self.instance_list.pack()
        self.instance_list.grid(row=0, column=0, sticky=(N, S, W, E))

        self.instance_txt = Text(frm_inst, width=75)
        self.instance_txt.grid(row=0, column=1, rowspan=2, sticky=(N, S, W, E))
        self.instance_txt.config(state=DISABLED)

        self.btninstframe = Frame(frm_inst, bd=1)
        self.btninstframe.grid(row=1, column=0, columnspan=1)
        self.btninstframe.grid_columnconfigure(0, weight=1)
        Button(self.btninstframe, text=ugettext("Launch"), width=25, command=self.open_inst).grid(
            row=0, column=0, columnspan=2, sticky=(N, S))
        Button(self.btninstframe, text=ugettext("Modify"), width=10,
               command=self.modify_inst).grid(row=1, column=0, sticky=(N, S))
        Button(self.btninstframe, text=ugettext("Delete"), width=10,
               command=self.delete_inst).grid(row=1, column=1, sticky=(N, S))
        Button(self.btninstframe, text=ugettext("Save"), width=10,
               command=self.save_inst).grid(row=2, column=0, sticky=(N, S))
        Button(self.btninstframe, text=ugettext("Restore"), width=10,
               command=self.restore_inst).grid(row=2, column=1, sticky=(N, S))
        Button(self.btninstframe, text=ugettext("Add"), width=25, command=self.add_inst).grid(
            row=3, column=0, columnspan=2, sticky=(N, S))

        self.ntbk.add(frm_inst, text=ugettext('Instances'))
コード例 #21
0
ファイル: gui.py プロジェクト: karacho84/dinnerlog
    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")
コード例 #22
0
ファイル: rdparser_app.py プロジェクト: BohanHsu/developer
    def _init_grammar(self, parent):
        # Grammar view.
        self._prodframe = listframe = Frame(parent)
        self._prodframe.pack(fill='both', side='left', padx=2)
        self._prodlist_label = Label(self._prodframe, font=self._boldfont,
                                     text='Available Expansions')
        self._prodlist_label.pack()
        self._prodlist = Listbox(self._prodframe, selectmode='single',
                                 relief='groove', background='white',
                                 foreground='#909090', font=self._font,
                                 selectforeground='#004040',
                                 selectbackground='#c0f0c0')

        self._prodlist.pack(side='right', fill='both', expand=1)

        self._productions = list(self._parser.grammar().productions())
        for production in self._productions:
            self._prodlist.insert('end', ('  %s' % production))
        self._prodlist.config(height=min(len(self._productions), 25))

        # Add a scrollbar if there are more than 25 productions.
        if len(self._productions) > 25:
            listscroll = Scrollbar(self._prodframe,
                                   orient='vertical')
            self._prodlist.config(yscrollcommand = listscroll.set)
            listscroll.config(command=self._prodlist.yview)
            listscroll.pack(side='left', fill='y')

        # If they select a production, apply it.
        self._prodlist.bind('<<ListboxSelect>>', self._prodlist_select)
コード例 #23
0
 def __init__(self, master, line_collection):
     try:
         self.width_of_entry = len(line_collection[0])
     except IndexError:
         self.width_of_entry = 0
     self.top = Toplevel(master)
     self.current_lines_listbox = Listbox(self.top)
     self.removed_lines_listbox = Listbox(self.top)
     self.submit = Button(self.top, text = "Ok", command=self.submit)
     self.remove_button = Button(self.top, text = "Remove", command=self.remove_line)
     self.cancel = Button(self.top, text = "Cancel", command=self.top.destroy)
     self.top.bind("<Return>", func=self.submit)
     self.current_lines = line_collection
     self.removed_lines = []
     self.ids_internal = []
     self.ids = []
     for index, line in enumerate(self.current_lines):
         #removes the point data and converts the rest to strings
         id = line[1]
         if id not in self.ids_internal:
             self.ids_internal.append(id)
             self.ids.append(id)
             line = [str(element) for element in line[1:]]
             
             #put into the list
             self.current_lines_listbox.insert(index, " ".join(line))
     self.current_lines_listbox.grid(row=0, column=0, columnspan=3)
     self.submit.grid(row=1, column=1)
     self.cancel.grid(row=1, column=2)
     self.remove_button.grid(row=1, column=0)
コード例 #24
0
ファイル: bookmanager.py プロジェクト: hangyeolkim91/python
    def initUI(self):

        self.parent.title("Book Manager")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        self.columnconfigure(0, pad=3)
        self.columnconfigure(1, pad=3)
        self.columnconfigure(2, pad=3)
        self.rowconfigure(0, pad=3)
        self.rowconfigure(1, pad=3)
        self.rowconfigure(2, pad=3)
        self.rowconfigure(3, pad=3)
        self.rowconfigure(4, pad=3)
        self.rowconfigure(5, pad=3)
        self.rowconfigure(6, pad=3)


        self.input_bname=''
        self.input_aname=''
        self.input_price=0
        self.delete=''

        lb_bookname = Label(self, text="bookname:")
        lb_bookname.grid(row=0, column =0 ,sticky=W, pady=4, padx=5)

        self.entry_bookname = Entry(self)
        self.entry_bookname.grid(row=0, column = 1 )

        lb_author = Label(self, text="author:")
        lb_author.grid(row=0, column =2,sticky=W, pady=4, padx=5)

        self.entry_author = Entry(self)
        self.entry_author.grid(row=0, column = 3 )


        lb_price = Label(self, text="price:")
        lb_price.grid(row=0, column =4 ,sticky=W, pady=4, padx=5)

        self.entry_price = Entry(self)
        self.entry_price.grid(row=0, column = 5 ,padx=15)


        abtn = Button(self, text="Add", command=lambda:self.clicked_add())
        abtn.grid(row=0, column=6)

        sbtn = Button(self, text="Serach", command = lambda:self.clicked_search())
        sbtn.grid(row=1, column=6, pady=4)

        dbtn = Button(self, text="Delete", command = lambda:self.clicked_delete())
        dbtn.grid(row=2, column=6, pady=4)

        self.lb = Listbox(self)

        self.lb.grid(row=3,column = 0, columnspan = 6,rowspan= 4, sticky = E+W+S+N)
        self.lb.bind("<<ListboxSelect>>", self.onSelect)
コード例 #25
0
ファイル: mjolnir3.py プロジェクト: jsartisohn/krpc_scripts
  def __init__(self, root):
    super().__init__()
    self.root = root
    self.exception = None

    self.list_string = StringVar()
    self.listbox = Listbox(root, listvariable=self.list_string,
                           font='TkFixedFont', width=300)

    self.load()
コード例 #26
0
ファイル: masfir.py プロジェクト: claudemuller/masfir
    def _createUIElements(self):
        """ Create the main frame's UI elements """

        # Top frame with the Load Directory controls
        frmLoadDir = Frame(self)
        frmLoadDir.pack(side=TOP, anchor=N, fill=X)

        self.sLoadDirVar = StringVar()
        lblLoadDir = Label(frmLoadDir, text="<Empty Directory>", textvariable=self.sLoadDirVar)
        lblLoadDir.pack(side=LEFT)

        btnLoadDir = Button(frmLoadDir, text="Load Directory", command=self._onBtnLoadDir)
        btnLoadDir.pack(side=RIGHT)

        # Dropdown with list of series (directories) detected
        frmSeriesSelector = Frame(self)
        frmSeriesSelector.pack(side=TOP, anchor=N, fill=X)

        self.sSeriesVar = StringVar()
        self.optSeries = OptionMenu(frmSeriesSelector, self.sSeriesVar, 'one', 'two', 'three', 'Loading', command=self._onBtnSeriesSelected)
        self.optSeries.pack(side=LEFT)

        # The two diff-style listboxes containing original and new episode list names
        frmListBoxes = Frame(self)
        frmListBoxes.pack(fill=BOTH, expand=1)

        self.lstOrgFiles = Listbox(frmListBoxes)
        self.lstOrgFiles.bind("<<ListboxSelect>>", self._onListOrgFiles)
        self.lstOrgFiles.pack(side=LEFT, fill=BOTH, expand=1, anchor=W)

        self.lstNewFiles = Listbox(frmListBoxes)
        self.lstNewFiles.bind("<<ListboxSelect>>", self._onListNewFiles)
        self.lstNewFiles.pack(side=RIGHT, fill=BOTH, expand=1, anchor=E)

        # Bottom buttons
        frmFinal = Frame(self)
        frmFinal.pack(side=BOTTOM, anchor=S, fill=X)

        btnRename = Button(frmFinal, text="Rename", command=self._onBtnRename)
        btnRename.pack(side=LEFT)

        btnExit = Button(frmFinal, text="Exit", command=self._onBtnExit)
        btnExit.pack(side=RIGHT)
コード例 #27
0
ファイル: testejanela.py プロジェクト: phods/tagout
 def Listatag(self):
     # Lista de tags * em fase de teste
                     
     title = ['189.186.63.44.20','123.145.584.55.5', '','','']
     titleList = Listbox(self, height=5)
     for t in title:
         titleList.insert(END, t)
     titleList.grid(row=7, column=2, columnspan=2, pady=5, sticky=W+E)
     titleList.bind("<<ListboxSelect>>", self.newTitle)
コード例 #28
0
def new_random_swiss(main):
    players = []
    def add_player(event):
        if e.get() is "":
            return
        players.append(e.get())
        Lb.delete(0,END)
        for x in players:
            Lb.insert(0,x)
        e.delete(0,END)

    def remove_player():
        l=len(players)-1
        if Lb.curselection():
            for x in Lb.curselection():
                Lb.delete(x)
                players.pop(l-x)
        else:
            Lb.delete(0)
            players.pop(-1)
        Lb.delete(0,END)
        for x in players:
            Lb.insert(0,x)


    top = Toplevel(main)
    top.title("New Random Swiss")
    top.bind("<Return>",add_player)
    center_size(top,360,180)
    Label(top, text='Name:').grid(row=0,column=0)
    e = Entry(top,width=12)
    e.grid(row=0,column=1)
    e.focus_force()
    Button(top,text='Add',	command=lambda:add_player(None)			).grid(row=1,column=0)
    Button(top,text='Remove',	command=remove_player				).grid(row=1,column=1)
    Button(top,text='Cancel',	command=top.destroy				).grid(row=2,column=0)
    Button(top,text='Finish',	command=lambda:create_single_swiss(players,main)).grid(row=2,column=1)
    Sb = Scrollbar(top)
    Sb.grid(row=0,column=3,rowspan=3)
    Lb = Listbox(top,selectmode=EXTENDED,yscrollcommand=Sb.set)
    Lb.grid(row=0,rowspan=3,column=2)
    Sb.config(command=Lb.yview)
コード例 #29
0
 def __init__(self,root,list):
     self.list = list
     self.mini = Toplevel(root)
     self.mini.wm_title("Matches")
     print (root.winfo_screenwidth())
     self.mini.geometry("%dx%d+%d+%d" %(500,200,root.winfo_x()+root.winfo_width(),root.winfo_y()))
     self.filelist = Listbox(self.mini)
     for item in self.list:
         self.filelist.insert('end',str(item))
     self.filelist.bind("<<ListboxSelect>>",self.onClick)
     self.filelist.pack(fill="both")
コード例 #30
0
ファイル: tenacity2.py プロジェクト: jsartisohn/krpc_scripts
 def __init__(self, root):
   super().__init__()
   self.arbitrary_list = [
       ('bla', random.uniform(0, 500)),
       ('blub', random.randint(1, 10)),
       ('hurrz', 'yolo'),
       'sploink',
   ]
   self.listbox = Listbox(root)
   self.canvas = Canvas(root)
   self.load()
コード例 #31
0
ファイル: list-box.py プロジェクト: delight500/Tk-Assistant

def mid_clicked(event):
    """Middle clicked mouse on item."""
    ev_w = event.widget
    idx = int(ev_w.curselection()[0])
    value = ev_w.get(idx)
    messagebox.showinfo('About', 'Listbox middle clicked on: ' + str(value))


main_frame = LabelFrame(root)
main_frame.grid(padx=8, pady=8)

lst_bx = Listbox(master=main_frame,
                 selectmode='single',
                 width=36,
                 height=5,
                 fg='black',
                 bg='springgreen')

scrbar_vert = Scrollbar(main_frame, orient='vertical')
scrbar_vert.pack(side=RIGHT, fill=Y)
lst_bx.configure(yscrollcommand=scrbar_vert.set)
scrbar_vert.configure(command=lst_bx.yview)

scrbar_horiz = Scrollbar(main_frame, orient='horizontal')
scrbar_horiz.pack(side=BOTTOM, fill=X)
lst_bx.configure(xscrollcommand=scrbar_horiz.set)
scrbar_horiz.configure(command=lst_bx.xview)

lst_bx.pack()
lst_bx.bind('<Double-1>', double_clicked)
コード例 #32
0
class Combobox_Autocomplete(Entry, object):
    def __init__(self,
                 master,
                 list_of_items=None,
                 autocomplete_function=None,
                 listbox_width=None,
                 listbox_height=7,
                 ignorecase_match=False,
                 startswith_match=True,
                 vscrollbar=True,
                 hscrollbar=True,
                 **kwargs):
        if hasattr(self, "autocomplete_function"):
            if autocomplete_function is not None:
                raise ValueError(
                    "Combobox_Autocomplete subclass has 'autocomplete_function' implemented"
                )
        else:
            if autocomplete_function is not None:
                self.autocomplete_function = autocomplete_function
            else:
                if list_of_items is None:
                    raise ValueError(
                        "If not guiven complete function, list_of_items can't be 'None'"
                    )

                if ignorecase_match:
                    if startswith_match:

                        def matches_function(entry_data, item):
                            return item.startswith(entry_data)
                    else:

                        def matches_function(entry_data, item):
                            return item in entry_data

                    self.autocomplete_function = lambda entry_data: [
                        item for item in self.list_of_items
                        if matches_function(entry_data, item)
                    ]
                else:
                    if startswith_match:

                        def matches_function(escaped_entry_data, item):
                            if re.match(escaped_entry_data, item,
                                        re.IGNORECASE):
                                return True
                            else:
                                return False
                    else:

                        def matches_function(escaped_entry_data, item):
                            if re.search(escaped_entry_data, item,
                                         re.IGNORECASE):
                                return True
                            else:
                                return False

                    def autocomplete_function(entry_data):
                        escaped_entry_data = re.escape(entry_data)
                        return [
                            item for item in self.list_of_items
                            if matches_function(escaped_entry_data, item)
                        ]

                    self.autocomplete_function = autocomplete_function

        self._listbox_height = int(listbox_height)
        self._listbox_width = listbox_width

        self.list_of_items = list_of_items

        self._use_vscrollbar = vscrollbar
        self._use_hscrollbar = hscrollbar

        kwargs.setdefault("background", "white")

        if "textvariable" in kwargs:
            self._entry_var = kwargs["textvariable"]
        else:
            self._entry_var = kwargs["textvariable"] = StringVar()

        Entry.__init__(self, master, **kwargs)

        self._trace_id = self._entry_var.trace('w', self._on_change_entry_var)

        self._listbox = None

        self.bind("<Tab>", self._on_tab)
        self.bind("<Up>", self._previous)
        self.bind("<Down>", self._next)
        self.bind('<Control-n>', self._next)
        self.bind('<Control-p>', self._previous)

        self.bind("<Return>", self._update_entry_from_listbox)
        self.bind("<Escape>", lambda event: self.unpost_listbox())

    def _on_tab(self, event):
        self.post_listbox()
        return "break"

    def _on_change_entry_var(self, name, index, mode):

        entry_data = self._entry_var.get()

        if entry_data == '':
            self.unpost_listbox()
            self.focus()
        else:
            values = self.autocomplete_function(entry_data)
            if values:
                if self._listbox is None:
                    self._build_listbox(values)
                else:
                    self._listbox.delete(0, END)

                    height = min(self._listbox_height, len(values))
                    self._listbox.configure(height=height)

                    for item in values:
                        self._listbox.insert(END, item)

            else:
                self.unpost_listbox()
                self.focus()

    def _build_listbox(self, values):
        listbox_frame = Frame()

        self._listbox = Listbox(listbox_frame,
                                background="white",
                                selectmode=SINGLE,
                                activestyle="none",
                                exportselection=False)
        self._listbox.grid(row=0, column=0, sticky=N + E + W + S)

        self._listbox.bind("<ButtonRelease-1>",
                           self._update_entry_from_listbox)
        self._listbox.bind("<Return>", self._update_entry_from_listbox)
        self._listbox.bind("<Escape>", lambda event: self.unpost_listbox())

        self._listbox.bind('<Control-n>', self._next)
        self._listbox.bind('<Control-p>', self._previous)

        if self._use_vscrollbar:
            vbar = Scrollbar(listbox_frame,
                             orient=VERTICAL,
                             command=self._listbox.yview)
            vbar.grid(row=0, column=1, sticky=N + S)

            self._listbox.configure(
                yscrollcommand=lambda f, l: autoscroll(vbar, f, l))

        if self._use_hscrollbar:
            hbar = Scrollbar(listbox_frame,
                             orient=HORIZONTAL,
                             command=self._listbox.xview)
            hbar.grid(row=1, column=0, sticky=E + W)

            self._listbox.configure(
                xscrollcommand=lambda f, l: autoscroll(hbar, f, l))

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

        x = -self.cget("borderwidth") - self.cget("highlightthickness")
        y = self.winfo_height() - self.cget("borderwidth") - self.cget(
            "highlightthickness")

        if self._listbox_width:
            width = self._listbox_width
        else:
            width = self.winfo_width()

        listbox_frame.place(in_=self, x=x, y=y, width=width)

        height = min(self._listbox_height, len(values))
        self._listbox.configure(height=height)

        for item in values:
            self._listbox.insert(END, item)

    def post_listbox(self):
        if self._listbox is not None: return

        entry_data = self._entry_var.get()
        if entry_data == '': return

        values = self.autocomplete_function(entry_data)
        if values:
            self._build_listbox(values)

    def unpost_listbox(self):
        if self._listbox is not None:
            self._listbox.master.destroy()
            self._listbox = None

    def get_value(self):
        return self._entry_var.get()

    def set_value(self, text, close_dialog=False):
        self._set_var(text)

        if close_dialog:
            self.unpost_listbox()

        self.icursor(END)
        self.xview_moveto(1.0)

    def _set_var(self, text):
        self._entry_var.trace_vdelete("w", self._trace_id)
        self._entry_var.set(text)
        self._trace_id = self._entry_var.trace('w', self._on_change_entry_var)

    def _update_entry_from_listbox(self, event):
        if self._listbox is not None:
            current_selection = self._listbox.curselection()

            if current_selection:
                text = self._listbox.get(current_selection)
                self._set_var(text)

            self._listbox.master.destroy()
            self._listbox = None

            self.focus()
            self.icursor(END)
            self.xview_moveto(1.0)

        return "break"

    def _previous(self, event):
        if self._listbox is not None:
            current_selection = self._listbox.curselection()

            if len(current_selection) == 0:
                self._listbox.selection_set(0)
                self._listbox.activate(0)
            else:
                index = int(current_selection[0])
                self._listbox.selection_clear(index)

                if index == 0:
                    index = END
                else:
                    index -= 1

                self._listbox.see(index)
                self._listbox.selection_set(first=index)
                self._listbox.activate(index)

        return "break"

    def _next(self, event):
        if self._listbox is not None:

            current_selection = self._listbox.curselection()
            if len(current_selection) == 0:
                self._listbox.selection_set(0)
                self._listbox.activate(0)
            else:
                index = int(current_selection[0])
                self._listbox.selection_clear(index)

                if index == self._listbox.size() - 1:
                    index = 0
                else:
                    index += 1

                self._listbox.see(index)
                self._listbox.selection_set(index)
                self._listbox.activate(index)
        return "break"


# if __name__ == '__main__':
#     try:
#         from Tkinter import Tk
#     except ImportError:
#         from tkinter import Tk
#
#     list_of_items = ["Cordell Cannata", "Lacey Naples", "Zachery Manigault", "Regan Brunt", "Mario Hilgefort", "Austin Phong", "Moises Saum", "Willy Neill", "Rosendo Sokoloff", "Salley Christenberry", "Toby Schneller", "Angel Buchwald", "Nestor Criger", "Arie Jozwiak", "Nita Montelongo", "Clemencia Okane", "Alison Scaggs", "Von Petrella", "Glennie Gurley", "Jamar Callender", "Titus Wenrich", "Chadwick Liedtke", "Sharlene Yochum", "Leonida Mutchler", "Duane Pickett", "Morton Brackins", "Ervin Trundy", "Antony Orwig", "Audrea Yutzy", "Michal Hepp", "Annelle Hoadley", "Hank Wyman", "Mika Fernandez", "Elisa Legendre", "Sade Nicolson", "Jessie Yi", "Forrest Mooneyhan", "Alvin Widell", "Lizette Ruppe", "Marguerita Pilarski", "Merna Argento", "Jess Daquila", "Breann Bevans", "Melvin Guidry", "Jacelyn Vanleer", "Jerome Riendeau", "Iraida Nyquist", "Micah Glantz", "Dorene Waldrip", "Fidel Garey", "Vertie Deady", "Rosalinda Odegaard", "Chong Hayner", "Candida Palazzolo", "Bennie Faison", "Nova Bunkley", "Francis Buckwalter", "Georgianne Espinal", "Karleen Dockins", "Hertha Lucus", "Ike Alberty", "Deangelo Revelle", "Juli Gallup", "Wendie Eisner", "Khalilah Travers", "Rex Outman", "Anabel King", "Lorelei Tardiff", "Pablo Berkey", "Mariel Tutino", "Leigh Marciano", "Ok Nadeau", "Zachary Antrim", "Chun Matthew", "Golden Keniston", "Anthony Johson", "Rossana Ahlstrom", "Amado Schluter", "Delila Lovelady", "Josef Belle", "Leif Negrete", "Alec Doss", "Darryl Stryker", "Michael Cagley", "Sabina Alejo", "Delana Mewborn", "Aurelio Crouch", "Ashlie Shulman", "Danielle Conlan", "Randal Donnell", "Rheba Anzalone", "Lilian Truax", "Weston Quarterman", "Britt Brunt", "Leonie Corbett", "Monika Gamet", "Ingeborg Bello", "Angelique Zhang", "Santiago Thibeau", "Eliseo Helmuth"]
#
#     root = Tk()
#     root.geometry("300x200")
#
#     combobox_autocomplete = Combobox_Autocomplete(root, list_of_items, highlightthickness=1)
#     combobox_autocomplete.pack()
#
#     combobox_autocomplete.focus()
#
#     root.mainloop()
コード例 #33
0
    btn1 = Button(root, text=" . . . ", command=fileOpen)
    btn1.place(x=580, y=10)
    # btn.pack(side=RIGHT)

    lbl2 = Label(root, text="sheet name: ")
    lbl2.place(x=10, y=40)

    # sheet select
    combobox = ttk.Combobox(root,
                            width=56,
                            textvariable=sheetname,
                            postcommand=getSheetName)
    combobox.place(x=100, y=40)

    # data display frame
    listbox = Listbox(root, selectmode='extended', height=0)
    listbox.yview()
    listbox.place(x=10, y=110)

    # read file
    btn2 = Button(root, text="  read file  ", command=readFile)
    btn2.place(x=540, y=40)

    # write file
    btn3 = Button(root, text="  write file  ", command=writeFile)
    btn3.place(x=540, y=70)

    # test list display frame
    #

    # main loop
コード例 #34
0
def GUI():
    #Import main window
    global main

    #Listbox Frame construction
    noteframe = Frame(main)
    pathlist = Listbox(noteframe)

    #initialization of the class
    inst = File(listbox=pathlist)

    #bottombar construction
    bottombar = Frame(main)
    confirm = Button(bottombar,
                     text="Make Podcast",
                     height=2,
                     background="green",
                     foreground="white",
                     command=midend_start)

    #Topbar construction
    topbar = Frame(main)

    #Three Topbar Buttons
    impFiles = Button(topbar,
                      text="Import Files",
                      command=inst.opFile,
                      height=2)
    remFiles = Button(topbar,
                      text="Remove Files",
                      height=2,
                      command=inst.delFile)
    prevFiles = Button(topbar,
                       text="Preview File",
                       height=2,
                       command=inst.preview)

    #Packaging

    #Topbar Pack
    topbar.pack(side="top")
    prevFiles.pack(side="right")
    impFiles.pack(side="left")
    remFiles.pack(side="top")

    #Listbox Packs
    noteframe.pack(fill="both", expand="true")
    pathlist.pack(fill="both", expand="true")

    #Bottombar Packs
    bottombar.pack(side="right")
    confirm.pack()

    #menubar
    menubar = Menu(main)

    #Open Image or Text
    menubar.add_command(label="Import Images / Textdata", command=inst.opFile)
    #Close Current
    menubar.add_command(label="Remove Selected File", command=inst.delFile)
    #Preview Imported Image using standard Image Opener
    menubar.add_command(label="Preview selected File", command=inst.preview)
    #Help and Credits
    menubar.add_command(label="Help / Credits", command=credits_and_help)

    #other win config
    main.config(menu=menubar)
コード例 #35
0
e1 = Entry(window, textvariable=title_text)
e1.grid(row=0, column=1)

author_text = StringVar()
e2 = Entry(window, textvariable=author_text)
e2.grid(row=0, column=3)

year_text = StringVar()
e3 = Entry(window, textvariable=year_text)
e3.grid(row=1, column=1)

isbn_text = StringVar()
e4 = Entry(window, textvariable=isbn_text)
e4.grid(row=1, column=3)

list1 = Listbox(window, height=6, width=35)
list1.grid(row=2, column=0, rowspan=6, columnspan=2)

sb1 = Scrollbar(window)
sb1.grid(row=2, column=2, rowspan=6)

list1.configure(yscrollcommand=sb1.set)
sb1.configure(command=list1.yview)

list1.bind('<<ListboxSelect>>', get_selected_row)

b1 = Button(window, text="View all", width=12, command=view_command)
b1.grid(row=2, column=3)

b2 = Button(window, text="Search entry", width=12, command=search_command)
b2.grid(row=3, column=3)
コード例 #36
0
Label(main_win, text='Input Folder').grid(row=0, sticky='W')
input_value= StringVar()
input_path = Entry(main_win, textvariable=input_value)
input_path.grid(row=0, column=1, columnspan=2, padx=5, pady=5)
b_input = Button(main_win, text = "Browse...", command = chooseDir(input_path))
b_input.grid(row=0, column = 3, padx=5, pady=5)

Label(main_win, text='Output Folder').grid(row=1, sticky='W')
output_value = StringVar()
output_path = Entry(main_win, textvariable=output_value)
output_path.grid(row=1, column=1, columnspan=2, padx=5, pady=5)
b_output = Button(main_win, text = "Browse...", command = chooseDir(output_path))
b_output.grid(row=1, column = 3, padx=5, pady=5)

test_result = Listbox(main_win)
test_result.grid(row=3, column=0, columnspan = 4, sticky='NESW')

def tests_suite():
    tests = manage.manage(input_value.get(), output_value.get())()
    for test in tests:
        test_result.insert(END, test)

def create_report():
    manage.manage(input_value.get(), output_value.get())
    result = messagebox.askyesno('Show Report File', 'Do you want to open Reports.txt? ')
    if result:
        os.system('start "" {}\\reports.txt'.format(output_value.get()))

b_test = Button(main_win, text='Test Input Quality', command=tests_suite)
b_test.grid(row=2, column=0, columnspan=2, padx=5, pady=5, sticky='NESW')
コード例 #37
0
    def __init__(self, master=None):
        Toplevel.__init__(self, master=master)
        self.cliente = Cliente()
        self.dao = ClienteDAO()

        self.geometry('1500x850+0+0')
        self.title('Excluir cliente')
        self.resizable(0, 0)  # impede de maximizar
        self.configure(background='#c9c9ff')

        self.id = None

        self.heading = Label(self,
                             text="Excluir um cliente do banco de dados",
                             bg='#c9c9ff',
                             fg='white',
                             font=('Verdana 20 bold'))
        self.heading.place(x=550, y=50)

        self.pesquisar_veiculo = Label(self,
                                       text="Pesquisar por nome:",
                                       bg='#c9c9ff',
                                       font=('Verdana  15 bold'))
        self.pesquisar_veiculo.place(x=40, y=150)

        self.search_var = StringVar()
        self.search_var.trace("w",
                              lambda name, index, mode: self.view_command())
        self.search_entry = Entry(self,
                                  textvariable=self.search_var,
                                  width=20,
                                  font=('Verdana  15 bold'))
        self.search_entry.place(x=300, y=150)

        # LIST BOX =============================================================
        self.lista_clientes = Listbox(self,
                                      width=95,
                                      height=10,
                                      font=('Verdana 15 bold'))
        self.lista_clientes.place(x=40, y=300)

        # BOTOES =================================================================
        self.botao_deletar = Button(self,
                                    text="Deletar cliente do banco de dados",
                                    width=46,
                                    height=1,
                                    bg='#baffc9',
                                    fg='black',
                                    font=('Verdana  15 bold'),
                                    command=self.delete)
        self.botao_deletar.place(x=40, y=600)

        self.botao_sair = Button(self,
                                 text="Sair",
                                 width=46,
                                 height=1,
                                 bg='#ffb3ba',
                                 fg='black',
                                 font=('Verdana  15 bold'),
                                 command=self.close)
        self.botao_sair.place(x=720, y=600)

        # self.botao_pesquisar = Button(self, text="Pesquisar", width=20, height=1, bg='#ffdfba', fg='black', font=(
        #     'Verdana  15 bold'))
        # self.botao_pesquisar.place(x=620, y=140)

        # Associando a Scrollbar com a Listbox...
        self.scrollbar_cliente = Scrollbar(self)
        self.lista_clientes.configure(
            yscrollcommand=self.scrollbar_cliente.set)
        self.scrollbar_cliente.configure(command=self.lista_clientes.yview)
        self.scrollbar_cliente.place(x=1375,
                                     y=300,
                                     relheight=0.31,
                                     anchor='ne')

        self.pesquisar_cliente = Label(self,
                                       text="Lista de clientes cadastrados:",
                                       bg='#c9c9ff',
                                       font=('Verdana 15 bold'))
        self.pesquisar_cliente.place(x=40, y=260)

        self.view_command()
        self.lista_clientes.bind('<<ListboxSelect>>', self.selecionar_list_box)
class Tela_emprestimo_devolucao(Tela):
    '''Classe que modela a interface grafica da tela para realizar emprestimo e devolucao do livro'''
    def __init__(self):
        super().__init__()
        self.janela.wm_title("emprestimo/devolucao - DELIBRARY")

        self.txt_id_livro_emprestimo = StringVar()
        self.txt_nome_livro_emprestimo = StringVar()
        self.txt_genero_livro_emprestimo = StringVar()
        self.txt_autor_livro_emprestimo = StringVar()
        self.txt_area_livro_emprestimo = StringVar()
        self.txt_editora_livro_emprestimo = StringVar()
        self.txt_edicao_livro_emprestimo = StringVar()
        self.txt_login_cliente_emprestimo = StringVar()
        self.txt_senha_cliente_emprestimo = StringVar()
        #
        self.txt_id_livro_devolucao = StringVar()
        self.txt_login_cliente_devolucao = StringVar()

        self.lbl_emprestimo = Label(self.janela, text="Emprestimo")
        self.lbl_id_livro_emprestimo = Label(self.janela, text="ID")
        self.lbl_nome_livro_emprestimo = Label(self.janela, text="Nome")
        self.lbl_genero_livro_emprestimo = Label(self.janela, text="Genero")
        self.lbl_autor_livro_emprestimo = Label(self.janela, text="Autor")
        self.lbl_area_livro_emprestimo = Label(self.janela, text="Area")
        self.lbl_editora_livro_emprestimo = Label(self.janela, text="Editora")
        self.lbl_edicao_livro_emprestimo = Label(self.janela, text="Edicao")
        self.lbl_login_cliente_emprestimo = Label(self.janela,
                                                  text="Login do Cliente")
        self.lbl_senha_cliente_emprestimo = Label(self.janela,
                                                  text="Senha do Cliente")
        #
        self.lbl_devolucao = Label(self.janela, text="Devoluçao")
        self.lbl_id_livro_devolucao = Label(self.janela, text="ID")
        self.lbl_login_cliente_devolucao = Label(self.janela,
                                                 text="Login do Cliente")
        self.lbl_info_emprestado = Label(self.janela,
                                         text="Livros emprestados")
        self.lbl_info_disponivel = Label(self.janela, text="Livros disponivel")

        self.ent_id_livro_emprestimo = Entry(
            self.janela, textvariable=self.txt_id_livro_emprestimo)
        self.ent_nome_livro_emprestimo = Entry(
            self.janela, textvariable=self.txt_nome_livro_emprestimo)
        self.ent_genero_livro_emprestimo = Entry(
            self.janela, textvariable=self.txt_genero_livro_emprestimo)
        self.ent_autor_livro_emprestimo = Entry(
            self.janela, textvariable=self.txt_autor_livro_emprestimo)
        self.ent_area_livro_emprestimo = Entry(
            self.janela, textvariable=self.txt_area_livro_emprestimo)
        self.ent_editora_livro_emprestimo = Entry(
            self.janela, textvariable=self.txt_editora_livro_emprestimo)
        self.ent_edicao_livro_emprestimo = Entry(
            self.janela, textvariable=self.txt_edicao_livro_emprestimo)
        self.ent_login_cliente_emprestimo = Entry(
            self.janela, textvariable=self.txt_login_cliente_emprestimo)
        self.ent_senha_cliente_emprestimo = Entry(
            self.janela,
            textvariable=self.txt_senha_cliente_emprestimo,
            show="*")
        self.ent_id_livro_devolucao = Entry(
            self.janela, textvariable=self.txt_id_livro_devolucao)
        self.ent_login_cliente_devolucao = Entry(
            self.janela, textvariable=self.txt_login_cliente_devolucao)

        self.btn_emprestimo = Button(self.janela, width=15, text="Emprestimo")
        self.btn_obter_info_emprestimo = Button(self.janela,
                                                width=15,
                                                text="Verificar")
        self.btn_devolucao = Button(self.janela, width=15, text="Devolução")
        self.btn_obter_info_devolucao = Button(self.janela,
                                               width=15,
                                               text="Pesquisar")
        self.btn_sair = Button(self.janela, width=15, text="Sair")

        self.list_emprestimo = Listbox(self.janela, width=85)
        self.scroll_emprestimo = Scrollbar(self.janela)
        self.list_devolucao = Listbox(self.janela, width=85)
        self.scroll_devolucao = Scrollbar(self.janela)

    def config_layout(self):
        '''Metodo para configurar os widgets da janela'''
        self.lbl_emprestimo.grid(row=0, column=0)
        self.lbl_info_disponivel.grid(row=0, column=2)
        self.lbl_id_livro_emprestimo.grid(row=1, column=0)
        self.btn_obter_info_emprestimo.grid(row=2, column=0)
        self.lbl_nome_livro_emprestimo.grid(row=3, column=0)
        self.lbl_genero_livro_emprestimo.grid(row=4, column=0)
        self.lbl_autor_livro_emprestimo.grid(row=5, column=0)
        self.lbl_area_livro_emprestimo.grid(row=6, column=0)
        self.lbl_editora_livro_emprestimo.grid(row=7, column=0)
        self.lbl_edicao_livro_emprestimo.grid(row=8, column=0)
        self.lbl_login_cliente_emprestimo.grid(row=9, column=0)
        self.lbl_senha_cliente_emprestimo.grid(row=10, column=0)
        self.ent_id_livro_emprestimo.grid(row=1, column=1)
        self.ent_nome_livro_emprestimo.grid(row=3, column=1)
        self.ent_genero_livro_emprestimo.grid(row=4, column=1)
        self.ent_autor_livro_emprestimo.grid(row=5, column=1)
        self.ent_area_livro_emprestimo.grid(row=6, column=1)
        self.ent_editora_livro_emprestimo.grid(row=7, column=1)
        self.ent_edicao_livro_emprestimo.grid(row=8, column=1)
        self.ent_login_cliente_emprestimo.grid(row=9, column=1)
        self.ent_senha_cliente_emprestimo.grid(row=10, column=1)
        self.btn_emprestimo.grid(row=11, column=0)

        self.lbl_devolucao.grid(row=12, column=0)
        self.lbl_info_emprestado.grid(row=12, column=2)
        self.lbl_id_livro_devolucao.grid(row=13, column=0)
        self.lbl_login_cliente_devolucao.grid(row=14, column=0, rowspan=8)
        self.ent_id_livro_devolucao.grid(row=13, column=1)
        self.ent_login_cliente_devolucao.grid(row=14, column=1)

        self.btn_obter_info_devolucao.grid(row=19, column=0)
        self.btn_devolucao.grid(row=19, column=1)
        self.btn_sair.grid(row=20, column=0)

        self.list_emprestimo.grid(row=1, column=2, rowspan=8)
        self.scroll_emprestimo.grid(row=1, column=3, rowspan=8)
        self.list_emprestimo.configure(
            yscrollcommand=self.scroll_emprestimo.set)
        self.scroll_emprestimo.configure(command=self.list_emprestimo.yview)

        self.list_devolucao.grid(row=13, column=2, rowspan=8)
        self.scroll_devolucao.grid(row=13, column=3, rowspan=8)
        self.list_devolucao.configure(yscrollcommand=self.scroll_devolucao.set)
        self.scroll_devolucao.configure(command=self.list_devolucao.yview)

    def iniciar(self):
        '''Metodo para desenhar a janela e processar eventos'''
        self.config_layout()
        return super().iniciar()
コード例 #39
0
def generate_subjects_list(root, subjects):
    return Listbox(root, height=len(subjects), width=18, selectmode=MULTIPLE)
コード例 #40
0
ファイル: main.py プロジェクト: athiffau/PiWallGuiController
 def create_display_box(self):
     """
         Creates display box that displays all current items in the playlist
     """
     self.display_box = Listbox(width=30, height=10)
     self.display_box.grid(row=0, column=2, columnspan=2)
コード例 #41
0
ファイル: main.py プロジェクト: athiffau/PiWallGuiController
class SelectorWindow(Frame):
    """
        GUI Class extending the tkinter.Frame class
    """
    TIMEOUTS = {
        '1 hour ': 3600,
        '2 hours': 7200,
        '3 hours': 10800,
        'Infinite': -1,
    }

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.__playlist = Playlist()
        self.__controller = PiWallController()
        self.__dropdown_selection = StringVar()
        self.__timeout_selection = StringVar()
        self.__command_thread = Thread(target=self.__controller.run_commands,
                                       args=(self.__playlist, ))
        self.grid()
        self.create_video_file_dropdown()
        self.create_timeout_dropdown()
        self.create_display_box()
        self.create_add_button()
        self.create_delete_button()
        self.create_play_button()
        self.create_reboot_button()
        self.create_status_label()
        self.create_stop_button()

    def create_video_file_dropdown(self):
        """
            Creates the dropdown to display the video files from
        """
        videos = self.__controller.get_video_file_list()

        if videos:
            self.__dropdown_selection.set(videos[0])
        else:
            videos.append(None)

        self.video_dropdown = OptionMenu(None, self.__dropdown_selection,
                                         *videos)
        self.video_dropdown.config(width=10)
        self.video_dropdown.grid(row=0, column=0)

    def create_timeout_dropdown(self):
        """
            Creates the dropdown that displays the timeouts
        """
        timeouts = list(self.TIMEOUTS.keys())
        timeouts.sort()
        self.__timeout_selection.set(timeouts[0])
        self.timeout_dropdown = OptionMenu(None, self.__timeout_selection,
                                           *timeouts)
        self.timeout_dropdown.config(width=5)
        self.timeout_dropdown.grid(row=0, column=1)

    def create_display_box(self):
        """
            Creates display box that displays all current items in the playlist
        """
        self.display_box = Listbox(width=30, height=10)
        self.display_box.grid(row=0, column=2, columnspan=2)

    def create_play_button(self):
        """
            Creates the play button
        """
        self.submit_button = Button(text="Play", width=10)
        self.submit_button['command'] = self.play_wall
        self.submit_button.grid(row=1, column=2, pady=5)

    def create_add_button(self):
        """
            Creates the button to add the current values in the video and timeout dropdown
            into the playlist
        """
        self.add_button = Button(text='Add', fg='green', width=10)
        self.add_button['command'] = self.update_display_box
        self.add_button.grid(row=1, column=0, pady=5)

    def create_delete_button(self):
        """
            Creates delete button to delete items from display blox
        """
        self.delete_button = Button(text='Delete', fg='red', width=10)
        self.delete_button['command'] = self.delete_selected_item
        self.delete_button.grid(row=1, column=1, pady=5)

    def create_reboot_button(self):
        """
            Creates button that reboots the pi's
        """
        self.reboot_button = Button(text='Reboot Tiles', fg='red', width=10)
        self.reboot_button['command'] = self.reboot_pressed
        self.reboot_button.grid(row=1, column=3, pady=5)

    def create_status_label(self):
        """
            Creates label to display current status of the wall
        """
        self.status_label = Label(relief="ridge", width=11)
        self.set_status_label(0)
        self.status_label.grid(row=2, column=3, pady=5)

    def create_stop_button(self):
        """
            Creates stop button to stop PiWall
        """
        self.stop_button = Button(text='Stop Playing')
        self.set_status_label(0)
        self.stop_button['command'] = self.stop_pressed
        self.stop_button.grid(row=2, column=2, pady=5)

    def delete_selected_item(self):
        """
            Deletes the currently selected item from the displaybox
        """
        self.__playlist.remove_playlist_item(self.display_box.curselection())
        self.display_box.delete(self.display_box.curselection())

    def play_wall(self):
        """
            Submits ths form to be played on the pi's
        """
        if self.__playlist.is_empty():
            return
        self.set_status_label(1)
        self.display_box.delete(0, END)
        # If there is a thread running, we need to stop the wall, which will
        # end the thread
        if self.__command_thread.isAlive():
            print("Stopping Wall")
            self.__controller.stop_wall()
            self.__command_thread.join()
        self.__command_thread = Thread(target=self.__controller.run_commands,
                                       args=(self.__playlist, ))
        self.__command_thread.start()

    def update_display_box(self):
        """
            Button listener for the Add Button (create_add_button)
        """
        video_file = self.__dropdown_selection.get()
        timeout = self.__timeout_selection.get()
        self.__playlist.add_playlist_item(video_file, self.TIMEOUTS[timeout])
        self.display_box.insert(END, "{0}   {1}".format(timeout, video_file))

    def stop_pressed(self):
        """
            Button listener for the Stop Button (create_stop_button)
        """
        self.__controller.stop_wall()
        self.set_status_label(0)

    def reboot_pressed(self):
        """
            Button listener for the Reboot Button (create_reboot_button)
        """
        self.set_status_label(0)
        self.__controller.reboot_pis()
        return True

    def set_status_label(self, state):
        """
            Updates the status label to the current status of the PiWall
        """
        if state == 1:
            self.status_label.config(text='Playing', fg='green')
            return True
        elif state == 0:
            self.status_label.config(text='Not Playing', fg='red')
            return True
        else:
            Exception(
                'Status label state {0} not supported. Try 1 or 2'.format(
                    state))

    def get_controller(self):
        """
            Returns the piwallcontrollers
        """
        return self.__controller
コード例 #42
0
class DBReadingapp(Toplevel):
    def __init__(self, *args, **kwargs):

        Toplevel.__init__(self, *args, **kwargs)
        Toplevel.wm_title(self, "DBReadingapp")
        Toplevel.config(self, background="white")
        self.wm_geometry("300x150")
        center(self)
        self.initUI()

    def initUI(self):
        self.master.withdraw()
        self.protocol("WM_DELETE_WINDOW", self.on_closing)

        self.canvas0 = tk.Canvas(self, borderwidth=0, background="#ffffff")
        #self.superframe=Frame(self.canvas0,background="#ffffff")
        self.canvas0.pack(side="left", fill="both", expand=True)

        Button(self.canvas0,
               text="Welcome to the\nUltimate Database Reading System",
               command=self.on_start,
               width=100).pack(expand=1)
#        Button(self.canvas0, text="test",
#               command = self.test, width=100).pack()

    def on_start(self):

        try:
            path = filedialog.askopenfilenames(
                title="Please select the Database .db file")[0]

            if path != "":
                if path[-3:] == ".db":
                    self.db_conn = sqlite3.connect(path)
                    self.theCursor = self.db_conn.cursor()

                    print("connected to DB")
                    self.SELECTwindow()
                else:
                    print("not correct file extension")
                    messagebox.showinfo("", "not correct file extension")
        except IndexError:
            print("you did not select a file")
            messagebox.showinfo("", "you did not select a file")

    def on_closing(self):
        #if messagebox.askokcancel("Quit", "Do you want to quit?"):
        self.destroy()
        self.master.deiconify()

    class Drag_and_Drop_Listbox(tk.Listbox):
        #A tk listbox with drag'n'drop reordering of entries.
        def __init__(self, master, **kw):
            #kw['selectmode'] = tk.MULTIPLE
            kw['selectmode'] = tk.SINGLE
            kw['activestyle'] = 'none'
            tk.Listbox.__init__(self, master, kw)
            self.bind('<Button-1>', self.getState, add='+')
            self.bind('<Button-1>', self.setCurrent, add='+')
            self.bind('<B1-Motion>', self.shiftSelection)
            self.curIndex = None
            self.curState = None

        def setCurrent(self, event):
            ''' gets the current index of the clicked item in the listbox '''
            self.curIndex = self.nearest(event.y)

        def getState(self, event):
            ''' checks if the clicked item in listbox is selected '''
            #i = self.nearest(event.y)
            #self.curState = self.selection_includes(i)
            self.curState = 1

        def shiftSelection(self, event):
            ''' shifts item up or down in listbox '''
            i = self.nearest(event.y)
            if self.curState == 1:
                self.selection_set(self.curIndex)
            else:
                self.selection_clear(self.curIndex)
            if i < self.curIndex:
                # Moves up
                x = self.get(i)
                selected = self.selection_includes(i)
                self.delete(i)
                self.insert(i + 1, x)
                if selected:
                    self.selection_set(i + 1)
                self.curIndex = i
            elif i > self.curIndex:
                # Moves down
                x = self.get(i)
                selected = self.selection_includes(i)
                self.delete(i)
                self.insert(i - 1, x)
                if selected:
                    self.selection_set(i - 1)
                self.curIndex = i

################################################################################
################################################################################
#select which parameter we want to see in the final report (head of columns of the report table)

    def SELECTwindow(self):
        global tablesAndcolnames, SetallcolnamesWOids

        self.withdraw()
        self.selectionwindow = tk.Toplevel()
        center(self.selectionwindow)
        self.selectionwindow.protocol("WM_DELETE_WINDOW", self.backtomain)
        self.selectionwindow.wm_geometry("350x200")
        self.selectionwindow.wm_title("Selection of Search Parameters")

        self.theCursor.execute(
            "SELECT name FROM sqlite_master WHERE type='table';")
        tables = list(map(lambda x: x[0], self.theCursor.fetchall()))

        allcolnames = []
        for item in tables:
            if item != 'sqlite_sequence':
                dat = self.theCursor.execute('SELECT * FROM ' + item)
                names = list(map(lambda x: item + '.' + x[0], dat.description))
                tablesAndcolnames.append([item, names])
                allcolnames += names

        Setallcolnames = list(set(allcolnames))
        #        Setallcolnames.remove('id')
        SetallcolnamesWOids = []
        for item in Setallcolnames:
            if "id" not in item:
                SetallcolnamesWOids.append(item)
        SetallcolnamesWOids = sorted(SetallcolnamesWOids)
        #        print(SetallcolnamesWOids)
        frame1 = Frame(self.selectionwindow, borderwidth=0, bg="white")
        frame1.pack(fill=tk.BOTH)

        self.parameterlist = SetallcolnamesWOids
        self.parameterChoice = StringVar()
        self.parameterChoice.set(self.parameterlist[0])
        self.dropMenuFrame = OptionMenu(frame1,
                                        self.parameterChoice,
                                        *self.parameterlist,
                                        command=self.addparametertolist)
        self.dropMenuFrame.pack(side="left")

        Button(frame1,
               text="Add the usuals",
               command=self.addtheusualparameters).pack(side="left")
        Button(frame1, text="Add all",
               command=self.addallparameters).pack(side="left")

        frame = Frame(self.selectionwindow, borderwidth=0, bg="white")
        frame.pack(fill=tk.BOTH, expand=1)

        #        self.listboxsamples=Listbox(frame,width=20, height=5, selectmode=tk.EXTENDED)
        #        self.listboxsamples.pack(side="left", fill=tk.BOTH, expand=1)
        #        scrollbar = tk.Scrollbar(frame, orient="vertical")
        #        scrollbar.config(command=self.listboxsamples.yview)
        #        scrollbar.pack(side="right", fill="y")
        #        self.listboxsamples.config(yscrollcommand=scrollbar.set)

        self.listboxsamples = self.Drag_and_Drop_Listbox(frame)
        self.listboxsamples.pack(fill=tk.BOTH, expand=True)
        scrollbar = tk.Scrollbar(self.listboxsamples, orient="vertical")
        scrollbar.config(command=self.listboxsamples.yview)
        scrollbar.pack(side="right", fill="y")
        self.listboxsamples.config(yscrollcommand=scrollbar.set)

        frame3 = Frame(self.selectionwindow, borderwidth=0, bg="white")
        frame3.pack()
        Button(frame3,
               text="DeleteParam",
               command=self.deleteparameterfromlist).pack(side="left",
                                                          fill=tk.BOTH,
                                                          expand=1)
        Button(frame3, text="Validate",
               command=self.validateparameters).pack(side="left",
                                                     fill=tk.BOTH,
                                                     expand=1)
        Button(frame3, text="Cancel",
               command=self.backtomain).pack(side="left",
                                             fill=tk.BOTH,
                                             expand=1)

    def addallparameters(self):
        global parameterList, SetallcolnamesWOids

        for item in SetallcolnamesWOids:
            if item not in parameterList:
                parameterList.append(item)
                self.listboxsamples.insert(tk.END, item)

    def addtheusualparameters(self):
        global parameterList, SetallcolnamesWOids

        usualparam = [
            'samples.samplename',
            'users.username',
            'JVmeas.CellArea',
            'JVmeas.DateTimeJV',
            'JVmeas.Eff',
            'JVmeas.FF',
            'JVmeas.Jsc',
            'JVmeas.Voc',
        ]

        for item in usualparam:
            if item not in parameterList:
                parameterList.append(item)
                self.listboxsamples.insert(tk.END, item)

    def addparametertolist(self, a):
        global parameterList

        #cannot select twice the same parameter
        if self.parameterChoice.get() in parameterList:
            messagebox.showinfo("", "parameter already selected in the list")
        else:  #add parameter to list
            parameterList.append(self.parameterChoice.get())

            #show it in the listbox
            self.listboxsamples.insert(tk.END, self.parameterChoice.get())

    def deleteparameterfromlist(self):
        global parameterList

        selection = self.listboxsamples.curselection()

        pos = 0
        for i in selection:
            idx = int(i) - pos
            value = self.listboxsamples.get(i)
            ind = parameterList.index(value)
            del (parameterList[ind])
            self.listboxsamples.delete(idx, idx)
            pos = pos + 1

    def validateparameters(self):
        global parameterList

        if parameterList != []:
            parameterList = list(self.listboxsamples.get(0, tk.END))
            #            print(parameterList)
            self.RestrictionCriteriawindow()
        else:
            messagebox.showinfo("",
                                "at least one parameter should be selected")

################################################################################
################################################################################
#define here restriction criteria, to limit the search to specific samples...

    def RestrictionCriteriawindow(self):
        global tablesAndcolnames, SetallcolnamesWOids, criteriaList, criteriaexclusionlist

        self.withdraw()
        self.selectionwindow.destroy()
        self.criteriawindow = tk.Toplevel()
        center(self.criteriawindow)
        self.criteriawindow.protocol("WM_DELETE_WINDOW", self.backtomain)
        self.criteriawindow.wm_geometry("350x200")
        self.criteriawindow.wm_title("Selection of restriction criteria")

        #        tk.Label(self.criteriawindow, text="if no criteria are selected, the search will be done without\nrestriction, which can potentially generate a very large output file.", bg="black",fg="white").pack()

        colnamesnew = [
            item for item in SetallcolnamesWOids
            if item not in criteriaexclusionlist
        ]
        frame1 = Frame(self.criteriawindow, borderwidth=0, bg="white")
        frame1.pack(fill=tk.BOTH, expand=1)
        self.criterialist = colnamesnew
        self.parameterChoice = StringVar()
        self.parameterChoice.set(self.parameterlist[0])
        self.dropMenuFrame = OptionMenu(frame1,
                                        self.parameterChoice,
                                        *self.criterialist,
                                        command=self.addcriteriatolist)
        self.dropMenuFrame.pack(side="left")
        #        Button(frame1, text="Add all to list",
        #               command = self.addallcriteria).pack(side="left")

        frame = Frame(self.criteriawindow, borderwidth=0, bg="white")
        frame.pack(fill=tk.BOTH, expand=1)

        self.listboxsamples = Listbox(frame,
                                      width=20,
                                      height=5,
                                      selectmode=tk.EXTENDED)
        self.listboxsamples.pack(side="left", fill=tk.BOTH, expand=1)
        scrollbar = tk.Scrollbar(frame, orient="vertical")
        scrollbar.config(command=self.listboxsamples.yview)
        scrollbar.pack(side="right", fill="y")
        self.listboxsamples.config(yscrollcommand=scrollbar.set)

        frame3 = Frame(self.criteriawindow, borderwidth=0, bg="white")
        frame3.pack()
        Button(frame3,
               text="DeleteCriteria",
               command=self.deletecriteriafromlist).pack(side="left",
                                                         fill=tk.BOTH,
                                                         expand=1)
        Button(frame3, text="Validate",
               command=self.validatecriteria).pack(side="left",
                                                   fill=tk.BOTH,
                                                   expand=1)
        Button(frame3, text="Cancel",
               command=self.backtomain).pack(side="left",
                                             fill=tk.BOTH,
                                             expand=1)
        self.numb_for = 0

    def addallcriteria(self):
        global criteriaList, SetallcolnamesWOids, criteriaexclusionlist

        colnamesnew = [
            item for item in SetallcolnamesWOids
            if item not in criteriaexclusionlist
        ]

        for item in colnamesnew:
            if item not in criteriaList:
                criteriaList.append(item)
                self.listboxsamples.insert(tk.END, item)

    def addcriteriatolist(self, a):
        global criteriaList, criteriaexclusionlist

        #cannot select twice the same criteria
        if self.parameterChoice.get() in criteriaList:
            messagebox.showinfo("", "criteria already selected in the list")
        else:  #add criteria to list
            criteriaList.append(self.parameterChoice.get())

            #show it in the listbox
            self.listboxsamples.insert(tk.END, self.parameterChoice.get())

    def deletecriteriafromlist(self):
        global criteriaList

        selection = self.listboxsamples.curselection()

        pos = 0
        for i in selection:
            idx = int(i) - pos
            value = self.listboxsamples.get(i)
            ind = criteriaList.index(value)
            del (criteriaList[ind])
            self.listboxsamples.delete(idx, idx)
            pos = pos + 1

    def validatecriteria(self):
        global criteriaList, SetallcolnamesWOids, criteriaexclusionlist

        if criteriaList != []:
            self.detaillingcriteriaList()
        else:
            messagebox.showinfo("", "at least one criteria should be selected")

################################################################################
################################################################################
#generate popup windows to

    def dropdowncriteriaRefinement(self, criterianame, listoptions):

        self.dropdownwindow = tk.Toplevel()
        center(self.dropdownwindow)
        self.dropdownwindow.protocol("WM_DELETE_WINDOW", self.backtomain)
        self.dropdownwindow.wm_geometry("400x200")
        self.dropdownwindow.wm_title("Select for: " + criterianame +
                                     " (multiple choice possible)")

        self.critname = criterianame

        frame2 = Frame(self.dropdownwindow, borderwidth=0, bg="white")
        frame2.pack(fill=tk.BOTH, expand=1)

        self.listboxsamples = Listbox(frame2,
                                      width=20,
                                      height=5,
                                      selectmode=tk.EXTENDED)
        self.listboxsamples.pack(side="left", fill=tk.BOTH, expand=1)
        scrollbar = tk.Scrollbar(frame2, orient="vertical")
        scrollbar.config(command=self.listboxsamples.yview)
        scrollbar.pack(side="right", fill="y")
        self.listboxsamples.config(yscrollcommand=scrollbar.set)

        for item in listoptions:
            self.listboxsamples.insert(tk.END, item)

        frame = Frame(self.dropdownwindow, borderwidth=0, bg="white")
        frame.pack()
        self.buttondropdown = Button(frame,
                                     text="done",
                                     command=self.dropdownfinished).pack(
                                         side="left", fill=tk.BOTH, expand=1)

    def dropdownfinished(self):
        global criteriaListdetailled

        values = [
            self.listboxsamples.get(idx)
            for idx in self.listboxsamples.curselection()
        ]

        if values != []:
            criteriaListdetailled.append(
                [copy.deepcopy(self.critname), values])
            self.dropdownwindow.destroy()
            self.detaillingcriteriaList()
        else:
            messagebox.showinfo("", "you must pick at least one")

    def minmaxcriteriaRefinement(self, criterianame, minimum, maximum):

        self.minmaxwindow = tk.Toplevel()
        center(self.minmaxwindow)
        self.minmaxwindow.protocol("WM_DELETE_WINDOW", self.backtomain)
        self.minmaxwindow.wm_geometry("500x60")
        self.minmaxwindow.wm_title("Select for: " + criterianame +
                                   " (default values are min and max in DB)")

        self.critname = criterianame

        frame = Frame(self.minmaxwindow, borderwidth=0, bg="white")
        frame.pack()
        tk.Label(frame, text="from", font=("Verdana", 10)).pack(side="left",
                                                                fill=tk.BOTH,
                                                                expand=1)
        self.min = tk.StringVar()
        self.entry1 = Entry(frame, textvariable=self.min, width=20)
        self.entry1.pack(side="left", fill=tk.BOTH, expand=1)
        self.min.set(str(minimum))
        tk.Label(frame, text="to", font=("Verdana", 10)).pack(side="left",
                                                              fill=tk.BOTH,
                                                              expand=1)
        self.max = tk.StringVar()
        self.entry1 = Entry(frame, textvariable=self.max, width=20)
        self.entry1.pack(side="left", fill=tk.BOTH, expand=1)
        self.max.set(str(maximum))

        Button(self.minmaxwindow, text="done",
               command=self.minmaxfinished).pack(side="left",
                                                 fill=tk.BOTH,
                                                 expand=1)

    def minmaxfinished(self):
        global criteriaListdetailled2

        criteriaListdetailled2.append(
            [self.critname, self.min.get(),
             self.max.get()])

        self.minmaxwindow.destroy()
        self.detaillingcriteriaList()

    def bydeffunction(self):
        self.criteriawindow = tk.Toplevel()
        center(self.criteriawindow)
        self.criteriawindow.protocol("WM_DELETE_WINDOW", self.backtomain)
        self.criteriawindow.wm_geometry("100x100")
        self.criteriawindow.wm_title("Selection of Search Parameters")

        Button(self.criteriawindow,
               text="Ok",
               command=self.detaillingcriteriaList).pack(side="left",
                                                         fill=tk.BOTH,
                                                         expand=1)

#        self.detaillingcriteriaList()

    def detaillingcriteriaList(self):
        """
        now it iterates through the selected criteria and propose all possibilities existing in the DB
        in the future, it should restrict the possibilities after each criteria definition, in order to limit directly the search and not end up with 0 results after having set all criteria
        
        """
        global parameterList, criteriaList, criteriaexclusionlist, dropdowncriteria, fromtocriteria, timecriteria, criteriaListdetailled, criteriaListdetailled2
        try:
            self.criteriawindow.destroy()
        except:
            pass

        #        print(len(criteriaList))
        #        print(self.numb_for)

        if self.numb_for < len(criteriaList):

            if criteriaList[self.numb_for] in dropdowncriteria:
                self.theCursor.execute(
                    "SELECT " + criteriaList[self.numb_for].split('.')[1] +
                    " FROM " + criteriaList[self.numb_for].split('.')[0])
                listoptions = list(
                    set([x[0] for x in self.theCursor.fetchall()]))
                self.dropdowncriteriaRefinement(criteriaList[self.numb_for],
                                                listoptions)
#                print(criteriaList[self.numb_for])
            elif criteriaList[self.numb_for] in fromtocriteria:
                self.theCursor.execute(
                    "SELECT " + criteriaList[self.numb_for].split('.')[1] +
                    " FROM " + criteriaList[self.numb_for].split('.')[0])
                listoptions = list(
                    set([x[0] for x in self.theCursor.fetchall()]))
                minimum = min(listoptions)
                maximum = max(listoptions)
                self.minmaxcriteriaRefinement(criteriaList[self.numb_for],
                                              minimum, maximum)
#                print(criteriaList[self.numb_for])
            elif criteriaList[self.numb_for] in timecriteria:
                self.theCursor.execute(
                    "SELECT " + criteriaList[self.numb_for].split('.')[1] +
                    " FROM " + criteriaList[self.numb_for].split('.')[0])
                listoptions = list(
                    set([
                        x[0].split(" ")[0] for x in self.theCursor.fetchall()
                    ]))
                datemin = min(listoptions)
                datemax = max(listoptions)
                self.minmaxcriteriaRefinement(criteriaList[self.numb_for],
                                              datemin, datemax)
#                print(criteriaList[self.numb_for])
            else:
                self.bydeffunction()

#            print(self.numb_for)
            self.numb_for += 1
#            print("")
        else:
            #            print("finished")
            #            print(parameterList)
            #            print(criteriaList)
            #            print(criteriaListdetailled)
            #            print(criteriaListdetailled2)

            self.SearchingAndExporting()

################################################################################
################################################################################

    def SearchingAndExporting(self):
        global parameterList, criteriaList, criteriaexclusionlist, dropdowncriteria, fromtocriteria, timecriteria
        global criteriaListdetailled, criteriaListdetailled2, tablesAndcolnames, SetallcolnamesWOids

        path = filedialog.asksaveasfilename(
            title="Select where to save the extracted data",
            defaultextension=".xlsx")

        try:
            self.dropdownwindow.destroy()
        except:
            pass
        try:
            self.minmaxwindow.destroy()
        except:
            pass

        parametertables = list(set([x.split('.')[0] for x in parameterList]))
        dictparam = {}
        for item in parametertables:
            dictparam[item] = []
        for item in parameterList:
            dictparam[item.split('.')[0]].append(item)

        ####################
        workbook = xlsxwriter.Workbook(path)
        worksheet1 = workbook.add_worksheet("DB info")

        self.theCursor.execute(
            "SELECT COUNT(*) FROM batch")  # * means everything
        numbbatch = self.theCursor.fetchall()[0][0]
        worksheet1.write(0, 0, "number of batch")
        worksheet1.write(0, 1, numbbatch)
        #print(numbbatch)
        self.theCursor.execute(
            "SELECT COUNT(*) FROM samples")  # * means everything
        numbsamples = self.theCursor.fetchall()[0][0]
        worksheet1.write(1, 0, "number of samples")
        worksheet1.write(1, 1, numbsamples)
        #print(numbsamples)
        self.theCursor.execute(
            "SELECT COUNT(*) FROM cells")  # * means everything
        numbcells = self.theCursor.fetchall()[0][0]
        worksheet1.write(2, 0, "number of cells")
        worksheet1.write(2, 1, numbcells)
        #print(numbcells)
        self.theCursor.execute(
            "SELECT COUNT(*) FROM JVmeas")  # * means everything
        numbJVmeas = self.theCursor.fetchall()[0][0]
        worksheet1.write(3, 0, "number of JV scans")
        worksheet1.write(3, 1, numbJVmeas)
        #print(numbJVmeas)
        worksheet1.write(6, 0, "highest efficiency")
        self.theCursor.execute("SELECT Eff FROM JVmeas")  # * means everything
        numbJVmeas = self.theCursor.fetchall()
        #print(max(numbJVmeas)[0])
        worksheet1.write(6, 1, max(numbJVmeas)[0])
        self.theCursor.execute(
            """SELECT batchname, startdate, users.username
                          FROM batch
                          INNER JOIN JVmeas ON batch.id = JVmeas.batch_id
                          INNER JOIN users ON batch.users_id = users.id
                          WHERE JVmeas.Eff=?""", (max(numbJVmeas)[0], ))
        numbJVmeas = self.theCursor.fetchall()[0]
        #print(numbJVmeas)
        worksheet1.write(6, 2, numbJVmeas[0])
        worksheet1.write(6, 3, numbJVmeas[1])
        worksheet1.write(6, 4, numbJVmeas[2])
        worksheet1.write(7, 0, "highest Voc")
        self.theCursor.execute("SELECT Voc FROM JVmeas")  # * means everything
        numbJVmeas = self.theCursor.fetchall()
        #print(max(numbJVmeas)[0])
        worksheet1.write(7, 1, max(numbJVmeas)[0])
        self.theCursor.execute(
            """SELECT batchname, startdate, users.username
                          FROM batch
                          INNER JOIN JVmeas ON batch.id = JVmeas.batch_id
                          INNER JOIN users ON batch.users_id = users.id
                          WHERE JVmeas.Voc=?""", (max(numbJVmeas)[0], ))
        numbJVmeas = self.theCursor.fetchall()[0]
        #print(numbJVmeas)
        worksheet1.write(7, 2, numbJVmeas[0])
        worksheet1.write(7, 3, numbJVmeas[1])
        worksheet1.write(7, 4, numbJVmeas[2])

        worksheet1.write(8, 0, "highest Jsc")
        self.theCursor.execute("SELECT Jsc FROM JVmeas")  # * means everything
        numbJVmeas = self.theCursor.fetchall()
        #print(max(numbJVmeas)[0])
        worksheet1.write(8, 1, max(numbJVmeas)[0])
        self.theCursor.execute(
            """SELECT batchname, startdate, users.username
                          FROM batch
                          INNER JOIN JVmeas ON batch.id = JVmeas.batch_id
                          INNER JOIN users ON batch.users_id = users.id
                          WHERE JVmeas.Jsc=?""", (max(numbJVmeas)[0], ))
        numbJVmeas = self.theCursor.fetchall()[0]
        #print(numbJVmeas)
        worksheet1.write(8, 2, numbJVmeas[0])
        worksheet1.write(8, 3, numbJVmeas[1])
        worksheet1.write(8, 4, numbJVmeas[2])

        worksheet1.write(9, 0, "highest FF")
        self.theCursor.execute("SELECT FF FROM JVmeas")  # * means everything
        numbJVmeas = self.theCursor.fetchall()
        #print(max(numbJVmeas)[0])
        worksheet1.write(9, 1, max(numbJVmeas)[0])
        self.theCursor.execute(
            """SELECT batchname, startdate, users.username
                          FROM batch
                          INNER JOIN JVmeas ON batch.id = JVmeas.batch_id
                          INNER JOIN users ON batch.users_id = users.id
                          WHERE JVmeas.FF=?""", (max(numbJVmeas)[0], ))
        numbJVmeas = self.theCursor.fetchall()[0]
        #print(numbJVmeas)
        worksheet1.write(9, 2, numbJVmeas[0])
        worksheet1.write(9, 3, numbJVmeas[1])
        worksheet1.write(9, 4, numbJVmeas[2])

        worksheet1.write(14, 0, "List of search criteria:")
        critlist = criteriaListdetailled + criteriaListdetailled2
        #print(critlist)
        for item in range(len(critlist)):
            for item0 in range(len(critlist[item])):
                if type(critlist[item][item0]) != list:
                    worksheet1.write(item + 15, item0, critlist[item][item0])
                else:
                    for item1 in range(len(critlist[item][item0])):
                        worksheet1.write(item + 15, item0 + item1,
                                         critlist[item][item0][item1])

        ####################
        parametertables = sorted(parametertables, key=lambda s: s.casefold())

        for item1 in parametertables:
            if item1 != "characsetups":
                #            print("\n"+item1)
                tablenames = list(
                    set(["batch", "samples"] +
                        [x.split('.')[0] for x in criteriaList + [item1]]))
                #            print(tablenames)
                wherelist = ["samples.batch_id = batch.id AND "]
                for item in tablenames:
                    self.theCursor.execute("SELECT * FROM " + item)
                    headcol = [x[0] for x in self.theCursor.description]
                    headcol = [x[:-3] for x in headcol if '_id' in x]
                    for item2 in headcol:
                        if item2 in tablenames:
                            wherelist.append(item + '.' + item2 + '_id = ' +
                                             item2 + '.id AND ')
                wherelist = list(set(wherelist))
                #            print(wherelist)
                listwosamplename = [
                    "batch", "environment", "users", "takencharacsetups"
                ]
                if item1 in listwosamplename:
                    SelectInstructions = "SELECT batch.batchname, "
                    heads = ["batchname"]
                    for item in dictparam[item1]:
                        if item != "batch.batchname":
                            SelectInstructions += item + ', '
                            heads.append(item.split('.')[1])
                else:
                    SelectInstructions = "SELECT samples.samplename, "
                    heads = ["samplename"]
                    for item in dictparam[item1]:
                        if item != "samples.samplename":
                            SelectInstructions += item + ', '
                            heads.append(item.split('.')[1])

                SelectInstructions = SelectInstructions[:-2] + ' FROM '
                for item in tablenames:
                    SelectInstructions += item + ', '
                SelectInstructions = SelectInstructions[:-2] + " WHERE "
                for item in wherelist:
                    SelectInstructions += item
                for item in criteriaListdetailled:
                    SelectInstructions += '('
                    for item2 in item[1]:
                        SelectInstructions += item[0] + ' = ' + "'" + str(
                            item2) + "' OR "
                    SelectInstructions = SelectInstructions[:-4] + ') AND '
                for item in criteriaListdetailled2:
                    SelectInstructions += '(' + item[0] + ' BETWEEN ' + item[
                        1] + ' AND ' + item[2] + ') AND '
                self.theCursor.execute(SelectInstructions[:-4] +
                                       "ORDER BY samples.samplename ASC")
                data = list(set(self.theCursor.fetchall()))
                data = sorted(data, key=lambda x: str(x[0]))
                if data != []:
                    data = [tuple(heads)] + data
                    worksheetx = workbook.add_worksheet(item1)
                    for item in range(len(data)):
                        for item0 in range(len(data[item])):
                            worksheetx.write(item, item0, data[item][item0])
                if item1 == "samples":
                    length = len(data) - 1

        worksheet1.write(12, 0, length)
        worksheet1.write(12, 1, "samples found")

        workbook.close()

        parameterList = []
        tablesAndcolnames = []
        SetallcolnamesWOids = []
        criteriaList = []
        criteriaListdetailled = []
        criteriaListdetailled2 = []

        self.theCursor.close()
        self.db_conn.close()
        self.deiconify()
        #        self.master.destroy()
        #        print(len(data))
        messagebox.showinfo("#results", str(length) + " samples found")
        #        self.backtomain()
        os.startfile(path)

################################################################################
################################################################################

    def backtomain(self):
        global parameterList, criteriaList, tablesAndcolnames, criteriaexclusionlist, dropdowncriteria, fromtocriteria, timecriteria
        global criteriaListdetailled, criteriaListdetailled2, SetallcolnamesWOids

        try:
            self.selectionwindow.destroy()
        except:
            pass
        try:
            self.criteriawindow.destroy()
        except:
            pass
        try:
            self.dropdownwindow.destroy()
        except:
            pass
        try:
            self.minmaxwindow.destroy()
        except:
            pass

        parameterList = []
        tablesAndcolnames = []
        SetallcolnamesWOids = []
        criteriaList = []
        criteriaListdetailled = []
        criteriaListdetailled2 = []

        self.theCursor.close()
        self.db_conn.close()
        self.deiconify()
コード例 #43
0
from tkinter import Tk, Listbox, Button, Scrollbar


def get():
    userline = leftside.get('active')
    print(userline)


thescale = Tk()
thescale.geometry('600x600')
scroll = Scrollbar(thescale)
scroll.pack(side='right', fill='y')

leftside = Listbox(thescale,
                   bg='#333',
                   fg='#ccc',
                   yscrollcommand=scroll.set,
                   width=10,
                   selectbackground='#333',
                   font=('Times New Roman', 24))
for line in range(101):
    leftside.insert('end', "Scale " + str(line))

leftside.place(x=0, y=0)
scroll.config(command=leftside.yview)

selectbutton = Button(thescale, text="Select")
selectbutton.pack()

thescale.mainloop()
コード例 #44
0
 def __init__(self, master, lists):
     Frame.__init__(self, master)
     self.lists = []
     for list_, widget in lists:
         frame = Frame(self)
         frame.pack(side=LEFT, expand=YES, fill=BOTH)
         Label(frame, text=list_, borderwidth=1, relief=RAISED).pack(fill=X)
         list_box = Listbox(
             frame,
             width=widget,
             borderwidth=0,
             selectborderwidth=0,
             relief=FLAT,
             exportselection=FALSE,
         )
         list_box.pack(expand=YES, fill=BOTH)
         self.lists.append(list_box)
         list_box.bind("<B1-Motion>", lambda e, s=self: s._select(e.y))
         list_box.bind("<Button-1>", lambda e, s=self: s._select(e.y))
         list_box.bind("<Leave>", lambda e: "break")
         list_box.bind("<B2-Motion>",
                       lambda e, s=self: s._b2motion(e.x, e.y))
         list_box.bind("<Button-2>", lambda e, s=self: s._button2(e.x, e.y))
     frame = Frame(self)
     frame.pack(side=LEFT, fill=Y)
     Label(frame, borderwidth=1, relief=RAISED).pack(fill=X)
     scroll = Scrollbar(frame, orient=VERTICAL, command=self._scroll)
     scroll.pack(expand=YES, fill=Y)
     self.lists[0]["yscrollcommand"] = scroll.set
コード例 #45
0
ファイル: trial2.py プロジェクト: sshah257/WesternSSCapp_v2
    def register(self):
        try:
            pythoncom.RegisterDragDrop(
                self.hwnd,
                pythoncom.WrapObject(self, pythoncom.IID_IDropTarget,
                                     pythoncom.IID_IDropTarget))
        except pywintypes.com_error:
            global text_list
            text_list = ["COM failure!"]


def update_list():
    listbox.delete(0, END)
    for t in text_list:
        listbox.insert(END, t)
    root.after(100, update_list)


root = Tk()
root.geometry('720x360')
listbox = Listbox(root, font=("Courier", 10, "normal"))
listbox.pack(fill=BOTH, expand=1)
text_list = ['Drag files to this window.']

hwnd = root.winfo_id()
pythoncom.OleInitialize()

root.after(100, update_list)
root.after(200, DropTarget, hwnd)
root.mainloop()
    def __init__(self):
        super().__init__()
        self.janela.wm_title("emprestimo/devolucao - DELIBRARY")

        self.txt_id_livro_emprestimo = StringVar()
        self.txt_nome_livro_emprestimo = StringVar()
        self.txt_genero_livro_emprestimo = StringVar()
        self.txt_autor_livro_emprestimo = StringVar()
        self.txt_area_livro_emprestimo = StringVar()
        self.txt_editora_livro_emprestimo = StringVar()
        self.txt_edicao_livro_emprestimo = StringVar()
        self.txt_login_cliente_emprestimo = StringVar()
        self.txt_senha_cliente_emprestimo = StringVar()
        #
        self.txt_id_livro_devolucao = StringVar()
        self.txt_login_cliente_devolucao = StringVar()

        self.lbl_emprestimo = Label(self.janela, text="Emprestimo")
        self.lbl_id_livro_emprestimo = Label(self.janela, text="ID")
        self.lbl_nome_livro_emprestimo = Label(self.janela, text="Nome")
        self.lbl_genero_livro_emprestimo = Label(self.janela, text="Genero")
        self.lbl_autor_livro_emprestimo = Label(self.janela, text="Autor")
        self.lbl_area_livro_emprestimo = Label(self.janela, text="Area")
        self.lbl_editora_livro_emprestimo = Label(self.janela, text="Editora")
        self.lbl_edicao_livro_emprestimo = Label(self.janela, text="Edicao")
        self.lbl_login_cliente_emprestimo = Label(self.janela,
                                                  text="Login do Cliente")
        self.lbl_senha_cliente_emprestimo = Label(self.janela,
                                                  text="Senha do Cliente")
        #
        self.lbl_devolucao = Label(self.janela, text="Devoluçao")
        self.lbl_id_livro_devolucao = Label(self.janela, text="ID")
        self.lbl_login_cliente_devolucao = Label(self.janela,
                                                 text="Login do Cliente")
        self.lbl_info_emprestado = Label(self.janela,
                                         text="Livros emprestados")
        self.lbl_info_disponivel = Label(self.janela, text="Livros disponivel")

        self.ent_id_livro_emprestimo = Entry(
            self.janela, textvariable=self.txt_id_livro_emprestimo)
        self.ent_nome_livro_emprestimo = Entry(
            self.janela, textvariable=self.txt_nome_livro_emprestimo)
        self.ent_genero_livro_emprestimo = Entry(
            self.janela, textvariable=self.txt_genero_livro_emprestimo)
        self.ent_autor_livro_emprestimo = Entry(
            self.janela, textvariable=self.txt_autor_livro_emprestimo)
        self.ent_area_livro_emprestimo = Entry(
            self.janela, textvariable=self.txt_area_livro_emprestimo)
        self.ent_editora_livro_emprestimo = Entry(
            self.janela, textvariable=self.txt_editora_livro_emprestimo)
        self.ent_edicao_livro_emprestimo = Entry(
            self.janela, textvariable=self.txt_edicao_livro_emprestimo)
        self.ent_login_cliente_emprestimo = Entry(
            self.janela, textvariable=self.txt_login_cliente_emprestimo)
        self.ent_senha_cliente_emprestimo = Entry(
            self.janela,
            textvariable=self.txt_senha_cliente_emprestimo,
            show="*")
        self.ent_id_livro_devolucao = Entry(
            self.janela, textvariable=self.txt_id_livro_devolucao)
        self.ent_login_cliente_devolucao = Entry(
            self.janela, textvariable=self.txt_login_cliente_devolucao)

        self.btn_emprestimo = Button(self.janela, width=15, text="Emprestimo")
        self.btn_obter_info_emprestimo = Button(self.janela,
                                                width=15,
                                                text="Verificar")
        self.btn_devolucao = Button(self.janela, width=15, text="Devolução")
        self.btn_obter_info_devolucao = Button(self.janela,
                                               width=15,
                                               text="Pesquisar")
        self.btn_sair = Button(self.janela, width=15, text="Sair")

        self.list_emprestimo = Listbox(self.janela, width=85)
        self.scroll_emprestimo = Scrollbar(self.janela)
        self.list_devolucao = Listbox(self.janela, width=85)
        self.scroll_devolucao = Scrollbar(self.janela)
コード例 #47
0
class DeletaCliente(Toplevel):
    '''Classe interface cadastrar cliente'''
    def __init__(self, master=None):
        Toplevel.__init__(self, master=master)
        self.cliente = Cliente()
        self.dao = ClienteDAO()

        self.geometry('1500x850+0+0')
        self.title('Excluir cliente')
        self.resizable(0, 0)  # impede de maximizar
        self.configure(background='#c9c9ff')

        self.id = None

        self.heading = Label(self,
                             text="Excluir um cliente do banco de dados",
                             bg='#c9c9ff',
                             fg='white',
                             font=('Verdana 20 bold'))
        self.heading.place(x=550, y=50)

        self.pesquisar_veiculo = Label(self,
                                       text="Pesquisar por nome:",
                                       bg='#c9c9ff',
                                       font=('Verdana  15 bold'))
        self.pesquisar_veiculo.place(x=40, y=150)

        self.search_var = StringVar()
        self.search_var.trace("w",
                              lambda name, index, mode: self.view_command())
        self.search_entry = Entry(self,
                                  textvariable=self.search_var,
                                  width=20,
                                  font=('Verdana  15 bold'))
        self.search_entry.place(x=300, y=150)

        # LIST BOX =============================================================
        self.lista_clientes = Listbox(self,
                                      width=95,
                                      height=10,
                                      font=('Verdana 15 bold'))
        self.lista_clientes.place(x=40, y=300)

        # BOTOES =================================================================
        self.botao_deletar = Button(self,
                                    text="Deletar cliente do banco de dados",
                                    width=46,
                                    height=1,
                                    bg='#baffc9',
                                    fg='black',
                                    font=('Verdana  15 bold'),
                                    command=self.delete)
        self.botao_deletar.place(x=40, y=600)

        self.botao_sair = Button(self,
                                 text="Sair",
                                 width=46,
                                 height=1,
                                 bg='#ffb3ba',
                                 fg='black',
                                 font=('Verdana  15 bold'),
                                 command=self.close)
        self.botao_sair.place(x=720, y=600)

        # self.botao_pesquisar = Button(self, text="Pesquisar", width=20, height=1, bg='#ffdfba', fg='black', font=(
        #     'Verdana  15 bold'))
        # self.botao_pesquisar.place(x=620, y=140)

        # Associando a Scrollbar com a Listbox...
        self.scrollbar_cliente = Scrollbar(self)
        self.lista_clientes.configure(
            yscrollcommand=self.scrollbar_cliente.set)
        self.scrollbar_cliente.configure(command=self.lista_clientes.yview)
        self.scrollbar_cliente.place(x=1375,
                                     y=300,
                                     relheight=0.31,
                                     anchor='ne')

        self.pesquisar_cliente = Label(self,
                                       text="Lista de clientes cadastrados:",
                                       bg='#c9c9ff',
                                       font=('Verdana 15 bold'))
        self.pesquisar_cliente.place(x=40, y=260)

        self.view_command()
        self.lista_clientes.bind('<<ListboxSelect>>', self.selecionar_list_box)

    def view_command(self):
        "método para visualização dos resultados"
        try:
            rows = self.dao.view()
            self.lista_clientes.delete(0, END)
            for r in rows:
                if str(self.search_var.get()).lower() in str(r).lower():
                    self.lista_clientes.insert(END, r)
        except Exception as e:
            print(e)

    # def get_items(self):
    #     self.cliente.nome = self.nome_entry.get()
    #     self.cliente.rg = self.rg_entry.get()
    #     self.cliente.cpf = self.cpf_entry.get()
    #     self.cliente.email = self.email_entry.get()
    #     self.cliente.telefone = self.telefone_entry.get()
    #     self.cliente.nascimento = self.nascimento_entry.get()
    #     self.cliente.estado_civil = self.estado_civil_entry.get()
    #     self.cliente.genero = self.genero_entry.get()

    def selecionar_list_box(self, event):
        if self.lista_clientes.curselection():
            indice = self.lista_clientes.curselection()[0]
            self.selecionado = self.lista_clientes.get(indice)

            self.id = self.selecionado[0]

    def delete(self):
        try:
            self.dao.delete(self.id)
        except Exception:
            tkinter.messagebox.showinfo('Aviso!',
                                        'Erro ao acessar o banco de dados.')
        else:
            tkinter.messagebox.showinfo('Aviso!',
                                        'Produto Excluido com Sucesso!')
            self.view_command()

    # def clear_all(self):
    # self.nome_entry.delete(0, END)
    # self.rg_entry.delete(0, END)
    # self.cpf_entry.delete(0, END)
    # self.email_entry.delete(0, END)
    # self.telefone_entry.delete(0, END)
    # self.nascimento_entry.delete(0, END)
    # self.estado_civil_entry.delete(0, END)
    # self.genero_entry.delete(0, END)
    # self.cep_entry.delete(0, END)
    # self.logradouro_entry.delete(0, END)
    # self.bairro_entry.delete(0, END)
    # self.numero_logradouro_entry.delete(0, END)
    # self.cidade_entry.delete(0, END)
    # self.estado_entry.delete(0, END)
    # self.complemento_entry.delete(0, END)
    # self.numero_cnh_entry.delete(0, END)
    # self.numero_registro_cnh_entry.delete(0, END)
    # self.data_validade_cnh_entry.delete(0, END)
    # self.uf_cnh_entry.delete(0, END)
    # self.contato_emergencial_entry.delete(0, END)
    # self.nome_contato_emergencial_entry.delete(0, END)
    '''
    def view_command(self):
        "método para visualização dos resultados"
        try:
            rows = self.dao.view()
            self.lista_clientes.delete(0, END)
            for r in rows:
                self.lista_clientes.insert(END, r)
        except Exception as e:
            print(e)

    def search_command(self):
        "método para buscar registros"
        self.lista_clientes.delete(0, END)
        self.__fill_current_client()
        try:
            rows = self.dao.search(self.currentClient)
            for r in rows:
                self.gui.lista_clientes.insert(END, r)
        except Exception as e:
            print(e)
    '''

    def close(self):
        self.dao.close()
        self.destroy()

    def run(self):
        self.mainloop()
コード例 #48
0
ファイル: Mao.py プロジェクト: ssurava/MyProjects
import pandas as pd
import tkinter as tk
from tkinter import Listbox, Message, Button, Canvas
from PIL import Image, ImageTk
m = tk.Tk()
m.configure(background="blue")
m.title("This is Mao")
ourMessage = 'Mao, there are no rules'
messageVar = Message(m, text=ourMessage)
messageVar.config(bg='orange')
messageVar.pack()

y = np.array([
    "1)Rule1", "2)Rule2", "3)Rule3", "4)Rule4", "5)Rule5", "6)Rule6", "7)Rule7"
])
lb = Listbox(m)


def easy():
    x = np.random.randint(0, 3)
    lb.insert(x, y[x])
    lb.pack()


def medium():
    x = np.random.randint(0, 5)
    lb.insert(x, y[x])
    lb.pack()


def hard():
コード例 #49
0
class Chatwindows(tk.Tk):
    '''
    Main Chat window
    '''
    def __init__(self, input_q, output_q):
        super().__init__()
        self.update_scaling_unit()
        # self.adjust_size()
        self.title("EnigmaChat")
        self.frame = Frame(self)
        self.rowconfigure(0, weight=1)
        self.columnconfigure(0, weight=1)
        self.frame.grid(row=0, column=0, sticky=N + S + E + W)
        self.organize_widgets(self.frame)
        self.input_q = input_q
        self.output_q = output_q
        self.resizable(width=False, height=False)
        self.listlen = 0

    def organize_widgets(self, frame):
        '''
        initialize the widgets
        '''
        self.chatbox = Text(frame, height=20, width=35, font=12)
        self.chatbox.grid(row=0, column=0, sticky=N + S + E + W)
        self.chatbox.config(state=DISABLED)
        self.chatbox.tag_config('INFO', foreground='blue')
        self.chatbox.tag_config('ERROR', foreground='red')
        # svar = StringVar()
        # svar.trace("w", lambda name, index, mode, sv=svar: self.messagebox_onchange(sv))
        self.messagebox = Text(frame, height=5, width=35, font=12)
        self.messagebox.grid(row=1, column=0, sticky=N + S + E + W)
        # self.messagebox.bind('<<Modified>>', self.messagebox_onchange)

        self.listbox = Listbox(frame, font=12, width=20)
        self.listbox.grid(row=0, column=1, rowspan=2, sticky=N + S + E + W)
        self.sendbutton = Button(frame,
                                 text="Send",
                                 command=self.send_message,
                                 font=12,
                                 width=5,
                                 height=1)
        self.sendbutton.grid(row=2, column=0)
        self.sendbutton.config(state=DISABLED)
        self.serverentry = Entry(frame, width=18, font=8)
        self.serverentry.insert(END, '127.0.0.1:7654')
        self.serverentry.grid(row=3, column=0, sticky=W)
        self.connbutton = Button(frame,
                                 text="Connect",
                                 font=8,
                                 width=10,
                                 height=1,
                                 command=self.connect)

        self.connbutton.grid(row=3, column=0, sticky=E)

        # self.statusbar = Message(
        #     frame, text='Ready to Connect')
        # self.statusbar.grid(row=2, rowspan=2, column=1)

        frame.rowconfigure(0, weight=10)
        frame.rowconfigure(1, weight=2)
        frame.rowconfigure(2, weight=1)
        frame.columnconfigure(0, weight=2)
        frame.columnconfigure(1, weight=3)

    def update_scaling_unit(self):
        '''
        get current windows resolution
        '''
        # Get screen size
        screen_width = self.winfo_screenwidth()
        screen_height = self.winfo_screenheight()

        # Make a scaling unit, this is bases on average percentage from
        # width and height.
        self.width_unit = screen_width / 100
        self.height_unit = screen_height / 100

    def adjust_size(self):
        '''
        resize the windows
        '''
        height = int(50 * self.height_unit)
        width = int(50 * self.height_unit) * WIDTH_HEIGHT_RATIO
        self.geometry("%dx%d" % (width, height))
        self.minsize(width=width, height=width)

    def update(self):
        '''
        the main polling function the communicate with client
        '''
        if not self.output_q.empty():
            inputinfo = self.output_q.get(True, 0.5)
            if inputinfo['cmd'] == 1:
                self.add_chat_record(inputinfo['body'])
            elif inputinfo['cmd'] == 0:
                self.add_system_record(1, inputinfo['body'])
            # connect successfully
            elif inputinfo['cmd'] == 2:
                self.connbutton.config(state=DISABLED)
                self.sendbutton.config(state=NORMAL)
            # print(inputinfo)
            elif inputinfo['cmd'] == 4:
                self.update_list(inputinfo['body'])

        self.after(20, self.update)

    def add_chat_record(self, message):
        '''
        add message to chatbox
        '''
        self.chatbox.config(state=NORMAL)
        self.chatbox.insert(END, message.strip() + '\n')
        self.chatbox.config(state=DISABLED)
        self.chatbox.see(END)

    def add_system_record(self, infotype, info):
        '''
        the system info display
        '''
        self.chatbox.config(state=NORMAL)
        if infotype == 1:
            self.chatbox.insert(END, "INFO:" + info.strip() + '\n', 'INFO')
        else:
            self.chatbox.insert(END, "BUG:" + info.strip() + '\n', 'BUG')
        self.chatbox.config(state=DISABLED)
        self.chatbox.see(END)

    def send_message(self):
        '''
        send message through the queue
        '''
        message = self.messagebox.get("1.0", END)
        if message != '':
            self.input_q.put({'cmd': 0, 'body': message})
            self.messagebox.delete('1.0', END)

    def connect(self):
        '''
        send connect command to the queue
        '''
        # self.statusbar.config(text="Connecting")
        self.input_q.put({'cmd': 1, 'body': self.serverentry.get()})

    def update_list(self, clientlist):
        '''
        update the online user list
        '''
        # print("update list")
        self.listbox.delete(0, END)
        for i, item in enumerate(clientlist):
            self.listbox.insert(i + 1, item)
        self.listlen = len(clientlist)
コード例 #50
0
# Setup fields for the search function
find_frame = Frame(root, bg="#6c4cfc", bd=5)
find_frame.place(relx=0.5, rely=0.55, relwidth=0.3, relheight=0.1, anchor="n")

find_button = Button(find_frame,
                     text="GO!",
                     bg="white",
                     command=get_businesses,
                     font=("Century", 20))
find_button.place(relwidth=1, relheight=1)

# Setup fields for the results based on filters
results_frame = Frame(root, bg="#6c4cfc", bd=5)
results_frame.place(relx=0.5,
                    rely=0.7,
                    relwidth=0.8,
                    relheight=0.2,
                    anchor="n")

scrlbr = Scrollbar(results_frame, orient="vertical")

results_listbox = Listbox(results_frame,
                          yscrollcommand=scrlbr.set,
                          font=("Century", 10))
results_listbox.place(relwidth=0.95, relheight=1)

scrlbr.config(command=results_listbox.yview)
scrlbr.place(relwidth=0.05, relheight=1, relx=0.95, rely=0)

root.mainloop()
コード例 #51
0
    def __init__(self, parent):
        self.is_future = False
        #inputday
        hour = StringVar()
        hour.set('0--23')
        minute = StringVar()
        minute.set('0--59')
        self.btncheck_list = []
        self.plistback = []
        #self.judgepas = []
        self.varp = []  #num与它有关
        num = -1
        self.page = 0
        self.allpage = 0

        self.next = parent

        self.next.geometry('960x930+300+0')
        self.canvas = Canvas(self.next)
        self.canvas.place(relx=0, rely=0, relwidth=1, relheight=1)
        """
        self.vbar = Scrollbar(self.canvas, orient=VERTICAL)  # 竖直滚动条
        self.vbar.place(x=180, width=20, height=180)
        self.vbar.configure(command=self.canvas.yview)
        self.canvas.config( yscrollcommand=self.vbar.set)  # 设置
        self.canvas.create_window((90, 240), window=self.frame)  # create_window
        """
        self.frameAll = Frame(self.canvas, bg='#f0f0f0')
        self.frameAll.place(relx=0, rely=0, relwidth=1, relheight=1)
        self.next.title('车站信息')
        self.nresulte = StringVar()
        self.nresulte.set('北京')  # 显示面板显示结果1,用于显示默认数字0
        self.nresulte1 = StringVar()
        self.nresulte1.set('天津')
        self.nresulte2 = StringVar()
        self.nresulte2.set('2018')
        self.nresulte3 = StringVar()
        self.nresulte3.set('07')
        self.nresulte4 = StringVar()
        self.nresulte4.set('01')
        self.nresulte5 = StringVar()
        self.nresulte5.set(strtime)

        def sendtimeInfor():
            print('我进来了')
            self.top.destroy()

        def show_success():
            self.book_tickets = Toplevel(self.next)
            self.book_tickets.title("抢票")
            self.book_tickets.geometry('480x130+300+0')
            l = Label(self.book_tickets,
                      font=('微软雅黑', 12),
                      fg='green',
                      bd='1',
                      anchor='w',
                      text='抢票成功!!!')
            l.pack()

        def check_book_f():
            if lo.myTickets.book_tickets_on_sale(self.tickets_list[5],
                                                 self.inputday,
                                                 self.plistback):
                show_success()
            print('future')

        def check_book_t():
            if lo.myTickets.book_tickets_on_sale(self.tickets_list[5],
                                                 self.inputday,
                                                 self.plistback):
                show_success()
            print('on sale')

        # self.nresulte = StringVar()
        # self.nresulte.set('请您输入用户名')
        # self.nresulte1 = StringVar()
        # self.nresulte1.set('请您输入密码')
        def sendInfor():

            value = self.entryfromdayyear.get()
            value2 = self.entryfromdaymonth.get()
            value3 = self.entryfromdayday.get()
            #print(value[0:4])
            print(value.isdigit())
            print(len(value))
            print(len(value2))
            if value.isdigit() == False or value2.isdigit(
            ) == False or value3.isdigit() == False or len(value) != 4 or len(
                    value2) != 2 or len(value3) != 2:
                self.nresulte2.set('2018')
                self.nresulte3.set('07')
                self.nresulte3.set('01')
                #print( self.entryfromday.get())
                self.entryfromdayyear = Entry(self.frame,
                                              font=('微软雅黑', 9),
                                              bg='white',
                                              bd='1',
                                              fg='red',
                                              textvariable=self.nresulte2)
                self.entryfromdayyear.place(relx=0.59,
                                            rely=0.17,
                                            width=50,
                                            height=30)
                self.entryfromdaymonth = Entry(self.frame,
                                               font=('微软雅黑', 9),
                                               bg='white',
                                               bd='1',
                                               fg='red',
                                               textvariable=self.nresulte3)
                self.entryfromdaymonth.place(relx=0.68,
                                             rely=0.17,
                                             width=30,
                                             height=30)
                self.entryfromdayday = Entry(self.frame,
                                             font=('微软雅黑', 9),
                                             bg='white',
                                             bd='1',
                                             fg='red',
                                             textvariable=self.nresulte4)
                self.entryfromdayday.place(relx=0.75,
                                           rely=0.17,
                                           width=30,
                                           height=30)

                lo.set_judgecheck(0)

            self.inputday = value + '-' + value2 + '-' + value3
            inputdaydt = datetime.datetime.strptime(self.inputday, '%Y-%m-%d')
            print(self.inputday)
            print(maxday)
            if self.inputday == maxday:
                self.is_future = True

            if self.is_future == True:
                self.top = Toplevel(self.next)
                self.top.title("抢票时间")
                self.top.geometry('480x130+300+0')
                l = Label(self.top,
                          font=('微软雅黑', 12),
                          fg='red',
                          bd='1',
                          anchor='w',
                          text='还无法抢' + self.inputday + '的票,请输入开始抢票时间')
                l.pack()

                lh = Label(self.top,
                           font=('微软雅黑', 12),
                           bg='#D2E9FF',
                           bd='1',
                           fg='black',
                           anchor='w',
                           text='时:')
                lh.place(relx=0.15, rely=0.2, width=70, height=30)
                print("我执行了")
                eh = Entry(self.top,
                           font=('微软雅黑', 12),
                           bg='white',
                           bd='1',
                           fg='#828282',
                           textvariable=hour)

                eh.place(relx=0.35, rely=0.2, width=150, height=30)
                lm = Label(self.top,
                           font=('微软雅黑', 12),
                           bg='#D2E9FF',
                           bd='1',
                           fg='black',
                           anchor='w',
                           text='分:')
                lm.place(relx=0.15, rely=0.45, width=70, height=30)
                em = Entry(self.top,
                           font=('微软雅黑', 12),
                           bg='white',
                           bd='1',
                           fg='#828282',
                           textvariable=minute)

                em.place(relx=0.35, rely=0.45, width=150, height=30)
                btnright = Button(self.top,
                                  font=(
                                      '微软雅黑',
                                      12,
                                  ),
                                  bg='#ffa042',
                                  fg='white',
                                  text='确  定',
                                  activeforeground='#00FFFF',
                                  command=sendtimeInfor)
                btnright.place(relx=0.35, rely=0.7, width=150, height=30)
            if inputdaydt >= todaytime + datetime.timedelta(
                    days=-1) and inputdaydt <= maxdaytime:
                print('good')
                self.labeldtx = Label(self.frametx,
                                      font=('微软雅黑', 12),
                                      bd='9',
                                      fg='red',
                                      anchor='w',
                                      text=' ')
                self.labeldtx.place(relx=0.5, rely=0.17, width=90, height=20)
                lo.set_judgecheck(1)
            else:
                self.labeldtx = Label(self.frametx,
                                      font=('微软雅黑', 12),
                                      bd='9',
                                      fg='red',
                                      anchor='w',
                                      text='时间超限')
                self.labeldtx.place(relx=0.5, rely=0.17, width=90, height=20)
                lo.set_judgecheck(0)

            print(lo.get_judgecheck())
            if lo.get_judgecheck() == 1:
                self.entryfromday = Entry(self.frame,
                                          font=('微软雅黑', 9),
                                          bg='white',
                                          bd='1',
                                          fg='black',
                                          textvariable=self.nresulte2)
                self.entryfromday.place(relx=0.59,
                                        rely=0.17,
                                        width=50,
                                        height=30)
                self.entryfromdayyear.place(relx=0.59,
                                            rely=0.17,
                                            width=50,
                                            height=30)
                self.entryfromdaymonth = Entry(self.frame,
                                               font=('微软雅黑', 9),
                                               bg='white',
                                               bd='1',
                                               fg='black',
                                               textvariable=self.nresulte3)
                self.entryfromdaymonth.place(relx=0.68,
                                             rely=0.17,
                                             width=30,
                                             height=30)
                self.entryfromdayday = Entry(self.frame,
                                             font=('微软雅黑', 9),
                                             bg='white',
                                             bd='1',
                                             fg='black',
                                             textvariable=self.nresulte4)
                self.entryfromdayday.place(relx=0.75,
                                           rely=0.17,
                                           width=30,
                                           height=30)

                self.tickets_list = lo.myTickets.get_tickets_info(
                    self.entryfrom.get(), self.entryto.get(), self.inputday,
                    self.is_future)

                numtl = 0
                #self.mylb.delete(0,END)
                self.tllen = len(self.tickets_list)

                self.page = 1
                self.allpage = int((self.tllen) / 20) + 1
                for item in self.tickets_list[0:20]:
                    placey = numtl * 0.05
                    string = '  '
                    for k, v in item.items():
                        if k != 'bookable' and k != 'book_btn':
                            string = string + '{:^8}'.format(v)
                    #print(string)

                    self.stationtickets_list = Label(self.mylb,
                                                     font=('微软雅黑', 10),
                                                     bg='white',
                                                     bd='9',
                                                     width=90,
                                                     height=1,
                                                     fg='black',
                                                     anchor='w',
                                                     text=string)
                    self.stationtickets_list.place(relx=0, rely=placey)

                    if item['bookable'] == False:
                        if self.is_future == True:

                            self.btncheck = Button(self.mylb,
                                                   font=('微软雅黑', 11),
                                                   width=9,
                                                   height=1,
                                                   fg='black',
                                                   text='预  订',
                                                   activeforeground='#00FFFF',
                                                   command=check_book_f)
                            self.btncheck.place(relx=0.88, rely=placey)
                        else:
                            self.btncheck = Button(self.mylb,
                                                   font=('微软雅黑', 11),
                                                   width=9,
                                                   height=1,
                                                   fg='black',
                                                   text='预  订',
                                                   activeforeground='#00FFFF',
                                                   command=check_book_t)
                            self.btncheck.place(relx=0.88, rely=placey)
                    else:
                        self.btncheck = Button(self.mylb,
                                               font=('微软雅黑', 11),
                                               width=9,
                                               height=1,
                                               bg='#ffa042',
                                               fg='black',
                                               text='预  订',
                                               activeforeground='#00FFFF',
                                               command=check_book_t)
                        self.btncheck.place(relx=0.88, rely=placey)

                    #strnum = str(numtl)+'  '+string
                    numtl = numtl + 1
                    print('here')
                    #print(strnum)
                    self.mylb.insert(END, self.stationtickets_list)
                    self.mylb.insert(END, self.btncheck)
                    self.labelnum = Label(self.frameAll,
                                          font=('微软雅黑', 12, 'bold'),
                                          fg='black',
                                          text=self.page)
                    self.labelnum.place(relx=0.475,
                                        rely=0.92,
                                        width=20,
                                        height=30)
                    self.labelnum3 = Label(self.frameAll,
                                           font=('微软雅黑', 12, 'bold'),
                                           fg='black',
                                           text=self.allpage)
                    self.labelnum3.place(relx=0.505,
                                         rely=0.92,
                                         width=20,
                                         height=30)
                    self.btnup = Button(self.frameAll,
                                        font=(
                                            '微软雅黑',
                                            12,
                                        ),
                                        fg='black',
                                        text='上 一 页',
                                        activeforeground='#00FFFF',
                                        command=page_last)
                    self.btnup.place(relx=0.42, rely=0.92, width=80, height=30)
                    '''
                    self.frame4 = Frame(self.frameAll, width=150, height=300)
                    self.frame4.place(relx=0.03,rely=0.26)
                    '''

            lo.set_judgecheck(-1)

        def bindcbtnpas():

            for num in range(len(self.varp)):
                print(self.varp[num].get())
                if self.varp[num].get() == 1:
                    a = 0
                    for num1 in self.plistback:
                        if self.passengers[num] == num1:
                            a = 1
                    if a == 0:
                        self.plistback.append((self.passengers[num]))
                if self.varp[num].get() == 0:
                    b = 0
                    for num1 in self.plistback:
                        if self.passengers[num] == num1:
                            b = 1
                    if b == 1:
                        self.plistback.remove((self.passengers[num]))
            print(self.plistback)

        self.frame = Frame(self.frameAll, bg='#D2E9FF', width=950, height=45)
        self.frame.place(relx=0.2, rely=0.03)
        self.frametx = Frame(self.frameAll, width=950, height=37)
        self.frametx.place(relx=0.2, rely=0.08)
        # place,pace,grid
        self.labely = Label(self.frame,
                            font=('微软雅黑', 12),
                            bg='#D2E9FF',
                            bd='9',
                            fg='black',
                            anchor='w',
                            text='出发地:')
        self.labely.place(relx=0.05, rely=0.17, width=70, height=30)
        self.labelm = Label(self.frame,
                            font=('微软雅黑', 12),
                            bg='#D2E9FF',
                            bd='9',
                            fg='black',
                            anchor='w',
                            text='目的地:')
        self.labelm.place(relx=0.275, rely=0.17, width=70, height=30)
        self.labeld = Label(self.frame,
                            font=('微软雅黑', 12),
                            bg='#D2E9FF',
                            bd='9',
                            fg='black',
                            anchor='w',
                            text='出发日期:')
        self.labeld.place(relx=0.5, rely=0.17, width=90, height=30)
        self.labeldtx = Label(self.frametx,
                              font=('微软雅黑', 9),
                              bd='9',
                              fg='blue',
                              anchor='w',
                              textvariable=self.nresulte5)
        self.labeldtx.place(relx=0.05, rely=0.1, width=250, height=30)
        self.labeldy = Label(self.frame,
                             font=('微软雅黑', 12),
                             bg='#D2E9FF',
                             bd='9',
                             fg='black',
                             anchor='w',
                             text='年')
        self.labeldy.place(relx=0.64, rely=0.17, width=90, height=30)
        self.labeldm = Label(self.frame,
                             font=('微软雅黑', 12),
                             bg='#D2E9FF',
                             bd='9',
                             fg='black',
                             anchor='w',
                             text='月')
        self.labeldm.place(relx=0.71, rely=0.17, width=90, height=30)
        self.labeldd = Label(self.frame,
                             font=('微软雅黑', 12),
                             bg='#D2E9FF',
                             bd='9',
                             fg='black',
                             anchor='w',
                             text='日')
        self.labeldd.place(relx=0.78, rely=0.17, width=90, height=30)
        self.entryfrom = Entry(self.frame,
                               font=('微软雅黑', 9),
                               bg='white',
                               bd='1',
                               fg='#828282',
                               textvariable=self.nresulte)

        self.entryfrom.place(relx=0.12, rely=0.17, width=150, height=30)
        self.entryto = Entry(self.frame,
                             font=('微软雅黑', 9),
                             bg='white',
                             bd='1',
                             fg='#828282',
                             textvariable=self.nresulte1)
        self.entryto.place(relx=0.345, rely=0.17, width=150, height=30)
        self.entryfromdayyear = Entry(self.frame,
                                      font=('微软雅黑', 9),
                                      bg='white',
                                      bd='1',
                                      fg='#828282',
                                      textvariable=self.nresulte2)
        self.entryfromdayyear.place(relx=0.59, rely=0.17, width=50, height=30)
        self.entryfromdaymonth = Entry(self.frame,
                                       font=('微软雅黑', 9),
                                       bg='white',
                                       bd='1',
                                       fg='#828282',
                                       textvariable=self.nresulte3)
        self.entryfromdaymonth.place(relx=0.68, rely=0.17, width=30, height=30)
        self.entryfromdayday = Entry(self.frame,
                                     font=('微软雅黑', 9),
                                     bg='white',
                                     bd='1',
                                     fg='#828282',
                                     textvariable=self.nresulte4)
        self.entryfromdayday.place(relx=0.75, rely=0.17, width=30, height=30)
        self.btncheck = Button(self.frame,
                               font=(
                                   '微软雅黑',
                                   12,
                               ),
                               bg='#ffa042',
                               fg='white',
                               text='查  询',
                               activeforeground='#00FFFF',
                               command=sendInfor)
        self.btncheck.place(relx=0.85, rely=0.17, width=80, height=30)
        '''
            
        def bindcbtn():

            if var.get() == 1:
                print('a')
                # 跳出函数
            else:
                print('b')
            if var1.get() == 1:
                print('a1')
            else:
                print('b1')
            if var2.get() == 1:
                print('a2')
            else:
                print('b2')
            if var3.get() == 1:
                print('a3')
            else:
                print('b3')
            if var4.get() == 1:
                print('a4')
            else:
                print('b4')
            if var5.get() == 1:
                print('a5')
            else:
                print('b5')


        self.frame1 = Frame(self.frameAll, bg='white', width=950, height=45, bd='1')
        self.frame1.place(relx=0.2, rely=0.12)

        var = IntVar()
        var1 = IntVar()
        var2 = IntVar()
        var3 = IntVar()
        var4 = IntVar()
        var5 = IntVar()
        

        self.checkbutton = Checkbutton(self.frame1, font=('微软雅黑', 9), bg='white', bd='9', fg='black', anchor='w',
                                       text='全部', variable=var, onvalue=1, offvalue=0, command=bindcbtn)
        self.checkbutton.place(relx=0.05, rely=0.17, width=70, height=30)
        #self.checkbutton.select()
        self.checkbutton1 = Checkbutton(self.frame1, font=('微软雅黑', 9), bg='white', bd='9', fg='black', anchor='w',
                                        text='GC-高铁/城际', variable=var1, onvalue=1, offvalue=0, command=bindcbtn)
        self.checkbutton1.place(relx=0.2, rely=0.17, width=110, height=30)
        self.checkbutton2 = Checkbutton(self.frame1, font=('微软雅黑', 9), bg='white', bd='9', fg='black', anchor='w',
                                        text='D-动车', variable=var2, onvalue=1, offvalue=0, command=bindcbtn)
        self.checkbutton2.place(relx=0.35, rely=0.17, width=70, height=30)
        self.checkbutton3 = Checkbutton(self.frame1, font=('微软雅黑', 9), bg='white', bd='9', fg='black', anchor='w',
                                        text='Z-直达', variable=var3, onvalue=1, offvalue=0, command=bindcbtn)
        self.checkbutton3.place(relx=0.5, rely=0.17, width=70, height=30)
        self.checkbutton4 = Checkbutton(self.frame1, font=('微软雅黑', 9), bg='white', bd='9', fg='black', anchor='w',
                                        text='T-特快', variable=var4, onvalue=1, offvalue=0, command=bindcbtn)
        self.checkbutton4.place(relx=0.65, rely=0.17, width=70, height=30)
        self.checkbutton5 = Checkbutton(self.frame1, font=('微软雅黑', 9), bg='white', bd='9', fg='black', anchor='w',
                                        text='K-快速', variable=var5, onvalue=1, offvalue=0, command=bindcbtn)
        self.checkbutton5.place(relx=0.8, rely=0.17, width=70, height=30)

        
        '''

        self.passengers = lo.myTickets._get_passengers()

        self.frame2 = Frame(self.frameAll, width=150, height=300)
        self.frame2.place(relx=0.03, rely=0.03)
        for pas in self.passengers:
            #self.judge.append(0)
            num = num + 1
            self.varp.append(IntVar())
            self.checkbuttonp = Checkbutton(self.frame2,
                                            font=('微软雅黑', 9),
                                            text=pas,
                                            anchor='w',
                                            variable=self.varp[num],
                                            onvalue=1,
                                            offvalue=0,
                                            command=bindcbtnpas)
            self.checkbuttonp.grid()
            '''
        'trainNumber':'',
                'fromStation':'',
                'toStation':'',
                'departTime':'',
                'arriveTime':'',
                'period':'',
                'specialSeat':'',
                'oneClassSeat':'',
                'twoClassSeat':'',
                'advancedSoftSleeper':'',
                'softSleeper':'',
                'hardSleeper':'',
                'motionSleeper':'',
                'softSeat':'',
                'hardSeat':'',
                'noSeat':'',
                'bookable':False,
                'book_btn':None 
        '''
        self.frame3 = Frame(self.frameAll, bg='#D2E9FF', width=950, height=40)
        self.frame3.place(relx=0.2, rely=0.12)
        self.stationlabal = Label(
            self.frame3,
            font=('微软雅黑', 10, 'bold'),
            anchor='w',
            bg='#D2E9FF',
            fg='black',
            text=
            '   车次   出发站   到达站   出发时间   到达时间   历时   特等座   一等座   二等座   高级软卧   软卧   硬卧   动卧   软座   硬座   无座'
        )
        self.stationlabal.place(relx=0, rely=0, relwidth=1, relheight=1)
        self.mylb = Listbox(self.frameAll,
                            font=('微软雅黑', 15),
                            bd='0',
                            width=79,
                            height=20)
        #self.sl = Scrollbar(self.canvas)
        #self.sl.pack(side=RIGHT, fill=Y)
        #self.mylb['yscrollcommand'] = self.sl.set
        #self.sl['command']=self.mylb.yview
        self.mylb.place(relx=0.2, rely=0.21)
        for item in range(0, 20):
            self.mylb.insert(END, ' ')

        def page_last():
            if self.page > 1:

                self.page = self.page - 1
                if self.page < self.allpage:
                    self.btndown = Button(self.frameAll,
                                          font=(
                                              '微软雅黑',
                                              12,
                                          ),
                                          bg='#ffa042',
                                          fg='black',
                                          text='下 一 页',
                                          activeforeground='#00FFFF',
                                          command=page_next)
                    self.btndown.place(relx=0.52,
                                       rely=0.92,
                                       width=80,
                                       height=30)
                if self.page == 1:
                    self.btnup = Button(self.frameAll,
                                        font=(
                                            '微软雅黑',
                                            12,
                                        ),
                                        fg='black',
                                        text='上 一 页',
                                        activeforeground='#00FFFF',
                                        command=page_last)
                    self.btnup.place(relx=0.42, rely=0.92, width=80, height=30)
                self.labelnum = Label(self.frameAll,
                                      font=('微软雅黑', 12, 'bold'),
                                      fg='black',
                                      text=self.page)
                self.labelnum.place(relx=0.475, rely=0.92, width=20, height=30)
                numtl = 0
                self.begin = (self.page - 1) * 20
                self.end = self.page * 20
                for item in self.tickets_list[self.begin:self.end]:
                    placey = numtl * 0.05
                    string = '  '
                    for k, v in item.items():
                        if k != 'bookable' and k != 'book_btn':
                            string = string + '{:^8}'.format(v)

                    self.stationtickets_list = Label(self.mylb,
                                                     font=('微软雅黑', 10),
                                                     bg='white',
                                                     bd='9',
                                                     width=90,
                                                     height=1,
                                                     fg='black',
                                                     anchor='w',
                                                     text=string)
                    self.stationtickets_list.place(relx=0, rely=placey)

                    if item['bookable'] == False:
                        if self.is_future == True:

                            self.btncheck = Button(self.mylb,
                                                   font=('微软雅黑', 11),
                                                   width=9,
                                                   height=1,
                                                   fg='black',
                                                   text='预  订',
                                                   activeforeground='#00FFFF',
                                                   command=check_book_f)
                            self.btncheck.place(relx=0.88, rely=placey)
                        else:
                            self.btncheck = Button(self.mylb,
                                                   font=('微软雅黑', 11),
                                                   width=9,
                                                   height=1,
                                                   fg='black',
                                                   text='预  订',
                                                   activeforeground='#00FFFF',
                                                   command=check_book_t)
                            self.btncheck.place(relx=0.88, rely=placey)
                    else:
                        self.btncheck = Button(self.mylb,
                                               font=('微软雅黑', 11),
                                               width=9,
                                               height=1,
                                               bg='#ffa042',
                                               fg='black',
                                               text='预  订',
                                               activeforeground='#00FFFF',
                                               command=check_book_t)
                        self.btncheck.place(relx=0.88, rely=placey)
                    #strnum = str(numtl)+'  '+string
                    numtl = numtl + 1
                    #print('here')

                    self.mylb.insert(END, self.stationtickets_list)
                    self.mylb.insert(END, self.btncheck)

        def page_next():
            if self.page < self.allpage:

                self.page = self.page + 1
                if self.page > 1:
                    self.btnup = Button(self.frameAll,
                                        font=(
                                            '微软雅黑',
                                            12,
                                        ),
                                        bg='#ffa042',
                                        fg='black',
                                        text='上 一 页',
                                        activeforeground='#00FFFF',
                                        command=page_last)
                    self.btnup.place(relx=0.42, rely=0.92, width=80, height=30)
                if self.page == self.allpage:
                    self.btnup = Button(self.frameAll,
                                        font=(
                                            '微软雅黑',
                                            12,
                                        ),
                                        fg='black',
                                        text='下 一 页',
                                        activeforeground='#00FFFF',
                                        command=page_next)
                    self.btnup.place(relx=0.52, rely=0.92, width=80, height=30)
                    for item in range(20 - self.tllen // 20):
                        placeybug = 0.95 - item * 0.05
                        self.stationtickets_list = Label(self.mylb,
                                                         font=('微软雅黑', 12),
                                                         bg='white',
                                                         bd='9',
                                                         width=100,
                                                         height=1,
                                                         fg='black',
                                                         anchor='w',
                                                         text=' ')
                        self.stationtickets_list.place(relx=0, rely=placeybug)
                self.labelnum = Label(self.frameAll,
                                      font=('微软雅黑', 12, 'bold'),
                                      fg='black',
                                      text=self.page)
                self.labelnum.place(relx=0.475, rely=0.92, width=20, height=30)
                numtl = 0
                self.begin = (self.page - 1) * 20
                self.end = self.page * 20
                for item in self.tickets_list[self.begin:self.end]:
                    placey = numtl * 0.05
                    string = '  '
                    for k, v in item.items():
                        if k != 'bookable' and k != 'book_btn':
                            string = string + '{:^8}'.format(v)

                    self.stationtickets_list = Label(self.mylb,
                                                     font=('微软雅黑', 10),
                                                     bg='white',
                                                     bd='9',
                                                     width=90,
                                                     height=1,
                                                     fg='black',
                                                     anchor='w',
                                                     text=string)
                    self.stationtickets_list.place(relx=0, rely=placey)

                    if item['bookable'] == False:
                        if self.is_future == True:

                            self.btncheck = Button(self.mylb,
                                                   font=('微软雅黑', 11),
                                                   width=9,
                                                   height=1,
                                                   fg='black',
                                                   text='预  订',
                                                   activeforeground='#00FFFF',
                                                   command=check_book_f)
                            self.btncheck.place(relx=0.88, rely=placey)
                        else:
                            self.btncheck = Button(self.mylb,
                                                   font=('微软雅黑', 11),
                                                   width=9,
                                                   height=1,
                                                   fg='black',
                                                   text='预  订',
                                                   activeforeground='#00FFFF',
                                                   command=check_book_t)
                            self.btncheck.place(relx=0.88, rely=placey)
                    else:
                        self.btncheck = Button(self.mylb,
                                               font=('微软雅黑', 11),
                                               width=9,
                                               height=1,
                                               bg='#ffa042',
                                               fg='black',
                                               text='预  订',
                                               activeforeground='#00FFFF',
                                               command=check_book_t)
                        self.btncheck.place(relx=0.88, rely=placey)

                    #strnum = str(numtl)+'  '+string
                    numtl = numtl + 1
                    #print('here')
                    #print(self.page)
                    self.mylb.insert(END, self.stationtickets_list)
                    self.mylb.insert(END, self.btncheck)
            else:
                print('wo zai zhe li')

        self.btnup = Button(self.frameAll,
                            font=(
                                '微软雅黑',
                                12,
                            ),
                            bg='#ffa042',
                            fg='black',
                            text='上 一 页',
                            activeforeground='#00FFFF',
                            command=page_last)
        self.btnup.place(relx=0.42, rely=0.92, width=80, height=30)
        self.btndown = Button(self.frameAll,
                              font=(
                                  '微软雅黑',
                                  12,
                              ),
                              bg='#ffa042',
                              fg='black',
                              text='下 一 页',
                              activeforeground='#00FFFF',
                              command=page_next)
        self.btndown.place(relx=0.52, rely=0.92, width=80, height=30)
        self.labelnum = Label(self.frameAll,
                              font=('微软雅黑', 12, 'bold'),
                              fg='black',
                              text='-')
        self.labelnum.place(relx=0.475, rely=0.92, width=20, height=30)
        self.labelnum2 = Label(self.frameAll,
                               font=('微软雅黑', 12, 'bold'),
                               fg='black',
                               text='/')
        self.labelnum2.place(relx=0.493, rely=0.92, width=10, height=30)
        self.labelnum3 = Label(self.frameAll,
                               font=('微软雅黑', 12, 'bold'),
                               fg='black',
                               text='-')
        self.labelnum3.place(relx=0.50, rely=0.92, width=20, height=30)
        """
コード例 #52
0
ファイル: rdparser_app.py プロジェクト: jamesmorcombe/nltk
class RecursiveDescentApp(object):
    """
    A graphical tool for exploring the recursive descent parser.  The tool
    displays the parser's tree and the remaining text, and allows the
    user to control the parser's operation.  In particular, the user
    can expand subtrees on the frontier, match tokens on the frontier
    against the text, and backtrack.  A "step" button simply steps
    through the parsing process, performing the operations that
    ``RecursiveDescentParser`` would use.
    """
    def __init__(self, grammar, sent, trace=0):
        self._sent = sent
        self._parser = SteppingRecursiveDescentParser(grammar, trace)

        # Set up the main window.
        self._top = Tk()
        self._top.title('Recursive Descent Parser Application')

        # Set up key bindings.
        self._init_bindings()

        # Initialize the fonts.
        self._init_fonts(self._top)

        # Animations.  animating_lock is a lock to prevent the demo
        # from performing new operations while it's animating.
        self._animation_frames = IntVar(self._top)
        self._animation_frames.set(5)
        self._animating_lock = 0
        self._autostep = 0

        # The user can hide the grammar.
        self._show_grammar = IntVar(self._top)
        self._show_grammar.set(1)

        # Create the basic frames.
        self._init_menubar(self._top)
        self._init_buttons(self._top)
        self._init_feedback(self._top)
        self._init_grammar(self._top)
        self._init_canvas(self._top)

        # Initialize the parser.
        self._parser.initialize(self._sent)

        # Resize callback
        self._canvas.bind('<Configure>', self._configure)

    #########################################
    ##  Initialization Helpers
    #########################################

    def _init_fonts(self, root):
        # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
        self._sysfont = tkinter.font.Font(font=Button()["font"])
        root.option_add("*Font", self._sysfont)

        # TWhat's our font size (default=same as sysfont)
        self._size = IntVar(root)
        self._size.set(self._sysfont.cget('size'))

        self._boldfont = tkinter.font.Font(family='helvetica',
                                           weight='bold',
                                           size=self._size.get())
        self._font = tkinter.font.Font(family='helvetica',
                                       size=self._size.get())
        if self._size.get() < 0: big = self._size.get() - 2
        else: big = self._size.get() + 2
        self._bigfont = tkinter.font.Font(family='helvetica',
                                          weight='bold',
                                          size=big)

    def _init_grammar(self, parent):
        # Grammar view.
        self._prodframe = listframe = Frame(parent)
        self._prodframe.pack(fill='both', side='left', padx=2)
        self._prodlist_label = Label(self._prodframe,
                                     font=self._boldfont,
                                     text='Available Expansions')
        self._prodlist_label.pack()
        self._prodlist = Listbox(self._prodframe,
                                 selectmode='single',
                                 relief='groove',
                                 background='white',
                                 foreground='#909090',
                                 font=self._font,
                                 selectforeground='#004040',
                                 selectbackground='#c0f0c0')

        self._prodlist.pack(side='right', fill='both', expand=1)

        self._productions = list(self._parser.grammar().productions())
        for production in self._productions:
            self._prodlist.insert('end', ('  %s' % production))
        self._prodlist.config(height=min(len(self._productions), 25))

        # Add a scrollbar if there are more than 25 productions.
        if len(self._productions) > 25:
            listscroll = Scrollbar(self._prodframe, orient='vertical')
            self._prodlist.config(yscrollcommand=listscroll.set)
            listscroll.config(command=self._prodlist.yview)
            listscroll.pack(side='left', fill='y')

        # If they select a production, apply it.
        self._prodlist.bind('<<ListboxSelect>>', self._prodlist_select)

    def _init_bindings(self):
        # Key bindings are a good thing.
        self._top.bind('<Control-q>', self.destroy)
        self._top.bind('<Control-x>', self.destroy)
        self._top.bind('<Escape>', self.destroy)
        self._top.bind('e', self.expand)
        #self._top.bind('<Alt-e>', self.expand)
        #self._top.bind('<Control-e>', self.expand)
        self._top.bind('m', self.match)
        self._top.bind('<Alt-m>', self.match)
        self._top.bind('<Control-m>', self.match)
        self._top.bind('b', self.backtrack)
        self._top.bind('<Alt-b>', self.backtrack)
        self._top.bind('<Control-b>', self.backtrack)
        self._top.bind('<Control-z>', self.backtrack)
        self._top.bind('<BackSpace>', self.backtrack)
        self._top.bind('a', self.autostep)
        #self._top.bind('<Control-a>', self.autostep)
        self._top.bind('<Control-space>', self.autostep)
        self._top.bind('<Control-c>', self.cancel_autostep)
        self._top.bind('<space>', self.step)
        self._top.bind('<Delete>', self.reset)
        self._top.bind('<Control-p>', self.postscript)
        #self._top.bind('<h>', self.help)
        #self._top.bind('<Alt-h>', self.help)
        self._top.bind('<Control-h>', self.help)
        self._top.bind('<F1>', self.help)
        #self._top.bind('<g>', self.toggle_grammar)
        #self._top.bind('<Alt-g>', self.toggle_grammar)
        #self._top.bind('<Control-g>', self.toggle_grammar)
        self._top.bind('<Control-g>', self.edit_grammar)
        self._top.bind('<Control-t>', self.edit_sentence)

    def _init_buttons(self, parent):
        # Set up the frames.
        self._buttonframe = buttonframe = Frame(parent)
        buttonframe.pack(fill='none', side='bottom', padx=3, pady=2)
        Button(
            buttonframe,
            text='Step',
            background='#90c0d0',
            foreground='black',
            command=self.step,
        ).pack(side='left')
        Button(
            buttonframe,
            text='Autostep',
            background='#90c0d0',
            foreground='black',
            command=self.autostep,
        ).pack(side='left')
        Button(buttonframe,
               text='Expand',
               underline=0,
               background='#90f090',
               foreground='black',
               command=self.expand).pack(side='left')
        Button(buttonframe,
               text='Match',
               underline=0,
               background='#90f090',
               foreground='black',
               command=self.match).pack(side='left')
        Button(buttonframe,
               text='Backtrack',
               underline=0,
               background='#f0a0a0',
               foreground='black',
               command=self.backtrack).pack(side='left')
        # Replace autostep...
#         self._autostep_button = Button(buttonframe, text='Autostep',
#                                        underline=0, command=self.autostep)
#         self._autostep_button.pack(side='left')

    def _configure(self, event):
        self._autostep = 0
        (x1, y1, x2, y2) = self._cframe.scrollregion()
        y2 = event.height - 6
        self._canvas['scrollregion'] = '%d %d %d %d' % (x1, y1, x2, y2)
        self._redraw()

    def _init_feedback(self, parent):
        self._feedbackframe = feedbackframe = Frame(parent)
        feedbackframe.pack(fill='x', side='bottom', padx=3, pady=3)
        self._lastoper_label = Label(feedbackframe,
                                     text='Last Operation:',
                                     font=self._font)
        self._lastoper_label.pack(side='left')
        lastoperframe = Frame(feedbackframe, relief='sunken', border=1)
        lastoperframe.pack(fill='x', side='right', expand=1, padx=5)
        self._lastoper1 = Label(lastoperframe,
                                foreground='#007070',
                                background='#f0f0f0',
                                font=self._font)
        self._lastoper2 = Label(lastoperframe,
                                anchor='w',
                                width=30,
                                foreground='#004040',
                                background='#f0f0f0',
                                font=self._font)
        self._lastoper1.pack(side='left')
        self._lastoper2.pack(side='left', fill='x', expand=1)

    def _init_canvas(self, parent):
        self._cframe = CanvasFrame(
            parent,
            background='white',
            #width=525, height=250,
            closeenough=10,
            border=2,
            relief='sunken')
        self._cframe.pack(expand=1, fill='both', side='top', pady=2)
        canvas = self._canvas = self._cframe.canvas()

        # Initially, there's no tree or text
        self._tree = None
        self._textwidgets = []
        self._textline = None

    def _init_menubar(self, parent):
        menubar = Menu(parent)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label='Reset Parser',
                             underline=0,
                             command=self.reset,
                             accelerator='Del')
        filemenu.add_command(label='Print to Postscript',
                             underline=0,
                             command=self.postscript,
                             accelerator='Ctrl-p')
        filemenu.add_command(label='Exit',
                             underline=1,
                             command=self.destroy,
                             accelerator='Ctrl-x')
        menubar.add_cascade(label='File', underline=0, menu=filemenu)

        editmenu = Menu(menubar, tearoff=0)
        editmenu.add_command(label='Edit Grammar',
                             underline=5,
                             command=self.edit_grammar,
                             accelerator='Ctrl-g')
        editmenu.add_command(label='Edit Text',
                             underline=5,
                             command=self.edit_sentence,
                             accelerator='Ctrl-t')
        menubar.add_cascade(label='Edit', underline=0, menu=editmenu)

        rulemenu = Menu(menubar, tearoff=0)
        rulemenu.add_command(label='Step',
                             underline=1,
                             command=self.step,
                             accelerator='Space')
        rulemenu.add_separator()
        rulemenu.add_command(label='Match',
                             underline=0,
                             command=self.match,
                             accelerator='Ctrl-m')
        rulemenu.add_command(label='Expand',
                             underline=0,
                             command=self.expand,
                             accelerator='Ctrl-e')
        rulemenu.add_separator()
        rulemenu.add_command(label='Backtrack',
                             underline=0,
                             command=self.backtrack,
                             accelerator='Ctrl-b')
        menubar.add_cascade(label='Apply', underline=0, menu=rulemenu)

        viewmenu = Menu(menubar, tearoff=0)
        viewmenu.add_checkbutton(label="Show Grammar",
                                 underline=0,
                                 variable=self._show_grammar,
                                 command=self._toggle_grammar)
        viewmenu.add_separator()
        viewmenu.add_radiobutton(label='Tiny',
                                 variable=self._size,
                                 underline=0,
                                 value=10,
                                 command=self.resize)
        viewmenu.add_radiobutton(label='Small',
                                 variable=self._size,
                                 underline=0,
                                 value=12,
                                 command=self.resize)
        viewmenu.add_radiobutton(label='Medium',
                                 variable=self._size,
                                 underline=0,
                                 value=14,
                                 command=self.resize)
        viewmenu.add_radiobutton(label='Large',
                                 variable=self._size,
                                 underline=0,
                                 value=18,
                                 command=self.resize)
        viewmenu.add_radiobutton(label='Huge',
                                 variable=self._size,
                                 underline=0,
                                 value=24,
                                 command=self.resize)
        menubar.add_cascade(label='View', underline=0, menu=viewmenu)

        animatemenu = Menu(menubar, tearoff=0)
        animatemenu.add_radiobutton(label="No Animation",
                                    underline=0,
                                    variable=self._animation_frames,
                                    value=0)
        animatemenu.add_radiobutton(label="Slow Animation",
                                    underline=0,
                                    variable=self._animation_frames,
                                    value=10,
                                    accelerator='-')
        animatemenu.add_radiobutton(label="Normal Animation",
                                    underline=0,
                                    variable=self._animation_frames,
                                    value=5,
                                    accelerator='=')
        animatemenu.add_radiobutton(label="Fast Animation",
                                    underline=0,
                                    variable=self._animation_frames,
                                    value=2,
                                    accelerator='+')
        menubar.add_cascade(label="Animate", underline=1, menu=animatemenu)

        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label='About', underline=0, command=self.about)
        helpmenu.add_command(label='Instructions',
                             underline=0,
                             command=self.help,
                             accelerator='F1')
        menubar.add_cascade(label='Help', underline=0, menu=helpmenu)

        parent.config(menu=menubar)

    #########################################
    ##  Helper
    #########################################

    def _get(self, widget, treeloc):
        for i in treeloc:
            widget = widget.subtrees()[i]
        if isinstance(widget, TreeSegmentWidget):
            widget = widget.label()
        return widget

    #########################################
    ##  Main draw procedure
    #########################################

    def _redraw(self):
        canvas = self._canvas

        # Delete the old tree, widgets, etc.
        if self._tree is not None:
            self._cframe.destroy_widget(self._tree)
        for twidget in self._textwidgets:
            self._cframe.destroy_widget(twidget)
        if self._textline is not None:
            self._canvas.delete(self._textline)

        # Draw the tree.
        helv = ('helvetica', -self._size.get())
        bold = ('helvetica', -self._size.get(), 'bold')
        attribs = {
            'tree_color': '#000000',
            'tree_width': 2,
            'node_font': bold,
            'leaf_font': helv,
        }
        tree = self._parser.tree()
        self._tree = tree_to_treesegment(canvas, tree, **attribs)
        self._cframe.add_widget(self._tree, 30, 5)

        # Draw the text.
        helv = ('helvetica', -self._size.get())
        bottom = y = self._cframe.scrollregion()[3]
        self._textwidgets = [
            TextWidget(canvas, word, font=self._font) for word in self._sent
        ]
        for twidget in self._textwidgets:
            self._cframe.add_widget(twidget, 0, 0)
            twidget.move(0, bottom - twidget.bbox()[3] - 5)
            y = min(y, twidget.bbox()[1])

        # Draw a line over the text, to separate it from the tree.
        self._textline = canvas.create_line(-5000,
                                            y - 5,
                                            5000,
                                            y - 5,
                                            dash='.')

        # Highlight appropriate nodes.
        self._highlight_nodes()
        self._highlight_prodlist()

        # Make sure the text lines up.
        self._position_text()

    def _redraw_quick(self):
        # This should be more-or-less sufficient after an animation.
        self._highlight_nodes()
        self._highlight_prodlist()
        self._position_text()

    def _highlight_nodes(self):
        # Highlight the list of nodes to be checked.
        bold = ('helvetica', -self._size.get(), 'bold')
        for treeloc in self._parser.frontier()[:1]:
            self._get(self._tree, treeloc)['color'] = '#20a050'
            self._get(self._tree, treeloc)['font'] = bold
        for treeloc in self._parser.frontier()[1:]:
            self._get(self._tree, treeloc)['color'] = '#008080'

    def _highlight_prodlist(self):
        # Highlight the productions that can be expanded.
        # Boy, too bad tkinter doesn't implement Listbox.itemconfig;
        # that would be pretty useful here.
        self._prodlist.delete(0, 'end')
        expandable = self._parser.expandable_productions()
        untried = self._parser.untried_expandable_productions()
        productions = self._productions
        for index in range(len(productions)):
            if productions[index] in expandable:
                if productions[index] in untried:
                    self._prodlist.insert(index, ' %s' % productions[index])
                else:
                    self._prodlist.insert(index,
                                          ' %s (TRIED)' % productions[index])
                self._prodlist.selection_set(index)
            else:
                self._prodlist.insert(index, ' %s' % productions[index])

    def _position_text(self):
        # Line up the text widgets that are matched against the tree
        numwords = len(self._sent)
        num_matched = numwords - len(self._parser.remaining_text())
        leaves = self._tree_leaves()[:num_matched]
        xmax = self._tree.bbox()[0]
        for i in range(0, len(leaves)):
            widget = self._textwidgets[i]
            leaf = leaves[i]
            widget['color'] = '#006040'
            leaf['color'] = '#006040'
            widget.move(leaf.bbox()[0] - widget.bbox()[0], 0)
            xmax = widget.bbox()[2] + 10

        # Line up the text widgets that are not matched against the tree.
        for i in range(len(leaves), numwords):
            widget = self._textwidgets[i]
            widget['color'] = '#a0a0a0'
            widget.move(xmax - widget.bbox()[0], 0)
            xmax = widget.bbox()[2] + 10

        # If we have a complete parse, make everything green :)
        if self._parser.currently_complete():
            for twidget in self._textwidgets:
                twidget['color'] = '#00a000'

        # Move the matched leaves down to the text.
        for i in range(0, len(leaves)):
            widget = self._textwidgets[i]
            leaf = leaves[i]
            dy = widget.bbox()[1] - leaf.bbox()[3] - 10.0
            dy = max(dy, leaf.parent().label().bbox()[3] - leaf.bbox()[3] + 10)
            leaf.move(0, dy)

    def _tree_leaves(self, tree=None):
        if tree is None: tree = self._tree
        if isinstance(tree, TreeSegmentWidget):
            leaves = []
            for child in tree.subtrees():
                leaves += self._tree_leaves(child)
            return leaves
        else:
            return [tree]

    #########################################
    ##  Button Callbacks
    #########################################

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

    def reset(self, *e):
        self._autostep = 0
        self._parser.initialize(self._sent)
        self._lastoper1['text'] = 'Reset Application'
        self._lastoper2['text'] = ''
        self._redraw()

    def autostep(self, *e):
        if self._animation_frames.get() == 0:
            self._animation_frames.set(2)
        if self._autostep:
            self._autostep = 0
        else:
            self._autostep = 1
            self._step()

    def cancel_autostep(self, *e):
        #self._autostep_button['text'] = 'Autostep'
        self._autostep = 0

    # Make sure to stop auto-stepping if we get any user input.
    def step(self, *e):
        self._autostep = 0
        self._step()

    def match(self, *e):
        self._autostep = 0
        self._match()

    def expand(self, *e):
        self._autostep = 0
        self._expand()

    def backtrack(self, *e):
        self._autostep = 0
        self._backtrack()

    def _step(self):
        if self._animating_lock: return

        # Try expanding, matching, and backtracking (in that order)
        if self._expand(): pass
        elif self._parser.untried_match() and self._match(): pass
        elif self._backtrack(): pass
        else:
            self._lastoper1['text'] = 'Finished'
            self._lastoper2['text'] = ''
            self._autostep = 0

        # Check if we just completed a parse.
        if self._parser.currently_complete():
            self._autostep = 0
            self._lastoper2['text'] += '    [COMPLETE PARSE]'

    def _expand(self, *e):
        if self._animating_lock: return
        old_frontier = self._parser.frontier()
        rv = self._parser.expand()
        if rv is not None:
            self._lastoper1['text'] = 'Expand:'
            self._lastoper2['text'] = rv
            self._prodlist.selection_clear(0, 'end')
            index = self._productions.index(rv)
            self._prodlist.selection_set(index)
            self._animate_expand(old_frontier[0])
            return True
        else:
            self._lastoper1['text'] = 'Expand:'
            self._lastoper2['text'] = '(all expansions tried)'
            return False

    def _match(self, *e):
        if self._animating_lock: return
        old_frontier = self._parser.frontier()
        rv = self._parser.match()
        if rv is not None:
            self._lastoper1['text'] = 'Match:'
            self._lastoper2['text'] = rv
            self._animate_match(old_frontier[0])
            return True
        else:
            self._lastoper1['text'] = 'Match:'
            self._lastoper2['text'] = '(failed)'
            return False

    def _backtrack(self, *e):
        if self._animating_lock: return
        if self._parser.backtrack():
            elt = self._parser.tree()
            for i in self._parser.frontier()[0]:
                elt = elt[i]
            self._lastoper1['text'] = 'Backtrack'
            self._lastoper2['text'] = ''
            if isinstance(elt, Tree):
                self._animate_backtrack(self._parser.frontier()[0])
            else:
                self._animate_match_backtrack(self._parser.frontier()[0])
            return True
        else:
            self._autostep = 0
            self._lastoper1['text'] = 'Finished'
            self._lastoper2['text'] = ''
            return False

    def about(self, *e):
        ABOUT = ("NLTK Recursive Descent Parser Application\n" +
                 "Written by Edward Loper")
        TITLE = 'About: Recursive Descent Parser Application'
        try:
            from tkinter.messagebox import Message
            Message(message=ABOUT, title=TITLE).show()
        except:
            ShowText(self._top, TITLE, ABOUT)

    def help(self, *e):
        self._autostep = 0
        # The default font's not very legible; try using 'fixed' instead.
        try:
            ShowText(self._top,
                     'Help: Recursive Descent Parser Application',
                     (__doc__ or '').strip(),
                     width=75,
                     font='fixed')
        except:
            ShowText(self._top,
                     'Help: Recursive Descent Parser Application',
                     (__doc__ or '').strip(),
                     width=75)

    def postscript(self, *e):
        self._autostep = 0
        self._cframe.print_to_file()

    def mainloop(self, *args, **kwargs):
        """
        Enter the Tkinter mainloop.  This function must be called if
        this demo is created from a non-interactive program (e.g.
        from a secript); otherwise, the demo will close as soon as
        the script completes.
        """
        if in_idle(): return
        self._top.mainloop(*args, **kwargs)

    def resize(self, size=None):
        if size is not None: self._size.set(size)
        size = self._size.get()
        self._font.configure(size=-(abs(size)))
        self._boldfont.configure(size=-(abs(size)))
        self._sysfont.configure(size=-(abs(size)))
        self._bigfont.configure(size=-(abs(size + 2)))
        self._redraw()

    #########################################
    ##  Expand Production Selection
    #########################################

    def _toggle_grammar(self, *e):
        if self._show_grammar.get():
            self._prodframe.pack(fill='both',
                                 side='left',
                                 padx=2,
                                 after=self._feedbackframe)
            self._lastoper1['text'] = 'Show Grammar'
        else:
            self._prodframe.pack_forget()
            self._lastoper1['text'] = 'Hide Grammar'
        self._lastoper2['text'] = ''


#     def toggle_grammar(self, *e):
#         self._show_grammar = not self._show_grammar
#         if self._show_grammar:
#             self._prodframe.pack(fill='both', expand='y', side='left',
#                                  after=self._feedbackframe)
#             self._lastoper1['text'] = 'Show Grammar'
#         else:
#             self._prodframe.pack_forget()
#             self._lastoper1['text'] = 'Hide Grammar'
#         self._lastoper2['text'] = ''

    def _prodlist_select(self, event):
        selection = self._prodlist.curselection()
        if len(selection) != 1: return
        index = int(selection[0])
        old_frontier = self._parser.frontier()
        production = self._parser.expand(self._productions[index])

        if production:
            self._lastoper1['text'] = 'Expand:'
            self._lastoper2['text'] = production
            self._prodlist.selection_clear(0, 'end')
            self._prodlist.selection_set(index)
            self._animate_expand(old_frontier[0])
        else:
            # Reset the production selections.
            self._prodlist.selection_clear(0, 'end')
            for prod in self._parser.expandable_productions():
                index = self._productions.index(prod)
                self._prodlist.selection_set(index)

    #########################################
    ##  Animation
    #########################################

    def _animate_expand(self, treeloc):
        oldwidget = self._get(self._tree, treeloc)
        oldtree = oldwidget.parent()
        top = not isinstance(oldtree.parent(), TreeSegmentWidget)

        tree = self._parser.tree()
        for i in treeloc:
            tree = tree[i]

        widget = tree_to_treesegment(self._canvas,
                                     tree,
                                     node_font=self._boldfont,
                                     leaf_color='white',
                                     tree_width=2,
                                     tree_color='white',
                                     node_color='white',
                                     leaf_font=self._font)
        widget.label()['color'] = '#20a050'

        (oldx, oldy) = oldtree.label().bbox()[:2]
        (newx, newy) = widget.label().bbox()[:2]
        widget.move(oldx - newx, oldy - newy)

        if top:
            self._cframe.add_widget(widget, 0, 5)
            widget.move(30 - widget.label().bbox()[0], 0)
            self._tree = widget
        else:
            oldtree.parent().replace_child(oldtree, widget)

        # Move the children over so they don't overlap.
        # Line the children up in a strange way.
        if widget.subtrees():
            dx = (oldx + widget.label().width() / 2 -
                  widget.subtrees()[0].bbox()[0] / 2 -
                  widget.subtrees()[0].bbox()[2] / 2)
            for subtree in widget.subtrees():
                subtree.move(dx, 0)

        self._makeroom(widget)

        if top:
            self._cframe.destroy_widget(oldtree)
        else:
            oldtree.destroy()

        colors = [
            'gray%d' % (10 * int(10 * x / self._animation_frames.get()))
            for x in range(self._animation_frames.get(), 0, -1)
        ]

        # Move the text string down, if necessary.
        dy = widget.bbox()[3] + 30 - self._canvas.coords(self._textline)[1]
        if dy > 0:
            for twidget in self._textwidgets:
                twidget.move(0, dy)
            self._canvas.move(self._textline, 0, dy)

        self._animate_expand_frame(widget, colors)

    def _makeroom(self, treeseg):
        """
        Make sure that no sibling tree bbox's overlap.
        """
        parent = treeseg.parent()
        if not isinstance(parent, TreeSegmentWidget): return

        index = parent.subtrees().index(treeseg)

        # Handle siblings to the right
        rsiblings = parent.subtrees()[index + 1:]
        if rsiblings:
            dx = treeseg.bbox()[2] - rsiblings[0].bbox()[0] + 10
            for sibling in rsiblings:
                sibling.move(dx, 0)

        # Handle siblings to the left
        if index > 0:
            lsibling = parent.subtrees()[index - 1]
            dx = max(0, lsibling.bbox()[2] - treeseg.bbox()[0] + 10)
            treeseg.move(dx, 0)

        # Keep working up the tree.
        self._makeroom(parent)

    def _animate_expand_frame(self, widget, colors):
        if len(colors) > 0:
            self._animating_lock = 1
            widget['color'] = colors[0]
            for subtree in widget.subtrees():
                if isinstance(subtree, TreeSegmentWidget):
                    subtree.label()['color'] = colors[0]
                else:
                    subtree['color'] = colors[0]
            self._top.after(50, self._animate_expand_frame, widget, colors[1:])
        else:
            widget['color'] = 'black'
            for subtree in widget.subtrees():
                if isinstance(subtree, TreeSegmentWidget):
                    subtree.label()['color'] = 'black'
                else:
                    subtree['color'] = 'black'
            self._redraw_quick()
            widget.label()['color'] = 'black'
            self._animating_lock = 0
            if self._autostep: self._step()

    def _animate_backtrack(self, treeloc):
        # Flash red first, if we're animating.
        if self._animation_frames.get() == 0: colors = []
        else: colors = ['#a00000', '#000000', '#a00000']
        colors += [
            'gray%d' % (10 * int(10 * x / (self._animation_frames.get())))
            for x in range(1,
                           self._animation_frames.get() + 1)
        ]

        widgets = [self._get(self._tree, treeloc).parent()]
        for subtree in widgets[0].subtrees():
            if isinstance(subtree, TreeSegmentWidget):
                widgets.append(subtree.label())
            else:
                widgets.append(subtree)

        self._animate_backtrack_frame(widgets, colors)

    def _animate_backtrack_frame(self, widgets, colors):
        if len(colors) > 0:
            self._animating_lock = 1
            for widget in widgets:
                widget['color'] = colors[0]
            self._top.after(50, self._animate_backtrack_frame, widgets,
                            colors[1:])
        else:
            for widget in widgets[0].subtrees():
                widgets[0].remove_child(widget)
                widget.destroy()
            self._redraw_quick()
            self._animating_lock = 0
            if self._autostep: self._step()

    def _animate_match_backtrack(self, treeloc):
        widget = self._get(self._tree, treeloc)
        node = widget.parent().label()
        dy = (1.0 * (node.bbox()[3] - widget.bbox()[1] + 14) /
              max(1, self._animation_frames.get()))
        self._animate_match_backtrack_frame(self._animation_frames.get(),
                                            widget, dy)

    def _animate_match(self, treeloc):
        widget = self._get(self._tree, treeloc)

        dy = ((self._textwidgets[0].bbox()[1] - widget.bbox()[3] - 10.0) /
              max(1, self._animation_frames.get()))
        self._animate_match_frame(self._animation_frames.get(), widget, dy)

    def _animate_match_frame(self, frame, widget, dy):
        if frame > 0:
            self._animating_lock = 1
            widget.move(0, dy)
            self._top.after(10, self._animate_match_frame, frame - 1, widget,
                            dy)
        else:
            widget['color'] = '#006040'
            self._redraw_quick()
            self._animating_lock = 0
            if self._autostep: self._step()

    def _animate_match_backtrack_frame(self, frame, widget, dy):
        if frame > 0:
            self._animating_lock = 1
            widget.move(0, dy)
            self._top.after(10, self._animate_match_backtrack_frame, frame - 1,
                            widget, dy)
        else:
            widget.parent().remove_child(widget)
            widget.destroy()
            self._animating_lock = 0
            if self._autostep: self._step()

    def edit_grammar(self, *e):
        CFGEditor(self._top, self._parser.grammar(), self.set_grammar)

    def set_grammar(self, grammar):
        self._parser.set_grammar(grammar)
        self._productions = list(grammar.productions())
        self._prodlist.delete(0, 'end')
        for production in self._productions:
            self._prodlist.insert('end', (' %s' % production))

    def edit_sentence(self, *e):
        sentence = " ".join(self._sent)
        title = 'Edit Text'
        instr = 'Enter a new sentence to parse.'
        EntryDialog(self._top, sentence, instr, self.set_sentence, title)

    def set_sentence(self, sentence):
        self._sent = sentence.split()  #[XX] use tagged?
        self.reset()
コード例 #53
0
ファイル: srparser_app.py プロジェクト: Asgardian8740/Django
class ShiftReduceApp(object):
    """
    A graphical tool for exploring the shift-reduce parser.  The tool
    displays the parser's stack and the remaining text, and allows the
    user to control the parser's operation.  In particular, the user
    can shift tokens onto the stack, and can perform reductions on the
    top elements of the stack.  A "step" button simply steps through
    the parsing process, performing the operations that
    ``nltk.parse.ShiftReduceParser`` would use.
    """

    def __init__(self, grammar, sent, trace=0):
        self._sent = sent
        self._parser = SteppingShiftReduceParser(grammar, trace)

        # Set up the main window.
        self._top = Tk()
        self._top.title("Shift Reduce Parser Application")

        # Animations.  animating_lock is a lock to prevent the demo
        # from performing new operations while it's animating.
        self._animating_lock = 0
        self._animate = IntVar(self._top)
        self._animate.set(10)  # = medium

        # The user can hide the grammar.
        self._show_grammar = IntVar(self._top)
        self._show_grammar.set(1)

        # Initialize fonts.
        self._init_fonts(self._top)

        # Set up key bindings.
        self._init_bindings()

        # Create the basic frames.
        self._init_menubar(self._top)
        self._init_buttons(self._top)
        self._init_feedback(self._top)
        self._init_grammar(self._top)
        self._init_canvas(self._top)

        # A popup menu for reducing.
        self._reduce_menu = Menu(self._canvas, tearoff=0)

        # Reset the demo, and set the feedback frame to empty.
        self.reset()
        self._lastoper1["text"] = ""

    #########################################
    ##  Initialization Helpers
    #########################################

    def _init_fonts(self, root):
        # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
        self._sysfont = Font(font=Button()["font"])
        root.option_add("*Font", self._sysfont)

        # TWhat's our font size (default=same as sysfont)
        self._size = IntVar(root)
        self._size.set(self._sysfont.cget("size"))

        self._boldfont = Font(family="helvetica", weight="bold", size=self._size.get())
        self._font = Font(family="helvetica", size=self._size.get())

    def _init_grammar(self, parent):
        # Grammar view.
        self._prodframe = listframe = Frame(parent)
        self._prodframe.pack(fill="both", side="left", padx=2)
        self._prodlist_label = Label(
            self._prodframe, font=self._boldfont, text="Available Reductions"
        )
        self._prodlist_label.pack()
        self._prodlist = Listbox(
            self._prodframe,
            selectmode="single",
            relief="groove",
            background="white",
            foreground="#909090",
            font=self._font,
            selectforeground="#004040",
            selectbackground="#c0f0c0",
        )

        self._prodlist.pack(side="right", fill="both", expand=1)

        self._productions = list(self._parser.grammar().productions())
        for production in self._productions:
            self._prodlist.insert("end", (" %s" % production))
        self._prodlist.config(height=min(len(self._productions), 25))

        # Add a scrollbar if there are more than 25 productions.
        if 1:  # len(self._productions) > 25:
            listscroll = Scrollbar(self._prodframe, orient="vertical")
            self._prodlist.config(yscrollcommand=listscroll.set)
            listscroll.config(command=self._prodlist.yview)
            listscroll.pack(side="left", fill="y")

        # If they select a production, apply it.
        self._prodlist.bind("<<ListboxSelect>>", self._prodlist_select)

        # When they hover over a production, highlight it.
        self._hover = -1
        self._prodlist.bind("<Motion>", self._highlight_hover)
        self._prodlist.bind("<Leave>", self._clear_hover)

    def _init_bindings(self):
        # Quit
        self._top.bind("<Control-q>", self.destroy)
        self._top.bind("<Control-x>", self.destroy)
        self._top.bind("<Alt-q>", self.destroy)
        self._top.bind("<Alt-x>", self.destroy)

        # Ops (step, shift, reduce, undo)
        self._top.bind("<space>", self.step)
        self._top.bind("<s>", self.shift)
        self._top.bind("<Alt-s>", self.shift)
        self._top.bind("<Control-s>", self.shift)
        self._top.bind("<r>", self.reduce)
        self._top.bind("<Alt-r>", self.reduce)
        self._top.bind("<Control-r>", self.reduce)
        self._top.bind("<Delete>", self.reset)
        self._top.bind("<u>", self.undo)
        self._top.bind("<Alt-u>", self.undo)
        self._top.bind("<Control-u>", self.undo)
        self._top.bind("<Control-z>", self.undo)
        self._top.bind("<BackSpace>", self.undo)

        # Misc
        self._top.bind("<Control-p>", self.postscript)
        self._top.bind("<Control-h>", self.help)
        self._top.bind("<F1>", self.help)
        self._top.bind("<Control-g>", self.edit_grammar)
        self._top.bind("<Control-t>", self.edit_sentence)

        # Animation speed control
        self._top.bind("-", lambda e, a=self._animate: a.set(20))
        self._top.bind("=", lambda e, a=self._animate: a.set(10))
        self._top.bind("+", lambda e, a=self._animate: a.set(4))

    def _init_buttons(self, parent):
        # Set up the frames.
        self._buttonframe = buttonframe = Frame(parent)
        buttonframe.pack(fill="none", side="bottom")
        Button(
            buttonframe,
            text="Step",
            background="#90c0d0",
            foreground="black",
            command=self.step,
        ).pack(side="left")
        Button(
            buttonframe,
            text="Shift",
            underline=0,
            background="#90f090",
            foreground="black",
            command=self.shift,
        ).pack(side="left")
        Button(
            buttonframe,
            text="Reduce",
            underline=0,
            background="#90f090",
            foreground="black",
            command=self.reduce,
        ).pack(side="left")
        Button(
            buttonframe,
            text="Undo",
            underline=0,
            background="#f0a0a0",
            foreground="black",
            command=self.undo,
        ).pack(side="left")

    def _init_menubar(self, parent):
        menubar = Menu(parent)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(
            label="Reset Parser", underline=0, command=self.reset, accelerator="Del"
        )
        filemenu.add_command(
            label="Print to Postscript",
            underline=0,
            command=self.postscript,
            accelerator="Ctrl-p",
        )
        filemenu.add_command(
            label="Exit", underline=1, command=self.destroy, accelerator="Ctrl-x"
        )
        menubar.add_cascade(label="File", underline=0, menu=filemenu)

        editmenu = Menu(menubar, tearoff=0)
        editmenu.add_command(
            label="Edit Grammar",
            underline=5,
            command=self.edit_grammar,
            accelerator="Ctrl-g",
        )
        editmenu.add_command(
            label="Edit Text",
            underline=5,
            command=self.edit_sentence,
            accelerator="Ctrl-t",
        )
        menubar.add_cascade(label="Edit", underline=0, menu=editmenu)

        rulemenu = Menu(menubar, tearoff=0)
        rulemenu.add_command(
            label="Step", underline=1, command=self.step, accelerator="Space"
        )
        rulemenu.add_separator()
        rulemenu.add_command(
            label="Shift", underline=0, command=self.shift, accelerator="Ctrl-s"
        )
        rulemenu.add_command(
            label="Reduce", underline=0, command=self.reduce, accelerator="Ctrl-r"
        )
        rulemenu.add_separator()
        rulemenu.add_command(
            label="Undo", underline=0, command=self.undo, accelerator="Ctrl-u"
        )
        menubar.add_cascade(label="Apply", underline=0, menu=rulemenu)

        viewmenu = Menu(menubar, tearoff=0)
        viewmenu.add_checkbutton(
            label="Show Grammar",
            underline=0,
            variable=self._show_grammar,
            command=self._toggle_grammar,
        )
        viewmenu.add_separator()
        viewmenu.add_radiobutton(
            label="Tiny",
            variable=self._size,
            underline=0,
            value=10,
            command=self.resize,
        )
        viewmenu.add_radiobutton(
            label="Small",
            variable=self._size,
            underline=0,
            value=12,
            command=self.resize,
        )
        viewmenu.add_radiobutton(
            label="Medium",
            variable=self._size,
            underline=0,
            value=14,
            command=self.resize,
        )
        viewmenu.add_radiobutton(
            label="Large",
            variable=self._size,
            underline=0,
            value=18,
            command=self.resize,
        )
        viewmenu.add_radiobutton(
            label="Huge",
            variable=self._size,
            underline=0,
            value=24,
            command=self.resize,
        )
        menubar.add_cascade(label="View", underline=0, menu=viewmenu)

        animatemenu = Menu(menubar, tearoff=0)
        animatemenu.add_radiobutton(
            label="No Animation", underline=0, variable=self._animate, value=0
        )
        animatemenu.add_radiobutton(
            label="Slow Animation",
            underline=0,
            variable=self._animate,
            value=20,
            accelerator="-",
        )
        animatemenu.add_radiobutton(
            label="Normal Animation",
            underline=0,
            variable=self._animate,
            value=10,
            accelerator="=",
        )
        animatemenu.add_radiobutton(
            label="Fast Animation",
            underline=0,
            variable=self._animate,
            value=4,
            accelerator="+",
        )
        menubar.add_cascade(label="Animate", underline=1, menu=animatemenu)

        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label="About", underline=0, command=self.about)
        helpmenu.add_command(
            label="Instructions", underline=0, command=self.help, accelerator="F1"
        )
        menubar.add_cascade(label="Help", underline=0, menu=helpmenu)

        parent.config(menu=menubar)

    def _init_feedback(self, parent):
        self._feedbackframe = feedbackframe = Frame(parent)
        feedbackframe.pack(fill="x", side="bottom", padx=3, pady=3)
        self._lastoper_label = Label(
            feedbackframe, text="Last Operation:", font=self._font
        )
        self._lastoper_label.pack(side="left")
        lastoperframe = Frame(feedbackframe, relief="sunken", border=1)
        lastoperframe.pack(fill="x", side="right", expand=1, padx=5)
        self._lastoper1 = Label(
            lastoperframe, foreground="#007070", background="#f0f0f0", font=self._font
        )
        self._lastoper2 = Label(
            lastoperframe,
            anchor="w",
            width=30,
            foreground="#004040",
            background="#f0f0f0",
            font=self._font,
        )
        self._lastoper1.pack(side="left")
        self._lastoper2.pack(side="left", fill="x", expand=1)

    def _init_canvas(self, parent):
        self._cframe = CanvasFrame(
            parent,
            background="white",
            width=525,
            closeenough=10,
            border=2,
            relief="sunken",
        )
        self._cframe.pack(expand=1, fill="both", side="top", pady=2)
        canvas = self._canvas = self._cframe.canvas()

        self._stackwidgets = []
        self._rtextwidgets = []
        self._titlebar = canvas.create_rectangle(
            0, 0, 0, 0, fill="#c0f0f0", outline="black"
        )
        self._exprline = canvas.create_line(0, 0, 0, 0, dash=".")
        self._stacktop = canvas.create_line(0, 0, 0, 0, fill="#408080")
        size = self._size.get() + 4
        self._stacklabel = TextWidget(
            canvas, "Stack", color="#004040", font=self._boldfont
        )
        self._rtextlabel = TextWidget(
            canvas, "Remaining Text", color="#004040", font=self._boldfont
        )
        self._cframe.add_widget(self._stacklabel)
        self._cframe.add_widget(self._rtextlabel)

    #########################################
    ##  Main draw procedure
    #########################################

    def _redraw(self):
        scrollregion = self._canvas["scrollregion"].split()
        (cx1, cy1, cx2, cy2) = [int(c) for c in scrollregion]

        # Delete the old stack & rtext widgets.
        for stackwidget in self._stackwidgets:
            self._cframe.destroy_widget(stackwidget)
        self._stackwidgets = []
        for rtextwidget in self._rtextwidgets:
            self._cframe.destroy_widget(rtextwidget)
        self._rtextwidgets = []

        # Position the titlebar & exprline
        (x1, y1, x2, y2) = self._stacklabel.bbox()
        y = y2 - y1 + 10
        self._canvas.coords(self._titlebar, -5000, 0, 5000, y - 4)
        self._canvas.coords(self._exprline, 0, y * 2 - 10, 5000, y * 2 - 10)

        # Position the titlebar labels..
        (x1, y1, x2, y2) = self._stacklabel.bbox()
        self._stacklabel.move(5 - x1, 3 - y1)
        (x1, y1, x2, y2) = self._rtextlabel.bbox()
        self._rtextlabel.move(cx2 - x2 - 5, 3 - y1)

        # Draw the stack.
        stackx = 5
        for tok in self._parser.stack():
            if isinstance(tok, Tree):
                attribs = {
                    "tree_color": "#4080a0",
                    "tree_width": 2,
                    "node_font": self._boldfont,
                    "node_color": "#006060",
                    "leaf_color": "#006060",
                    "leaf_font": self._font,
                }
                widget = tree_to_treesegment(self._canvas, tok, **attribs)
                widget.label()["color"] = "#000000"
            else:
                widget = TextWidget(self._canvas, tok, color="#000000", font=self._font)
            widget.bind_click(self._popup_reduce)
            self._stackwidgets.append(widget)
            self._cframe.add_widget(widget, stackx, y)
            stackx = widget.bbox()[2] + 10

        # Draw the remaining text.
        rtextwidth = 0
        for tok in self._parser.remaining_text():
            widget = TextWidget(self._canvas, tok, color="#000000", font=self._font)
            self._rtextwidgets.append(widget)
            self._cframe.add_widget(widget, rtextwidth, y)
            rtextwidth = widget.bbox()[2] + 4

        # Allow enough room to shift the next token (for animations)
        if len(self._rtextwidgets) > 0:
            stackx += self._rtextwidgets[0].width()

        # Move the remaining text to the correct location (keep it
        # right-justified, when possible); and move the remaining text
        # label, if necessary.
        stackx = max(stackx, self._stacklabel.width() + 25)
        rlabelwidth = self._rtextlabel.width() + 10
        if stackx >= cx2 - max(rtextwidth, rlabelwidth):
            cx2 = stackx + max(rtextwidth, rlabelwidth)
        for rtextwidget in self._rtextwidgets:
            rtextwidget.move(4 + cx2 - rtextwidth, 0)
        self._rtextlabel.move(cx2 - self._rtextlabel.bbox()[2] - 5, 0)

        midx = (stackx + cx2 - max(rtextwidth, rlabelwidth)) / 2
        self._canvas.coords(self._stacktop, midx, 0, midx, 5000)
        (x1, y1, x2, y2) = self._stacklabel.bbox()

        # Set up binding to allow them to shift a token by dragging it.
        if len(self._rtextwidgets) > 0:

            def drag_shift(widget, midx=midx, self=self):
                if widget.bbox()[0] < midx:
                    self.shift()
                else:
                    self._redraw()

            self._rtextwidgets[0].bind_drag(drag_shift)
            self._rtextwidgets[0].bind_click(self.shift)

        # Draw the stack top.
        self._highlight_productions()

    def _draw_stack_top(self, widget):
        # hack..
        midx = widget.bbox()[2] + 50
        self._canvas.coords(self._stacktop, midx, 0, midx, 5000)

    def _highlight_productions(self):
        # Highlight the productions that can be reduced.
        self._prodlist.selection_clear(0, "end")
        for prod in self._parser.reducible_productions():
            index = self._productions.index(prod)
            self._prodlist.selection_set(index)

    #########################################
    ##  Button Callbacks
    #########################################

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

    def reset(self, *e):
        self._parser.initialize(self._sent)
        self._lastoper1["text"] = "Reset App"
        self._lastoper2["text"] = ""
        self._redraw()

    def step(self, *e):
        if self.reduce():
            return True
        elif self.shift():
            return True
        else:
            if list(self._parser.parses()):
                self._lastoper1["text"] = "Finished:"
                self._lastoper2["text"] = "Success"
            else:
                self._lastoper1["text"] = "Finished:"
                self._lastoper2["text"] = "Failure"

    def shift(self, *e):
        if self._animating_lock:
            return
        if self._parser.shift():
            tok = self._parser.stack()[-1]
            self._lastoper1["text"] = "Shift:"
            self._lastoper2["text"] = "%r" % tok
            if self._animate.get():
                self._animate_shift()
            else:
                self._redraw()
            return True
        return False

    def reduce(self, *e):
        if self._animating_lock:
            return
        production = self._parser.reduce()
        if production:
            self._lastoper1["text"] = "Reduce:"
            self._lastoper2["text"] = "%s" % production
            if self._animate.get():
                self._animate_reduce()
            else:
                self._redraw()
        return production

    def undo(self, *e):
        if self._animating_lock:
            return
        if self._parser.undo():
            self._redraw()

    def postscript(self, *e):
        self._cframe.print_to_file()

    def mainloop(self, *args, **kwargs):
        """
        Enter the Tkinter mainloop.  This function must be called if
        this demo is created from a non-interactive program (e.g.
        from a secript); otherwise, the demo will close as soon as
        the script completes.
        """
        if in_idle():
            return
        self._top.mainloop(*args, **kwargs)

    #########################################
    ##  Menubar callbacks
    #########################################

    def resize(self, size=None):
        if size is not None:
            self._size.set(size)
        size = self._size.get()
        self._font.configure(size=-(abs(size)))
        self._boldfont.configure(size=-(abs(size)))
        self._sysfont.configure(size=-(abs(size)))

        # self._stacklabel['font'] = ('helvetica', -size-4, 'bold')
        # self._rtextlabel['font'] = ('helvetica', -size-4, 'bold')
        # self._lastoper_label['font'] = ('helvetica', -size)
        # self._lastoper1['font'] = ('helvetica', -size)
        # self._lastoper2['font'] = ('helvetica', -size)
        # self._prodlist['font'] = ('helvetica', -size)
        # self._prodlist_label['font'] = ('helvetica', -size-2, 'bold')
        self._redraw()

    def help(self, *e):
        # The default font's not very legible; try using 'fixed' instead.
        try:
            ShowText(
                self._top,
                "Help: Shift-Reduce Parser Application",
                (__doc__ or "").strip(),
                width=75,
                font="fixed",
            )
        except:
            ShowText(
                self._top,
                "Help: Shift-Reduce Parser Application",
                (__doc__ or "").strip(),
                width=75,
            )

    def about(self, *e):
        ABOUT = "NLTK Shift-Reduce Parser Application\n" + "Written by Edward Loper"
        TITLE = "About: Shift-Reduce Parser Application"
        try:
            from tkinter.messagebox import Message

            Message(message=ABOUT, title=TITLE).show()
        except:
            ShowText(self._top, TITLE, ABOUT)

    def edit_grammar(self, *e):
        CFGEditor(self._top, self._parser.grammar(), self.set_grammar)

    def set_grammar(self, grammar):
        self._parser.set_grammar(grammar)
        self._productions = list(grammar.productions())
        self._prodlist.delete(0, "end")
        for production in self._productions:
            self._prodlist.insert("end", (" %s" % production))

    def edit_sentence(self, *e):
        sentence = " ".join(self._sent)
        title = "Edit Text"
        instr = "Enter a new sentence to parse."
        EntryDialog(self._top, sentence, instr, self.set_sentence, title)

    def set_sentence(self, sent):
        self._sent = sent.split()  # [XX] use tagged?
        self.reset()

    #########################################
    ##  Reduce Production Selection
    #########################################

    def _toggle_grammar(self, *e):
        if self._show_grammar.get():
            self._prodframe.pack(
                fill="both", side="left", padx=2, after=self._feedbackframe
            )
            self._lastoper1["text"] = "Show Grammar"
        else:
            self._prodframe.pack_forget()
            self._lastoper1["text"] = "Hide Grammar"
        self._lastoper2["text"] = ""

    def _prodlist_select(self, event):
        selection = self._prodlist.curselection()
        if len(selection) != 1:
            return
        index = int(selection[0])
        production = self._parser.reduce(self._productions[index])
        if production:
            self._lastoper1["text"] = "Reduce:"
            self._lastoper2["text"] = "%s" % production
            if self._animate.get():
                self._animate_reduce()
            else:
                self._redraw()
        else:
            # Reset the production selections.
            self._prodlist.selection_clear(0, "end")
            for prod in self._parser.reducible_productions():
                index = self._productions.index(prod)
                self._prodlist.selection_set(index)

    def _popup_reduce(self, widget):
        # Remove old commands.
        productions = self._parser.reducible_productions()
        if len(productions) == 0:
            return

        self._reduce_menu.delete(0, "end")
        for production in productions:
            self._reduce_menu.add_command(label=str(production), command=self.reduce)
        self._reduce_menu.post(
            self._canvas.winfo_pointerx(), self._canvas.winfo_pointery()
        )

    #########################################
    ##  Animations
    #########################################

    def _animate_shift(self):
        # What widget are we shifting?
        widget = self._rtextwidgets[0]

        # Where are we shifting from & to?
        right = widget.bbox()[0]
        if len(self._stackwidgets) == 0:
            left = 5
        else:
            left = self._stackwidgets[-1].bbox()[2] + 10

        # Start animating.
        dt = self._animate.get()
        dx = (left - right) * 1.0 / dt
        self._animate_shift_frame(dt, widget, dx)

    def _animate_shift_frame(self, frame, widget, dx):
        if frame > 0:
            self._animating_lock = 1
            widget.move(dx, 0)
            self._top.after(10, self._animate_shift_frame, frame - 1, widget, dx)
        else:
            # but: stacktop??

            # Shift the widget to the stack.
            del self._rtextwidgets[0]
            self._stackwidgets.append(widget)
            self._animating_lock = 0

            # Display the available productions.
            self._draw_stack_top(widget)
            self._highlight_productions()

    def _animate_reduce(self):
        # What widgets are we shifting?
        numwidgets = len(self._parser.stack()[-1])  # number of children
        widgets = self._stackwidgets[-numwidgets:]

        # How far are we moving?
        if isinstance(widgets[0], TreeSegmentWidget):
            ydist = 15 + widgets[0].label().height()
        else:
            ydist = 15 + widgets[0].height()

        # Start animating.
        dt = self._animate.get()
        dy = ydist * 2.0 / dt
        self._animate_reduce_frame(dt / 2, widgets, dy)

    def _animate_reduce_frame(self, frame, widgets, dy):
        if frame > 0:
            self._animating_lock = 1
            for widget in widgets:
                widget.move(0, dy)
            self._top.after(10, self._animate_reduce_frame, frame - 1, widgets, dy)
        else:
            del self._stackwidgets[-len(widgets) :]
            for widget in widgets:
                self._cframe.remove_widget(widget)
            tok = self._parser.stack()[-1]
            if not isinstance(tok, Tree):
                raise ValueError()
            label = TextWidget(
                self._canvas, str(tok.label()), color="#006060", font=self._boldfont
            )
            widget = TreeSegmentWidget(self._canvas, label, widgets, width=2)
            (x1, y1, x2, y2) = self._stacklabel.bbox()
            y = y2 - y1 + 10
            if not self._stackwidgets:
                x = 5
            else:
                x = self._stackwidgets[-1].bbox()[2] + 10
            self._cframe.add_widget(widget, x, y)
            self._stackwidgets.append(widget)

            # Display the available productions.
            self._draw_stack_top(widget)
            self._highlight_productions()

            #             # Delete the old widgets..
            #             del self._stackwidgets[-len(widgets):]
            #             for widget in widgets:
            #                 self._cframe.destroy_widget(widget)
            #
            #             # Make a new one.
            #             tok = self._parser.stack()[-1]
            #             if isinstance(tok, Tree):
            #                 attribs = {'tree_color': '#4080a0', 'tree_width': 2,
            #                            'node_font': bold, 'node_color': '#006060',
            #                            'leaf_color': '#006060', 'leaf_font':self._font}
            #                 widget = tree_to_treesegment(self._canvas, tok.type(),
            #                                              **attribs)
            #                 widget.node()['color'] = '#000000'
            #             else:
            #                 widget = TextWidget(self._canvas, tok.type(),
            #                                     color='#000000', font=self._font)
            #             widget.bind_click(self._popup_reduce)
            #             (x1, y1, x2, y2) = self._stacklabel.bbox()
            #             y = y2-y1+10
            #             if not self._stackwidgets: x = 5
            #             else: x = self._stackwidgets[-1].bbox()[2] + 10
            #             self._cframe.add_widget(widget, x, y)
            #             self._stackwidgets.append(widget)

            # self._redraw()
            self._animating_lock = 0

    #########################################
    ##  Hovering.
    #########################################

    def _highlight_hover(self, event):
        # What production are we hovering over?
        index = self._prodlist.nearest(event.y)
        if self._hover == index:
            return

        # Clear any previous hover highlighting.
        self._clear_hover()

        # If the production corresponds to an available reduction,
        # highlight the stack.
        selection = [int(s) for s in self._prodlist.curselection()]
        if index in selection:
            rhslen = len(self._productions[index].rhs())
            for stackwidget in self._stackwidgets[-rhslen:]:
                if isinstance(stackwidget, TreeSegmentWidget):
                    stackwidget.label()["color"] = "#00a000"
                else:
                    stackwidget["color"] = "#00a000"

        # Remember what production we're hovering over.
        self._hover = index

    def _clear_hover(self, *event):
        # Clear any previous hover highlighting.
        if self._hover == -1:
            return
        self._hover = -1
        for stackwidget in self._stackwidgets:
            if isinstance(stackwidget, TreeSegmentWidget):
                stackwidget.label()["color"] = "black"
            else:
                stackwidget["color"] = "black"
コード例 #54
0
ファイル: teamWindow.py プロジェクト: Go1den/StreamOpener
class TeamWindow:
    def __init__(self, parent, teams):
        self.window = Toplevel(parent.window)
        self.window.withdraw()
        self.parent = parent
        self.teams = deepcopy(teams)
        self.teamFrame = Frame(self.window)
        self.streamFrame = Frame(self.window)
        self.buttonFrame = Frame(self.window)

        self.isRename = False
        self.tempName = None
        self.currentTeam = None
        self.teamsExist = False
        self.pageLoaded = False

        self.comboboxTeam = None
        self.freeAgentListbox = None
        self.teamMemberListbox = None

        self.selectedFreeAgents = None
        self.selectedTeamMembers = None

        self.buttonLeftArrow = None
        self.buttonUpArrow = None
        self.buttonDownArrow = None
        self.buttonRightArrow = None
        self.buttonRename = None

        WindowHelper.initializeWindow(self.window, self.parent, 380, 282, 30, 50, LabelConstants.TEAM_WINDOW)
        self.gridFrames()
        self.addDropdown()
        self.addFreeAgentListbox()
        self.addListboxButtons()
        self.addTeamMemberListbox()
        self.addButtons()
        if self.teamsExist:
            self.switchActiveTeam()
        self.pageLoaded = True
        WindowHelper.finalizeWindow(self.window, self.parent)

    def gridFrames(self):
        self.buttonFrame.grid_columnconfigure(0, weight=1)
        self.buttonFrame.grid_columnconfigure(1, weight=1)
        self.buttonFrame.grid_columnconfigure(2, weight=1)
        self.buttonFrame.grid_columnconfigure(3, weight=1)
        self.teamFrame.grid(row=0, sticky=NSEW, padx=4, pady=4)
        self.streamFrame.grid(row=1, sticky=NSEW, padx=4, pady=4)
        self.buttonFrame.grid(row=2, sticky=NSEW, padx=4, pady=4)

    def addDropdown(self):
        teams = self.getListOfTeams()
        labelTeam = Label(self.teamFrame, text=LabelConstants.TEAMS_DROPDOWN)
        labelTeam.grid(row=0, column=0, sticky=NSEW, padx=4, pady=4)
        self.comboboxTeam = Combobox(self.teamFrame, values=teams, state="readonly")
        self.comboboxTeam.bind("<<ComboboxSelected>>", self.switchActiveTeam)
        if teams:
            self.teamsExist = True
            self.comboboxTeam.current(0)
            self.currentTeam = self.comboboxTeam.get()
        self.comboboxTeam.grid(row=0, column=1, padx=4, pady=4)
        buttonNewTeam = Button(self.teamFrame, text=LabelConstants.CREATE_NEW_TEAM, width=16, command=self.createNewTeam)
        buttonNewTeam.grid(row=0, column=2, sticky=NSEW, padx=(40, 4), pady=4)

    def addFreeAgentListbox(self):
        frameFreeAgentListBox = Frame(self.streamFrame)
        frameFreeAgentListBox.grid(row=0, column=0, sticky=NSEW, padx=4, pady=(0, 4))
        labelFreeAgentListBox = Label(frameFreeAgentListBox, text=LabelConstants.FREE_AGENTS)
        labelFreeAgentListBox.grid(row=0, column=0, padx=4, sticky=W)
        scrollbar = Scrollbar(frameFreeAgentListBox)
        scrollbar.grid(row=1, column=1, sticky="NWS")
        self.freeAgentListbox = Listbox(frameFreeAgentListBox, selectmode=MULTIPLE, yscrollcommand=scrollbar.set, activestyle=NONE)
        scrollbar.config(command=self.freeAgentListbox.yview)
        self.freeAgentListbox.bind('<<ListboxSelect>>', self.onSelectFreeAgentListbox)
        self.freeAgentListbox.grid(row=1, column=0, sticky=NSEW, padx=(4, 0))

    def addListboxButtons(self):
        frameListBoxButtons = Frame(self.streamFrame)
        frameListBoxButtons.grid(row=0, column=1, sticky=NSEW, pady=(0, 4))
        self.buttonLeftArrow = Button(frameListBoxButtons, text=LabelConstants.LEFT, width=7, command=lambda: self.moveLeft(), state=DISABLED)
        self.buttonLeftArrow.grid(row=0, sticky=NSEW, padx=4, pady=(38, 4))
        self.buttonUpArrow = Button(frameListBoxButtons, text=LabelConstants.UP, width=7, command=lambda: self.moveUp(), state=DISABLED)
        self.buttonUpArrow.grid(row=1, sticky=NSEW, padx=4, pady=4)
        self.buttonDownArrow = Button(frameListBoxButtons, text=LabelConstants.DOWN, width=7, command=lambda: self.moveDown(), state=DISABLED)
        self.buttonDownArrow.grid(row=2, sticky=NSEW, padx=4, pady=4)
        self.buttonRightArrow = Button(frameListBoxButtons, text=LabelConstants.RIGHT, width=7, command=lambda: self.moveRight(), state=DISABLED)
        self.buttonRightArrow.grid(row=3, sticky=NSEW, padx=4, pady=4)

    def addTeamMemberListbox(self):
        frameTeamMemberListbox = Frame(self.streamFrame)
        frameTeamMemberListbox.grid(row=0, column=2, sticky=NSEW, pady=(0, 4))
        labelLiveListBox = Label(frameTeamMemberListbox, text=LabelConstants.TEAM_MEMBERS)
        labelLiveListBox.grid(row=0, column=0, padx=4, sticky=W)
        scrollbar = Scrollbar(frameTeamMemberListbox)
        scrollbar.grid(row=1, column=1, sticky="NWS")
        self.teamMemberListbox = Listbox(frameTeamMemberListbox, selectmode=SINGLE, yscrollcommand=scrollbar.set, activestyle=NONE)
        scrollbar.config(command=self.teamMemberListbox.yview)
        self.teamMemberListbox.bind('<<ListboxSelect>>', self.onSelectTeamMemberListbox)
        self.teamMemberListbox.grid(row=1, column=0, sticky=NSEW, padx=(4, 0))

    def addButtons(self):
        # TODO: These don't need to be defined as self.
        self.buttonRename = Button(self.buttonFrame, text=LabelConstants.RENAME, width=8, command=lambda: self.rename())
        self.buttonRename.grid(row=0, column=0, sticky=NSEW, padx=(8, 4), pady=4)
        buttonDelete = Button(self.buttonFrame, text=LabelConstants.DELETE, width=8, command=lambda: self.delete())
        buttonDelete.grid(row=0, column=1, sticky=NSEW, padx=4, pady=4)
        buttonSave = Button(self.buttonFrame, text=LabelConstants.OK, width=8, command=lambda: self.ok())
        buttonSave.grid(row=0, column=2, sticky=NSEW, padx=4, pady=4)
        buttonCancel = Button(self.buttonFrame, text=LabelConstants.CANCEL, width=8, command=lambda: self.window.destroy())
        buttonCancel.grid(row=0, column=3, sticky=NSEW, padx=4, pady=4)

    def moveLeft(self):
        if self.selectedTeamMembers:
            for stream in self.selectedTeamMembers:
                self.freeAgentListbox.insert(END, self.teamMemberListbox.get(stream))
            for stream in reversed(self.selectedTeamMembers):
                self.teamMemberListbox.delete(stream)
            self.teamMemberListbox.selection_clear(0, END)
            self.selectedTeamMembers = None
            self.buttonLeftArrow.configure(state=DISABLED)

    def moveUp(self):
        index = self.teamMemberListbox.curselection()
        if self.selectedTeamMembers and len(self.selectedTeamMembers) == 1 and index is not None and index[0] != 0:
            stream = self.teamMemberListbox.get(index[0])
            self.teamMemberListbox.delete(index[0])
            self.teamMemberListbox.insert(index[0] - 1, stream)
            self.teamMemberListbox.selection_set(index[0] - 1)

    def moveDown(self):
        index = self.teamMemberListbox.curselection()
        if self.selectedTeamMembers and len(self.selectedTeamMembers) == 1 and index is not None and index[0] != self.teamMemberListbox.size() - 1:
            stream = self.teamMemberListbox.get(index[0])
            self.teamMemberListbox.delete(index[0])
            self.teamMemberListbox.insert(index[0] + 1, stream)
            self.teamMemberListbox.selection_set(index[0] + 1)

    def moveRight(self):
        if self.selectedFreeAgents:
            for stream in self.selectedFreeAgents:
                self.teamMemberListbox.insert(END, self.freeAgentListbox.get(stream))
            for stream in reversed(self.selectedFreeAgents):
                self.freeAgentListbox.delete(stream)
            self.freeAgentListbox.selection_clear(0, END)
            self.selectedFreeAgents = None
            self.buttonRightArrow.configure(state=DISABLED)

    def switchActiveTeam(self, event=None):
        if self.pageLoaded and self.currentTeam is not None and len(self.currentTeam) > 0:
            self.storeCurrentTeamChanges(self.currentTeam)
        teamMembers = self.teams[self.comboboxTeam.get()]
        freeAgents = sorted([x for x in self.teams[LabelConstants.ALL_TEAM] if x not in teamMembers], key=str.casefold)
        self.clearListboxes()
        for streamer in freeAgents:
            self.freeAgentListbox.insert(END, streamer)
        for streamer in teamMembers:
            self.teamMemberListbox.insert(END, streamer)
        self.currentTeam = self.comboboxTeam.get()

    def clearListboxes(self):
        self.freeAgentListbox.selection_clear(0, END)
        self.teamMemberListbox.selection_clear(0, END)
        self.freeAgentListbox.delete(0, END)
        self.teamMemberListbox.delete(0, END)

    def onSelectFreeAgentListbox(self, event):
        w = event.widget
        self.selectedFreeAgents = w.curselection()
        self.buttonRightArrow.configure(state=NORMAL)
        self.buttonLeftArrow.configure(state=DISABLED)
        self.buttonUpArrow.configure(state=DISABLED)
        self.buttonDownArrow.configure(state=DISABLED)

    def onSelectTeamMemberListbox(self, event):
        w = event.widget
        self.selectedTeamMembers = w.curselection()
        self.buttonRightArrow.configure(state=DISABLED)
        self.buttonLeftArrow.configure(state=NORMAL)
        if len(self.selectedTeamMembers) > 1:
            self.buttonUpArrow.configure(state=DISABLED)
            self.buttonDownArrow.configure(state=DISABLED)
        else:
            self.buttonUpArrow.configure(state=NORMAL)
            self.buttonDownArrow.configure(state=NORMAL)

    def getListOfTeams(self) -> List[str]:
        return list(key for key in self.teams.keys() if key != LabelConstants.ALL_TEAM and key != LabelConstants.TOP_TWITCH_TEAM)

    def rename(self):
        if self.comboboxTeam.current() >= 0:
            self.isRename = True
            TeamNameWindow(self)

    def storeCurrentTeamChanges(self, key):
        self.teams[key] = list(self.teamMemberListbox.get(0, END))

    def ok(self):
        if self.comboboxTeam.get() != "":
            self.storeCurrentTeamChanges(self.comboboxTeam.get())
        self.parent.setTeams(self.teams)
        self.window.destroy()

    def delete(self):
        self.teams.pop(self.comboboxTeam.get())
        self.comboboxTeam.set("")
        self.comboboxTeam.selection_clear()
        self.clearListboxes()
        self.comboboxTeam.configure(values=self.getListOfTeams())
        self.currentTeam = None

    def createNewTeam(self):
        self.isRename = False
        TeamNameWindow(self)
コード例 #55
0
class _cross_platform_fonts(_Dialog):
    def body(self, master):
        dialogframe = Frame(master, width=523, height=346)
        self.dialogframe = dialogframe
        dialogframe.pack()

        self.RadioGroup_1_StringVar = StringVar()

        self.make_Entry_2(self.dialogframe)  #       Entry:  at Main(1,2)
        self.make_LabelFrame_1(
            self.dialogframe)  #  LabelFrame: Attributes : at Main(2,4)
        self.make_Label_3(
            self.dialogframe
        )  #       Label: (see sample text above) : at Main(9,1)
        self.make_Label_4(
            self.dialogframe)  #       Label: ABCD efg 123.0 : at Main(8,1)
        self.make_Label_6(
            self.dialogframe
        )  #       Label: Courier 10 normal italic underline overstrike : at Main(0,1)
        self.make_Label_7(self.dialogframe)  #       Label:  at Main(2,3)
        self.make_Label_8(
            self.dialogframe)  #       Label: System Fonts : at Main(0,5)
        self.make_Listbox_1(self.dialogframe)  #     Listbox:  at Main(2,2)
        self.make_Listbox_2(self.dialogframe)  #     Listbox:  at Main(1,5)
        self.make_RadioGroup_1(
            self.dialogframe
        )  #  RadioGroup: Cross Platform Fonts : at Main(2,1)
        self.make_Checkbutton_1(
            self.LabelFrame_1)  # Checkbutton: Bold : at LabelFrame_1(1,1)
        self.make_Checkbutton_2(
            self.LabelFrame_1)  # Checkbutton: Italic : at LabelFrame_1(2,1)
        self.make_Checkbutton_3(
            self.LabelFrame_1)  # Checkbutton: Underline : at LabelFrame_1(3,1)
        self.make_Checkbutton_4(
            self.LabelFrame_1
        )  # Checkbutton: Overstrike : at LabelFrame_1(4,1)
        self.make_Radiobutton_1(
            self.RadioGroup_1)  # Radiobutton: Courier : at RadioGroup_1(1,0)
        self.make_Radiobutton_2(
            self.RadioGroup_1)  # Radiobutton: Helvetica : at RadioGroup_1(2,0)
        self.make_Radiobutton_3(
            self.RadioGroup_1)  # Radiobutton: Times : at RadioGroup_1(3,0)
        self.make_Radiobutton_4(
            self.RadioGroup_1
        )  # Radiobutton: TkDefaultFont : at RadioGroup_1(4,0)
        self.make_Radiobutton_5(
            self.RadioGroup_1
        )  # Radiobutton: Platform Specific : at RadioGroup_1(6,0)
        self.make_Radiobutton_6(
            self.RadioGroup_1)  # Radiobutton: Symbol : at RadioGroup_1(5,0)

        self.RadioGroup_1_StringVar.set("1")
        self.RadioGroup_1_StringVar_traceName = self.RadioGroup_1_StringVar.trace_variable(
            "w", self.RadioGroup_1_StringVar_Callback)
        # >>>>>>insert any user code below this comment for section "top_of_init"

        self.RadioGroup_1_StringVar.set("2")  # make Helvetica the default
        self.current_font_name = 'Helvetica'

        self.ignore_entry_change = False  # used when Listbox sets Entry
        self.Entry_2_StringVar.set('10')

    def set_current_state(self):

        sL = [self.current_font_name]

        points = self.Entry_2_StringVar.get().strip()
        try:
            points = int(points.strip())
        except:
            points = 10
        if points:
            sL.append(points)
        else:
            sL.append(10)

        if self.Checkbutton_1_StringVar.get() == 'yes':
            sL.append('bold')
        else:
            sL.append('normal')

        if self.Checkbutton_2_StringVar.get() == 'yes':
            sL.append('italic')
        else:
            sL.append('roman')

        if self.Checkbutton_3_StringVar.get() == 'yes':
            sL.append('underline')

        if self.Checkbutton_4_StringVar.get() == 'yes':
            sL.append('overstrike')

        self.full_font_desc = tuple(sL)
        self.Label_6.configure(text=self.full_font_desc)

        self.Label_4.configure(font=self.full_font_desc)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Entry_2"
    def make_Entry_2(self, frame):
        """       Entry:  at Main(1,2)"""
        self.Entry_2 = Entry(frame, width="4")
        self.Entry_2.grid(row=1, column=2, sticky="w")
        self.Entry_2_StringVar = StringVar()

        # >>>>>>insert any user code below this comment for section "make_Entry_2"

        self.Entry_2.configure(textvariable=self.Entry_2_StringVar)
        self.Entry_2_StringVar_traceName = self.Entry_2_StringVar.trace_variable(
            "w", self.Entry_2_StringVar_Callback)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_LabelFrame_1"
    def make_LabelFrame_1(self, frame):
        """  LabelFrame: Attributes : at Main(2,4)"""
        self.LabelFrame_1 = LabelFrame(frame,
                                       text="Attributes",
                                       width="60",
                                       height="50")
        self.LabelFrame_1.grid(row=2, column=4, sticky="n", rowspan="2")

        # >>>>>>insert any user code below this comment for section "make_LabelFrame_1"

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Label_3"
    def make_Label_3(self, frame):
        """       Label: (see sample text above) : at Main(9,1)"""
        self.Label_3 = Label(frame, text="(see sample text above)", width="30")
        self.Label_3.grid(row=9, column=1, columnspan="5")

        # >>>>>>insert any user code below this comment for section "make_Label_3"

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Label_4"
    def make_Label_4(self, frame):
        """       Label: ABCD efg 123.0 : at Main(8,1)"""
        self.Label_4 = Label(frame, text="ABCD efg 123.0", width="14")
        self.Label_4.grid(row=8, column=1, sticky="ew", columnspan="5")

        # >>>>>>insert any user code below this comment for section "make_Label_4"

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Label_6"
    def make_Label_6(self, frame):
        """       Label: Courier 10 normal italic underline overstrike : at Main(0,1)"""
        self.Label_6 = Label(
            frame,
            text="Courier 10 normal italic underline overstrike",
            width="30",
            font="TkDefaultFont 12")
        self.Label_6.grid(row=0, column=1, sticky="ew", columnspan="4")

        # >>>>>>insert any user code below this comment for section "make_Label_6"

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Label_7"
    def make_Label_7(self, frame):
        """       Label:  at Main(2,3)"""
        self.Label_7 = Label(frame, text="", width="3")
        self.Label_7.grid(row=2, column=3)

        # >>>>>>insert any user code below this comment for section "make_Label_7"

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Label_8"
    def make_Label_8(self, frame):
        """       Label: System Fonts : at Main(0,5)"""
        self.Label_8 = Label(frame, text="System Fonts", width="15")
        self.Label_8.grid(row=0, column=5, sticky="s")

        # >>>>>>insert any user code below this comment for section "make_Label_8"

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Listbox_1"
    def make_Listbox_1(self, frame):
        """     Listbox:  at Main(2,2)"""

        lbframe = Frame(frame)
        self.Listbox_1_frame = lbframe
        vbar = Scrollbar(lbframe, orient=VERTICAL)
        self.Listbox_1 = Listbox(lbframe,
                                 width="4",
                                 borderwidth="4",
                                 height="10",
                                 yscrollcommand=vbar.set)
        vbar.config(command=self.Listbox_1.yview)

        vbar.grid(row=0, column=1, sticky='ns')
        self.Listbox_1.grid(row=0, column=0)

        self.Listbox_1_frame.grid(row=2, column=2, sticky="nsw")

        # >>>>>>insert any user code below this comment for section "make_Listbox_1"
        self.Listbox_1.configure(
            exportselection=False)  # stay highlighted after focus leaves

        # Edit the Listbox Entries
        self.font_sizeL = [
            "%i" % i for i in (list(range(6, 17)) + list(range(18, 32, 2)) +
                               [42, 48, 54, 60, 72])
        ]

        for s in self.font_sizeL:
            self.Listbox_1.insert(END, s)

        self.Listbox_1.bind("<ButtonRelease-1>", self.Listbox_1_Click)
        self.Listbox_1.bind('<<ListboxSelect>>', self.Listbox_1_Click)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Listbox_2"
    def make_Listbox_2(self, frame):
        """     Listbox:  at Main(1,5)"""

        lbframe = Frame(frame)
        self.Listbox_2_frame = lbframe
        vbar = Scrollbar(lbframe, orient=VERTICAL)
        self.Listbox_2 = Listbox(lbframe,
                                 width="25",
                                 height="15",
                                 yscrollcommand=vbar.set)
        vbar.config(command=self.Listbox_2.yview)

        vbar.grid(row=0, column=1, sticky='ns')
        self.Listbox_2.grid(row=0, column=0)

        self.Listbox_2_frame.grid(row=1, column=5, sticky="ns", rowspan="7")

        # >>>>>>insert any user code below this comment for section "make_Listbox_2"
        self.Listbox_2.configure(
            exportselection=False)  # stay highlighted after focus leaves

        self.sys_fonts = list(set(families()))
        self.sys_fonts.sort()

        for s in self.sys_fonts:
            self.Listbox_2.insert(END, s)

        self.Listbox_2.bind("<ButtonRelease-1>", self.Listbox_2_Click)
        self.Listbox_2.bind('<<ListboxSelect>>', self.Listbox_2_Click)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_RadioGroup_1"
    def make_RadioGroup_1(self, frame):
        """  RadioGroup: Cross Platform Fonts : at Main(2,1)"""
        self.RadioGroup_1 = LabelFrame(frame,
                                       text="Cross Platform Fonts",
                                       width="60",
                                       height="50")
        self.RadioGroup_1.grid(row=2, column=1, sticky="n", rowspan="2")

        # >>>>>>insert any user code below this comment for section "make_RadioGroup_1"

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Checkbutton_1"
    def make_Checkbutton_1(self, frame):
        """ Checkbutton: Bold : at LabelFrame_1(1,1)"""
        self.Checkbutton_1 = Checkbutton(frame,
                                         text="Bold",
                                         width="15",
                                         anchor="w")
        self.Checkbutton_1.grid(row=1, column=1)
        self.Checkbutton_1_StringVar = StringVar()

        # >>>>>>insert any user code below this comment for section "make_Checkbutton_1"

        self.Checkbutton_1.configure(variable=self.Checkbutton_1_StringVar,
                                     onvalue="yes",
                                     offvalue="no")
        self.Checkbutton_1_StringVar.set("no")
        self.Checkbutton_1_StringVar_traceName = self.Checkbutton_1_StringVar.trace_variable(
            "w", self.Checkbutton_1_StringVar_Callback)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Checkbutton_2"
    def make_Checkbutton_2(self, frame):
        """ Checkbutton: Italic : at LabelFrame_1(2,1)"""
        self.Checkbutton_2 = Checkbutton(frame,
                                         text="Italic",
                                         width="15",
                                         anchor="w")
        self.Checkbutton_2.grid(row=2, column=1)
        self.Checkbutton_2_StringVar = StringVar()

        # >>>>>>insert any user code below this comment for section "make_Checkbutton_2"

        self.Checkbutton_2.configure(variable=self.Checkbutton_2_StringVar,
                                     onvalue="yes",
                                     offvalue="no")
        self.Checkbutton_2_StringVar.set("no")
        self.Checkbutton_2_StringVar_traceName = self.Checkbutton_2_StringVar.trace_variable(
            "w", self.Checkbutton_2_StringVar_Callback)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Checkbutton_3"
    def make_Checkbutton_3(self, frame):
        """ Checkbutton: Underline : at LabelFrame_1(3,1)"""
        self.Checkbutton_3 = Checkbutton(frame,
                                         text="Underline",
                                         width="15",
                                         anchor="w")
        self.Checkbutton_3.grid(row=3, column=1)
        self.Checkbutton_3_StringVar = StringVar()

        # >>>>>>insert any user code below this comment for section "make_Checkbutton_3"

        self.Checkbutton_3.configure(variable=self.Checkbutton_3_StringVar,
                                     onvalue="yes",
                                     offvalue="no")
        self.Checkbutton_3_StringVar.set("no")
        self.Checkbutton_3_StringVar_traceName = self.Checkbutton_3_StringVar.trace_variable(
            "w", self.Checkbutton_3_StringVar_Callback)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Checkbutton_4"
    def make_Checkbutton_4(self, frame):
        """ Checkbutton: Overstrike : at LabelFrame_1(4,1)"""
        self.Checkbutton_4 = Checkbutton(frame,
                                         text="Overstrike",
                                         width="15",
                                         anchor="w")
        self.Checkbutton_4.grid(row=4, column=1)
        self.Checkbutton_4_StringVar = StringVar()

        # >>>>>>insert any user code below this comment for section "make_Checkbutton_4"

        self.Checkbutton_4.configure(variable=self.Checkbutton_4_StringVar,
                                     onvalue="yes",
                                     offvalue="no")
        self.Checkbutton_4_StringVar.set("no")
        self.Checkbutton_4_StringVar_traceName = self.Checkbutton_4_StringVar.trace_variable(
            "w", self.Checkbutton_4_StringVar_Callback)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Radiobutton_1"
    def make_Radiobutton_1(self, frame):
        """ Radiobutton: Courier : at RadioGroup_1(1,0)"""
        self.Radiobutton_1 = Radiobutton(frame,
                                         text="Courier",
                                         value="1",
                                         width="15",
                                         anchor="w")
        self.Radiobutton_1.grid(row=1, column=0)

        # >>>>>>insert any user code below this comment for section "make_Radiobutton_1"

        self.Radiobutton_1.configure(variable=self.RadioGroup_1_StringVar)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Radiobutton_2"
    def make_Radiobutton_2(self, frame):
        """ Radiobutton: Helvetica : at RadioGroup_1(2,0)"""
        self.Radiobutton_2 = Radiobutton(frame,
                                         text="Helvetica",
                                         value="2",
                                         width="15",
                                         anchor="w")
        self.Radiobutton_2.grid(row=2, column=0)

        # >>>>>>insert any user code below this comment for section "make_Radiobutton_2"

        self.Radiobutton_2.configure(variable=self.RadioGroup_1_StringVar)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Radiobutton_3"
    def make_Radiobutton_3(self, frame):
        """ Radiobutton: Times : at RadioGroup_1(3,0)"""
        self.Radiobutton_3 = Radiobutton(frame,
                                         text="Times",
                                         value="3",
                                         width="15",
                                         anchor="w")
        self.Radiobutton_3.grid(row=3, column=0)

        # >>>>>>insert any user code below this comment for section "make_Radiobutton_3"

        self.Radiobutton_3.configure(variable=self.RadioGroup_1_StringVar)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Radiobutton_4"
    def make_Radiobutton_4(self, frame):
        """ Radiobutton: TkDefaultFont : at RadioGroup_1(4,0)"""
        self.Radiobutton_4 = Radiobutton(frame,
                                         text="TkDefaultFont",
                                         value="4",
                                         width="15",
                                         anchor="w")
        self.Radiobutton_4.grid(row=4, column=0)

        # >>>>>>insert any user code below this comment for section "make_Radiobutton_4"

        self.Radiobutton_4.configure(variable=self.RadioGroup_1_StringVar)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Radiobutton_5"
    def make_Radiobutton_5(self, frame):
        """ Radiobutton: Platform Specific : at RadioGroup_1(6,0)"""
        self.Radiobutton_5 = Radiobutton(frame,
                                         text="Platform Specific",
                                         value="6",
                                         width="15",
                                         anchor="e")
        self.Radiobutton_5.grid(row=6, column=0)

        # >>>>>>insert any user code below this comment for section "make_Radiobutton_5"

        self.Radiobutton_5.configure(variable=self.RadioGroup_1_StringVar)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Radiobutton_6"
    def make_Radiobutton_6(self, frame):
        """ Radiobutton: Symbol : at RadioGroup_1(5,0)"""
        self.Radiobutton_6 = Radiobutton(frame,
                                         text="Symbol",
                                         value="5",
                                         width="15",
                                         anchor="w")
        self.Radiobutton_6.grid(row=5, column=0)

        # >>>>>>insert any user code below this comment for section "make_Radiobutton_6"

        self.Radiobutton_6.configure(variable=self.RadioGroup_1_StringVar)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "Listbox_1_Click"
    def Listbox_1_Click(self, event):  #bind method for component ID=Listbox_1
        """     Listbox:  at Main(2,2)"""
        pass
        # >>>>>>insert any user code below this comment for section "Listbox_1_Click"
        # replace, delete, or comment-out the following
        #print( "executed method Listbox_1_Click" )

        #print( "current selection(s) =",self.Listbox_1.curselection() )
        labelL = []
        for i in self.Listbox_1.curselection():
            labelL.append(self.Listbox_1.get(i))
        #print( "current label(s) =",labelL )

        if labelL:
            self.ignore_entry_change = True
            self.Entry_2_StringVar.set(labelL[0])
            self.ignore_entry_change = False

        # use self.Listbox_1.insert(0, "item zero")
        #     self.Listbox_1.insert(index, "item i")
        #            OR
        #     self.Listbox_1.insert(END, "item end")
        #   to insert items into the list box

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "Listbox_2_Click"
    def Listbox_2_Click(self, event):  #bind method for component ID=Listbox_2
        """     Listbox:  at Main(1,5)"""
        pass
        # >>>>>>insert any user code below this comment for section "Listbox_2_Click"
        # replace, delete, or comment-out the following
        #print( "executed method Listbox_2_Click" )

        #print( "current selection(s) =",self.Listbox_2.curselection() )
        labelL = []
        for i in self.Listbox_2.curselection():
            labelL.append(self.Listbox_2.get(i))
        #print( "current label(s) =",labelL )
        # use self.Listbox_2.insert(0, "item zero")
        #     self.Listbox_2.insert(index, "item i")
        #            OR
        #     self.Listbox_2.insert(END, "item end")
        #   to insert items into the list box

        self.RadioGroup_1_StringVar.set("6")  # make Helvetica the default
        if labelL:
            self.current_font_name = labelL[0]

        self.set_current_state()

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "Entry_2_StringVar_traceName"
    def Entry_2_StringVar_Callback(self, varName, index, mode):
        """       Entry:  at Main(1,2)"""
        pass

        # >>>>>>insert any user code below this comment for section "Entry_2_StringVar_traceName"
        # replace, delete, or comment-out the following
        #print( "Entry_2_StringVar_Callback varName, index, mode",varName, index, mode )
        #print( "    new StringVar value =",self.Entry_2_StringVar.get() )

        self.set_current_state()

        if self.ignore_entry_change:
            return

        # Looks like a manual change, so try to change Listbox
        sval = self.Entry_2_StringVar.get().strip()
        try:
            ival = int(sval)
        except:
            ival = 0

        if ival and (sval in self.font_sizeL):
            index = self.font_sizeL.index(sval)

            self.Listbox_1.selection_clear(0, "end")
            self.Listbox_1.select_set(index)
            self.Listbox_1.see(index)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "Checkbutton_1_StringVar_traceName"
    def Checkbutton_1_StringVar_Callback(self, varName, index, mode):
        """ Checkbutton: Bold : at LabelFrame_1(1,1)"""
        pass

        # >>>>>>insert any user code below this comment for section "Checkbutton_1_StringVar_traceName"
        # replace, delete, or comment-out the following
        #print( "Checkbutton_1_StringVar_Callback varName, index, mode",varName, index, mode )
        #print( "    new StringVar value =",self.Checkbutton_1_StringVar.get() )

        self.set_current_state()

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "Checkbutton_2_StringVar_traceName"
    def Checkbutton_2_StringVar_Callback(self, varName, index, mode):
        """ Checkbutton: Italic : at LabelFrame_1(2,1)"""
        pass

        # >>>>>>insert any user code below this comment for section "Checkbutton_2_StringVar_traceName"
        # replace, delete, or comment-out the following
        #print( "Checkbutton_2_StringVar_Callback varName, index, mode",varName, index, mode )
        #print( "    new StringVar value =",self.Checkbutton_2_StringVar.get() )
        self.set_current_state()

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "Checkbutton_3_StringVar_traceName"
    def Checkbutton_3_StringVar_Callback(self, varName, index, mode):
        """ Checkbutton: Underline : at LabelFrame_1(3,1)"""
        pass

        # >>>>>>insert any user code below this comment for section "Checkbutton_3_StringVar_traceName"
        # replace, delete, or comment-out the following
        #print( "Checkbutton_3_StringVar_Callback varName, index, mode",varName, index, mode )
        #print( "    new StringVar value =",self.Checkbutton_3_StringVar.get() )
        self.set_current_state()

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "Checkbutton_4_StringVar_traceName"
    def Checkbutton_4_StringVar_Callback(self, varName, index, mode):
        """ Checkbutton: Overstrike : at LabelFrame_1(4,1)"""
        pass

        # >>>>>>insert any user code below this comment for section "Checkbutton_4_StringVar_traceName"
        # replace, delete, or comment-out the following
        #print( "Checkbutton_4_StringVar_Callback varName, index, mode",varName, index, mode )
        #print( "    new StringVar value =",self.Checkbutton_4_StringVar.get() )
        self.set_current_state()

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "RadioGroup_1_StringVar_traceName"
    def RadioGroup_1_StringVar_Callback(self, varName, index, mode):
        """  RadioGroup: Cross Platform Fonts : at Main(2,1)"""
        pass

        # >>>>>>insert any user code below this comment for section "RadioGroup_1_StringVar_traceName"
        # replace, delete, or comment-out the following
        #print( "RadioGroup_1_StringVar_Callback varName, index, mode",varName, index, mode )
        #print( "    new StringVar value =",self.RadioGroup_1_StringVar.get() )

        svar = self.RadioGroup_1_StringVar.get()

        if svar == '1':
            self.current_font_name = 'Courier'
        elif svar == '2':
            self.current_font_name = 'Helvetica'
        elif svar == '3':
            self.current_font_name = 'Times'
        elif svar == '4':
            self.current_font_name = 'TkDefaultFont'
        elif svar == '5':
            self.current_font_name = 'Symbol'

        elif svar == '6':
            labelL = []
            for i in self.Listbox_2.curselection():
                labelL.append(self.Listbox_2.get(i))
            if labelL:
                self.current_font_name = labelL[0]

        self.set_current_state()

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "dialog_validate"
    def validate(self):
        self.result = {}  # return a dictionary of results

        self.result["Entry_2"] = self.Entry_2_StringVar.get()
        self.result["Checkbutton_1"] = self.Checkbutton_1_StringVar.get()
        self.result["Checkbutton_2"] = self.Checkbutton_2_StringVar.get()
        self.result["Checkbutton_3"] = self.Checkbutton_3_StringVar.get()
        self.result["Checkbutton_4"] = self.Checkbutton_4_StringVar.get()
        self.result["RadioGroup_1"] = self.RadioGroup_1_StringVar.get()

        # >>>>>>insert any user code below this comment for section "dialog_validate"
        # set values in "self.result" dictionary for return
        # for example...
        # self.result["age"] = self.Entry_2_StringVar.get()

        self.result = {}
        t = self.full_font_desc
        self.result["full_font_desc"] = t  # return the tuple
        self.result["full_font_str"] = t[0].replace(
            ' ', '\ ') + ' %i ' % t[1] + ' '.join(t[2:])

        return 1


# TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "end"

    def apply(self):
        pass
コード例 #56
0
class MyGui(ttk.Frame):
    controller = None
    tabs = None
    _log = None
    _screen_width = None
    _screen_height = None
    COLOR_buttons = '#FFCB6B'
    COLOR_frames = '#333333'
    COLOR_foreground = '#D9C7B3'
    COLOR_log = '#1E1E1E'
    
    def __init__(self, master, controller):
        super().__init__()
        self.controller = controller
        self.initUI(master)
    
    def initUI(self, master):
        self.master.title("Corinne")
        self.master.grid_columnconfigure(0, weight=1)
        self.master.grid_rowconfigure(2, weight=1)
        self.master.option_add('*foreground', 'black')
        self.master.option_add('*background', 'white')
        
        # Style for ttk widgets
        style = ttk.Style()
        style.configure("TNotebook", background=self.COLOR_frames, borderwidth=1, highlightthickness=1)
        style.configure("TNotebook.Tab", background=self.COLOR_frames, foreground="black",
                             lightcolor=self.COLOR_frames, borderwidth=0)
        style.map("TNotebook.Tab", background=[("selected", self.COLOR_buttons)],
                       foreground=[("selected", 'black')])
        style.configure("TFrame", background=self.COLOR_frames, foreground="black")
        
        # get screen resolution
        self._screen_width, self._screen_height = master.winfo_screenwidth(), master.winfo_screenheight()
        start_x = int((self._screen_width / 4))
        start_y = int((self._screen_height / 4))
        # fit the guy at screen resolution
        master.geometry('%dx%d+%d+%d' % (self._screen_width / 2, self._screen_height / 2, start_x, start_y))
        
        # create all of the containers
        top_frame = Frame(master)
        top_frame.grid(row=1, column=0, sticky=(tk.N, tk.S, tk.E, tk.W))
        top_frame.configure(bg=self.COLOR_frames)
        top_frame.grid_columnconfigure(0, weight=1)
        
        property_frame = Frame(master)
        property_frame.grid(row=2, column=0, sticky=(tk.N, tk.S, tk.E, tk.W))
        property_frame.configure(bg=self.COLOR_frames)
        property_frame.grid_columnconfigure(0, weight=1)
        property_frame.grid_rowconfigure(0, weight=1)
        
        buttons_frame = Frame(master, padx=10, pady=10)
        buttons_frame.grid(row=0, column=0, sticky=(tk.N, tk.S, tk.E, tk.W))
        buttons_frame.configure(bg=self.COLOR_frames)
        buttons_frame.grid_columnconfigure(0, weight=1)
        buttons_frame.grid_columnconfigure(1, weight=1)
        buttons_frame.grid_columnconfigure(2, weight=1)
        buttons_frame.grid_columnconfigure(3, weight=1)
        buttons_frame.grid_columnconfigure(4, weight=1)
        
        open_icon = PhotoImage(file="icons/open.png")
        open_button = Button(buttons_frame, text=" Open", image=open_icon, compound=tk.LEFT, padx=1,
                             highlightthickness=0,
                             command=self.open_file)
        open_button.configure(borderwidth=0, background=self.COLOR_buttons)
        open_button.image = open_icon
        open_button.grid(row=0, column=0, padx=5, sticky=(tk.N, tk.S, tk.E, tk.W))
        
        render_icon = PhotoImage(file="icons/render.png")
        render_button = Button(buttons_frame, text=" Render", image=render_icon, compound=tk.LEFT, padx=1,
                               highlightthickness=0,
                               command=self.open_render_view)
        render_button.configure(borderwidth=0, background=self.COLOR_buttons)
        render_button.image = render_icon
        render_button.grid(row=0, column=1, padx=5, sticky=(tk.N, tk.S, tk.E, tk.W))
        
        prod_icon = PhotoImage(file="icons/product.png")
        prod_button = Button(buttons_frame, text="   Product", image=prod_icon, compound=tk.LEFT, highlightthickness=0,
                             command=self.open_product_view)
        prod_button.configure(borderwidth=0, background=self.COLOR_buttons)
        prod_button.image = prod_icon
        prod_button.grid(row=0, column=2, padx=5, sticky=(tk.N, tk.S, tk.E, tk.W))
        
        sync_icon = PhotoImage(file="icons/sync.png")
        sync_button = Button(buttons_frame, text="  Sync", image=sync_icon, compound=tk.LEFT, highlightthickness=0,
                             command=self.open_sync_view)
        sync_button.configure(borderwidth=0, background=self.COLOR_buttons)
        sync_button.image = sync_icon
        sync_button.grid(row=0, column=3, padx=5, sticky=(tk.N, tk.S, tk.E, tk.W))
        
        proj_icon = PhotoImage(file="icons/projection.png")
        proj_button = Button(buttons_frame, text="  Projection", image=proj_icon, compound=tk.LEFT,
                             highlightthickness=0,
                             command=self.open_proj_view)
        proj_button.configure(borderwidth=0, background=self.COLOR_buttons)
        proj_button.image = proj_icon
        proj_button.grid(row=0, column=4, padx=5, sticky=(tk.N, tk.S, tk.E, tk.W))
        
        # create the log box
        self._log = Listbox(top_frame, highlightthickness=0, height=5, background=self.COLOR_log,
                            foreground=self.COLOR_foreground)
        #_scrollb = Scrollbar(top_frame, orient=tk.VERTICAL)
        #self._log.configure(yscrollcommand=_scrollb.set)
        #_scrollb.config(command=self._log.yview)
        self._log.grid(column=0, row=0, padx=10, sticky=(tk.N, tk.S, tk.E, tk.W))

        # _scrollb.grid(column=1, row=0, sticky=tk.S + tk.N)
        
        # create the tab manager for property
        self.tabs = ttk.Notebook(property_frame)
    
    def open_file(self):
        path = filedialog.askopenfilename(initialdir=".",
                                          filetypes=(("DOT graph", "*.gv *.dot"),
                                                     ("Chorgram grammar", "*.txt"), ("all files", "*.*")),
                                          title="Choose a file."
                                          )
        msg_result = []
        # Check in case user enter an unknown file
        # or closes without choosing a file.
        try:
            path_splitted = os.path.split(path)
            ext = path_splitted[1].split('.')
            # Chorgram file
            if ext[1] == 'txt':
                msg_result = self.__open_chorgram_file(path)
            # DOT files
            elif ext[1] == 'dot' or ext[1] == 'gv':
                msg_result = self.__open_dot_file__(path)
            else:
                self.popupmsg("Unknown extension file")
            # update log box
            self.log(msg_result)
        except:
            pass
    
    def __open_chorgram_file(self, path):
        path_splitted = os.path.split(path)
        # ask where store the converted dot file
        ask_for_path: bool = messagebox.askyesno("Chorgram", "A Chorgram file was inserted\n" +
                                                 "Do you wish to save the converted dot file in " +
                                                 path_splitted[0] + "?\n" +
                                                 "(Click NO to choose a new path)")
        if ask_for_path:  # Yes, use same path
            # (input path, path to store)
            msg_result, graph_name = self.controller.GGparser(path, path_splitted[0])
        else:
            new_folder = filedialog.askdirectory()
            msg_result, graph_name = self.controller.GGparser(path, new_folder)
        self.__add_new_tab__(graph_name)
        return msg_result
    
    def __open_dot_file__(self, path):
        # result[0] domitilla boolean
        # result[1] a message
        # result[2] graph name
        result = self.controller.DOTparser(path)
        msg_result = result[1]
        if result[0]:  # if a domitilla graph was founded
            # ask where store the converted dot file
            path_splitted = os.path.split(path)
            ask_for_path: bool = messagebox.askyesno("Domitilla", "A Domitilla file was inserted\n"
                                                                  "Do you wish to store the converted file in " +
                                                     path_splitted[0] + "?\n"
                                                                        "(Click NO to choose a new path)")
            if ask_for_path:  # Yes, use same path
                msg_result.append(
                    self.controller.DomitillaConverter(result[2], path,
                                                       path_splitted[0]))  # (graph name, input path, path to store)
            else:
                new_folder = filedialog.askdirectory()
                msg_result.append(self.controller.DomitillaConverter(result[2], path, new_folder))
        if len(result) > 2:  # case NO-errors detected
            # add a new tab for the new graph just opened
            self.__add_new_tab__(result[2])
        return msg_result
    
    def open_render_view(self):
        try:
            path = filedialog.askopenfilename(initialdir=".", filetypes=(("DOT graph", "*.gv *.dot"),
                                                                         ("all files", "*.*")), title="Choose a file.")
            path_splitted = os.path.split(path)
            ext = path_splitted[1].split('.')
            # Check in case user enter an unknown file
            # or closes without choosing a file.
            if ext[1] != 'dot' and ext[1] != 'gv':
                self.popupmsg("Wrong extension file inserted!\n"
                              "Please insert a DOT file")
            else:
                # define the frame and its geometry
                r_window = tk.Toplevel(padx=20, pady=20, bg=self.COLOR_frames)
                r_window.wm_title("Render")
                r_window.resizable(False, False)
                self.__set_window_dimension__(r_window)
                label_format = tk.Label(r_window, text="Choose a file format for render:", fg=self.COLOR_foreground,
                                        bg=self.COLOR_frames, wraplength=500)
                label_format.grid(row=0, column=0)
                
                # Initialize file format variable for radiobutton
                option = tk.StringVar()
                # Radiobutton
                rb1 = Radiobutton(r_window, text='png', value="png", var=option, bg=self.COLOR_frames)
                rb2 = Radiobutton(r_window, text='pdf', value="pdf", var=option, bg=self.COLOR_frames)
                rb1.grid(row=1, column=0)
                rb2.grid(row=1, column=1)
                # TODO try except for wrong dot files
                b = Button(r_window, text='Render', bg=self.COLOR_buttons,
                           command=lambda: (self.log(["[RENDER] " + self.controller.render(path, option.get())]),
                                            r_window.destroy()))
                b.grid(row=2, column=1)
        except:
            pass
    
    def open_product_view(self):
        # define the frame and its geometry
        p_window = tk.Toplevel(padx=20, pady=20, bg=self.COLOR_frames)
        p_window.wm_title("Product")
        p_window.resizable(False, False)
        # set window dimension
        self.__set_window_dimension__(p_window)
        
        # label and combo for 1st graph
        lbl1 = tk.Label(p_window, text="Choose 1st Graph", bg=self.COLOR_frames, fg=self.COLOR_foreground)
        lbl1.grid(row=0, column=0, pady=10)
        combo1 = ttk.Combobox(p_window, values=list(self.controller.get_all_ca().keys()))
        combo1.grid(row=0, column=1, pady=10)
        
        # label and combo for 2st graph
        lbl2 = tk.Label(p_window, text="Choose 2st Graph", bg=self.COLOR_frames, fg='white')
        lbl2.grid(row=1, column=0, pady=10)
        combo2 = ttk.Combobox(p_window, values=list(self.controller.get_all_ca().keys()))
        combo2.grid(row=1, column=1, pady=10)
        
        make_button = Button(p_window, text='Make product', bg=self.COLOR_buttons,
                             command=lambda:
                             (self.__exec_product_button__(combo1.get(), combo2.get()),
                              p_window.destroy()))
        make_button.grid(row=2, column=0, pady=10)
    
    def open_sync_view(self):
        s_window = tk.Toplevel(padx=20, pady=20, bg=self.COLOR_frames)
        s_window.wm_title("Synchronisation")
        s_window.resizable(False, False)
        # set window dimension
        self.__set_window_dimension__(s_window)
        
        # label and combo for the graph to synchronize
        lbl1 = tk.Label(s_window, text="Choose Graph", fg='white', bg=self.COLOR_frames)
        lbl1.grid(row=0, column=0, padx=10, pady=10)
        option_v1 = tk.StringVar()
        option_v2 = tk.StringVar()
        combo = ttk.Combobox(s_window, values=list(self.controller.get_all_ca().keys()))
        combo.bind("<<ComboboxSelected>>", lambda event: self.__make_sync_interface_menu__(s_window, list(
            self.controller.get_participants(combo.get())), option_v1, option_v2))
        combo.grid(row=1, column=0, padx=10, pady=10)
        
        sync_button = Button(s_window, text='Synchronize', bg=self.COLOR_buttons,
                             command=lambda: (
                                 self.__exec_sync_button__(combo.get(), option_v1.get(), option_v2.get()),
                                 s_window.destroy()))
        
        sync_button.grid(row=4, column=0)
    
    def open_proj_view(self):
        proj_window = tk.Toplevel(padx=20, pady=20, bg=self.COLOR_frames)
        proj_window.wm_title("Projection")
        proj_window.resizable(False, False)
        
        # set window dimension
        self.__set_window_dimension__(proj_window)
        
        # label and combo for the graph to synchronize
        lbl1 = tk.Label(proj_window, text="Choose Graph", bg=self.COLOR_frames, fg='white')
        lbl1.grid(row=0, column=0, padx=10, pady=10)
        
        option = tk.StringVar()
        combo = ttk.Combobox(proj_window, values=list(self.controller.get_all_ca().keys()))
        combo.bind("<<ComboboxSelected>>", lambda event: self.__make_proj_participant_menu__(proj_window, list(
            self.controller.get_participants(combo.get())), option))
        combo.grid(row=1, column=0, padx=10, pady=10)
        
        proj_button = Button(proj_window, text='Project', bg=self.COLOR_buttons,
                             command=lambda: (
                                 self.__exec_proj_button__(combo.get(), option.get()),
                                 proj_window.destroy()))
        
        proj_button.grid(row=4, column=0)
    
    def __add_new_tab__(self, graph_name):
        self.tabs.grid(row=0, column=0, sticky=(tk.N, tk.S, tk.E, tk.W), padx=10, pady=5)
        frame = ttk.Frame(self.tabs)
        frame.grid_columnconfigure(5, weight=1)
        #frame.grid_columnconfigure(0, weight=2)
        #frame.grid_rowconfigure(1, weight=2)

        # Add the tab
        self.tabs.add(frame, text=graph_name)
        
        # -------- LEFT widgets --------- #
        
        # create N.states label and textbox
        label_s = tk.Label(frame, text="N° States :", wraplength=500, bg=self.COLOR_frames, fg=self.COLOR_foreground)
        label_s.grid(row=0, column=0, pady=10, padx=40)
        entry_s = Entry(frame, justify=tk.CENTER, width=5, fg='black', highlightthickness=0)
        entry_s.grid(row=0, column=1, sticky=tk.W)
        entry_s.insert(tk.END, str(len(self.controller.get_states(graph_name))))
        # create N.edges label and textbox
        label_e = tk.Label(frame, text="N° Edges :", wraplength=500, bg=self.COLOR_frames, fg=self.COLOR_foreground)
        label_e.grid(row=1, column=0, pady=30, padx=10)
        entry_e = Entry(frame, justify=tk.CENTER, width=5, fg='black', highlightthickness=0)
        entry_e.grid(row=1, column=1, sticky=tk.W)
        entry_e.insert(tk.END, str(len(self.controller.get_edges(graph_name))))
        # create Start Node label and textbox
        label_sn = tk.Label(frame, text="Start Node :", wraplength=500, bg=self.COLOR_frames, fg=self.COLOR_foreground)
        label_sn.grid(row=2, column=0, pady=10, padx=10)
        entry_sn = Entry(frame, justify=tk.CENTER, width=5, fg='black', highlightthickness=0)
        entry_sn.grid(row=2, column=1, sticky=tk.W)
        entry_sn.insert(tk.END, str(self.controller.get_start_node(graph_name)))

        # ------- RIGHT widgets ----------- #
        
        # create N.Labels label, textbox and Optionmenu
        label_l = tk.Label(frame, text="N° Labels :", wraplength=500, bg=self.COLOR_frames, fg=self.COLOR_foreground)
        label_l.grid(row=0, column=2, pady=10, padx=40)
        entry_l = Entry(frame, justify=tk.CENTER, width=5, fg='black', highlightthickness=0)
        entry_l.grid(row=0, column=3, sticky=tk.W)
        option_l = tk.StringVar()
        elements_l = list(self.controller.get_labels(graph_name))
        entry_l.insert(tk.END, len(elements_l))
        option_l.set(elements_l[0])
        label_menu = ttk.OptionMenu(frame, option_l, elements_l[0], *elements_l)
        label_menu.grid(row=0, column=4, pady=10, padx=40, sticky=tk.W)
        # create N.participants label, textbox and Optionmenu
        label_p = tk.Label(frame, text="N° Participants :", wraplength=500, bg=self.COLOR_frames, fg=self.COLOR_foreground)
        label_p.grid(row=1, column=2, pady=10, padx=10)
        entry_p = Entry(frame, justify=tk.CENTER, width=5, fg='black', highlightthickness=0)
        entry_p.grid(row=1, column=3, sticky=tk.W)
        option_p = tk.StringVar()
        elements_p = list(self.controller.get_participants(graph_name))
        entry_p.insert(tk.END, len(elements_p))
        option_p.set(elements_p[0])
        part_menu = ttk.OptionMenu(frame, option_p, elements_p[0], *elements_p)
        part_menu.grid(row=1, column=4, pady=10, padx=40, sticky=tk.W)
        # create epsilon moves label and textbox
        label_eps = tk.Label(frame, text="Epsilon moves :", bg=self.COLOR_frames, fg=self.COLOR_foreground)
        label_eps.grid(row=2, column=2, pady=10, padx=10)
        entry_eps = Entry(frame, justify=tk.CENTER, width=5, fg='black', highlightthickness=0)
        entry_eps.grid(row=2, column=3, sticky=tk.W)
        entry_eps.insert(tk.END, self.controller.check_for_epsilon_moves(graph_name))
        # create close button
        close_button = Button(frame, text='X', bg=self.COLOR_frames, highlightthickness=0, borderwidth=0, command=lambda: (
            self.controller.remove_record(self.tabs.tab(self.tabs.select(), "text")),
            # remove the record from opened graphs struct
            self.tabs.forget(self.tabs.select())))  # delete the tab
        close_button.grid(row=0, column=5, sticky=tk.E + tk.N)
        
        # once created, select the tab
        self.tabs.select(frame)
    
    def __exec_sync_button__(self, combo_value, interface1, interface2):
        path_to_store = filedialog.asksaveasfilename(initialdir=".", title="Save as",
                                                     filetypes=("DOT graph", "*.gv *.dot"))
        result = self.controller.synchronize(combo_value, interface1, interface2, path_to_store)
        # print the log message
        self.log(result[0])
        # create a new tab for the product graph
        self.__add_new_tab__(result[1])
    
    def __exec_product_button__(self, combo_value1, combo_value2):
        path_to_store = filedialog.asksaveasfilename(initialdir=".", title="Save as",
                                                     filetypes=("DOT graph", "*.gv *.dot"))
        result = self.controller.make_product(combo_value1, combo_value2, path_to_store)
        # print the log message
        self.log(result[0])
        # create a new tab for the product graph
        self.__add_new_tab__(result[1])
    
    def __exec_proj_button__(self, combo_value, participant):
        path_to_store = filedialog.asksaveasfilename(initialdir=".", title="Save as",
                                                     filetypes=("DOT graph", "*.gv *.dot"))
        result = self.controller.projection(combo_value, participant, path_to_store)
        # print the log message
        self.log(result)
    
    def __make_sync_interface_menu__(self, frame, elements, option_v1, option_v2):
        # label and optionMenu for the 1st interface
        option_v1.set(elements[0])
        lbl2 = tk.Label(frame, text="Select 1st participant", bg=self.COLOR_frames, fg=self.COLOR_foreground)
        lbl2.grid(row=2, column=0, padx=10, pady=10)
        op_menu_1 = ttk.OptionMenu(frame, option_v1, elements[0], *elements)
        op_menu_1.grid(row=2, column=1, padx=10, pady=10)
        
        # label and optionMenu for the 2st interface
        option_v2.set(elements[0])
        lbl3 = tk.Label(frame, text='Select 2st participant', bg=self.COLOR_frames, fg=self.COLOR_foreground)
        lbl3.grid(row=3, column=0, pady=10)
        op_menu_2 = ttk.OptionMenu(frame, option_v2, elements[0], *elements)
        op_menu_2.grid(row=3, column=1, padx=10, pady=10)
        
        # update window dimension
        self.__set_window_dimension__(frame)
    
    def __make_proj_participant_menu__(self, frame, elements, option):
        option.set(elements[0])
        lbl = tk.Label(frame, text='Select participant to project', bg=self.COLOR_frames, fg=self.COLOR_foreground)
        lbl.grid(row=2, column=0, padx=10, pady=10)
        op_menu = ttk.OptionMenu(frame, option, elements[0], *elements)
        op_menu.grid(row=2, column=1, padx=10, pady=10)
        self.__set_window_dimension__(frame)
    
    def __set_window_dimension__(self, frame):
        # set window dimension
        width, height = frame.winfo_reqwidth(), frame.winfo_reqheight()
        frame.geometry('+%d+%d' % (self._screen_width / 2 - width / 2, self._screen_height / 2 - height / 2))
        
    def log(self, msg):
        # Write a message in the log box
        for line in msg:
            self._log.insert(tk.END, line)
        self._log.see(tk.END)
        # make the last item background red
        #self._log.itemconfig(tk.END, {'bg': 'red'})
    
    def popupmsg(self, msg):
        popup = tk.Toplevel(padx=20, pady=20)
        popup.wm_title("!")
        popup.resizable(False, False)
        
        screen_width, screen_height = popup.winfo_screenwidth(), popup.winfo_screenheight()
        width, height = popup.winfo_reqwidth(), popup.winfo_reqheight()
        
        popup.geometry('+%d+%d' % (screen_width / 2 - width / 2, screen_height / 2 - height / 2))
        
        max_size = popup.winfo_screenwidth() / 3
        label = tk.Label(popup, text=msg, wraplength=max_size)
        label.grid(row=0, column=0)
        
        b = ttk.Button(popup, text="Okay", command=popup.destroy)
        b.grid(row=1, column=0)
コード例 #57
0
ファイル: table.py プロジェクト: David-Mahannah/Quizscrape
    def __init__(self, master, columns, column_weights=None, cnf={}, **kw):
        """
        Construct a new multi-column listbox widget.

        :param master: The widget that should contain the new
            multi-column listbox.

        :param columns: Specifies what columns should be included in
            the new multi-column listbox.  If ``columns`` is an integer,
            the it is the number of columns to include.  If it is
            a list, then its length indicates the number of columns
            to include; and each element of the list will be used as
            a label for the corresponding column.

        :param cnf, kw: Configuration parameters for this widget.
            Use ``label_*`` to configure all labels; and ``listbox_*``
            to configure all listboxes.  E.g.:

                >>> mlb = MultiListbox(master, 5, label_foreground='red')
        """
        # If columns was specified as an int, convert it to a list.
        if isinstance(columns, int):
            columns = list(range(columns))
            include_labels = False
        else:
            include_labels = True

        if len(columns) == 0:
            raise ValueError("Expected at least one column")

        # Instance variables
        self._column_names = tuple(columns)
        self._listboxes = []
        self._labels = []

        # Pick a default value for column_weights, if none was specified.
        if column_weights is None:
            column_weights = [1] * len(columns)
        elif len(column_weights) != len(columns):
            raise ValueError("Expected one column_weight for each column")
        self._column_weights = column_weights

        # Configure our widgets.
        Frame.__init__(self, master, **self.FRAME_CONFIG)
        self.grid_rowconfigure(1, weight=1)
        for i, label in enumerate(self._column_names):
            self.grid_columnconfigure(i, weight=column_weights[i])

            # Create a label for the column
            if include_labels:
                l = Label(self, text=label, **self.LABEL_CONFIG)
                self._labels.append(l)
                l.grid(column=i, row=0, sticky="news", padx=0, pady=0)
                l.column_index = i

            # Create a listbox for the column
            lb = Listbox(self, **self.LISTBOX_CONFIG)
            self._listboxes.append(lb)
            lb.grid(column=i, row=1, sticky="news", padx=0, pady=0)
            lb.column_index = i

            # Clicking or dragging selects:
            lb.bind("<Button-1>", self._select)
            lb.bind("<B1-Motion>", self._select)
            # Scroll wheel scrolls:
            lb.bind("<Button-4>", lambda e: self._scroll(-1))
            lb.bind("<Button-5>", lambda e: self._scroll(+1))
            lb.bind("<MouseWheel>", lambda e: self._scroll(e.delta))
            # Button 2 can be used to scan:
            lb.bind("<Button-2>", lambda e: self.scan_mark(e.x, e.y))
            lb.bind("<B2-Motion>", lambda e: self.scan_dragto(e.x, e.y))
            # Dragging outside the window has no effect (disable
            # the default listbox behavior, which scrolls):
            lb.bind("<B1-Leave>", lambda e: "break")
            # Columns can be resized by dragging them:
            l.bind("<Button-1>", self._resize_column)

        # Columns can be resized by dragging them.  (This binding is
        # used if they click on the grid between columns:)
        self.bind("<Button-1>", self._resize_column)

        # Set up key bindings for the widget:
        self.bind("<Up>", lambda e: self.select(delta=-1))
        self.bind("<Down>", lambda e: self.select(delta=1))
        self.bind("<Prior>", lambda e: self.select(delta=-self._pagesize()))
        self.bind("<Next>", lambda e: self.select(delta=self._pagesize()))

        # Configuration customizations
        self.configure(cnf, **kw)
コード例 #58
0
ファイル: libconfig.py プロジェクト: Urdeney/CobraAV
class EntryOptionsWindow:
    def __init__(self, ls: str, tk: Tk, select_path=False) -> None:
        self.select_path = select_path
        self.List = ls
        self.Tk = tk
        self.Root = Toplevel(self.Tk)
        self.Root.withdraw()
        self.Frame = Frame(self.Root)
        self.Box = Listbox(self.Frame, selectmode='extended', width=54, height=24)
        for i in globals()[self.List]:
            self.Box.insert(END, i)
        self.Scroll = Scrollbar(self.Frame, command=self.Box.yview)
        self.Entry = Entry(self.Frame)
        self.ButtonAdd = Button(self.Frame, text='Добавить', command=self.__add_item)
        self.ButtonDel = Button(self.Frame, text='Удалить', command=self.__del_item)
        self.ButtonDone = Button(self.Frame, text='Готово', command=self.__save_list)
        self.ButtonExit = Button(self.Frame, text='Отмена', command=self.Root.destroy)

    def __add_item(self) -> None:
        if self.select_path:
            text = filedialog.askdirectory()
        else:
            text = self.Entry.get()
        if text:
            self.Box.insert(END, text)
            self.Entry.delete(0, END)

    def __del_item(self) -> None:
        select = list(self.Box.curselection())
        select.reverse()
        for i in select:
            self.Box.delete(i)

    def __save_list(self) -> None:
        globals()[self.List] = list(self.Box.get(0, END))
        self.Root.destroy()

    def main(self) -> None:
        center_win(self.Root, '500x400')
        self.Root.deiconify()
        self.Root.title(f'Editing {self.List}')
        self.Box.pack(side='left', expand=True)
        self.Scroll.pack(side='left', fill='y')
        self.Box.config(yscrollcommand=self.Scroll.set)
        self.Frame.pack(side='left', padx=10)
        if not self.select_path:
            self.Entry.pack(anchor='n')
        self.ButtonAdd.pack(fill='x')
        self.ButtonDel.pack(fill='x')
        self.ButtonDone.pack(fill='x')
        self.ButtonExit.pack(fill='x')
        self.Root.mainloop()
コード例 #59
0
ファイル: Tkinter_exemple.py プロジェクト: schluchi/WATCHMAN
    def __init__(self, parent):
        Frame.__init__(self, parent, background="white")
        self.parent = parent
        self.parent.title("Simple Window")
        self.style = ttk.Style()
        self.style.theme_use("default")
        self.centreWindow()
        self.pack(fill=BOTH, expand=1)

        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)
        fileMenu = Menu(menubar)
        fileMenu.add_command(label="Exit", command=self.quit)
        menubar.add_cascade(label="File", menu=fileMenu)

        firstNameLabel = Label(self, text="First Name")
        firstNameLabel.grid(row=0, column=0, sticky=W + E)
        lastNameLabel = Label(self, text="Last Name")
        lastNameLabel.grid(row=1, column=0, sticky=W + E)
        countryLabel = Label(self, text="Country")
        countryLabel.grid(row=2, column=0, sticky=W + E)
        addressLabel = Label(self, text="Address")
        addressLabel.grid(row=3, column=0, pady=10, sticky=W + E + N)

        firstNameText = Entry(self, width=20)
        firstNameText.grid(row=0,
                           column=1,
                           padx=5,
                           pady=5,
                           ipady=2,
                           sticky=W + E)
        lastNameText = Entry(self, width=20)
        lastNameText.grid(row=1,
                          column=1,
                          padx=5,
                          pady=5,
                          ipady=2,
                          sticky=W + E)

        self.countryVar = StringVar()
        self.countryCombo = ttk.Combobox(self, textvariable=self.countryVar)
        self.countryCombo['values'] = ('United States', 'United Kingdom',
                                       'France')
        self.countryCombo.current(1)
        self.countryCombo.bind("<<ComboboxSelected>>", self.newCountry)
        self.countryCombo.grid(row=2,
                               column=1,
                               padx=5,
                               pady=5,
                               ipady=2,
                               sticky=W)

        addressText = Text(self, padx=5, pady=5, width=20, height=6)
        addressText.grid(row=3, column=1, padx=5, pady=5, sticky=W)

        self.salaryVar = StringVar()
        salaryLabel = Label(self, text="Salary:", textvariable=self.salaryVar)
        salaryLabel.grid(row=0, column=2, columnspan=2, sticky=W + E)
        salaryScale = Scale(self,
                            from_=10000,
                            to=100000,
                            orient=HORIZONTAL,
                            resolution=500,
                            command=self.onSalaryScale)
        salaryScale.grid(row=1, column=2, columnspan=2, sticky=W + E)

        self.fullTimeVar = IntVar()
        fullTimeCheck = Checkbutton(self,
                                    text="Full-time?",
                                    variable=self.fullTimeVar,
                                    command=self.fullChecked)
        fullTimeCheck.grid(row=2, column=2, columnspan=2, sticky=W + E)
        #fullTimeCheck.select()

        self.titleVar = StringVar()
        self.titleVar.set("TBA")
        Label(self, textvariable=self.titleVar).grid(
            row=4, column=1,
            sticky=W + E)  # a reference to the label is not retained

        title = ['Programmer', 'Developer', 'Web Developer', 'Designer']
        titleList = Listbox(self, height=5)
        for t in title:
            titleList.insert(END, t)
        titleList.grid(row=3,
                       column=2,
                       columnspan=2,
                       pady=5,
                       sticky=N + E + S + W)
        titleList.bind("<<ListboxSelect>>", self.newTitle)

        okBtn = Button(self, text="OK", width=10, command=self.onConfirm)
        okBtn.grid(row=4, column=2, padx=5, pady=3, sticky=W + E)
        closeBtn = Button(self, text="Close", width=10, command=self.onExit)
        closeBtn.grid(row=4, column=3, padx=5, pady=3, sticky=W + E)
コード例 #60
0
    def initUI(self, master):
        self.master.title("Corinne")
        self.master.grid_columnconfigure(0, weight=1)
        self.master.grid_rowconfigure(2, weight=1)
        self.master.option_add('*foreground', 'black')
        self.master.option_add('*background', 'white')
        
        # Style for ttk widgets
        style = ttk.Style()
        style.configure("TNotebook", background=self.COLOR_frames, borderwidth=1, highlightthickness=1)
        style.configure("TNotebook.Tab", background=self.COLOR_frames, foreground="black",
                             lightcolor=self.COLOR_frames, borderwidth=0)
        style.map("TNotebook.Tab", background=[("selected", self.COLOR_buttons)],
                       foreground=[("selected", 'black')])
        style.configure("TFrame", background=self.COLOR_frames, foreground="black")
        
        # get screen resolution
        self._screen_width, self._screen_height = master.winfo_screenwidth(), master.winfo_screenheight()
        start_x = int((self._screen_width / 4))
        start_y = int((self._screen_height / 4))
        # fit the guy at screen resolution
        master.geometry('%dx%d+%d+%d' % (self._screen_width / 2, self._screen_height / 2, start_x, start_y))
        
        # create all of the containers
        top_frame = Frame(master)
        top_frame.grid(row=1, column=0, sticky=(tk.N, tk.S, tk.E, tk.W))
        top_frame.configure(bg=self.COLOR_frames)
        top_frame.grid_columnconfigure(0, weight=1)
        
        property_frame = Frame(master)
        property_frame.grid(row=2, column=0, sticky=(tk.N, tk.S, tk.E, tk.W))
        property_frame.configure(bg=self.COLOR_frames)
        property_frame.grid_columnconfigure(0, weight=1)
        property_frame.grid_rowconfigure(0, weight=1)
        
        buttons_frame = Frame(master, padx=10, pady=10)
        buttons_frame.grid(row=0, column=0, sticky=(tk.N, tk.S, tk.E, tk.W))
        buttons_frame.configure(bg=self.COLOR_frames)
        buttons_frame.grid_columnconfigure(0, weight=1)
        buttons_frame.grid_columnconfigure(1, weight=1)
        buttons_frame.grid_columnconfigure(2, weight=1)
        buttons_frame.grid_columnconfigure(3, weight=1)
        buttons_frame.grid_columnconfigure(4, weight=1)
        
        open_icon = PhotoImage(file="icons/open.png")
        open_button = Button(buttons_frame, text=" Open", image=open_icon, compound=tk.LEFT, padx=1,
                             highlightthickness=0,
                             command=self.open_file)
        open_button.configure(borderwidth=0, background=self.COLOR_buttons)
        open_button.image = open_icon
        open_button.grid(row=0, column=0, padx=5, sticky=(tk.N, tk.S, tk.E, tk.W))
        
        render_icon = PhotoImage(file="icons/render.png")
        render_button = Button(buttons_frame, text=" Render", image=render_icon, compound=tk.LEFT, padx=1,
                               highlightthickness=0,
                               command=self.open_render_view)
        render_button.configure(borderwidth=0, background=self.COLOR_buttons)
        render_button.image = render_icon
        render_button.grid(row=0, column=1, padx=5, sticky=(tk.N, tk.S, tk.E, tk.W))
        
        prod_icon = PhotoImage(file="icons/product.png")
        prod_button = Button(buttons_frame, text="   Product", image=prod_icon, compound=tk.LEFT, highlightthickness=0,
                             command=self.open_product_view)
        prod_button.configure(borderwidth=0, background=self.COLOR_buttons)
        prod_button.image = prod_icon
        prod_button.grid(row=0, column=2, padx=5, sticky=(tk.N, tk.S, tk.E, tk.W))
        
        sync_icon = PhotoImage(file="icons/sync.png")
        sync_button = Button(buttons_frame, text="  Sync", image=sync_icon, compound=tk.LEFT, highlightthickness=0,
                             command=self.open_sync_view)
        sync_button.configure(borderwidth=0, background=self.COLOR_buttons)
        sync_button.image = sync_icon
        sync_button.grid(row=0, column=3, padx=5, sticky=(tk.N, tk.S, tk.E, tk.W))
        
        proj_icon = PhotoImage(file="icons/projection.png")
        proj_button = Button(buttons_frame, text="  Projection", image=proj_icon, compound=tk.LEFT,
                             highlightthickness=0,
                             command=self.open_proj_view)
        proj_button.configure(borderwidth=0, background=self.COLOR_buttons)
        proj_button.image = proj_icon
        proj_button.grid(row=0, column=4, padx=5, sticky=(tk.N, tk.S, tk.E, tk.W))
        
        # create the log box
        self._log = Listbox(top_frame, highlightthickness=0, height=5, background=self.COLOR_log,
                            foreground=self.COLOR_foreground)
        #_scrollb = Scrollbar(top_frame, orient=tk.VERTICAL)
        #self._log.configure(yscrollcommand=_scrollb.set)
        #_scrollb.config(command=self._log.yview)
        self._log.grid(column=0, row=0, padx=10, sticky=(tk.N, tk.S, tk.E, tk.W))

        # _scrollb.grid(column=1, row=0, sticky=tk.S + tk.N)
        
        # create the tab manager for property
        self.tabs = ttk.Notebook(property_frame)