Esempio n. 1
1
    def show(frame, iterator):
        """Выводит на экран выборку, заданную в iterator"""

        scrollbar = Scrollbar(frame)
        tree = Treeview(frame, selectmode='none', padding=3,
                                style='Custom.Treeview', height=REPORT_HEIGHT,
                                yscrollcommand=scrollbar.set)
        tree.pack(side=LEFT, fill=BOTH, expand=YES)
        scrollbar.config(command=tree.yview)
        scrollbar.pack(side=LEFT, fill=Y)

        tree.tag_configure('1', font=('Verdana', FONT_SIZE_REPORT))
        tree.tag_configure('2', font=('Verdana', FONT_SIZE_REPORT),
                                                           background='#f5f5ff')

        Style().configure('Custom.Treeview', rowheight=FONT_SIZE_REPORT*2)

        columns = ['#' + str(x + 1) for x in range(8)]
        tree.configure(columns=columns)

        for q in range(len(header)):
            tree.heading('#%d' % (q + 1), text=header[q], anchor='w')
            tree.column('#%d' % (q + 1), width=REPORT_SCALE * col_width[q + 1],
                                                                     anchor='w')
        tree.heading('#0', text='', anchor='w')
        tree.column('#0', width=0, anchor='w', minwidth=0)

        flag = True
        summ = 0
        for item in iterator:

            value = item.quantity * item.price * (100 - item.discount) / 100
            summ += value

            col = []
            col.append(add_s(item.check.id))
            col.append(add_s(item.goods.cathegory.name))
            col.append(add_s(item.goods.name))
            col.append(add_s(item.quantity))
            col.append(add_s(item.discount) +'%' if item.discount else ' -- ')
            col.append(add_s(u'%6.2f грн.' % value))
            col.append(add_s(item.check.date_time.strftime('%d.%m.%Y')))
            col.append(add_s(item.check.date_time.time())[:8])

            flag = not flag
            if flag:
                tree.insert('', 'end', text='', values=col, tag='2')
            else:
                tree.insert('', 'end', text='', values=col, tag='1')

        return summ
Esempio n. 2
0
    def __init__(self, parent, process, x, y):
        Toplevel.__init__(self, parent)
        self.wm_overrideredirect(True)
        self.wm_geometry("+%d+%d" % (x+25,y+20))
        label = Label(self, text="", justify='left',
                       background='white', relief='solid', borderwidth=1,
                       font=("times", "12", "normal"))
        label.pack(ipadx=20)
        tree = Treeview(label)
        tree["columns"] = ("value")
        tree.column("#0", minwidth=0, width=100)
        tree.column("#1", minwidth=0, width=100)
        tree.heading("#0", text="Name")
        tree.heading("#1", text="Value")

        for A, state in process.state.items():
            if isinstance(A, Algorithm):
                tree.insert("", 0, iid=A, text=str(A), values=("",))
                for key, val in state.items():
                    tree.insert(A, 0, text=key, values=(val,))
        for key, val in process.state.items():
            if not isinstance(key, Algorithm):
                tree.insert("", 0, text=key, values=(val,))
        tree.insert("", 0, text="UID", values=(process.UID,))
        tree.pack()
Esempio n. 3
0
class FilamentReport(Toplevel):
	def __init__(self, app, printer, settings, logger, *arg):
		self.app = app
		self.printer = printer
		self.settings = settings
		self.logger = logger
		
		layers = self.app.gcodeInfo.layerOrder
		usage = self.app.gcodeInfo.filLayers

		self.selection = None
		
		Toplevel.__init__(self, app, *arg)
		self.title("Layer by Layer Filament Usage")
		self.protocol("WM_DELETE_WINDOW", self.doCancel)

		f = Frame(self)
		f.grid(row=1, column=1, rowspan=1, padx=10)

		self.tree = Treeview(self, height=12, selectmode='browse')
		self.sb = Scrollbar(self)
		self.sb.config(command=self.tree.yview)
		self.tree.config(yscrollcommand=self.sb.set)

		ln = []
		for l in layerinfo:
			ln.append(l[0])
		del ln[0]
		self.tree.config(columns=ln)
		
		for l in layerinfo:
			self.tree.column(l[0], width=l[1], anchor=l[2])
			self.tree.heading(l[0], text=l[3])

		self.sb.pack(side=RIGHT, fill=Y)
		self.tree.pack(side=LEFT, fill=BOTH, expand=1)

		prev = 0.0	
		tl = layers[-1]
		total = usage[tl]		
		for l in layers:
			n = usage[l]
			self.tree.insert('', 'end', text=l, values=("%7.3f" % (n-prev), "%9.3f" % n, "%9.3f" % (total-n)))
			prev = n

	def doCancel(self):
		self.app.closeFilamentReport()
Esempio n. 4
0
    def show(frame, iterator):
        """Выводит на экран выборку, заданную в iterator"""

        scrollbar = Scrollbar(frame)
        tree = Treeview(frame, selectmode='none', padding=3,
                                    style='Custom.Treeview', height=REPORT_HEIGHT,
                                    yscrollcommand=scrollbar.set)
        tree.pack(side=LEFT, fill=BOTH, expand=YES)
        scrollbar.config(command=tree.yview)
        scrollbar.pack(side=LEFT, fill=Y)

        tree.tag_configure('1', font=('Verdana', FONT_SIZE_REPORT))
        tree.tag_configure('2', font=('Verdana', FONT_SIZE_REPORT),
                                                           background='#f5f5ff')

        Style().configure('Custom.Treeview', rowheight=FONT_SIZE_REPORT*2)

        columns = ['#' + str(x + 1) for x in range(7)]
        tree.configure(columns=columns)

        for q in range(len(header)):
            tree.heading('#%d' % (q + 1), text=header[q], anchor='w')
            tree.column('#%d' % (q + 1), width=REPORT_SCALE * col_width[q + 1],
                                                                     anchor='w')
        tree.heading('#0', text='', anchor='w')
        tree.column('#0', width=0, anchor='w', minwidth=0)

        flag = True
        for item in iterator:
            col = []
            col.append(add_s(item.goods.cathegory.name if item.goods.cathegory
                                                                 else u'-Нет-'))
            col.append(add_s(item.goods.name))
            col.append(add_s(item.quantity))
            col.append(add_s(item.goods.measure))
            col.append(add_s(item.date_time.strftime('%d.%m.%Y')))
            col.append(add_s(item.reason.reason))
            col.append(form(item.full_reason))

            flag = not flag
            if flag:
                tree.insert('', 'end', text='', values=col, tag='2')
            else:
                tree.insert('', 'end', text='', values=col, tag='1')
Esempio n. 5
0
def start_query_browse():
    global root
    root = Tk()
    root.title("Browse Camps, Bunkhouse and Teams")
    root.minsize(width=500, height=500)

    browse_query_tree = Treeview(root)
    browse_query_tree["columns"] = ("1", "2", "3", "4", "5", "6", "7", "8",
                                    "9")
    browse_query_tree.column("1", width=100)
    browse_query_tree.column("2", width=100)
    browse_query_tree.column("3", width=100)
    browse_query_tree.column("4", width=100)
    browse_query_tree.column("5", width=100)
    browse_query_tree.column("6", width=100)
    browse_query_tree.column("7", width=100)
    browse_query_tree.column("8", width=100)
    browse_query_tree.column("9", width=100)
    browse_query_tree.heading("1", text="Bunkhouses IDs")
    browse_query_tree.heading("2", text="Camps IDs")
    browse_query_tree.heading("3", text="Camp Start Date")
    browse_query_tree.heading("4", text="Camp End Date")
    browse_query_tree.heading("5", text="Camper ID")
    browse_query_tree.heading("6", text="First Name")
    browse_query_tree.heading("7", text="Last Name")
    browse_query_tree.heading("8", text="Gender")
    browse_query_tree.heading("9", text="Teams IDs")

    index = 0
    for row_data in Bunkhouse.get_all_query_data():
        browse_query_tree.insert('',
                                 index,
                                 text="row" + str(index + 1),
                                 values=(row_data[0], row_data[1], row_data[2],
                                         row_data[3], row_data[4], row_data[5],
                                         row_data[6], row_data[7],
                                         row_data[8]))
        index += 1

    browse_query_tree.pack()

    exit_bt = Button(root, text="Exit", width=30, command=exit_bt_handler)
    exit_bt.pack(expand=True)
    root.mainloop()
Esempio n. 6
0
def make_tree( mainframe, directory ):
    logging.debug( "Creating a new tree" )
    tree = Treeview( mainframe, columns=( 'ins', 'outs' ) )

    logging.debug( "Packing the tree into the GUI. Adding columns and headings" )

    tree.grid( column=2, row=4 )
    tree.heading( "#0", text="Block" )
    tree.heading( 'ins', text='Inputs' )
    tree.heading( 'outs', text="Outputs" )

    # Set the width and alignment of the two columns
    tree.column( 'ins', width=60, anchor='center' )
    tree.column( 'outs', width=60, anchor='center' )

    logging.debug( "Filling the tree with directory: %s" % directory )
    codefiles = fill_tree( tree, directory )
    logging.debug( "Done filling tree" )

    return tree, codefiles
Esempio n. 7
0
    def CreateUI(self):
        tv = Treeview(self)
        tv['columns'] = ('m_s_id', 's_id','s_para','no_of_coin')
        tv.heading("#0", text='Date', anchor='c')
        tv.column("#0", anchor="c")
        tv.heading('m_s_id', text='Miner ID')
        tv.column('m_s_id', anchor='center', width=100)
        tv.heading('s_id', text='Service ID')
        tv.column('s_id', anchor='center', width=100)
        tv.heading('s_para', text='Data')
        tv.column('s_para', anchor='center', width=100)
        tv.heading('no_of_coin', text='No Of Coin')
        tv.column('no_of_coin', anchor='center', width=100)
        tv.grid(sticky=(N, S, W, E))
        self.treeview = tv
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        btn = Button(self, text=('Back'), command=self.back, width=10, background='red')
        btn.grid(sticky=(S + E))
Esempio n. 8
0
class MainWindow(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.treeview = None
        self.createui()
        self.loadtable()
        self.grid(sticky=(N, S, W, E))
        parent.grid_rowconfigure(0, weight=1)
        parent.grid_columnconfigure(0, weight=1)

    def createui(self):
        image = Image.open('header.png')
        photo = ImageTk.PhotoImage(image)
        lbl = Label(self, image=photo)
        lbl.image = photo
        lbl.grid(row=0, column=0, columnspan=2, sticky='ns')
        self.treeview = Treeview(self)
        self.treeview['columns'] = ['title']
        self.treeview.heading("#0", text='Repeticiones', anchor='center')
        self.treeview.column("#0", anchor="center", width=90)
        self.treeview.heading('title', text='Titulo', anchor='w')
        self.treeview.column('title', anchor='w', width=700)
        self.treeview.grid(sticky=(N, S, W, E))
        self.treeview.bind("<Double-1>", self.openlink)
        ysb = Scrollbar(self, width=18, orient='vertical', command=self.treeview.yview)
        ysb.grid(row=1, column=1, sticky='ns')
        self.treeview.configure(yscroll=ysb.set)
        self.grid_rowconfigure(1, weight=1)
        self.grid_columnconfigure(0, weight=1)

    def openlink(self, event):
        item = self.treeview.identify('item', event.x, event.y)
        web = self.treeview.item(item, 'values')[1]
        webbrowser.open_new(web)

    def loadtable(self):
        self.treeview.delete(*self.treeview.get_children())
        sorted_x = sorted(dic.items(), key=lambda x: x[1][1], reverse=True)
        for key, value in sorted_x:
            self.treeview.insert('', 'end', text=str(value[1]), values=[value[0], key])
Esempio n. 9
0
def start_browse_teams():
    global root
    root = Tk()
    root.title("Browse Teams")
    root.minsize(width=500, height=500)

    browse_teams_tree = Treeview(root)
    browse_teams_tree["columns"] = ("1", "2", "3", "4", "5")
    browse_teams_tree.column("1", width=100)
    browse_teams_tree.column("2", width=100)
    browse_teams_tree.column("3", width=100)
    browse_teams_tree.column("4", width=100)
    browse_teams_tree.column("5", width=100)
    browse_teams_tree.heading("1", text="Team ID")
    browse_teams_tree.heading("2", text="Camp ID")
    browse_teams_tree.heading("3", text="Team Name")
    browse_teams_tree.heading("4", text="Max Number of Members")
    browse_teams_tree.heading("5", text="Number of Members")

    index = 0
    for team_id in Team.get_all_ids():
        current_team = Team.select_team(team_id[0])
        browse_teams_tree.insert('', index, text= "row" + str(index + 1), values = (team_id[0], current_team[0], current_team[1], current_team[2], current_team[3]))
        index += 1

    browse_teams_tree.pack()

    exit_browse_teams_bt = Button(root, text="Exit", width=30, command = exit_browse_teams_bt_handler)
    exit_browse_teams_bt.pack(expand=True)
    root.mainloop()
Esempio n. 10
0
    def CreateUI(self):
        tv = Treeview(self)
        tv['columns'] = ('m_s_id', 's_id', 's_para', 'no_of_coin')
        tv.heading("#0", text='Date', anchor='c')
        tv.column("#0", anchor="c")
        tv.heading('m_s_id', text='Miner ID')
        tv.column('m_s_id', anchor='center', width=100)
        tv.heading('s_id', text='Service ID')
        tv.column('s_id', anchor='center', width=100)
        tv.heading('s_para', text='Data')
        tv.column('s_para', anchor='center', width=100)
        tv.heading('no_of_coin', text='No Of Coin')
        tv.column('no_of_coin', anchor='center', width=100)
        tv.grid(sticky=(N, S, W, E))
        self.treeview = tv
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        btn = Button(self,
                     text=('Back'),
                     command=self.back,
                     width=10,
                     background='red')
        btn.grid(sticky=(S + E))
Esempio n. 11
0
def start_browse_payments():
    global root
    root = Tk()
    root.title("Browse Payments")
    root.minsize(width=500, height=500)

    browse_payments_tree = Treeview(root)
    browse_payments_tree["columns"] = ("1", "2", "3", "4", "5", "6")
    browse_payments_tree.column("1", width=100)
    browse_payments_tree.column("2", width=100)
    browse_payments_tree.column("3", width=100)
    browse_payments_tree.column("4", width=100)
    browse_payments_tree.column("5", width=100)
    browse_payments_tree.column("6", width=100)
    browse_payments_tree.heading("1", text="Payment ID")
    browse_payments_tree.heading("2", text="Camper ID")
    browse_payments_tree.heading("3", text="Camp ID")
    browse_payments_tree.heading("4", text="Date of Payment")
    browse_payments_tree.heading("5", text="Amount Paid")
    browse_payments_tree.heading("6", text="Camp Start Date")

    index = 0
    for payment_id in Payment.get_all_ids():
        current_payment = Payment(payment_id[0])
        data = current_payment.select_payment()
        mycamp = Camp(data[1])
        camp_start = mycamp.select_camp()[0]
        browse_payments_tree.insert('',
                                    index,
                                    text="row" + str(index + 1),
                                    values=(payment_id, data[0], data[1],
                                            data[2], data[3], camp_start))
        index += 1

    browse_payments_tree.pack()

    exit_payments_camp_bt = Button(root,
                                   text="Exit",
                                   width=30,
                                   command=exit_browse_payment_bt_handler)
    exit_payments_camp_bt.pack(expand=True)
    root.mainloop()
Esempio n. 12
0
    def new_point(self):
        window = Toplevel(self)
        tree = Treeview(window)
        tree["columns"]=("1","2","3","4","5")
        tree.column("1", width=50)
        tree.column("2", width=50)
        tree.column("3", width=50)
        tree.column("4", width=50)
        tree.column("5", width=50)
        tree.heading("1", text="Played")
        tree.heading("2", text="Won")
        tree.heading("3", text="Lost")
        tree.heading("4", text="Points")
        
        rows = cur.execute('''SELECT * FROM point_table ORDER BY points DESC''')
        c = 0
        for row in rows:        
            tree.insert("" , c,text=str(row[1]), values=(row[2],row[3],row[4],row[5]))
            c+=1

        tree.pack()
Esempio n. 13
0
class pylasticGUI(Frame):
  
    def __init__(self):
        
        self.__fileName = 'POSCAR'
        self.__NoP = 11
        self.__strain = 0.05
        self.__executable = '/home/t.dengg/bin/vasp/vasp.5.3/vasp'
        self.__status = None
        self.__finished = None
        self.__paths = None
        self.__structuresinst = None
        self.__p1 = None
        self.__p2 = None
        self.__workdir = os.getcwd()
        Frame.__init__(self, name = 'pylastic')
        self.grid(row=0, column=0, sticky=NSEW)   
        #self.pack(expand=Y, fill=BOTH)
        self._create_panel()
            
        
    def _create_panel(self):
        
        panel = Frame(self, name='elastic')
        #panel.pack(side=TOP, fill=BOTH, expand=Y)
        panel.grid(row=0, column=0, sticky=NSEW) 
        nb = Notebook(panel, name='notebook')
        
        nb.enable_traversal()
        #nb.pack(fill=BOTH, expand=Y, padx=2, pady=3)
        nb.grid(row=0, column=0, sticky=NSEW)
        self._create_setup_tab(nb)
        self._create_analyze_tab(nb)
        
    def _create_setup_tab(self, nb):
        
        frame = Frame(nb, name='setup')
        
        self.e1 = Entry(frame, width=7)
        self.e1.bind()
        self.e1.grid(row=0, column=1)
        self.e1.delete(0, END)
        self.e1.insert(0, '21')
        
        self.label1 = Label(frame, text='Number of points:')
        self.label1.grid(row=0, column=0, sticky=W)
        
        self.e2 = Entry(frame, width=7)
        self.e2.bind()
        self.e2.grid(row=1, column=1)
        self.e2.delete(0, END)
        self.e2.insert(0, '0.05')
        
        self.label2 = Label(frame, text='Max. Lagrangian strain:')
        self.label2.grid(row=1, column=0, sticky=W)
        
        #Choose inputfile (Button)
        b2 = Button(frame, text="Inputfile", width=15, command=self.select_file)
        b2.grid(row=3, column=0, columnspan=2)
        
        b = Button(frame, text="set values", width=15, command=self.read_val)
        b.grid(row=4, column=0, columnspan=2)
        
        #Read structure (Button)
        b1 = Button(frame, text="Read structure", width=15, command=self.read_POS)
        b1.grid(row=5, column=0, columnspan=2)
        
        #Write structures (Button)
        b3 = Button(frame, text="Setup calculation", width=15, command=self.setup_calc)
        b3.grid(row=6, column=0, columnspan=2)
        
        #Strart calculations
        b4 = Button(frame, text="Calculation status", width=15, command=self.check_calc)
        b4.grid(row=7, column=0, columnspan=2)
        
        
        v = IntVar()
        r11 = Radiobutton(frame, text="Energy", variable=v, value=1)
        r12 = Radiobutton(frame, text="Strain", variable=v, value=2, state=DISABLED)
        r11.select()
        r11.grid(row=8, column=0, sticky=W)
        r12.grid(row=9, column=0, sticky=W)
        
        
        w = IntVar()
        r21 = Radiobutton(frame, text="2nd", variable=w, value=1)
        r22 = Radiobutton(frame, text="3rd", variable=w, value=2)
        r21.select()
        r21.grid(row=10, column=0, sticky=W)
        r22.grid(row=11, column=0, sticky=W)
        
        
        nb.add(frame, text='Setup', underline=0, padding=2)
        
        return
    
    
    def _create_analyze_tab(self, nb): 
        frame = Frame(nb, name='analyze')
        
        self._create_treeview(frame, )
        root = self.tree.insert('', END, text = 'calc', values=['text1','text2'])
        
        
        
        #self._populate_tree(root)
        
        #
        b1 = Button(frame, text="Refresh", width=15, command=lambda: self._populate_tree(root))
        b1.grid(row=2, column=0) 
        
        b2 = Button(frame, text="Analyze", width=15, command=lambda: self.analyze(frame))
        b2.grid(row=2, column=1)
        
        b2 = Button(frame, text="Result", width=15, command=lambda: self.create_window())
        b2.grid(row=2, column=2)
        
        
        if self.__status and '--------' in self.__status: self.__finished = False
        else: self.__finished = True
        
        if self.__status and self.__finished:
            ECs.set_analytics()
        
        
        

        
        
        nb.add(frame, text='Analyze', underline=0, padding=2)
        return
    
    def _populate_tree(self, root, lock=None):
        
        if lock: lock.acquire()
        if len(self.tree.get_children(self.tree.get_children())) > 1: 
            for i in self.tree.get_children(self.tree.get_children()): self.tree.delete(i)
        #self.tree.delete(self.tree.get_children())
        status, paths = self.check_calc()
        
        for key in status.keys():
            #print paths[key].lstrip(self.__workdir).split('/')
            self.tree.insert(root, END, text = status[key], values=['text3','text4', paths[key]])
        if lock: lock.release()
        
    
    def _create_treeview(self, parent):
        f = Frame(parent)
        #f.pack(side=TOP, fill=BOTH, expand=Y)
        f.grid(row=0, column=0, sticky=NSEW, columnspan=3)
        
        # create the tree and scrollbars
        self.dataCols = ('fullpath', 'type', 'status')       
        self.tree = Treeview(columns=self.dataCols,
                                 displaycolumns='status')
        
        ysb = Scrollbar(orient=VERTICAL, command= self.tree.yview)
        xsb = Scrollbar(orient=HORIZONTAL, command= self.tree.xview)
        self.tree['yscroll'] = ysb.set
        self.tree['xscroll'] = xsb.set
        
        # setup column headings
        self.tree.heading('#0', text='Directory Structure', anchor=W)
        self.tree.heading('status', text='Status', anchor=W)
        self.tree.column('status', stretch=0, width=100)
        
        # add tree and scrollbars to frame
        self.tree.grid(in_=f, row=0, column=0, sticky=NSEW)
        ysb.grid(in_=f, row=0, column=1, sticky=NS)
        xsb.grid(in_=f, row=1, column=0, sticky=EW)
        
        # set frame resizing priorities
        f.rowconfigure(0, weight=1)
        f.columnconfigure(0, weight=1)
        
        # action to perform when a node is expanded
        self.tree.bind('<<TreeviewOpen>>', self._update_tree)
        
        self.tree.bind("<Double-1>", self.OnDoubleClick)
        
    def OnDoubleClick(self, event):
        item = self.tree.identify('item',event.x,event.y)
        if self.tree.item(item,"text") == 'calc':
            self.create_window()
        
        
    def _update_tree(self, event):
        # user expanded a node - build the related directory
        nodeId = self.tree.focus()      # the id of the expanded node
        
        if self.tree.parent(nodeId):    # not at root
            topChild = self.tree.get_children(nodeId)[0]
            
            # if the node only has a 'dummy' child, remove it and
            # build new directory; skip if the node is already
            # populated
            if self.tree.item(topChild, option='text') == 'dummy':
                self.tree.delete(topChild)
                path = self.tree.set(nodeId, 'fullpath')
                self._populate_tree(nodeId, path, os.listdir(path))
    
    def create_window(self):
        
        t = Toplevel(self)
        t.wm_title("Elastic constants")
        l = Label(t, text="Elastic constants:")
        l.grid(row=0, column=0)
        textf = Text(t)
        try:
            textf.insert(INSERT, self.ec.get_C())
        except:
            textf.insert(INSERT, '')
        textf.grid(row=1, column=0)

    
    def read_val(self):
        self.__NoP = float(self.e1.get())
        self.__strain = float(self.e2.get())
        
    def read_POS(self):
        self.__poscar = POS(self.__fileName).read_pos()
        #print self.__poscar
        
    def read_strain(self):
        self.__strain = self.e2.get()
        
    def select_file(self):
        self.__fileName = askopenfilename()
        print self.__fileName
        self.__workdir = self.__fileName.rstrip('POSCAR')
        print self.__workdir
        
    def setup_calc(self):
        
        ###################### Create Structures instance: ###################
        self.__structuresinst = Structures()
        
        ## Generate distorted structures and add them to structures object: ##
        atom = ElAtoms()
        print self.__poscar
        atom.poscarToAtoms(self.__poscar)
        for etan in np.linspace(-self.__strain, self.__strain, self.__NoP):
            for strains in range(len(atom.strainList)):
                atom = ElAtoms()
                atom.poscarToAtoms(self.__poscar)
                atom.distort(eta=etan, strainType_index = strains)
                self.__structuresinst.append_structure(atom)
        
        ####################### Write vasp input files: #######################
        
        self.__structuresinst.workdir = self.__workdir
        self.__structuresinst.write_structures(self.__structuresinst)
        
        #################### Start local vasp calculation: ####################
        if self.__executable:
            lock = thread.allocate_lock()
            self.__structuresinst.executable = self.__executable
            thread.start_new_thread(self.__structuresinst.calc_vasp, (lock,))
            
    def check_calc(self):
        self.__status = {}
        self.__paths = {}
        if not self.__structuresinst:
            try:
                with open(self.__workdir+'/structures.pkl', 'rb') as input:
                    structures = pickle.load(input)
                atoms = structures.get_structures()
            except:
                raise Exception("Please do setup first!")
            
                
        else:
            atoms = self.__structuresinst.get_structures()
            #print self.__structuresinst
        
        for stype, eta in atoms:
            #print stype, eta, atoms[(stype,eta)].path
            
            try:
                et.parse(atoms[(stype,eta)].path+'/vasprun.xml')
                self.__status[(stype,eta)] = 'finished'
            except:
                self.__status[(stype,eta)] = '--------'
            self.__paths[(stype,eta)] = atoms[(stype,eta)].path
        
        return self.__status, self.__paths
        
    
    def analyze(self, frame):
        if self.__status and '--------' in self.__status: self.__finished = False
        else: self.__finished = True
        
        if self.__status and self.__finished:
        
            self.ec = ECs()
            self.ec.set_structures()
            self.ec.set_gsenergy()
            self.ec.set_analytics()
            
            self.__p1 = self.ec.plot_cvs()
            self.__p2 = self.ec.plot_2nd()
            canvas = FigureCanvasTkAgg(self.__p1, master=frame)
            canvas.show()
            canvas.get_tk_widget().grid(row=3, column=0)
            canvas = FigureCanvasTkAgg(self.__p2, master=frame)
            canvas.show()
            canvas.get_tk_widget().grid(row=3, column=1)

            canvas._tkcanvas.grid(row=3, column=2)
Esempio n. 14
0
class App(object):
    def __init__(self, root, cursor, db):
        self.frame = Frame(root)
        self.frame.configure(background='white')
        self.list_toplevel = {}
        self.cursor = cursor
        self.db = db
        self.child_toplevel = None
        self.frame.pack()
        image = Image.open("photo.jpg")
        image = image.resize((250, 250), Image.ANTIALIAS)
        photo = ImageTk.PhotoImage(image)
        label = Label(self.frame, image=photo)
        label.grid(row=0, column=0, sticky=W)
        label.image = photo  # keep a reference!
        nou_registre = LabelFrame(self.frame,
                                  text="Nou registre",
                                  fg="Blue",
                                  padx=5,
                                  pady=5)
        nou_registre.configure(background='white')
        nou_registre.grid(row=0, column=1, padx=15, sticky=W)

        text_nom = Label(nou_registre, text="Nom:", fg="Blue")
        text_nom.configure(background='white')
        text_nom.grid(row=0, column=0)
        self.entry_nom = Entry(nou_registre)
        self.entry_nom.grid(row=0, column=1, sticky=W)

        text_telefon = Label(nou_registre, text="Telèfon: ", fg="Blue")
        text_telefon.configure(background='white')
        text_telefon.grid(row=1, column=0)
        self.entry_telefon = Entry(nou_registre)
        self.entry_telefon.grid(row=1, column=1)

        text_email = Label(nou_registre, text="Email: ", fg="Blue")
        text_email.configure(background='white')
        text_email.grid(row=2, column=0)
        self.entry_email = Entry(nou_registre)
        self.entry_email.grid(row=2, column=1)

        button_afegir_contacte = Button(nou_registre,
                                        text="Afegir contacte",
                                        fg="Blue",
                                        command=self.afegeix_contacte)
        button_afegir_contacte.grid(row=3, column=1, sticky=E)

        button_mostra_historic = Button(nou_registre,
                                        text="Mostra historic",
                                        fg="Blue",
                                        command=self.mostra_historic)
        button_mostra_historic.grid(row=4, column=0, sticky=W)

        mostrar_contactes = Button(self.frame,
                                   text="Mostrar contactes",
                                   fg="Blue",
                                   command=self.insert_contacts_treeview)
        mostrar_contactes.grid(sticky=W, row=3)

        self.missatge_error_confirmacio = StringVar()

        self.label_error_confirmacio = Label(
            self.frame, textvariable=self.missatge_error_confirmacio, fg="Red")
        self.label_error_confirmacio.configure(background='white')
        self.label_error_confirmacio.grid(sticky=W, row=3, column=1)

        self.agenda_contactes = Treeview(self.frame,
                                         columns=["nom", "tel"],
                                         show="headings")
        self.agenda_contactes.heading("nom", text="Nom")
        self.agenda_contactes.heading("tel", text="Telefon")
        self.agenda_contactes.column("nom",
                                     minwidth=0,
                                     width=200,
                                     stretch=NO,
                                     anchor="c")
        self.agenda_contactes.column("tel",
                                     minwidth=0,
                                     width=200,
                                     stretch=NO,
                                     anchor="c")
        self.agenda_contactes.grid(row=4, column=0, padx=0, columnspan=2)

        self.insert_contacts_treeview()
        elimina_seleccionat = Button(self.frame,
                                     text="Eliminar seleccionat",
                                     command=self.elimina_contacte,
                                     fg="Blue")
        elimina_seleccionat.grid(row=5, column=0, sticky=W)

        self.modificar_seleccionat = Button(self.frame,
                                            text="Modificar seleccionat",
                                            fg="Blue",
                                            command=self.modifica_contacte)
        self.modificar_seleccionat.grid(row=5, column=1, sticky=W)
        sortir = Button(self.frame,
                        text="Sortir",
                        fg="Blue",
                        command=self.frame.quit)
        sortir.grid(row=5, column=2, sticky=E)

    def mostra_historic(self):
        popup = Toplevel()
        agenda_historic = Treeview(
            popup,
            columns=["nom", "tel", "email", "path", "accio", "data"],
            show="headings")
        agenda_historic.heading("nom", text="Nom")
        agenda_historic.heading("tel", text="Telefon")
        agenda_historic.heading("email", text="Email")
        agenda_historic.heading("path", text="Path")
        agenda_historic.heading("accio", text="Acció")
        agenda_historic.heading("data", text="Data")
        agenda_historic.column("nom",
                               minwidth=0,
                               width=150,
                               stretch=True,
                               anchor="c")
        agenda_historic.column("tel",
                               minwidth=0,
                               width=100,
                               stretch=True,
                               anchor="c")
        agenda_historic.column("email",
                               minwidth=0,
                               width=150,
                               stretch=True,
                               anchor="c")
        agenda_historic.column("path",
                               minwidth=0,
                               width=200,
                               stretch=True,
                               anchor="c")
        agenda_historic.column("accio",
                               minwidth=0,
                               width=100,
                               stretch=True,
                               anchor="c")
        agenda_historic.column("data",
                               minwidth=0,
                               width=150,
                               stretch=True,
                               anchor="c")
        agenda_historic.grid(row=0, column=0, padx=5, pady=5)
        self.cursor.execute("select * from HISTORIC ORDER BY data DESC;")
        dades = self.cursor.fetchall()
        for data_usuari in dades:
            agenda_historic.insert('', 'end', values=data_usuari)

    def insert_contacts_treeview(self):
        self.cursor.execute("select * from CONTACTES order by nom ASC;")
        self.agenda_contactes.delete(*self.agenda_contactes.get_children())
        for i in self.cursor.fetchall():
            self.agenda_contactes.insert('', 'end', values=i[:2])

    def show_image(self, imatge_label, path_imatge=''):
        file_per_default = 'avatar.jpeg'
        if path_imatge == '':

            image = Image.open(file_per_default)
        else:
            if os.path.exists(path_imatge):
                try:
                    image = Image.open(path_imatge)
                except:
                    print "Error al mostrar imatge!"
                    return False
            else:
                image = Image.open(file_per_default)

        image = image.resize((120, 120), Image.ANTIALIAS)
        photo = ImageTk.PhotoImage(image)
        imatge_label.configure(image=photo)
        imatge_label.image = photo
        return True

    def edit_image(self, imatge_label, path_imatge, nom, telefon):
        if os.path.isfile(path_imatge):
            try:
                image = Image.open(path_imatge)
            except:
                self.missatge_error_confirmacio.set("Imatge incorrecte!")

            else:
                try:
                    self.cursor.execute(
                        "UPDATE CONTACTES SET foto=:pathfoto where nom=:nom and telf=:telf",
                        {
                            'pathfoto': path_imatge,
                            'nom': nom,
                            'telf': str(telefon)
                        })
                    self.db.commit()
                except:
                    self.missatge_error_confirmacio.set(
                        "Error actualitzant la imatge!")
                    return False

        self.show_image(imatge_label, path_imatge)

    def demana_imatge(self, imatge_label, nom, telefon):
        t = tkFileDialog.askopenfilename(title="Selecciona foto",
                                         filetypes=(("jpg files", "*.jpg"),
                                                    ("jpeg files", "*.jpeg"),
                                                    ("all files", "*.*")))
        if t:
            self.edit_image(imatge_label, t, nom, telefon)

    def modificar_contacte(self, entries_fixed, entries_variable,
                           treeview_seleccionat):
        #print dades_usuari
        nom_fixed = entries_fixed[0]
        telefon_fixed = entries_fixed[1]
        email_fixed = entries_fixed[2]

        telefon_variable = entries_variable[0]
        email_variable = entries_variable[1]

        valor_text_telefon_antic = entries_fixed[3]
        valor_text_email_antic = entries_fixed[4]

        changed_email = False
        changed_tel = False
        if email_variable.get() != '':
            try:
                self.check_email(email_variable.get())
            except:
                self.missatge_error_confirmacio.set("El mail no és correcte!")
            else:
                self.cursor.execute(
                    "UPDATE CONTACTES SET email=:email where nom=:nom and telf=:telf",
                    {
                        'email': email_variable.get(),
                        'nom': nom_fixed.get(),
                        'telf': str(telefon_fixed.get())
                    })
                valor_text_email_antic.set(email_variable.get())
                changed_email = True

        if telefon_variable.get() != '':
            try:
                assert int(telefon_variable.get()) >= 600000000
            except:
                self.missatge_error_confirmacio.set("Error en el telefon!")
            else:
                try:
                    self.cursor.execute(
                        "UPDATE CONTACTES SET telf=:nou_telf where nom=:nom and telf=:telf",
                        {
                            'nou_telf': telefon_variable.get(),
                            'nom': nom_fixed.get(),
                            'telf': str(telefon_fixed.get())
                        })
                except sqlite3.IntegrityError:
                    self.missatge_error_confirmacio.set(
                        "El telèfon ja està registrat!")
                else:
                    changed_tel = True
                    self.agenda_contactes.item(treeview_seleccionat,
                                               values=(nom_fixed.get(),
                                                       telefon_variable.get()))
                    valor_text_telefon_antic.set(telefon_variable.get())

        self.db.commit()
        if changed_email & changed_tel:
            self.missatge_error_confirmacio.set(
                "Dades modificades correctament!")
        elif changed_email:
            self.missatge_error_confirmacio.set(
                "Email modificat correctament!")
        elif changed_tel:
            self.missatge_error_confirmacio.set(
                "Telefon modificat correctament!")

    def modifica_contacte(self):
        if self.child_toplevel is not None:
            self.child_toplevel.destroy()

        element_a_modificar = self.agenda_contactes.focus()
        valor_usuari = self.agenda_contactes.item(
            element_a_modificar)['values']
        self.cursor.execute("select * from CONTACTES where nom=? and telf=?;",
                            tuple(valor_usuari))
        dades = self.cursor.fetchone()
        t = Toplevel()
        self.child_toplevel = t

        label_imatge = Label(t)
        label_imatge.configure(background='white')
        label_imatge.pack(side="left", fill="both", expand=True)
        self.show_image(label_imatge, dades[3])
        frame_info = Frame(t)
        frame_info.pack(side="right", fill="both", expand=False)
        frame_info.configure(background='white')
        label_nom = Label(frame_info, text="Nom: ")
        label_nom.configure(background='white')
        label_nom.grid(row=0, column=0)
        entry_nom = Entry(frame_info,
                          textvariable=StringVar(frame_info, value=dades[0]),
                          width=20,
                          state='disabled')
        entry_nom.grid(row=0, column=1)
        label_telefon = Label(frame_info, text="Telefon antic: ")
        label_telefon.configure(background='white')
        label_telefon.grid(row=1, column=0)
        text_telefon = StringVar(frame_info, value=dades[1])
        entry_telefon = Entry(frame_info,
                              textvariable=text_telefon,
                              width=20,
                              state='disabled')
        entry_telefon.grid(row=1, column=1)

        label_telefon_nou = Label(frame_info, text="Telefon nou: ")
        label_telefon_nou.configure(background='white')
        label_telefon_nou.grid(row=2, column=0)
        entry_telefon_nou = Entry(frame_info, width=20)
        entry_telefon_nou.grid(row=2, column=1)

        label_email = Label(frame_info, text="Email: ")
        label_email.configure(background='white')
        label_email.grid(row=3, column=0)
        text_email = StringVar(frame_info, value=dades[2])  #-----
        entry_email = Entry(frame_info,
                            width=20,
                            textvariable=text_email,
                            state='disabled')
        entry_email.grid(row=3, column=1)
        label_email_nou = Label(frame_info, text="Email nou:")
        label_email_nou.configure(background='white')
        label_email_nou.grid(row=4, column=0)
        entry_email_nou = Entry(frame_info, width=20)
        entry_email_nou.grid(row=4, column=1)

        selecciona_imatge = Button(
            frame_info,
            text="Edita foto",
            command=lambda: self.demana_imatge(label_imatge, dades[0],
                                               text_telefon.get()))
        selecciona_imatge.grid(row=5)
        button_modifica_contacte = Button(
            frame_info,
            text="Modificar contacte",
            fg="Blue",
            command=lambda: self.modificar_contacte([
                entry_nom, entry_telefon, entry_email, text_telefon, text_email
            ], [entry_telefon_nou, entry_email_nou], element_a_modificar))
        button_modifica_contacte.grid(row=6, column=1, sticky=E)

    def check_email(self, email):
        if re.match("(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)",
                    email):
            return True
        else:
            raise "Mail no vàlid!"

    def elimina_contacte(self):
        element_seleccionat = self.agenda_contactes.focus()
        if element_seleccionat != '':
            informacio_contacte = self.agenda_contactes.item(
                element_seleccionat)['values']
            self.cursor.execute("DELETE from CONTACTES where nom=? and telf=?",
                                tuple(informacio_contacte))
            self.db.commit()
            self.agenda_contactes.delete(element_seleccionat)
            self.missatge_error_confirmacio.set("Borrat correctament")
            if self.child_toplevel is not None:
                self.child_toplevel.destroy()
            #print self.agenda_contactes.focus()
            #print self.agenda_contactes.selection()
        else:
            self.missatge_error_confirmacio.set("Selecciona un usuari!")
            print "Selecciona element"

    def afegeix_contacte(self):
        try:
            Nom = self.entry_nom.get()
            assert Nom != ''
            Telef = int(self.entry_telefon.get())
            assert Telef > 600000000
            Email = self.check_email(self.entry_email.get())

        except:
            self.missatge_error_confirmacio.set(
                "Introdueix les dades correctament!")
        else:
            try:
                self.cursor.execute(
                    """INSERT INTO CONTACTES values (?,?,?,'');""",
                    (Nom.title(), Telef, self.entry_email.get()))
                self.db.commit()
            except sqlite3.IntegrityError:
                self.missatge_error_confirmacio.set("Contacte ja existent!")

            else:
                self.insert_contacts_treeview()
                self.missatge_error_confirmacio.set(
                    "Afegit contacte correctament")
Esempio n. 15
0
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)

        #INSTANCIAS
        global cc, nombre, pago, ref, cod, desc, valor, resultado, total, tiempo, mes, anio, fechapago
        #INSTANCIAS DE LOS WIDGETS
        global e1, e2, e3, e4, e5, tree, l8, lb

        cc = IntVar()
        nombre = StringVar()
        pago = StringVar()
        ref = StringVar()
        cod = StringVar()
        desc = StringVar()
        valor = DoubleVar()

        tiempo = datetime.date.today()
        anio = time.strftime("%Y")
        mes = time.strftime("%B")
        fechapago = StringVar()

        total = 0.0
        resultado = DoubleVar()

        tbancos = [
            'Bancolombia', "Banco Bogotá", "Banco Agrario", "Banco Occidente"
        ]

        lupa = PhotoImage(file='img/lupa.png')

        tbanktype = ['Corriente', 'Ahorro']
        fpago = ['Efectivo', 'Transferencia']

        #BUSQUEDA = ["Nombre","CC/Nit"]
        busqueda = StringVar()
        busqueda.trace("w", lambda name, index, mode: buscar())
        dato = StringVar()

        #WIDGETS

        #========================= HEADER ==============================

        self.titleL = Label(self, text="GASTOS", font="bold")
        self.titleL.pack(pady=20, side=TOP)

        #========================== WRAPPER ============================

        self.wrapper = Frame(self)
        self.wrapper.pack(side=LEFT, fill=Y)
        #Esto centro el wrapper
        #self.wrapper.pack(side=LEFT, fill=BOTH, expand=True)

        #======================== BENEFICIARIO =======================

        self.lf1 = LabelFrame(self.wrapper, text="Beneficiario")
        self.lf1.pack(fill=X, ipady=5)

        self.f0 = Frame(self.lf1)
        self.f0.pack(pady=5, fill=X)  #-----------------------------------

        l1 = Label(self.f0, text='CC/Nit:')
        l1.pack(side=LEFT)

        e1 = Entry(self.f0, textvariable=cc)
        e1.pack(side=LEFT)
        e1.bind('<Return>', buscarB)

        b0 = Button(self.f0,
                    text='Buscar:',
                    image=lupa,
                    command=topBeneficiarios)
        b0.pack(side=LEFT)

        l2 = Label(self.f0, text='Nombre:')
        l2.pack(side=LEFT)
        e2 = Entry(self.f0, textvariable=nombre)
        e2.pack(side=LEFT, fill=X, expand=1)

        self.f1 = Frame(self.lf1)
        self.f1.pack(pady=5, fill=X)  #-----------------------------------

        l3 = Label(self.f1, text='Forma de Pago:')
        l3.pack(side=LEFT)
        Cbx = Combobox(self.f1, textvariable=pago, values=fpago, width=15)
        Cbx.set('Efectivo')
        Cbx.pack(side=LEFT)

        l4 = Label(self.f1, text='Ref. Bancaria:')
        l4.pack(side=LEFT)
        e3 = Entry(self.f1, textvariable=ref)
        e3.pack(side=LEFT, fill=X, expand=1)

        b1 = Button(self.f1, text='Buscar:', image=lupa)
        b1.image = lupa
        b1.pack(side=LEFT)

        #======================== CONCEPTO ========================

        self.lf2 = LabelFrame(self.wrapper, text="Concepto")
        self.lf2.pack(fill=X, ipady=5)

        self.f2 = Frame(self.lf2)
        self.f2.pack(pady=5, fill=X)  #-------------------------------

        l5 = Label(self.f2, text='Código:')
        l5.pack(side=LEFT)
        e4 = Entry(self.f2, textvariable=cod)
        e4.pack(side=LEFT)
        e4.bind('<Return>', buscarC)

        b2 = Button(self.f2,
                    text='Buscar:',
                    image=lupa,
                    command=topCtasContables)
        b2.pack(side=LEFT)

        self.f3 = Frame(self.lf2)
        self.f3.pack(pady=5, fill=X)  #-------------------------------

        l6 = Label(self.f3, text='Descripción:')
        l6.pack(side=LEFT)
        e5 = Entry(self.f3, textvariable=desc, state=DISABLED)
        e5.pack(side=LEFT, fill=X, expand=1)

        l7 = Label(self.f3, text='Valor:')
        l7.pack(side=LEFT)
        e6 = Entry(self.f3, width=15, textvariable=valor)
        e6.pack(side=LEFT)

        b3 = Button(self.f3, text='Agregar:', command=agregar)
        b3.pack(side=LEFT)

        #-------------------------- TREEVIEW ---------------------------

        self.f4 = Frame(self.wrapper)
        self.f4.pack(pady=5, fill=X)

        tree = Treeview(self.f4,
                        height=4,
                        show="headings",
                        columns=('col1', 'col2', 'col3'))
        tree.pack(side=LEFT, fill=X, expand=1)
        tree.column('col1', width=20, anchor='center')
        tree.column('col2', width=200, anchor='center')
        tree.column('col3', width=10, anchor='center')

        tree.heading('col1', text='Código')
        tree.heading('col2', text='Concepto')
        tree.heading('col3', text='Valor')

        scroll = Scrollbar(self.f4, orient=VERTICAL, command=tree.yview)
        tree.configure(yscrollcommand=scroll.set)
        tree.bind("<Delete>", borrar)

        #-------------------------- RESULTADOS ---------------------------

        self.f5 = Frame(self.wrapper)
        self.f5.pack(pady=5, fill=X)  #-------------------

        l8 = Label(self.f5,
                   textvariable=resultado,
                   fg="red",
                   bg="white",
                   anchor='e',
                   font="bold, 22",
                   relief=SUNKEN)
        l8.pack(fill=X, side=RIGHT, expand=1)

        #-------------------------- FOOTER ---------------------------

        self.fBtn = Frame(self.wrapper)
        self.fBtn.pack()  #-------------------------------

        clean = Button(self.fBtn,
                       text='Cancelar',
                       bg='navy',
                       foreground='white',
                       activebackground='red3',
                       activeforeground='white',
                       command=limpiar)
        clean.pack(side=RIGHT)

        add = Button(self.fBtn,
                     text='Grabar',
                     bg='navy',
                     foreground='white',
                     activebackground='red3',
                     activeforeground='white',
                     command=grabar)
        add.pack(side=RIGHT)

        #========================= ASIDE ===========================

        self.aside = Frame(self)
        self.aside.pack(side=TOP, fill=BOTH)

        self.wrap1 = Frame(self.aside)
        self.wrap1.pack()

        self.viewer = Label(self.wrap1, text="LISTA DE GASTOS")
        self.viewer.pack()

        scroll = Scrollbar(self.wrap1, orient=VERTICAL)
        scroll.pack(side=RIGHT, fill=Y)

        lb = Listbox(self.wrap1,
                     yscrollcommand=scroll.set,
                     height=20,
                     width=30)
        scroll.config(command=lb.yview)
        lb.pack(fill=BOTH)

        self.wrap2 = Frame(self.aside)
        self.wrap2.pack()

        load = Button(self.wrap2,
                      text='Cargar lista',
                      bg='navy',
                      foreground='white',
                      activebackground='red3',
                      activeforeground='white',
                      command=cargar_lista)
        load.pack(fill=X)

        delete = Button(self.wrap2,
                        text='Borrar',
                        bg='navy',
                        foreground='white',
                        activebackground='red3',
                        activeforeground='white',
                        command=None)
        delete.pack(fill=X)

        edit = Button(self.wrap2,
                      text='Modificar',
                      bg='navy',
                      foreground='white',
                      activebackground='red3',
                      activeforeground='white',
                      command=None)
        edit.pack(fill=X)

        buscador = Label(self.wrap2, text="Buscar por Número:")
        buscador.pack()
        E = Entry(self.wrap2, textvariable=busqueda, width=24)
        E.pack()
        E.bind("<KeyRelease>", caps)
Esempio n. 16
0
def start_browse_camps():
    global root
    root = Tk()
    root.title("Browse Camps")
    root.minsize(width=500, height=500)

    browse_camps_tree = Treeview(root)
    browse_camps_tree["columns"] = ("Camp ID", "Start Date", "End Date",
                                    "Number of Bunckhouses", "Number of Teams",
                                    "Cost")
    browse_camps_tree.column("Camp ID", width=100)
    browse_camps_tree.column("Start Date", width=100)
    browse_camps_tree.column("End Date", width=100)
    browse_camps_tree.column("Number of Bunckhouses", width=100)
    browse_camps_tree.column("Number of Teams", width=100)
    browse_camps_tree.column("Cost", width=100)
    browse_camps_tree.heading("Camp ID", text="Camp ID")
    browse_camps_tree.heading("Start Date", text="Start Date")
    browse_camps_tree.heading("End Date", text="End Date")
    browse_camps_tree.heading("Number of Bunckhouses",
                              text="Number of Bunckhouses")
    browse_camps_tree.heading("Number of Teams", text="Number of Teams")
    browse_camps_tree.heading("Cost", text="Cost")

    index = 0
    for camp_id in Camp.get_all_ids():
        current_camp = Camp(camp_id[0])
        data = current_camp.select_camp()
        browse_camps_tree.insert('',
                                 index,
                                 text="row" + str(index + 1),
                                 values=(camp_id, data[0], data[1], data[2],
                                         data[3], data[4]))
        index += 1

    browse_camps_tree.pack()

    exit_browse_camp_bt = Button(root,
                                 text="Exit",
                                 width=30,
                                 command=exit_browse_camp_bt_handler)
    exit_browse_camp_bt.pack(expand=True)
    root.mainloop()
Esempio n. 17
0
class ReciboCaja(Frame):
        def __init__(self, parent, controller):
                Frame.__init__(self, parent)

		lupa = PhotoImage(file='img/lupa.png')
		
		#VARIABLES
		tcontrato = ['Vivienda', 'Comercial']
		aplica = StringVar()
		
		#WIDGETS
		
		#========================= HEADER ===========================
		
		self.header = Label(self, text="RECIBO DE CAJA", font="bold")
		self.header.pack(pady=20, side=TOP)
		
		#========================== WRAPPER ==========================
		
		self.wrapper = Frame (self)
		self.wrapper.pack(side=TOP, fill=Y)
		#self.wrapper.pack(side=LEFT, fill=Y)#Este ubica el forma a la IZA
		
		#================ NOTEBOOK =============>
		
		self.nb = Notebook(self.wrapper)
		
		#-----------------------> TAB 1
		
		self.tab1 = Frame (self.nb)
		self.tab1.pack()
		
		self.f0 = Frame(self.tab1)#-------------------------------------
		self.f0.pack(pady=5,fill=X)

		self.R1 = Radiobutton(self.f0, text="Arrendatario", variable=aplica, value='Arrendatario')
		self.R1.pack(padx=20,side=LEFT)
		self.R2 = Radiobutton (self.f0, text="Propietario", variable=aplica, value='Propietario')
		self.R2.pack(padx=20,side=LEFT)
		self.R3 = Radiobutton (self.f0, text="Tercero", variable=aplica, value='Tercero')
		self.R3.pack(padx=20,side=LEFT)
		
		self.f1 = Frame(self.tab1)#-------------------------------------
		self.f1.pack(pady=5,fill=X)
		
		self.cc = Label(self.f1, text='CC/Nit: ')
		self.cc.pack(side=LEFT)
		self.ccE = Entry(self.f1)
		self.ccE.pack(side=LEFT)
		
		self.b1 = Button(self.f1, text='Buscar', image=lupa)
		self.b1.image=lupa
		self.b1.pack(side=LEFT)

		self.f2 = Frame(self.tab1)
		self.f2.pack(pady=5,fill=X)#------------------------------------
		
		self.nombre = Label(self.f2, text='Nombre:')
		self.nombre.pack(side=LEFT)
		self.nombrE = Entry(self.f2, width=5, state=DISABLED)
		self.nombrE.pack(side=LEFT, fill=X, expand=1)
		
		self.f3 = Frame(self.tab1)
		self.f3.pack(pady=5,fill=X)#------------------------------------
		
		self.inmueble = Label(self.f3, text='Inmueble:')
		self.inmueble.pack(side=LEFT)
		
		self.inmuebleCbx = Combobox(self.f3, values=NONE, width=10)
		self.inmuebleCbx.set('')
		self.inmuebleCbx.pack(side=LEFT, fill=X, expand=1)
		
		self.b2 = Button(self.f3, text='Agregar', image=lupa)
		self.b2.image=lupa
		self.b2.pack(side=LEFT)
		
		self.f4 = Frame(self.tab1)
		self.f4.pack(pady=5,fill=X)#------------------------------------
		
		self.fpago = Label(self.f4, text='Forma de Pago:')
		self.fpago.pack(side=LEFT)
		
		self.fpagoCbx = Combobox(self.f4, values=NONE, width=10)
		self.fpagoCbx.set('')
		self.fpagoCbx.pack(side=LEFT)
		
		self.b3 = Button(self.f4, text='Crear novedad', state=DISABLED)
		self.b3.pack(side=LEFT)

		#========================== TREEVIEW ===========================
		
		self.f5 = Frame(self.tab1)
		self.f5.pack(pady=5,fill=X)#------------------------------------
		
		self.tree = Treeview(self.f5, height=4, show="headings", columns=('col1','col2','col3'))
		self.tree.pack(side=LEFT, fill=X, expand=1)
		self.tree.column('col1', width=20, anchor='center')
		self.tree.column('col2', width=200, anchor='center')
		self.tree.column('col3', width=10, anchor='center')
		
		self.tree.heading('col1', text='CC')
		self.tree.heading('col2', text='Descripción')
		self.tree.heading('col3', text='Valor')
		
		self.scroll = Scrollbar(self.f3,orient=VERTICAL,command=self.tree.yview)
		self.tree.configure(yscrollcommand=self.scroll.set)

		self.f6 = Frame(self.tab1)
		self.f6.pack(pady=5,fill=X)#--------------------

		self.notesL = Label(self.f6, text='Observaciones:')
		self.notesL.pack(side=LEFT)

		self.f7 = Frame(self.tab1)
		self.f7.pack(pady=5,fill=X)#-------------------

		self.notesT = Text(self.f7, height=5)
		self.notesT.pack(fill=X, side=LEFT, expand=1)
		
		#-----------------------> TAB 2
		
		self.tab2 = Frame (self.nb)
		self.tab2.pack()
		
		#-----------------------> TAB 3
		
		self.tab3 = Frame (self.nb)
		self.tab3.pack()
	
		#---------------------------------------------------------------
		
		self.nb.add (self.tab1, text="Datos Generales")
		self.nb.add(self.tab2, text="Referencia de Pago", state=DISABLED)
		self.nb.add(self.tab3, text="Referencias Bancarias", state=DISABLED)
		
		self.nb.pack()
		
		#---------------------------------------------------------------
		
		self.fBtn = Frame(self.wrapper)
		self.fBtn.pack()#-------------------------------
	
		self.queryB = Button(self.fBtn, text='Consultar')
		self.queryB.pack(side=RIGHT)
		self.deleteB = Button(self.fBtn, text='Borrar')
		self.deleteB.pack(side=RIGHT)
		self.updateB = Button(self.fBtn, text='Actualizar')
		self.updateB.pack(side=RIGHT)
		self.addB = Button(self.fBtn, text='Agregar')
		self.addB.pack(side=RIGHT)
		
		#========================= ASIDE ===========================
		"""
class vb_sine_amplitude:
    def __init__(self,parent): 
        self.master=parent        # store the parent
        top = tk.Frame(parent)    # frame for all class widgets
        top.pack(side='top')      # pack frame in parent's window
        
        self.master.minsize(400,550)
        self.master.geometry("500x550")
        self.master.title("vb_sine_amplitude_gui.py ver 1.2  by Tom Irvine")         

        
        self.iflag=0
        
        crow=0
        
        self.hwtext1=tk.Label(top,text='Sine Amplitude Conversion Utility')
        self.hwtext1.grid(row=crow, column=0, columnspan=6, pady=7,sticky=tk.W)        
        
        crow=crow+1

        self.hwtext3=tk.Label(top,text='Select Input')
        self.hwtext3.grid(row=crow, column=0, columnspan=1, pady=7,sticky=tk.E)       
        
        crow=crow+1

        self.Lb1 = tk.Listbox(top,height=4,width=30,exportselection=0)
        self.Lb1.insert(1, "Displacement (peak-to-peak)")
        self.Lb1.insert(2, "Displacement (zero-to-peak)")
        self.Lb1.insert(3, "Velocity (zero-to-peak)")
        self.Lb1.insert(4, "Acceleration (zero-to-peak)")        
        self.Lb1.grid(row=crow, column=0, columnspan=2, pady=4)
        self.Lb1.select_set(0) 
        self.Lb1.bind("<<ListboxSelect>>", self.OnKeyPress)        

        crow=crow+1
        
        self.hwtext_freq=tk.Label(top,text='Enter Frequency (Hz)')
        self.hwtext_freq.grid(row=crow, column=0, columnspan=6, pady=12,sticky=tk.W) 
 
        self.amp_text=tk.StringVar()  
        self.amp_text.set('Enter Displacement (peak-to-peak)')         
        self.hwtext_amp=tk.Label(top,textvariable=self.amp_text)
        self.hwtext_amp.grid(row=crow, column=1, columnspan=6, padx=40, pady=12,sticky=tk.S)          
             
        crow=crow+1             

        self.fnr=tk.StringVar()  
        self.fnr.set('')  
        self.fn_entry=tk.Entry(top, width = 12,textvariable=self.fnr)
        self.fn_entry.grid(row=crow, column=0,padx=5, pady=1,sticky=tk.N)  

        self.ampr=tk.StringVar()  
        self.ampr.set('')  
        self.amp_entry=tk.Entry(top, width = 12,textvariable=self.ampr)
        self.amp_entry.grid(row=crow, column=1,padx=20, pady=1,sticky=tk.NE)
        
        self.Lb2 = tk.Listbox(top,height=2,width=10,exportselection=0)
        self.Lb2.insert(1, "inch")
        self.Lb2.insert(2, "mm")
        self.Lb2.grid(row=crow, column=2, columnspan=1, padx=1,pady=1,sticky=tk.NW)
        self.Lb2.select_set(0)        
        
        crow=crow+1    
        
        self.button_calculate = tk.Button(top, text="Calculate", command=self.calculation)
        self.button_calculate.config( height = 2, width = 15)
        self.button_calculate.grid(row=crow, column=0,columnspan=1, pady=20) 
                
        root=self.master             

        self.button_quit=tk.Button(top, text="Quit", command=lambda root=root:quit(root))
        self.button_quit.config( height = 2, width = 15 )
        self.button_quit.grid(row=crow, column=1,columnspan=1, padx=10,pady=20)
        
        crow=crow+1  
        
        self.hwtext_results=tk.Label(top,text='Results')
        self.hwtext_results.grid(row=crow, column=0, columnspan=2, pady=12) 

        crow=crow+1          
                
        self.tree = Treeview(top,selectmode="extended",columns=("A","B"),height=5)
        self.tree.grid(row=crow, column=0,columnspan=2, padx=10,pady=1,sticky=tk.NW)

        self.tree.heading('#0', text='') 
        self.tree.heading('A', text='Parameter')          
        self.tree.heading('B', text='Value')
        
        self.tree.column('#0',minwidth=0,width=1)
        self.tree.column('A',minwidth=0,width=170, stretch=tk.YES)        
        self.tree.column('B',minwidth=0,width=85)              


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

    def OnKeyPress(self,event):
        self.Lb2.delete(0, tk.END)

        n=1+int(self.Lb1.curselection()[0]) 

        s1='Enter Displacement (peak-to-peak)'
        s2='Enter Displacement (zero-to-peak)'
        s3='Enter Velocity'
        s4='Enter Acceleration'


        if(n==1 or n==2):
            str1='inch'
            str2='mm'

        if(n==1):
            self.amp_text.set(s1)

        if(n==2):
            self.amp_text.set(s2)

        if(n==3):
            self.amp_text.set(s3)
            str1='inch/sec'
            str2='m/sec'

        if(n==4):
            self.amp_text.set(s4)
            str1='G'
            str2='m/sec^2'


        self.Lb2.insert(1, str1)
        self.Lb2.insert(2, str2)
        self.Lb2.select_set(0) 
          
###############################################################################        

    def calculation(self):
        
        x=self.tree.get_children()
        
        for i in range (0,len(x)):
            self.tree.delete(x[i])
                
#        map(self.tree.delete, self.tree.get_children())

        n=1+int(self.Lb1.curselection()[0]) 
        m=1+int(self.Lb2.curselection()[0])         

        freq= float(self.fnr.get())   
        amp= float(self.ampr.get())        
        
        omega=2*np.pi*freq
        om2=omega**2     
        
        mm_per_in=25.4
        in_per_mm=1/mm_per_in

        m_per_in=mm_per_in/1000
        in_per_m=1/m_per_in

        dzp_in=0
        dzp_mm=0
        dpp_in=0
        dpp_mm=0        

        if(n==1):
#
           if(m==1):  # inch input
               dpp_in=amp
               dpp_mm=amp*mm_per_in       
           else:
               dpp_mm=amp
               dpp_in=amp*in_per_mm     
   
#
           dzp_in=dpp_in/2
           dzp_mm=dpp_mm/2

        if(n==2):

           if(m==1):  # inch input
               dzp_in=amp
               dzp_mm=amp*mm_per_in       
           else:
               dzp_mm=amp
               dzp_in=amp*in_per_mm     
   
        if(n==3):

           if(m==1):  # in/sec input
               v_ips=amp
               v_mps=amp*m_per_in  

           else:  # m/sec
              v_mps=amp 
              v_ips=amp*in_per_m

           dzp_in=v_ips/omega
           dzp_mm=(v_mps/omega)*1000
           
        if(n==4):

           if(m==1):  # G input
             a_g=amp
             a_mps2=amp*9.81 

           else:  # m/sec
             a_mps2=amp 
             a_g=amp/9.81
   
           dzp_in=(a_g/om2)*386
           dzp_mm=(a_mps2/om2)*1000

        if(n!=1):
           dpp_in=dzp_in*2
           dpp_mm=dzp_mm*2

        if(n!=3):
           v_ips=omega*dzp_in
           v_mps=omega*(dzp_mm)/1000

        if(n!=4):
           a_g=om2*dzp_in/386
           a_mps2=om2*dzp_mm/1000

        print ("\n")

        s0='Frequency'
        s1="%8.4g Hz" %freq
        self.tree.insert('', 'end', values=(s0,s1))
        print (s0,s1)

        s0='Displacement (peak-to-peak)'
        if(m==1):
            s1="%8.4g in" %dpp_in
        else:
            s1="%8.4g mm" %dpp_mm
        self.tree.insert('', 'end', values=(s0,s1))
        print (s0,s1)
        
        s0='Displacement (zero-to-peak)'
        if(m==1):
            s1="%8.4g in" %dzp_in
        else:
            s1="%8.4g mm" %dzp_mm
        self.tree.insert('', 'end', values=(s0,s1))
        print (s0,s1)
        
        s0='Velocity (zero-to-peak)'
        if(m==1):
            s1="%8.4g in/sec" %v_ips
        else:
            s1="%8.4g m/sec" %v_mps
        self.tree.insert('', 'end', values=(s0,s1))
        print (s0,s1)
            
        s0='Accel (zero-to-peak)'
        if(n==3 and m==2):
            s1="%8.4g m/sec^2" %a_mps2
        else:
            s1="%8.4g G" %a_g            
        self.tree.insert('', 'end', values=(s0,s1))    
        print (s0,s1)

        self.iflag=1        
Esempio n. 19
0
	def __init__(self, parent, controller):
		Frame.__init__(self, parent)
		
		global e0, e1, e2, e3, e4, e5, e6, e7, e8, CbxVlr, observaciones, scroll, tree, pdfB, add
		global cc, arrend, inmueble, codigo, tel, valor
		global Cbx, meses, mes1, mes2, tiempo, fechapago, anio, mes
		global prop, nit, tp, subtotal, iva, total
				
		#VARIABLES
		tiempo = datetime.date.today()
		anio = time.strftime("%Y")
		mes = time.strftime("%B")
		fechapago = StringVar()
		
		cc = StringVar()
		arrend = StringVar()
		
		inmueble = StringVar()
		codigo = StringVar()
		tel = StringVar()
		valor = DoubleVar()
		
		prop = StringVar()
		nit = StringVar()
		tp = StringVar()
		
		subtotal = DoubleVar()
		iva = DoubleVar()
		total = DoubleVar()
		
		mes1 = StringVar()
		mes2 = StringVar()
		meses = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"]

		#WIDGETS
		
		#=========================== HEADER ============================
		
		self.titleL = Label(self, text="FACTURA INQUILINO", font="bold")
		self.titleL.pack(pady=20, side=TOP)
		
		#========================= WRAPPER 1 ===========================
		
		wrapper = Frame (self)
		wrapper.pack(fill='both')

		#======================= DATOS GENERALES =======================
		
		self.lf = LabelFrame(wrapper, text="Datos generales")
		self.lf.pack(side=LEFT)#-------------------------------

		self.f0 = Frame(self.lf)
		self.f0.pack(pady=5,fill=X)#---------------------------

		self.ccnitL = Label(self.f0, text='CC/Nit:')
		self.ccnitL.pack(side=LEFT)
		e0 = Entry(self.f0, textvariable=cc, width=30)
		e0.pack(side=LEFT)
		
		self.b1 = Button (self.f0, text='Buscar', command=buscar)
		self.b1.pack(side=LEFT)

		self.f1 = Frame(self.lf)
		self.f1.pack(pady=5,fill=X)#---------------------------
		
		self.nombreL = Label(self.f1, text='Nombre:')
		self.nombreL.pack(side=LEFT)
		e1 = Entry(self.f1, textvariable=arrend, width=50, state=DISABLED)
		e1.pack(side=LEFT,fill=X)

		self.f2 = Frame(self.lf)
		self.f2.pack(pady=5,fill=X)#---------------------------
		
		self.inmuebleL = Label(self.f2, text='Inmueble:')
		self.inmuebleL.pack(side=LEFT)
		e2 = Entry(self.f2, textvariable=inmueble, state=DISABLED, width=48)
		e2.pack(side=LEFT,fill=X)
		
		self.f3 = Frame(self.lf)
		self.f3.pack(pady=5,fill=X)#---------------------------
		
		self.inmuebleL = Label(self.f3, text='Código: ')
		self.inmuebleL.pack(side=LEFT)
		e3 = Entry(self.f3, textvariable=codigo, state=DISABLED, width=5)
		e3.pack(side=LEFT,fill=X)
		
		self.tel = Label(self.f3, text='Teléfono: ')
		self.tel.pack(side=LEFT)
		e4 = Entry(self.f3, textvariable=tel, state=DISABLED, width=15)
		e4.pack(side=LEFT,fill=X)
		
		self.precio = Label(self.f3, text='Arriendo $: ')
		self.precio.pack(side=LEFT)
		e5 = Entry(self.f3, textvariable=valor, state=DISABLED, width=15)
		e5.pack(side=LEFT,fill=X)
		
		#======================= DATOS PROPIETARIO =======================
		
		wrap = Frame(wrapper)
		wrap.pack(side=RIGHT)
		
		lf = LabelFrame(wrap, text="Propietario")
		lf.pack()#-------------------------
		#lf.pack_forget()#-------------------------
		
		f0 = Frame(lf)
		f0.pack(pady=5,fill=X)#---------------------------
		
		nombreL = Label(f0, text='Nombre: ')
		nombreL.pack(side=LEFT)
		e6 = Entry(f0, textvariable=prop, width=48, state=DISABLED)
		e6.pack(side=LEFT,fill=X)
		
		f1 = Frame(lf)
		f1.pack(pady=5,fill=X)#---------------------------

		ccnitL = Label(f1, text='CC/Nit: ')
		ccnitL.pack(side=LEFT)
		e7 = Entry(f1, textvariable=nit, state=DISABLED, width=48)
		e7.pack(side=LEFT)
		
		f2 = Frame(wrap)
		f2.pack(pady=5,fill=X)#---------------------------
		
		self.lb = Label(f2, text=None)
		self.lb.pack(side=LEFT)
		
		f3 = Frame(wrap)
		f3.pack(pady=5,fill=X)#---------------------------
		
		"""
		self.inmuebleL = Label(f2, text='Tipo Persona: ')
		self.inmuebleL.pack(side=LEFT)
		e8 = Entry(f2, textvariable=tp, state=DISABLED, width=40)
		e8.pack(side=LEFT,fill=X)
		"""
		
		l = Label(f3, text='SubTotal ')
		l.pack(side=LEFT)
		e8 = Entry(f3, textvariable=subtotal, state=DISABLED, width=12)
		e8.pack(side=LEFT,fill=X)
		
		l = Label(f3, text='IVA ')
		l.pack(side=LEFT)
		e9 = Entry(f3, textvariable=iva, state=DISABLED, width=12)
		e9.pack(side=LEFT,fill=X)
		
		l = Label(f3, text='Total ')
		l.pack(side=LEFT)
		e10 = Entry(f3, textvariable=total, state=DISABLED, width=12)
		e10.pack(side=LEFT,fill=X)
		
		f4 = Frame(wrap)
		f4.pack(pady=5,fill=X)#---------------------------
		
		#========================= FACTURACIÓN =========================
		
		self.lf1 = LabelFrame(self, text="Periodo a facturar")
		self.lf1.pack(anchor=W,pady=5,fill=X)#-------------------------

		self.f2 = Frame(self.lf1)
		self.f2.pack(pady=5,fill=X)#---------------------------

		self.mesiniL = Label(self.f2, text='Mes inicial:')
		self.mesiniL.pack(padx=5,side=LEFT)

		CbxVlr = Combobox(self.f2, textvariable=mes1, values=meses, width=10, state=DISABLED)
		CbxVlr.set(mes)
		CbxVlr.pack(side=LEFT)

		self.emptyL = Label(self.f2)###VACIO###
		self.emptyL.pack(padx=5, side=LEFT)
	
		self.yeariniL = Label(self.f2, text='Año:')
		self.yeariniL.pack(side=LEFT)
		self.yeariniE = Entry(self.f2, textvariable=fechapago, width=8, state=DISABLED)
		fechapago.set(anio)
		self.yeariniE.pack(side=LEFT)

		self.mesfinL = Label(self.f2, text='Mes final:')
		self.mesfinL.pack(padx=5,side=LEFT)

		self.mesfinCbx = Combobox(self.f2, textvariable=mes2, values=meses, width=10)
		self.mesfinCbx.set(mes)
		self.mesfinCbx.pack(side=LEFT)

		self.emptyL = Label(self.f2)###VACIO###
		self.emptyL.pack(padx=5, side=LEFT)

		self.yearfinL = Label(self.f2, text='Año:')
		self.yearfinL.pack(side=LEFT)
		self.yearfinE = Entry(self.f2, textvariable=fechapago, width=8)
		fechapago.set(anio)
		self.yearfinE.pack(side=LEFT)

		self.emptyL = Label(self.f2)###VACIO###
		self.emptyL.pack(padx=5, side=LEFT)
		
		pdfB = Button(self.f2, text="Facturar", command=agregar, state=DISABLED)
		pdfB.pack(side=LEFT)

		#========================== TREEVIEW ===========================
		
		self.f3 = Frame(self)
		self.f3.pack(pady=5,fill=X)#------------------------------------
		
		tree = Treeview(self.f3, height=4, show="headings", columns=('col1','col2'))
		tree.pack(side=LEFT, fill=X, expand=1)
		
		tree.column('col1', width=250, anchor='center')
		tree.column('col2', width=5, anchor='center')
		
		tree.heading('col1', text='Descripción')
		tree.heading('col2', text='Valor')
		
		scroll = Scrollbar(self.f3,orient=VERTICAL,command=tree.yview)
		tree.configure(yscrollcommand=scroll.set)
		tree.bind("<Delete>", borrar)
		
		#======================== OBSERVACIONES ========================

		self.f4 = Frame(self)
		self.f4.pack(pady=5,fill=X)#--------------------

		self.notesL = Label(self.f4, text='Observaciones:')
		self.notesL.pack(side=LEFT)

		self.f5 = Frame(self)
		self.f5.pack(pady=5,fill=X)#-------------------

		observaciones = Text(self.f5, height=5)
		observaciones.pack(fill=X, side=LEFT, expand=1)
		
		#=========================== BOTONES ===========================
		
		footer = Frame(self)
		footer.pack()#-------------------------------
		
		clean = Button(footer, text='Cancelar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=cancelar)
		clean.pack(side=RIGHT)
		
		add = Button(footer, text='Grabar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=grabar, state=DISABLED)
		add.pack(side=RIGHT)
Esempio n. 20
0
        def __init__(self, parent, controller):
			Frame.__init__(self, parent)
			
			#INSTANCIAS
			global cc, nombre, pago, ref, cod, desc, valor, resultado, total, tiempo, mes, anio, fechapago
			#INSTANCIAS DE LOS WIDGETS
			global e1, e2, e3, e4, e5, tree, l8, lb
			
			cc = IntVar()
			nombre = StringVar()
			pago = StringVar()
			ref = StringVar()
			cod = StringVar()
			desc = StringVar()
			valor = DoubleVar()
			
			tiempo = datetime.date.today()
			anio = time.strftime("%Y")
			mes = time.strftime("%B")
			fechapago = StringVar()
			
			total = 0.0
			resultado = DoubleVar()
			
			tbancos = ['Bancolombia', "Banco Bogotá", "Banco Agrario", "Banco Occidente"]
			
			lupa = PhotoImage(file='img/lupa.png')
			
			tbanktype = ['Corriente','Ahorro']
			fpago = ['Efectivo','Transferencia']
			
			#BUSQUEDA = ["Nombre","CC/Nit"]
			busqueda = StringVar()
			busqueda.trace("w", lambda name, index, mode: buscar())
			dato = StringVar()
			
			#WIDGETS
			
			#========================= HEADER ==============================
			
			self.titleL = Label(self, text="GASTOS", font="bold")
			self.titleL.pack(pady=20, side=TOP)
			
			#========================== WRAPPER ============================
			
			self.wrapper = Frame (self)
			self.wrapper.pack(side=LEFT, fill=Y)
			#Esto centro el wrapper
			#self.wrapper.pack(side=LEFT, fill=BOTH, expand=True)
			
			#======================== BENEFICIARIO =======================
			
			self.lf1 = LabelFrame(self.wrapper, text="Beneficiario")
			self.lf1.pack(fill=X, ipady=5)
			
			self.f0 = Frame(self.lf1)
			self.f0.pack(pady=5, fill=X)#-----------------------------------
			
			l1 = Label(self.f0, text='CC/Nit:')
			l1.pack(side=LEFT)
			
			e1 = Entry(self.f0, textvariable=cc)
			e1.pack(side=LEFT)
			e1.bind('<Return>', buscarB)
			
			b0 = Button(self.f0, text='Buscar:', image=lupa, command=topBeneficiarios)
			b0.pack(side=LEFT)
			
			l2 = Label(self.f0, text='Nombre:')
			l2.pack(side=LEFT)
			e2 = Entry(self.f0, textvariable=nombre)
			e2.pack(side=LEFT, fill=X, expand=1)
			
			self.f1 = Frame(self.lf1)
			self.f1.pack(pady=5, fill=X)#-----------------------------------
			
			l3 = Label(self.f1, text='Forma de Pago:')
			l3.pack(side=LEFT)
			Cbx = Combobox(self.f1, textvariable=pago, values=fpago, width=15)
			Cbx.set('Efectivo')
			Cbx.pack(side=LEFT)
			
			l4 = Label(self.f1, text='Ref. Bancaria:')
			l4.pack(side=LEFT)
			e3 = Entry(self.f1, textvariable=ref)
			e3.pack(side=LEFT, fill=X, expand=1)
			
			b1 = Button(self.f1, text='Buscar:', image=lupa)
			b1.image=lupa
			b1.pack(side=LEFT)
			
			#======================== CONCEPTO ========================
			
			self.lf2 = LabelFrame(self.wrapper, text="Concepto")
			self.lf2.pack(fill=X, ipady=5)
			
			self.f2 = Frame(self.lf2)
			self.f2.pack(pady=5, fill=X)#-------------------------------
			
			l5 = Label(self.f2, text='Código:')
			l5.pack(side=LEFT)
			e4 = Entry(self.f2, textvariable=cod)
			e4.pack(side=LEFT)
			e4.bind('<Return>', buscarC)
			
			b2 = Button(self.f2, text='Buscar:', image=lupa, command=topCtasContables)
			b2.pack(side=LEFT)
			
			self.f3 = Frame(self.lf2)
			self.f3.pack(pady=5, fill=X)#-------------------------------
			
			l6 = Label(self.f3, text='Descripción:')
			l6.pack(side=LEFT)
			e5 = Entry(self.f3, textvariable=desc, state=DISABLED)
			e5.pack(side=LEFT, fill=X, expand=1)
			
			l7 = Label(self.f3, text='Valor:')
			l7.pack(side=LEFT)
			e6 = Entry(self.f3, width=15, textvariable=valor)
			e6.pack(side=LEFT)
			
			b3 = Button(self.f3, text='Agregar:', command=agregar)
			b3.pack(side=LEFT)
			
			#-------------------------- TREEVIEW ---------------------------
			
			self.f4 = Frame(self.wrapper)
			self.f4.pack(pady=5,fill=X)
			
			tree = Treeview(self.f4, height=4, show="headings", columns=('col1','col2','col3'))
			tree.pack(side=LEFT, fill=X, expand=1)
			tree.column('col1', width=20, anchor='center')
			tree.column('col2', width=200, anchor='center')
			tree.column('col3', width=10, anchor='center')
			
			tree.heading('col1', text='Código')
			tree.heading('col2', text='Concepto')
			tree.heading('col3', text='Valor')
			
			scroll = Scrollbar(self.f4,orient=VERTICAL,command=tree.yview)
			tree.configure(yscrollcommand=scroll.set)
			tree.bind("<Delete>", borrar)
			
			#-------------------------- RESULTADOS ---------------------------
			
			self.f5 = Frame(self.wrapper)
			self.f5.pack(pady=5,fill=X)#-------------------
			
			l8 = Label(self.f5, textvariable=resultado, fg="red", bg="white", anchor='e', font="bold, 22", relief= SUNKEN)
			l8.pack(fill=X, side=RIGHT, expand=1)
			
			#-------------------------- FOOTER ---------------------------
			
			self.fBtn = Frame(self.wrapper)
			self.fBtn.pack()#-------------------------------
			
			clean = Button(self.fBtn, text='Cancelar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=limpiar)
			clean.pack(side=RIGHT)
			
			add = Button(self.fBtn, text='Grabar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=grabar)
			add.pack(side=RIGHT)
			
			#========================= ASIDE ===========================
			
			self.aside = Frame(self)
			self.aside.pack(side=TOP, fill=BOTH)
			
			self.wrap1 = Frame(self.aside)
			self.wrap1.pack()
			
			self.viewer = Label(self.wrap1, text="LISTA DE GASTOS")
			self.viewer.pack()
			
			scroll = Scrollbar(self.wrap1, orient=VERTICAL)
			scroll.pack(side=RIGHT, fill=Y)
			
			lb = Listbox(self.wrap1, yscrollcommand=scroll.set, height=20, width=30)
			scroll.config (command=lb.yview)
			lb.pack(fill=BOTH)
			
			self.wrap2 = Frame(self.aside)
			self.wrap2.pack()
			
			load = Button(self.wrap2, text='Cargar lista', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=cargar_lista)
			load.pack(fill=X)
			
			delete = Button(self.wrap2, text='Borrar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=None)
			delete.pack(fill=X)
			
			edit = Button(self.wrap2, text='Modificar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=None)
			edit.pack(fill=X)
			
			buscador = Label(self.wrap2, text="Buscar por Número:")
			buscador.pack()
			E = Entry(self.wrap2, textvariable=busqueda, width=24)
			E.pack()
			E.bind("<KeyRelease>", caps)
Esempio n. 21
0
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)

        global cbox, inmueble, loc, nit, nombre, carpeta, grupo, porcentaje, tree, busqueda
        global e1, e2, nitE

        lupa = PhotoImage(file='img/lupa.png')

        inmueble = IntVar()
        loc = StringVar()
        nit = StringVar()
        nombre = StringVar()
        carpeta = IntVar()
        grupo = IntVar()
        porcentaje = DoubleVar()

        lupa = PhotoImage(file='img/lupa.png')

        #BUSQUEDA = ["Nombre","CC/Nit"]
        busqueda = StringVar()
        #busqueda.trace("w", lambda name, index, mode: buscar())
        dato = StringVar()

        #WIDGETS

        #=========================== HEADER ============================

        self.titleL = Label(self,
                            text="RELACIÓN INMUEBLES/PROPIETARIO",
                            font="bold")
        self.titleL.pack(pady=20, side=TOP)

        #=========================== WRAPPER ===========================

        self.wrapper = Frame(self)
        self.wrapper.pack(side=TOP, fill=Y)

        self.f = Frame(self.wrapper)
        self.f.pack(pady=5, fill=X)  #-----------------------------------

        l1 = Label(self.f, text='Inmueble:')
        l1.pack(side=LEFT)

        e1 = Entry(self.f, textvariable=inmueble)
        e1.pack(side=LEFT)
        e1.bind('<Return>', buscarI)

        b1 = Button(self.f, text="Buscar", image=lupa, command=topInmueble)
        b1.image = lupa
        b1.pack(side=LEFT)

        self.f0 = Frame(self.wrapper)
        self.f0.pack(pady=5, fill=X)  #-----------------------------------

        l2 = Label(self.f0, text="Dirección: ")
        l2.pack(side=LEFT)

        e2 = Entry(self.f0, textvariable=loc, width=90, state=DISABLED)
        e2.pack(side=LEFT, fill=X, expand=1)

        self.f1 = Frame(self.wrapper)
        self.f1.pack(pady=5, fill=X)  #-----------------------------------

        self.nit = Label(self.f1, text="CC/Nit")
        self.nit.pack(side=LEFT)

        nitE = Entry(self.f1, textvariable=nit)
        nitE.pack(side=LEFT)
        nitE.bind('<Return>', buscarP)

        self.add = Button(self.f1,
                          text="Buscar",
                          image=lupa,
                          command=topPropietario)
        self.add.pack(side=LEFT)

        self.f2 = Frame(self.wrapper)
        self.f2.pack(pady=5, fill=X)  #-----------------------------------

        self.nombre = Label(self.f2, text="Nombre: ")
        self.nombre.pack(side=LEFT)
        self.nombreE = Entry(self.f2,
                             textvariable=nombre,
                             width=90,
                             state=DISABLED)
        self.nombreE.pack(side=LEFT, fill=X, expand=1)

        self.f3 = Frame(self.wrapper)
        self.f3.pack(pady=5, fill=X)  #-----------------------------------

        self.carpeta = Label(self.f3, text="Carpeta: ")
        self.carpeta.pack(side=LEFT)
        self.carpetaE = Entry(self.f3, textvariable=carpeta, width=5)
        self.carpetaE.pack(side=LEFT)
        carpeta.set(1)

        self.grupo = Label(self.f3, text="Grupo: ")
        self.grupo.pack(side=LEFT)
        self.grupoE = Entry(self.f3, textvariable=grupo, width=5)
        self.grupoE.pack(side=LEFT)
        grupo.set(1)

        self.porcentaje = Label(self.f3, text="Porcentaje: ")
        self.porcentaje.pack(side=LEFT)
        self.porcentajE = Entry(self.f3, textvariable=porcentaje, width=5)
        self.porcentajE.pack(side=LEFT)

        self.chkb0 = Checkbutton(self.f3, text="Representante")
        self.chkb0.pack(side=LEFT)

        self.update = Button(self.f3,
                             text="Cargar",
                             bg='navy',
                             foreground='white',
                             activebackground='red3',
                             activeforeground='white',
                             command=cargar)
        self.update.pack(side=RIGHT)

        self.add = Button(self.f3,
                          text="Agregar",
                          bg='navy',
                          foreground='white',
                          activebackground='red3',
                          activeforeground='white',
                          command=agregar)
        self.add.pack(side=RIGHT)

        self.f4 = Frame(self.wrapper)
        self.f4.pack(pady=5, fill=X)  #-----------------------------------

        tree = Treeview(self.f4,
                        show="headings",
                        columns=('col1', 'col2', 'col3', 'col4', 'col5',
                                 'col6'))
        tree.pack(side=LEFT, fill=X, expand=1)

        tree.column('col1', width=5, anchor='center')
        tree.column('col2', width=150, anchor='center')
        tree.column('col3', width=5, anchor='center')
        tree.column('col4', width=150, anchor='center')
        tree.column('col5', width=1, anchor='center')
        tree.column('col6', width=1, anchor='center')

        tree.heading('col1', text='Cod')
        tree.heading('col2', text='Imnueble')
        tree.heading('col3', text='CC/nit')
        tree.heading('col4', text='Dueño')
        tree.heading('col5', text='Grupo')
        tree.heading('col6', text='%')

        self.scroll = Scrollbar(self.f4, orient=VERTICAL, command=tree.yview)
        tree.configure(yscrollcommand=self.scroll.set)
        """
        #EJEMPLO 2 SÍ FUNCIONA (0)
                self.tree = Treeview(self.f4, height=5, columns=2)
                self.tree.pack()
                self.tree.heading('#0', text='CC/Nit', anchor=W)
                self.tree.heading(2, text='Nombre', anchor=W)"""

        self.f5 = Frame(self.wrapper)
        self.f5.pack(pady=5, fill=X)  #-----------------------------------

        self.delete = Button(self.f5,
                             text="Eliminar",
                             bg='navy',
                             foreground='white',
                             activebackground='red3',
                             activeforeground='white',
                             command=borrar)
        self.delete.pack(side=RIGHT)

        e3 = Entry(self.f5, textvariable=busqueda)
        e3.pack(side=LEFT)
        #e3.bind("<KeyRelease>", caps)

        b3 = Button(self.f5, text='BUSCAR', image=lupa, command=buscar)
        b3.image = lupa
        b3.pack(side=LEFT)
Esempio n. 22
0
class SDCard: 
	def __init__(self, root, prtr, settings, log):
		self.app = root
		self.printer = prtr
		self.settings = settings
		self.log = log
		self.top = None

	def isActive(self):
		return self.top != None

	def start(self):
		self.app.sdchecking = True
		self.printer.send_now("M21")
		
	def sdCheckComplete(self, ready):
		if not ready:
			self.log.logMsg("Error initializing SD card")
		else:
			self.app.sdlisting = True
			self.printer.send_now("M20")
			
	def refresh(self):
		self.top.destroy()
		self.app.sdlisting = True
		self.printer.send_now("M20")
			
	def sdListComplete(self, sdlist):
		top = self.top = Toplevel(self.app) 
		top.title("SD Card Control")
		top.protocol('WM_DELETE_WINDOW', self.delTop)
		f = Frame(top, height=150, width=150)
		f.grid(row=1, column=1);
		self.tree = Treeview(f, height=12, selectmode='browse') 
		self.tree.column("#0", minwidth=100)
		self.tree.bind("<<TreeviewSelect>>", self.treeSelect)
		self.sb = Scrollbar(f)
		self.sb.config(command=self.tree.yview)
		self.tree.config(yscrollcommand=self.sb.set)
			
		self.sb.pack(side=RIGHT, fill=Y)
		self.tree.pack(side=LEFT, fill=BOTH, expand=1)

		SDroot = SDDir('')
		for item in sdlist:
			if item.startswith('/'):
				cd = SDroot
				l = item[1:].split('/')
				for d in l[:-1]:
					ncd = cd.getDir(d)
					if ncd == None:
						ncd = cd.addDir(d)
			
					cd = ncd
				cd.addFile(l[-1], fqn=item)
					
			else:
				SDroot.addFile(item)
				
		SDroot.sortAll()
		
		self.fileMap = {}
		self.startFile = None
		self.loadDir(SDroot, '')
		bf = Frame(top, width=50)
		bf.grid(column=3, row=1)
		
		blf = LabelFrame(bf, text="Print from SD Card", width=48, height=40)
		
		self.bPrint = Button(blf, text='Print', command=self.doPrint, width = 6) 
		self.bPrint.pack()
		blf.pack(fill='x')
		
		blf = LabelFrame(bf, text="Delete from SD Card", width=48, height=40)
		
		self.bDelete = Button(blf, text="Delete", command=self.doDelete, width=6)
		self.bDelete.pack()
		blf.pack(fill='x')
		
		blf = LabelFrame(bf, text="Upload to SD Card", width=48, height=180)

		self.upDir = Label(blf, text="Dir:", justify=LEFT)
		self.upDir.pack()

		ef = Frame(blf)

		l = Label(ef, text="File:", justify=LEFT)
		l.pack(side=LEFT)

		self.entry = Entry(ef, width=12)
		self.entry.pack(side=LEFT)
		fn = 'untitled.g'
		if self.app.GCodeFile:
			fn = os.path.basename(self.app.GCodeFile)
			if len(fn) > 8:
				fn = fn[0:8]
			fn += ".g"
		self.entry.delete(0, END)
		self.entry.insert(0, fn)
		ef.pack()
		
		self.bUpload = Button(blf, text="Upload", command=self.doUpload, width=6)
		self.bUpload.pack()

		blf.pack(fill='x')
		
		if self.app.printing or self.app.sdprinting:
			self.bPrint.config(state=DISABLED)
			self.bUpload.config(state=DISABLED)
			
		if not self.app.GCodeFile:
			self.bUpload.config(state=DISABLED)
			
		blf = Frame(bf)
		self.bExit = Button(blf, text='Exit', command=self.doExit, width=6) 
		self.bExit.pack()
		blf.pack()

		if self.startFile:
			self.tree.selection_set(self.startFile)
			
		self.top.geometry("360x300+100+100")

	def delTop(self):
		self.top.destroy()
		self.top = None
	
	def treeSelect(self, *arg):
		s = self.tree.selection()[0]
		
		try:
			d = s.split(':')[0]
		except:
			d = ""
			
		if len(d) == 0:
			d = '(root)'
			
		self.upDir.config(text="Dir: " + d)
		
		if self.app.printing or self.app.sdprinting or not self.app.GCodeFile:
			self.bUpload.config(state=DISABLED)
		else:
			self.bUpload.config(state=NORMAL)
			
		if ':' in s: # a file is chosen
			if self.app.printing or self.app.sdprinting:
				self.bPrint.config(state=DISABLED)
			else:
				self.bPrint.config(state=NORMAL)
			self.bDelete.config(state=NORMAL)
			
		else: # a directory is chosen
			self.bPrint.config(state=DISABLED)
			self.bDelete.config(state=DISABLED)


	def loadDir(self, d, did):
		d.resetDir()
		nd = d.nextDir()
		while (nd):
			myid = did + '/' + nd.dirName()
			self.tree.insert(did, 'end', myid, text=nd.dirName())
			self.loadDir(nd, myid)
			nd = d.nextDir()
			
		d.resetFile()
		f = d.nextFile()
		while (f):
			myid = did + ':' + f[0]
			self.fileMap[myid] = f[1]
			self.tree.insert(did, 'end', myid, text=f[0])
			if self.startFile == None:
				self.startFile = myid
			f = d.nextFile()		
		
	def doExit(self): 
		self.top.destroy()
		self.top = None

	def doPrint(self): 
		s = self.tree.selection()[0]
		if s in self.fileMap:
			fn = self.fileMap[s].lower()
			self.log.logMsg("Starting print of SD file %s" % fn)
			self.printer.send_now("M23 %s" % fn)  # select the file
			self.printer.send_now("M24") # start the print
			self.app.sdprinting = True
			self.app.setToolbarSDPrint()
			self.top.destroy()
			self.top = None
		
	def doDelete(self):
		s = self.tree.selection()[0]
		if s in self.fileMap:
			fn = self.fileMap[s].lower()
			self.log.logMsg("Deleting file %s" % fn)
			self.printer.send_now("M30 %s" % fn)
			self.refresh()
		
	def doUpload(self):
		bn = self.entry.get()

		try:		
			d = self.tree.selection()[0].split(':')[0]
		except:
			d = ""
			
		if len(d) != 0:
			d += '/'
		
		fn = (d + bn).lower()
		self.log.logMsg("Starting upload to SD file %s" % fn)
		self.printer.send_now("M28 %s" % fn)  # select the file
		self.app.startUpload()
		self.top.destroy()
		self.top = None
Esempio n. 23
0
    def _add_frames(self):
        # Adding Answer Backup Frame
        f1 = Frame(self)
        f1.grid(column=0, row=0, sticky="NWES")
        for i in range(4):
            f1.grid_rowconfigure(i, weight=0, pad=5)
        f1.grid_rowconfigure(4, weight=1, pad=5)
        for i in range(4):
            f1.grid_columnconfigure(i, weight=1, pad=5)

        Label(f1, anchor="e", text="Answers Count : ").grid(column=0, row=0, sticky="EWNS")
        self.answer_count = StringVar(value=len(self.crawler.answer_list))
        Label(f1, anchor="w", textvariable=self.answer_count).grid(column=1, row=0, sticky="EWNS")
        Label(f1, anchor="e", text="User Name : ").grid(column=2, row=0, sticky="EWNS")
        self.user = StringVar(value="Unknown")
        Label(f1, anchor="w", textvariable=self.user).grid(column=3, row=0, sticky="EWNS")

        tf_col = "#e6e6e6"
        tf = Tkinter.Frame(f1, relief=GROOVE, borderwidth="2p")
        tf.grid(row=1, columnspan=2, column=0, sticky="EWNS")
        Label(tf, text="Quora User Options", bg=tf_col, anchor="c").grid(column=0, row=0, columnspan=2, sticky="EWNS")
        Button(tf, text="Login", command=lambda: self.thread("login"), highlightbackground=tf_col).grid(
            column=0, row=1, sticky="EWNS"
        )
        Button(tf, text="Logout", command=lambda: self.thread("logout"), highlightbackground=tf_col).grid(
            column=1, row=1, sticky="EWNS"
        )
        tf.grid_rowconfigure(0, weight=1, pad=5)
        tf.grid_rowconfigure(1, weight=1, pad=5)
        tf.grid_columnconfigure(0, weight=1, pad=5)
        tf.grid_columnconfigure(1, weight=1, pad=5)

        tf = Frame(f1, relief=GROOVE, borderwidth="2p")
        tf.grid(row=1, columnspan=2, column=2, sticky="EWNS")
        Label(tf, text="Answer List Option", bg=tf_col, anchor="c").grid(column=0, columnspan=2, row=0, sticky="EWNS")
        Button(tf, text="Reset", command=lambda: self.thread("reset"), highlightbackground=tf_col).grid(
            column=0, row=1, sticky="EWNS"
        )
        Button(tf, text="Update", command=lambda: self.thread("update"), highlightbackground=tf_col).grid(
            column=1, row=1, sticky="EWNS"
        )
        tf.grid_rowconfigure(0, weight=1, pad=5)
        tf.grid_rowconfigure(1, weight=1, pad=5)
        tf.grid_columnconfigure(0, weight=1, pad=5)
        tf.grid_columnconfigure(1, weight=1, pad=5)

        # Add Progress Bar
        self.backup_progress = Progressbar(f1, orient="horizontal", length=100, mode="determinate")
        self.backup_progress.grid(row=2, columnspan=4, column=0, sticky="EWNS")

        # Adding Status Pane
        self.backup_status = StringVar(value="Ready")
        Label(f1, textvariable=self.backup_status, anchor="w").grid(row=3, column=0, columnspan=4, sticky="EWNS")

        # Adding The list of all answers
        tree = Treeview(f1, columns=("sno", "date", "question"))
        tree.heading("sno", text="S. No")
        tree.heading("date", text="Date")
        tree.heading("question", text="Question")

        tree.column("#0", width=0, stretch=False)
        tree.column("sno", width=40, stretch=False, anchor="center")
        tree.column("date", width=120, stretch=False, anchor="center")
        tree.column("question", stretch=True, anchor="w")
        tree.grid(column=0, columnspan=4, row=4, sticky="EWNS")
        tree.bind("<Double-1>", self.tree_item_click)
        self.answer_tree = tree
        self.populate_tree()

        f2 = Frame(self)
        self.add(f1, text="Answer Backup", underline=7)
        self.add(f2, text="Analytics")
class SudokuUI(Frame):
    """
    Sudoku grid UI class.
    Adapted from: http://newcoder.io/gui/part-4/
    """
    def __init__(self, parent, board):
        self.game = board
        Frame.__init__(self, parent)
        self.parent = parent

        self.row, self.col = -1, -1
        self.new_entry = None
        self.previous_guess = None

        self.game_state = 0

        self.scores = []

        self.__initUI()

    def __initUI(self):
        """
        Initialize sudoku playing field grid and bind clicking and entry handlers."""

        self.parent.title("Sudoku")
        self.pack(fill=BOTH, expand=1)
        self.canvas = Canvas(self, width=WIDTH, height=HEIGHT)
        self.canvas.grid(row=1, column=0)

        self.__draw_grid()
        self.__draw_puzzle()
        self.__draw_scores()

        self.canvas.bind("<Button-1>", self.__cell_clicked)
        self.canvas.bind("<Key>", self.__key_pressed)

    def __draw_grid(self):
        """
        Draw Sudoku 3x3 x 3x3 grid."""

        for i in xrange(10):
            color = "blue" if i % 3 == 0 else "gray"

            x0 = MARGIN + i * SIDE
            y0 = MARGIN
            x1 = MARGIN + i * SIDE
            y1 = HEIGHT - MARGIN
            self.canvas.create_line(x0, y0, x1, y1, fill=color)

            x0 = MARGIN
            y0 = MARGIN + i * SIDE
            x1 = WIDTH - MARGIN
            y1 = MARGIN + i * SIDE
            self.canvas.create_line(x0, y0, x1, y1, fill=color)

    def __draw_puzzle(self):
        """
        Draw Sudoku solution numbers."""

        self.canvas.delete("numbers")
        for i in xrange(9):
            for j in xrange(9):
                answer = self.game.board[i][j]
                if answer != 0:
                    x = MARGIN + j * SIDE + SIDE / 2
                    y = MARGIN + i * SIDE + SIDE / 2
                    self.canvas.create_text(x, y, text=answer, tags="numbers")

    def __cell_clicked(self, event):
        """
        Handle a single cell click and highlight the clicked cell.
        :param event:
        """
        x, y = event.x, event.y
        if MARGIN < x < WIDTH - MARGIN and MARGIN < y < HEIGHT - MARGIN:
            self.canvas.focus_set()

            # get row and col numbers from x,y coordinates
            row, col = (y - MARGIN) / SIDE, (x - MARGIN) / SIDE

            # if cell was selected already - deselect it
            if (row, col) == (self.row, self.col):
                self.row, self.col = -1, -1
            elif self.game.board[row][col] == 0:
                self.row, self.col = row, col

        self.__draw_cursor()

    def __draw_cursor(self):
        """
        Draw the red outline for the selected square."""

        self.canvas.delete("cursor")
        if self.row >= 0 and self.col >= 0:
            x0 = MARGIN + self.col * SIDE + 1
            y0 = MARGIN + self.row * SIDE + 1
            x1 = MARGIN + (self.col + 1) * SIDE - 1
            y1 = MARGIN + (self.row + 1) * SIDE - 1
            self.canvas.create_rectangle(x0,
                                         y0,
                                         x1,
                                         y1,
                                         outline="green",
                                         tags="cursor")

    def __key_pressed(self, event):
        """
        Handle solution number entry."""

        if self.row >= 0 and self.col >= 0 and event.char in "123456789" and self.game_state == 1:
            self.new_entry = (self.row, self.col, int(event.char))
            self.col, self.row = -1, -1
            self.__draw_puzzle()
            self.__draw_cursor()

    def __draw_scores(self):
        self.score_list = Treeview(self, columns=('name', 'score'))
        self.score_list['show'] = 'headings'
        self.score_list.heading('name', text='Name')
        self.score_list.column('name', width=80, anchor=CENTER)
        self.score_list.heading('score', text='Score')
        self.score_list.column('score', width=80, anchor=CENTER)

        self.score_list.grid(row=1, column=1, padx=(0, 20))

    def __update_scores(self, scores):
        self.score_list.delete(*self.score_list.get_children())
        for entry in scores:
            self.score_list.insert('', 'end', values=(entry[0], entry[1]))

    def show_winner(self, score, user_id):
        if score[2] == user_id:
            winner_text = "YOU HAVE WON!"
        else:
            winner_text = "Player " + str(score[0]) + " has won!"
        tkMessageBox.showwarning("A WINNER IS FOUND", winner_text)

    def update_board(self, root, board, scores, new_game_state):
        """
        Update board during the gameplay. If all players are not connected, solution entry is not permitted.
        In case of a wrong answer the selected square is flashed red for a fraction of a second to notify
        the player about his life decisions.

        :param root:
        :param board:
        :param new_game_state:
        :return entered value:
        """
        return_val = None

        self.__update_scores(scores)

        # Check for game state, if it is "0", just return, else continue the game
        if self.game_state == 0:
            root.update()

            if new_game_state != 0:
                self.game_state = new_game_state
            return return_val

        # If previous guess was not correct flash it red
        if self.previous_guess is not None and board[self.previous_guess[0]][self.previous_guess[1]] != \
                self.previous_guess[2]:
            row, col, _ = self.previous_guess
            x0 = MARGIN + col * SIDE + 1
            y0 = MARGIN + row * SIDE + 1
            x1 = MARGIN + (col + 1) * SIDE - 1
            y1 = MARGIN + (row + 1) * SIDE - 1
            self.canvas.create_rectangle(x0,
                                         y0,
                                         x1,
                                         y1,
                                         fill="red",
                                         tags="fail")
        else:
            self.canvas.delete("fail")

        # Initiate return value to none, update the board and draw it
        self.game.update_board(board)
        self.__draw_puzzle()
        root.update()

        # If user has entered anything in between, write it into the return value and previous guess and return
        if self.new_entry is not None:
            return_val = self.new_entry
            self.previous_guess = self.new_entry
            self.new_entry = None
        else:
            self.previous_guess = None

        return return_val
Esempio n. 25
0
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)

        global docID, nombre, refbanco, tree, busqueda, info, delete
        global e3

        lupa = PhotoImage(file='img/lupa.png')

        docID = StringVar()
        nombre = StringVar()
        refbanco = StringVar()
        busqueda = StringVar()
        info = IntVar()

        #WIDGETS

        #=========================== HEADER ============================

        l0 = Label(self, text="BENEFICIARIOS", font="bold")
        l0.pack(pady=20, side=TOP)

        #=========================== WRAPPER ===========================

        wrapper = Frame(self)
        wrapper.pack(side=TOP, fill=Y)
        #wrapper.pack(side=LEFT, fill=Y) #UBICA EL FORM A LA IZQ

        f1 = Frame(wrapper)
        f1.pack(pady=5, fill=X)  #-----------------------------------

        l1 = Label(f1, text="CC/Nit: ")
        l1.pack(side=LEFT)
        e1 = Entry(f1, textvariable=docID, width=20)
        e1.pack(side=LEFT)
        e1.bind("<KeyRelease>", caps)
        e1.focus_set()

        f2 = Frame(wrapper)
        f2.pack(pady=5, fill=X)  #-----------------------------------

        l2 = Label(f2, text="Nombre: ")
        l2.pack(side=LEFT)
        e2 = Entry(f2, textvariable=nombre, width=60)
        e2.pack(side=LEFT, fill=X, expand=1)
        e2.bind("<KeyRelease>", caps)

        f3 = Frame(wrapper)
        f3.pack(pady=5, fill=X)  #-----------------------------------

        l3 = Label(f3, text="Referencia Bancaria: ")
        l3.pack(side=LEFT)
        e3 = Entry(f3, textvariable=refbanco, width=60)
        e3.pack(side=LEFT, fill=X, expand=1)
        e3.bind("<KeyRelease>", caps)

        f4 = Frame(wrapper)
        f4.pack(pady=5, fill=X)  #-----------------------------------

        b1 = Button(f4,
                    text="Cargar",
                    bg='navy',
                    foreground='white',
                    activebackground='red3',
                    activeforeground='white',
                    command=cargar)
        b1.pack(side=RIGHT)

        b2 = Button(f4,
                    text="Agregar",
                    bg='navy',
                    foreground='white',
                    activebackground='red3',
                    activeforeground='white',
                    command=agregar)
        b2.pack(side=RIGHT)

        #========================== TREEVIEW ===========================

        f5 = Frame(wrapper)
        f5.pack(pady=5, fill=X)  #-----------------------------------

        tree = Treeview(f5, show="headings", columns=('col1', 'col2'))
        tree.pack(side=LEFT, fill=X, expand=1)
        tree.column('col1', width=0, anchor='center')
        tree.column('col2', width=150, anchor='w')

        tree.heading('col1', text='CC/Nit')
        tree.heading('col2', text='Nombre Completo')

        scroll = Scrollbar(f5, orient=VERTICAL, command=tree.yview)
        tree.configure(yscrollcommand=scroll.set)

        f6 = Frame(wrapper)
        f6.pack(pady=5, fill=X)  #-----------------------------------

        delete = Button(f6,
                        text="Eliminar",
                        bg='navy',
                        foreground='white',
                        activebackground='red3',
                        activeforeground='white',
                        command=borrar)
        delete.pack(side=RIGHT)

        e4 = Entry(f6, textvariable=busqueda)
        e4.pack(side=LEFT)
        e4.bind("<KeyRelease>", caps)

        b4 = Button(f6, text='BUSCAR', image=lupa, command=buscar)
        b4.image = lupa
        b4.pack(side=LEFT)

        R1 = Radiobutton(f6, text="CC/nit", variable=info, value=1)
        R1.pack(side=LEFT)
        R2 = Radiobutton(f6, text="Nombre", variable=info, value=2)
        R2.pack(side=LEFT)
        info.set(1)
Esempio n. 26
0
bottomLeft.get_tk_widget().pack()
sentFig.tight_layout()

#Top Keywords
lab3=tk.Label(rightPan,text="Most Frequent Unmodeled Keywords",font='arial 10 bold')
rightPan.add(lab3)
lab3.pack()

keywords=Treeview(rightPan)
keywords["columns"]=["Frequency"]
style = Style(root)
style.configure('Treeview', rowheight=29,font='arial 10 bold')

keywords.heading("#0", text="Word")
keywords.heading("Frequency", text="Frequency")
keywords.column("#0", anchor=tk.CENTER)
keywords.column("Frequency", anchor=tk.CENTER)
keywordIndex={}
top10Words=topWords[-10:]

tree_i=0
for index,row in top10Words.iteritems():
    treeind=keywords.insert(parent="",index=0,text=str(index), values=(str(row)))
    keywordIndex[tree_i]=treeind
    tree_i+=1
    
rightPan.add(keywords)
keywords.pack()


#Sample    
Esempio n. 27
0
class App:
    def __init__(self,master):
        self.master = master
        self.master.resizable(0,0)
        self.master.update_idletasks()
        self.master.overrideredirect(1)
        self.master.attributes("-topmost",True)
        self.master.title("New Graph")
        self.master.lift()
        self.menubar = Menu(self.master)
        self.master.config(menu=self.menubar)
        self.default_color = self.master.cget("bg")
        self.active_edit_flag = 0
        self.modify_flag = 0
        self.graph_types = ['Default','Maelstrom','Rankine Half-Body','Rankine Oval', 'Cylinder','Stagnation & Vortex']
       #-----------------------------------------------------------------------
        self.file_menu = Menu(self.menubar)
        
        self.Fig = matplotlib.figure.Figure(figsize=(2.148,1.777),dpi=100,tight_layout=True)
        self.FigSubPlot = self.Fig.add_subplot(111)     
        frame = Frame(master,bg='#%02x%02x%02x' % (231, 231, 231))
        frame.pack(fill=BOTH, expand=1)
        frame2 = Frame(frame,bg='#%02x%02x%02x' % (221, 221, 221))
        frame2.pack(fill=BOTH, expand=1,padx=20,pady=23)
        self.frame3 = Frame(frame2, bg='#%02x%02x%02x' % (221, 221, 221))
        self.frame3.pack(fill=BOTH, padx=17,pady=17,expand=1)
        self.radio_frame = Frame(self.frame3,bg='#%02x%02x%02x' % (221, 221, 221))
      
        #self.listbox = Listbox(self.frame3)
        self.radio_var = StringVar()
        self.radio_var.set('Default')
        for key in self.graph_types:
            b = Radiobutton(self.radio_frame,text=key,variable=self.radio_var,value = key,bg='#%02x%02x%02x' % (221, 221, 221),indicatoron=1)
            b.pack(anchor=W)
#        for key_num in range(0,len(self.graph_types)):
#            self.listbox.insert(END,self.graph_types[key_num])
#        self.listbox.select_set(0)
#        self.listbox.bind('<<ListboxSelect>>',self.changegraph)
        self.radio_var.trace('w',self.changegraph)
#        self.old = self.listbox.get(self.listbox.curselection())
        self.blankc = Canvas(self.frame3,width=225,height=188)
        self.canvas = FigureCanvasTkAgg(self.Fig, master=self.frame3)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=RIGHT,padx=0,pady=5)
        self.radio_frame.pack(side=LEFT,anchor=W,padx=8,pady=5,fill=BOTH,expand=1) 
        #self.listbox.pack(side=LEFT,anchor=W,padx=8,pady=5,fill=BOTH,expand=1)   
        self.button_frame = Frame(frame,bg='#%02x%02x%02x' % (231, 231, 231))
        self.button_frame.pack(side=RIGHT)
        self.buffer_frame = Frame(self.button_frame,bg='#%02x%02x%02x' % (231, 231, 231))
        self.buffer_frame.pack(side=BOTTOM,pady=8)
        self.buffer_frame2 = Frame(self.button_frame,bg='#%02x%02x%02x' % (231, 231, 231))
        self.buffer_frame2.pack(side=RIGHT,padx=11)
        self.button_c = Button(self.button_frame,width=9, text='Choose',bg='#%02x%02x%02x' % (231, 231, 231),command=self.Continue)
        self.button_x = Button(self.button_frame,text='Cancel',bg='#%02x%02x%02x' % (231, 231, 231),width=9,command=self.quit)
        self.button_c.focus()
        self.button_c.pack(side=RIGHT)
        self.button_x.pack(side=RIGHT,padx=14)
        self.line_color = StringVar()
        self.line_color.set('#000000')
        self.wt_var = StringVar()
        self.wt_var.set('- WT:')
        self.wt_var.trace('w',self.wt_update)
        self.linet_var = StringVar()
        self.linet_var.set('-')
        self.linet_var.trace('w',self.line_style_update)
        self.line_var = IntVar()
        self.line_var.set(25)
        self.line_val = 25
        self.div_check_var = IntVar()
        self.div_check_var.set(50)
        self.div_val = 50
        self.density_var = IntVar()
        self.density_var.set(35)
        self.density_val = 35
        self.arrow_var = IntVar()
        self.arrow_var.set(25) 
        self.arrow_val = 25
        self.div_var = IntVar()
        self.div_var.set(0)
        self.mark_var = IntVar()
        self.mark_var.set(0)
        self.lock_var = IntVar()
        self.lock_var.set(1)
        self.active_numbers = {'s':0,'v':0,'u':0,'d':0,'n':0}
        self.sel_point = None
        self.selected = None
    def changegraph(self,*args):
        self.xlim = [-5.0,5.0]
        self.ylim = [-5.0,5.0]
        Y, X = mgrid[-5:5:100j, -5:5:100j]
        self.X,self.Y = X,Y
        self.FigSubPlot.clear()
        #if self.listbox.get(self.listbox.curselection()) == 'Default':
        if self.radio_var.get() == 'Default':
            self.U = 0*X
            self.V = 0*X
            self.FigSubPlot.streamplot(X,Y,self.U,self.V)
        #elif self.listbox.get(self.listbox.curselection()) == 'Maelstrom':
        elif self.radio_var.get() == 'Maelstrom':    
            self.U = self.source(X,Y,1)[0]+self.vortex(X,Y,1)[0]
            self.V = self.source(X,Y,1)[1]+self.vortex(X,Y,1)[1]
            self.FigSubPlot.streamplot(X,Y,self.U,self.V, color='k', linewidth=(2.0/71.0)*self.line_var.get()+(13.0/71.0),density=(2.0/71.0)*self.density_var.get()+(13.0/71.0),arrowstyle='-')
        #elif self.listbox.get(self.listbox.curselection()) == 'Rankine Half-Body':
        elif self.radio_var.get() == 'Rankine Half-Body':
            self.U = self.source(X,Y,10)[0]+self.uniform(X,Y,1,1,0)[0]
            self.V = self.source(X,Y,10)[1]+self.uniform(X,Y,1,1,0)[1]
            self.FigSubPlot.streamplot(X, Y,self.U,self.V, color='k', linewidth=(2.0/71.0)*self.line_var.get()+(13.0/71.0),density=(2.0/71.0)*self.density_var.get()+(13.0/71.0),arrowstyle='-')
        #elif self.listbox.get(self.listbox.curselection()) == 'Rankine Oval':
        elif self.radio_var.get() == 'Rankine Oval':
            self.U = self.source(X+2,Y,10)[0]+self.source(X-2,Y,-10)[0]+self.uniform(X,Y,1,1,0)[0]
            self.V = self.source(X+2,Y,10)[1]+self.source(X-2,Y,-10)[1]+self.uniform(X,Y,1,1,0)[1]
            self.FigSubPlot.streamplot(X, Y,self.U,self.V, color='k', linewidth=(2.0/71.0)*self.line_var.get()+(13.0/71.0),density=(2.0/71.0)*self.density_var.get()+(13.0/71.0),arrowstyle='-')
        #elif self.listbox.get(self.listbox.curselection()) == 'Cylinder':
        elif self.radio_var.get() == 'Cylinder':
            self.U = self.doublet(X,Y,25)[0]+self.uniform(X,Y,1,1,0)[0]
            self.V = self.doublet(X,Y,25)[1]+self.uniform(X,Y,1,1,0)[1]
            self.FigSubPlot.streamplot(X, Y,self.U,self.V, color='k', linewidth=(2.0/71.0)*self.line_var.get()+(13.0/71.0),density=(2.0/71.0)*self.density_var.get()+(13.0/71.0),arrowstyle='-')
        #elif self.listbox.get(self.listbox.curselection()) == 'Stagnation & Vortex':
        elif self.radio_var.get() == 'Stagnation & Vortex':
            self.U = self.vortex(X,Y,25)[0]+self.corner(X,Y,'2,1')[0]
            self.V = self.vortex(X,Y,25)[1]+self.corner(X,Y,'2,1')[1]
            self.FigSubPlot.streamplot(X, Y,self.U,self.V, color='k', linewidth=(2.0/71.0)*self.line_var.get()+(13.0/71.0),density=(2.0/71.0)*self.density_var.get()+(13.0/71.0),arrowstyle='-')
        self.FigSubPlot.set_xlim(self.xlim)
        self.FigSubPlot.set_ylim(self.ylim)
        self.canvas.draw()
#        self.old = self.listbox.get(self.listbox.curselection())
    def source(self,X,Y,l):
        l = float(l)
        U = (l/(2*pi))*X/(X*X + Y*Y)
        V = (l/(2*pi))*Y/(X*X + Y*Y)
        return (U,V)
    def vortex(self,X,Y,g):
        g = float(g)
        U = (g/(2*pi))*Y/(X*X + Y*Y)
        V = (g/(2*pi))*-X/(X*X + Y*Y)
        return (U,V)
    def uniform(self,X,Y,v_0,x_0,y_0):
        v_0 = float(v_0)
        x_0 = float(x_0)
        y_0 = float(y_0)
        U = v_0*x_0/(x_0*x_0+y_0*y_0)**0.5
        V = v_0*y_0/(x_0*x_0+y_0*y_0)**0.5
        return (U,V)
    def doublet(self,X,Y,k):
        k = float(k)
        U = (k/(2*pi))*((2*Y*Y/((X*X+Y*Y)*(X*X+Y*Y)))-(1/(X*X+Y*Y)))
        V = -(k/(2*pi))*(2*X*Y/((X*X+Y*Y)*(X*X+Y*Y)))
        return (U,V)
    def corner(self,X,Y,tup):
        comma_flag = 0
        A = ''
        n = ''
        for char in tup:
            if char == ',':
                comma_flag = 1
            elif comma_flag == 0:
                n += char
            elif comma_flag == 1:
                A += char
        A = float(A)
        n = float(n)
        R = (X*X+Y*Y)**0.5
        t = arctan2(-Y,-X)
        U = -A*n*R**(n-1)*(cos(n*t)*cos(t)+sin(n*t)*sin(t))
        V = -A*n*R**(n-1)*(cos(n*t)*sin(t)-sin(n*t)*cos(t))
        return (U,V)
    def stream_source(self,X,Y,l):
        l = float(l)
        stream = (l/(2*pi))*arctan2(-Y,-X)
        return stream
    def stream_vortex(self,X,Y,g):
        g = float(g)
        stream = (g/(2*pi))*log((X*X + Y*Y)**0.5)
        return stream
    def stream_uniform(self,X,Y,v_0,x_0,y_0):
        v_0 = float(v_0)
        x_0 = float(x_0)
        y_0 = float(y_0)
        stream = (v_0*Y*x_0/(x_0*x_0+y_0*y_0)**0.5)-(v_0*X*y_0/(x_0*x_0+y_0*y_0)**0.5)
        return stream
    def stream_doublet(self,X,Y,k):
        k = float(k)
        stream = -(k/(2*pi))*Y/(X*X+Y*Y)
        return stream
    def stream_corner(self,X,Y,tup):
        comma_flag = 0
        A = ''
        n = ''
        for char in tup:
            if char == ',':
                comma_flag = 1
            elif comma_flag == 0:
                n += char
            elif comma_flag == 1:
                A += char
        A = float(A)
        n = float(n)
        stream = A*(X*X+Y*Y)**(n*0.5)*sin(n*arctan2(-Y,-X))
        return stream
    def quit(self):
        self.master.destroy()    
    def Continue(self):
        self.master.withdraw()
        self.main = Toplevel(self.master)
        self.main.geometry("%dx%d+%d+%d" % (1038-206, 
                               694,
                               int((500.0/2560.0)*screen_resolution[0]), 
                               int((60.0/1440.0)*screen_resolution[1])))
        self.main.minsize(376,227)                      
        self.interior = PanedWindow(self.main,sashwidth=5)
        self.interior.pack(fill=BOTH, expand=1)

        self.elements_frame = Frame(self.interior, height=1038, width=212,relief=RIDGE,borderwidth=0)
        self.interior.add(self.elements_frame) 
        self.interior.paneconfig(self.elements_frame,minsize=130)
        self.graph_frame = Frame(self.interior)
        self.interior.add(self.graph_frame)
        self.interior.paneconfig(self.graph_frame,minsize=130)

        self.main.bind("<ButtonRelease-1>",self.pan_update)
        self.main.bind("<ButtonRelease-3>",self.pan_update)
        self.main.bind("<Button-3>",self.right_menu)
        
        self.edit_frame = Frame(self.graph_frame)
        self.edit_frame.pack(side=TOP,fill=X,padx=10)
        self.canvas = FigureCanvasTkAgg(self.Fig, master=self.graph_frame)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(fill=BOTH,expand=1)
        self.nav_frame = Frame(self.edit_frame)
        self.nav_frame.pack(side=LEFT,anchor=W)
        self.toolbar = NavigationToolbar(self.canvas, self.nav_frame)
        
        self.main.protocol('WM_DELETE_WINDOW',self.master.destroy) 
        self.elements = Treeview(self.elements_frame,columns=("values","xlocations","ylocations"),selectmode=BROWSE)
        self.elements.heading("#0",text="Components")
        self.elements.heading("values",text="Str")
        self.elements.heading("xlocations",text="X")
        self.elements.heading("ylocations",text="Y")
        self.elements.column("#0",width=90,anchor=CENTER)
        self.elements.column("values",width=45,anchor=CENTER)
        self.elements.column("xlocations",width=26,anchor=CENTER)
        self.elements.column("ylocations",width=26,anchor=CENTER)
        self.elements.pack(fill=BOTH,expand=1)
        
        self.as_button_frame = Frame(self.elements_frame)
        self.add_button = Button(self.as_button_frame,text = '+',width=2,command=self.add)       
        self.sub_button = Button(self.as_button_frame,text = '-',width=2,command=self.subtract) 
        self.options_button = Button(self.as_button_frame,text='Options',command=self.options)
        self.as_button_frame.pack(side=BOTTOM,anchor=W)
        self.options_button.pack(side=RIGHT)
        self.sub_button.pack(side=RIGHT,anchor=W)
        self.add_button.pack(side=LEFT,anchor=W)
        self.addsub_menu = Menu(self.as_button_frame,tearoff=0)
        self.addsub_menu.add_command(command=self.add_source,label='Source')
        self.addsub_menu.add_command(command=self.add_vortex,label='Vortex')
        self.addsub_menu.add_command(command=self.add_uniform,label='Uniform')
        self.addsub_menu.add_command(command=self.add_doublet,label='Doublet')
        self.addsub_menu.add_command(command=self.add_corner,label='Corner')
        

        #if self.listbox.get(self.listbox.curselection()) == 'Default':
        if self.radio_var.get() == 'Default':
            self.active_components = []
            self.active_calls = {} 
            pass
        #elif self.listbox.get(self.listbox.curselection()) == 'Maelstrom':
        elif self.radio_var.get() == 'Maelstrom':
            self.elements.insert("",0,"M",text="Maelstrom",open=TRUE)
            self.active_components = ['M']
            self.elements.insert("M",0,iid='s%s'%self.active_numbers['s'],text="Source",values=("%s"%1,0,0))
            self.elements.insert("M",0,iid='v%s'%self.active_numbers['v'],text="Vortex",values=("%s"%1,0,0))
            self.active_calls = {'s%s'%self.active_numbers['s']:("s",self.elements.item('s%s'%self.active_numbers['s'],"values")),
                                 'v%s'%self.active_numbers['v']:("v",self.elements.item('v%s'%self.active_numbers['v'],"values"))}
            self.active_numbers['s'] += 1
            self.active_numbers['v'] += 1
        elif self.radio_var.get() == 'Rankine Half-Body':
            self.elements.insert("",0,"RHF",text="Rankine Half-Body",open=TRUE)
            self.active_components = ['RHF']
            self.elements.insert("RHF",0,iid='s%s'%self.active_numbers['s'],text="Source",values=("%s"%10,0,0))
            self.elements.insert("RHF",0,iid='u%s'%self.active_numbers['u'],text="Uniform",values=("%s"%1,1,0))
            self.active_calls = {'s%s'%self.active_numbers['s']:("s",self.elements.item('s%s'%self.active_numbers['s'],"values")),
                                 'u%s'%self.active_numbers['u']:("u",self.elements.item('u%s'%self.active_numbers['u'],"values"))}
            self.active_numbers['s'] += 1
            self.active_numbers['u'] += 1
        elif self.radio_var.get() == 'Rankine Oval':
            self.elements.insert("",0,"RO",text="Rankine Oval",open=TRUE)
            self.active_components = ['RO']
            self.elements.insert("RO",0,iid='s%s'%self.active_numbers['s'],text="Source",values=("%s"%10,-2,0))
            self.elements.insert("RO",0,iid='s%s'%(self.active_numbers['s']+1),text="Source",values=("%s"%-10,2,0))
            self.elements.insert("RO",0,iid='u%s'%self.active_numbers['u'],text="Uniform",values=("%s"%1,1,0))
            self.active_calls = {'s%s'%self.active_numbers['s']:("s",self.elements.item('s%s'%self.active_numbers['s'],"values")),
                                 's%s'%(self.active_numbers['s']+1):("s",self.elements.item('s%s'%(self.active_numbers['s']+1),"values")),
                                 'u%s'%self.active_numbers['u']:("u",self.elements.item('u%s'%self.active_numbers['u'],"values"))}
            self.active_numbers['s'] += 2
            self.active_numbers['u'] += 1       
        elif self.radio_var.get() == 'Cylinder':
            self.elements.insert("",0,'D+U',text="Cylinder",open=TRUE)
            self.active_components = ['D+U']
            self.elements.insert('D+U',0,iid='d%s'%self.active_numbers['d'],text="Doublet",values=("%s"%25,0,0))
            self.elements.insert('D+U',0,iid='u%s'%self.active_numbers['u'],text="Uniform",values=("%s"%1,1,0))
            self.active_calls = {'d%s'%self.active_numbers['d']:("d",self.elements.item('d%s'%self.active_numbers['d'],"values")),
                                 'u%s'%self.active_numbers['u']:("u",self.elements.item('u%s'%self.active_numbers['u'],"values"))}
            self.active_numbers['d'] += 1
            self.active_numbers['u'] += 1
        elif self.radio_var.get() == 'Stagnation & Vortex':
            self.elements.insert("",0,'S+V',text="Stag+Vort",open=TRUE)
            self.active_components = ['S+V']
            self.elements.insert('S+V',0,iid='n%s'%self.active_numbers['n'],text="C (n,A)",values=("%s,%s"%(2,1),0,0))
            self.elements.insert('S+V',0,iid='v%s'%self.active_numbers['v'],text="Vortex",values=("%s"%25,0,0))
            self.active_calls = {'n%s'%self.active_numbers['n']:("n",self.elements.item('n%s'%self.active_numbers['n'],"values")),
                                 'v%s'%self.active_numbers['v']:("v",self.elements.item('v%s'%self.active_numbers['v'],"values"))}
            self.active_numbers['n'] += 1
            self.active_numbers['v'] += 1
        self.elements.bind("<Double-Button-1>",self.edit)
        self.elements.bind('<<TreeviewSelect>>',self.treeview_select)
        self.main.bind("<Return>",self.edit_return)
        self.main.bind("<Escape>",self.edit_return)

        
        self.rightc_menu = Menu(self.graph_frame,tearoff=0)
        self.add_menu = Menu(self.rightc_menu,tearoff=0)
        self.rightc_menu.add_cascade(label="Add",menu=self.add_menu)
        self.add_menu.add_command(command=self.addm_source,label='Source')
        self.add_menu.add_command(command=self.addm_vortex,label='Vortex')
        self.add_menu.add_command(command=self.addm_uniform,label='Uniform')
        self.add_menu.add_command(command=self.addm_doublet,label='Doublet')
        self.add_menu.add_command(command=self.addm_corner,label='Corner')
    def right_menu(self,event):
        print "event", event.x,event.y
        #print "graph", self.main.winfo_x()+self.interior.winfo_x()+self.graph_frame.winfo_x(), self.main.winfo_y()+self.interior.winfo_y()+self.graph_frame.winfo_y()
        self.plot_x,self.plot_y = self.FigSubPlot.transData.inverted().transform((event.x,event.y+20))
        self.plot_y = -self.plot_y
        self.rightc_menu.post(self.main.winfo_x()+self.interior.winfo_x()+self.graph_frame.winfo_x()+event.x+9,self.main.winfo_y()+self.graph_frame.winfo_y()+event.y+66)
        
    def treeview_select(self,event):
        if self.elements.get_children(self.elements.selection()[0]) == ():
            if self.mark_var.get() == 0 or self.selected == self.elements.selection():
                pass
            elif self.mark_var.get() == 1:
                
                #add red markers here
                
                if self.elements.selection() != '':
                    child = self.elements.selection()[0]
                    if child != '':
                        self.sel_point = (self.elements.item(child,"values")[1],self.elements.item(child,"values")[2])
                        self.graph_update()
                        self.selected = self.elements.selection()
                else:
                    pass
        else:
            if self.mark_var.get() == 0 or self.selected == self.elements.selection():
                pass
            elif self.mark_var.get() == 1:
                if self.elements.selection() != '':
                    child = self.elements.selection()[0]
                    if child != '':
                        self.sel_point = None
                        self.graph_update()
                        self.selected = self.elements.selection()
    def mark_check_fun(self):
        if self.mark_var.get() == 0:
            self.sel_point = None
            self.graph_update()
        elif self.elements.selection() != '':
            child = self.elements.selection()[0]
            self.sel_point = [self.elements.item(child,"values")[1],self.elements.item(child,"values")[2]]
            self.graph_update()
            
    def add(self):
        self.addsub_menu.post(self.main.winfo_x()+self.as_button_frame.winfo_x()+self.add_button.winfo_x(),self.main.winfo_y()+self.as_button_frame.winfo_y()+self.add_button.winfo_y()-len(self.active_numbers.keys())*14)
    def subtract(self):
        if self.active_edit_flag == 1:
            self.del_edit(self)
        child = self.elements.selection()[0]
        if child == '':
            return
        if self.elements.parent(child) == '':
            ID = child
            self.active_components.remove(child)
            self.elements.delete(child)
        else:
            ID = self.elements.parent(child)
            self.active_components.remove(ID)
            for comp in self.elements.get_children(ID):
                if comp != child:
                    self.active_components.append(comp)
                    self.elements.move(comp,"",0)
            self.elements.delete(ID)
        self.sel_point = None
        self.graph_update()
    def options(self):
        self.options_window = Toplevel(self.main)
        self.options_window.geometry("%dx%d+%d+%d" % (280, 
                                                      200+20,
                                                      self.main.winfo_x()+self.as_button_frame.winfo_x()+self.options_button.winfo_x()-272+26+72+86,
                                                      self.main.winfo_y()+self.as_button_frame.winfo_y()+self.options_button.winfo_y()-196-20))
        self.main.bind('<FocusIn>',self.close_options)
        self.options_window.title("Options")
        self.options_window.update_idletasks()
        self.options_window.bind("<ButtonRelease-1>",self.pan_update)
        self.options_frame = Frame(self.options_window)
        self.options_frame.pack(fill=BOTH,expand=1)
        self.options_window.attributes("-topmost",True)

        self.line_frame = Frame(self.options_frame,bd=2,relief=RIDGE)
        self.line_frame.grid(row=0,column=1,sticky=N+S+E+W,ipady=7)
        self.color_frame = Frame(self.options_frame,bd=2,relief=RIDGE,padx=2)
        self.color_frame.grid(row=0,column=0,sticky=N+S+E+W)
        
        self.color_button = Label(self.color_frame,bg=self.line_color.get(),text = '     ')
        self.color_button.pack(side=RIGHT)
        Label(self.color_frame,text='C:').pack(side=RIGHT)
        self.color_button.bind('<Button-1>',self.getColor)
        
        self.wt_slider = Scale(self.line_frame,from_=1,to=100,orient=HORIZONTAL,variable=self.line_var)
        if self.wt_var.get() == '-> WT:':
            self.wt_slider.config(variable=self.arrow_var)
        elif self.wt_var.get() == '- WT:':
            self.wt_slider.config(variable=self.line_var)
        elif self.wt_var.get() == 'div WT:':
            self.wt_slider.config(variable=self.div_check_var)
        self.wt_slider.pack(side=RIGHT)
        
        self.wt_menu = OptionMenu(self.line_frame,self.wt_var,'- WT:','-> WT:','div WT:')
        self.wt_menu.pack(side=RIGHT,anchor='center',fill=X,expand=1)
        self.wt_menu.config(width=8)
        self.density_frame = Frame(self.options_frame,bd=2,relief=RIDGE)
        self.density_frame.grid(row=1,column=1,sticky=N+S+E+W)
        self.density_slider = Scale(self.density_frame,from_=1,to=100,orient=HORIZONTAL,variable=self.density_var)
        self.density_slider.pack(side=RIGHT)
        Label(self.density_frame,text='Density').pack(side=LEFT,anchor=CENTER,fill=X,expand=1)
        
        self.linet_frame = Frame(self.options_frame,bd=2,relief=RIDGE)
        self.linet_frame.grid(row=1,column=0,sticky=N+S+E+W)
        Label(self.linet_frame,text='Style').pack(anchor='n')
        self.linet_menu = OptionMenu(self.linet_frame,self.linet_var,'-','->','-|>')
        self.linet_menu.pack(anchor='s',side=BOTTOM)
        self.linet_menu.config(width=5)
        
        self.div_check = Checkbutton(self.options_frame,text = 'Dividing Streamline',variable=self.div_var,onvalue=1,offvalue=0,command = self.graph_update)
        self.div_check.grid(row=2,column=1,sticky=W)
        self.mark_check = Checkbutton(self.options_frame,text = 'Selection Marker',variable=self.mark_var,onvalue=1,offvalue=0,command = self.mark_check_fun)
        self.mark_check.grid(row=3,column=1,sticky=W)
        
        self.limit_frame = Frame(self.options_frame)
        self.limit_frame.grid(row=4,column=1,sticky=W)
        #self.aspect_lock = Checkbutton(self.limit_frame,text='LK',variable = self.lock_var)
        #self.aspect_lock.grid(row=0,column=4,rowspan=2,sticky=E)
        
        Label(self.limit_frame,text='x').grid(row=0,column=0)
        self.xlimlow_var = DoubleVar()
        self.xlimlow_var.set(self.FigSubPlot.get_xlim()[0])
        self.xlimlow_entry = Entry(self.limit_frame,textvariable=self.xlimlow_var,width=5)
        self.xlimlow_entry.grid(row=0,column=1)
        Label(self.limit_frame,text='...').grid(row=0,column=2)
        self.xlimhigh_var = DoubleVar()
        self.xlimhigh_var.set(self.FigSubPlot.get_xlim()[1])
        self.xlimhigh_entry = Entry(self.limit_frame,textvariable=self.xlimhigh_var,width=5)
        self.xlimhigh_entry.grid(row=0,column=3)
        Label(self.limit_frame,text='y').grid(row=1,column=0)
        self.ylimlow_var = DoubleVar()
        self.ylimlow_var.set(self.FigSubPlot.get_ylim()[0])
        self.ylimlow_entry = Entry(self.limit_frame,textvariable=self.ylimlow_var,width=5)
        self.ylimlow_entry.grid(row=1,column=1)
        Label(self.limit_frame,text='...').grid(row=1,column=2)
        self.ylimhigh_var = DoubleVar()
        self.ylimhigh_var.set(self.FigSubPlot.get_ylim()[1])
        self.ylimhigh_entry = Entry(self.limit_frame,textvariable=self.ylimhigh_var,width=5)
        self.ylimhigh_entry.grid(row=1,column=3)
        
        
        #self.limit_frame.bind('<FocusOut>',self.limits_update)
        self.xlimhigh_var.trace('w',self.limits_update)
        self.ylimhigh_var.trace('w',self.limits_update)
        self.xlimlow_var.trace('w',self.limits_update)
        self.ylimlow_var.trace('w',self.limits_update)
        
    def limits_update(self,*args):

        if self.xlimlow_entry.get() == '' or self.ylimlow_entry.get() == '' or self.xlimhigh_entry.get() == '' or self.ylimhigh_entry.get() == '':
            pass
        elif self.xlimlow_entry.get() == '-' or self.ylimlow_entry.get() == '-' or self.xlimhigh_entry.get() == '-' or self.ylimhigh_entry.get() == '-':
            pass
        elif self.xlimlow_entry.get() == '.' or self.ylimlow_entry.get() == '.' or self.xlimhigh_entry.get() == '.' or self.ylimhigh_entry.get() == '.':
            pass
        else:
            self.xlim = [float(self.xlimlow_var.get()),float(self.xlimhigh_var.get())]
            self.ylim = [float(self.ylimlow_var.get()),float(self.ylimhigh_var.get())]

            self.FigSubPlot.set_xlim(self.xlim)
            self.FigSubPlot.set_ylim(self.ylim)
            self.graph_update()
    def getColor(self,event):
        color=askcolor(self.line_color.get())
        if color != "None":
            self.line_color.set(color[1])
            self.graph_update()
    def wt_update(self,*args):
        if self.wt_var.get() == '-> WT:':
            self.wt_slider.config(variable=self.arrow_var)
        elif self.wt_var.get() == '- WT:':
            self.wt_slider.config(variable=self.line_var)
        elif self.wt_var.get() == 'div WT:':
            self.wt_slider.config(variable=self.div_check_var)
    def line_style_update(self,*args):
        self.graph_update()
    def close_options(self,event):
        self.options_window.destroy()
    def add_source(self):
        if self.modify_flag == 0:
            self.plot_x,self.plot_y = 0,0
        self.elements.insert("",0,iid='s%s'%self.active_numbers['s'],text="Source",values=("%s"%1,self.plot_x,self.plot_y))
        self.active_calls['s%s'%self.active_numbers['s']] = ("s",self.elements.item('s%s'%self.active_numbers['s'],"values"))
        self.active_components.append('s%s'%self.active_numbers['s'])
        if self.modify_flag == 1:
            self.elements.selection_set('s%s'%self.active_numbers['s'])
            self.modify_flag = 0
        self.graph_update()
        self.active_numbers['s'] += 1
        
    def add_vortex(self):
        if self.modify_flag == 0:
            self.plot_x,self.plot_y = 0,0
        self.elements.insert("",0,iid='v%s'%self.active_numbers['v'],text="Vortex",values=("%s"%1,self.plot_x,self.plot_y))
        self.active_calls['v%s'%self.active_numbers['v']] = ("v",self.elements.item('v%s'%self.active_numbers['v'],"values"))
        self.active_components.append('v%s'%self.active_numbers['v'])

        if self.modify_flag == 1:
            self.elements.selection_set('v%s'%self.active_numbers['v'])
            self.modify_flag = 0
        self.graph_update()
        self.active_numbers['v'] += 1
    def add_uniform(self):
        if self.modify_flag == 0:
            self.plot_x,self.plot_y = 1,0
        self.elements.insert("",0,iid='u%s'%self.active_numbers['u'],text="Uniform",values=("%s"%1,self.plot_x,self.plot_y))
        self.active_calls['u%s'%self.active_numbers['u']] = ("u",self.elements.item('u%s'%self.active_numbers['u'],"values"))
        self.active_components.append('u%s'%self.active_numbers['u'])
        if self.modify_flag == 1:
            self.elements.selection_set('u%s'%self.active_numbers['u'])
            self.modify_flag = 0
        self.graph_update()
        self.active_numbers['u'] += 1
    def add_doublet(self):
        if self.modify_flag == 0:
            self.plot_x,self.plot_y = 0,0
        self.elements.insert("",0,iid='d%s'%self.active_numbers['d'],text="Doublet",values=("%s"%1,self.plot_x,self.plot_y))
        self.active_calls['d%s'%self.active_numbers['d']] = ("d",self.elements.item('d%s'%self.active_numbers['d'],"values"))
        self.active_components.append('d%s'%self.active_numbers['d'])
        if self.modify_flag == 1:
            self.elements.selection_set('d%s'%self.active_numbers['d'])
            self.modify_flag = 0
        self.graph_update()
        self.active_numbers['d'] += 1
    def add_corner(self):
        if self.modify_flag == 0:
            self.plot_x,self.plot_y = 0,0
        self.elements.insert("",0,iid='n%s'%self.active_numbers['n'],text="Corner (n,A)",values=("%s,%s"%(2,1),self.plot_x,self.plot_y))
        self.active_calls['n%s'%self.active_numbers['n']] = ("n",self.elements.item('n%s'%self.active_numbers['n'],"values"))
        self.active_components.append('n%s'%self.active_numbers['n'])
        if self.modify_flag == 1:
            self.elements.selection_set('n%s'%self.active_numbers['n'])
            self.modify_flag = 0
        self.graph_update()
        self.active_numbers['n'] += 1
    def addm_source(self):
        self.modify_flag = 1 
        self.add_source()
    def addm_vortex(self):
        self.modify_flag = 1
        self.add_vortex()
    def addm_uniform(self):
        self.modify_flag = 1
        self.add_uniform()
    def addm_doublet(self):
        self.modify_flag = 1
        self.add_doublet()
    def addm_corner(self):
        self.modify_flag = 1
        self.add_corner()
    def pan_update(self,event):
        if [self.FigSubPlot.get_xlim()[0],self.FigSubPlot.get_xlim()[1]] != self.xlim or [self.FigSubPlot.get_ylim()[0],self.FigSubPlot.get_ylim()[1]] != self.ylim or self.density_var.get() != self.density_val or self.line_var.get() != self.line_val or self.arrow_var.get() != self.arrow_val or self.arrow_var.get() != self.arrow_val or self.div_check_var.get() != self.div_val:
            self.graph_update()
            self.density_val = self.density_var.get()
            self.line_val = self.line_var.get()
            self.arrow_val = self.arrow_var.get()
            self.div_val = self.div_check_var.get()
        else:
            return
    def graph_update(self):
        self.FigSubPlot.clear()
        Y, X = mgrid[self.FigSubPlot.get_ylim()[0]:self.FigSubPlot.get_ylim()[1]:100j, self.FigSubPlot.get_xlim()[0]:self.FigSubPlot.get_xlim()[1]:100j]     
        self.xlim = [self.FigSubPlot.get_xlim()[0],self.FigSubPlot.get_xlim()[1]]
        self.ylim = [self.FigSubPlot.get_ylim()[0],self.FigSubPlot.get_ylim()[1]]
        self.U = 0*X
        self.V = 0*X      
        self.stream = 0*X
        for ID in self.active_components:
            if self.elements.get_children(ID) == ():
                child = ID
                self.active_calls[child] = (child[0],self.elements.item(child,"values"))
                if self.active_calls[child][0] == "s":
                    self.U += self.source(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[0]
                    self.V += self.source(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[1]
                    self.stream += self.stream_source(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])
                elif self.active_calls[child][0] == 'v':
                    self.U += self.vortex(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[0]
                    self.V += self.vortex(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[1]
                    self.stream += self.stream_vortex(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])
                elif self.active_calls[child][0] == 'u':
                    if self.active_calls[child][1][1] == '0' and self.active_calls[child][1][2] == '0':
                        pass
                    else:
                        self.U += self.uniform(X,Y,self.active_calls[child][1][0],self.active_calls[child][1][1],self.active_calls[child][1][2])[0]
                        self.V += self.uniform(X,Y,self.active_calls[child][1][0],self.active_calls[child][1][1],self.active_calls[child][1][2])[1]
                        self.stream += self.stream_uniform(X,Y,self.active_calls[child][1][0],self.active_calls[child][1][1],self.active_calls[child][1][2])
                elif self.active_calls[child][0] == 'd':
                    self.U += self.doublet(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[0]
                    self.V += self.doublet(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[1]
                    self.stream += self.stream_doublet(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])
                elif self.active_calls[child][0] == 'n':
                    self.U += self.corner(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[0]
                    self.V += self.corner(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[1]
                    self.stream += self.stream_corner(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])
            else:
                for child in self.elements.get_children(ID):
                    self.active_calls[child] = (child[0],self.elements.item(child,"values"))
                    if self.active_calls[child][0] == "s":
                        self.U += self.source(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[0]
                        self.V += self.source(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[1]
                        self.stream += self.stream_source(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])
                    elif self.active_calls[child][0] == 'v':
                        self.U += self.vortex(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[0]
                        self.V += self.vortex(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[1]
                        self.stream += self.stream_vortex(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])
                    elif self.active_calls[child][0] == 'u':
                        if self.active_calls[child][1][1] == '0' and self.active_calls[child][1][2] == '0':
                            pass
                        else:
                            self.U += self.uniform(X,Y,self.active_calls[child][1][0],self.active_calls[child][1][1],self.active_calls[child][1][2])[0]
                            self.V += self.uniform(X,Y,self.active_calls[child][1][0],self.active_calls[child][1][1],self.active_calls[child][1][2])[1]
                            self.stream += self.stream_uniform(X,Y,self.active_calls[child][1][0],self.active_calls[child][1][1],self.active_calls[child][1][2])
                    elif self.active_calls[child][0] == 'd':
                        self.U += self.doublet(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[0]
                        self.V += self.doublet(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[1]
                        self.stream += self.stream_doublet(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])
                    elif self.active_calls[child][0] == 'n':
                        self.U += self.corner(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[0]
                        self.V += self.corner(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[1]
                        self.stream += self.stream_corner(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])

        self.FigSubPlot.streamplot(X,Y,self.U,self.V,color=self.line_color.get(), linewidth=(2.0/71.0)*self.line_var.get()+(13.0/71.0),density=(2.0/71.0)*self.density_var.get()+(13.0/71.0),arrowstyle=self.linet_var.get(),arrowsize=(4.0/71.0)*self.arrow_var.get()+(13.0/71.0))
        if self.div_var.get() == 1:
            #self.FigSubPlot.contour(X,Y,self.stream,[-0.01,0.01],linewidths=[(4.0/71.0)*self.div_check_var.get()+(13.0/71.0),(4.0/71.0)*self.div_check_var.get()+(13.0/71.0)])
            
            self.FigSubPlot.contour(X,Y,self.stream,[0],linewidths=[(4.0/71.0)*self.div_check_var.get()+(13.0/71.0)])
        if self.mark_var.get() == 1:
            if self.sel_point != None:
                self.plot_point()
        self.FigSubPlot.set_xlim(self.xlim)
        self.FigSubPlot.set_ylim(self.ylim)
        self.canvas.draw()
    def plot_point(self):
        if self.elements.selection()[0][0] == 'u':
            norm = float(float(self.sel_point[0])*float(self.sel_point[0])+float(self.sel_point[1])*float(self.sel_point[1]))**0.5
            if norm == 0:
                norm = 1
            X,Y,U,V = 0,0, float(self.sel_point[0])/norm,float(self.sel_point[1])/norm
            self.FigSubPlot.quiver(X,Y,U,V,angles='xy',scale_units='xy',scale=1,color='g')
        else:
            self.FigSubPlot.plot([self.sel_point[0]],[self.sel_point[1]],'r^',ms=10)
    def edit(self,event):
        if self.active_edit_flag == 1 or self.elements.identify_row(event.y) == '':
            pass
        else:
            self.rowid = self.elements.identify_row(event.y)
            self.column = self.elements.identify_column(event.x)
            self.edit_var = StringVar()
            if int(self.column[-1]) == 0:
                self.edit_var.set('%s'%self.elements.item("%s"%self.elements.identify("item",event.x, event.y))['text'])

            else:
                self.edit_var.set('%s'%self.elements.item("%s"%self.elements.identify("item",event.x, event.y))['values'][int(self.column[-1])-1])

            x,y,width,height = self.elements.bbox(self.rowid, self.column)
            self.edit_entry = Entry(self.elements_frame,textvariable=self.edit_var)
            self.edit_entry.place(x=x,y=y,width=width)
            self.edit_entry.focus_force()
            self.edit_entry.bind("<FocusOut>", self.del_edit)
            self.active_edit_flag = 1
    def edit_return(self,event):
        self.main.focus()
    def del_edit(self,event):
        if self.column[-1] == '0':
            self.elements.item(self.rowid,text='%s'%self.edit_var.get())
        elif self.rowid[0] == 'n' and self.column[-1] == '1' and ',' not in self.edit_var.get():
            pass
        else:
            value = ''
            initial_value = str(self.elements.item(self.rowid)['values'][int(self.column[-1])-1])
            comma_flag = 0
            div_flag = 0
            for index in range(0,len(self.edit_var.get())):
                char = self.edit_var.get()[index]
                if char in '-0123456789.':
                    value += char
                elif self.rowid[0] == 'n' and char == ',':
                    if comma_flag == 1:
                        self.edit_entry.destroy()
                        self.active_edit_flag = 0
                        return
                    value += char
                    comma_flag = 1
                    comma_index = index
                if char == '/':
                    if div_flag == 0:
                        div_flag = 1
                        div_index = index
                    elif div_flag == 1 and comma_flag == 1:
                        div_flag = 2
                        div_index2 = index
                    elif div_flag == 1 and comma_flag == 0 or div_flag == 2:
                        self.edit_entry.destroy()
                        self.active_edit_flag = 0
                        return
                   
            if div_flag == 1:
                if comma_flag == 1:
                    if div_index < comma_index:
                        arg = int(float(value[:div_index])*100/float(value[div_index:comma_index-1]))/100.0
                        value = str(arg)+value[comma_index-1:]
                    elif div_index > comma_index:
                        arg = int(float(value[comma_index+1:div_index])*100/float(value[div_index:]))/100.0
                        value = value[:comma_index+1]+str(arg)
                else:
                    arg = int(float(value[:div_index])*100/float(value[div_index:]))/100.0
                    value = str(arg)
            elif div_flag == 2: 
                arg1 = int(float(value[:div_index])*100/float(value[div_index:comma_index-1]))/100.0
                arg2 = int(float(value[comma_index:div_index2-1])*100/float(value[div_index2-1:]))/100.0
                value = str(arg1)+','+str(arg2)
            if value == '' or value == initial_value:
                self.edit_entry.destroy()
                self.active_edit_flag = 0
                return
            
            self.elements.set(self.rowid,column=(int(self.column[-1])-1),value=value)
            if self.mark_var.get() == 1:
                self.sel_point = [self.elements.item(self.rowid,"values")[1],self.elements.item(self.rowid,"values")[2]]
            self.graph_update()
        self.edit_entry.destroy()
        self.active_edit_flag = 0
class SleepableThreadManagerGUI:
    ui = None  # Main UI Window

    top = None  # Top UI frame
    bottom = None  # Bottom UI frame

    allow_scroll = True

    manager = None  # Sleepable thread manager

    iidList = []

    ui_update_thread = None  # UI Update thread

    thread_dropdown = None  # Dropdown to select threads
    function_dropdown = None  # Dropdown to select functions

    thread_selected = None  # Variable for the thread selection
    threads_selected = []
    function_selected = None  # Variable for the function selection

    function_menu = None
    selection_context_menu = None
    empty_selection_context_menu = None

    info_tree_view = None  # Tree view for thread info
    output_textbox = None  # Output textbox for the UI thread to write to

    def __init__(self):
        self.manager = SleepableThreadManager()

        self.ui = Tk()
        self.ui.title('Sleepable Thread Manager')
        self.ui.geometry('550x600')

        self.function_selected = StringVar(self.ui)
        self.thread_selected = StringVar(self.ui)

        self.thread_selected.set('Select a Thread...')
        self.function_selected.set('Select a Function...')

        # create all of the main containers
        self.top = Frame(self.ui, width=300, height=50, pady=5)
        self.bottom = Frame(self.ui, bg='orange', width=300, height=20, pady=0)

        # main window
        self.ui.grid_columnconfigure(
            0, weight=1)  # expand main column when main ui resizes
        self.top.grid(row=0, sticky="ew")  # Stick top frame to east/west
        self.bottom.grid(
            row=1,
            sticky="nsew")  # Stick bottom frame to north/south/easy/west
        self.ui.grid_rowconfigure(
            1, weight=1)  # Expand bottom panel when main ui resizes

        # top frame component config
        self.top.grid_rowconfigure(
            0, weight=1)  # Expand first row when top frame resizes
        self.top.grid_rowconfigure(
            1, weight=1)  # Expand second row when top frame resizes
        self.top.grid_columnconfigure(
            1, weight=1)  # Expand second column when top frame resizes

        # bottom frame component config
        self.bottom.grid_rowconfigure(
            0, weight=1)  # Expand row 1 when bottom frame resizes
        self.bottom.grid_rowconfigure(
            1, weight=1)  # Expand row 2 when bottom frame resizes
        self.bottom.grid_columnconfigure(
            0, weight=1)  # Expand column 1 when bottom frame resizes
        self.bottom.grid_columnconfigure(0, weight=1)

        # create widgets for top frame
        function_label = Label(self.top, text='Function name:')
        self.function_dropdown = OptionMenu(
            self.top, self.function_selected,
            *self.manager.function_mappings.keys())

        # layout the widgets in the top frame
        function_label.grid(row=1, column=0)
        self.function_dropdown.grid(row=1, column=1, columnspan=3, sticky="ew")

        # create widgets for bottom frame
        self.selection_context_menu = Menu(self.info_tree_view)
        createMultiple = Menu(self.info_tree_view)
        functionMenu = Menu(self.selection_context_menu)
        functionMenu.add_command(
            label='Square', command=lambda: self.set_thread_function('Square'))
        functionMenu.add_command(
            label='Cube', command=lambda: self.set_thread_function('Cube'))

        self.selection_context_menu.add_cascade(label='Create...',
                                                menu=createMultiple)
        self.selection_context_menu.add_cascade(label='Set function...',
                                                menu=functionMenu)

        self.selection_context_menu.add_command(label='Start',
                                                command=self.start_thread)
        self.selection_context_menu.add_command(label='Sleep',
                                                command=self.sleep_thread)
        self.selection_context_menu.add_command(label='Wake',
                                                command=self.wake_thread)
        self.selection_context_menu.add_command(label='Stop',
                                                command=self.stop_thread)
        self.selection_context_menu.add_command(label='Restart',
                                                command=self.restart_thread)
        self.selection_context_menu.add_command(label='Remove',
                                                command=self.remove_thread)

        self.empty_selection_context_menu = Menu(self.info_tree_view)

        createMultiple.add_command(label='1', command=self.create_thread)
        createMultiple.add_command(
            label='5', command=lambda: self.create_thread(amount=5))
        createMultiple.add_command(
            label='10', command=lambda: self.create_thread(amount=10))
        createMultiple.add_command(
            label='20', command=lambda: self.create_thread(amount=20))

        self.empty_selection_context_menu.add_cascade(label='Create',
                                                      menu=createMultiple)

        self.info_tree_view = Treeview(self.bottom,
                                       columns=('Function', 'Status'))
        self.info_tree_view.heading('#0', text='Thread Name')
        self.info_tree_view.heading('#1', text='Function Name')
        self.info_tree_view.heading('#2', text='Status')
        self.info_tree_view.column('#0', width=100, stretch=NO)
        self.info_tree_view.column('#1', width=75)
        self.info_tree_view.column('#2', width=100, stretch=NO)
        self.info_tree_view.bind('<Button-3>', self.popup)
        self.output_textbox = Text(self.bottom,
                                   background="white",
                                   font=("Helvetica", 8))

        self.output_scrollbar = Scrollbar(self.bottom,
                                          command=self.output_textbox.yview)
        self.info_scrollbar = Scrollbar(self.bottom,
                                        command=self.info_tree_view.yview)

        # layout for the widgets in the bottom frame
        self.info_tree_view.grid(row=0, column=0, sticky='nsew')
        self.info_scrollbar.grid(row=0, column=1, sticky="nse")
        self.info_tree_view.config(yscrollcommand=self.info_scrollbar.set)

        self.output_textbox.grid(row=1, column=0, sticky='nsew')
        self.output_scrollbar.grid(row=1, column=1, sticky="nse")
        self.output_textbox.config(yscrollcommand=self.output_scrollbar.set)

        self.ui_update_thread = SleepableThread(work_wait=0.5)
        self.ui_update_thread.set_thread_work(self.refresh_output)
        self.ui_update_thread.start_thread()

        # Mainloop
        self.ui.mainloop()

    # UI refresh
    def refresh_tree_view(self):
        self.info_tree_view.delete(*self.info_tree_view.get_children())
        for item in self.manager.threads.items():
            self.info_tree_view.insert(
                '',
                'end',
                text=item[0],
                values=(str(item[1].work_function),
                        item[1].thread_state_mappings[item[1].thread_state]))

    def refresh_output(self):
        # function passed to ui thread, change to labels/gridview? need independent message queue on threads
        if self.manager.functions.MessageQueue.__len__() > 0:
            while self.manager.functions.MessageQueue.__len__() != 0:
                item = self.manager.functions.MessageQueue.pop()
                if len(item) >= 400:
                    raise Exception('Output too large')
                else:
                    self.output_textbox.delete('1.0', END)
                    self.output_textbox.insert(END, '{}\n'.format(item))
                    if self.manager.thread_stats(
                    )[1] > 0 and self.allow_scroll:
                        self.output_textbox.see('end')

    def popup(self, event):
        self.allow_scroll = False
        #iid = self.info_tree_view.identify_row(event.y)
        self.iidList = self.info_tree_view.selection()
        if self.iidList:
            if self.iidList > 0:
                for i in self.iidList:
                    self.threads_selected.append(
                        self.info_tree_view.item(i)['text'])
            # self.info_tree_view.selection_set(iid)
            # self.thread_selected.set(self.info_tree_view.item(iid)['text'])
            self.selection_context_menu.post(event.x_root, event.y_root)
        else:
            self.empty_selection_context_menu.post(event.x_root, event.y_root)
            pass
        self.manager.functions.MessageQueue = []
        self.allow_scroll = True

    # Button functions
    def create_thread(self, amount=1):
        i = 0
        while i != amount:
            self.manager.control(command='create')
            i += 1
        self.refresh_tree_view()

    def remove_thread(self):
        while self.threads_selected.__len__() != 0:
            self.manager.control(thread=self.threads_selected.pop(),
                                 command='remove')
        self.refresh_tree_view()

    def start_thread(self):
        while self.threads_selected.__len__() != 0:
            self.manager.control(thread=self.threads_selected.pop(),
                                 command='start')
        self.refresh_tree_view()

    def restart_thread(self):
        while self.threads_selected.__len__() != 0:
            self.manager.control(thread=self.threads_selected.pop(),
                                 command='restart')
        self.refresh_tree_view()

    def sleep_thread(self):
        while self.threads_selected.__len__() != 0:
            self.manager.control(thread=self.threads_selected.pop(),
                                 command='sleep')
        self.refresh_tree_view()

    def wake_thread(self):
        while self.threads_selected.__len__() != 0:
            self.manager.control(thread=self.threads_selected.pop(),
                                 command='wake')
        self.refresh_tree_view()

    def stop_thread(self):
        while self.threads_selected.__len__() != 0:
            self.manager.control(thread=self.threads_selected.pop(),
                                 command='stop')
        self.refresh_tree_view()

    def set_thread_function(self, funct):
        while self.threads_selected.__len__() != 0:
            self.manager.set_function(self.threads_selected.pop(), funct)
        self.refresh_tree_view()
Esempio n. 29
0
    def initUI_main(self):
        self.parent.title("Personal Helper")
        self.pack(fill=BOTH, expand=True)

        self.columnconfigure(0, weight=1)
        self.columnconfigure(7, weight=1)
        self.columnconfigure(5, pad=10)
        self.columnconfigure(3, pad=10)
        self.columnconfigure(1, weight=3)
        self.rowconfigure(0, weight=0)
        self.rowconfigure(5, weight=1)
        self.rowconfigure(5, pad=7)
        self.rowconfigure(6, pad=6)

        lbl = Label(self, text="Windows")
        lbl.grid(sticky=W + N, pady=4, padx=5)

        check_box = {"work": IntVar(), "boost": IntVar()}

        check1 = Checkbutton(self,
                             text="work-Mode",
                             variable=check_box["work"])
        check1.grid(row=7, column=0)

        check2 = Checkbutton(self,
                             text="boost games",
                             variable=check_box["boost"])
        check2.grid(row=7, column=1)

        ### old version, may be used again later
        area = Treeview(self)
        area['show'] = 'headings'
        area["columns"] = ("one", "two", "three", "four")
        area.column("one", width=10)
        area.column("two", width=10)
        area.column("three", width=10)
        area.column("four", width=10)
        area.heading("one", text="process name")
        area.heading("two", text="Priority")
        area.heading("three", text="PID")
        area.heading("four", text="Usage")
        ###about this part
        #area.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N)
        #######

        #comboboxes and relevant buttons

        self.block_drop = Combobox(self, postcommand=self.update_blocked)
        self.block_drop['values'] = working_bans
        self.block_drop.current(0)
        self.block_drop.grid(row=1, column=1, pady=1)
        self.entry = Entry(self)
        self.entry.insert(0, "enter to block")
        self.entry.grid(row=1, column=4)

        block_btn_remv = Button(self,
                                text="Remove",
                                command=lambda: remove_from_list(
                                    working_bans, self.block_drop.get()))
        block_btn_remv.grid(row=1, column=2)

        block_btn_add = Button(
            self,
            text="Add",
            command=lambda: add_to_list(working_bans, self.entry.get(), self.
                                        entry, defults["block"]))
        block_btn_add.grid(row=1, column=3)

        ############
        #boosted combo
        self.boost_drop = Combobox(self, postcommand=self.update_boosted)
        self.boost_drop['values'] = boosted
        self.boost_drop.current(0)
        self.boost_drop.grid(row=2, column=1, pady=1)
        self.entry2 = Entry(self)
        self.entry2.insert(0, "enter to buff priority")
        self.entry2.grid(row=2, column=4, pady=4)

        boost_btn_remv = Button(
            self,
            text="Remove",
            command=lambda: remove_from_list(boosted, self.boost_drop.get()))
        boost_btn_remv.grid(row=2, column=2)

        boost_btn_add = Button(
            self,
            text="Add",
            command=lambda: add_to_list(boosted, self.entry2.get(), self.
                                        entry2, defults["boost"]))
        boost_btn_add.grid(row=2, column=3)

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

        #degraded combo
        self.deg_drop = Combobox(self, postcommand=self.update_degraded)
        self.deg_drop['values'] = degraded
        self.deg_drop.current(0)
        self.deg_drop.grid(row=3, column=1, pady=1)
        self.entry3 = Entry(self)
        self.entry3.insert(0, "enter to lower priority")
        self.entry3.grid(row=3, column=4, pady=4)

        deg_btn_remv = Button(
            self,
            text="Remove",
            command=lambda: remove_from_list(degraded, self.deg_drop.get()))
        deg_btn_remv.grid(row=3, column=2)

        deg_btn_add = Button(
            self,
            text="Add",
            command=lambda: add_to_list(degraded, self.entry3.get(), self.
                                        entry3, defults["degrade"]))
        deg_btn_add.grid(row=3, column=3)

        ####
        #music combo

        self.music_drop = Combobox(self, postcommand=self.update_music)
        self.music_drop['values'] = music_list.keys()
        self.music_drop.current(0)
        self.music_drop.grid(row=4, column=1, pady=1)
        self.entry4 = Entry(self)
        self.entry4.insert(0, "enter url")
        self.entry4.grid(row=4, column=5)
        self.entry5 = Entry(self)
        self.entry5.insert(0, "enter song's name")
        self.entry5.grid(row=4, column=4)

        music_btn_remv = Button(self,
                                text="Remove",
                                command=lambda: remove_from_list(
                                    music_list, self.music_drop.get()))
        music_btn_remv.grid(row=4, column=2)

        music_btn_add = Button(
            self,
            text="Add",
            command=lambda: add_music(music_list, self.entry5.get(
            ), self.entry4.get(), self.entry5, defults["music"]))
        music_btn_add.grid(row=4, column=3)

        abtn = Button(self, text="Activate", command=scan_computer_programs)
        abtn.grid(row=1, column=5, sticky=E)

        sbtn = Button(self, text="Stop", command=lambda: stop_running())
        sbtn.grid(row=2, column=5, pady=6, sticky=E)

        cbtn = Button(self, text="Close", command=quit)
        cbtn.grid(row=3, column=5, pady=4, sticky=E)

        hbtn = Button(self, text="Save", command=save_lists)
        hbtn.grid(row=6, column=0, sticky=W)

        tsbtn = Button(self,
                       text="TaskManager",
                       command=lambda: os.system("TaskManager\pyProcMon.py"))
        tsbtn.grid(row=3, column=5, sticky=E)

        obtn = Button(
            self,
            text="start",
            command=lambda: call_running(area, threads["procs"], check_box))
        obtn.grid(row=6, column=5, sticky=E)
Esempio n. 30
0
	def __init__(self, parent, controller):
		Frame.__init__(self, parent)
		
		global codigo, descripcion, tree, busqueda, info
		global e3
		
		lupa = PhotoImage(file='img/lupa.png')
		
		codigo = StringVar()
		descripcion = StringVar()
		busqueda = StringVar()
		info = IntVar()
		
		#WIDGETS
		
		#=========================== HEADER ============================
		
		self.titleL = Label(self, text="CUENTAS CONTABLES", font="bold")
		self.titleL.pack(pady=20, side=TOP)
		
		#=========================== WRAPPER ===========================
		
		self.wrapper = Frame (self)
		self.wrapper.pack(side=TOP, fill=Y)
		#self.wrapper.pack(side=LEFT, fill=Y) #UBICA EL FORM A LA IZQ
		
		self.f0 = Frame(self.wrapper)
		self.f0.pack(pady=5, fill=X)#-----------------------------------
		
		l1 = Label (self.f0, text="Código:")
		l1.pack(side=LEFT)
		e1 = Entry (self.f0, textvariable=codigo, width=20)
		e1.pack(side=LEFT)
		e1.bind("<KeyRelease>", caps)
		e1.focus_set()
		
		self.f2 = Frame(self.wrapper)
		self.f2.pack(pady=5, fill=X)#-----------------------------------
		
		l2 = Label (self.f2, text="Descripción: ")
		l2.pack(side=LEFT)
		e2 = Entry (self.f2, textvariable=descripcion, width=60)
		e2.pack(side=LEFT, fill=X, expand=1)
		e2.bind("<KeyRelease>", caps)
		
		self.f3 = Frame(self.wrapper)
		self.f3.pack(pady=5, fill=X)#-----------------------------------
		
		b1 = Button (self.f3, text="Cargar", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=cargar)
		b1.pack(side=RIGHT)
		
		b2 = Button (self.f3, text="Agregar", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=agregar)
		b2.pack(side=RIGHT)
		
		#========================== TREEVIEW ===========================
		
		self.f4 = Frame(self.wrapper)
		self.f4.pack(pady=5, fill=X)#-----------------------------------
		
		tree = Treeview(self.f4, show="headings", columns=('col1','col2'))
		tree.pack(side=LEFT, fill=X, expand=1)
		tree.column('col1', width=0, anchor='center')
		tree.column('col2', width=150, anchor='w')
		
		tree.heading('col1', text='Código')
		tree.heading('col2', text='Descripción')
		
		self.scroll = Scrollbar(self.f4,orient=VERTICAL,command=tree.yview)
		tree.configure(yscrollcommand=self.scroll.set)
		
		self.f5 = Frame(self.wrapper)
		self.f5.pack(pady=5, fill=X)#-----------------------------------
		
		self.delete = Button (self.f5, text="Eliminar", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=borrar)
		self.delete.pack(side=RIGHT)
		
		e3 = Entry(self.f5, textvariable=busqueda)
		e3.pack(side=LEFT)
		e3.bind("<KeyRelease>", caps)
		
		b3 = Button(self.f5, text='BUSCAR', image=lupa, command=buscar)
		b3.image = lupa
		b3.pack(side=LEFT)
		
		R1 = Radiobutton(self.f5, text="Código", variable=info, value=1)
		R1.pack(side=LEFT)
		R2 = Radiobutton (self.f5, text="Desc", variable=info, value=2)
		R2.pack(side=LEFT)
		info.set(1)
Esempio n. 31
0
#使用Treeview组件实现表格功能
frame = Frame(root)
frame.place(x=0, y=10, width=680, height=380)

#滚动条
scrollBar = tkinter.Scrollbar(frame)

scrollBar.pack(side=tkinter.RIGHT, fill=tkinter.Y)
#Treeview组件,6列,显示表头,带垂直滚动条
tree = Treeview(frame,
                columns=('c1', 'c2', 'c3', 'c4', 'c5', 'c6'),
                show="headings",
                yscrollcommand=scrollBar.set)

#设置每列宽度和对齐方式
tree.column('c1', width=70, anchor='center')
tree.column('c2', width=40, anchor='center')
tree.column('c3', width=40, anchor='center')
tree.column('c4', width=120, anchor='center')
tree.column('c5', width=100, anchor='center')
tree.column('c6', width=90, anchor='center')

#设置每列表头标题文本
tree.heading('c1', text='姓名')
tree.heading('c2', text='性别')
tree.heading('c3', text='年龄')
tree.heading('c4', text='部门')
tree.heading('c5', text='电话')
tree.heading('c6', text='QQ')
tree.pack(side=tkinter.LEFT, fill=tkinter.Y)
class LobbyUI(Frame):
    """
    Sudoku multiplayer lobby UI class.
    In case of incorrect inputs error messages are shown.
    """
    action = None

    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.row, self.col = -1, -1
        self.__initUI()

    def __initUI(self):
        """
        Initialize UI with a list and required entry fields and submit buttons."""

        self.parent.title('Multiplayer Game')
        self.pack(fill=BOTH, expand=1)

        self.lobby_list = Treeview(self, columns=('room', 'players'))
        self.lobby_list['show'] = 'headings'
        self.lobby_list.heading('room', text='Room ID')
        self.lobby_list.column('room', width=250, anchor=CENTER)
        self.lobby_list.heading('players', text='Players')
        self.lobby_list.column('players', width=100, anchor=CENTER)
        self.lobby_list.grid(row=1,
                             column=0,
                             columnspan=2,
                             rowspan=2,
                             padx=20,
                             pady=(10, 0))

        self.connect_lobby = Button(self,
                                    text='Joining Sudoku\n Solving Session',
                                    command=self.__connect_lobby)
        self.connect_lobby.grid(row=3, column=1, pady=(0, 10))

        Label(self,
              text='Creating new Sudoku\n solving session:').grid(row=4,
                                                                  column=0)

        self.max_players = Entry(self)
        self.max_players.grid(row=4, column=1)

        self.create_game = Button(self,
                                  text='Join new game',
                                  command=self.__create_game)
        self.create_game.grid(row=5, column=1)

    def __connect_lobby(self):
        """
        Handle lobby connection button."""
        LOG.debug('Lobby connect button has been pressed.')
        current_item = self.lobby_list.focus()
        selected_id = None

        if current_item is not None and current_item.strip() != '':
            # Select game column value from item values dictionary.
            selected_id = self.lobby_list.item(current_item)['values'][0]
            LOG.debug('Player wishes to join game ' + str(selected_id))

            if selected_id is not None:
                self.action = ('select', selected_id)
        else:
            tkMessageBox.showwarning(
                "Connection error",
                "Please select a game from the lobby to join.")

    def __create_game(self):
        """
        Create game with some number of max players."""
        max_ok = False

        try:
            max_count = int(self.max_players.get())
        except (ValueError, TypeError):
            max_count = -1
            tkMessageBox.showwarning("Input error",
                                     "Max player count has to be an integer.")

        if isinstance(max_count, int):
            if max_count >= 2:
                max_ok = True
                LOG.debug('Ok max player count.')
            else:
                tkMessageBox.showwarning(
                    "Input error", "Max player count has to be larger than 2.")
                LOG.error('Bad max count.')

        if max_ok:
            self.action = ('create', max_count)

    def populate_list(self, games):
        """
        Method to re-populate the lobby list every poll.
        Additionally retains the focused line during polling.
        :param games:
        """
        previous_selection = self.lobby_list.selection()
        prev_item = None
        if len(previous_selection) > 0:
            prev_item = self.lobby_list.item(previous_selection[0])

        self.lobby_list.delete(*self.lobby_list.get_children())
        for game in games:
            self.lobby_list.insert('',
                                   'end',
                                   values=(str(game[0]),
                                           str(game[1]) + '/' + str(game[2])))

        if prev_item is not None:
            for item in self.lobby_list.get_children():
                if self.lobby_list.item(item) == prev_item:
                    self.lobby_list.selection_set(item)
                    self.lobby_list.focus(item)
Esempio n. 33
0
 def mostra_historic(self):
     popup = Toplevel()
     agenda_historic = Treeview(
         popup,
         columns=["nom", "tel", "email", "path", "accio", "data"],
         show="headings")
     agenda_historic.heading("nom", text="Nom")
     agenda_historic.heading("tel", text="Telefon")
     agenda_historic.heading("email", text="Email")
     agenda_historic.heading("path", text="Path")
     agenda_historic.heading("accio", text="Acció")
     agenda_historic.heading("data", text="Data")
     agenda_historic.column("nom",
                            minwidth=0,
                            width=150,
                            stretch=True,
                            anchor="c")
     agenda_historic.column("tel",
                            minwidth=0,
                            width=100,
                            stretch=True,
                            anchor="c")
     agenda_historic.column("email",
                            minwidth=0,
                            width=150,
                            stretch=True,
                            anchor="c")
     agenda_historic.column("path",
                            minwidth=0,
                            width=200,
                            stretch=True,
                            anchor="c")
     agenda_historic.column("accio",
                            minwidth=0,
                            width=100,
                            stretch=True,
                            anchor="c")
     agenda_historic.column("data",
                            minwidth=0,
                            width=150,
                            stretch=True,
                            anchor="c")
     agenda_historic.grid(row=0, column=0, padx=5, pady=5)
     self.cursor.execute("select * from HISTORIC ORDER BY data DESC;")
     dades = self.cursor.fetchall()
     for data_usuari in dades:
         agenda_historic.insert('', 'end', values=data_usuari)
Esempio n. 34
0
class CommSearch(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent        
        self.initUI()
        
    def initUI(self):

        self.entries_found = []

        self.parent.title("Search your command cards")
        self.style = Style()
        self.style.theme_use("default")        
        self.pack()
        
        self.input_title = Label(self, text="Enter your command below")
        self.input_title.grid(row=0, columnspan=2)
        self.input_box = Entry(self, width=90)
        self.input_box.grid(row=1, column=0)
        self.input_box.focus()
        self.input_box.bind("<Key>", self.onUpdateSearch)
        self.search_btn = Button(self, text="Search", command=self.onSearch)
        self.search_btn.grid(row=1, column=1)
        self.output_box = Treeview(self, columns=("Example"))
        ysb = Scrollbar(self, orient='vertical', command=self.output_box.yview)
        xsb = Scrollbar(self, orient='horizontal', command=self.output_box.xview)
        self.output_box.configure(yscroll=ysb.set, xscroll=xsb.set)
        self.output_box.heading('Example', text='Example', anchor='w')
        self.output_box.column("#0",minwidth=0,width=0, stretch=NO)
        self.output_box.column("Example",minwidth=0,width=785)
        self.output_box.bind("<Button-1>", self.OnEntryClick)
        self.output_box.grid(row=3, columnspan=2)
        self.selected_box = Text(self, width=110, height=19)
        self.selected_box.grid(row=4, columnspan=2)
        self.gotoadd_btn = Button(self, text="Go to Add", command=self.onGoToAdd)
        self.gotoadd_btn.grid(row=5)

    def OnEntryClick(self, event):
        try:
            item = self.output_box.selection()[0]
        except IndexError:
            pass
        entry_title = self.output_box.item(item,"value")
        for item in self.entries_found:
            if str(entry_title) == str("('" + item.title.strip('\n') + "',)"):
                self.selected_box.delete(0.1, END)
                self.selected_box.insert(END, item.text + '\n')

    def onUpdateSearch(self, key):
    # Somehow calling self.onSearch() does not register last key
    # And we need to correct "special chars"
        global entries, entries_map
        text_entries = ""
        for item in self.output_box.get_children():
            self.output_box.delete(item)		
    # ...like, for instance, deleting last character
        if key.char == '\b':
            search_terms = str(self.input_box.get()[:-1])
        else: 
            search_terms = str(self.input_box.get() + key.char)
        self.entries_found = []
        self.entries_found = data.Search(search_terms,entries,entries_map)
        for item in range(len(self.entries_found)):
            aux = self.output_box.insert('', 'end', '', value=[self.entries_found[item].title.split('\n')[0]])

			
    def onSearch(self):
        global entries, entries_map
        text_entries = ""
        for item in self.output_box.get_children():
            self.output_box.delete(item)
        search_terms = str(self.input_box.get())
        for item in data.Search(search_terms,entries,entries_map):
            self.output_box.insert('', 'end', '', value=[self.entries_found[item].title.split('\n')[0]])
			
    def onGoToAdd(self):
        newroot = Tk()
        newcomm = CommAdd(newroot)
        newroot.geometry("800x600+0+0")
        newroot.mainloop()
class Gui(Frame):
    """ Gui class for Graphical User Interface"""
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.searcher = Searcher()
        self.initUI()

    def initUI(self):
        self.pack(fill=BOTH, expand=True)
        Grid.columnconfigure(self, 0, weight=1)
        Label(self,
              text='Classroom Finder',
              font=('Arial', 20, 'bold'),
              bg='cyan',
              fg='white').grid(sticky=W + E,
                               columnspan=3)  # classroom finder header
        Label(self, text='Url:').grid(column=0, row=1, pady=10, padx=(50, 0))
        self.urlentry = Entry(self, width=100)  # url entry to get url
        self.urlentry.grid(column=1, row=1, padx=(0, 80))
        self.color_label = Label(
            self, bg='red', width=10)  # color label to make red,yellow,green
        self.color_label.grid(column=0,
                              row=2,
                              sticky=E,
                              columnspan=2,
                              padx=(120),
                              pady=(0, 40))
        self.fetchbtn = Button(self,
                               text='Fetch',
                               height=2,
                               width=10,
                               command=self.dynamic)  # fetch button
        self.fetchbtn.grid(column=1,
                           row=2,
                           sticky=E,
                           padx=(0, 30),
                           pady=(10, 50))
        Label(self,
              text='Filters',
              bg='cyan',
              fg='white',
              font=('Arial', 20, 'bold'),
              width=10).grid(column=0, row=3, padx=10)
        self.frame = Frame(self, borderwidth=3,
                           relief=GROOVE)  # frame to keep filters part
        self.frame.grid(column=0,
                        row=4,
                        columnspan=3,
                        sticky=W + E + S + N,
                        pady=10,
                        padx=10)
        Label(self.frame, text='Where am I?').grid(sticky=W)
        self.where_combo = Combobox(self.frame,
                                    state='readonly')  # where am i combobox
        self.where_combo.grid(column=1, row=0, pady=20)
        self.where_combo.bind(
            '<<ComboboxSelected>>',
            self.change_build)  # to update room button wrt where combo
        Label(self.frame, text='Room').grid(sticky=W)
        self.room_combo = Combobox(self.frame,
                                   state='readonly')  # rooms combobox
        self.room_combo.grid(column=1, row=1)
        Label(self.frame, text='Start').grid(sticky=W)
        self.start_combo = Combobox(self.frame, state='readonly',
                                    width=7)  # start time combobox
        self.start_combo.grid(column=1, row=2, pady=20, sticky=W)
        Label(self.frame, text='End').grid(column=2, row=2, sticky=W)
        self.end_combo = Combobox(self.frame, state='readonly',
                                  width=7)  # end time combobox
        self.end_combo.grid(column=3, row=2, sticky=W)
        Label(self.frame, text='Day').grid(sticky=W)
        self.day_combo = Combobox(self.frame,
                                  state='readonly')  # days combobox
        self.day_combo.grid(column=1, row=3, pady=(0, 20))
        self.search = Button(self.frame,
                             text='Search',
                             width=10,
                             height=2,
                             command=self.add_treeview)  # seach button
        self.search.grid(padx=(0, 50), columnspan=2)
        Label(self.frame, text='Classroom results', bg='gray',
              fg='white').grid(sticky=N + E + W,
                               column=4,
                               row=0,
                               rowspan=5,
                               padx=(55, 0))
        self.scroll = Scrollbar(
            self.frame, orient='vertical')  # vertical scrollbar for treeview
        self.tree = Treeview(self.frame,
                             columns=('', '', '', '', ''),
                             selectmode='extended',
                             show='headings')
        listofcolumn = [
            'Room', 'Traffic', 'Availability %', 'Closeness', 'Overall Score'
        ]  # colums to treeview
        counter = 1
        for column in listofcolumn:
            self.tree.column('#' + str(counter), width=90)  # to resize columns
            self.tree.heading('#' + str(counter), text=column,
                              anchor=CENTER)  # to set headings
            counter += 1
        self.scroll.config(command=self.tree.yview)
        self.tree.config(yscrollcommand=self.scroll.set)
        self.tree.grid(column=4, row=0, rowspan=5, padx=(40, 0), pady=(30, 0))
        self.scroll.grid(column=5,
                         row=0,
                         rowspan=5,
                         sticky=N + S,
                         pady=(30, 0))
        self.urlentry.insert(
            0,
            'https://www.sehir.edu.tr/en/announcements/2018-2019-bahar-donemi-ders-programi'
        )

    def dynamic(self):
        self.color_label.configure(
            bg='yellow'
        )  # make color label yellow at the beginning of the process
        self.update_idletasks()
        self.searcher.fetch(self.urlentry.get(
        ))  # to call fetch method in searcher class to start process
        self.color_label.configure(bg='green')
        room_num = [
            room.room_num
            for room in self.searcher.buildings['ACAD BUILD 1'].classrooms
        ]
        self.where_combo.configure(
            values=[build for build in sorted(self.searcher.buildings)])
        self.where_combo.current(
            0)  # to get values in combobox and set value 0 as a default
        self.room_combo.configure(values=[room for room in sorted(room_num)])
        self.room_combo.current(0)
        self.start_combo.configure(
            values=["{}:00".format(time) for time in range(9, 20)])
        self.start_combo.current(
            0)  # start and end combo both have the same interval from 9 to 19
        self.end_combo.configure(
            values=["{}:00".format(time) for time in range(9, 20)])
        self.end_combo.current(len(self.end_combo['values']) - 1)
        self.day_combo.configure(
            values=["Monday", 'Tuesday', 'Wednesday', 'Thursday', 'Friday'])
        self.day_combo.current(0)

    def change_build(
            self, event
    ):  # when where am i combobox chance, room combobox also chance
        building = self.where_combo.get()
        room_num = [
            room.room_num
            for room in self.searcher.buildings[building].classrooms
        ]
        self.room_combo.configure(values=[room for room in sorted(room_num)])
        self.room_combo.current(0)

    def add_treeview(self):  # to add scores in treeview
        self.tree.delete(*self.tree.get_children())
        self.overall_scores = self.searcher.search(
            self.day_combo.get(),
            self.where_combo.get(), self.room_combo.get(),
            self.start_combo.get(), self.end_combo.get()
        )  # key operator for the sorted dict by values which overall score
        for item, score in sorted(self.overall_scores.items(),
                                  key=operator.itemgetter(1),
                                  reverse=True):
            if item.availability_score == 0:  # to avoid from availability score 0
                continue
            room = str(item.classroom.building_num) + str(
                item.classroom.room_num)
            self.tree.insert('',
                             'end',
                             values=(room, item.traffic_score,
                                     item.availability_score,
                                     item.closeness_score, score))
Esempio n. 36
0
def start_browse_campers():
    global root
    root = Tk()
    root.title("Browse Campers")
    root.minsize(width=500, height=500)

    browse_camps_tree = Treeview(root)
    browse_camps_tree["columns"] = ("Camper ID", "First Name", "Last Name",
                                    "Date of Birth", "Gender", "Address",
                                    "Camps IDs", "Bunkhouses IDs", "Teams IDs")
    browse_camps_tree.column("Camper ID", width=100)
    browse_camps_tree.column("First Name", width=100)
    browse_camps_tree.column("Last Name", width=100)
    browse_camps_tree.column("Date of Birth", width=100)
    browse_camps_tree.column("Gender", width=100)
    browse_camps_tree.column("Address", width=100)
    browse_camps_tree.column("Camps IDs", width=100)
    browse_camps_tree.column("Bunkhouses IDs", width=100)
    browse_camps_tree.column("Teams IDs", width=100)
    browse_camps_tree.heading("Camper ID", text="Camper ID")
    browse_camps_tree.heading("First Name", text="First Name")
    browse_camps_tree.heading("Last Name", text="Last Name")
    browse_camps_tree.heading("Date of Birth", text="Date of Birth")
    browse_camps_tree.heading("Gender", text="Gender")
    browse_camps_tree.heading("Address", text="Address")
    browse_camps_tree.heading("Camps IDs", text="Camps IDs")
    browse_camps_tree.heading("Bunkhouses IDs", text="Bunkhouses IDs")
    browse_camps_tree.heading("Teams IDs", text="Teams IDs")

    index = 0
    for camper_id in Camper.get_all_ids():
        current_camper = Camper(camper_id[0])
        data = current_camper.select_camper()
        data2 = Bunkhouse.select_camp_team_bunkhouse(camper_id[0])
        browse_camps_tree.insert('',
                                 index,
                                 text="row" + str(index + 1),
                                 values=(camper_id, data[0], data[1], data[2],
                                         data[3], data[4], data2[0][:-2],
                                         data2[2][:-2], data2[1][:-2]))
        index += 1

    browse_camps_tree.pack()

    exit_browse_camp_bt = Button(root,
                                 text="Exit",
                                 width=30,
                                 command=exit_browse_camp_bt_handler)
    exit_browse_camp_bt.pack(expand=True)
    root.mainloop()
Esempio n. 37
0
    def show(frame, iterator):
        """Выводит на экран выборку, заданную в iterator"""

        scrollbar = Scrollbar(frame)
        tree = Treeview(frame, selectmode='none', padding=3,
                                    style='Custom.Treeview', height=REPORT_HEIGHT,
                                    yscrollcommand=scrollbar.set)
        tree.pack(side=LEFT, fill=BOTH, expand=YES)
        scrollbar.config(command=tree.yview)
        scrollbar.pack(side=LEFT, fill=Y)

        tree.tag_configure('1', font=('Verdana', FONT_SIZE_REPORT))
        tree.tag_configure('2', font=('Verdana', FONT_SIZE_REPORT),
                                                           background='#f5f5ff')
        tree.tag_configure('red1', font=('Verdana', FONT_SIZE_REPORT),
                                                               foreground='red')
        tree.tag_configure('red2', font=('Verdana', FONT_SIZE_REPORT),
                                         background='#f5f5ff', foreground='red')
        tree.tag_configure('grey1', font=('Verdana', FONT_SIZE_REPORT),
                                                              foreground='#dddddd')
        tree.tag_configure('grey2', font=('Verdana', FONT_SIZE_REPORT),
                                        background='#f5f5ff', foreground='#dddddd')

        Style().configure('Custom.Treeview', rowheight=FONT_SIZE_REPORT*2)

        columns = ['#' + str(x + 1) for x in range(4)]
        tree.configure(columns=columns)

        for q in range(len(header)):
            tree.heading('#%d' % (q + 1), text=header[q], anchor='w')
            tree.column('#%d' % (q + 1), width=REPORT_SCALE * col_width[q + 1],
                                                                     anchor='w')
        tree.heading('#0', text='', anchor='w')
        tree.column('#0', width=0, anchor='w', minwidth=0)

        flag = True
        for item in iterator:
            if not item.calculation:
                col = []
                col.append(add_s(item.cathegory.name if item.cathegory
                                                                 else u'-Нет-'))
                col.append(add_s(item.name))
                storage = queries.items_in_storage(item)
                col.append(add_s(storage))
                col.append(add_s(item.measure))
                if int(storage) > 0:
                    flag = not flag
                    if flag:
                        tree.insert('', 'end', text='', values=col, tag='2')
                    else:
                        tree.insert('', 'end', text='', values=col, tag='1')
                elif storage == '0':
                    flag = not flag
                    if flag:
                        tree.insert('', 'end', text='', values=col, tag='grey2')
                    else:
                        tree.insert('', 'end', text='', values=col, tag='grey1')
                else:
                    flag = not flag
                    if flag:
                        tree.insert('', 'end', text='', values=col, tag='red2')
                    else:
                        tree.insert('', 'end', text='', values=col, tag='red1')
Esempio n. 38
0
class XML_Viwer(Frame):

    def __init__(self, master, xml=None, heading_text=None, heading_anchor=None, padding=None, cursor=None, takefocus=None, style=None):
        Frame.__init__(self, master, class_="XML_Viwer")

        self._vsb = Scrollbar(self, orient=VERTICAL)
        self._hsb = Scrollbar(self, orient=HORIZONTAL)

        kwargs = {}
        kwargs["yscrollcommand"] = lambda f, l: autoscroll(self._vsb, f, l)
        kwargs["xscrollcommand"] = lambda f, l: autoscroll(self._hsb, f, l)
       
        if style is not None:
            kwargs["style"] = style
            
        if padding is not None:
            kwargs["padding"] = padding
            
        if cursor is not None:
            kwargs["cursor"] = cursor
            
        if takefocus is not None:
            kwargs["takefocus"] = takefocus

        self._treeview = Treeview(self, **kwargs)
        
        if heading_text is not None:
            if heading_anchor is not None:
                self._treeview.heading("#0", text=heading_text, anchor=heading_anchor)
            else:
                self._treeview.heading("#0", text=heading_text)

        self._treeview.bind("<<TreeviewOpen>>", self._on_open)
        self._treeview.bind("<<TreeviewClose>>", self._on_close)
        
        # Without this line, horizontal scrolling doesn't work properly.
        self._treeview.column("#0", stretch= False)

        self._vsb['command'] = self._treeview.yview
        self._hsb['command'] = self._treeview.xview

        self._treeview.grid(column=0, row=0, sticky=N+S+W+E)
        self._vsb.grid(column=1, row=0, sticky=N+S)
        self._hsb.grid(column=0, row=1, sticky=E+W)
        
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(0, weight=1)

        self._element_tree = None
        self._item_ID_to_element = {}

        if xml is not None:
            self.parse_xml(xml)

    def _on_open(self, event):
        item_ID = self._treeview.focus()
        if item_ID not in self._item_ID_to_element: return

        node = self._item_ID_to_element[item_ID]

        self._treeview.item(item_ID, text = self._repr_of_openning_tag(node))
        
    def _on_close(self, event):
        item_ID = self._treeview.focus()
        if item_ID not in self._item_ID_to_element: return

        node = self._item_ID_to_element[item_ID]
        
        text = self._repr_of_openning_tag(node) + self._repr_of_closing_tag(node)
        self._treeview.item(item_ID, text = text)

    def parse_xml(self, xml):
        self._element_tree = ET.ElementTree(ET.fromstring(xml))
        
        self.clear()
        self._walk_xml(self._element_tree.getroot())
        
    @property
    def element_tree(self):
        return self._element_tree
    
    @element_tree.setter
    def element_tree(self, element_tree):
        self._element_tree = element_tree
        
        self.clear()
        self._walk_xml(element_tree.getroot())   
        
    def clear(self):
        self._item_ID_to_element = {}
        self._treeview.delete(*self._treeview.get_children())
        
    def _repr_of_openning_tag(self, node):
        text = "<" + node.tag

        attrs = node.attrib
        
        # list function is here necessary to provide support to Python 3
        a_names = list(attrs.keys())
        a_names.sort()

        for a_name in a_names:
            text += ' %s="' % a_name
            text += attrs[a_name]
            text += '"'

        text += ">"
        return text
        
    def _repr_of_closing_tag(self, node):
        return "</%s>"%node.tag

    def _walk_xml(self, node, depth=0, parent=""):
        text = self._repr_of_openning_tag(node) + self._repr_of_closing_tag(node)

        item = self._treeview.insert(parent, END, text = text)
        self._item_ID_to_element[item] = node
        
        if node.text:
            text = node.text.strip()
            if text != "":
                for line in text.splitlines():
                    self._treeview.insert(item, END, text = line)

        child_nodes = sorted(list(node), key=attrgetter('tag'))
        for child_node in node:
            self._walk_xml(child_node, depth+1, parent=item)

        
        if node.tail:
            tail = node.tail.strip()
            if tail != "":
                for line in tail.splitlines():
                    self._treeview.insert(parent, END, text = line)
Esempio n. 39
0
class Multicolumn_Listbox(object):
    _style_index = 0

    class List_Of_Rows(object):
        def __init__(self, multicolumn_listbox):
            self._multicolumn_listbox = multicolumn_listbox

        def data(self, index):
            return self._multicolumn_listbox.row_data(index)
            
        def get(self, index):
            return Row(self._multicolumn_listbox, index)

        def insert(self, data, index=None):
            self._multicolumn_listbox.insert_row(data, index)

        def delete(self, index):
            self._multicolumn_listbox.delete_row(index)

        def update(self, index, data):
            self._multicolumn_listbox.update_row(index, data)

        def select(self, index):
            self._multicolumn_listbox.select_row(index)

        def deselect(self, index):
            self._multicolumn_listbox.deselect_row(index)

        def set_selection(self, indices):
            self._multicolumn_listbox.set_selection(indices)

        def __getitem__(self, index): 
            return self.get(index)

        def __setitem__(self, index, value): 
            return self._multicolumn_listbox.update_row(index, value)

        def __delitem__(self, index): 
            self._multicolumn_listbox.delete_row(index)

        def __len__(self): 
            return self._multicolumn_listbox.number_of_rows

    class List_Of_Columns(object):
        def __init__(self, multicolumn_listbox):
            self._multicolumn_listbox = multicolumn_listbox
        
        def data(self, index):
            return self._multicolumn_listbox.get_column(index)

        def get(self, index):
            return Column(self._multicolumn_listbox, index)

        def delete(self, index):
            self._multicolumn_listbox.delete_column(index)

        def update(self, index, data):
            self._multicolumn_listbox.update_column(index, data)

        def __getitem__(self, index): 
            return self.get(index)

        def __setitem__(self, index, value): 
            return self._multicolumn_listbox.update_column(index, value)

        def __delitem__(self, index): 
            self._multicolumn_listbox.delete_column(index)

        def __len__(self): 
            return self._multicolumn_listbox.number_of_columns

    def __init__(self, master, columns, data=None, command=None, sort=True, select_mode=None, heading_anchor = CENTER, cell_anchor=W, style=None, height=None, padding=None, adjust_heading_to_content=False, stripped_rows=None, selection_background=None, selection_foreground=None, field_background=None, heading_font= None, heading_background=None, heading_foreground=None, cell_pady=2, cell_background=None, cell_foreground=None, cell_font=None, headers=True):

        self._stripped_rows = stripped_rows

        self._columns = columns
        
        self._number_of_rows = 0
        self._number_of_columns = len(columns)
        
        self.row = self.List_Of_Rows(self)
        self.column = self.List_Of_Columns(self)
        
        s = Style()

        if style is None:
            style_name = "Multicolumn_Listbox%s.Treeview"%self._style_index
            self._style_index += 1
        else:
            style_name = style
        
        style_map = {}
        if selection_background is not None:
            style_map["background"] = [('selected', selection_background)]
            
        if selection_foreground is not None:
            style_map["foeground"] = [('selected', selection_foreground)]

        if style_map:
            s.map(style_name, **style_map)

        style_config = {}
        if cell_background is not None:
            style_config["background"] = cell_background

        if cell_foreground is not None:
            style_config["foreground"] = cell_foreground

        if cell_font is None:
            font_name = s.lookup(style_name, "font")
            cell_font = nametofont(font_name)
        else:
            if not isinstance(cell_font, Font):
                if isinstance(cell_font, basestring):
                    cell_font = nametofont(cell_font)
                else:
                    if len(font) == 1:
                        cell_font = Font(family=cell_font[0])
                    elif len(font) == 2:
                        cell_font = Font(family=cell_font[0], size=cell_font[1])
                        
                    elif len(font) == 3:
                        cell_font = Font(family=cell_font[0], size=cell_font[1], weight=cell_font[2])
                    else:
                        raise ValueError("Not possible more than 3 values for font")
        
            style_config["font"] = cell_font
        
        self._cell_font = cell_font

        self._rowheight = cell_font.metrics("linespace")+cell_pady
        style_config["rowheight"]=self._rowheight

        if field_background is not None:
            style_config["fieldbackground"] = field_background

        s.configure(style_name, **style_config)

        heading_style_config = {}
        if heading_font is not None:
            heading_style_config["font"] = heading_font
        if heading_background is not None:
            heading_style_config["background"] = heading_background
        if heading_foreground is not None:
            heading_style_config["foreground"] = heading_foreground

        heading_style_name = style_name + ".Heading"
        s.configure(heading_style_name, **heading_style_config)

        treeview_kwargs = {"style": style_name}

        if height is not None:
            treeview_kwargs["height"] = height
            
        if padding is not None:
            treeview_kwargs["padding"] = padding
            
        if headers:
            treeview_kwargs["show"] = "headings"
        else:
            treeview_kwargs["show"] = ""
        
        if select_mode is not None:
            treeview_kwargs["selectmode"] = select_mode

        self.interior = Treeview(master, columns=columns, **treeview_kwargs)
        
        if command is not None:
            self._command = command
            self.interior.bind("<<TreeviewSelect>>", self._on_select)

        for i in range(0, self._number_of_columns):

            if sort:
                self.interior.heading(i, text=columns[i], anchor=heading_anchor, command=lambda col=i: self.sort_by(col, descending=False))
            else:
                self.interior.heading(i, text=columns[i], anchor=heading_anchor)
                
            if adjust_heading_to_content:
                self.interior.column(i, width=Font().measure(columns[i]))

            self.interior.column(i, anchor=cell_anchor)
            
        if data is not None:
            for row in data:
                self.insert_row(row)

    @property
    def row_height(self):
        return self._rowheight
        
    @property
    def font(self):
        return self._cell_font

    def configure_column(self, index, width=None, minwidth=None, anchor=None, stretch=None):
        kwargs = {}
        for config_name in ("width", "anchor", "stretch", "minwidth"):
            config_value = locals()[config_name]
            if config_value is not None:
                kwargs[config_name] = config_value
            
        self.interior.column('#%s'%(index+1), **kwargs)

    def row_data(self, index):
        try:
            item_ID = self.interior.get_children()[index]
        except IndexError:
            raise ValueError("Row index out of range: %d"%index)        

        return self.item_ID_to_row_data(item_ID)

    def update_row(self, index, data):
        try:
            item_ID = self.interior.get_children()[index]
        except IndexError:
            raise ValueError("Row index out of range: %d"%index)
            
        if len(data) == len(self._columns):
            self.interior.item(item_ID, values=data)
        else:
            raise ValueError("The multicolumn listbox has only %d columns"%self._number_of_columns)

    def delete_row(self, index):
        list_of_items = self.interior.get_children()

        try:
            item_ID = list_of_items[index]
        except IndexError:
            raise ValueError("Row index out of range: %d"%index)

        self.interior.delete(item_ID)
        self._number_of_rows -= 1
        
        if self._stripped_rows:
            for i in range(index, self._number_of_rows):
                self.interior.tag_configure(list_of_items[i+1], background=self._stripped_rows[i%2])
            
    def insert_row(self, data, index=None):
        if len(data) != self._number_of_columns:
            raise ValueError("The multicolumn listbox has only %d columns"%self._number_of_columns)
        
        if index is None:
            index = self._number_of_rows-1

        item_ID = self.interior.insert('', index, values=data)        
        self.interior.item(item_ID, tags=item_ID)

        self._number_of_rows += 1        

        if self._stripped_rows:            
            list_of_items = self.interior.get_children()

            self.interior.tag_configure(item_ID, background=self._stripped_rows[index%2])

            for i in range(index+1, self._number_of_rows):
                self.interior.tag_configure(list_of_items[i], background=self._stripped_rows[i%2])

    def column_data(self, index):
        return [self.interior.set(child_ID, index) for child_ID in self.interior.get_children('')]

    def update_column(self, index, data):
        for i, item_ID in enumerate(self.interior.get_children()): 
            data_row = self.item_ID_to_row_data(item_ID)
            data_row[index] = data[i]

            self.interior.item(item_ID, values=data_row)

        return data

    def clear(self):
        # Another possibility:
        #  self.interior.delete(*self.interior.get_children())

        for row in self.interior.get_children():
            self.interior.delete(row)
            
        self._number_of_rows = 0
            
    def update(self, data):
        self.clear()

        for row in data:
            self.insert_row(row)
            
    def focus(self, index=None):
        if index is None:
            return self.interior.item(self.interior.focus())
        else:
            item = self.interior.get_children()[index]
            self.interior.focus(item)

    def state(self, state=None):
        if stateSpec is None:
            return self.interior.state()
        else:
            self.interior.state(state)

    @property
    def number_of_rows(self):
        return self._number_of_rows
        
    @property
    def number_of_columns(self):
        return self._number_of_columns
        
    def toogle_selection(self, index):
        list_of_items = self.interior.get_children()
        
        try:
            item_ID = list_of_items[index]
        except IndexError:
            raise ValueError("Row index out of range: %d"%index)

        self.interior.selection_toggle(item_ID)     

    def select_row(self, index):
        list_of_items = self.interior.get_children()
        
        try:
            item_ID = list_of_items[index]
        except IndexError:
            raise ValueError("Row index out of range: %d"%index)

        self.interior.selection_add(item_ID)

    def deselect_row(self, index):
        list_of_items = self.interior.get_children()
        
        try:
            item_ID = list_of_items[index]
        except IndexError:
            raise ValueError("Row index out of range: %d"%index)

        self.interior.selection_remove(item_ID)
        
    def deselect_all(self):
        self.interior.selection_remove(self.interior.selection())

    def set_selection(self, indices):
        list_of_items = self.interior.get_children()

        self.interior.selection_set(" ".join(list_of_items[row_index] for row_index in indices))

    @property
    def selected_rows(self):
        data = []
        for item_ID in self.interior.selection():
            data_row = self.item_ID_to_row_data(item_ID)
            data.append(data_row)
        
        return data

    @property
    def indices_of_selected_rows(self):
        list_of_indices = []
        for index, item_ID in enumerate(self.interior.get_children()):
            if item_ID in self.interior.selection():
                list_of_indices.append(index)

        return list_of_indices
        
    def delete_all_selected_rows(self):
        selected_items = self.interior.selection()
        for item_ID in selected_items:
            self.interior.delete(item_ID)
        
        number_of_deleted_rows = len(selected_items)
        self._number_of_rows -= number_of_deleted_rows

        return number_of_deleted_rows

    def _on_select(self, event):
        for item_ID in event.widget.selection():
            data_row = self.item_ID_to_row_data(item_ID)
            self._command(data_row)

    def item_ID_to_row_data(self, item_ID):
        item = self.interior.item(item_ID)
        return item["values"]
    
    @property
    def table_data(self):
        data = []

        for item_ID in self.interior.get_children():
            data_row = self.item_ID_to_row_data(item_ID)
            data.append(data_row)

        return data
    
    @table_data.setter
    def table_data(self, data):
        self.update(data)
    
    def cell_data(self, row, column):
        """Get the value of a table cell"""
        try:
            item = self.interior.get_children()[row]
        except IndexError:
            raise ValueError("Row index out of range: %d"%row)
            
        return self.interior.set(item, column)
            
    def update_cell(self, row, column, value):
        """Set the value of a table cell"""

        item_ID = self.interior.get_children()[row]
        
        data = self.item_ID_to_row_data(item_ID)
        
        data[column] = value
        self.interior.item(item_ID, values=data)
    
    def __getitem__(self, index):
        if isinstance(index, tuple):
            row, column = index
            return self.cell_data(row, column)
        else:
            raise Exception("Row and column indices are required")
        
    def __setitem__(self, index, value):
        if isinstance(index, tuple):
            row, column = index
            self.update_cell(row, column, value)
        else:
            raise Exception("Row and column indices are required")

    def bind(self, event, handler):
        self.interior.bind(event, handler)

    def sort_by(self, col, descending):
        """
        sort tree contents when a column header is clicked
        """
        # grab values to sort
        data = [(self.interior.set(child_ID, col), child_ID) for child_ID in self.interior.get_children('')]
        
        # if the data to be sorted is numeric change to float
        try:
            data = [(float(number), child_ID) for number, child_ID in data]
        except ValueError:
            pass

        # now sort the data in place
        data.sort(reverse=descending)
        for idx, item in enumerate(data):
            self.interior.move(item[1], '', idx)

        # switch the heading so that it will sort in the opposite direction
        self.interior.heading(col, command=lambda col=col: self.sort_by(col, not descending))
        
        if self._stripped_rows:
            list_of_items = self.interior.get_children('')
            for i in range(len(list_of_items)):
                self.interior.tag_configure(list_of_items[i], background=self._stripped_rows[i%2])

    def destroy(self):
        self.interior.destroy()
        
    def item_ID(self, index):
        return self.interior.get_children()[index]
Esempio n. 40
0
    def initUI_main(self):
        self.parent.title("Personal Helper")
        self.pack(fill=BOTH, expand=True)

        self.columnconfigure(0, weight=1)
        self.columnconfigure(7, weight=1)
        self.columnconfigure(5, pad=10)
        self.columnconfigure(3, pad=10)
        self.columnconfigure(1, weight=3)
        self.rowconfigure(0, weight=0)
        self.rowconfigure(5, weight=1)
        self.rowconfigure(5, pad=7)
        self.rowconfigure(6, pad=6)


        lbl = Label(self, text="Windows")
        lbl.grid(sticky=W+N, pady=4, padx=5)


        check_box = {"work": IntVar(),
                     "boost": IntVar()}

        check1 = Checkbutton(self, text="work-Mode", variable=check_box["work"])
        check1.grid(row=7, column=0)

        check2 = Checkbutton(self, text="boost games", variable=check_box["boost"])
        check2.grid(row=7, column=1)


        ### old version, may be used again later
        area = Treeview(self)
        area['show'] = 'headings'
        area["columns"] = ("one", "two", "three", "four")
        area.column("one", width=10)
        area.column("two", width=10)
        area.column("three", width=10)
        area.column("four", width=10)
        area.heading("one", text="process name")
        area.heading("two", text="Priority")
        area.heading("three", text="PID")
        area.heading("four", text="Usage")
        ###about this part
        #area.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N)
        #######

        #comboboxes and relevant buttons

        self.block_drop = Combobox(self, postcommand= self.update_blocked)
        self.block_drop['values'] = working_bans
        self.block_drop.current(0)
        self.block_drop.grid(row=1, column=1, pady=1)
        self.entry = Entry(self)
        self.entry.insert(0, "enter to block")
        self.entry.grid(row=1, column=4)

        block_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(working_bans, self.block_drop.get()))
        block_btn_remv.grid(row=1, column=2)

        block_btn_add = Button(self, text="Add", command=lambda: add_to_list(working_bans, self.entry.get(), self.entry, defults["block"]))
        block_btn_add.grid(row=1, column=3)

        ############
        #boosted combo
        self.boost_drop = Combobox(self, postcommand=self.update_boosted)
        self.boost_drop['values'] = boosted
        self.boost_drop.current(0)
        self.boost_drop.grid(row=2, column=1, pady=1)
        self.entry2 = Entry(self)
        self.entry2.insert(0, "enter to buff priority")
        self.entry2.grid(row=2, column=4, pady=4)

        boost_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(boosted, self.boost_drop.get()))
        boost_btn_remv.grid(row=2, column=2)

        boost_btn_add = Button(self, text="Add", command=lambda: add_to_list(boosted, self.entry2.get(), self.entry2, defults["boost"]))
        boost_btn_add.grid(row=2, column=3)

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

        #degraded combo
        self.deg_drop = Combobox(self, postcommand=self.update_degraded)
        self.deg_drop['values'] = degraded
        self.deg_drop.current(0)
        self.deg_drop.grid(row=3, column=1, pady=1)
        self.entry3 = Entry(self)
        self.entry3.insert(0, "enter to lower priority")
        self.entry3.grid(row=3, column=4, pady=4)

        deg_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(degraded, self.deg_drop.get()))
        deg_btn_remv.grid(row=3, column=2)

        deg_btn_add = Button(self, text="Add", command=lambda: add_to_list(degraded, self.entry3.get(), self.entry3, defults["degrade"]))
        deg_btn_add.grid(row=3, column=3)

        ####
        #music combo

        self.music_drop = Combobox(self, postcommand=self.update_music)
        self.music_drop['values'] = music_list.keys()
        self.music_drop.current(0)
        self.music_drop.grid(row=4, column=1, pady=1)
        self.entry4 = Entry(self)
        self.entry4.insert(0, "enter url")
        self.entry4.grid(row=4, column=5)
        self.entry5 = Entry(self)
        self.entry5.insert(0, "enter song's name")
        self.entry5.grid(row=4, column=4)

        music_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(music_list, self.music_drop.get()))
        music_btn_remv.grid(row=4, column=2)

        music_btn_add = Button(self, text="Add", command=lambda: add_music(music_list, self.entry5.get(),self.entry4.get() ,self.entry5, defults["music"]))
        music_btn_add.grid(row=4, column=3)


        abtn = Button(self, text="Activate", command=scan_computer_programs)
        abtn.grid(row=1, column=5, sticky=E)

        sbtn = Button(self, text="Stop", command=lambda: stop_running())
        sbtn.grid(row=2, column=5, pady=6, sticky=E)

        cbtn = Button(self, text="Close", command=quit)
        cbtn.grid(row=3, column=5, pady=4, sticky=E)

        hbtn = Button(self, text="Save", command=save_lists)
        hbtn.grid(row=6, column=0, sticky=W)

        tsbtn = Button(self, text="TaskManager", command=lambda: os.system("TaskManager\pyProcMon.py"))
        tsbtn.grid(row=3, column=5, sticky=E)

        obtn = Button(self, text="start", command=lambda: call_running(area, threads["procs"], check_box))
        obtn.grid(row=6, column=5, sticky=E)
Esempio n. 41
0
  def _add_frames(self):
    # Adding Answer Backup Frame
    f1 = Frame(self)
    f1.grid(column=0, row=0, sticky="NWES")
    for i in range(4):
      f1.grid_rowconfigure(i, weight=0, pad=5)
    f1.grid_rowconfigure(4, weight=1, pad=5)
    for i in range(4):
      f1.grid_columnconfigure(i, weight=1, pad=5)

    Label(f1, anchor='e', text='Answers Count : ').grid(column=0, row=0, sticky='EWNS')
    self.answer_count = StringVar(value=len(self.crawler.answer_list))
    Label(f1, anchor='w', textvariable=self.answer_count).grid(column=1, row=0, sticky='EWNS')
    Label(f1, anchor='e', text='User Name : ').grid(column=2, row=0, sticky='EWNS')
    self.user = StringVar(value='Unknown')
    Label(f1, anchor='w', textvariable=self.user).grid(column=3, row=0, sticky='EWNS')

    tf_col = '#e6e6e6'
    tf = Tkinter.Frame(f1, relief=GROOVE, borderwidth='2p')
    tf.grid(row=1, columnspan=2, column=0, sticky='EWNS')
    Label(tf, text='Quora User Options', bg=tf_col, anchor='c').grid(column=0, row=0, columnspan=2, sticky='EWNS')
    Button(tf, text='Login', command=lambda : self.thread('login'),
      highlightbackground=tf_col).grid(column=0, row=1, sticky='EWNS')
    Button(tf, text='Logout', command=lambda : self.thread('logout'),
      highlightbackground=tf_col).grid(column=1, row=1, sticky='EWNS')
    tf.grid_rowconfigure(0, weight=1, pad=5)
    tf.grid_rowconfigure(1, weight=1, pad=5)
    tf.grid_columnconfigure(0, weight=1, pad=5)
    tf.grid_columnconfigure(1, weight=1, pad=5)

    tf = Frame(f1, relief=GROOVE, borderwidth='2p')
    tf.grid(row=1, columnspan=2, column=2, sticky='EWNS')
    Label(tf, text='Answer List Option', bg=tf_col, anchor='c').grid(column=0, columnspan=2, row=0, sticky='EWNS')
    Button(tf, text='Reset', command=lambda : self.thread('reset'),
      highlightbackground=tf_col).grid(column=0, row=1, sticky='EWNS')
    Button(tf, text='Update', command=lambda : self.thread('update'),
      highlightbackground=tf_col).grid(column=1, row=1, sticky='EWNS')
    tf.grid_rowconfigure(0, weight=1, pad=5)
    tf.grid_rowconfigure(1, weight=1, pad=5)
    tf.grid_columnconfigure(0, weight=1, pad=5)
    tf.grid_columnconfigure(1, weight=1, pad=5)

    # Add Progress Bar
    self.backup_progress = Progressbar(f1, orient="horizontal", length=100, mode="determinate")
    self.backup_progress.grid(row=2, columnspan=4, column=0, sticky='EWNS')

    # Adding Status Pane
    self.backup_status = StringVar(value='Ready')
    Label(f1, textvariable=self.backup_status, anchor='w').grid(row=3, column=0, columnspan=4, sticky='EWNS')

    # Adding The list of all answers
    tree = Treeview(f1, columns=('sno', 'date', 'question'))
    tree.heading('sno', text='S. No')
    tree.heading('date', text='Date')
    tree.heading('question', text='Question')

    tree.column("#0", width=0, stretch=False)
    tree.column('sno', width=40, stretch=False, anchor='center')
    tree.column('date', width=120, stretch=False, anchor='center')
    tree.column('question', stretch=True, anchor='w')
    tree.grid(column=0, columnspan=4, row=4, sticky='EWNS')
    tree.bind("<Double-1>", self.tree_item_click)
    self.answer_tree = tree
    self.populate_tree()

    f2 = Frame(self)
    self.add(f1, text='Answer Backup', underline=7)
    self.add(f2, text='Analytics')
class Multicolumn_Listbox(object):
    _style_index = 0

    class List_Of_Rows(object):
        def __init__(self, multicolumn_listbox):
            self._multicolumn_listbox = multicolumn_listbox

        def data(self, index):
            return self._multicolumn_listbox.row_data(index)

        def get(self, index):
            return Row(self._multicolumn_listbox, index)

        def insert(self, data, index=None):
            self._multicolumn_listbox.insert_row(data, index)

        def delete(self, index):
            self._multicolumn_listbox.delete_row(index)

        def update(self, index, data):
            self._multicolumn_listbox.update_row(index, data)

        def select(self, index):
            self._multicolumn_listbox.select_row(index)

        def deselect(self, index):
            self._multicolumn_listbox.deselect_row(index)

        def set_selection(self, indices):
            self._multicolumn_listbox.set_selection(indices)

        def __getitem__(self, index):
            return self.get(index)

        def __setitem__(self, index, value):
            return self._multicolumn_listbox.update_row(index, value)

        def __delitem__(self, index):
            self._multicolumn_listbox.delete_row(index)

        def __len__(self):
            return self._multicolumn_listbox.number_of_rows

    class List_Of_Columns(object):
        def __init__(self, multicolumn_listbox):
            self._multicolumn_listbox = multicolumn_listbox

        def data(self, index):
            return self._multicolumn_listbox.get_column(index)

        def get(self, index):
            return Column(self._multicolumn_listbox, index)

        def delete(self, index):
            self._multicolumn_listbox.delete_column(index)

        def update(self, index, data):
            self._multicolumn_listbox.update_column(index, data)

        def __getitem__(self, index):
            return self.get(index)

        def __setitem__(self, index, value):
            return self._multicolumn_listbox.update_column(index, value)

        def __delitem__(self, index):
            self._multicolumn_listbox.delete_column(index)

        def __len__(self):
            return self._multicolumn_listbox.number_of_columns

    def __init__(self,
                 master,
                 columns,
                 data=None,
                 command=None,
                 sort=True,
                 select_mode=None,
                 heading_anchor=CENTER,
                 cell_anchor=W,
                 style=None,
                 height=None,
                 padding=None,
                 adjust_heading_to_content=False,
                 stripped_rows=None,
                 selection_background=None,
                 selection_foreground=None,
                 field_background=None,
                 heading_font=None,
                 heading_background=None,
                 heading_foreground=None,
                 cell_pady=2,
                 cell_background=None,
                 cell_foreground=None,
                 cell_font=None,
                 headers=True):

        self._stripped_rows = stripped_rows

        self._columns = columns

        self._number_of_rows = 0
        self._number_of_columns = len(columns)

        self.row = self.List_Of_Rows(self)
        self.column = self.List_Of_Columns(self)

        s = Style()

        if style is None:
            style_name = "Multicolumn_Listbox%s.Treeview" % self._style_index
            self._style_index += 1
        else:
            style_name = style

        style_map = {}
        if selection_background is not None:
            style_map["background"] = [('selected', selection_background)]

        if selection_foreground is not None:
            style_map["foeground"] = [('selected', selection_foreground)]

        if style_map:
            s.map(style_name, **style_map)

        style_config = {}
        if cell_background is not None:
            style_config["background"] = cell_background

        if cell_foreground is not None:
            style_config["foreground"] = cell_foreground

        if cell_font is None:
            font_name = s.lookup(style_name, "font")
            cell_font = nametofont(font_name)
        else:
            if not isinstance(cell_font, Font):
                if isinstance(cell_font, basestring):
                    cell_font = nametofont(cell_font)
                else:
                    if len(font) == 1:
                        cell_font = Font(family=cell_font[0])
                    elif len(font) == 2:
                        cell_font = Font(family=cell_font[0],
                                         size=cell_font[1])

                    elif len(font) == 3:
                        cell_font = Font(family=cell_font[0],
                                         size=cell_font[1],
                                         weight=cell_font[2])
                    else:
                        raise ValueError(
                            "Not possible more than 3 values for font")

            style_config["font"] = cell_font

        self._cell_font = cell_font

        self._rowheight = cell_font.metrics("linespace") + cell_pady
        style_config["rowheight"] = self._rowheight

        if field_background is not None:
            style_config["fieldbackground"] = field_background

        s.configure(style_name, **style_config)

        heading_style_config = {}
        if heading_font is not None:
            heading_style_config["font"] = heading_font
        if heading_background is not None:
            heading_style_config["background"] = heading_background
        if heading_foreground is not None:
            heading_style_config["foreground"] = heading_foreground

        heading_style_name = style_name + ".Heading"
        s.configure(heading_style_name, **heading_style_config)

        treeview_kwargs = {"style": style_name}

        if height is not None:
            treeview_kwargs["height"] = height

        if padding is not None:
            treeview_kwargs["padding"] = padding

        if headers:
            treeview_kwargs["show"] = "headings"
        else:
            treeview_kwargs["show"] = ""

        if select_mode is not None:
            treeview_kwargs["selectmode"] = select_mode

        self.interior = Treeview(master, columns=columns, **treeview_kwargs)

        if command is not None:
            self._command = command
            self.interior.bind("<<TreeviewSelect>>", self._on_select)

        for i in range(0, self._number_of_columns):

            if sort:
                self.interior.heading(
                    i,
                    text=columns[i],
                    anchor=heading_anchor,
                    command=lambda col=i: self.sort_by(col, descending=False))
            else:
                self.interior.heading(i,
                                      text=columns[i],
                                      anchor=heading_anchor)

            if adjust_heading_to_content:
                self.interior.column(i, width=Font().measure(columns[i]))

            self.interior.column(i, anchor=cell_anchor)

        if data is not None:
            for row in data:
                self.insert_row(row)

    @property
    def row_height(self):
        return self._rowheight

    @property
    def font(self):
        return self._cell_font

    def configure_column(self,
                         index,
                         width=None,
                         minwidth=None,
                         anchor=None,
                         stretch=None):
        kwargs = {}
        for config_name in ("width", "anchor", "stretch", "minwidth"):
            config_value = locals()[config_name]
            if config_value is not None:
                kwargs[config_name] = config_value

        self.interior.column('#%s' % (index + 1), **kwargs)

    def row_data(self, index):
        try:
            item_ID = self.interior.get_children()[index]
        except IndexError:
            raise ValueError("Row index out of range: %d" % index)

        return self.item_ID_to_row_data(item_ID)

    def update_row(self, index, data):
        try:
            item_ID = self.interior.get_children()[index]
        except IndexError:
            raise ValueError("Row index out of range: %d" % index)

        if len(data) == len(self._columns):
            self.interior.item(item_ID, values=data)
        else:
            raise ValueError("The multicolumn listbox has only %d columns" %
                             self._number_of_columns)

    def delete_row(self, index):
        list_of_items = self.interior.get_children()

        try:
            item_ID = list_of_items[index]
        except IndexError:
            raise ValueError("Row index out of range: %d" % index)

        self.interior.delete(item_ID)
        self._number_of_rows -= 1

        if self._stripped_rows:
            for i in range(index, self._number_of_rows):
                self.interior.tag_configure(list_of_items[i + 1],
                                            background=self._stripped_rows[i %
                                                                           2])

    def insert_row(self, data, index=None):
        if len(data) != self._number_of_columns:
            raise ValueError("The multicolumn listbox has only %d columns" %
                             self._number_of_columns)

        if index is None:
            index = self._number_of_rows - 1

        item_ID = self.interior.insert('', index, values=data)
        self.interior.item(item_ID, tags=item_ID)

        self._number_of_rows += 1

        if self._stripped_rows:
            list_of_items = self.interior.get_children()

            self.interior.tag_configure(item_ID,
                                        background=self._stripped_rows[index %
                                                                       2])

            for i in range(index + 1, self._number_of_rows):
                self.interior.tag_configure(list_of_items[i],
                                            background=self._stripped_rows[i %
                                                                           2])

    def column_data(self, index):
        return [
            self.interior.set(child_ID, index)
            for child_ID in self.interior.get_children('')
        ]

    def update_column(self, index, data):
        for i, item_ID in enumerate(self.interior.get_children()):
            data_row = self.item_ID_to_row_data(item_ID)
            data_row[index] = data[i]

            self.interior.item(item_ID, values=data_row)

        return data

    def clear(self):
        # Another possibility:
        #  self.interior.delete(*self.interior.get_children())

        for row in self.interior.get_children():
            self.interior.delete(row)

        self._number_of_rows = 0

    def update(self, data):
        self.clear()

        for row in data:
            self.insert_row(row)

    def focus(self, index=None):
        if index is None:
            return self.interior.item(self.interior.focus())
        else:
            item = self.interior.get_children()[index]
            self.interior.focus(item)

    def state(self, state=None):
        if stateSpec is None:
            return self.interior.state()
        else:
            self.interior.state(state)

    @property
    def number_of_rows(self):
        return self._number_of_rows

    @property
    def number_of_columns(self):
        return self._number_of_columns

    def toogle_selection(self, index):
        list_of_items = self.interior.get_children()

        try:
            item_ID = list_of_items[index]
        except IndexError:
            raise ValueError("Row index out of range: %d" % index)

        self.interior.selection_toggle(item_ID)

    def select_row(self, index):
        list_of_items = self.interior.get_children()

        try:
            item_ID = list_of_items[index]
        except IndexError:
            raise ValueError("Row index out of range: %d" % index)

        self.interior.selection_add(item_ID)

    def deselect_row(self, index):
        list_of_items = self.interior.get_children()

        try:
            item_ID = list_of_items[index]
        except IndexError:
            raise ValueError("Row index out of range: %d" % index)

        self.interior.selection_remove(item_ID)

    def deselect_all(self):
        self.interior.selection_remove(self.interior.selection())

    def set_selection(self, indices):
        list_of_items = self.interior.get_children()

        self.interior.selection_set(" ".join(list_of_items[row_index]
                                             for row_index in indices))

    @property
    def selected_rows(self):
        data = []
        for item_ID in self.interior.selection():
            data_row = self.item_ID_to_row_data(item_ID)
            data.append(data_row)

        return data

    @property
    def indices_of_selected_rows(self):
        list_of_indices = []
        for index, item_ID in enumerate(self.interior.get_children()):
            if item_ID in self.interior.selection():
                list_of_indices.append(index)

        return list_of_indices

    def delete_all_selected_rows(self):
        selected_items = self.interior.selection()
        for item_ID in selected_items:
            self.interior.delete(item_ID)

        number_of_deleted_rows = len(selected_items)
        self._number_of_rows -= number_of_deleted_rows

        return number_of_deleted_rows

    def _on_select(self, event):
        for item_ID in event.widget.selection():
            data_row = self.item_ID_to_row_data(item_ID)
            self._command(data_row)

    def item_ID_to_row_data(self, item_ID):
        item = self.interior.item(item_ID)
        return item["values"]

    @property
    def table_data(self):
        data = []

        for item_ID in self.interior.get_children():
            data_row = self.item_ID_to_row_data(item_ID)
            data.append(data_row)

        return data

    @table_data.setter
    def table_data(self, data):
        self.update(data)

    def cell_data(self, row, column):
        """Get the value of a table cell"""
        try:
            item = self.interior.get_children()[row]
        except IndexError:
            raise ValueError("Row index out of range: %d" % row)

        return self.interior.set(item, column)

    def update_cell(self, row, column, value):
        """Set the value of a table cell"""

        item_ID = self.interior.get_children()[row]

        data = self.item_ID_to_row_data(item_ID)

        data[column] = value
        self.interior.item(item_ID, values=data)

    def __getitem__(self, index):
        if isinstance(index, tuple):
            row, column = index
            return self.cell_data(row, column)
        else:
            raise Exception("Row and column indices are required")

    def __setitem__(self, index, value):
        if isinstance(index, tuple):
            row, column = index
            self.update_cell(row, column, value)
        else:
            raise Exception("Row and column indices are required")

    def bind(self, event, handler):
        self.interior.bind(event, handler)

    def sort_by(self, col, descending):
        """
        sort tree contents when a column header is clicked
        """
        # grab values to sort
        data = [(self.interior.set(child_ID, col), child_ID)
                for child_ID in self.interior.get_children('')]

        # if the Demo_programs to be sorted is numeric change to float
        try:
            data = [(float(number), child_ID) for number, child_ID in data]
        except ValueError:
            pass

        # now sort the Demo_programs in place
        data.sort(reverse=descending)
        for idx, item in enumerate(data):
            self.interior.move(item[1], '', idx)

        # switch the heading so that it will sort in the opposite direction
        self.interior.heading(
            col, command=lambda col=col: self.sort_by(col, not descending))

        if self._stripped_rows:
            list_of_items = self.interior.get_children('')
            for i in range(len(list_of_items)):
                self.interior.tag_configure(list_of_items[i],
                                            background=self._stripped_rows[i %
                                                                           2])

    def destroy(self):
        self.interior.destroy()

    def item_ID(self, index):
        return self.interior.get_children()[index]
Esempio n. 43
0
class Tree(Treeview):
    """ Класс, формирующий таблицу """
    def __init__(self, root, frame, num, logit, all_values, list_styles_names):
        Treeview.__init__(self, root)
        self.root = root
        self.num = num
        self.frame = frame
        self.name = "MOXA-%s" % str(self.num)
        self.tree = Treeview(frame, style=list_styles_names[num])
        self.tree["columns"] = ("one", "two", "three")
        self.tree.heading("#0", text="")
        self.tree.column("#0", minwidth=0, width=5, stretch=NO)
        self.tree.heading("one", text="Port")
        self.tree.column("one", minwidth=0, width=30, stretch=NO)
        self.tree.column("two", minwidth=0, width=name_column, stretch=NO)
        self.tree.heading("three", text="State")
        self.tree.column("three", minwidth=0, width=state_column, stretch=YES)
        self.tree['height'] = 32
        self.tree.tag_configure('green',
                                background='gray7',
                                foreground='green2')
        self.tree.tag_configure('red',
                                background='gray7',
                                foreground='tomato2')
        self.tree.tag_configure('blue',
                                background='gray7',
                                foreground='RoyalBlue')
        self.tree.tag_configure('yellow',
                                background='gray7',
                                foreground='yellow')
        self.tree.tag_configure('ready',
                                background='gray7',
                                foreground='white')
        self.tree.tag_configure(
            'focus',
            background='yellow',
        )
        self.tree.bind("<Motion>", self.mycallback)
        self.last_focus = None
        self.tree.pack(side=LEFT)
        self.logit = logit
        self.moxa = all_values[self.num][0]
        self.wraplength = 180
        for key in self.moxa.keys():
            self.tree.insert("",
                             "end",
                             values=(str(key), self.moxa[key], "<><><>"),
                             tags=("green", ))

    def mycallback(self, event):
        """ Функция, отображающая комментарий при наведении мыши на канал """

        _iid = self.tree.identify_row(event.y)
        if _iid != self.last_focus:
            if self.last_focus:
                try:
                    if self.tw:
                        self.tw.destroy()
                except:
                    pass

            if _iid:
                row = self.tree.item(_iid)
                key = row["values"][0]
                if os.path.isfile('comments/comment_%s_%s.txt' %
                                  (self.num, key)):
                    with open('comments/comment_%s_%s.txt' % (self.num, key),
                              'a+') as comment:
                        file_log = comment.read()
                        param = self.tree.bbox(_iid)
                        x = (param[0] + space_X) * self.num
                        y = param[1] + space_Y
                        self.tw = tk.Toplevel()
                        self.tw.wm_overrideredirect(True)
                        self.tw.wm_geometry("+%d+%d" % (x, y))
                        label = tk.Label(self.tw,
                                         text=file_log,
                                         justify='left',
                                         background="yellow2",
                                         relief='solid',
                                         borderwidth=1,
                                         wraplength=self.wraplength,
                                         font=tkFont.Font(family=main_font,
                                                          size=size_font))
                        label.pack()
                self.last_focus = _iid
Esempio n. 44
0
class GUIMainMenu(Frame):
    """Main menu for test of Genesi i.MX53 systems"""

    def __init__(self,master=None):
        """Initialize the base class"""
        Frame.__init__(self,master)

        """Set window title"""
        self.master.title("Select System Test")

        """System Tests"""
        self.createTestEntries()

        """Constants"""
        self.TEST_COL=0
        self.STATUS_COL=1
        self.TEXT_ROW=0
        self.TREEVIEW_ROW=1
        self.BUTTON_ROW=2

        """Display main window with padding"""
        self.grid()
        self.createWidgets()

    def createTestEntries(self):
        #TODO must be a better way. Pickle?
        self.tests = [TestInfo("Audio", AudioGUI), TestInfo("Clock", Dummy1),
                      TestInfo("Display", Dummy1), TestInfo("Keyboard", Dummy1),
                      TestInfo("Network", Dummy1), TestInfo("SSD", Dummy2),
                      TestInfo("Video", VideoGUI)]
        self.testsLookup = {}
        for te in self.tests:
            self.testsLookup.update({te.name : te})

    def createWidgets(self):
        """Create all the initial widgets for this menu"""
        """Labels"""
        lbl = Label(self, text="Select test below", justify=LEFT)
        lbl.grid(row=self.TEXT_ROW, column=self.TEST_COL)
        
        """Tests"""
        self.trv = Treeview(self, columns=("Status"), displaycolumns='#all')

        for test in self.tests:
            treeviewInsertTest(self.trv, test)

        self.trv.column('#0', width=100)
        self.trv.heading('#0', text="Test")
        self.trv.heading('Status', text='Status')

        self.trv.grid(column=self.TEST_COL, row=self.TREEVIEW_ROW,
                      columnspan=2)

        """Buttons"""
        self.btnOK = Button(self, text="OK", command=self.launchTest)
        self.btnOK.grid(row=self.BUTTON_ROW, column=0)
        self.btnQuit = Button(self, text="Quit", command=self.quit)
        self.btnQuit.grid(row=self.BUTTON_ROW, column=1)

    def launchTest(self):
        # get the item in focus
        testItem = self.trv.item(self.trv.focus())

        if not testItem['text'] == '':
            testInfo = self.testsLookup[testItem['text']]
            testInfo.launchTest(self)

    def processResults(self, testInfo):
        self.trv.item(testInfo.name, values=(testInfo.status),
                      tags=(testInfo.status))
        # update color notifications
        self.trv.tag_configure('Success', foreground='green')
        self.trv.tag_configure('Failure', foreground='red')

        self.deiconify()

    def withdraw(self):
        """Helpful function to hide window"""
        self.master.withdraw()

    def deiconify(self):
        """Helpful function to restore window"""
        self.master.deiconify()
Esempio n. 45
0
class Display:
    def __init__(self, controller):
        self.controller = controller

        self.currIndex = 0

        # initialize the GUI
        self.app = Tk()
        self.app.title('Jack Magee\'s Pub')

        self.tree = Treeview(self.app, height=30)
        
        # name the tree columns, not sure if they have to be named numbers but that's how the example did it
        self.tree["columns"]=("one", "two", "three", "four")
        
        # set the column widths
        self.tree.column("one", width=200)
        self.tree.column("two", width=300)
        self.tree.column("three", width=200)
        self.tree.column("four", width=200)

        # set the column headings
        self.tree.heading("#0", text= "ID")
        self.tree.heading("one", text="Name")
        self.tree.heading("two", text="Order")
        self.tree.heading("three", text="Price")
        self.tree.heading("four", text="Respond (double-click)")

        self.tree.pack()
        
        # register handler for double-clicks
        self.tree.bind("<Double-1>", self.OnDoubleClick)

    def mainloop(self):
        self.app.mainloop()

    # this is like making tree entries buttons
    def OnDoubleClick(self, event):
        # get the pressed item
        item = self.tree.selection()[0]
        # get the item's text
        response =  self.tree.item(item,"text")

        # this is the only response we are sending for now
        if response == 'rdy':
            # get the parent directory whose text is the customer id
            parent = self.tree.parent(item)
            customer_id = self.tree.item(parent,"text")
            # remove it from the tree
            self.tree.delete(parent)
            # send the message to the customer
            self.controller.send_msg(customer_id, response)

    # add a new order to the tree
    def takeOrder(self, customer_id, name, order, price):
        # just a row identifier
        thisRow = str(self.currIndex)

        # insert the i.d. and name at the top level
        self.tree.insert("", self.currIndex, thisRow, text=customer_id, values=(name, "", "", ""))
        # insert the "button" for sending notification to clients
        self.tree.insert(thisRow, 0, text='rdy', values=("", "", "", "Ready For Pick Up"))

        # this is a hacky solution to get multiline orders to appear because treeviews will 
        # crop anything more than 1 line so I just make a new entry for every line
        multiline_order = order.split('\n')
        this_line = 1
        for line in multiline_order[:-1]:   # exclude the last end line
            if this_line == 1:  # the first line has the name of the order and it's price
                self.tree.insert(thisRow, 1, text="order",values=("", order, price, ""))
            else: # just keep printing the extra options, sides, and add ons
                self.tree.insert(thisRow, this_line, text="order",values=("", line, "", ""))
            this_line += 1

        self.currIndex += 1
Esempio n. 46
0
        def __init__(self, parent, controller):
                Frame.__init__(self, parent)

		global codigo, ctacontable, nombre, desc, tree
		
		lupa = PhotoImage(file='img/lupa.png')
		
		codigo = StringVar()
		ctacontable = StringVar()
		nombre = StringVar()
		desc = StringVar()
		
		#WIDGETS
		
		#=========================== HEADER ============================
		
		self.titleL = Label(self, text="CONCEPTO DE GASTOS", font="bold")
		self.titleL.pack(pady=20, side=TOP)
		
		#=========================== WRAPPER ===========================
		
		self.wrapper = Frame (self)
		self.wrapper.pack(side=TOP, fill=Y)
		
		self.f0 = Frame(self.wrapper)
		self.f0.pack(pady=5, fill=X)#-----------------------------------
		
		l1 = Label (self.f0, text="Código:")
		l1.pack(side=LEFT)
		e1 = Entry (self.f0, textvariable=codigo, width=60)
		e1.pack(side=LEFT)
		e1.bind("<KeyRelease>", caps)
		
		self.f2 = Frame(self.wrapper)
		self.f2.pack(pady=5, fill=X)#-----------------------------------
		
		l2 = Label (self.f2, text="Cuenta Contable: ")
		l2.pack(side=LEFT)
		
		e2 = Entry (self.f2, textvariable=ctacontable, width=60)
		e2.pack(side=LEFT, fill=X, expand=1)
		
		b0 = Button (self.f2, text="Buscar", image=lupa, command=buscar)
		b0.image=lupa
		b0.pack(side=LEFT)
		
		self.f3 = Frame(self.wrapper)
		self.f3.pack(pady=5, fill=X)#-----------------------------------
		
		self.nombre = Label (self.f3, text="Nombre: ")
		self.nombre.pack(side=LEFT)
		self.nombreE = Entry (self.f3, textvariable=nombre, state=DISABLED)
		self.nombreE.pack(side=LEFT, fill=X, expand=1)
		
		self.f4 = Frame(self.wrapper)
		self.f4.pack(pady=5, fill=X)#-----------------------------------
		
		self.descL = Label (self.f4, text="Descripción: ")
		self.descL.pack(side=LEFT)
		self.descE = Entry (self.f4, textvariable=desc)
		self.descE.pack(side=LEFT, fill=X, expand=1)
		self.descE.bind("<KeyRelease>", caps)
		
		self.f5 = Frame(self.wrapper)
		self.f5.pack(pady=5, fill=X)#-----------------------------------
		
		b1 = Button (self.f5, text="Cargar", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=cargar)
		b1.pack(side=RIGHT)
		
		b2 = Button (self.f5, text="Agregar", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=agregar)
		b2.pack(side=RIGHT)
		
		self.f6 = Frame(self.wrapper)
		self.f6.pack(pady=5, fill=X)#-----------------------------------
		
		tree = Treeview(self.f6, show="headings", columns=('col1','col2', 'col3', 'col4'))
		tree.pack(side=LEFT, fill=X, expand=1)
		tree.column('col1', width=2, anchor='center')
		tree.column('col2', width=150, anchor='center')
		tree.column('col3', width=10, anchor='center')
		tree.column('col4', width=150, anchor='center')
		
		tree.heading('col1', text='Código')
		tree.heading('col2', text='Descripción')
		tree.heading('col3', text='Cta Contable')
		tree.heading('col4', text='Nombre')
		
		self.scroll = Scrollbar(self.f6,orient=VERTICAL,command=tree.yview)
		tree.configure(yscrollcommand=self.scroll.set)
		
		self.f7 = Frame(self.wrapper)
		self.f7.pack(pady=5, fill=X)#-----------------------------------
		
		self.delete = Button (self.f7, text="Eliminar", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=borrar)
		self.delete.pack(side=RIGHT)
Esempio n. 47
0
class App:
    def __init__(self, window):
        self.window = window
        self.mainDaemonAlive = False
        self.reportServerAlive = False
        self.reportServerBut = None
        self.progressbarRunning = False
        self.modelTree = None
        self.nsListStr = StringVar(self.window)
        self.filterStatusStr = StringVar(self.window)
        self.reportClientStatusStr = StringVar(self.window)
        self.playModeStr = StringVar(self.window, PLAY_MODES[0])
        self.pktCopyMaxSize = StringVar(self.window, "60")
        self.netInterfaceStr = StringVar(self.window, NET_INTERFACES[0])
        self.servicePortsStr = StringVar(self.window, "DNS")
        self.debugLevelStr = StringVar(self.window, DEBUG_LEVELS[0])
        self.filterControlButStr = StringVar(self.window, "START")
        self.reportClientControlButStr = StringVar(self.window, "START")
        self.progressFrame = Frame(self.window, width=700, height=20)
        self.progressFrame.pack(side=TOP)
        Frame(self.window, width=700, height=10).pack(side=TOP)
        self.parseNS("/etc/resolv.conf")
        self.getDaemonStatus()
        self.home()
        Frame(self.window, width=700, height=10).pack(side=TOP)
        self.window.resizable(width=False, height=False)
        Style().configure("TButton",
                          padding=6,
                          relief="raised",
                          background="#999")

    def home(self):
        """
    Initialize main window.
    """
        #Configured NS info frame
        nsFrame = Frame(self.window, relief="groove", borderwidth=1)
        Label(nsFrame, text="Configured nameservers:", height=2,
              anchor='w').grid(row=0, sticky="nsew")
        Label(nsFrame, textvariable=self.nsListStr,
              relief="sunken").grid(row=1, sticky="nsew")
        nsFrame.pack(side=TOP, fill=X, padx=20, pady=10, ipadx=20, ipady=5)
        Separator(self.window, orient="horizontal").pack(side=TOP,
                                                         padx=20,
                                                         fill=X)
        #Runtime params frame
        nsFrame = Frame(self.window, relief="groove", borderwidth=1)
        Label(nsFrame, text="Runtime configurations:", height=2,
              anchor='w').grid(row=0, sticky="nsew")
        Label(nsFrame, text="Play mode:").grid(row=1, column=0)
        OptionMenu(nsFrame, self.playModeStr, *PLAY_MODES).grid(row=1,
                                                                column=1)
        Separator(nsFrame, orient="vertical").grid(row=1,
                                                   column=2,
                                                   sticky="ns",
                                                   padx=20)
        Label(nsFrame, text="Interface:").grid(row=1, column=3)
        OptionMenu(nsFrame, self.netInterfaceStr,
                   *NET_INTERFACES).grid(row=1, column=4)
        Separator(nsFrame, orient="vertical").grid(row=1,
                                                   column=5,
                                                   sticky="ns",
                                                   padx=20)
        Label(nsFrame, text="Service:").grid(row=1, column=6)
        OptionMenu(nsFrame, self.servicePortsStr,
                   *NET_PORTS.keys()).grid(row=1, column=7)
        Separator(nsFrame, orient="vertical").grid(row=1,
                                                   column=8,
                                                   sticky="ns",
                                                   padx=20)
        Label(nsFrame, text="Debug level:").grid(row=1, column=9)
        OptionMenu(nsFrame, self.debugLevelStr, *DEBUG_LEVELS).grid(row=1,
                                                                    column=10)
        nsFrame.pack(side=TOP, fill=X, padx=20, pady=10, ipadx=20, ipady=5)
        Separator(nsFrame, orient="vertical").grid(row=2,
                                                   column=2,
                                                   sticky="ns",
                                                   padx=20)
        Label(nsFrame, text="Max datagram bytes to copy:").grid(row=2,
                                                                column=3)
        Entry(nsFrame,
              width=5,
              text=self.pktCopyMaxSize.get(),
              textvariable=self.pktCopyMaxSize).grid(row=2, column=4)
        Separator(nsFrame, orient="vertical").grid(row=2,
                                                   column=5,
                                                   sticky="ns",
                                                   padx=20)
        nsFrame.pack(side=TOP, fill=X, padx=20, pady=10, ipadx=20, ipady=5)
        Separator(self.window, orient="horizontal").pack(side=TOP,
                                                         padx=20,
                                                         fill=X)
        #filter daemon status frame
        statusFrame = Frame(self.window)
        Label(statusFrame, text="DNS filter status:", height=2,
              anchor='w').grid(row=0, column=0)
        Label(statusFrame, textvariable=self.filterStatusStr).grid(row=0,
                                                                   column=1)
        Button(statusFrame,
               textvariable=self.filterControlButStr,
               command=self.changeFilterStatus).grid(row=1, column=0, sticky=W)
        statusFrame.pack(side=TOP, fill=X, padx=20, pady=10, ipadx=20, ipady=5)
        Separator(self.window, orient="horizontal").pack(side=TOP,
                                                         padx=20,
                                                         fill=X)
        #model files frame
        modelFrame = Frame(self.window)
        Label(modelFrame,
              text="Model tags: [{}]".format(configs["model_tags"]),
              height=2,
              anchor='w').grid(row=0, sticky="nsew")
        Label(modelFrame, text="Model configuration", height=2).grid(row=1,
                                                                     sticky=W)
        self.modelConfigFrame(modelFrame).grid(row=2, columnspan=2, sticky=W)
        modelFrame.pack(side=TOP, fill=X, padx=20, pady=10, ipadx=20, ipady=5)
        Separator(self.window, orient="horizontal").pack(side=TOP,
                                                         padx=20,
                                                         fill=X)
        #web report client frame
        reportClientFrame = Frame(self.window)
        Label(reportClientFrame,
              text="Realtime report client status:",
              height=2,
              anchor='w').grid(row=0, column=0)
        Label(reportClientFrame,
              textvariable=self.reportClientStatusStr).grid(row=0, column=1)
        self.reportServerBut = Button(
            reportClientFrame,
            textvariable=self.reportClientControlButStr,
            command=self.changeReportClientStatus,
            state=self.getButtonStateForBool(self.mainDaemonAlive))
        self.reportServerBut.grid(row=1, column=0, sticky=W)
        reportClientFrame.pack(side=TOP,
                               fill=X,
                               padx=20,
                               pady=10,
                               ipadx=20,
                               ipady=5)
        Separator(self.window, orient="horizontal").pack(side=TOP,
                                                         padx=20,
                                                         fill=X)
        #Refresh status frame
        reloadFrame = Frame(self.window)
        Button(reloadFrame, text="Reload",
               command=self.getDaemonStatus).grid(row=0, column=1, sticky=E)
        reloadFrame.pack(side=TOP, fill=X, padx=20, pady=10, ipadx=20, ipady=5)
        Separator(self.window, orient="horizontal").pack(side=TOP,
                                                         padx=20,
                                                         fill=X)
        return

    def modelConfigFrame(self, parent):
        """
    Create and place next under parent a frame containing the current model configuration.
    """
        #Create container
        frame = Frame(parent)
        #Create treeView for model configuration
        self.modelTree = Treeview(parent, columns=('size', 'modified'))
        self.populateModelTree()
        self.modelTree.grid(row=1)

        #Bind right-click (<Button-3>) on tree items for contextual menus
        def treeContextualMenu(event):
            itemId = self.modelTree.identify_row(event.y)
            if itemId:
                self.modelTree.selection_set(itemId)
                item = self.modelTree.selection()
                ctxMenu = Menu(self.window, tearoff=0)
                ctxMenu.add_separator()
                if item[0][:4] == "tag:":
                    tag = item[0][4:]
                    ctxMenu.add_command(
                        label="Add samples (from a csv file)",
                        command=lambda: self.addSampleFileToModelDir(tag))
                    ctxMenu.add_separator()
                    ctxMenu.add_command(
                        label="Visualize feature map w.r.t loaded model",
                        command=lambda: self.testOnLoadedModel(
                            join(configs["model_data_dir"], tag), True))
                elif item[0][:5] == "file:":
                    filename = item[0][5:]
                    ctxMenu.add_command(
                        label="Test on loaded model",
                        command=lambda: self.testOnLoadedModel(
                            join(configs["model_data_dir"], filename), False))
                    ctxMenu.add_separator()
                    ctxMenu.add_command(
                        label="Delete",
                        command=lambda: self.deleteModelFile(filename))
                ctxMenu.add_separator()
                ctxMenu.tk_popup(event.x_root, event.y_root)

        self.modelTree.bind("<Button-3>", treeContextualMenu)
        return frame

    def testOnLoadedModel(self, sampleFile, isDir):
        try:
            modelviz.model_viz(sampleFile, isDir)
        except Exception as exc:
            tkMessageBox.showinfo("Sorry!", exc)
        return

    def populateModelTree(self):
        if self.modelTree is None: return
        #Extract model tags
        tags = [s.strip() for s in configs["model_tags"].split(",")]
        self.modelTree.column('size', width=200, anchor='center')
        self.modelTree.column('modified', width=200, anchor='center')
        self.modelTree.heading('size', text='Length')
        self.modelTree.heading('modified', text='Modified')
        treeHeight = 0
        #Populate treeView with current configuration
        self.modelTree.delete(*self.modelTree.get_children())
        for i in range(len(tags)):
            treeHeight += 1
            dirName = join(configs["model_data_dir"], tags[i])
            children = self.getDirContentDescr(dirName)
            rowId = self.modelTree.insert('',
                                          i,
                                          "tag:{}".format(tags[i]),
                                          text=tags[i])
            for child in children:
                treeHeight += 1
                self.modelTree.insert(
                    rowId,
                    "end",
                    "file:{}/{}".format(tags[i], child['name']),
                    text=child['name'],
                    values=(child['size'], child['modified']))
        self.modelTree['height'] = treeHeight + 1
        return

    def addSampleFileToModelDir(self, tag):
        modelDir = join(configs["model_data_dir"], tag)
        file_opts = {
            'defaultextension': '.csv',
            'filetypes': [('CSV files', '.csv'), ('all files', '.*')],
            'initialdir': expanduser("~"),
            'title': 'Select data file'
        }
        filename = tkFileDialog.askopenfilename(**file_opts)
        try:
            modelLoader.add_file_to_model_dir(filename, modelDir)
        except Exception as exc:
            tkMessageBox.showerror("Error copying files", exc)
            return
        self.populateModelTree()
        tkMessageBox.showinfo(
            "Success", "Successfully copied data file {} to {}.".format(
                filename, modelDir))
        return

    def deleteModelFile(self, filename):
        if tkMessageBox.askyesno("Confirm deleting {}".format(filename),
                                 "Are you sure about deleting this file?"):
            try:
                remove(join(configs["model_data_dir"], filename))
                self.populateModelTree()
            except Exception, exc:
                tkMessageBox.showerror("Error deleting {}".format(filename),
                                       exc)
        return
Esempio n. 48
0
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)

        global e0, e1, e2, e3, e4, e5, e6, e7, e8, CbxVlr, observaciones, scroll, tree, pdfB, add
        global cc, arrend, inmueble, codigo, tel, valor
        global Cbx, meses, mes1, mes2, tiempo, fechapago, anio, mes
        global prop, nit, tp, subtotal, iva, total

        #VARIABLES
        tiempo = datetime.date.today()
        anio = time.strftime("%Y")
        mes = time.strftime("%B")
        fechapago = StringVar()

        cc = StringVar()
        arrend = StringVar()

        inmueble = StringVar()
        codigo = StringVar()
        tel = StringVar()
        valor = DoubleVar()

        prop = StringVar()
        nit = StringVar()
        tp = StringVar()

        subtotal = DoubleVar()
        iva = DoubleVar()
        total = DoubleVar()

        mes1 = StringVar()
        mes2 = StringVar()
        meses = [
            "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio",
            "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"
        ]

        #WIDGETS

        #=========================== HEADER ============================

        self.titleL = Label(self, text="FACTURA INQUILINO", font="bold")
        self.titleL.pack(pady=20, side=TOP)

        #========================= WRAPPER 1 ===========================

        wrapper = Frame(self)
        wrapper.pack(fill='both')

        #======================= DATOS GENERALES =======================

        self.lf = LabelFrame(wrapper, text="Datos generales")
        self.lf.pack(side=LEFT)  #-------------------------------

        self.f0 = Frame(self.lf)
        self.f0.pack(pady=5, fill=X)  #---------------------------

        self.ccnitL = Label(self.f0, text='CC/Nit:')
        self.ccnitL.pack(side=LEFT)
        e0 = Entry(self.f0, textvariable=cc, width=30)
        e0.pack(side=LEFT)

        self.b1 = Button(self.f0, text='Buscar', command=buscar)
        self.b1.pack(side=LEFT)

        self.f1 = Frame(self.lf)
        self.f1.pack(pady=5, fill=X)  #---------------------------

        self.nombreL = Label(self.f1, text='Nombre:')
        self.nombreL.pack(side=LEFT)
        e1 = Entry(self.f1, textvariable=arrend, width=50, state=DISABLED)
        e1.pack(side=LEFT, fill=X)

        self.f2 = Frame(self.lf)
        self.f2.pack(pady=5, fill=X)  #---------------------------

        self.inmuebleL = Label(self.f2, text='Inmueble:')
        self.inmuebleL.pack(side=LEFT)
        e2 = Entry(self.f2, textvariable=inmueble, state=DISABLED, width=48)
        e2.pack(side=LEFT, fill=X)

        self.f3 = Frame(self.lf)
        self.f3.pack(pady=5, fill=X)  #---------------------------

        self.inmuebleL = Label(self.f3, text='Código: ')
        self.inmuebleL.pack(side=LEFT)
        e3 = Entry(self.f3, textvariable=codigo, state=DISABLED, width=5)
        e3.pack(side=LEFT, fill=X)

        self.tel = Label(self.f3, text='Teléfono: ')
        self.tel.pack(side=LEFT)
        e4 = Entry(self.f3, textvariable=tel, state=DISABLED, width=15)
        e4.pack(side=LEFT, fill=X)

        self.precio = Label(self.f3, text='Arriendo $: ')
        self.precio.pack(side=LEFT)
        e5 = Entry(self.f3, textvariable=valor, state=DISABLED, width=15)
        e5.pack(side=LEFT, fill=X)

        #======================= DATOS PROPIETARIO =======================

        wrap = Frame(wrapper)
        wrap.pack(side=RIGHT)

        lf = LabelFrame(wrap, text="Propietario")
        lf.pack()  #-------------------------
        #lf.pack_forget()#-------------------------

        f0 = Frame(lf)
        f0.pack(pady=5, fill=X)  #---------------------------

        nombreL = Label(f0, text='Nombre: ')
        nombreL.pack(side=LEFT)
        e6 = Entry(f0, textvariable=prop, width=48, state=DISABLED)
        e6.pack(side=LEFT, fill=X)

        f1 = Frame(lf)
        f1.pack(pady=5, fill=X)  #---------------------------

        ccnitL = Label(f1, text='CC/Nit: ')
        ccnitL.pack(side=LEFT)
        e7 = Entry(f1, textvariable=nit, state=DISABLED, width=48)
        e7.pack(side=LEFT)

        f2 = Frame(wrap)
        f2.pack(pady=5, fill=X)  #---------------------------

        self.lb = Label(f2, text=None)
        self.lb.pack(side=LEFT)

        f3 = Frame(wrap)
        f3.pack(pady=5, fill=X)  #---------------------------
        """
		self.inmuebleL = Label(f2, text='Tipo Persona: ')
		self.inmuebleL.pack(side=LEFT)
		e8 = Entry(f2, textvariable=tp, state=DISABLED, width=40)
		e8.pack(side=LEFT,fill=X)
		"""

        l = Label(f3, text='SubTotal ')
        l.pack(side=LEFT)
        e8 = Entry(f3, textvariable=subtotal, state=DISABLED, width=12)
        e8.pack(side=LEFT, fill=X)

        l = Label(f3, text='IVA ')
        l.pack(side=LEFT)
        e9 = Entry(f3, textvariable=iva, state=DISABLED, width=12)
        e9.pack(side=LEFT, fill=X)

        l = Label(f3, text='Total ')
        l.pack(side=LEFT)
        e10 = Entry(f3, textvariable=total, state=DISABLED, width=12)
        e10.pack(side=LEFT, fill=X)

        f4 = Frame(wrap)
        f4.pack(pady=5, fill=X)  #---------------------------

        #========================= FACTURACIÓN =========================

        self.lf1 = LabelFrame(self, text="Periodo a facturar")
        self.lf1.pack(anchor=W, pady=5, fill=X)  #-------------------------

        self.f2 = Frame(self.lf1)
        self.f2.pack(pady=5, fill=X)  #---------------------------

        self.mesiniL = Label(self.f2, text='Mes inicial:')
        self.mesiniL.pack(padx=5, side=LEFT)

        CbxVlr = Combobox(self.f2,
                          textvariable=mes1,
                          values=meses,
                          width=10,
                          state=DISABLED)
        CbxVlr.set(mes)
        CbxVlr.pack(side=LEFT)

        self.emptyL = Label(self.f2)  ###VACIO###
        self.emptyL.pack(padx=5, side=LEFT)

        self.yeariniL = Label(self.f2, text='Año:')
        self.yeariniL.pack(side=LEFT)
        self.yeariniE = Entry(self.f2,
                              textvariable=fechapago,
                              width=8,
                              state=DISABLED)
        fechapago.set(anio)
        self.yeariniE.pack(side=LEFT)

        self.mesfinL = Label(self.f2, text='Mes final:')
        self.mesfinL.pack(padx=5, side=LEFT)

        self.mesfinCbx = Combobox(self.f2,
                                  textvariable=mes2,
                                  values=meses,
                                  width=10)
        self.mesfinCbx.set(mes)
        self.mesfinCbx.pack(side=LEFT)

        self.emptyL = Label(self.f2)  ###VACIO###
        self.emptyL.pack(padx=5, side=LEFT)

        self.yearfinL = Label(self.f2, text='Año:')
        self.yearfinL.pack(side=LEFT)
        self.yearfinE = Entry(self.f2, textvariable=fechapago, width=8)
        fechapago.set(anio)
        self.yearfinE.pack(side=LEFT)

        self.emptyL = Label(self.f2)  ###VACIO###
        self.emptyL.pack(padx=5, side=LEFT)

        pdfB = Button(self.f2,
                      text="Facturar",
                      command=agregar,
                      state=DISABLED)
        pdfB.pack(side=LEFT)

        #========================== TREEVIEW ===========================

        self.f3 = Frame(self)
        self.f3.pack(pady=5, fill=X)  #------------------------------------

        tree = Treeview(self.f3,
                        height=4,
                        show="headings",
                        columns=('col1', 'col2'))
        tree.pack(side=LEFT, fill=X, expand=1)

        tree.column('col1', width=250, anchor='center')
        tree.column('col2', width=5, anchor='center')

        tree.heading('col1', text='Descripción')
        tree.heading('col2', text='Valor')

        scroll = Scrollbar(self.f3, orient=VERTICAL, command=tree.yview)
        tree.configure(yscrollcommand=scroll.set)
        tree.bind("<Delete>", borrar)

        #======================== OBSERVACIONES ========================

        self.f4 = Frame(self)
        self.f4.pack(pady=5, fill=X)  #--------------------

        self.notesL = Label(self.f4, text='Observaciones:')
        self.notesL.pack(side=LEFT)

        self.f5 = Frame(self)
        self.f5.pack(pady=5, fill=X)  #-------------------

        observaciones = Text(self.f5, height=5)
        observaciones.pack(fill=X, side=LEFT, expand=1)

        #=========================== BOTONES ===========================

        footer = Frame(self)
        footer.pack()  #-------------------------------

        clean = Button(footer,
                       text='Cancelar',
                       bg='navy',
                       foreground='white',
                       activebackground='red3',
                       activeforeground='white',
                       command=cancelar)
        clean.pack(side=RIGHT)

        add = Button(footer,
                     text='Grabar',
                     bg='navy',
                     foreground='white',
                     activebackground='red3',
                     activeforeground='white',
                     command=grabar,
                     state=DISABLED)
        add.pack(side=RIGHT)
Esempio n. 49
0
	def __init__(self, parent, controller):
		Frame.__init__(self, parent)
		
		global docID, nombre, refbanco, tree, busqueda, info, delete
		global e3
		
		lupa = PhotoImage(file='img/lupa.png')
		
		docID = StringVar()
		nombre = StringVar()
		refbanco = StringVar()
		busqueda = StringVar()
		info = IntVar()
		
		#WIDGETS
		
		#=========================== HEADER ============================
		
		l0 = Label(self, text="BENEFICIARIOS", font="bold")
		l0.pack(pady=20, side=TOP)
		
		#=========================== WRAPPER ===========================
		
		wrapper = Frame (self)
		wrapper.pack(side=TOP, fill=Y)
		#wrapper.pack(side=LEFT, fill=Y) #UBICA EL FORM A LA IZQ
		
		f1 = Frame(wrapper)
		f1.pack(pady=5, fill=X)#-----------------------------------
		
		l1 = Label (f1, text="CC/Nit: ")
		l1.pack(side=LEFT)
		e1 = Entry (f1, textvariable=docID, width=20)
		e1.pack(side=LEFT)
		e1.bind("<KeyRelease>", caps)
		e1.focus_set()
		
		f2 = Frame(wrapper)
		f2.pack(pady=5, fill=X)#-----------------------------------
		
		l2 = Label (f2, text="Nombre: ")
		l2.pack(side=LEFT)
		e2 = Entry (f2, textvariable=nombre, width=60)
		e2.pack(side=LEFT, fill=X, expand=1)
		e2.bind("<KeyRelease>", caps)
		
		f3 = Frame(wrapper)
		f3.pack(pady=5, fill=X)#-----------------------------------
		
		l3 = Label (f3, text="Referencia Bancaria: ")
		l3.pack(side=LEFT)
		e3 = Entry (f3, textvariable=refbanco, width=60)
		e3.pack(side=LEFT, fill=X, expand=1)
		e3.bind("<KeyRelease>", caps)
		
		f4 = Frame(wrapper)
		f4.pack(pady=5, fill=X)#-----------------------------------
		
		b1 = Button (f4, text="Cargar", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=cargar)
		b1.pack(side=RIGHT)
		
		b2 = Button (f4, text="Agregar", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=agregar)
		b2.pack(side=RIGHT)
		
		#========================== TREEVIEW ===========================
		
		f5 = Frame(wrapper)
		f5.pack(pady=5, fill=X)#-----------------------------------
		
		tree = Treeview(f5, show="headings", columns=('col1','col2'))
		tree.pack(side=LEFT, fill=X, expand=1)
		tree.column('col1', width=0, anchor='center')
		tree.column('col2', width=150, anchor='w')
		
		tree.heading('col1', text='CC/Nit')
		tree.heading('col2', text='Nombre Completo')
		
		scroll = Scrollbar(f5,orient=VERTICAL,command=tree.yview)
		tree.configure(yscrollcommand=scroll.set)
		
		f6 = Frame(wrapper)
		f6.pack(pady=5, fill=X)#-----------------------------------
		
		delete = Button (f6, text="Eliminar", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=borrar)
		delete.pack(side=RIGHT)
		
		e4 = Entry(f6, textvariable=busqueda)
		e4.pack(side=LEFT)
		e4.bind("<KeyRelease>", caps)
		
		b4 = Button(f6, text='BUSCAR', image=lupa, command=buscar)
		b4.image = lupa
		b4.pack(side=LEFT)
		
		R1 = Radiobutton(f6, text="CC/nit", variable=info, value=1)
		R1.pack(side=LEFT)
		R2 = Radiobutton (f6, text="Nombre", variable=info, value=2)
		R2.pack(side=LEFT)
		info.set(1)
Esempio n. 50
0
class SnakeLog(Frame):

    def createMenubar(self, master):
        self.menubar = Menu(root)

        self.filemenu = Menu(self.menubar, tearoff=0)

        self.importmenu = Menu(self.filemenu)
        self.importmenu.add_command(label="from ADIF...", command=None)

        self.exportmenu = Menu(self.filemenu)
        self.exportmenu.add_command(label="to ADIF...", command=None)
        self.exportmenu.add_command(label="to Cabrillo...", command=None)

        self.filemenu.add_command(label="Open log...", command=None)
        self.filemenu.add_command(label="Save log as...", command=None)
        self.filemenu.add_separator()
        self.filemenu.add_cascade(label="Export", menu=self.exportmenu)
        self.filemenu.add_cascade(label="Import", menu=self.importmenu)
        self.filemenu.add_separator()
        self.filemenu.add_command(label="Exit", command=None)

        self.menubar.add_cascade(label="File", menu=self.filemenu)

        master.config(menu=self.menubar)

    def createQSOView(self, master):
        self.qsoviewScrollbar = Scrollbar(master)
        self.qsoview = Treeview(master, show=('headings'),
                                yscrollcommand=self.qsoviewScrollbar.set)


        self.qsoviewfields = {'day':            {'name': "D", 'width': 10},
                              'month':          {'name': "M", 'width': 10},
                              'year':           {'name': "Y", 'width': 20},
                              'timeon':         {'name': "Time", 'width': 30},
                              'timeoff':        {'name': "Timeoff", 'width': 30},
                              'band':           {'name': "Band", 'width': 20},
                              'freq':           {'name': "Frequency", 'width': 50},
                              'mode':           {'name': "Mode", 'width': 25},
                              'call':           {'name': "Call", 'width': 50},
                              'srst':           {'name': "S RST", 'width': 25},
                              'rrst':           {'name': "R RST",'width': 25},
                              'name':           {'name': "Name",'width': 40},
                              'grid':           {'name': "Gridsquare",'width': 30},
                              'iota':           {'name': "IOTA", 'width': 30},
                              'qsls':           {'name': "Q S",'width': 25},
                              'qsls_date':      {'name': "Q S D",'width': 50},
                              'qslr':           {'name': "Q R",'width': 25},
                              'qslr_date':      {'name': "Q R D",'width': 50},
                              'lotw_qsls':      {'name': "LQ S",'width': 25},
                              'lotw_qsls_date': {'name': "LQ S D",'width': 50},
                              'lotw_qslr':      {'name': "LQ R",'width': 25},
                              'lotw_qslr_date': {'name': "LQ R D",'width': 50}}


        self.qsoviewdisplayesfields = ('day', 'month', 'year', 'timeon',
                                       'band', 'freq', 'mode', 'call',
                                       'srst', 'rrst', 'name', 'grid',
                                       'iota', 'qsls', 'qsls_date', 'qslr',
                                       'qslr_date', 'lotw_qsls', 'lotw_qsls_date', 'lotw_qslr',
                                       'lotw_qslr_date')


        self.qsoview["columns"] = self.qsoviewfields.keys()
        self.qsoview["displaycolumns"] = self.qsoviewdisplayesfields


        self.qsoview.column(0, width=40)
        for columnname, data in self.qsoviewfields.items():
            # set columnwidth for QSOView
            self.qsoview.column(columnname, width=data['width'])
            # set QSOView headers
            self.qsoview.heading(columnname, text=data['name'])

        for i in range(400):
            self.qsoview.insert('', 'end', str(i), values=(str(i), 'bar'+str(i)))

        self.qsoviewScrollbar.config(command=self.qsoview.yview)

        self.qsoviewScrollbar.grid(column=1, row=0, sticky=(N,S))
        self.qsoview.grid(column=0, row=0, sticky=(N,S,E,W))

        master.columnconfigure(0, weight=1)
        master.rowconfigure(0, weight=1)

    def __init__(self, master=None):

        master.columnconfigure(0, weight=1)
        master.rowconfigure(0, weight=1)

        self.mainFrame = Frame.__init__(self, master)

        self.grid(sticky=(N,S,E,W))
        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        self.createMenubar(master)

        self.qsoFrame = Frame(self.mainFrame)
        self.createQSOView(self.qsoFrame)
        self.qsoFrame.grid(sticky=(N,S,E,W))
Esempio n. 51
0
class XML_Viwer(Frame):
    def __init__(self,
                 master,
                 xml=None,
                 heading_text=None,
                 heading_anchor=None,
                 padding=None,
                 cursor=None,
                 takefocus=None,
                 style=None):
        Frame.__init__(self, master, class_="XML_Viwer")

        self._vsb = Scrollbar(self, orient=VERTICAL)
        self._hsb = Scrollbar(self, orient=HORIZONTAL)

        kwargs = {}
        kwargs["yscrollcommand"] = lambda f, l: autoscroll(self._vsb, f, l)
        kwargs["xscrollcommand"] = lambda f, l: autoscroll(self._hsb, f, l)

        if style is not None:
            kwargs["style"] = style

        if padding is not None:
            kwargs["padding"] = padding

        if cursor is not None:
            kwargs["cursor"] = cursor

        if takefocus is not None:
            kwargs["takefocus"] = takefocus

        self._treeview = Treeview(self, **kwargs)

        if heading_text is not None:
            if heading_anchor is not None:
                self._treeview.heading("#0",
                                       text=heading_text,
                                       anchor=heading_anchor)
            else:
                self._treeview.heading("#0", text=heading_text)

        self._treeview.bind("<<TreeviewOpen>>", self._on_open)
        self._treeview.bind("<<TreeviewClose>>", self._on_close)

        # Without this line, horizontal scrolling doesn't work properly.
        self._treeview.column("#0", stretch=False)

        self._vsb['command'] = self._treeview.yview
        self._hsb['command'] = self._treeview.xview

        self._treeview.grid(column=0, row=0, sticky=N + S + W + E)
        self._vsb.grid(column=1, row=0, sticky=N + S)
        self._hsb.grid(column=0, row=1, sticky=E + W)

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

        self._element_tree = None
        self._item_ID_to_element = {}

        if xml is not None:
            self.parse_xml(xml)

    def _on_open(self, event):
        item_ID = self._treeview.focus()
        if item_ID not in self._item_ID_to_element: return

        node = self._item_ID_to_element[item_ID]

        self._treeview.item(item_ID, text=self._repr_of_openning_tag(node))

    def _on_close(self, event):
        item_ID = self._treeview.focus()
        if item_ID not in self._item_ID_to_element: return

        node = self._item_ID_to_element[item_ID]

        text = self._repr_of_openning_tag(node) + self._repr_of_closing_tag(
            node)
        self._treeview.item(item_ID, text=text)

    def parse_xml(self, xml):
        self._element_tree = ET.ElementTree(ET.fromstring(xml))

        self.clear()
        self._walk_xml(self._element_tree.getroot())

    @property
    def element_tree(self):
        return self._element_tree

    @element_tree.setter
    def element_tree(self, element_tree):
        self._element_tree = element_tree

        self.clear()
        self._walk_xml(element_tree.getroot())

    def clear(self):
        self._item_ID_to_element = {}
        self._treeview.delete(*self._treeview.get_children())

    def _repr_of_openning_tag(self, node):
        text = "<" + node.tag

        attrs = node.attrib

        # list function is here necessary to provide support to Python 3
        a_names = list(attrs.keys())
        a_names.sort()

        for a_name in a_names:
            text += ' %s="' % a_name
            text += attrs[a_name]
            text += '"'

        text += ">"
        return text

    def _repr_of_closing_tag(self, node):
        return "</%s>" % node.tag

    def _walk_xml(self, node, depth=0, parent=""):
        text = self._repr_of_openning_tag(node) + self._repr_of_closing_tag(
            node)

        item = self._treeview.insert(parent, END, text=text)
        self._item_ID_to_element[item] = node

        if node.text:
            text = node.text.strip()
            if text != "":
                for line in text.splitlines():
                    self._treeview.insert(item, END, text=line)

        child_nodes = sorted(list(node), key=attrgetter('tag'))
        for child_node in node:
            self._walk_xml(child_node, depth + 1, parent=item)

        if node.tail:
            tail = node.tail.strip()
            if tail != "":
                for line in tail.splitlines():
                    self._treeview.insert(parent, END, text=line)
Esempio n. 52
0
class WaitingRoom(cll.ClientListener, object): #Note: extending cll.ClientListener if Gui does not extend WaitingRoom
    def __init__(self):
        self.Names = []
        self.tree_headers = ['Player','Status','Address','Game','Color']
        self.quit = False   #quit program after wroom has been closed. it will be passed to Gui.quit

    def startWaitingRoomUI(self, pumpit):
        self.pumpit = True
        if 'pumpit' in locals():
            self.pumpit = pumpit
        cfg.wroom = Tk()
        cfg.wroom.protocol("WM_DELETE_WINDOW", self.quitWaitingRoom)

        """State variables - By using textvariable=var in definition widget is tied to this variable"""
        statusmsg_sv = StringVar() #needed
        entry_sv = StringVar(value = cfg.name)
        #entry_sv.trace("w", lambda name, index, mode, sv=entry_sv: self.changeName(sv))
        chatentry_sv = StringVar(value = "Press enter to chat")

        """Create and grid the outer content frame"""
        content = ttk.Frame(cfg.wroom) #, padding=(5, 5, 12, 0)) 		#Frame in cfg.wroom
        content.grid(column = 0, row = 0, sticky = (N,W,E,S))
        cfg.wroom.grid_columnconfigure(0, weight = 1)
        cfg.wroom.grid_rowconfigure(0, weight = 1)

        """Create the different widgets; note the variables that some widgets are bound to"""
        self.tree = Treeview(content, show="headings", columns=cfg.wroominstance.tree_headers, name = "treeview")
        self.tree.column("#1", minwidth = 100, width = 120, stretch = NO)
        self.tree.column("#2", minwidth = 30, width = 60, stretch = NO)
        self.tree.column("#3", minwidth = 30, width = 50, stretch = YES)
        self.tree.column("#4", minwidth = 30, width = 50, stretch = YES)
        self.tree.column("#5", minwidth = 30, width = 50, stretch = YES)
        namelbl = ttk.Label(content, text="Player name")
        self.nameentry = ttk.Entry(content, bg = 'white', textvariable = entry_sv, name = "nameentry")#, validatecommand=validateIt)
        colorlbl = ttk.Label(content, text="Player color")
        self.colorframe = ttk.Frame(content, name = "colorframe", borderwidth = 1, relief='sunken')
        lbl = ttk.Label(content, text="Send to player:")	#Label on the right
        self.log = Listbox(content, height = 5, bg = 'white', name = "logbox")#, listvariable=cmessagelog		#Listbox with messages
        self.chatAll = ttk.Button(content, text = 'Chat to All', command = self.chatToAll, default = 'active', width = '6',name = "chat")
        self.chatentry = ttk.Entry(content, bg = 'white', foreground = 'gray', textvariable = chatentry_sv, name = "chatentry", selectforeground = 'blue')
        testbtn = ttk.Button(content, text = 'Connections', command = self.test, default = 'active', width = '6', name = "testbtn")
        ready = ttk.Button(content, text = 'Ready', command = self.toggleReadyForGame, default = 'active', width = '6', name = "readybtn")
        solitaire = ttk.Button(content, text = 'Solitaire', command = self.solitaire, default = 'active', width = '6', name = "solitairebtn")
        quit = ttk.Button(content, text = 'Quit', command = self.quitWaitingRoom, default = 'active', width = '6', name = "quitbtn")
        status = ttk.Label(content, textvariable = statusmsg_sv, anchor = W, name = "statuslbl") #Label on the bottom

        def get_tree():
            """Get from the self.tree an item when clicked"""
            idxs = self.tree.item(self.tree.focus())
            vals = idxs['values']
            if len(idxs['values'])==0: return None
            return vals
        """def sortby(tree, col, descending):
            Sort tree contents when a column header is clicked on
            # grab values to sort
            data = [(tree.set(child, col), child) \
                for child in tree.get_children('')]
            # now sort the data in place
            data.sort(reverse=descending)
            for ix, item in enumerate(data):
                tree.move(item[1], '', ix)
            # switch the heading so it will sort in the opposite direction
            tree.heading(col, command=lambda col=col: sortby(tree, col, int(not descending)))
        """
        def showstatus(*args):
            """Called when the selection in the listbox changes;
            Update the status message on the bottom with the new information"""
            list = get_tree()
            if list is None:
                return
            statusmsg_sv.set("Player %s has this status: %s" % (list[0], list[1]))

        # Grid all the widgets
        self.tree.grid(row = 0, column = 0, rowspan = 9, sticky = (N,S,E,W))
        namelbl.grid(row = 0, column = 1, columnspan = 2, sticky = (N,W), padx = 5)
        self.nameentry.grid(row = 1, column = 1, columnspan = 2, sticky = (N,E,W), pady = 5, padx = 5)
        colorlbl.grid(row = 0, column = 3, columnspan = 1, sticky = (N,W), padx = 5)
        self.colorframe.grid(row = 1, column = 3, columnspan = 1, sticky = (N,E,W), pady = 5, padx = 5)
        #testbtn.grid(row = 3, column = 3, columnspan = 1, sticky = E, padx = 5)		#Test Button
        self.log.grid(row = 5, column = 1, columnspan = 3, sticky = (N,S,E,W), padx = 5, pady = 5)   #Listbox with all messages
        self.chatentry.grid(row = 6, column = 1, columnspan = 2, sticky = (N,E), padx = 5, pady = 5)
        self.chatAll.grid(row = 6, column = 3, columnspan = 1, sticky = (N,E), padx = 5, pady = 5)
        ready.grid(row = 7, column = 1, sticky = (W,S), padx = 5, pady = 5)			#
        solitaire.grid(row = 7, column = 2, sticky = (W,S), padx = 5, pady = 5)
        quit.grid(row = 7, column = 3, sticky = (W,S), padx = 5, pady = 5)
        status.grid(row = 9, column = 0, columnspan = 2, sticky = (W,E))

        """Configure content Frame and color Frame"""
        content.grid_columnconfigure(0, weight = 1)
        content.grid_rowconfigure(5, weight = 1)
        h = self.nameentry.winfo_reqheight()
        self.colorframe.configure(height = h, bg = 'red')

        """Set event bindings"""
        self.tree.bind('<<TreeviewSelect>>', showstatus)
        self.nameentry.bind('<Return>', (lambda _: self.askChangeName(self.nameentry)))
        self.nameentry.bind('<FocusOut>', (lambda _: self.askChangeName(self.nameentry)))
        cfg.wroom.bind('<Control-Key-w>', self.quitWaitingRoom)
        cfg.wroom.bind('<Control-Key-q>', self.quitWaitingRoom)
        cfg.wroom.bind('<Control-Key-r>', self.toggleReadyForGame)
        cfg.wroom.bind('<Control-Key-s>', self.solitaire)
        self.chatentry.bind("<Return>",self.chatToAll)
        def chatEntryActive(e = None):
            self.chatentry.config(foreground = 'black')
            self.chatentry.delete(0, 'end')
        def chatEntryInactive(e = None):
            print(self)
            chatentry_sv.set("Press enter to chat")
            self.chatentry.config(foreground = 'gray')
        self.chatentry.bind("<FocusIn>", lambda e: chatEntryActive(e))
        self.chatentry.bind("<FocusOut>", lambda e: chatEntryInactive(e))
        self.colorframe.bind("<ButtonRelease-1>", self.changeColor)

        """Set tooltips on widgets"""
        hover.createToolTip(namelbl, "Type in your name")
        hover.createToolTip(self.nameentry, "Type in your name")
        hover.createToolTip(ready, "Toggle ready state to play tantrix with other players")
        hover.createToolTip(solitaire, "Start a two player game on this computer")
        hover.createToolTip(quit, "Quit Tantrix")
        hover.createToolTip(self.chatentry, "Press enter to send to chat")
        hover.createToolTip(self.chatAll, "Press enter to send to chat")
        hover.createToolTip(self.colorframe, "Click to select your color")
        hover.createToolTip(colorlbl, "Your color")

        """Set the starting state of the interface"""
        statusmsg_sv.set('')
        showstatus()

        """Start main loop for tkinter and Sixpodnet"""
        self.keepLooping = True
        if self.pumpit:
            self.mainLoopWithPump()
        else:
            self.mainLoopWithoutPump()
        return self.quit

    def test(self):
        if self.pumpit:
            self.send_to_server("test")

    def chatToAll(self, e = None):
        """Chat to every player in the wroom"""
        """Get the chat entry and add it to the local log"""
        msgList = [self.chatentry.get()]
        if len(msgList[0]) is 0: return
        """Send message to server"""
        self.sendChatToAll(msgList = msgList)
        """Clear chat entry"""
        self.chatentry.delete(0, 'end')
        self.chatentry.focus_set()


    def buildTree(self, tree_list):
        def sortby(tree, col, descending):
            """Sort tree contents when a column header is clicked on"""
            # grab values to sort
            data = [(tree.set(child, col), child) \
                for child in tree.get_children('')]
            # now sort the data in place
            data.sort(reverse=descending)
            for ix, item in enumerate(data):
                tree.move(item[1], '', ix)
            # switch the heading so it will sort in the opposite direction
            tree.heading(col, command=lambda col=col: sortby(tree, col, int(not descending)))

        for ind, col in enumerate(self.tree_headers):
            self.tree.heading(ind, text=col.title(),command=lambda c=col: sortby(self.tree, c, 0))#
            # adjust the column's width to the header string
            #self.tree.column(col, width=tkFont.Font().measure(col.title()))
        """Convert Status and Game to a better format, then insert in Treeview"""
        convert_status = {0: "Idle", 1: "Ready", -1: "Playing", -2: "Solitaire"}
        for item in tree_list:
            item[1] = convert_status[item[1]]
            if item[3] is None: item[3] = ""
            self.tree.insert('', 'end', values=item)
            # adjust column's width if necessary to fit each value
            #import Tkinter.font as tkFont
            #for ix, val in enumerate(item):
                #col_w = tkFont.Font().measure(val)
            #if self.tree.column(selfcfg.wroominstance.tree_headers[ix],width=None)<col_w:
                #self.tree.column(selfcfg.wroominstance.tree_headers[ix], width=col_w)

    def addToMessageLog(self, listToLog, fg = 'black'):
        """Add a line to the log listbox"""
        for item in listToLog:
            self.log.insert(END, item)
            self.log.itemconfig(END, {'fg': fg})
        self.log.select_set(END)
        self.log.yview(END)

    def searchTreeByHeader(self, val, header = 'Player'):
        """Return item in Treeview by player name"""
        val = str(val)
        items = self.tree.get_children()
        headerIndToSearchInto = cfg.wroominstance.tree_headers.index(header) # ['Player','Status','Address']
        for item in items:
            itemval = str(self.tree.item(item, 'values')[headerIndToSearchInto])
            if itemval.startswith(val):
                return item
        return None

    def editItemInTree(self, item, valList, headerList = ['Player']):
        """Edit an item of TreeView by its header(s)"""
        #Get the current (old) values as a list
        old_vals = self.tree.item(item)['values']
        #Create a list with the new values
        newvalues = list(old_vals)
        for ind, header in enumerate(headerList):
            #Get from headerList which index should be changed
            headerIndex = cfg.wroominstance.tree_headers.index(header)
            newvalues[headerIndex] = valList[ind]
        #Finally change the old values
        self.tree.item(item, values=newvalues)

    def removeFromTree(self, name = ''):
        """remove an item of TreeView by its name filed"""
        item = self.searchTreeByHeader(name, header = 'Player')
        if item is not None:
            self.tree.delete(item)

    def askChangeName(self, sv):
        """User wants to change name. Ask server if ok"""
        name = sv.get()
        self.sendChangedName(name)

    def changeName(self, name):
        """Server sends the name of this player"""
        self.nameentry.delete(0, END)
        self.nameentry.insert(0, name)
        cfg.name = name
        cfg.wroom.title(name + ": waiting room")
        cfg.wroom.update()

    def changeColor(self, e = None):
        current = self.colorframe.cget('bg')
        color_ind = cfg.PLAYERCOLORS.index(current) + 1
        color = cfg.PLAYERCOLORS[color_ind % 4]
        self.colorframe.configure(bg = color)
        cfg.playercolor = color
        self.sendChangedColor(color)

    def toggleReadyForGame(self, e = None):
        if self.pumpit:
            self.sendToggleReady()
            #Change button layout when clicked
            frame = cfg.wroom.winfo_children()[0]
            readybtn = frame.children['readybtn']
            """Configure the button"""
            if readybtn.config('relief')[4]=='raised':
                readybtn.configure(relief='sunken')
                readybtn.configure(bg = 'green')
            elif readybtn.config('relief')[4]=='sunken':
                readybtn.configure(relief='raised')
                readybtn.configure(bg = '#d6d6d6')
            sleep(0.1)
            cfg.wroom.update()

    def quitWaitingRoom(self, e = None):
        print("Quitting the waiting room")
        self.keepLooping = False
        self.quit = True    #used to quit everything after wroom has been closed
        if self.pumpit:
            self.send_to_server("quit")

    def solitaire(self, e = None):
        print("Starting a game on one client (solitaire)")
        cfg.solitaire = True
        self.keepLooping = False
        if self.pumpit:
            self.sendSolitaire()
        #cfg.wroominstance.tree = None

    def mainLoopWithoutPump(self):
        """Start main loop in waiting room. Do not use Sixpodnet to connect with server"""
        while self.keepLooping: #self.keepLooping changed by callbacks below
            """Update the boards"""
            cfg.wroom.update()
            cfg.wroom.update_idletasks()
        cfg.wroom.destroy()

    def mainLoopWithPump(self):
        """Start main loop in waiting room"""
        while self.keepLooping:      #self.keepLooping changed by callbacks below
            """Polling loop for the client. asks the connection singleton for any new messages from the network"""
            connection.Pump()
            """Server"""
            self.Pump()
            """Check if there is a connection. If so start the waiting room, else go to preSolitaire"""
            if cfg.connected:
                """Update the boards"""
                cfg.wroom.update()
                cfg.wroom.update_idletasks()
            else:
                global attempt2connect
                attempt2connect += 1
                if attempt2connect == 20:
                    self.solitaire()
        cfg.wroom.destroy()
Esempio n. 53
0
        def __init__(self, parent, controller):
                Frame.__init__(self, parent)
		
		global info, tree
		
		#VARIABLES
		info = IntVar()
		
		#WIDGETS
		
		#========================= HEADER ===========================
		
		self.header = Label(self, text="ADMINISTRADOR DE DOCUMENTOS", font="bold")
		self.header.pack(pady=20, side=TOP)
		
		#========================= WRAPPER 1 ===========================
		
		self.wrapper = Frame (self)
		self.wrapper.pack(side=LEFT, fill=Y)

		#======================== DOCUMENTOS DE ========================
		
		self.f0 = Frame(self.wrapper)
		self.f0.pack(pady=5,fill=X)#------------------------------------

		self.lf1 = LabelFrame(self.f0, text="Documentos de")#---------->

		self.f1 = Frame(self.lf1)
		self.f1.pack(pady=5, side=LEFT)
		
		self.pR1 = Radiobutton(self.f1, text="Propietario", variable=info, value=1, command=select)
		self.pR1.grid(row=0, column=0, sticky=W)
		self.aR2 = Radiobutton (self.f1, text="Arrendatario", variable=info, value=2, command=select)
		self.aR2.grid(row=1, column=0, sticky=W)
		self.tR3 = Radiobutton (self.f1, text="Tercero", variable=info, value=3, command=select)
		self.tR3.grid(row=2, column=0, sticky=W)
		
		self.lf1.pack(side=LEFT)#<--------------------------------------
		
		#====================== FECHAS DE BÚSQUEDA =====================
		
		self.lf2 = LabelFrame(self.f0, text="Fechas de búsqueda")#------>

		self.f2 = Frame(self.lf2)
		self.f2.pack(pady=5)#---------------------------
		
		self.deL = Label(self.f2, text='De:')
		self.deL.pack(side=LEFT)
		
		self.deCbx = Combobox(self.f2, width=32)
		self.deCbx.set('')
		self.deCbx.pack(side=LEFT)
		
		self.f3 = Frame(self.lf2)
		self.f3.pack(pady=5)#---------------------------
		
		self.hastaL = Label(self.f3, text='Hasta:')
		self.hastaL.pack(side=LEFT)
		
		self.hastaCbx = Combobox(self.f3, width=30)
		self.hastaCbx.set('')
		self.hastaCbx.pack(side=LEFT)

		self.lf2.pack(side=LEFT, fill=X)#<---------------------------

		#========================= WRAPPER 2 ===========================
		
		self.wrapper2 = Frame (self.wrapper)
		self.wrapper2.pack(pady=5,fill=X)
		
		#========================= BENEFICIARIO ========================
		
		self.box1 = Frame(self.wrapper2)
		self.box1.pack(side=LEFT)
		
		#---------------------------------------------------------------
		
		self.f4 = Frame(self.box1)
		self.f4.pack()
		
		self.l1 = Label(self.f4, text="Beneficiario")
		self.l1.pack()

		tree = Treeview(self.f4, height=7, show="headings", columns=('col1','col2'))
		tree.pack(side=LEFT, fill=X, expand=1)
		tree.column('col1', width=100, anchor='center')
		tree.column('col2', width=180, anchor='center')
		
		tree.heading('col1', text='CC')
		tree.heading('col2', text='Nombres')
		
		self.scroll = Scrollbar(self.f4,orient=VERTICAL,command=tree.yview)
		tree.configure(yscrollcommand=self.scroll.set)

		self.f5 = Frame(self.box1)#----------------------------------
		self.f5.pack()
		
		self.lf3 = LabelFrame(self.f5, text="Factura Propietario")#---->
		
		self.e1 = Entry(self.lf3, width=12).pack(side=LEFT)
		self.anularCk = Checkbutton(self.lf3, text="Anular").pack(side=LEFT)
		self.viewB = Button(self.lf3, text='Visualizar').pack(side=LEFT)
		
		self.lf3.pack(side=LEFT)#<--------------------------------------
		
		#========================== FACTURAS ==========================
		
		self.box2 = Frame(self.wrapper2)
		self.box2.pack(side=LEFT)
		
		#---------------------------------------------------------------
		
		self.f6 = Frame(self.box2)
		self.f6.pack()
		
		self.l2 = Label(self.f6, text="Facturas")
		self.l2.pack()

		self.tree = Treeview(self.f6, height=7, show="headings", columns=('col1','col2'))
		self.tree.pack(side=LEFT, fill=X, expand=1)
		self.tree.column('col1', width=100, anchor='center')
		self.tree.column('col2', width=100, anchor='center')
		
		self.tree.heading('col1', text='Número')
		self.tree.heading('col2', text='Valor')
		
		self.scroll = Scrollbar(self.f6,orient=VERTICAL,command=self.tree.yview)
		self.tree.configure(yscrollcommand=self.scroll.set)
		
		self.f7 = Frame(self.box2)#----------------------------------
		self.f7.pack()
		
		self.lf4 = LabelFrame(self.f7, text="Factura Arrendatario")#---->
		
		self.e1 = Entry(self.lf4, width=12).pack(side=LEFT)
		self.anularCk = Checkbutton(self.lf4, text="Anular").pack(side=LEFT)
		self.viewB = Button(self.lf4, text='Ver', width=5).pack(side=LEFT)
		
		self.lf4.pack(side=LEFT)#<--------------------------------------
		
		#========================== RECIBOS ==========================
		
		self.box3 = Frame(self.wrapper2)
		self.box3.pack(side=LEFT)
		
		#---------------------------------------------------------------
		
		self.f8 = Frame(self.box3)
		self.f8.pack()
		
		self.l3 = Label(self.f8, text="Recibos de caja")
		self.l3.pack()

		self.tree = Treeview(self.f8, height=7, show="headings", columns=('col1','col2'))
		self.tree.pack(side=LEFT, fill=X, expand=1)
		self.tree.column('col1', width=100, anchor='center')
		self.tree.column('col2', width=100, anchor='center')
		
		self.tree.heading('col1', text='Número')
		self.tree.heading('col2', text='Valor')
		
		self.scroll = Scrollbar(self.f8,orient=VERTICAL,command=self.tree.yview)
		self.tree.configure(yscrollcommand=self.scroll.set)
		
		self.f9 = Frame(self.box3)#----------------------------------
		self.f9.pack()
		
		self.lf5 = LabelFrame(self.f9, text="Recibos de caja")#---->
		
		self.e1 = Entry(self.lf5, width=12).pack(side=LEFT)
		self.anularCk = Checkbutton(self.lf5, text="Anular").pack(side=LEFT)
		self.viewB = Button(self.lf5, text='Ver', width=5).pack(side=LEFT)
		
		self.lf5.pack(side=LEFT)#<--------------------------------------
		
		#===================== COMPROBANTE DE PAGO =====================
		
		self.box4 = Frame(self.wrapper2)
		self.box4.pack(side=LEFT)
		
		#---------------------------------------------------------------
		
		self.f10 = Frame(self.box4)
		self.f10.pack()
		
		self.l4 = Label(self.f10, text="Comprobantes de pago")
		self.l4.pack()

		self.tree = Treeview(self.f10, height=7, show="headings", columns=('col1','col2'))
		self.tree.pack(side=LEFT, fill=X, expand=1)
		self.tree.column('col1', width=100, anchor='center')
		self.tree.column('col2', width=100, anchor='center')
		
		self.tree.heading('col1', text='Número')
		self.tree.heading('col2', text='Valor')
		
		self.scroll = Scrollbar(self.f10,orient=VERTICAL,command=self.tree.yview)
		self.tree.configure(yscrollcommand=self.scroll.set)
		
		self.f11 = Frame(self.box4)#----------------------------------
		self.f11.pack()
		
		self.lf6 = LabelFrame(self.f11, text="Pagos")#---->
		
		self.e1 = Entry(self.lf6, width=12).pack(side=LEFT)
		self.anularCk = Checkbutton(self.lf6, text="Anular").pack(side=LEFT)
		self.viewB = Button(self.lf6, text='Ver', width=5).pack(side=LEFT)
		
		self.lf6.pack(side=LEFT)#<--------------------------------------
Esempio n. 54
0
class Statistics(Toplevel):	
	def __init__(self,parent):
		Toplevel.__init__(self,parent)
		self.title("Статистика")	
		self.transient(parent)
		self.parent = parent

	#fields for parameters of search-----------------------------------------------------------------------------------
		paramframe = Frame(self,relief=GROOVE,width=200,bd=1)
		paramframe.pack(side=LEFT,fill=BOTH)

		Label(paramframe, text="Что вывести",width=20,height=2).grid(row=0,column=0,columnspan=2)
		what = Combobox(paramframe,state='readonly',values = [u"Расходы",u"Доходы",u"Всё"],height=5)
		what.set(u"Расходы")
		what.grid(row=1,column=0,columnspan=2)
		self.what = what		
		
		Label(paramframe, text="За период",height=2).grid(row=2,column=0,columnspan=2)
		when = Combobox(paramframe,state='readonly',values=[u"Сегодня",u"3 дня",u"5 дней",u"Неделю",u"3 недели",u"Месяц",u"Всё время"],height=5)
		when.set(u"Сегодня")
		when.grid(row=3,column=0,columnspan=2)
		self.when = when
		
		Label(paramframe,text="Упорядочить по",height=2).grid(row=4,column=0,columnspan=2)
		orderby = Combobox(paramframe,state='readonly',values=[u"Дата",u"Cумма",u"Категория"],height=3)
		orderby.set(u"Дата")
		orderby.grid(row=5,column=0,columnspan=2)
		
		self.orderby = orderby		

		Button(paramframe,text="Вывести",command=(lambda: self.getStatistics())).grid(row=6,column=0,columnspan=2)		

		Label(paramframe,text="Итого: ",height=20).grid(row=7,column=0)
		self.summarylbl = Label(paramframe,text='0.0',height=20)
		self.summarylbl.grid(row=7,column=1)


	#end ------------------------------------------------------------------------------------------------------------------
		
	#table -------------------------------------------------------------------------------------------------------------
		
		self.viewframe = Frame(self,relief=GROOVE,width=200,bd=1)
		self.viewframe.pack(side=RIGHT,fill=BOTH,expand=YES)

	#end ------------------------------------------------------------------------------------------------------------------

		self.geometry("%dx%d+%d+%d" % (1000,500,225,125))
		self.wait_window(self)
	
	def getStatistics(self):
		when = self.when.current()
		dateRange = ''
		
		if when == 0:
		#today
			dateRange = datetime.date.today()
		elif when == 1:
		#3 days
			dateRange = datetime.date.today() - datetime.timedelta(days=3)
		elif when == 2:
		#5 days
			dateRange = datetime.date.today() - datetime.timedelta(days=5)
		elif when == 3:
		#1 week
			dateRange = datetime.date.today() - datetime.timedelta(weeks=1)
		elif when == 4:
		#3 weeks
			dateRange = datetime.date.today() - datetime.timedelta(weeks=3)
		elif when == 5:
		#1 month
			dateRange = datetime.date.today() - datetime.timedelta(weeks=4)
		elif when == 6:
		#all 
			dateRange = '2012-01-01'
		
		orderby = self.orderby.current()
		if orderby == 0:
		#date
			orderby = 4
		elif orderby == 1:
		#summ
			orderby = 2
		elif orderby == 2:
		#c.title
			orderby = 6
			
		global payments
		payments.getPayments(1,str(dateRange))
		
		if hasattr(self, 'tree'):
			self.tree.destroy()
			
		self.tree = Treeview(self.viewframe,selectmode="extended",columns=('summ', 'comment', 'date','mul','category_title'))
		self.tree.heading('#0',text='№')
		self.tree.column('#0',width=15,anchor='center')
		
		
		self.tree.column('summ', width=60, anchor='center')
		self.tree.column('comment', anchor='center')
		self.tree.column('date', width=60, anchor='center')
		self.tree.column('mul', width=7, anchor='center')
		self.tree.column('category_title',  anchor='center')
		
		self.tree.heading('summ', text='Сумма')
		self.tree.heading('comment', text='Комметарий')
		self.tree.heading('date', text='Дата')
		self.tree.heading('mul', text='Количество')
		self.tree.heading('category_title', text='Категория')
		
		i=1
		summary = 0.0
		for row in payments.paymetsList:
			self.tree.insert('', i,str(i), text=str(i))
			self.tree.set(str(i),'summ',row['summ'])
			self.tree.set(str(i),'comment',row['comment'])
			self.tree.set(str(i),'date',row['date'])
			self.tree.set(str(i),'mul',row['mul'])
			self.tree.set(str(i),'category_title',row['category_title'])
			i+=1
			summary+=row['summ']*row['mul']
		
		self.summarylbl.config(text=str(summary))
		self.tree.pack(side=TOP, fill=BOTH, expand=YES)
		
		s = Scrollbar(self.tree, orient=VERTICAL, command=self.tree.yview)
		self.tree.configure(yscrollcommand=s.set)
		s.pack(side=RIGHT,fill=Y)