class ComboBox(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() self.speed = 1.0 def initUI(self): self.parent.title("Combobox") self.pack(fill = BOTH, expand=True) frame = Frame(self) frame.pack(fill=X) field = Label(frame, text = "Typing Speed:", width = 15) field.pack(side = LEFT, padx = 5, pady = 5) self.box_value = StringVar() self.box = Combobox(frame, textvariable=self.box_value, width = 5) self.box['values'] = ('1x', '2x', '5x', '10x' ) self.box.current(0) self.box.pack(fill = X, padx =5, expand = True) self.box.bind("<<ComboboxSelected>>", self.value) def value(self,event): self.speed = float(self.box.get()[:-1])
class SnapFrame(Frame): def __init__(self, parent, cb=dummy): Frame.__init__(self, parent) self.parent = parent self.cb = cb self._init_ui() def _cb(self, *args): self.cb(SNAP_DICT[self._var.get()]) def _init_ui(self): self._var = StringVar() self.snap_combobox = Combobox( self, values=SNAP_DICT.keys(), width=5, textvariable=self._var, state='readonly') self.snap_combobox.set(SNAP_DICT.keys()[0]) self._var.trace('w', self._cb) self.snap_label = Label(self, text='Snap') self.snap_label.pack(side=LEFT) self.snap_combobox.pack(side=LEFT)
class ComboBox(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() self.speed = 1.0 def initUI(self): self.parent.title("Combobox") self.pack(fill=BOTH, expand=True) frame = Frame(self) frame.pack(fill=X) field = Label(frame, text="Typing Speed:", width=15) field.pack(side=LEFT, padx=5, pady=5) self.box_value = StringVar() self.box = Combobox(frame, textvariable=self.box_value, width=5) self.box['values'] = ('1x', '2x', '5x', '10x') self.box.current(0) self.box.pack(fill=X, padx=5, expand=True) self.box.bind("<<ComboboxSelected>>", self.value) def value(self, event): self.speed = float(self.box.get()[:-1])
class JournalEntry(LabelFrame): def __init__(self, parent, question, i, defaultanswer, *options): LabelFrame.__init__(self, parent, text=question, padx=5, pady=5) self.var = StringVar(parent) try: if defaultanswer in options: options = tuple(x for x in options if x != defaultanswer) options = (defaultanswer,) + options self.var.set(options[0]) except IndexError: self.var.set("") self.om = Combobox(self, textvariable=self.var) self.om['values'] = options self.om.pack(padx=5,pady=5, side="left") self.grid(row=i,column=0,columnspan=3, sticky=W, pady=10)
class PreferencesDialog(Dialog): def __init__(self, parent, title, font, size): self._master = parent self.result = False self.font = font self.size = size Dialog.__init__(self, parent, title) def body(self, master): self._npFrame = LabelFrame(master, text='Annotation window text') self._npFrame.pack(fill=X) self._fontFrame = Frame(self._npFrame, borderwidth=0) self._fontLabel = Label(self._fontFrame, text='Font:', width=5) self._fontLabel.pack(side=LEFT, padx=3) self._fontCombo = Combobox(self._fontFrame, values=sorted(families()), state='readonly') self._fontCombo.pack(side=RIGHT, fill=X) self._sizeFrame = Frame(self._npFrame, borderwidth=0) self._sizeLabel = Label(self._sizeFrame, text='Size:', width=5) self._sizeLabel.pack(side=LEFT, padx=3) self._sizeCombo = Combobox(self._sizeFrame, values=range(8, 15), state='readonly') self._sizeCombo.pack(side=RIGHT, fill=X) self._fontFrame.pack() self._sizeFrame.pack() self._npFrame.pack(fill=X) self._fontCombo.set(self.font) self._sizeCombo.set(self.size) def apply(self): self.font = self._fontCombo.get() self.size = self._sizeCombo.get() self.result = True def cancel(self, event=None): if self.parent is not None: self.parent.focus_set() self.destroy()
class ComboBox(Frame): def __init__(self, root, *args, **kwargs): label_kwargs = dict(text=kwargs.pop('label', '')) combobox_kwargs = dict() combobox_kwargs['state'] = kwargs.pop('state', 'normal') combobox_kwargs['textvariable'] = kwargs.pop('textvariable', None) Frame.__init__(self, root, *args, **kwargs) self.label = Label(self, **label_kwargs) self.combobox = Combobox(self, **combobox_kwargs) self.values = list() self.label.pack(side=LEFT) self.combobox.pack(side=RIGHT) def insert(self, position, value): if position.lower() == 'end': self.values.append(value) else: self.values.insert(int(position), value) self.combobox['values'] = self.values
class PreferencesDialog(Dialog): def __init__(self, parent, title, font, size): self._master = parent self.result = False self.font = font self.size = size Dialog.__init__(self, parent, title) def body(self, master): self._npFrame = LabelFrame(master, text='Annotation window text') self._npFrame.pack(fill=X) self._fontFrame = Frame(self._npFrame, borderwidth=0) self._fontLabel = Label(self._fontFrame, text='Font:', width=5) self._fontLabel.pack(side=LEFT, padx=3) self._fontCombo = Combobox(self._fontFrame, values=sorted(families()), state='readonly') self._fontCombo.pack(side=RIGHT, fill=X) self._sizeFrame = Frame(self._npFrame, borderwidth=0) self._sizeLabel = Label(self._sizeFrame, text='Size:', width=5) self._sizeLabel.pack(side=LEFT, padx=3) self._sizeCombo = Combobox(self._sizeFrame, values=range(8,15), state='readonly') self._sizeCombo.pack(side=RIGHT, fill=X) self._fontFrame.pack() self._sizeFrame.pack() self._npFrame.pack(fill=X) self._fontCombo.set(self.font) self._sizeCombo.set(self.size) def apply(self): self.font = self._fontCombo.get() self.size = self._sizeCombo.get() self.result = True def cancel(self, event=None): if self.parent is not None: self.parent.focus_set() self.destroy()
class MyEntry: #Класс для уменьшений объёма кода однотипных элементов для ввода параметров. def __init__(self, place_class, string_class, DefaultValue, choise_class = False, button_add = False): #При создании принимается место прикрепления виджета и строковое значение для надписи. # A string value to add a combobox or a button could be also inputed. def button_finfo(): messagebox.showinfo(locale(u"ui_iftxt", Settingz["str_langu"]), button_add) # Here it is a function to show information window. self.frame_class = Frame(place_class) self.frame_class.pack(side = TOP, fill = BOTH) #Внутри – рамка для виджетов, растягивается по ширине окна. self.label_class = Label(self.frame_class, text = string_class) self.label_class.pack(side = LEFT) #В ней – надписи для описания вводимых значений выровнены по левому краю. self.entry_class = Entry(self.frame_class, width = 15) self.entry_class.pack(side = RIGHT) self.entry_class.insert(0, DefaultValue) #И элементы для ввода значений шириной в 15 знаков выровнены по правому краю. if choise_class: self.box_class = Combobox(self.frame_class, values = choise_class, width = 2) self.box_class.set(choise_class[0]) self.box_class.pack(side = RIGHT) elif button_add: self.button_class = Button(self.frame_class, text = u"?", command = button_finfo, width = -1) self.button_class.pack(side = RIGHT) # The combobox widget or the button will be created if it is set. def get(self): return(self.entry_class.get()) #Метод .get() передаётся от элемента для ввода объекту описываемого класса. def getbox(self): if self.box_class.get() in ["+", "~"]: return(True) else: return(False)
class PanelPerfilGui: def __init__(self, master, name): self.frameMenu = Frame(master, background="#B4CDCD", pady=5) self.frameMenu.pack(side=TOP, fill=X) self.setPerfil(name) def setPerfil(self, name): global img img_ = Image.open("Images/profile.png") img_.thumbnail((80, 80), Image.ANTIALIAS) img = ImageTk.PhotoImage(img_) Label(self.frameMenu, foreground="#66CD00", background="#B4CDCD", font=("Arial", 12, "bold"), image=img, compound=LEFT).pack(side=LEFT) self.cb = Combobox(self.frameMenu, width=18) self.cb.pack(side=LEFT, fill=X) values = ("Israel Gomes", "Andreza Dantas", "Sandra Noronha") self.cb.config(value=values) self.cb.config(state="readonly", style="C.TCombobox") self.cb.set(values[0])
class PCombobox(Frame, PConfig): def __init__(self, master=None, combobox_callback=None): Frame.__init__(self, master=master) self.__cb_stringvar = StringVar() self.__combobox = Combobox( master=self, textvariable=self.__cb_stringvar) if combobox_callback and callable(combobox_callback): self.__cb_stringvar.trace('w', self.__combobox_chang) self.__user_call_back = combobox_callback self.__combobox.pack() def set_choices(self, choices=[]): if isinstance(choices, list): self.__combobox['values'] = choices else: self.__combobox['values'] = [] def set_text_aliagen(self, aliagn='left'): if isinstance(aliagn, str) and aliagn in ['left', 'center', 'right']: self.__combobox['justify'] = aliagn else: raise IllegalArugments, aliagn def get_select_string(self): return self.__cb_stringvar.get() def set_select_string(self, msg): if msg and (isinstance(msg, str) or isinstance(msg, unicode)): self.__cb_stringvar.set(msg) else: raise IllegalArugments, msg def __combobox_chang(self, *args): if self.__user_call_back: self.__user_call_back(self.get_select_string(), *args)
class MainFrame(Frame): def __init__(self, parent, stdoutq): Frame.__init__(self, parent) self.parent = parent self.width = 750 self.height = 450 self.title = ximaexport.__version__ self.stdoutq = stdoutq self.initUI() self.hasdb = False self.hasout = False self.exit = False self.path_frame = self.addPathFrame() self.action_frame = self.addActionFrame() self.message_frame = self.addMessageFrame() self.printStr() self.stateq = Queue.Queue() def centerWindow(self): sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() x = (sw - self.width) / 2 y = (sh - self.height) / 2 self.parent.geometry('%dx%d+%d+%d' \ %(self.width,self.height,x,y)) def initUI(self): self.parent.title(self.title) self.style = Style() #Choose from default, clam, alt, classic self.style.theme_use('alt') self.pack(fill=tk.BOTH, expand=True) self.centerWindow() def printStr(self): while self.stdoutq.qsize() and self.exit == False: try: msg = self.stdoutq.get() self.text.update() self.text.insert(tk.END, msg) self.text.see(tk.END) except Queue.Empty: pass self.after(100, self.printStr) def checkReady(self): if self.hasdb and self.hasout: self.start_button.configure(state=tk.NORMAL) #print('XimaExport Ready.') printch('XimaExport 就绪.') else: self.start_button.configure(state=tk.DISABLED) def addPathFrame(self): frame = Frame(self) frame.pack(fill=tk.X, expand=0, side=tk.TOP, padx=8, pady=5) frame.columnconfigure(1, weight=1) #------------------Database file------------------ label=tk.Label(frame,text=dgbk('ting.sqlite文件:'),\ bg='#bbb') label.grid(row=0,column=0,\ sticky=tk.W,padx=8) self.db_entry = tk.Entry(frame) self.db_entry.grid(row=0, column=1, sticky=tk.W + tk.E, padx=8) self.db_button = tk.Button(frame, text=dgbk('打开'), command=self.openFile) self.db_button.grid(row=0, column=2, padx=8, sticky=tk.E) #--------------------Output dir-------------------- label2=tk.Label(frame,text=dgbk('导出到文件夹:'),\ bg='#bbb') label2.grid(row=2,column=0,\ sticky=tk.W,padx=8) self.out_entry = tk.Entry(frame) self.out_entry.grid(row=2, column=1, sticky=tk.W + tk.E, padx=8) self.out_button = tk.Button(frame, text=dgbk('选择'), command=self.openDir) self.out_button.grid(row=2, column=2, padx=8, sticky=tk.E) def openDir(self): self.out_entry.delete(0, tk.END) dirname = askdirectory() self.out_entry.insert(tk.END, dirname) if len(dirname) > 0: #print('Output folder: %s' %dirname) printch('输出到文件夹:') print(' ' + dirname) self.hasout = True self.checkReady() def openFile(self): self.db_entry.delete(0, tk.END) ftypes = [('sqlite files', '*.sqlite'), ('ALL files', '*')] filename = askopenfilename(filetypes=ftypes) self.db_entry.insert(tk.END, filename) if len(filename) > 0: #print('Database file: %s' %filename) printch('数据文件:') print(' ' + filename) self.probeAlbums() def probeAlbums(self): dbfile = self.db_entry.get() try: db = sqlite3.connect(dbfile) df = ximaexport.getData(db) self.albumlist = ximaexport.getAlbumList(df, None) #(id, name) self.albumnames = ['All'] + [ii[1] for ii in self.albumlist ] #names to display self.albummenu['values'] = tuple(self.albumnames) self.albummenu.current(0) db.close() self.hasdb = True self.checkReady() except Exception as e: #print('Failed to recoganize the given database file.') printch('无法识别sqlite数据文件.') print(e) def addActionFrame(self): frame = Frame(self, relief=tk.RAISED, borderwidth=1) frame.pack(fill=tk.X,side=tk.TOP,\ expand=0,padx=8,pady=5) #label=tk.Label(frame,text='Actions:',bg='#bbb') #label.grid(row=0,column=0,sticky=tk.W,padx=8) #---------------Action checkbuttons--------------- frame.columnconfigure(0, weight=1) #---------------------2nd row--------------------- subframe = Frame(frame) subframe.grid(row=1,column=0,columnspan=6,sticky=tk.W+tk.E,\ pady=5) #-------------------Album options------------------- albumlabel=tk.Label(subframe,text=dgbk('专辑:'),\ bg='#bbb') albumlabel.pack(side=tk.LEFT, padx=8) self.album = tk.StringVar() self.albumnames = [ 'All', ] self.albummenu=Combobox(subframe,textvariable=\ self.album,values=self.albumnames,state='readonly') self.albummenu.current(0) self.albummenu.bind('<<ComboboxSelected>>', self.setAlbum) self.albummenu.pack(side=tk.LEFT, padx=8) #-------------------Quit button------------------- quit_button=tk.Button(subframe,text=dgbk('退出'),\ command=self.quit) quit_button.pack(side=tk.RIGHT, padx=8) #-------------------Stop button------------------- ''' self.stop_button=tk.Button(subframe,text='Stop',\ command=self.stop) self.stop_button.pack(side=tk.RIGHT,padx=8) ''' #-------------------Start button------------------- self.start_button=tk.Button(subframe,text=dgbk('开始'),\ command=self.start,state=tk.DISABLED) self.start_button.pack(side=tk.RIGHT, pady=8) #-------------------Help button------------------- self.help_button=tk.Button(subframe,text=dgbk('帮助'),\ command=self.showHelp) self.help_button.pack(side=tk.RIGHT, padx=8) def setAlbum(self, x): import json self.albummenu.selection_clear() self.album = self.albummenu.get() self.albummenu.set(self.album) if self.album == 'All': #print('Work on all albums.') printch('导出所有专辑.') else: #print('Select album: '+self.album) printch('导出所选专辑:') print(' ' + self.album) def showHelp(self): helpstr = dgbk('''\n\n 导出喜马拉雅下载音频,并自动按专辑归档、重命名:\n 1. 找到手机/pad中的喜马拉雅数据文件夹:\n (1)苹果用户:链接电脑itunes,在app一栏中找到“喜马拉雅”,单击,右侧会出现“喜马拉雅”的数据文件。选择“iDoc”,并导出到电脑。\n (2)安卓用户:链接电脑后,拷贝出ting文件夹。\n 2. 运行ximaexport-gui.exe。\n 在 “ting.sqlite文件”一栏,选择步骤1中拷贝出的文件夹里的 ting.sqlite. 文件。\n 在 “导出到文件夹”一栏,选择音频存储位置。\n 在 “专辑”下拉菜单,选择要导出的专辑。若全部导出选择“All”。\n 点击“开始”开始处理。 ''') tkMessageBox.showinfo(title='Help', message=helpstr) #print(self.menfolder.get()) def start(self): dbfile = self.db_entry.get() outdir = self.out_entry.get() self.album = self.albummenu.get() self.out_button.configure(state=tk.DISABLED) self.start_button.configure(state=tk.DISABLED) self.help_button.configure(state=tk.DISABLED) self.albummenu.configure(state=tk.DISABLED) self.messagelabel.configure(text=dgbk('信息 (处理中...)')) album = None if self.album == 'All' else self.album args = [dbfile, outdir, album, True] self.workthread = WorkThread('work', False, self.stateq) self.workthread.deamon = True self.workthread.args = args self.workthread.start() self.reset() def reset(self): while self.stateq.qsize() and self.exit == False: try: msg = self.stateq.get() if msg == 'done': self.db_button.configure(state=tk.NORMAL) self.out_button.configure(state=tk.NORMAL) self.start_button.configure(state=tk.NORMAL) self.help_button.configure(state=tk.NORMAL) self.albummenu.configure(state='readonly') self.messagelabel.configure(text=dgbk('消息')) return except Queue.Empty: pass self.after(100, self.reset) def stop(self): #self.workthread.stop() pass def addMessageFrame(self): frame = Frame(self) frame.pack(fill=tk.BOTH,side=tk.TOP,\ expand=1,padx=8,pady=5) self.messagelabel = tk.Label(frame, text=dgbk('消息'), bg='#bbb') self.messagelabel.pack(side=tk.TOP, fill=tk.X) self.text = tk.Text(frame) self.text.pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.text.height = 10 scrollbar = tk.Scrollbar(self.text) scrollbar.pack(side=tk.RIGHT, fill=tk.Y) self.text.config(yscrollcommand=scrollbar.set) scrollbar.config(command=self.text.yview)
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)
class MainFrame(Frame): TOP_FRAME_BACKGROUND_COLOR = 'gray75' w_ = 500 h_ = 400 a_ = 5. b_ = 5. pad_l = 10 def __init__(self, parent): Frame.__init__(self, parent, background='white') self.parent_ = parent # this is the main frame we are working on self.img_frame = Frame(self, background='navy') self.entry1 = None self.entry2 = None self.cb = None # self.init_ui() self.centering() # broken TV app)) # while True: self.state = 0 self.init_random_image() # time.sleep(0.05) def centering(self): pos_x = (self.parent_.winfo_screenwidth() - self.w_) / 2 pos_y = (self.parent_.winfo_screenheight() - self.h_) / 2 self.parent_.geometry('{}x{}+{}+{}'.format(self.w_, self.h_, pos_x, pos_y)) def init_ui(self): self.parent_.title('Rough surface generator') self.pack(fill=BOTH, expand=True) # top panel with controls frame_top = Frame(self, background=self.TOP_FRAME_BACKGROUND_COLOR) frame_top.pack(fill=X) self.cb = Combobox(frame_top, values=('Gaussian', 'Laplace')) self.cb.current(0) self.cb.pack(side=LEFT, padx=5, expand=True) l1 = Label(frame_top, text=r'Cx', background=self.TOP_FRAME_BACKGROUND_COLOR, width=4) l1.pack(side=LEFT, padx=5, expand=True) self.entry1 = Entry(frame_top, validate='key', validatecommand=(self.register(self.on_validate), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W'), width=10) self.entry1.pack(side=LEFT, padx=5, expand=True) self.entry1.insert(0, str(self.a_)) l1 = Label(frame_top, text=r'Cy', width=4, background=self.TOP_FRAME_BACKGROUND_COLOR) l1.pack(side=LEFT, padx=5) self.entry2 = Entry(frame_top, validate='key', validatecommand=(self.register(self.on_validate), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W'), width=10) self.entry2.pack(side=LEFT, padx=5, expand=True) self.entry2.insert(0, str(self.b_)) but1 = Button(frame_top, text='RUN', command=self.button_action) but1.pack(side=RIGHT, padx=5, pady=5) # central panel. It will have a label with an image. Image may have a random noise state, or # transformed image state self.img_frame.pack(fill=BOTH, expand=True) img_label = Label(self.img_frame, background=None) img_label.pack(expand=True, fill=BOTH, padx=5, pady=5) def on_validate(self, d, i, P, s, S, v, V, W): """ :param d: type of action: 1 - insert, 0 - delete, -1 - other :param i: index of char string to be inserted/deleted, or -1 :param P: value of the entry if the edit is allowed :param s: value of entry prior to editing :param S: the text string being inserted or deleted, if any :param v: the type of validation that is currently set :param V: the type of validation that triggered the callback (key, focusin, focusout, forced) :param W: the tk name of the widget :return: True/False -> Valid / Invalid Found it here: https://stackoverflow.com/questions/4140437/interactively-validating-entry-widget-content-in-tkinter Very good answer! """ if d == '1': if W == str(self.entry1): try: float(s + S) return True except ValueError: self.entry1.delete(0, 'end') self.entry1.insert(0, s) print("Not a number, entry 1") return False if W == str(self.entry2): try: float(s + S) return True except ValueError: self.entry2.delete(0, 'end') self.entry2.insert(0, s) print("Not a number, entry 2") return False return True def init_random_image(self): """ Create a rough surface image from a random noise """ self.update() # set a colormap c_map = cm.get_cmap('bwr') # width and height of the image w_ = self.img_frame.winfo_width()-self.pad_l h_ = self.img_frame.winfo_height()-self.pad_l # generate random noise random_map = np.random.random((h_, w_)) # generate a meshgrid for the filter xv, yv = np.meshgrid(np.linspace(-int(w_ / 2.), int(w_ / 2.), w_), np.linspace(-int(h_ / 2.), int(h_ / 2.), h_)) # define correlation length and width if len(self.entry1.get()) > 0: clx = float(self.entry1.get()) else: return if len(self.entry2.get()) > 0: cly = float(self.entry2.get()) else: return # if self.cb.get().startswith('G'): # Gaussian filter filter_ = np.exp(-np.power(xv, 2) / clx - np.power(yv, 2) / cly) else: # Laplace filter filter_ = np.exp(-np.abs(xv) / clx - np.abs(yv) / cly) # this is a resulting map random_map = np.fft.ifft2(np.multiply(np.fft.fft2(random_map), np.fft.fft2(filter_))) random_map = np.real(random_map) # normalize to [0, 1] random_map -= np.min(random_map) random_map /= np.max(random_map) # create PhotoImage object to add on the panel img = ImageTk.PhotoImage( Image.fromarray( # image really likes unsigned ints)) np.uint8( # convert to colormap you like c_map( # give a random image to color map with values between 0 and 1 # np.random.random( # (self.img_frame.winfo_height()-self.pad_l, self.img_frame.winfo_width()-self.pad_l) # ) random_map )*255 ) ) ) # Gray colormap # img = ImageTk.PhotoImage( # Image.fromarray(np.random.random_integers(0, 255, # (self.img_frame.winfo_height()-self.pad_l, # self.img_frame.winfo_width()-self.pad_l)).astype(np.int8) # ).convert('L') # ) keys = self.img_frame.children.keys() for key in keys: self.img_frame.children[key].configure(image=img) self.img_frame.children[key].image = img def button_action(self): """ """ self.init_random_image()
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)
def CompareTime(): global InputDate , HeadderRows, DateLoc TestPlanFileLocation = GetWorkSheet() HeadderRows = 4 now = datetime.datetime.now() ## print "Current date and time using str method of datetime object:" ## print str(now) ## print "Current date and time using instance attributes:" years =str(now.year) months = str(now.month) days = str(now.day) print "Current year: %s" % years print "Current month: %s" % months print "Current day: %s" % days print "%s" %Day print Month print Year if (int(Day) < int(days)) or (int(Month) < int(months)): tkMessageBox.showerror("Error", "Wrong input") else: InputDate = "a " + Day + "/" + Month + "/" + Year print InputDate Test_Workbook = xlrd.open_workbook(TestPlanFileLocation) Test_Worksheet = Test_Workbook.sheet_by_name(SheetName) Test_Nrows = Test_Worksheet.nrows print 'Test_Nrows = ',Test_Nrows Test_Ncols = Test_Worksheet.ncols DateCount = 0 DateLoc = [] for i in range(HeadderRows,Test_Nrows): #print "enter1" Date = Test_Worksheet.cell_value(i,5) print "date = ",Date if Date == InputDate: print "match" DateCount += 1 DateLoc.append(i) print "DateLoc = ", DateLoc print "DateCount = ", DateCount for dateCount in range (0,DateCount): FL = str(Test_Worksheet.cell_value(DateLoc[dateCount],19))# to get selected flight PL = str(Test_Worksheet.cell_value(DateLoc[dateCount],10)) # to get selected flight's price DEPL = str(Test_Worksheet.cell_value(DateLoc[dateCount],7)) # to get selected flight's departure time flightColumn = str(DateLoc[dateCount]) # to get corresponding column of the selected flight print "enter" ADDL = flightColumn + " Flight = " + FL + " Price = " + PL + "Rs" + " Dept Time = " + DEPL FlishtsLists.append(ADDL) # print's when available flight's button is pressed print "exit" ## FlishtsListsCol.append() FlishtsLists.append("AnyOne") # adds anyone option too print "FlishtsLists = ",FlishtsLists #============================================================================= """Available flight Label""" Label(f4, text="Available Flights", fg = "red",font=('Lucida Sans Typewriter',(15), "bold")).pack(side = LEFT, padx = 10, pady = 40) ## f4 = Frame(mf) ## f4.pack(fill=X) global v5 v5 = StringVar() # will take selected flights value Values = FlishtsLists w = Combobox(f4,values = Values ,width = 60, height = 5, textvariable= v5) w.bind('<<ComboboxSelected>>',PassFlightCol) w.pack(side = LEFT,padx = 10, pady = 40) Button(f4, text="SUGGEST",fg ="white" ,bg = "blue" ,font=('Lucida Sans Typewriter',(10), 'bold'), command=lambda: Suggest1()).pack(side = LEFT, padx=10,pady=40) return
class ActivityLogger(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.init_ui() # Pop-up interval, in minutes. self.interval = 2 # List of all tasks, sorted alphabetically. self.tasks = [] # Last-reported task. self.last_task = "" # Change flag. self.changed = False return def get_next_time(self): now = time.time() bits = time.localtime(now) m = (bits.tm_hour * 60) + bits.tm_min #used = m % self.interval start = (m / self.interval) * self.interval next_time = start + self.interval t = time.mktime((bits.tm_year, bits.tm_mon, bits.tm_mday, next_time / 60, next_time % 60, 0, 0, 0, 0)) s = t - now print "Time now is %u:%02u:%02u" % (bits.tm_hour, bits.tm_min, bits.tm_sec) print "Interval started at %u:%02u:00" % (start / 60, start % 60) print "Next interval starts at %u:%02u:00" % (next_time / 60, next_time % 60) print "Sleeping for %f seconds" % s return s def init_ui(self): self.parent.title("Activity Logger") self.parent.focusmodel("active") self.style = Style() self.style.theme_use("aqua") self.combo_text = StringVar() cb = self.register(self.combo_complete) self.combo = Combobox(self, textvariable=self.combo_text, validate="all", validatecommand=(cb, '%P')) self.combo['values'] = ["Food", "Email", "Web"] self.combo.pack(side=TOP, padx=5, pady=5, fill=X, expand=0) #self.entry = Text(self, bg="white", height="5") #self.entry.pack(side=TOP, padx=5, pady=5, fill=BOTH, expand=1) self.pack(fill=BOTH, expand=1) self.centre() self.ok = Button(self, text="Ok", command=self.do_ok) self.ok.pack(side=RIGHT, padx=5, pady=5) self.journal = Button(self, text="Journal", command=self.do_journal) self.journal.pack(side=RIGHT, padx=5, pady=5) self.exit = Button(self, text="Exit", command=self.do_exit) self.exit.pack(side=RIGHT, padx=5, pady=5) def combo_complete(self, partial): # Flag field touched. self.changed = True # Do completion on combobox text #print self.combo_text.get() if partial: print partial return True def do_journal(self): print "journal not yet implemented, sorry" return def do_ok(self): # Get entered activity name. activity = self.combo_text.get() # Get current list of known activity names. activities = list(self.combo['values']) # Prepend the latest activity if it wasn't already known. if activity not in activities: activities.insert(0, activity) self.combo['values'] = activities # Save this activity. self.last_task = activity # Hide the window. self.parent.withdraw() # Get remaining time in interval. s = self.get_next_time() # Schedule a reappearance. self.parent.after(int(s * 1000), self.do_show) # Record the activity print "Did:", activity return def do_exit(self): self.quit() return def do_show(self): # Reset change flag. self.changed = False # Restore last activity. self.combo_text.set(self.last_task) # Show window. self.parent.deiconify() self.parent.lift() # Pop-down after a minute if not touched. self.parent.after(1000 * 60, self.do_timeout) return def do_timeout(self): if self.changed: return # Hide the window. self.parent.withdraw() # Get remaining time in interval. s = self.get_next_time() # Schedule a reappearance. self.parent.after(int(s * 1000), self.do_show) # Log. print "Timed out with no data entry. Sleeping for %f seconds." % s return def centre(self): w = 400 h = 75 sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() x = (sw - w) / 2 y = (sh - h) / 2 self.parent.geometry("%ux%u+%u+%u" % (w, h, x, y))
class MainWindow(Tk): def __init__(self): Tk.__init__(self) self.title(mainWindowTitle) self.resizable(width=0, height=0) self.__setStyles() self.__initializeComponents() self.__dataController = DataController(); self.mainloop() def __initializeComponents(self): self.imageCanvas = Canvas(master=self, width=imageCanvasWidth, height=windowElementsHeight, bg="white") self.imageCanvas.pack(side=LEFT, padx=(windowPadding, 0), pady=windowPadding, fill=BOTH) self.buttonsFrame = Frame(master=self, width=buttonsFrameWidth, height=windowElementsHeight) self.buttonsFrame.propagate(0) self.loadFileButton = Button(master=self.buttonsFrame, text=loadFileButtonText, command=self.loadFileButtonClick) self.loadFileButton.pack(fill=X, pady=buttonsPadding); self.colorByLabel = Label(self.buttonsFrame, text=colorByLabelText) self.colorByLabel.pack(fill=X) self.colorByCombobox = Combobox(self.buttonsFrame, state=DISABLED, values=colorByComboboxValues) self.colorByCombobox.set(colorByComboboxValues[0]) self.colorByCombobox.bind("<<ComboboxSelected>>", self.__colorByComboboxChange) self.colorByCombobox.pack(fill=X, pady=buttonsPadding) self.rejectedValuesPercentLabel = Label(self.buttonsFrame, text=rejectedMarginLabelText) self.rejectedValuesPercentLabel.pack(fill=X) self.rejectedValuesPercentEntry = Entry(self.buttonsFrame) self.rejectedValuesPercentEntry.insert(0, defaultRejectedValuesPercent) self.rejectedValuesPercentEntry.config(state=DISABLED) self.rejectedValuesPercentEntry.pack(fill=X, pady=buttonsPadding) self.colorsSettingsPanel = Labelframe(self.buttonsFrame, text=visualisationSettingsPanelText) self.colorsTableLengthLabel = Label(self.colorsSettingsPanel, text=colorsTableLengthLabelText) self.colorsTableLengthLabel.pack(fill=X) self.colorsTableLengthEntry = Entry(self.colorsSettingsPanel) self.colorsTableLengthEntry.insert(0, defaultColorsTableLength) self.colorsTableLengthEntry.config(state=DISABLED) self.colorsTableLengthEntry.pack(fill=X) self.scaleTypeLabel = Label(self.colorsSettingsPanel, text=scaleTypeLabelText) self.scaleTypeLabel.pack(fill=X) self.scaleTypeCombobox = Combobox(self.colorsSettingsPanel, state=DISABLED, values=scaleTypesComboboxValues) self.scaleTypeCombobox.set(scaleTypesComboboxValues[0]) self.scaleTypeCombobox.bind("<<ComboboxSelected>>", self.__scaleTypeComboboxChange) self.scaleTypeCombobox.pack(fill=X) self.colorsTableMinLabel = Label(self.colorsSettingsPanel, text=colorsTableMinLabelText) self.colorsTableMinLabel.pack(fill=X) self.colorsTableMinEntry = Entry(self.colorsSettingsPanel) self.colorsTableMinEntry.insert(0, defaultColorsTableMin) self.colorsTableMinEntry.config(state=DISABLED) self.colorsTableMinEntry.pack(fill=X) self.colorsTableMaxLabel = Label(self.colorsSettingsPanel, text=colorsTableMaxLabelText) self.colorsTableMaxLabel.pack(fill=X) self.colorsTableMaxEntry = Entry(self.colorsSettingsPanel) self.colorsTableMaxEntry.insert(0, defaultColorsTableMax) self.colorsTableMaxEntry.config(state=DISABLED) self.colorsTableMaxEntry.pack(fill=X) self.colorsSettingsPanel.pack(fill=X, pady=buttonsPadding) self.redrawButton = Button(master=self.buttonsFrame, text=redrawButtonText, state=DISABLED, command=self.__redrawButtonClick) self.redrawButton.pack(fill=X, pady=buttonsPadding) self.buttonsFrame.pack(side=RIGHT, padx=windowPadding, pady=windowPadding, fill=BOTH) def __setStyles(self): Style().configure("TButton", padding=buttonsTextPadding, font=buttonsFont) def loadFileButtonClick(self): fileName = tkFileDialog.askopenfilename(filetypes=[('Tablet files', '*.mtb'), ('Tablet files', '*.htd')]) if (fileName): if (not self.__getInputParams()): self.__showInvalidInputMessage() return self.lastFileName = fileName; self.title(mainWindowTitle + " " + fileName) self.__draw(fileName) tkMessageBox.showinfo(measureDialogTitle, measureDialogText + str(self.__dataController.getMeasure(fileName))) self.redrawButton.config(state=NORMAL) self.colorByCombobox.config(state="readonly") self.colorsTableLengthEntry.config(state=NORMAL) self.scaleTypeCombobox.config(state="readonly") def __redrawButtonClick(self): if (not self.__getInputParams()): self.__showInvalidInputMessage() return self.__draw(self.lastFileName) def __scaleTypeComboboxChange(self, event): if (self.scaleTypeCombobox.get() == relativeScaleType): self.colorsTableMinEntry.config(state=DISABLED) self.colorsTableMaxEntry.config(state=DISABLED) else: self.colorsTableMinEntry.config(state=NORMAL) self.colorsTableMaxEntry.config(state=NORMAL) def __colorByComboboxChange(self, event): if (self.colorByCombobox.get() == colorByNoneOption): self.rejectedValuesPercentEntry.config(state=DISABLED) else: self.rejectedValuesPercentEntry.config(state=NORMAL) def __draw(self, fileName): self.imageCanvas.delete(ALL) dataForDrawing = self.__dataController.getDataForDrawing( fileName, self.colorByCombobox.get(), self.colorsTableLength, self.scaleTypeCombobox.get(), self.colorsTableMinValue, self.colorsTableMaxValue, self.rejectedValuesPercent) for package in dataForDrawing: x = package[0]; y = package[1]; color = package[2]; self.imageCanvas.create_line(x, y, x + 1, y + 1, fill=color) def __drawColorBySpeed(self, dataPackages, minX, minY, ratio, hsv): allSpeeds = self.__getAllSpeeds(dataPackages) minSpeed = min(allSpeeds) maxSpeed = max(allSpeeds) if (self.scaleTypeCombobox.get() == relativeScaleType): colorsTableMinValue = minSpeed colorsTableMaxValue = maxSpeed else: colorsTableMinValue = self.colorsTableMinValue colorsTableMaxValue = self.colorsTableMaxValue i = 0 for package in dataPackages: x = (package[dataXNumber] - minX) * ratio y = (package[dataYNumber] - minY) * ratio color = hsv.getColorByValue(colorsTableMinValue, colorsTableMaxValue, allSpeeds[i]) tk_rgb = "#%02x%02x%02x" % color self.imageCanvas.create_line(x, y, x + 1, y + 1, fill=tk_rgb) i += 1 def __showInvalidInputMessage(self): tkMessageBox.showinfo(invalidInputMessageTitle, invalidInputMessageText) def __getInputParams(self): try: self.colorsTableLength = int(self.colorsTableLengthEntry.get()) self.colorsTableMinValue = float(self.colorsTableMinEntry.get()) self.colorsTableMaxValue = float(self.colorsTableMaxEntry.get()) self.rejectedValuesPercent = float(self.rejectedValuesPercentEntry.get()) if (self.colorsTableLength < 1 or self.colorsTableMinValue >= self.colorsTableMaxValue or self.rejectedValuesPercent < 0 or self.rejectedValuesPercent >= 100): raise return True except: return False
class View(Frame): def __init__(self, parent,controller): Frame.__init__(self, parent) self.parent = parent self.parent.title("Autocompleter") self.pack(fill = 'both', expand = 1) self.initializeComponents() CenterWindow(self.parent) self.controller = controller def initializeComponents(self): self.boxValue = StringVar() self.boxValue.trace('w', \ lambda name, index, mode, \ boxValue = self.boxValue : \ self.box_valueEditted(boxValue)) self.box = Combobox(self,\ justify = 'left',\ width = 50, \ textvariable = self.boxValue,\ ) self.box.pack(side = 'left',expand = 1, padx = 5, pady = 5) self.box.bind('<<ComboboxSelected>>',self.box_selected) self.box.bind('<Return>',self.box_returned) self.importButton = Button(self, \ text = "Import", \ command = self.importButton_clicked,\ ) self.importButton.pack(side = 'left',expand = 1) self.cmd_str = StringVar(None,"Prefix Only") self.switchButton = Button(self, \ textvariable = self.cmd_str, \ command = self.switchButton_clicked, \ ) self.switchButton.pack(side = 'right', padx = 5, pady = 5) #******************Callbacks****************** def box_valueEditted(self,sv): ''' Edit text of combo box will trigger autocomplete This implementation is moved to "box_returned" ''' pass def box_selected(self,event): ''' Selecting 1 value of dropdown list finds all strings with this prefix. Testing only. ''' # tag = event.widget.get() # print self.controller.Contains(tag) pass def box_returned(self,event): ''' Press 'return' will show combo box's dropdown list ''' tag = self.boxValue.get() container = self.controller.List(tag) self.box['value'] = [] # clear self.box['value'] = container self.box.event_generate('<Down>') def importButton_clicked(self): ''' Press 'import' button will import test file and initialize Trie ''' self.box['value'] = self.controller.LoadFile() self.controller.Construct() def switchButton_clicked(self): ''' Press will switch between 'Prefix Only' and 'Prefix and Infix' mode ''' self.controller.SwitchCommand() cmd_str = self.cmd_str.get() if cmd_str == 'Prefix Only': self.cmd_str.set('Prefix and Infix') else: self.cmd_str.set('Prefix Only')
class Application(Frame): cols = [1, 2, 3, 4, 5] rows = ["A", "B", "C", "D", "E"] scheduler = sched.scheduler(time.time, time.sleep) playStates = {} sensorStates = {} buttons = {} currentPlayMode = GameModes.SINGLE_HIT currentStep = None selectedChannelName = None def load(self): print("loading sounds into PD..") command = "" path = self.setCombo.get() soundSet = self.conf["SoundSets"][path] sensorsPerRow = 5.0 gapsPerRow = sensorsPerRow - 1 balanceSpread = 1.0 / gapsPerRow # 0.25 col = 0.0 row = 0.0 for r in range(len(self.rows)): for c in range(len(self.cols)): channelName = str(self.rows[r]) + " " + str(self.cols[c]) command += channelName + " load " + path + "/" + channelName.replace( " ", "") + ".wav," backFrontMultiplyer = ( gapsPerRow - r ) / gapsPerRow # row0: 1, row1: 0.75, row3: 0.5, row4: 0.25, row5: 0 v1 = (1 - (balanceSpread * c)) * backFrontMultiplyer v2 = (balanceSpread * c) * backFrontMultiplyer v3 = (1 - (balanceSpread * c)) * (1 - backFrontMultiplyer) v4 = (balanceSpread * c) * (1 - backFrontMultiplyer) command += channelName + " panorama " + str(v1) + " " + str( v2) + " " + str(v3) + " " + str(v4) + "," command += channelName + " volume " + str( self.getChannelVolume(channelName, True)) + "," self.playStates[channelName] = False self.enableButton(channelName, False) self.sendToPd(command) def getMasterVolume(self): if (self.currentStep is None): return 1 else: return self.currentStep["masterVolume"] def getChannelVolume(self, channelName, includeMasterVolume): channelConfig = self.currentSet.get(channelName) if (channelConfig): v = channelConfig.get("volume") else: v = 1 if (includeMasterVolume): v = v * self.getMasterVolume() return v def singleHit(self, channelName): self.sendToPd(channelName + " play") def buttonPress(self, channelName): print(self.currentMode.get()) if (self.currentMode.get() == "play"): if (self.currentGameMode == GameModes.SINGLE_HIT): self.singleHit(channelName) else: self.playStates[channelName] = not self.playStates.get( channelName) if (self.playStates.get(channelName)): self.sendChannelVolumeToPd(channelName) else: self.sendToPd(channelName + " volume 0") self.enableButton(channelName, self.playStates.get(channelName)) elif (self.currentMode.get() == "setMac"): lastActiveMac = self.activeMacAddrLabel["text"] self.conf["SensorNames"][lastActiveMac] = channelName self.currentMode.set("play") elif (self.currentMode.get() == "setVolume"): self.currentChannelVolumeLabel["text"] = str( self.getChannelVolume(channelName, False)) self.selectedChannelName = channelName def sendChannelVolumeToPd(self, channelName): self.sendToPd(channelName + " volume " + str(self.getChannelVolume(channelName, True))) def enableButton(self, channelName, enable): color = 'black' if enable else 'white' self.buttons[channelName].configure(highlightbackground=color) def sendToPd(self, command): print("sending command to PD: " + command) os.system("echo '" + command + "' | " + self.conf["SystemSettings"]["pdSendPath"] + " 3000 localhost udp") def enableChannel(self, channelName): if (self.playStates[channelName]): return self.sendToPd(channelName + " volume " + str(self.getChannelVolume(channelName, True))) self.playStates[channelName] = True def disableChannel(self, channelName): if (not self.playStates.get(channelName)): return self.sendToPd(channelName + " volume 0") self.playStates[channelName] = False def onMessage(self, client, userdata, message): val = str(message.payload.decode("utf-8")) if (message.topic == "control"): if (val == "nextSet"): self.switchNextSet() elif (val == "prevSet"): self.switchPrevSet() elif (val.startswith("pd:")): self.sendToPd(val.split(":")[1]) elif (message.topic == "sensor"): ''' Callback for MQTT messages {"k": "XXX", "v": 100} ''' #print(str(message.payload.decode("utf-8"))) start_new_thread(self.handleSensorData, (message, )) elif (message.topic.startswith("sensorControl")): if (message.topic.find("set/brightness")): self.conf["SystemSettings"]["sensorBrightness"] = int(val) elif (message.topic.find("set/triggerLevel")): self.conf["SystemSettings"]["sensorTriggerLevel"] = int(val) elif (message.topic == "status"): obj = json.loads(val) status = obj.get("status") mac = obj.get('k') print("status: " + mac + " status: " + status) if (status == "connected"): sensorTopic = "sensorControl" + mac self.client.publish( sensorTopic, "{\"command\": \"setTriggerLevel\", \"val\": " + str(self.getSensorTriggerLevel()) + "}", 1) self.client.publish( sensorTopic, "{\"command\": \"setBrightness\", \"val\": " + str(self.getSensorBrightness()) + "}", 1) def getSensorBrightness( self): # the brightness of the lights in the sensor if (self.currentStep and self.currentStep.get("sensorBrightness")): return self.currentStep.get("sensorBrightness") return self.conf["SystemSettings"]["sensorBrightness"] def getSensorTriggerLevel( self ): # the sensor value threshold which makes the sensors send an ON and OFF signal return self.conf["SystemSettings"]["sensorTriggerLevel"] def handleSensorData(self, message): val = json.loads(str(message.payload.decode("utf-8"))) v = 0.0 s = 0 channelName = "" try: sensorId = val['k'] v = int(val['v']) s = int(val.get('s')) except: print('Could not digest ' + str(message.payload.decode("utf-8"))) return channelName = self.conf["SensorNames"].get(sensorId) if (not channelName): print("channel for sensorId " + sensorId + " not found") return prevVal = self.sensorStates.get(sensorId) self.sensorStates[sensorId] = v print("sensorId: " + sensorId + ", channel: " + channelName + ", v: " + str(v) + " s:" + str(s)) if (self.currentGameMode == GameModes.SINGLE_HIT): if (s == 1): self.singleHit(channelName) self.buttons[channelName].configure(highlightbackground='red') else: self.buttons[channelName].configure( highlightbackground='white') else: if (s == 1): self.enableChannel(channelName) self.buttons[channelName].configure( highlightbackground='black') else: self.disableChannel(channelName) self.buttons[channelName].configure( highlightbackground='white') if (s == 1): self.activeMacAddrLabel["text"] = sensorId def checkTime(self): lastStep = None for step in self.conf["Scheduler"]['steps'].keys(): startHour = int(step.split(":")[0]) startMinute = int(step.split(":")[1]) startSecond = int(step.split(":")[2]) startDate = datetime.datetime.now().replace(hour=startHour, minute=startMinute, second=startSecond, microsecond=0) #print("now", datetime.datetime.now()) if (startDate < datetime.datetime.now()): lastStep = step if (lastStep is not None and lastStep != self.stepCombo.get()): print("automatic step switch: ", lastStep) self.switchStep(lastStep) info = "currentStep: " + self.stepCombo.get() + "\n" info += "currentGameMode: " + self.currentGameMode + "\n" self.client.publish("info", "info: " + info, 0) def switchStep(self, stepId): self.client.publish("info/step", stepId, 0) self.stepCombo.set(stepId) self.currentStep = self.conf["Scheduler"]["steps"][stepId] print("switch step: ") pprint(self.currentStep) if (self.currentStep.get('pdCommand')): self.sendToPd(self.currentStep.get('pdCommand')) self.switchSet(self.currentStep.get("set")) def switchNextSet(self): currentSet = self.setCombo.get() nextIndex = (self.conf["SoundSets"].keys().index(currentSet) + 1) % len(self.conf["SoundSets"].keys()) nextSetPath = self.conf["SoundSets"].keys()[nextIndex] self.switchSet(nextSetPath) def switchPrevSet(self): currentSet = self.setCombo.get() prevIndex = (self.conf["SoundSets"].keys().index(currentSet) - 1) % len(self.conf["SoundSets"].keys()) prevSetPath = self.conf["SoundSets"].keys()[prevIndex] self.switchSet(prevSetPath) def switchSet(self, path): self.currentSet = self.conf["SoundSets"].get(path) self.setCombo.set(path) self.currentGameMode = GameModes.SINGLE_HIT if self.currentSet[ 'mode'] == 'SINGLE_HIT' else GameModes.LOOP if (self.currentGameMode == GameModes.SINGLE_HIT): self.sendToPd("loop stop, all volume " + str(self.getMasterVolume())) else: duration = self.currentSet['duration'] self.sendToPd("loop start " + duration + ", all volume 0") print("New mode: " + self.currentGameMode) self.infoLabel["text"] = ("Mode: {0}\n" "MasterVolume: {1}\n" "SensorBrightness: {2}").format( self.currentGameMode, self.getMasterVolume(), self.getSensorBrightness()) self.load() self.client.publish("info/set", path, 0) def patchFirmware(self): self.client.publish("sensorControl/patch", self.conf["SystemSettings"]["otaUpdateUrl"], 1) def copyMacToClipBoard(self): root.clipboard_clear() root.clipboard_append(self.activeMacAddrLabel['text']) root.update() def onStepComboChanged(self, event): print(self.stepCombo.get()) self.switchStep(self.stepCombo.get()) def onSetComboChanged(self, event): pprint(self.setCombo.get()) self.switchSet(self.setCombo.get()) def increaseChannelVolume(self): self.setCurrentChannelVolume( self.getChannelVolume(self.selectedChannelName, False) + 0.1) def decreaseChannelVolume(self): self.setCurrentChannelVolume( self.getChannelVolume(self.selectedChannelName, False) - 0.1) def setCurrentChannelVolume(self, v): self.currentChannelVolumeLabel["text"] = str(v) self.currentSet[self.selectedChannelName] = {} self.currentSet[self.selectedChannelName]["volume"] = v self.sendChannelVolumeToPd(self.selectedChannelName) self.singleHit(self.selectedChannelName) def saveConfig(self): with open("conf1.json", "w") as confFile: json.dump(self.conf, confFile, indent=4, sort_keys=False) print("config saved: ") pprint(self.conf) def createWidgets(self): topFrame = Frame(self) topFrame.pack(side=TOP) stepKeys = self.conf["Scheduler"]["steps"].keys() stepKeys.sort() self.stepCombo = Combobox(topFrame, values=stepKeys, state="readonly") self.stepCombo.pack(side=LEFT) self.stepCombo.bind("<<ComboboxSelected>>", self.onStepComboChanged) self.setCombo = Combobox(topFrame, values=self.conf["SoundSets"].keys(), state="readonly") self.setCombo.pack(side=LEFT) self.setCombo.bind("<<ComboboxSelected>>", self.onSetComboChanged) contentFrame = Frame(self) contentFrame.pack(side=LEFT) contentLeft = Frame(contentFrame) contentLeft.pack(side=LEFT) contentMiddle = Frame(contentFrame) contentMiddle.pack(side=LEFT) contentRight = Frame(contentFrame) contentRight.pack(side=LEFT) footerFrame = Frame(self) footerFrame.pack(side=BOTTOM) self.infoLabel = Label(contentRight, text="info", anchor='w') self.infoLabel.pack(fill='both') self.currentMode = StringVar() Radiobutton(contentMiddle, text="Play", variable=self.currentMode, value="play").grid(row=0, column=0) Radiobutton(contentMiddle, text="Write Mac to config", variable=self.currentMode, value="setMac").grid(row=1, column=0) Radiobutton(contentMiddle, text="Set volume", variable=self.currentMode, value="setVolume").grid(row=2, column=0) Button(contentMiddle, text="-", command=self.decreaseChannelVolume).grid(row=2, column=1) self.currentChannelVolumeLabel = Label(contentMiddle, text="vol") self.currentChannelVolumeLabel.grid(row=2, column=2) Button(contentMiddle, text="+", command=self.increaseChannelVolume).grid(row=2, column=3) self.currentMode.set("play") self.activeMacAddrLabel = Button(contentMiddle, text='Last active mac', command=self.copyMacToClipBoard) self.activeMacAddrLabel.grid(row=3, column=0) self.patchFirmwareButton = Button(contentMiddle, text='Patch Firmware', command=self.patchFirmware) self.patchFirmwareButton.grid(row=4, column=0) self.saveButton = Button(contentMiddle, text='Save Configuration', command=self.saveConfig) self.saveButton.grid(row=5, column=0) #self.activeMacAddressLabel = Label(contentFrame) #self.activeMacAddressLabel.pack( side = LEFT) for c in range(len(self.cols)): for r in range(len(self.rows)): channelName = str(self.rows[r]) + " " + str(self.cols[c]) button = Button( contentLeft, text=channelName, command=lambda sn=channelName: self.buttonPress(sn)) button.grid(row=r, column=c) self.buttons[channelName] = button def __init__(self, master=None): Frame.__init__(self, master) with open('conf.json') as f: self.conf = json.load(f) self.pack() self.createWidgets() print("Connecting to broker...") self.client = mqtt.Client(self.conf["brokerSettings"]['client']) self.client.connect(self.conf["brokerSettings"]['address'], self.conf["brokerSettings"]['port']) print("connected!") # wait for MQTT connection # TODO: implement proper callback https://www.eclipse.org/paho/clients/python/docs/ # with error handling on failed connection time.sleep(0.5) # sensor: updates from the sensors; control: topic for controlling this program; status: topic where status updates are posted (mostly sensors when the join the network); sensorControl: listening to the control messages of the sensors self.client.subscribe([("sensor", 0), ("control", 0), ("status", 0), ("sensorControl/#", 0)]) # setup callback self.client.on_message = self.onMessage self.client.loop_start() #self.switchSetIndex(0) self.switchSet(self.conf["SoundSets"].keys()[0]) # self.checkTime() #self.checkTime() self.scheduler = timer.Scheduler(30, self.checkTime) self.scheduler.start() def quit(self): print("Terminating...") self.scheduler.stop() root.destroy()
class BoardConfigAdvance(Frame): def __init__(self, master=None, main=None): Frame.__init__(self, master) self.parent = master self.main = main self.parent.geometry("280x174") self.parent.title(os.getenv("NAME") + " - Advance Board Config") self.master.configure(padx=10, pady=10) self.HEAPSIZE = {"512 byte": 512, "1024 byte": 1024,} self.OPTIMIZATION = "-O2 -O3 -Os".split() self.mips16_var = IntVar() self.checkBox_mips16 = Checkbutton(self.parent, text="Mips16", anchor="w", variable=self.mips16_var) self.checkBox_mips16.pack(expand=True, fill=BOTH, side=TOP) frame_heap = Frame(self.parent) Label(frame_heap, text="Heap size:", anchor="w", width=12).pack(side=LEFT, fill=X, expand=True) self.comboBox_heapsize = Combobox(frame_heap, values=self.HEAPSIZE.keys()) self.comboBox_heapsize.pack(fill=X, expand=True, side=RIGHT) frame_heap.pack(fill=X, expand=True, side=TOP) frame_opt = Frame(self.parent) Label(frame_opt, text="Optimization:", anchor="w", width=12).pack(side=LEFT, fill=X, expand=True) self.comboBox_optimization = Combobox(frame_opt, values=self.OPTIMIZATION) self.comboBox_optimization.pack(fill=X, expand=True, side=RIGHT) frame_opt.pack(fill=X, expand=True, side=TOP) frame_buttons = Frame(self.parent) Button(frame_buttons, text="Accept", command=self.accept_config).pack(fill=X, expand=True, side=LEFT) Button(frame_buttons, text="Restore Default", command=self.restore_default).pack(fill=X, expand=True, side=RIGHT) frame_buttons.pack(fill=X, expand=True, side=BOTTOM) self.load_config() #---------------------------------------------------------------------- def quit(self): self.master.destroy() #---------------------------------------------------------------------- def load_config(self): #Called in the parent frame #self.main.configIDE.load_config() if self.main.configIDE.config("Board", "mips16", True): self.checkBox_mips16.select() else: self.checkBox_mips16.deselect() heapsize = self.main.configIDE.config("Board", "heapsize", 512) for key in self.HEAPSIZE.keys(): if self.HEAPSIZE[key] == heapsize: self.comboBox_heapsize.set(key) break optimization = self.main.configIDE.config("Board", "optimization", "-O3") self.comboBox_optimization.set(optimization) #---------------------------------------------------------------------- def restore_default(self): self.checkBox_mips16.select() self.comboBox_heapsize.set(self.HEAPSIZE.keys()[1]) self.comboBox_optimization.set(self.OPTIMIZATION[1]) #---------------------------------------------------------------------- def accept_config(self): self.save_config() self.main.configIDE.save_config() self.quit() #---------------------------------------------------------------------- def save_config(self): self.main.configIDE.set("Board", "mips16", self.mips16_var.get()==1) heapsize = self.HEAPSIZE[self.comboBox_heapsize.get()] self.main.configIDE.set("Board", "heapsize", heapsize) self.main.configIDE.set("Board", "optimization", self.comboBox_optimization.get())
class CoreGUI(object): def __init__(self): self.mw = Tk() self.style = MainWindowStyles() self.quality = IntVar() self.setup(self.mw) def setup(self, parent): parent.title("Z5212 Debug Client by 2017 ZEBEX, Inc. Version 1.3") resize_and_center(parent, 900, 480) self.conn_status = StringVar() self.conn_status.set('...') # Top Frame (name entry box, buttons, conn status) self.conn_frame = Frame(parent, **self.style.Frame) self.conn_frame.pack(side="top", fill="x") self.lower_frame = Frame(parent, **self.style.Frame) self.lower_frame.pack(side="top", fill="both", expand=1) # The message entry self.display_frame = Frame(self.lower_frame, **self.style.Frame) self.display_frame.pack(side="top", fill="both", expand=1, padx=5, pady=5) self.right_frame = Frame(self.lower_frame, **self.style.Frame) self.right_frame.pack(side="right", fill="y") ### # Top Frame Widgets ### self.name_label = Label(self.conn_frame, textvariable=self.conn_status, **self.style.Label).pack(side="left", padx=5, pady=5) Button(self.conn_frame, text='連線', command=self.conn, **self.style.SettingButton)\ .pack(side="left", padx=5, pady=5) Button(self.conn_frame, text="重新開始", command=self.reopen, **self.style.SettingButton)\ .pack(side="left", padx=5, pady=5) self.ports_Combobox = Combobox(self.conn_frame, values=c.port, width=8) # assign function to combobox self.ports_Combobox.bind('<<ComboboxSelected>>', self.port_on_select) self.ports_Combobox.current(portindex) self.baud_rate_Combo = Combobox(self.conn_frame, values=c.baud, width=8) self.baud_rate_Combo.bind('<<ComboboxSelected>>', self.baud_rate_on_select) self.baud_rate_Combo.current(baudindex) self.enter_exit_button = Button(self.conn_frame, text="回復預設值", command=self.quit, **self.style.Button) self.ports_Combobox.pack(side="left", padx=5, pady=5) self.baud_rate_Combo.pack(side="left", padx=5, pady=5) self.enter_exit_button.pack(side="left", padx=5, pady=5) ### # Image Frame Widgets get image, set quality ### self.img_frame = Frame(self.conn_frame, **self.style.Frame) image_q_label = Label(self.img_frame, text='Quality', anchor="w", **self.style.Label) image_q_label.pack(side=LEFT, fill="x") self.quality.set(85) Radiobutton(self.img_frame, text='L', variable=self.quality, value=35, command=self.selected_quality).pack(side=RIGHT, anchor="w") Radiobutton(self.img_frame, text='M', variable=self.quality, value=85, command=self.selected_quality).pack(side=RIGHT, anchor="w") Radiobutton(self.img_frame, text='H', variable=self.quality, value=93, command=self.selected_quality).pack(side=RIGHT, anchor="w") self.img_frame.pack(side="left", padx=5, pady=5) Button(self.conn_frame, text='拍照', command=self.getimg, **self.style.SettingButton).pack(side="left", padx=5, pady=5) ### # Display Frame Widgets ### self.display_frame.configure(background='#666666') # Create a canvas self.canvas = Canvas(self.display_frame, width=640, height=360, bg="#666666") self.loadImage('Capture.jpg') def conn(self): self.conn_status.set("...") c = Config('') c.baud = self.baud_rate_Combo.get() c.port = self.ports_Combobox.get() c.isRs232 = int(c.baud) - 115200 <= 0 c.dump() self.serConnector = connect(c) serConnector = self.serConnector Has_response = handshake(self.serConnector) if Has_response: setDefault(c, self.serConnector) self.conn_status.set('已連線') commGUI(self.right_frame, c.Gain, self.serConnector, "Gain") commGUI(self.right_frame, c.Shutter, self.serConnector, "Shutter") commGUI(self.right_frame, c.light, self.serConnector, "light") def baud_rate_on_select(self, event=None): print("event.widget:", event.widget.get()) def port_on_select(self, event=None): print("event.widget:", event.widget.get()) def quit(self): self.serConnector.write("quit".encode('ascii') + '\r\n') def reopen(self): portindex = self.ports_Combobox.getint baudindex = self.baud_rate_Combo.getint try: self.serConnector.close() except AttributeError: pass self.mw.destroy() app = CoreGUI() def getimg(self): self.canvas.delete("all") getImage("image" + str(self.quality.get()), self.serConnector, c.isRs232) self.loadImage('Capture.jpg') def loadImage(self, filename): # Load the image file try: im = Image.open(filename) except IOError: print 'IOError' return # Put the image into a canvas compatible class, and stick in an # arbitrary variable to the garbage collector doesn't destroy it self.canvas.image = ImageTk.PhotoImage(im) # Add the image to the canvas, and set the anchor to the top left / north west corner self.canvas.create_image(0, 0, image=self.canvas.image, anchor='nw') self.canvas.pack() def start(self): self.mw.mainloop() def selected_quality(self): pass
def makeCombobox(root, keyStr, valueStr): Label(root, width=15, text=keyStr).pack(side=LEFT) chose = Combobox(root) chose["values"] = valueStr chose.pack(side=LEFT) return chose
class App: """Main class for the gui layer.""" def __init__(self, master): self.master = master self.master.title("Gaussian Elimination / Jacobi Method") self.create_widgets(master) # options for opening or saving a file self.file_opt = options = {} options['filetypes'] = [('all files', '*'), ('text files', '.txt'), ('csv files', '.csv')] def create_widgets(self, master): """Populate the main window with gui components.""" # buttons, slider, combobox etc. frame0 = Frame(master) frame0.grid(row=1, column=0, sticky=N) self.scale = Scale(frame0, from_=2, to=2000, orient=HORIZONTAL, label='Matrix / vector size (n):') self.scale.pack(fill="x") btn_gen_mtx = Button(frame0, text="Generate matrix A (n x n)", command=self.gen_mtx) btn_gen_mtx.pack(fill="x") btn_gen_vec = Button(frame0, text="Generate vector B (n)", command=self.gen_vec) btn_gen_vec.pack(fill="x") btn_load_mtx = Button(frame0, text="Load matrix A", command=self.load_mtx) btn_load_mtx.pack(fill="x") btn_load_vec = Button(frame0, text="Load vector B", command=self.load_vec) btn_load_vec.pack(fill="x") btn_solve = Button(frame0, text="SOLVE", command=self.solve) btn_solve.pack(fill="x") self.combobox = Combobox(frame0, state="readonly", values=("Gauss Method", "Jacobi Method", "numpy.linalg.solve()")) self.combobox.pack(fill="x") self.combobox.set("Gauss Method") # default choice btn_quit = Button(frame0, text="Quit", command=self.quit) btn_quit.pack(fill='x', pady=28) # scrollbar text widget (matrix a) self.frame1 = Frame(master) xscrollbar1 = Scrollbar(self.frame1, orient=HORIZONTAL) xscrollbar1.grid(row=1, column=0, sticky=E+W) yscrollbar1 = Scrollbar(self.frame1) yscrollbar1.grid(row=0, column=1, sticky=N+S) self.text1 = Text(self.frame1, wrap=NONE, bd=0, state=DISABLED, xscrollcommand=xscrollbar1.set, yscrollcommand=yscrollbar1.set) self.text1.grid(row=0, column=0, sticky=N+S+W+E) xscrollbar1.config(command=self.text1.xview) yscrollbar1.config(command=self.text1.yview) self.frame1.grid_rowconfigure(0, weight=1) self.frame1.grid_columnconfigure(0, weight=1) self.frame1.grid(row=1, column=1, sticky=N+S+W+E) # scrollbar text widget (vector b) self.frame2 = Frame(master) xscrollbar2 = Scrollbar(self.frame2, orient=HORIZONTAL) xscrollbar2.grid(row=1, column=0, sticky=E+W) yscrollbar2 = Scrollbar(self.frame2) yscrollbar2.grid(row=0, column=1, sticky=N+S) self.text2 = Text(self.frame2, width=30, wrap=NONE, bd=0, state=DISABLED, xscrollcommand=xscrollbar2.set, yscrollcommand=yscrollbar2.set) self.text2.grid(row=0, column=0, sticky=N+S+E+W) xscrollbar2.config(command=self.text2.xview) yscrollbar2.config(command=self.text2.yview) self.frame2.grid_rowconfigure(0, weight=1) self.frame2.grid_columnconfigure(0, weight=1) self.frame2.grid(row=1, column=2, sticky=N+S) # scrollbar text widget (vector x) self.frame3 = Frame(master) xscrollbar3 = Scrollbar(self.frame3, orient=HORIZONTAL) xscrollbar3.grid(row=1, column=0, sticky=E+W) yscrollbar3 = Scrollbar(self.frame3) yscrollbar3.grid(row=0, column=1, sticky=N+S) self.text3 = Text(self.frame3, width=30, wrap=NONE, bd=0, state=DISABLED, xscrollcommand=xscrollbar3.set, yscrollcommand=yscrollbar3.set) self.text3.grid(row=0, column=0, sticky=N+S+E+W) xscrollbar3.config(command=self.text3.xview) yscrollbar3.config(command=self.text3.yview) self.frame3.grid_rowconfigure(0, weight=1) self.frame3.grid_columnconfigure(0, weight=1) self.frame3.grid(row=1, column=3, sticky=N+S) # labels label1 = Label(master, text="Matrix A") label1.grid(row=0, column=1) label2 = Label(master, text="Vector B") label2.grid(row=0, column=2) label3 = Label(master, text="Vector X") label3.grid(row=0, column=3) self.bottom_label = Label(master) self.bottom_label.grid(row=2, column=0, columnspan=4, sticky=W+E) # which row/column should grow/shrink when resizing the main window self.master.grid_rowconfigure(1, weight=1) self.master.grid_columnconfigure(1, weight=1) def quit(self): """A callback method for quitting the app.""" self.master.destroy() def gen_mtx(self): """A callback method for generating matrix A.""" self.bottom_label.config(text='') self.subp_launcher(ngm.posdef_diag_dom, self.scale.get()) self.cw = CancelWindow(self.master, self.subp) def gen_vec(self): """A callback method for generating vector B.""" self.bottom_label.config(text='') self.subp_launcher(ngm.gen_rnd_vec, self.scale.get()) self.cw = CancelWindow(self.master, self.subp) def load_mtx(self): """A callback method for loading matrix A.""" # TODO: add a handler for exceptions raised by nmgj.check_input_data() self.bottom_label.config(text='') filename = tkFileDialog.askopenfilename(**self.file_opt) if filename: self.a = nmgj.load_mtx(filename) self.display_text(self.text1, self.a) def load_vec(self): """A callback method for loading vector B.""" self.bottom_label.config(text='') filename = tkFileDialog.askopenfilename(**self.file_opt) if filename: self.b = nmgj.load_vec(filename) self.display_text(self.text2, self.b) def delete_text(self, text_wgt): """A helper function for text widget refreshing.""" text_wgt.config(state=NORMAL) text_wgt.delete(1.0, END) text_wgt.config(state=DISABLED) def display_text(self, text_wgt, text): """A helper function for text widget refreshing.""" text_wgt.config(state=NORMAL) text_wgt.delete(1.0, END) if text is not None: text_wgt.insert(END, text) text_wgt.config(state=DISABLED) def solve(self): """A callback method for solving a given set of equations.""" self.x = None self.delete_text(self.text3) if (self.a is None or self.b is None) or (len(self.a) != len(self.b)): # TODO: consider different error message for the 'None' case tkMessageBox.showerror("Error", "Dimensions mismatch.") return choice = self.combobox.get() f = { "Gauss Method": nmgj.gauss, "Jacobi Method": nmgj.jacobi, "numpy.linalg.solve()": nmgj.la.solve, }.get(choice) self.subp_launcher(f, self.a, self.b) self.cw = CancelWindow(self.master, self.subp) def calc_residual(self, a, x, b): """Handles calculation of residual & dislpaying the results.""" self.res_min, self.res_avg, self.res_max = nmgj.calc_residual(a, x, b) self.display_text(self.text3, self.x) self.bottom_label.config(text='Residual: min ' + str(self.res_min) + ' avg ' + str(self.res_avg) + ' max ' + str(self.res_max)) def subp_launcher(self, f, *args): """Creates a queue for communication, spawns the subprocess and schedules checking if it's still active. """ # note: there will be no more than one subprocess at any given time self.q = mp.Queue() self.subp = mp.Process(target=self.subp_wrapper, args=(f, args)) self.subp.start() #print "subprocess started - pid:", self.subp.pid # for diagnostics self.check_subp(f) def subp_wrapper(self, f, args): """Wraps the subprocess f, creates the temp file for data passing and puts its name on the queue. """ results = f(*args) # Generally, out-of-band signalling is better than in-band signalling - # hence temporary file for data, and queue for communication *only*. # And also, although you can safely put objects up to 32 MB through # the queue, there's a 'hidden' pipe mechanism involved here (with its # own limits), so the order in which you use join() and get() methods # may be sigificant (see: http://bugs.python.org/issue8426). with NamedTemporaryFile(delete=False) as temp: np.savez(temp, results) temp.flush() self.q.put(temp.name) def check_subp(self, f): """Checks if the subprocess is still alive, otherwise does the cleanup.""" if self.subp.is_alive() is False: if self.subp.exitcode > 0: self.subp.terminate() self.subp.join() #print 'subprocess finished' # for diagnostics self.subp_cleanup(f) return self.master.after(100, self.check_subp, f) # every 100 ms def subp_cleanup(self, f): """Cleans up after the calculations, displays the solution.""" if self.q.empty() is not True: temp = self.q.get() results = np.load(temp).items()[0][1] os.remove(temp) else: results = None if f == ngm.posdef_diag_dom: self.a = results self.display_text(self.text1, self.a) elif f == ngm.gen_rnd_vec: self.b = results self.display_text(self.text2, self.b) elif f in (nmgj.gauss, nmgj.jacobi, nmgj.la.solve): self.x = results self.display_text(self.text3, results) if self.x is not None: self.calc_residual(self.a, self.x, self.b)
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)
def __init__(self, parent, controller): Frame.__init__(self, parent) #VARIABLES GLOBALES global cedula, titulo, residencia, nombres, apellidos, direccion, telefono, envio, correo, celular, dia, mes, profesion, empresa, oficina, tel, telfax, banco, tcuenta, numcuenta, tipopersona, retefuente, reteiva, gcontribuyente, gfactura, gcheque, notas, co1cc, co1nombres, co1dir, co1tel1, co1cargo, co1empresa, co1oficina, co1tel2, co2cc, co2nombres, co2dir, co2tel1, co2cargo, co2empresa, co2oficina, co2tel2, co3cc, co3nombres, co3dir, co3tel1, co3cargo, co3empresa, co3oficina, co3tel2, lb, note, busqueda, dato, E #INSTANCIEAS DE LOS WIDGETS global codeE, refE, cityE, nameE, lastnameE, adressE, phoneE, mailE, emailE, mobileE, birthdayE, birthdayCbx, ocupationE, companyE, ofiE, officetelE, faxE, bankCbx, banktypeCbx, numbankE, personR1, personR2, Ch1, Ch2, Ch3, Ch4, Ch5, note, cc1E, name1E, adress1E, phone1E, job1E, jobphone1E, office1E, officetel1E, cc2E, name2E, adress2E, phone2E, job2E, jobphone2E, office2E, officetel2E, cc3E, name3E, adress3E, phone3E, job3E, jobphone3E, office3E, officetel3E, add, update, delete, clean, cancel global info, _arrendatarios _arrendatarios = dict() #Variables cedula = StringVar() titulo = StringVar() residencia = StringVar() nombres = StringVar() apellidos = StringVar() direccion = StringVar() telefono = StringVar() envio = StringVar() correo = StringVar() celular = StringVar() dia = IntVar() mes = StringVar() meses = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto","Septiembre", "Octubre", "Noviembre", "Diciembre"] profesion = StringVar() empresa = StringVar() oficina = StringVar() tel = StringVar() telfax = StringVar() banco = StringVar() bancos = ['Bancolombia', "Banco Bogotá", "Banco Agrario", "Banco Occidente"] banktype = ['Corriente','Ahorro'] tcuenta = StringVar() numcuenta = StringVar() tipopersona = IntVar() retefuente = IntVar() reteiva = IntVar() gcontribuyente = IntVar() gfactura = IntVar() gcheque = IntVar() notas = StringVar() #---------------------------- co1cc = StringVar() co1nombres = StringVar() co1dir = StringVar() co1tel1 = StringVar() co1cargo = StringVar() co1empresa = StringVar() co1oficina = StringVar() co1tel2 = StringVar() co2cc = StringVar() co2nombres = StringVar() co2dir = StringVar() co2tel1 = StringVar() co2cargo = StringVar() co2empresa = StringVar() co2oficina = StringVar() co2tel2 = StringVar() co3cc = StringVar() co3nombres = StringVar() co3dir = StringVar() co3tel1 = StringVar() co3cargo = StringVar() co3empresa = StringVar() co3oficina = StringVar() co3tel2 = StringVar() #BUSQUEDA = ["Nombre","CC/Nit"] busqueda = StringVar() busqueda.trace("w", lambda name, index, mode: buscar()) info = IntVar() dato = StringVar() #WIDGETS #========================= HEADER =========================== self.header = Label(self, text="GESTIÓN DE ARRENDATARIOS", font="bold") self.header.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) #================ NOTEBOOK =============> self.nb = Notebook(self.wrapper) #-----------------------> TAB 1 self.tab1 = Frame (self.nb) self.f0 = Frame(self.tab1)#Para dejar espacio entre Tab y Label self.f0.pack(fill=X, pady=10)#------------------------------- #======================= DATOS GENERALES ======================= self.f0 = Frame(self.tab1) self.f0.pack(pady=5,fill=X)#------------------------------------ self.codeL = Label(self.f0, text='CC:') self.codeL.pack(side=LEFT) codeE = Entry(self.f0, textvariable=cedula, width=10) codeE.pack(side=LEFT, fill=X, expand=1) codeE.focus_set() self.refL = Label(self.f0, text='Título:') self.refL.pack(side=LEFT) refE = Entry(self.f0, textvariable=titulo, width=10) refE.pack(side=LEFT) #refE.bind("<KeyRelease>", caps) self.cityL = Label(self.f0, text='Ciudad de residencia:') self.cityL.pack(side=LEFT) cityE = Entry(self.f0, textvariable=residencia, width=10) cityE.pack(side=LEFT) cityE.bind("<KeyRelease>", caps) self.f1 = Frame(self.tab1)#------------------------------- self.f1.pack(pady=5,fill=X) self.nameL = Label(self.f1, text='Nombres:') self.nameL.pack(side=LEFT) nameE = Entry(self.f1, textvariable=nombres) nameE.pack(side=LEFT, fill=X, expand=1) nameE.bind("<KeyRelease>", caps) self.lastnameL = Label(self.f1, text='Apellidos:') self.lastnameL.pack(side=LEFT) lastnameE = Entry(self.f1, textvariable=apellidos) lastnameE.pack(side=LEFT, fill=X, expand=1) lastnameE.bind("<KeyRelease>", caps) self.f2 = Frame(self.tab1) self.f2.pack(pady=5,fill=X)#------------------------------------ self.adressL = Label(self.f2, text='Dir. Casa:') self.adressL.pack(side=LEFT) adressE = Entry(self.f2, textvariable=direccion) adressE.pack(side=LEFT, fill=X, expand=1) adressE.bind("<KeyRelease>", caps) self.phoneL = Label(self.f2, text='Teléfono:') self.phoneL.pack(side=LEFT) phoneE = Entry(self.f2, textvariable=telefono, width=20) phoneE.pack(side=LEFT) self.f3 = Frame(self.tab1) self.f3.pack(pady=5,fill=X)#--------------------------- self.mailL = Label(self.f3, text='Dir. Correspondencia:') self.mailL.pack(side=LEFT) mailE = Entry(self.f3, textvariable=envio) mailE.pack(side=LEFT, fill=X, expand=1) mailE.bind("<KeyRelease>", caps) self.emailL = Label(self.f3, text='Email:') self.emailL.pack(side=LEFT) emailE = Entry(self.f3, textvariable=correo, width=15) emailE.pack(side=LEFT, fill=X, expand=1) self.f4 = Frame(self.tab1) self.f4.pack(pady=5,fill=X)#--------------------------- self.mobileL = Label(self.f4, text='Celular:') self.mobileL.pack(side=LEFT) mobileE = Entry(self.f4, textvariable=celular, width=10) mobileE.pack(side=LEFT, fill=X, expand=1) self.birthdayL = Label(self.f4, text='Cumpleaños:') self.birthdayL.pack(side=LEFT) self.birthdayL2 = Label(self.f4, text='Día:') self.birthdayL2.pack(padx=5,side=LEFT) birthdayE = Entry(self.f4, textvariable=dia, width=3) birthdayE.pack(side=LEFT) #s = Spinbox(self.f4, from_=1, to=31,textvariable=dia, width=3) #s.pack(side=LEFT) self.birthdayL3 = Label(self.f4, text='Mes:') self.birthdayL3.pack(padx=5,side=LEFT) birthdayCbx = Combobox(self.f4, textvariable=mes, values=meses, width=10) birthdayCbx.set('Enero') birthdayCbx.pack(side=LEFT) self.lf = LabelFrame(self.tab1, text="Info laboral")#======== self.f5 = Frame(self.lf) self.f5.pack(pady=5,fill=X)#--------------------------- self.ocupationL = Label(self.f5, text='Profesión:') self.ocupationL.pack(side=LEFT) ocupationE = Entry(self.f5, textvariable=profesion, width=20) ocupationE.pack(side=LEFT, fill=X, expand=1) ocupationE.bind("<KeyRelease>", caps) self.companyL = Label(self.f5, text='Empresa:') self.companyL.pack(side=LEFT) companyE = Entry(self.f5, textvariable=empresa, width=24) companyE.pack(side=LEFT, fill=X, expand=1) companyE.bind("<KeyRelease>", caps) self.f6 = Frame(self.lf) self.f6.pack(pady=5,fill=X)#-------------------- self.ofiL = Label(self.f6, text='Dir. Oficina:') self.ofiL.pack(side=LEFT) ofiE = Entry(self.f6, textvariable=oficina) ofiE.pack(side=LEFT, fill=X, expand=1) ofiE.bind("<KeyRelease>", caps) self.officetelL = Label(self.f6, text='Tel:') self.officetelL.pack(side=LEFT) officetelE = Entry(self.f6, textvariable=tel, width=10) officetelE.pack(fill=X, side=LEFT) self.faxL = Label(self.f6, text='Fax:') self.faxL.pack(side=LEFT) faxE = Entry(self.f6, textvariable=telfax, width=10) faxE.pack(side=LEFT) self.lf.pack(fill=X)#=========================================== self.f7 = Frame(self.tab1) self.f7.pack(pady=5,fill=X)#----------------- self.bankL = Label(self.f7, text='Banco:') self.bankL.pack(side=LEFT) bankCbx = Combobox(self.f7, textvariable=banco, values=bancos, width=12) bankCbx.set('') bankCbx.pack(side=LEFT) self.bankL = Label(self.f7, text='Tipo Cuenta:') self.bankL.pack(side=LEFT) banktypeCbx = Combobox(self.f7, textvariable=tcuenta, values=banktype, width=10) banktypeCbx.set('') banktypeCbx.pack(side=LEFT) self.numbankL = Label(self.f7, text="# Cuenta:") self.numbankL.pack(side=LEFT) numbankE = Entry(self.f7, textvariable=numcuenta, width=13) numbankE.pack(side=LEFT, fill=X, expand=1) self.f8 = Frame(self.tab1) self.f8.pack(pady=5,fill=X)#-------------------- self.personL = Label(self.f8, text='Tipo Persona:') self.personL.pack(side=LEFT) personR1 = Radiobutton(self.f8, text="Natural", variable=tipopersona, value=1) personR1.pack(padx=20,side=LEFT) personR2 = Radiobutton (self.f8, text="Jurídica", variable=tipopersona, value=2) personR2.pack(padx=20,side=LEFT) self.f = Frame(self.tab1) self.f.pack(pady=5,fill=X)#------------------------------------ Ch1 = Checkbutton(self.f, text="Retefuente", variable=retefuente) Ch1.pack(side=LEFT) Ch2 = Checkbutton(self.f, text="Rete IVA", variable=reteiva) Ch2.pack(side=LEFT) Ch3 = Checkbutton(self.f, text="Gran Contribuyente", variable=gcontribuyente) Ch3.pack(side=LEFT) Ch4 = Checkbutton(self.f, text="Genera Factura", variable=gfactura) Ch4.pack(side=LEFT) Ch5 = Checkbutton(self.f, text="Genera Cheque", variable=gcheque) Ch5.pack(side=LEFT) self.f9 = Frame(self.tab1) self.f9.pack(pady=5,fill=X)#-------------------- self.notesL = Label(self.f9, text='Observaciones:') self.notesL.pack(side=LEFT) self.f10 = Frame(self.tab1) self.f10.pack(pady=5,fill=X)#------------------- note = Text(self.f10, height=5) note.pack(fill=X, side=LEFT) #note.bind("<KeyRelease>", caps) #-----------------------> TAB 2 self.tab2 = Frame (self.nb) self.tab2.pack() self.f0 = Frame(self.tab2)#Para dejar espacio entre Tab y Label self.f0.pack(fill=X, pady=10)#---------------------------------- #===================== INFORMACIÓN CODEUDOR ==================== self.lf1 = LabelFrame(self.tab2, text="Codeudor 1") self.f0 = Frame(self.lf1) self.f0.pack(fill=X, pady=5)#------------------------------- self.ccL = Label(self.f0, text='CC:') self.ccL.pack(side=LEFT) cc1E = Entry(self.f0, textvariable= co1cc, width=10) cc1E.pack(side=LEFT, fill=X, expand=1) self.nameL = Label(self.f0, text='Nombres:') self.nameL.pack(side=LEFT) name1E = Entry(self.f0, textvariable=co1nombres) name1E.pack(side=LEFT, fill=X, expand=1) name1E.bind("<KeyRelease>", caps) self.f1 = Frame(self.lf1) self.f1.pack(fill=X, pady=5)#------------------------------- self.adressL = Label(self.f1, text='Dir. Casa:') self.adressL.pack(side=LEFT) adress1E = Entry(self.f1, textvariable=co1dir) adress1E.pack(side=LEFT, fill=X, expand=1) adress1E.bind("<KeyRelease>", caps) self.phoneL = Label(self.f1, text='Tel:') self.phoneL.pack(side=LEFT) phone1E = Entry(self.f1, textvariable=co1tel1, width=20) phone1E.pack(side=LEFT) self.f2 = Frame(self.lf1) self.f2.pack(fill=X, pady=5)#------------------------------- self.jobL = Label(self.f2, text='Cargo:') self.jobL.pack(side=LEFT) job1E = Entry(self.f2, textvariable=co1cargo, width=20) job1E.pack(side=LEFT, fill=X, expand=1) job1E.bind("<KeyRelease>", caps) self.phoneL = Label(self.f2, text='Empresa:') self.phoneL.pack(side=LEFT) jobphone1E = Entry(self.f2, textvariable=co1empresa) jobphone1E.pack(side=LEFT) jobphone1E.bind("<KeyRelease>", caps) self.f3 = Frame(self.lf1) self.f3.pack(fill=X, pady=5)#------------------------------- self.officeL = Label(self.f3, text='Dir. Oficina:') self.officeL.pack(side=LEFT) office1E = Entry(self.f3, textvariable=co1oficina) office1E.pack(side=LEFT, fill=X, expand=1) office1E.bind("<KeyRelease>", caps) self.officetelL = Label(self.f3, text='Tel:') self.officetelL.pack(side=LEFT) officetel1E = Entry(self.f3, textvariable=co1tel2, width=20) officetel1E.pack(fill=X, side=LEFT) self.lf1.pack(fill=X, ipady=5)#================================= self.lf2 = LabelFrame(self.tab2, text="Codeudor 2") self.f0 = Frame(self.lf2) self.f0.pack(fill=X, pady=5)#------------------------------- self.ccL = Label(self.f0, text='CC:') self.ccL.pack(side=LEFT) cc2E = Entry(self.f0, textvariable=co2cc, width=10) cc2E.pack(side=LEFT, fill=X, expand=1) self.nameL = Label(self.f0, text='Nombres:') self.nameL.pack(side=LEFT) name2E = Entry(self.f0, textvariable=co2nombres) name2E.pack(side=LEFT, fill=X, expand=1) name2E.bind("<KeyRelease>", caps) self.f1 = Frame(self.lf2) self.f1.pack(fill=X, pady=5)#------------------------------- self.adressL = Label(self.f1, text='Dir. Casa:') self.adressL.pack(side=LEFT) adress2E = Entry(self.f1, textvariable=co2dir) adress2E.pack(side=LEFT, fill=X, expand=1) adress2E.bind("<KeyRelease>", caps) self.phoneL = Label(self.f1, text='Tel:') self.phoneL.pack(side=LEFT) phone2E = Entry(self.f1, textvariable=co2tel1, width=20) phone2E.pack(side=LEFT) self.f2 = Frame(self.lf2) self.f2.pack(fill=X, pady=5)#------------------------------- self.adressL = Label(self.f2, text='Cargo:') self.adressL.pack(side=LEFT) job2E = Entry(self.f2, textvariable=co2cargo, width=20) job2E.pack(side=LEFT, fill=X, expand=1) job2E.bind("<KeyRelease>", caps) self.phoneL = Label(self.f2, text='Empresa:') self.phoneL.pack(side=LEFT) jobphone2E = Entry(self.f2, textvariable=co2empresa) jobphone2E.pack(side=LEFT) jobphone2E.bind("<KeyRelease>", caps) self.f3 = Frame(self.lf2) self.f3.pack(fill=X, pady=5)#------------------------------- self.officeL = Label(self.f3, text='Dir. Oficina:') self.officeL.pack(side=LEFT) office2E = Entry(self.f3, textvariable=co2oficina) office2E.pack(side=LEFT, fill=X, expand=1) office2E.bind("<KeyRelease>", caps) self.officetelL = Label(self.f3, text='Tel:') self.officetelL.pack(side=LEFT) officetel2E = Entry(self.f3, textvariable=co2tel2, width=20) officetel2E.pack(fill=X, side=LEFT) self.lf2.pack(fill=X, ipady=5)#================================= self.lf3 = LabelFrame(self.tab2, text="Codeudor 3") self.f0 = Frame(self.lf3) self.f0.pack(fill=X, pady=5)#------------------------------- self.ccL = Label(self.f0, text='CC:') self.ccL.pack(side=LEFT) cc3E = Entry(self.f0, textvariable=co3cc, width=10) cc3E.pack(side=LEFT, fill=X, expand=1) self.nameL = Label(self.f0, text='Nombres:') self.nameL.pack(side=LEFT) name3E = Entry(self.f0, textvariable=co3nombres) name3E.pack(side=LEFT, fill=X, expand=1) name3E.bind("<KeyRelease>", caps) self.f1 = Frame(self.lf3) self.f1.pack(fill=X, pady=5)#------------------------------- self.adressL = Label(self.f1, text='Dir. Casa:') self.adressL.pack(side=LEFT) adress3E = Entry(self.f1, textvariable=co3dir) adress3E.pack(side=LEFT, fill=X, expand=1) adress3E.bind("<KeyRelease>", caps) self.phoneL = Label(self.f1, text='Tel:') self.phoneL.pack(side=LEFT) phone3E = Entry(self.f1, textvariable=co3tel1, width=20) phone3E.pack(side=LEFT) self.f2 = Frame(self.lf3) self.f2.pack(fill=X, pady=5)#------------------------------- self.adressL = Label(self.f2, text='Cargo:') self.adressL.pack(side=LEFT) job3E = Entry(self.f2, textvariable=co3cargo, width=20) job3E.pack(side=LEFT, fill=X, expand=1) job3E.bind("<KeyRelease>", caps) self.phoneL = Label(self.f2, text='Empresa:') self.phoneL.pack(side=LEFT) jobphone3E = Entry(self.f2, textvariable=co3empresa) jobphone3E.pack(side=LEFT) jobphone3E.bind("<KeyRelease>", caps) self.f3 = Frame(self.lf3) self.f3.pack(fill=X, pady=5)#------------------------------- self.officeL = Label(self.f3, text='Dir. Oficina:') self.officeL.pack(side=LEFT) office3E = Entry(self.f3, textvariable=co3oficina) office3E.pack(side=LEFT, fill=X, expand=1) office3E.bind("<KeyRelease>", caps) self.officetelL = Label(self.f3, text='Tel:') self.officetelL.pack(side=LEFT) officetel3E = Entry(self.f3, textvariable=co3tel2, width=20) officetel3E.pack(fill=X, side=LEFT) self.lf3.pack(fill=X, ipady=5)#================================= #--------------------------------------------------------------- self.nb.add (self.tab1, text="Datos Generales") self.nb.add(self.tab2, text="Información Codeudor") self.nb.pack() #=========================== BOTONES =========================== self.fBtn = Frame(self.wrapper) self.fBtn.pack()#------------------------------- clean = Button(self.fBtn, text='Limpiar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=limpiar) clean.pack(side=RIGHT) update = Button(self.fBtn, text='Actualizar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=actualizar, state=DISABLED) update.pack(side=RIGHT) add = Button(self.fBtn, text='Agregar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=agregar) 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 ARRENDATARIOS") 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, bg='#d8ecf3') scroll.config (command=lb.yview) lb.pack(fill=BOTH) lb.bind("<Double-Button-1>", callback) self.wrap2 = Frame(self.aside) self.wrap2.pack() load = Button(self.wrap2, text='Cargar lista', width=20, bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=cargar_lista) load.pack(fill=X) delete = Button(self.wrap2, text='Borrar', width=20, bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=borrar) delete.pack(fill=X) edit = Button(self.wrap2, text='Modificar', width=20, bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=modificar) edit.pack(fill=X) self.wrap3 = Frame(self.aside) self.wrap3.pack() buscador = Label(self.wrap3, text="Buscar por:") buscador.pack(side=LEFT) R1 = Radiobutton(self.wrap3, text="CC", variable=info, value=1) R1.pack(side=LEFT) R2 = Radiobutton (self.wrap3, text="Apellido", variable=info, value=2) R2.pack(side=LEFT) info.set(1) self.wrap4 = Frame(self.aside) self.wrap4.pack() E = Entry(self.wrap4, textvariable=busqueda, width=24) E.pack() E.bind("<KeyRelease>", caps) """
def switch_sub_ddl(event): """ set the sub dropdownlist values according to the selected value in the main dropdownlist """ if event.widget.get() == 'Open': ddl_sub["values"] = li_sub_open elif event.widget.get() == 'Limited': ddl_sub["values"] = li_sub_cloz # main program root = Tk() li_main = ['Open', 'Limited'] # main list li_sub_open = ["Open Database Licence", "Licence Ouverte / Open Licence"] # 1st sublist li_sub_cloz = ["Security", "Legal", ""] # 2nd sublist # main dropdownlist ddl_main = Combobox(root, values = li_main) ddl_main.pack() ddl_main.bind("<<ComboboxSelected>>", switch_sub_ddl) # a separator to see better ^^ Separator(orient=HORIZONTAL).pack() # sub dropdownlist ddl_sub = Combobox(root, values = li_sub_open) ddl_sub.pack() root.mainloop()
class GUI_elements(object): # GUI objects, including those accessed # during session; initialize only once def __init__(self, master, app): self.master = master if app_state['exec_mode'] == 'PVS-client': emacs_pid = pvs_eval_and_wait('(emacs-pid)') else: emacs_pid = app_state['exec_mode'] master.title('Hypatheon Client for PVS (%s)' % emacs_pid) if on_aqua: pass # no separtor needed on OS X else: Frame(master, height=1, bg='black', bd=0 ).pack(fill=X, expand=YES) status_row = Frame(master) # drawing info displays, control buttons self.status_msg, self.prover_status, self.import_status, \ self.exec_mode_status = \ [ Label(status_row, relief=SUNKEN, bd=1, padx=5, font=text_font) for i in range(4) ] # must match number of fields self.status_msg['text'] = 'Welcome to Hypatheon ' for widget in (self.status_msg, self.prover_status, self.import_status): widget.pack(padx=2, side=LEFT) Frame(status_row).pack(side=LEFT, fill=X, expand=YES) if on_aqua: # avoid resize handle on lower right Frame(status_row).pack(padx=10, side=RIGHT) self.exec_mode_status.pack(padx=2, side=RIGHT) status_row.pack(padx=5, pady=2, fill=X, side=BOTTOM) self.create_query_control_area(master) self.query_history = [] # collect previous queries for listbox if on_osx: main_geometry = '+0+40' # upper left, with Y offset else: main_geometry = '-0+0' # upper right master.geometry(newGeometry=main_geometry) master.deiconify() # At the top of the main window is where queries are entered and launched. # This region contains a few Entry widgets for entering search terms # plus the buttons needed for control. def create_query_control_area(self, win): def clear_entries(): for ent in self.q_entries: ent.delete(0, END) self.q_entries[0].focus_set() bind_control_key(win, 'u', clear_entries) def invoke_query(dummy=None, terms=None, explicit_query=1): if terms == None: first = self.q_entries[0].get() if ';' in first: packed = split_and_pad_terms(first) terms = [ term.strip() for term in packed ] else: terms = [ ent.get().strip() for ent in self.q_entries ] results = submit_query(terms, explicit_query) if not explicit_query and not results: return results for ent, term in zip(self.q_entries, terms): ent.delete(0, END) ent.insert(END, term) return results self.invoke_query_handler = \ EventHandler('Invoke query choice', invoke_query) button_width = 5 def make_bottom_right(parent): try: # If the ttk combo-box widget is available, use it for the # Types field. Otherwise, create one out of other Tk widgets. from ttk import Combobox itypes = [ ' ' + t for t in cap_item_types ] self.type_ent = Combobox(parent, values=itypes, width=(query_entry_width - 6), height=len(itypes)) self.ttk_type_entry = 1 return self.type_ent except: self.ttk_type_entry = 0 # ttk not present bottom_right = Frame(parent) self.type_ent = entry_widget(bottom_right, width=(query_entry_width - 6)) self.type_ent.pack(side=LEFT, fill=X, expand=YES) self.types_pulldown_button = \ Button(bottom_right, text=u_triagdn, pady=0, anchor=S, command=EventHandler('Display file type list', self.types_pull_down)) self.types_pulldown_button.pack(side=LEFT, padx=2) return bottom_right def col_4(parent, row): if row == 0: return entry_widget(parent, width=query_entry_width) else: return make_bottom_right(parent) def col_6(parent, row): if row == 0: return ThinButton(parent, text='Clear', width=button_width, command=EventHandler('Clear entries', clear_entries, 0)) else: self.submit_function_button = \ ThinButton(parent, text='Search', width=button_width+1, ### command=self.invoke_query_handler) # , # default=ACTIVE) return self.submit_function_button text_bg = colors['text_bg_color'] q_frame, q_widgets = build_table(win, (lambda w,t: Label(w, text=t), lambda w,wid: entry_widget(w, width=wid), lambda w,t: Label(w, text=t), col_4, lambda w,t: Frame(w), col_6), (('Name:', query_entry_width, ' Refs:', 0, '', 0), ('Path:', query_entry_width, ' Type:', 1, '', 1)), anchors=(E, EW, E, EW, E, EW), col_weights=(0, 1, 0, 1, 0, 0), padx=1, pady=2) q_frame.pack(fill=X) Frame(win).pack(pady=1) self.q_entries = [q_widgets[0][1], q_widgets[0][3], q_widgets[1][1], self.type_ent] if not using_ttk and self.ttk_type_entry: for ent in self.q_entries[:3]: ent['bg'] = 'white' for ent in self.q_entries: ent.bind('<Return>', self.invoke_query_handler) self.q_entries[0].focus_set() # The rest of the window is managed as a tabbed notebook, where # query results will be displayed. self.notebook_panel = add_notebook_panel(win) # Another pull-down menu is provided for the list of available item types. # This is just a way to implement a simple combo-box, which is a widget # type not included in Tk until 8.5. The behavior is a little different # from a combo-box because strings are appended to the Entry value rather # than replacing it. def types_pull_down(self): button = self.types_pulldown_button x = button.winfo_rootx() - self.master.winfo_rootx() + 20 ### y = button.winfo_rooty() - self.master.winfo_rooty() + 25 ### fr = Frame(self.master, relief=SOLID, bd=2) itypes = cap_item_types[:] tlist = Listbox(fr, bd=0, highlightthickness=0, relief=FLAT, background=colors['text_bg_color'], exportselection=0, height=min(20, 1+len(itypes)), width=16) if using_ttk or using_tile: scrollbar = Scrollbar(fr, command=tlist.yview) else: scrollbar = Scrollbar(fr, command=tlist.yview, width=10, elementborderwidth=2, highlightthickness=0, bd=1) tlist.configure(yscrollcommand=scrollbar.set) tlist.pack(side=LEFT, fill=BOTH, expand=YES, padx=2, pady=2) scrollbar.pack(side=LEFT, fill=Y, expand = YES, pady=2) tlist.insert(END, 'None (clear)') for itype in itypes: tlist.insert(END, itype) def select_decl_type(y): index = int(tlist.nearest(y)) if index < 0: return if index == 0: self.type_ent.delete(0, END) else: self.type_ent.insert(END, ' ') self.type_ent.insert(END, tlist.get(index).strip()) fr.destroy() tlist.bind('<Button-1>', EventHandler('Select decl type', lambda event: select_decl_type(event.y))) def history_motion(event): tlist.selection_clear(0, END) tlist.selection_set(int(tlist.nearest(event.y))) tlist.bind('<Motion>', EventHandler('History list motion', history_motion, 0)) fr.place(x=x, y=y, anchor=NE) def dismiss_if_out(event): win = event.widget if not str(win).startswith(str(fr)): fr.destroy() self.master.bind('<Button-1>', lambda event: dismiss_if_out(event))
class MainFrame(Frame): def __init__(self,parent,stdoutq): Frame.__init__(self,parent) self.parent=parent self.width=850 self.height=650 self.title=menotexport.__version__ self.stdoutq=stdoutq self.initUI() self.hasdb=False self.hasout=False self.hasaction=False self.exit=False self.path_frame=self.addPathFrame() self.action_frame=self.addActionFrame() self.message_frame=self.addMessageFrame() self.printStr() self.stateq=Queue.Queue() #self.workproc=Pool(1) def centerWindow(self): sw=self.parent.winfo_screenwidth() sh=self.parent.winfo_screenheight() x=(sw-self.width)/2 y=(sh-self.height)/2 self.parent.geometry('%dx%d+%d+%d' \ %(self.width,self.height,x,y)) def initUI(self): self.parent.title(self.title) self.style=Style() #Choose from default, clam, alt, classic self.style.theme_use('alt') self.pack(fill=tk.BOTH,expand=True) self.centerWindow() def printStr(self): while self.stdoutq.qsize() and self.exit==False: try: msg=self.stdoutq.get() self.text.update() self.text.insert(tk.END,msg) self.text.see(tk.END) except Queue.Empty: pass self.after(100,self.printStr) def checkReady(self): if self.isexport.get()==1 or self.ishighlight.get()==1\ or self.isnote.get()==1 or self.isbib.get()==1: self.hasaction=True else: self.hasaction=False if self.hasdb and self.hasout and self.hasaction: self.start_button.configure(state=tk.NORMAL) print('# <Menotexport>: Menotexport Ready.') else: self.start_button.configure(state=tk.DISABLED) def addPathFrame(self): frame=Frame(self) frame.pack(fill=tk.X,expand=0,side=tk.TOP,padx=8,pady=5) frame.columnconfigure(1,weight=1) #------------------Database file------------------ label=tk.Label(frame,text='Mendeley Data file:',\ bg='#bbb') label.grid(row=0,column=0,\ sticky=tk.W,padx=8) self.db_entry=tk.Entry(frame) self.db_entry.grid(row=0,column=1,sticky=tk.W+tk.E,padx=8) self.db_button=tk.Button(frame,text='Open',command=self.openFile) self.db_button.grid(row=0,column=2,padx=8,sticky=tk.E) hint=''' Default location on Linux: ~/.local/share/data/Mendeley\ Ltd./Mendeley\ Desktop/[email protected] Default location on Windows: C:\Users\Your_name\AppData\Local\Mendeley Ltd\Mendeley Desktop\[email protected]''' hint_label=tk.Label(frame,text=hint,\ justify=tk.LEFT,anchor=tk.NW) hint_label.grid(row=1,column=0,columnspan=3,\ sticky=tk.W,padx=8) #--------------------Output dir-------------------- label2=tk.Label(frame,text='Output folder:',\ bg='#bbb') label2.grid(row=2,column=0,\ sticky=tk.W,padx=8) self.out_entry=tk.Entry(frame) self.out_entry.grid(row=2,column=1,sticky=tk.W+tk.E,padx=8) self.out_button=tk.Button(frame,text='Choose',command=self.openDir) self.out_button.grid(row=2,column=2,padx=8,sticky=tk.E) def openDir(self): self.out_entry.delete(0,tk.END) dirname=askdirectory() self.out_entry.insert(tk.END,dirname) if len(dirname)>0: print('# <Menotexport>: Output folder: %s' %dirname) self.hasout=True self.checkReady() def openFile(self): self.db_entry.delete(0,tk.END) ftypes=[('sqlite files','*.sqlite'),('ALL files','*')] initialdir='~/.local/share/data/Mendeley Ltd./Mendeley Desktop' initialdir=os.path.expanduser(initialdir) if os.path.isdir(initialdir): filename=askopenfilename(filetypes=ftypes,initialdir=initialdir) else: filename=askopenfilename(filetypes=ftypes) self.db_entry.insert(tk.END,filename) if len(filename)>0: print('# <Menotexport>: Database file: %s' %filename) self.probeFolders() def probeFolders(self): dbfile=self.db_entry.get() try: db=sqlite3.connect(dbfile) self.menfolderlist=menotexport.getFolderList(db,None) #(id, name) self.foldernames=['All']+[ii[1] for ii in self.menfolderlist] #names to display self.foldersmenu['values']=tuple(self.foldernames) self.foldersmenu.current(0) db.close() self.hasdb=True self.checkReady() except Exception as e: print('# <Menotexport>: Failed to recoganize the given database file.') print(e) def addActionFrame(self): frame=Frame(self,relief=tk.RAISED,borderwidth=1) frame.pack(fill=tk.X,side=tk.TOP,\ expand=0,padx=8,pady=5) label=tk.Label(frame,text='Actions:',bg='#bbb') label.grid(row=0,column=0,sticky=tk.W,padx=8) #---------------Action checkbuttons--------------- self.isexport=tk.IntVar() self.ishighlight=tk.IntVar() self.isnote=tk.IntVar() self.isbib=tk.IntVar() self.isris=tk.IntVar() self.isseparate=tk.IntVar() self.iszotero=tk.IntVar() self.iscustomtemp=tk.IntVar() self.check_export=tk.Checkbutton(frame,text='Export PDFs',\ variable=self.isexport,command=self.doExport) self.check_highlight=tk.Checkbutton(frame,\ text='Extract highlights',\ variable=self.ishighlight,command=self.doHighlight) self.check_note=tk.Checkbutton(frame,\ text='Extract notes',\ variable=self.isnote,command=self.doNote) self.check_bib=tk.Checkbutton(frame,\ text='Export .bib',\ variable=self.isbib,command=self.doBib) self.check_ris=tk.Checkbutton(frame,\ text='Export .ris',\ variable=self.isris,command=self.doRis) self.check_separate=tk.Checkbutton(frame,\ text='Save separately',\ variable=self.isseparate,command=self.doSeparate,\ state=tk.DISABLED) self.check_iszotero=tk.Checkbutton(frame,\ text='For import to Zotero',\ variable=self.iszotero,command=self.doIszotero,\ state=tk.DISABLED) self.check_custom_template=tk.Checkbutton(frame,\ text='Use custom template (experimental)',\ variable=self.iscustomtemp,command=self.doCustomTemp,\ state=tk.DISABLED) frame.columnconfigure(0,weight=1) self.check_export.grid(row=1,column=1,padx=8,sticky=tk.W) self.check_highlight.grid(row=1,column=2,padx=8,sticky=tk.W) self.check_note.grid(row=1,column=3,padx=8,sticky=tk.W) self.check_bib.grid(row=2,column=1,padx=8,sticky=tk.W) self.check_ris.grid(row=2,column=2,padx=8,sticky=tk.W) self.check_separate.grid(row=2,column=3,padx=8,sticky=tk.W) self.check_iszotero.grid(row=3,column=1,padx=8,sticky=tk.W) self.check_custom_template.grid(row=3,column=2,padx=8,sticky=tk.W) #---------------------2nd row--------------------- subframe=Frame(frame) subframe.grid(row=4,column=0,columnspan=6,sticky=tk.W+tk.E,\ pady=5) #-------------------Folder options------------------- folderlabel=tk.Label(subframe,text='Mendeley folder:',\ bg='#bbb') folderlabel.pack(side=tk.LEFT, padx=8) self.menfolder=tk.StringVar() self.menfolderlist=['All',] self.foldersmenu=Combobox(subframe,textvariable=\ self.menfolder,values=self.menfolderlist,state='readonly') self.foldersmenu.current(0) self.foldersmenu.bind('<<ComboboxSelected>>',self.setfolder) self.foldersmenu.pack(side=tk.LEFT,padx=8) #-------------------Quit button------------------- quit_button=tk.Button(subframe,text='Quit',\ command=self.quit) quit_button.pack(side=tk.RIGHT,padx=8) #-------------------Stop button------------------- ''' self.stop_button=tk.Button(subframe,text='Stop',\ command=self.stop) self.stop_button.pack(side=tk.RIGHT,padx=8) ''' #-------------------Start button------------------- self.start_button=tk.Button(subframe,text='Start',\ command=self.start,state=tk.DISABLED) self.start_button.pack(side=tk.RIGHT,pady=8) #-------------------Help button------------------- self.help_button=tk.Button(subframe,text='Help',\ command=self.showHelp) self.help_button.pack(side=tk.RIGHT,padx=8) def setfolder(self,x): self.foldersmenu.selection_clear() self.menfolder=self.foldersmenu.get() self.foldersmenu.set(self.menfolder) if self.menfolder=='All': print('# <Menotexport>: Work on all folders.') else: print('# <Menotexport>: Select Mendeley folder: '+str(self.menfolder)) def doExport(self): if self.isexport.get()==1: print('# <Menotexport>: Export annotated PDFs.') else: print('# <Menotexport>: Dont export annotated PDFs.') self.checkReady() def doHighlight(self): if self.ishighlight.get()==1: print('# <Menotexport>: Extract highlighted texts.') self.check_separate.configure(state=tk.NORMAL) self.check_custom_template.configure(state=tk.NORMAL) else: print('# <Menotexport>: Dont extract highlighted texts.') if self.isnote.get()==0: self.check_separate.configure(state=tk.DISABLED) self.check_custom_template.configure(state=tk.DISABLED) self.checkReady() def doNote(self): if self.isnote.get()==1: print('# <Menotexport>: Extract notes.') self.check_separate.configure(state=tk.NORMAL) self.check_custom_template.configure(state=tk.NORMAL) else: print('# <Menotexport>: Dont extract notes.') self.check_separate.state=tk.DISABLED if self.ishighlight.get()==0: self.check_separate.configure(state=tk.DISABLED) self.check_custom_template.configure(state=tk.DISABLED) self.checkReady() self.checkReady() def doBib(self): if self.isbib.get()==1: print('# <Menotexport>: Export to .bib file.') self.check_iszotero.configure(state=tk.NORMAL) else: print('# <Menotexport>: Dont export .bib file.') if self.isris.get()==0: self.check_iszotero.configure(state=tk.DISABLED) self.checkReady() def doRis(self): if self.isris.get()==1: print('# <Menotexport>: Export to .ris file.') self.check_iszotero.configure(state=tk.NORMAL) else: print('# <Menotexport>: Dont export .ris file.') if self.isbib.get()==0: self.check_iszotero.configure(state=tk.DISABLED) self.checkReady() def doSeparate(self): if self.isseparate.get()==1: print('# <Menotexport>: Save annotations separately.') else: print('# <Menotexport>: Save all annotations to single file.') def doIszotero(self): if self.iszotero.get()==1: print('# <Menotexport>: Save .bib/.ris file in Zotero preferred format.') else: print('# <Menotexport>: Save .bib/.ris file to default format.') def doCustomTemp(self): if self.iscustomtemp.get()==1: print('# <Menotexport>: Use custom template for exported annotations.') else: print('# <Menotexport>: Use default template for exported annotations.') def showHelp(self): helpstr=''' %s\n\n - Export PDFs: Bulk export PDFs.\n - Extract highlights: Extract highlighted texts and output to txt files.\n - Extract notes: Extract notes and output to txt files.\n - Export .bib: Export meta-data and annotations to .bib files.\n - Export .ris: Export meta-data and annotations to .ris files.\n - For import to Zotero: Exported .bib and/or .ris files have suitable format to import to Zotero.\n - Save separately: If on, save each PDF's annotations to a separate txt.\n - Use custom annotation template: Use a custom template to format the exported annotations. See annotation_template.py for details. - See README.md for more info.\n ''' %self.title tkMessageBox.showinfo(title='Help', message=helpstr) #print(self.menfolder.get()) def start(self): dbfile=self.db_entry.get() outdir=self.out_entry.get() self.menfolder=self.foldersmenu.get() # get (folderid, folder) for folder for ii in self.menfolderlist: if ii[1]==self.menfolder: folder_sel=[ii[0],ii[1].split('/')[-1]] action=[] if self.isexport.get()==1: action.append('p') if self.ishighlight.get()==1: action.append('m') if self.isnote.get()==1: action.append('n') if self.isbib.get()==1: action.append('b') if self.isris.get()==1: action.append('r') if self.isseparate.get()==1: separate=True else: separate=False if self.iszotero.get()==1: iszotero=True else: iszotero=False if self.iscustomtemp.get()==1: action.append('t') if 'p' in action or 'm' in action or 'n' in action or 'b' in action or 'r' in action: self.db_button.configure(state=tk.DISABLED) self.out_button.configure(state=tk.DISABLED) self.start_button.configure(state=tk.DISABLED) self.help_button.configure(state=tk.DISABLED) self.foldersmenu.configure(state=tk.DISABLED) self.check_export.configure(state=tk.DISABLED) self.check_highlight.configure(state=tk.DISABLED) self.check_note.configure(state=tk.DISABLED) self.check_bib.configure(state=tk.DISABLED) self.check_ris.configure(state=tk.DISABLED) self.check_separate.configure(state=tk.DISABLED) self.check_iszotero.configure(state=tk.DISABLED) self.check_custom_template.configure(state=tk.DISABLED) self.messagelabel.configure(text='Message (working...)') folder=None if self.menfolder=='All' else folder_sel args=[dbfile,outdir,action,folder,separate,iszotero,True] self.workthread=WorkThread('work',False,self.stateq) self.workthread.deamon=True self.workthread.args=args self.workthread.start() self.reset() ''' self.workproc.apply_async(menotexport.main,args,\ callback=self.reset) self.workproc.join() ''' def reset(self): while self.stateq.qsize() and self.exit==False: try: msg=self.stateq.get() if msg=='done': self.db_button.configure(state=tk.NORMAL) self.out_button.configure(state=tk.NORMAL) self.start_button.configure(state=tk.NORMAL) self.help_button.configure(state=tk.NORMAL) self.foldersmenu.configure(state='readonly') self.check_export.configure(state=tk.NORMAL) self.check_highlight.configure(state=tk.NORMAL) self.check_note.configure(state=tk.NORMAL) self.check_bib.configure(state=tk.NORMAL) self.check_separate.configure(state=tk.NORMAL) self.check_iszotero.configure(state=tk.NORMAL) self.check_custom_template.configure(state=tk.NORMAL) self.messagelabel.configure(text='Message') return except Queue.Empty: pass self.after(100,self.reset) def stop(self): #self.workthread.stop() pass def addMessageFrame(self): frame=Frame(self) frame.pack(fill=tk.BOTH,side=tk.TOP,\ expand=1,padx=8,pady=5) self.messagelabel=tk.Label(frame,text='Message',bg='#bbb') self.messagelabel.pack(side=tk.TOP,fill=tk.X) self.text=tk.Text(frame) self.text.pack(side=tk.TOP,fill=tk.BOTH,expand=1) self.text.height=10 scrollbar=tk.Scrollbar(self.text) scrollbar.pack(side=tk.RIGHT,fill=tk.Y) self.text.config(yscrollcommand=scrollbar.set) scrollbar.config(command=self.text.yview)
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)
class UIBidding(Notify): class CoincheException(Exception): def __init__(self, pid): self.pid = pid def __init__(self, root, x, y, size_x, size_y): Notify.__init__(self) # Memorise the frame self._root = root self._frame = Frame(width = size_x, height = size_y) # No resize self._frame.pack_propagate(0) # Style self._frame.config(borderwidth = 5) self._x = x self._y = y # Init the buttons self._init_buttons() # Will be used to notify the main thread when waiting for a call self.need_bid_event = Event() # Will be used to notify the main thread when waiting for a coinche self.coinche_event = Event() self.pid = 0 self._last_bid = None self.enable() def display(self): """ Display the widget on the table """ self._frame.place(in_ = self._root, x = self._x, y = self._y) def hide(self): """ Hide the pannel when the biddings are closed for example """ self._frame.place_forget() def _init_color_buttons(self): """ Init the buttons to select the color """ # Dedicated frame for buttons self._buttons_frame = Frame() # This dictionnary will contains all the color buttons self._buttons = dict() # Several colors are available colors = list(Bidding.colors) colors.pop() # The buttons need to have a fixed size h = 2 w = 2 for c in colors: self._buttons[c] = Button(self._buttons_frame, text=c, \ height=h, width=w, \ command=lambda c=c: self._click_color(c)) self._buttons[c].pack(side = LEFT) # Pack the dedicated frame into the main frame self._buttons_frame.pack(in_ = self._frame) self._selected_color = None def _init_value_box(self): """ Init the list box which select the value of the bid """ availableValue = Bidding.values # TODO: display "pass" instead of "0" #availableValue[0] = "pass" self._value_box = Combobox(self._frame, \ values = availableValue, \ # TODO # Only justify the selected value #justify = RIGHT, \ state = 'readonly') self._value_box.bind("<<ComboboxSelected>>", lambda x: self._update_bid_button()) self._value_box.set(availableValue[0]) self._value_box.pack(fill = X) @staticmethod def raise_(e): raise e def _init_bid_button(self): # To bid self._bid_button = Button(self._frame, text = "Pass", \ command = self._click_bidding) self._bid_button.pack(fill = X) # To coinche self._coinche_button = Button(self._frame, text = "Coinche", \ command = lambda: self._event[EVT_UI_COINCHE]()) self._coinche_button.pack(fill = X) def _init_buttons(self): """ Init the buttons """ # Put the value box on top of the buttons self._init_value_box() self._init_color_buttons() self._init_bid_button() def _click_color(self, color): self._selected_color = color self._update_bid_button() def _click_bidding(self): """ Callback function on bidding click """ if self._bid_button.config('text')[-1] == "Pass": self._last_bid = Bidding(self.pid) else: if self._selected_color is None: self._event[CONSOLE_RED]("Choose a color!") return c = self._selected_color v = int(self._value_box.get()) self._last_bid = Bidding(self.pid, v, c) # Notify the consumer (main thread) self.need_bid_event.set() # Reset the event self.need_bid_event.clear() def _click_coinche(self): # Notify the consumer self.coinche_event.set() # Reset the event self.coinche_event.clear() def _update_bid_button(self): value = self._value_box.get() color = self._selected_color if value == "0" and color is None: self._bid_button.config(text = "Pass") elif value == "0": self._bid_button.config(text = "Bid " + color) elif color is None: self._bid_button.config(text = "Bid " + value) else: self._bid_button.config(text = "Bid " + value + " " + color) @property def last_bid(self): return self._last_bid @last_bid.setter def last_bid(self, value): if value is None: self._bid_button.config(text = "Pass") self._last_bid = None else: raise Exception("Should not be called") def disable(self): """ Disable the bid button """ self._bid_button.config(state = DISABLED) def enable(self): """ Enable the bid button """ self._bid_button.config(state = NORMAL)
class Gui(Frame): """ GUI class for Grahphical User Interface""" def __init__(self, parent): Frame.__init__(self, parent) self.appdata = AppData() # to create AppData object self.initUI() def initUI(self): self.pack(fill=BOTH, expand=True) Label(self, text='Election Data Analysis Tool v1.0', bg='red', fg='white', font=('Arial', 15, 'bold')).pack(fill=X, anchor=N) # header self.load_data_btn = Button(self, text='Load Election Data', width=30, height=2, command=self.appdata.readfile) self.load_data_btn.pack(pady=10, anchor=N) self.buttonsframe = Frame(self) # to keep buttons in frame self.buttonsframe.pack(fill=X, anchor=N) self.districtsbtn = Button(self.buttonsframe, text='Cluster Districts', width=30, height=3, command=self.clusterdistricts) self.districtsbtn.pack(side=LEFT, padx=(180, 5)) self.partiesbtn = Button(self.buttonsframe, text='Cluster Political Parties', width=30, height=3, command=self.clusterparties) self.partiesbtn.pack(side=LEFT) self.check_dynamic = True # to check dynamic function is called def dynamic(self): self.canvasframe = Frame(self) # to keep canvas self.canvasframe.pack(fill=X) self.canvas = Canvas(self.canvasframe, bg='grey') self.vbar = Scrollbar(self.canvasframe, orient=VERTICAL) # vertical scrollbar self.vbar.pack(side=RIGHT, fill=Y) self.vbar.config( command=self.canvas.yview) # to adapt vertical scrollbar to canvas self.hbar = Scrollbar(self.canvasframe, orient=HORIZONTAL) # horizontal scrollbar self.hbar.pack(side=BOTTOM, fill=X) self.hbar.config(command=self.canvas.xview ) # to adapt horizontal scrollbar to canvas self.canvas.pack(fill=X) self.canvas.config( xscrollcommand=self.hbar.set, yscrollcommand=self.vbar.set) # to set scrollbars in canvas self.bottomframe = Frame(self) # Frame to keep listbox and so on self.bottomframe.pack(fill=X) Label(self.bottomframe, text='Districts:').pack(side=LEFT, padx=(150, 0)) # districts label self.scroll = Scrollbar(self.bottomframe, orient="vertical") # Scrollbar to listbox self.listbox = Listbox(self.bottomframe, selectmode='multiple', yscrollcommand=self.scroll.set) self.listbox.pack(side=LEFT) self.scroll.config(command=self.listbox.yview ) # to adapt vertical scrollbar to canvas self.scroll.pack(side=LEFT, fill="y") Label(self.bottomframe, text='Treshould:').pack(side=LEFT) self.combo = Combobox( self.bottomframe, values=['0%', '1%', '10%', '20%', '30%', '40%', '50%'], width=5) # create combobox to keep persantages self.combo.pack(side=LEFT) self.combo.current(0) self.analysisbtn = Button(self.bottomframe, text="Refine Analysis", width=30, height=2, command=self.refine_analysis) self.analysisbtn.pack(side=LEFT) for i in sorted( self.appdata.districts): # to append all districts in listbox self.listbox.insert(END, i) def clusterdistricts(self, persantage=0, selected_text_list=[]): if self.check_dynamic: # to check dynamic func called or not self.dynamic() self.check_dynamic = False # after the called dynamic it will be false to don't enter again matrix = [] # to keep matrix nested list rows = set() # to keep districts in a list for name, dist_obj in sorted( self.appdata.districts.items()): # to move in the districts if name in selected_text_list or selected_text_list == []: # if selected_text list is empty or name in it list2append = [ ] # to keep parties' vote for a single districts rows.add(name) for tag in sorted( self.appdata.parties): # to check all parties try: # if it gives any error it will go except part if dist_obj.election_results[ tag] >= persantage: # if persantage is less than vote list2append.append( dist_obj.election_results[tag]) # append it else: raise KeyError # if not less than vote raise a keyerror and enter except part except KeyError: list2append.append( 0 ) # if less than or not have a that party append 0 matrix.append( list2append ) # to append each districts paries in matrix list clust = hcluster(matrix, distance=sim_distance) # make a cluster drawdendrogram(clust, sorted(list(rows))) im = Image.open( 'clusters.jpg') # to open jpg file and insert in canvas self.canvas.image = ImageTk.PhotoImage(im) self.canvas.create_image(0, 0, image=self.canvas.image, anchor='nw') self.canvas.config( scrollregion=self.canvas.bbox(ALL)) # to use all canvas box self.cluster = 'districts' # to define which cluster will be refining def clusterparties(self, persantage=0, selected_text_list=[]): """ # Same thing with the clusterdistricts method but for the parties """ if self.check_dynamic: # to check dynamic self.dynamic() self.check_dynamic = False # after the calling dynamic do it false matrix = [] # matrix for the votes as a nested list rows = set() # rows list to keep parties' acronyms for acronym, party_obj in sorted(self.appdata.parties.items()): list2append = [] # to keep each parties votes rows.add(acronym) for tag in sorted( self.appdata.districts ): # move in a districts as a sorted to be a regular if tag in selected_text_list or selected_text_list == []: # if checkbox not selected or not choosen try: if party_obj.election_results[ tag] >= persantage: # if vote grader and equal to persantage list2append.append( party_obj.election_results[tag] ) # append it in list2append list else: raise KeyError # if not grater and equal raise KeyError except KeyError: # if it give an error append 0 in a list list2append.append(0) matrix.append(list2append) # add list2append in a matrix clust = hcluster( matrix, distance=sim_distance) # make a cluster with using matrix drawdendrogram(clust, sorted(list(rows))) # draw a dendogram as a jpg file im = Image.open('clusters.jpg') self.canvas.image = ImageTk.PhotoImage(im) self.canvas.create_image(0, 0, image=self.canvas.image, anchor='nw') self.canvas.config(scrollregion=self.canvas.bbox(ALL)) self.cluster = 'parties' # to define which cluster will be refining def refine_analysis(self): try: pers = self.combo.get().split( '%') # pers to split % from persantage of combobox persantage = float(pers[0]) # to convert persantage to float value selected_text_list = [ self.listbox.get(i) for i in self.listbox.curselection() ] # to take all selected districts if self.cluster == 'districts': # to define which cluster will be refining self.clusterdistricts(persantage, selected_text_list) else: self.clusterparties(persantage, selected_text_list) except: pass # Eliminate the error case when clicking refine analysis button before the click cluster's button.
class Application(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.initUI() self.state = "inactive" #state remembers last clicked cluster button so when user clicks the refine analysis button #program is going to perform analysis on districts or parties with the information it gets from state. self.data_manager = DataCenter( ) #this is data center object to manage data processes. def initUI(self): self.pack(fill=BOTH) self.UI_frame = Frame(self) self.UI_frame.pack(side=TOP, fill=BOTH) self.header = Label(self.UI_frame, text="Election Data Analysis Tool v.1.0", background="red", font=('Arial', '23', 'bold'), foreground="white") self.header.pack(side=TOP, fill=BOTH, ipady=7) self.upload_data_button = Button(self.UI_frame, text="Load Election Data", height=2, width=20, command=self.upload_data) self.cluster_district_button = Button(self.UI_frame, text="Cluster Districts", height=2, width=20, command=self.cluster_district) self.cluster_parties_button = Button(self.UI_frame, text="Cluster Political Parties", height=2, width=20, command=self.cluster_parties) self.upload_data_button.pack(side=TOP, pady=10) self.cluster_district_button.pack(side=LEFT, padx=(255, 10)) self.cluster_parties_button.pack(side=LEFT) self.analysis_frame = Frame(self) self.canvas_frame = Frame(self.analysis_frame) self.canvas_frame.pack(side=TOP, fill=BOTH, padx=90, pady=10) self.canvas_horizontal_scroll = Scrollbar(self.canvas_frame, orient="horizontal") self.canvas_vertical_scroll = Scrollbar(self.canvas_frame, orient="vertical") self.canvas = Canvas(self.canvas_frame, background="white", height=250, width=700) self.canvas.grid(row=0, column=0) self.canvas_horizontal_scroll.grid(row=1, column=0, columnspan=2, sticky=W + E) self.canvas_vertical_scroll.grid(row=0, column=1, sticky=S + N) self.canvas.configure(xscrollcommand=self.canvas_horizontal_scroll.set, yscrollcommand=self.canvas_vertical_scroll.set) self.canvas_horizontal_scroll.configure(command=self.canvas.xview) self.canvas_vertical_scroll.configure(command=self.canvas.yview) self.canvas.configure(scrollregion=(0, 0, 1200, 800)) #scrollregion helps us to cover all of the dendogram with scrollbars. self.panel_frame = Frame(self.analysis_frame) self.panel_frame.pack(side=TOP, fill=BOTH) self.district_label = Label(self.panel_frame, text="Districts:") self.district_listbox = Listbox(self.panel_frame, selectmode="multiple") self.listbox_scroll = Scrollbar(self.panel_frame) self.district_listbox.configure(yscrollcommand=self.listbox_scroll.set) self.listbox_scroll.configure(command=self.district_listbox.yview) self.threshold_label = Label(self.panel_frame, text="Threshold:") threshold_list = ["%0", "%1", "%10", "%20", "%30", "%40", "%50"] #list for threshold combobox self.threshold_combobox = Combobox(self.panel_frame, width=7, state="readonly", values=threshold_list) self.threshold_combobox.current(0) #default threshold is %0 self.refine_button = Button(self.panel_frame, text="Refine Analysis", height=2, width=20, command=self.refined_analysis) self.district_label.pack(side=LEFT, padx=(120, 5)) self.district_listbox.pack(side=LEFT) self.listbox_scroll.pack(side=LEFT, fill=Y) self.threshold_label.pack(side=LEFT, padx=10) self.threshold_combobox.pack(side=LEFT) self.refine_button.pack(side=LEFT, padx=20) def upload_data(self): self.district_listbox.delete(0, END) txt_file = tkFileDialog.askopenfilename( title="Select file", filetypes=(("txt files", "*.txt"), ("all files", "*.*"))) self.data_manager.txt_manager(txt_file) #txt reader function self.data_manager.create_matrix( district_list=self.data_manager.district_dictionary.keys(), threshold="%0") #program creates matrix with default values which is all districts and %0 threshold right after reading txt. for district in sorted(self.data_manager.district_dictionary.keys()): self.district_listbox.insert(END, district) #inserting districts to listbox def cluster_district(self): self.state = "district" #if user clickes cluster districts state changes to district. self.analysis_frame.pack(side=TOP, fill=BOTH) self.canvas.delete("all") #clearing canvas # https://stackoverflow.com/questions/15839491/how-to-clear-tkinter-canvas self.party_list, self.district_list, self.data = clusters.readfile( "matrix.txt") new_data = clusters.rotatematrix(self.data) #we need to rotated matrix to cluster districts. clust = clusters.hcluster(new_data, distance=clusters.sim_distance) clusters.drawdendrogram(clust, self.district_list, jpeg='districts.jpg') self.insert_image("districts.jpg") #insert clustered image to canvas def cluster_parties(self): self.state = "party" #if user clickes cluster parties state changes to party. self.analysis_frame.pack(side=TOP, fill=BOTH) self.canvas.delete("all") #clearing canvas # https://stackoverflow.com/questions/15839491/how-to-clear-tkinter-canvas self.party_list, self.district_list, self.data = clusters.readfile( "matrix.txt") clust = clusters.hcluster(self.data, distance=clusters.sim_distance) clusters.drawdendrogram(clust, self.party_list, jpeg='parties.jpg') self.insert_image("parties.jpg") #insert clustered image to canvas def insert_image(self, name): #function to create PIL image and inserting canvas. img = Image.open(name) self.canvas.img = ImageTk.PhotoImage(img) self.canvas.create_image(0, 0, image=self.canvas.img, anchor="nw") #from link in the pdf related canvas. we need to justify left corner our dendogram to have a nice usage. def refined_analysis(self): """ we use try-except structure to raise zero-division error that occurs when user selects less districts and let cluster algorithm fail. """ try: selected_districts = map(lambda x: self.district_listbox.get(x), self.district_listbox.curselection()) #we use map function through list of indexes user choosed to get name of districts efficiently. if len(selected_districts) == 0: selected_districts = self.data_manager.district_dictionary.keys( ) #if our selection list is empty we tell program to use all of districts. self.data_manager.create_matrix( district_list=selected_districts, threshold=self.threshold_combobox.get()) #executing create_matrix function with selected list and threshold value from combobox. if self.state == "district": #here program decides to execute cluster_district or cluster_parties. self.cluster_district() else: self.cluster_parties() except: raise Exception( "You need to select more district to have an refined analysis!." )
def __init__(self, parent, controller): Frame.__init__(self, parent) #VARIABLES GLOBALES global cedula, titulo, ingreso, rsocial, residencia, nombres, apellidos, direccion, telefono, oficina, tel, telfax, correo, cumpleanos, dia, mes, envio, celular, tipopersona, comision, retefuente, reteiva, gcontribuyente, gfactura, gcheque, reprecc, reprenombres, repredireccion, repretelefono, repreoficina, repretel, reprebanco, repretcuenta, reprenumcuenta, tit1cc, tit1nombres, tit1banco, tit1tcuenta, tit1numcuenta, tit2cc, tit2nombres, tit2banco, tit2tcuenta, tit2numcuenta, lb, note, popmenu, busqueda, dato, E #INSTANCIEAS DE LOS WIDGETS global ccE, refE, dateinE, socialE, cityE, nameE, lnameE, adressE, phoneE, officeE, officetelE, telfaxE, emailE, birthdayE, birthdayCbx, mailE, mobileE, personR1, personR2, comisionE, Ch1, Ch2, Ch3, Ch4, Ch5, note, cc0E, name0E, adress0E, phone0E, office0E, officetel0E, bank0Cbx, tbank0Cbx, tcuenta0E, cc1E, name1E, bank1Cbx, tbank1Cbx, tcuenta1E, cc2E, name2E, bank2Cbx, tbank2Cbx, tcuenta2E, add, update, delete, clean global info, lists, _propietarios _propietarios = dict() lists = [] #Variables cedula = StringVar() titulo = StringVar() ingreso = StringVar() rsocial = StringVar() residencia = StringVar() nombres = StringVar() apellidos = StringVar() direccion = StringVar() telefono = StringVar() oficina = StringVar() tel = StringVar() telfax = StringVar() correo = StringVar() dia = IntVar() mes = StringVar() envio = StringVar() celular = StringVar() tipopersona = IntVar() comision = DoubleVar() retefuente = IntVar() reteiva = IntVar() gcontribuyente = IntVar() gfactura = IntVar() gcheque = IntVar() notas = StringVar() #---------------------------- reprecc = StringVar() reprenombres = StringVar() repredireccion = StringVar() repretelefono = StringVar() repreoficina = StringVar() repretel = StringVar() reprebanco = StringVar() repretcuenta = StringVar() reprenumcuenta = StringVar() tit1cc = StringVar() tit1nombres = StringVar() tit1banco = StringVar() tit1tcuenta = StringVar() tit1numcuenta = StringVar() tit2cc = StringVar() tit2nombres = StringVar() tit2banco = StringVar() tit2tcuenta = StringVar() tit2numcuenta = StringVar() meses = [ "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" ] tbancos = [ 'Bancolombia', "Banco Bogotá", "Banco Agrario", "Banco Occidente" ] tbanktype = ['Corriente', 'Ahorro'] #BUSQUEDA = ["Nombre","CC/Nit"] busqueda = StringVar() busqueda.trace("w", lambda name, index, mode: buscar()) info = IntVar() #eleccion = IntVar() dato = StringVar() # MENU DEL MOUSE popmenu = Menu(self, tearoff=0) popmenu.add_command(label="Imprimir", command=hello) popmenu.add_command(label="Cargar", command=modificar) popmenu.add_command(label="Eliminar", command=borrar) #popmenu.add_separator() popmenu.bind('<Escape>', release) #WIDGETS #========================= HEADER ============================== self.header = Label(self, text="GESTIÓN DE PROPIETARIOS", font="bold") self.header.pack(pady=20, side=TOP) #========================== WRAPPER ============================ #Contiene los Notebooks con los campos formulario self.wrapper = Frame(self) self.wrapper.pack(side=LEFT, fill=Y) #Esto centro el wrapper #self.wrapper.pack(side=LEFT, fill=BOTH, expand=True) #================ NOTEBOOK =============> self.nb = Notebook(self.wrapper) #-----------------------> TAB 1 self.tab1 = Frame(self.nb) self.f0 = Frame(self.tab1) #Para dejar espacio entre Tab y Label self.f0.pack(fill=X, pady=10) #------------------------------- #========================= PERSONALES ========================== self.f1 = Frame(self.tab1) #------------------------------- self.f1.pack(pady=5, fill=X) self.ccL = Label(self.f1, text='CC/Nit:') self.ccL.pack(side=LEFT) ccE = Entry(self.f1, textvariable=cedula) ccE.pack(side=LEFT, fill=X, expand=1) ccE.focus_set() self.refL = Label(self.f1, text='Título:') self.refL.pack(side=LEFT) refE = Entry(self.f1, textvariable=titulo, width=10) refE.pack(side=LEFT) #refE.bind("<KeyRelease>", caps) self.dateinL = Label(self.f1, text='Fecha Ingreso:') self.dateinL.pack(side=LEFT) dateinE = Entry(self.f1, textvariable=ingreso, width=10, state=DISABLED) ingreso.set("0000-00-00") dateinE.pack(side=LEFT) self.f2 = Frame(self.tab1) #------------------------------- self.f2.pack(pady=5, fill=X) self.socialL = Label(self.f2, text='Razón Social:') self.socialL.pack(side=LEFT) socialE = Entry(self.f2, textvariable=rsocial) socialE.pack(side=LEFT, fill=X, expand=1) socialE.bind("<KeyRelease>", caps) self.cityL = Label(self.f2, text='Ciudad de residencia:') self.cityL.pack(side=LEFT) cityE = Entry(self.f2, textvariable=residencia, width=15) cityE.pack(side=LEFT) cityE.bind("<KeyRelease>", caps) self.f3 = Frame(self.tab1) self.f3.pack(pady=5, fill=X) #----------------------------------------- self.nameL = Label(self.f3, text='Nombres:') self.nameL.pack(side=LEFT) nameE = Entry(self.f3, textvariable=nombres) nameE.pack(side=LEFT, fill=X, expand=1) nameE.bind("<KeyRelease>", caps) self.lnameL = Label(self.f3, text='Apellidos:') self.lnameL.pack(side=LEFT) lnameE = Entry(self.f3, textvariable=apellidos) lnameE.pack(side=LEFT, fill=X, expand=1) lnameE.bind("<KeyRelease>", caps) self.f4 = Frame(self.tab1) self.f4.pack(pady=5, fill=X) #----------------------------------------- self.adressL = Label(self.f4, text='Dir. Casa:') self.adressL.pack(side=LEFT) adressE = Entry(self.f4, textvariable=direccion) adressE.pack(side=LEFT, fill=X, expand=1) adressE.bind("<KeyRelease>", caps) self.phoneL = Label(self.f4, text='Tel:') self.phoneL.pack(side=LEFT) phoneE = Entry(self.f4, textvariable=telefono, width=20) phoneE.pack(side=LEFT) self.f5 = Frame(self.tab1) self.f5.pack(pady=5, fill=X) #------------------------------------ self.officeL = Label(self.f5, text='Dir. Oficina:') self.officeL.pack(side=LEFT) officeE = Entry(self.f5, textvariable=oficina, width=20) officeE.pack(side=LEFT, fill=X, expand=1) officeE.bind("<KeyRelease>", caps) self.officetelL = Label(self.f5, text='Tel:') self.officetelL.pack(side=LEFT) officetelE = Entry(self.f5, textvariable=tel, width=15) officetelE.pack(fill=X, side=LEFT) self.telfaxL = Label(self.f5, text='Tel. Fax:') self.telfaxL.pack(side=LEFT) telfaxE = Entry(self.f5, textvariable=telfax, width=10) telfaxE.pack(side=LEFT) self.f6 = Frame(self.tab1) self.f6.pack(pady=5, fill=X) #------------------------------------ self.emailL = Label(self.f6, text='Email:') self.emailL.pack(side=LEFT) emailE = Entry(self.f6, textvariable=correo, width=30) emailE.pack(side=LEFT) self.birthdayL = Label(self.f6, text='Cumpleaños:') self.birthdayL.pack(side=LEFT) self.birthdayL2 = Label(self.f6, text='Día:') self.birthdayL2.pack(padx=5, side=LEFT) #s = Spinbox(self.f6, from_=1, to=31,textvariable=dia, width=3) #s.pack(side=LEFT) birthdayE = Entry(self.f6, textvariable=dia, width=3) birthdayE.pack(side=LEFT) self.birthdayL3 = Label(self.f6, text='Mes:') self.birthdayL3.pack(padx=5, side=LEFT) birthdayCbx = Combobox(self.f6, textvariable=mes, values=meses, width=10) birthdayCbx.set('Enero') birthdayCbx.pack(side=LEFT) self.f7 = Frame(self.tab1) self.f7.pack(pady=5, fill=X) #------------------------------------ self.mailL = Label(self.f7, text='Dir. Correspondencia:') self.mailL.pack(side=LEFT) mailE = Entry(self.f7, textvariable=envio) mailE.pack(side=LEFT, fill=X, expand=1) mailE.bind("<KeyRelease>", caps) self.mobileL = Label(self.f7, text='Celular:') self.mobileL.pack(side=LEFT) mobileE = Entry(self.f7, textvariable=celular, width=10) mobileE.pack(side=LEFT, fill=X, expand=1) self.f8 = Frame(self.tab1) self.f8.pack(pady=5, fill=X) #------------------------------------ self.personL = Label(self.f8, text='Tipo Persona:') self.personL.pack(side=LEFT) personR1 = Radiobutton(self.f8, text="Natural", variable=tipopersona, value=1) personR1.pack(padx=20, side=LEFT) personR2 = Radiobutton(self.f8, text="Jurídica", variable=tipopersona, value=2) personR2.pack(padx=20, side=LEFT) self.comisionL = Label(self.f8, text='$ Comisión:') self.comisionL.pack(side=LEFT) comisionE = Entry(self.f8, textvariable=comision, width=5) comisionE.pack(side=LEFT) self.f = Frame(self.tab1) self.f.pack(pady=5, fill=X) #------------------------------------ Ch1 = Checkbutton(self.f, text="Retefuente", variable=retefuente) Ch1.pack(side=LEFT) Ch2 = Checkbutton(self.f, text="Rete IVA", variable=reteiva) Ch2.pack(side=LEFT) Ch3 = Checkbutton(self.f, text="Gran Contribuyente", variable=gcontribuyente) Ch3.pack(side=LEFT) Ch4 = Checkbutton(self.f, text="Genera Factura", variable=gfactura) Ch4.pack(side=LEFT) Ch5 = Checkbutton(self.f, text="Genera Cheque", variable=gcheque) Ch5.pack(side=LEFT) self.f9 = Frame(self.tab1) self.f9.pack(pady=5, fill=X) #------------------------------------ self.notesL = Label(self.f9, text='Observaciones:') self.notesL.pack(side=LEFT) self.f10 = Frame(self.tab1) self.f10.pack(pady=5, fill=X) #------------------------------------ note = Text(self.f10, height=5) note.pack(side=LEFT, fill=X, expand=1) self.tab1.pack() #-----------------------> TAB 2 self.tab2 = Frame(self.nb) self.tab2.pack() self.f0 = Frame(self.tab2) #Para dejar espacio entre Tab y Label self.f0.pack(fill=X, pady=10) #---------------------------------- #======================= COMPLEMENTARIOS ======================= self.lf = LabelFrame(self.tab2, text="Datos Representante") self.f0 = Frame(self.lf) self.f0.pack(fill=X, pady=5) #------------------------------- self.ccRL = Label(self.f0, text='CC:') self.ccRL.pack(side=LEFT) cc0E = Entry(self.f0, textvariable=reprecc, width=10) cc0E.pack(side=LEFT, fill=X, expand=1) self.nameL = Label(self.f0, text='Nombres:') self.nameL.pack(side=LEFT) name0E = Entry(self.f0, textvariable=reprenombres) name0E.pack(side=LEFT, fill=X, expand=1) name0E.bind("<KeyRelease>", caps) self.f1 = Frame(self.lf) self.f1.pack(fill=X, pady=5) #------------------------------- self.adressL = Label(self.f1, text='Dir. Casa:') self.adressL.pack(side=LEFT) adress0E = Entry(self.f1, textvariable=repredireccion) adress0E.pack(side=LEFT, fill=X, expand=1) adress0E.bind("<KeyRelease>", caps) self.phoneL = Label(self.f1, text='Tel:') self.phoneL.pack(side=LEFT) phone0E = Entry(self.f1, textvariable=repretelefono, width=20) phone0E.pack(side=LEFT) self.f2 = Frame(self.lf) self.f2.pack(fill=X, pady=5) #------------------------------- self.officeL = Label(self.f2, text='Dir. Oficina:') self.officeL.pack(side=LEFT) office0E = Entry(self.f2, textvariable=repreoficina) office0E.pack(side=LEFT, fill=X, expand=1) office0E.bind("<KeyRelease>", caps) self.officetelL = Label(self.f2, text='Tel:') self.officetelL.pack(side=LEFT) officetel0E = Entry(self.f2, textvariable=repretel, width=20) officetel0E.pack(fill=X, side=LEFT) self.f3 = Frame(self.lf) self.f3.pack(fill=X) #------------------------------------------- self.tbancpL = Label(self.f3, text='Banco:') self.tbancpL.pack(side=LEFT) bank0Cbx = Combobox(self.f3, textvariable=reprebanco, values=tbancos, width=12) bank0Cbx.set('') bank0Cbx.pack(side=LEFT) self.tbancpL = Label(self.f3, text='Tipo Cuenta:') self.tbancpL.pack(side=LEFT) tbank0Cbx = Combobox(self.f3, textvariable=repretcuenta, values=tbanktype, width=8) tbank0Cbx.set('') tbank0Cbx.pack(side=LEFT) self.tcuentaL = Label(self.f3, text='# Cuenta:') self.tcuentaL.pack(side=LEFT) tcuenta0E = Entry(self.f3, textvariable=reprenumcuenta) tcuenta0E.pack(side=LEFT, fill=X, expand=1) self.lf.pack(fill=X, ipady=5) #================================== self.f0 = Frame(self.tab2) #Para dejar espacio entre Tab y Label self.f0.pack(fill=X, pady=10) #------------------------------- #--------------------------------------------------------------- self.lf1 = LabelFrame(self.tab2, text="Datos Titular 1") self.f4 = Frame(self.lf1) self.f4.pack(fill=X, pady=5) #------------------------------- self.ccL = Label(self.f4, text='CC:') self.ccL.pack(side=LEFT) cc1E = Entry(self.f4, textvariable=tit1cc) cc1E.pack(side=LEFT, fill=X, expand=1) self.nameL = Label(self.f4, text='Nombres:') self.nameL.pack(side=LEFT) name1E = Entry(self.f4, textvariable=tit1nombres) name1E.pack(side=LEFT, fill=X, expand=1) name1E.bind("<KeyRelease>", caps) self.f5 = Frame(self.lf1) self.f5.pack(fill=X) #------------------------------------------- self.tbancpL = Label(self.f5, text='Banco:') self.tbancpL.pack(side=LEFT) bank1Cbx = Combobox(self.f5, textvariable=tit1banco, values=tbancos, width=12) bank1Cbx.set('') bank1Cbx.pack(side=LEFT) self.tbancpL = Label(self.f5, text='Tipo Cuenta:') self.tbancpL.pack(side=LEFT) tbank1Cbx = Combobox(self.f5, textvariable=tit1tcuenta, values=tbanktype, width=8) tbank1Cbx.set('') tbank1Cbx.pack(side=LEFT) self.tcuentaL = Label(self.f5, text='# Cuenta:') self.tcuentaL.pack(side=LEFT) tcuenta1E = Entry(self.f5, textvariable=tit1numcuenta) tcuenta1E.pack(side=LEFT, fill=X, expand=1) self.lf1.pack(fill=X, ipady=5) #================================ self.f0 = Frame(self.tab2) #Para dejar espacio entre Tab y Label self.f0.pack(fill=X, pady=10) #------------------------------- #--------------------------------------------------------------- self.lf2 = LabelFrame(self.tab2, text="Datos Titular 2") self.f5 = Frame(self.lf2) self.f5.pack(fill=X, pady=5) #------------------------------- self.ccL = Label(self.f5, text='CC:') self.ccL.pack(side=LEFT) cc2E = Entry(self.f5, textvariable=tit2cc) cc2E.pack(side=LEFT, fill=X, expand=1) self.nameL = Label(self.f5, text='Nombres:') self.nameL.pack(side=LEFT) name2E = Entry(self.f5, textvariable=tit2nombres) name2E.pack(side=LEFT, fill=X, expand=1) name2E.bind("<KeyRelease>", caps) self.f6 = Frame(self.lf2) self.f6.pack(fill=X) #------------------------------------------- self.tbancpL = Label(self.f6, text='Banco:') self.tbancpL.pack(side=LEFT) bank2Cbx = Combobox(self.f6, textvariable=tit2banco, values=tbancos, width=12) bank2Cbx.set('') bank2Cbx.pack(side=LEFT) self.tbancpL = Label(self.f6, text='Tipo Cuenta:') self.tbancpL.pack(side=LEFT) tbank2Cbx = Combobox(self.f6, textvariable=tit2tcuenta, values=tbanktype, width=8) tbank2Cbx.set('') tbank2Cbx.pack(side=LEFT) self.tcuentaL = Label(self.f6, text='# Cuenta:') self.tcuentaL.pack(side=LEFT) tcuenta2E = Entry(self.f6, textvariable=tit2numcuenta) tcuenta2E.pack(side=LEFT, fill=X, expand=1) self.lf2.pack(fill=X, ipady=5) #================================ #--------------------------------------------------------------- self.nb.add(self.tab1, text="Personales") self.nb.add(self.tab2, text="Complementarios") self.nb.pack() #=========================== BOTONES =========================== self.btns = Frame(self.wrapper) self.btns.pack() #------------------------------- clean = Button(self.btns, text='Limpiar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=limpiar) clean.pack(side=RIGHT) update = Button(self.btns, text='Actualizar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=actualizar, state=DISABLED) update.pack(side=RIGHT) add = Button(self.btns, text='Agregar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=Agregar) add.pack(side=RIGHT) #========================= ASIDE =========================== self.aside = Frame(self) self.aside.pack(side=LEFT, fill=BOTH, expand=True) self.wrap1 = Frame(self.aside) self.wrap1.pack() self.viewer = Label(self.wrap1, text="LISTA DE PROPIETARIOS") 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, bg='#d8ecf3') scroll.config(command=lb.yview) lb.pack(fill=BOTH) lb.bind("<Double-Button-1>", callback) lb.bind("<Button-3>", popup) #lb.bind('<Escape>', release) self.wrap2 = Frame(self.aside) self.wrap2.pack() self.updateBP = Button(self.wrap2, text='Cargar lista', width=20, bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=cargar_lista) self.updateBP.pack() delete = Button(self.wrap2, text='Borrar', bg='navy', width=20, foreground='white', activebackground='red3', activeforeground='white', command=borrar) delete.pack() edit = Button(self.wrap2, text='Modificar', bg='navy', width=20, foreground='white', activebackground='red3', activeforeground='white', command=modificar) edit.pack() self.wrap3 = Frame(self.aside) self.wrap3.pack() buscador = Label(self.wrap3, text="Buscar por:") buscador.pack(side=LEFT) R1 = Radiobutton(self.wrap3, text="CC", variable=info, value=1) R1.pack(side=LEFT) R2 = Radiobutton(self.wrap3, text="Apellido", variable=info, value=2) R2.pack(side=LEFT) info.set(1) self.wrap4 = Frame(self.aside) self.wrap4.pack() E = Entry(self.wrap4, textvariable=busqueda, width=24) E.pack() E.bind("<KeyRelease>", caps)
class MainFrame(Frame): def __init__(self,parent,stdoutq): Frame.__init__(self,parent) self.parent=parent self.width=750 self.height=450 self.title=ximaexport.__version__ self.stdoutq=stdoutq self.initUI() self.hasdb=False self.hasout=False self.exit=False self.path_frame=self.addPathFrame() self.action_frame=self.addActionFrame() self.message_frame=self.addMessageFrame() self.printStr() self.stateq=Queue.Queue() def centerWindow(self): sw=self.parent.winfo_screenwidth() sh=self.parent.winfo_screenheight() x=(sw-self.width)/2 y=(sh-self.height)/2 self.parent.geometry('%dx%d+%d+%d' \ %(self.width,self.height,x,y)) def initUI(self): self.parent.title(self.title) self.style=Style() #Choose from default, clam, alt, classic self.style.theme_use('alt') self.pack(fill=tk.BOTH,expand=True) self.centerWindow() def printStr(self): while self.stdoutq.qsize() and self.exit==False: try: msg=self.stdoutq.get() self.text.update() self.text.insert(tk.END,msg) self.text.see(tk.END) except Queue.Empty: pass self.after(100,self.printStr) def checkReady(self): if self.hasdb and self.hasout: self.start_button.configure(state=tk.NORMAL) #print('XimaExport Ready.') printch('XimaExport 就绪.') else: self.start_button.configure(state=tk.DISABLED) def addPathFrame(self): frame=Frame(self) frame.pack(fill=tk.X,expand=0,side=tk.TOP,padx=8,pady=5) frame.columnconfigure(1,weight=1) #------------------Database file------------------ label=tk.Label(frame,text=dgbk('ting.sqlite文件:'),\ bg='#bbb') label.grid(row=0,column=0,\ sticky=tk.W,padx=8) self.db_entry=tk.Entry(frame) self.db_entry.grid(row=0,column=1,sticky=tk.W+tk.E,padx=8) self.db_button=tk.Button(frame,text=dgbk('打开'),command=self.openFile) self.db_button.grid(row=0,column=2,padx=8,sticky=tk.E) #--------------------Output dir-------------------- label2=tk.Label(frame,text=dgbk('导出到文件夹:'),\ bg='#bbb') label2.grid(row=2,column=0,\ sticky=tk.W,padx=8) self.out_entry=tk.Entry(frame) self.out_entry.grid(row=2,column=1,sticky=tk.W+tk.E,padx=8) self.out_button=tk.Button(frame,text=dgbk('选择'),command=self.openDir) self.out_button.grid(row=2,column=2,padx=8,sticky=tk.E) def openDir(self): self.out_entry.delete(0,tk.END) dirname=askdirectory() self.out_entry.insert(tk.END,dirname) if len(dirname)>0: #print('Output folder: %s' %dirname) printch('输出到文件夹:') print(' '+dirname) self.hasout=True self.checkReady() def openFile(self): self.db_entry.delete(0,tk.END) ftypes=[('sqlite files','*.sqlite'),('ALL files','*')] filename=askopenfilename(filetypes=ftypes) self.db_entry.insert(tk.END,filename) if len(filename)>0: #print('Database file: %s' %filename) printch('数据文件:') print(' '+filename) self.probeAlbums() def probeAlbums(self): dbfile=self.db_entry.get() try: db=sqlite3.connect(dbfile) df=ximaexport.getData(db) self.albumlist=ximaexport.getAlbumList(df,None) #(id, name) self.albumnames=['All']+[ii[1] for ii in self.albumlist] #names to display self.albummenu['values']=tuple(self.albumnames) self.albummenu.current(0) db.close() self.hasdb=True self.checkReady() except Exception as e: #print('Failed to recoganize the given database file.') printch('无法识别sqlite数据文件.') print(e) def addActionFrame(self): frame=Frame(self,relief=tk.RAISED,borderwidth=1) frame.pack(fill=tk.X,side=tk.TOP,\ expand=0,padx=8,pady=5) #label=tk.Label(frame,text='Actions:',bg='#bbb') #label.grid(row=0,column=0,sticky=tk.W,padx=8) #---------------Action checkbuttons--------------- frame.columnconfigure(0,weight=1) #---------------------2nd row--------------------- subframe=Frame(frame) subframe.grid(row=1,column=0,columnspan=6,sticky=tk.W+tk.E,\ pady=5) #-------------------Album options------------------- albumlabel=tk.Label(subframe,text=dgbk('专辑:'),\ bg='#bbb') albumlabel.pack(side=tk.LEFT, padx=8) self.album=tk.StringVar() self.albumnames=['All',] self.albummenu=Combobox(subframe,textvariable=\ self.album,values=self.albumnames,state='readonly') self.albummenu.current(0) self.albummenu.bind('<<ComboboxSelected>>',self.setAlbum) self.albummenu.pack(side=tk.LEFT,padx=8) #-------------------Quit button------------------- quit_button=tk.Button(subframe,text=dgbk('退出'),\ command=self.quit) quit_button.pack(side=tk.RIGHT,padx=8) #-------------------Stop button------------------- ''' self.stop_button=tk.Button(subframe,text='Stop',\ command=self.stop) self.stop_button.pack(side=tk.RIGHT,padx=8) ''' #-------------------Start button------------------- self.start_button=tk.Button(subframe,text=dgbk('开始'),\ command=self.start,state=tk.DISABLED) self.start_button.pack(side=tk.RIGHT,pady=8) #-------------------Help button------------------- self.help_button=tk.Button(subframe,text=dgbk('帮助'),\ command=self.showHelp) self.help_button.pack(side=tk.RIGHT,padx=8) def setAlbum(self,x): import json self.albummenu.selection_clear() self.album=self.albummenu.get() self.albummenu.set(self.album) if self.album=='All': #print('Work on all albums.') printch('导出所有专辑.') else: #print('Select album: '+self.album) printch('导出所选专辑:') print(' '+self.album) def showHelp(self): helpstr=dgbk('''\n\n 导出喜马拉雅下载音频,并自动按专辑归档、重命名:\n 1. 找到手机/pad中的喜马拉雅数据文件夹:\n (1)苹果用户:链接电脑itunes,在app一栏中找到“喜马拉雅”,单击,右侧会出现“喜马拉雅”的数据文件。选择“iDoc”,并导出到电脑。\n (2)安卓用户:链接电脑后,拷贝出ting文件夹。\n 2. 运行ximaexport-gui.exe。\n 在 “ting.sqlite文件”一栏,选择步骤1中拷贝出的文件夹里的 ting.sqlite. 文件。\n 在 “导出到文件夹”一栏,选择音频存储位置。\n 在 “专辑”下拉菜单,选择要导出的专辑。若全部导出选择“All”。\n 点击“开始”开始处理。 ''') tkMessageBox.showinfo(title='Help', message=helpstr) #print(self.menfolder.get()) def start(self): dbfile=self.db_entry.get() outdir=self.out_entry.get() self.album=self.albummenu.get() self.out_button.configure(state=tk.DISABLED) self.start_button.configure(state=tk.DISABLED) self.help_button.configure(state=tk.DISABLED) self.albummenu.configure(state=tk.DISABLED) self.messagelabel.configure(text=dgbk('信息 (处理中...)')) album=None if self.album=='All' else self.album args=[dbfile,outdir,album,True] self.workthread=WorkThread('work',False,self.stateq) self.workthread.deamon=True self.workthread.args=args self.workthread.start() self.reset() def reset(self): while self.stateq.qsize() and self.exit==False: try: msg=self.stateq.get() if msg=='done': self.db_button.configure(state=tk.NORMAL) self.out_button.configure(state=tk.NORMAL) self.start_button.configure(state=tk.NORMAL) self.help_button.configure(state=tk.NORMAL) self.albummenu.configure(state='readonly') self.messagelabel.configure(text=dgbk('消息')) return except Queue.Empty: pass self.after(100,self.reset) def stop(self): #self.workthread.stop() pass def addMessageFrame(self): frame=Frame(self) frame.pack(fill=tk.BOTH,side=tk.TOP,\ expand=1,padx=8,pady=5) self.messagelabel=tk.Label(frame,text=dgbk('消息'),bg='#bbb') self.messagelabel.pack(side=tk.TOP,fill=tk.X) self.text=tk.Text(frame) self.text.pack(side=tk.TOP,fill=tk.BOTH,expand=1) self.text.height=10 scrollbar=tk.Scrollbar(self.text) scrollbar.pack(side=tk.RIGHT,fill=tk.Y) self.text.config(yscrollcommand=scrollbar.set) scrollbar.config(command=self.text.yview)
def __init__(self, parent, controller): Frame.__init__(self, parent) #VARIABLES GLOBALES global cod, cc, inquilino, codinm, inmueble, nit, owner, rel, vlrenta, duracion global contratos, tcontrato, incremento, gfacturaIni, facturaSgte, fecha, hoy global notas, anexos, destinacion, servicios, conexos, tercero, nombret, fecha global aplicado, cc_aplicado, n_aplicado, inm_aplicado, novedad, n_nombre, n_valor global h, busqueda, clean, update, add #INSTANCIEAS DE LOS WIDGETS global e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, Cbx1, chkb1, chkb2, lb, cedulaE, notas fecha = datetime.date.today() hoy = "%s" % fecha #ESTE NUESTRA LA FECHA EN FORMATO AÑO-MES-DIA (YYYY/MM/DD) #hoy = time.strftime("%d/%m/%y") #ESTO PARA VER FORMATO FECHA EN DIA/MES/AÑO #hoy = time.strftime("%y/%m/%d") h = hoy #VARIABLES lupa = PhotoImage(file='img/lupa.png') schedule = PhotoImage(file='img/calendar.gif') cod = IntVar() cc = StringVar() inquilino = StringVar() codinm = IntVar() inmueble = StringVar() nit = StringVar() owner = StringVar() rel = IntVar() vlrenta = DoubleVar() duracion = IntVar() contratos = ['Vivienda', 'Comercial', 'Mixta'] tcontrato = StringVar() incremento = DoubleVar() gfacturaIni = IntVar() facturaSgte = IntVar() fecha = StringVar() notas = StringVar() anexos = StringVar() destinacion = StringVar() servicios = StringVar() conexos = StringVar() tercero = StringVar() nombret = StringVar() aplicado = IntVar() cc_aplicado = StringVar() n_aplicado = StringVar() inm_aplicado = StringVar() novedad = StringVar() n_nombre = StringVar() n_valor = DoubleVar() #BUSQUEDA = ["Nombre","CC/Nit"] busqueda = StringVar() busqueda.trace("w", lambda name, index, mode: buscar()) dato = StringVar() #WIDGETS #========================= HEADER =========================== self.header = Label(self, text="CONTRATOS", font="bold") self.header.pack(pady=20, side=TOP) #========================== WRAPPER ========================== self.wrapper = Frame(self) self.wrapper.pack(side=LEFT, fill=Y) #================ NOTEBOOK =============> self.nb = Notebook(self.wrapper) #-----------------------> TAB 1 self.tab1 = Frame(self.nb) self.f0 = Frame(self.tab1) #------------------------------------- self.f0.pack(pady=5, fill=X) l1 = Label(self.f0, text='Código:') l1.pack(side=LEFT) e1 = Entry(self.f0, textvariable=cod, width=10) e1.pack(side=LEFT) self.f1 = Frame(self.tab1) #------------------------------------- self.f1.pack(pady=5, fill=X) l2 = Label(self.f1, text='Arrendatario:') l2.pack(side=LEFT, fill=X) e2 = Entry(self.f1, textvariable=cc, width=15) e2.pack(side=LEFT) e2.bind('<Return>', buscarA) b1 = Button(self.f1, image=lupa, command=topArrendatario) b1.image = lupa b1.pack(side=LEFT) e3 = Entry(self.f1, textvariable=inquilino, state=DISABLED) e3.pack(side=LEFT, fill=X, expand=1) self.f2 = Frame(self.tab1) self.f2.pack(pady=5, fill=X) #------------------------------------ l3 = Label(self.f2, text='Inmueble:') l3.pack(side=LEFT) e4 = Entry(self.f2, textvariable=codinm, width=10) e4.pack(side=LEFT) e4.bind('<Return>', buscarR) b2 = Button(self.f2, image=lupa, command=topRelacion) b2.pack(side=LEFT) e5 = Entry(self.f2, textvariable=inmueble, state=DISABLED) e5.pack(side=LEFT, fill=X, expand=1) self.f3 = Frame(self.tab1) self.f3.pack(pady=5, fill=X) #------------------------------------ l4 = Label(self.f3, text='Propietario:') l4.pack(side=LEFT) e6 = Entry(self.f3, width=15, textvariable=nit, state=DISABLED) e6.pack(side=LEFT) e7 = Entry(self.f3, width=5, textvariable=owner, state=DISABLED) e7.pack(side=LEFT, fill=X, expand=1) self.f4 = Frame(self.tab1) self.f4.pack(pady=5, fill=X) #------------------------------------ self.arriendo = Label(self.f4, text='Arriendo $:') self.arriendo.pack(side=LEFT) e8 = Entry(self.f4, textvariable=vlrenta, state=DISABLED, width=20) e8.pack(side=LEFT) self.duracion = Label(self.f4, text='Duración Contrato:') self.duracion.pack(side=LEFT) e9 = Entry(self.f4, textvariable=duracion, width=5) e9.pack(side=LEFT) self.meses = Label(self.f4, text='Meses') self.meses.pack(side=LEFT) self.f5 = Frame(self.tab1) self.f5.pack(pady=5, fill=X) #------------------------------------ self.tcontrato = Label(self.f5, text='Tipo Contrato:') self.tcontrato.pack(side=LEFT) Cbx1 = Combobox(self.f5, textvariable=tcontrato, values=contratos, width=10) Cbx1.set('') Cbx1.pack(side=LEFT) self.incremento = Label(self.f5, text='Incremento:') self.incremento.pack(side=LEFT) e10 = Entry(self.f5, textvariable=incremento, width=5) e10.pack(side=LEFT) chkb1 = Checkbutton(self.f5, text="General factura\n inicial", variable=gfacturaIni) chkb1.pack(side=LEFT) chkb2 = Checkbutton(self.f5, text="Facturar príodo\n siguiente", variable=facturaSgte) chkb2.pack(side=LEFT) self.f6 = Frame(self.tab1) self.f6.pack(pady=5, fill=X) #------------------------------------ btime = Button(self.f6, image=schedule, command=calendario) btime.image = schedule btime.pack(side=RIGHT) etime = Entry(self.f6, textvariable=fecha, width=10) fecha.set(hoy) etime.pack(side=RIGHT) #ltime = Label(self.f6, text=hoy, font="bold", foreground='red') #ltime.pack(side=RIGHT) self.fi = Label(self.f6, text='Fecha Inicio: ') self.fi.pack(side=RIGHT) self.tab1.pack() #-----------------------> TAB 2 self.tab2 = Frame(self.nb) self.tab2.pack() self.f7 = Frame(self.tab2) #------------------------------------- self.f7.pack(fill=X, pady=10) notas = Text(self.f7, height=5) notas.pack(side=LEFT, fill=X, expand=1) self.f8 = Frame(self.tab2) self.f8.pack(pady=5, fill=X) #------------------------------------------- self.destino = Label(self.f8, text='Destinación:') self.destino.pack(side=LEFT) self.destinoE = Entry(self.f8, textvariable=destinacion, width=5) self.destinoE.pack(side=LEFT, fill=X, expand=1) self.f9 = Frame(self.tab2) self.f9.pack(pady=5, fill=X) #------------------------------------------- self.servicios = Label(self.f9, text='Servicios adicionales:') self.servicios.pack(side=LEFT) self.serviciosE = Entry(self.f9, textvariable=servicios, width=5) self.serviciosE.pack(side=LEFT, fill=X, expand=1) self.f10 = Frame(self.tab2) self.f10.pack(pady=5, fill=X) #------------------------------------------- self.conexos = Label(self.f10, text='Conexos:') self.conexos.pack(side=LEFT) self.conexosE = Entry(self.f10, textvariable=conexos, width=5) self.conexosE.pack(side=LEFT, fill=X, expand=1) #-----------------------> TAB 3 self.tab3 = Frame(self.nb) self.tab3.pack() self.f11 = Frame(self.tab3) #------------------------------------- self.f11.pack(fill=X, pady=5) self.cedula = Label(self.f11, text='CC/Nit: ') self.cedula.pack(side=LEFT) cedulaE = Entry(self.f11, textvariable=tercero, width=15) cedulaE.pack(side=LEFT) cedulaE.bind('<Return>', buscarT) b4 = Button(self.f11, image=lupa, command=topTercero) b4.image = lupa b4.pack(side=LEFT) self.f12 = Frame(self.tab3) #------------------------------------- self.f12.pack(fill=X, pady=5) self.tercero = Label(self.f12, text='Nombre: ') self.tercero.pack(side=LEFT) self.terceroE = Entry(self.f12, textvariable=nombret, width=5, state=DISABLED) self.terceroE.pack(side=LEFT, fill=X, expand=1) #-----------------------> TAB 4 self.tab4 = Frame(self.nb) self.tab4.pack() self.f13 = Frame(self.tab4) #------------------------------------- self.f13.pack(fill=X, pady=5) l = Label(self.f13, text='Aplicar a: ') l.pack(side=LEFT) Ch = Checkbutton(self.f13, text="Propietario", variable=aplicado) Ch.pack(side=LEFT) self.f14 = Frame(self.tab4) #------------------------------------- self.f14.pack(fill=X, pady=5) l13 = Label(self.f14, text='CC/Nit: ') l13.pack(side=LEFT) e13 = Entry(self.f14, textvariable=cc_aplicado, width=15) e13.pack(side=LEFT) b13 = Button(self.f14, image=lupa, command=None) b13.image = lupa b13.pack(side=LEFT) e13 = Entry(self.f14, textvariable=n_aplicado, state=DISABLED) e13.pack(side=LEFT, fill=X, expand=1) self.f15 = Frame(self.tab4) self.f15.pack(fill=X, pady=5) #------------------------------------ l14 = Label(self.f15, text='Cod.Inmueble:') l14.pack(side=LEFT) e14 = Entry(self.f15, textvariable=inm_aplicado, width=5, state=DISABLED) e14.pack(side=LEFT, fill=X, expand=1) self.f16 = Frame(self.tab4) self.f16.pack(fill=X, pady=5) #------------------------------------ l16 = Label(self.f16, text='Novedad:') l16.pack(side=LEFT, fill=X) e16 = Entry(self.f16, textvariable=novedad, width=15) e16.pack(side=LEFT) b16 = Button(self.f16, image=lupa, command=None) b16.image = lupa b16.pack(side=LEFT) e16 = Entry(self.f16, textvariable=n_nombre, state=DISABLED) e16.pack(side=LEFT, fill=X, expand=1) self.f17 = Frame(self.tab4) self.f17.pack(fill=X, pady=5) #------------------------------------ l17 = Label(self.f17, text='Vlr Novedad:') l17.pack(side=LEFT, fill=X) e17 = Entry(self.f17, textvariable=n_valor, width=15) e17.pack(side=LEFT) #--------------------------------------------------------------- self.nb.add(self.tab1, text="General") self.nb.add(self.tab2, text="Anexos") self.nb.add(self.tab3, text="Tercero") self.nb.add(self.tab4, text="Gasto fijo") self.nb.pack() self.fBtn = Frame(self.wrapper) self.fBtn.pack() #------------------------------- clean = Button(self.fBtn, text='Limpiar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=limpiar) clean.pack(side=RIGHT) update = Button(self.fBtn, text='Actualizar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=actualizar, state=DISABLED) update.pack(side=RIGHT) add = Button(self.fBtn, text='Agregar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=agregar) 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 CONTRATOS") 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) lb.bind("<Double-Button-1>", callback) self.wrap2 = Frame(self.aside) self.wrap2.pack() show = Button(self.wrap2, text='Cargar lista', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=cargar) show.pack(fill=X) delete = Button(self.wrap2, text='Borrar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=borrar) delete.pack(fill=X) edit = Button(self.wrap2, text='Modificar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=modificar) edit.pack(fill=X) buscador = Label(self.wrap2, text="Buscar por CC:") buscador.pack() E = Entry(self.wrap2, textvariable=busqueda, width=24) E.pack()
class MainFrame(Frame): def __init__(self,parent,stdoutq): Frame.__init__(self,parent) self.parent=parent self.width=700 self.height=400 self.title='Menotexport v1.0' self.stdoutq=stdoutq self.initUI() self.hasdb=False self.hasout=False self.hasaction=False self.exit=False self.path_frame=self.addPathFrame() self.action_frame=self.addActionFrame() self.message_frame=self.addMessageFrame() self.printStr() self.stateq=Queue.Queue() #self.workproc=Pool(1) def centerWindow(self): sw=self.parent.winfo_screenwidth() sh=self.parent.winfo_screenheight() x=(sw-self.width)/2 y=(sh-self.height)/2 self.parent.geometry('%dx%d+%d+%d' \ %(self.width,self.height,x,y)) def initUI(self): self.parent.title(self.title) self.style=Style() #Choose from default, clam, alt, classic self.style.theme_use('alt') self.pack(fill=tk.BOTH,expand=True) self.centerWindow() def printStr(self): while self.stdoutq.qsize() and self.exit==False: try: msg=self.stdoutq.get() self.text.update() self.text.insert(tk.END,'# '+msg) self.text.see(tk.END) except Queue.Empty: pass self.after(100,self.printStr) def checkReady(self): if self.isexport.get()==1 or self.ishighlight.get()==1\ or self.isnote.get()==1: self.hasaction=True else: self.hasaction=False if self.hasdb and self.hasout and self.hasaction: self.start_button.configure(state=tk.NORMAL) print('Menotexport Ready.') else: self.start_button.configure(state=tk.DISABLED) def addPathFrame(self): frame=Frame(self) frame.pack(fill=tk.X,expand=0,side=tk.TOP,padx=8,pady=5) frame.columnconfigure(1,weight=1) #------------------Database file------------------ label=tk.Label(frame,text='Mendeley Data file:',\ bg='#bbb') label.grid(row=0,column=0,\ sticky=tk.W,padx=8) self.db_entry=tk.Entry(frame) self.db_entry.grid(row=0,column=1,sticky=tk.W+tk.E,padx=8) self.db_button=tk.Button(frame,text='Open',command=self.openFile) self.db_button.grid(row=0,column=2,padx=8,sticky=tk.E) hint=''' Default location on Linux: ~/.local/share/data/Mendeley\ Ltd./Mendeley\ Desktop/[email protected] Default location on Windows: C:\Users\Your_name\AppData\Local\Mendeley Ltd\Mendeley Desktop\[email protected]''' hint_label=tk.Label(frame,text=hint,\ justify=tk.LEFT,anchor=tk.NW) hint_label.grid(row=1,column=0,columnspan=3,\ sticky=tk.W,padx=8) #--------------------Output dir-------------------- label2=tk.Label(frame,text='Output folder:',\ bg='#bbb') label2.grid(row=2,column=0,\ sticky=tk.W,padx=8) self.out_entry=tk.Entry(frame) self.out_entry.grid(row=2,column=1,sticky=tk.W+tk.E,padx=8) self.out_button=tk.Button(frame,text='Choose',command=self.openDir) self.out_button.grid(row=2,column=2,padx=8,sticky=tk.E) def openDir(self): self.out_entry.delete(0,tk.END) dirname=askdirectory() self.out_entry.insert(tk.END,dirname) if len(dirname)>0: print('Output folder: %s' %dirname) self.hasout=True self.checkReady() def openFile(self): self.db_entry.delete(0,tk.END) ftypes=[('sqlite files','*.sqlite'),('ALl files','*')] filename=askopenfilename(filetypes=ftypes) self.db_entry.insert(tk.END,filename) if len(filename)>0: print('Database file: %s' %filename) self.probeFolders() def probeFolders(self): dbfile=self.db_entry.get() try: db=sqlite3.connect(dbfile) query=\ '''SELECT Documents.title, DocumentFolders.folderid, Folders.name FROM Documents LEFT JOIN DocumentFolders ON Documents.id=DocumentFolders.documentId LEFT JOIN Folders ON Folders.id=DocumentFolders.folderid ''' ret=db.execute(query) data=ret.fetchall() df=pd.DataFrame(data=data,columns=['title',\ 'folerid','name']) fetchField=lambda x, f: x[f].unique().tolist() folders=fetchField(df,'name') folders.sort() folders.remove(None) self.menfolderlist=['All',]+folders self.foldersmenu['values']=tuple(self.menfolderlist) self.foldersmenu.current(0) db.close() self.hasdb=True self.checkReady() except Exception as e: print('Failed to recoganize the given database file.') print(e) def addActionFrame(self): frame=Frame(self,relief=tk.RAISED,borderwidth=1) frame.pack(fill=tk.X,side=tk.TOP,\ expand=0,padx=8,pady=5) label=tk.Label(frame,text='Actions:',bg='#bbb') label.grid(row=0,column=0,sticky=tk.W,padx=8) #---------------Action checkbuttons--------------- self.isexport=tk.IntVar() self.ishighlight=tk.IntVar() self.isnote=tk.IntVar() self.isseparate=tk.IntVar() self.check_export=tk.Checkbutton(frame,text='Export PDFs',\ variable=self.isexport,command=self.doExport) self.check_highlight=tk.Checkbutton(frame,\ text='Extract highlights',\ variable=self.ishighlight,command=self.doHighlight) self.check_note=tk.Checkbutton(frame,\ text='Extract notes',\ variable=self.isnote,command=self.doNote) self.check_separate=tk.Checkbutton(frame,\ text='Save separately',\ variable=self.isseparate,command=self.doSeparate,\ state=tk.DISABLED) frame.columnconfigure(0,weight=1) self.check_export.grid(row=0,column=1,padx=8,sticky=tk.W) self.check_highlight.grid(row=0,column=2,padx=8,sticky=tk.W) self.check_note.grid(row=0,column=3,padx=8,sticky=tk.W) self.check_separate.grid(row=0,column=4,padx=8,sticky=tk.W) #---------------------2nd row--------------------- subframe=Frame(frame) subframe.grid(row=1,column=0,columnspan=5,sticky=tk.W+tk.E,\ pady=5) #-------------------Folder options------------------- folderlabel=tk.Label(subframe,text='Mendeley folder:',\ bg='#bbb') folderlabel.pack(side=tk.LEFT, padx=8) self.menfolder=tk.StringVar() self.menfolderlist=['All',] self.foldersmenu=Combobox(subframe,textvariable=\ self.menfolder,values=self.menfolderlist,state='readonly') self.foldersmenu.current(0) self.foldersmenu.bind('<<ComboboxSelected>>',self.setfolder) self.foldersmenu.pack(side=tk.LEFT,padx=8) #-------------------Quit button------------------- quit_button=tk.Button(subframe,text='Quit',\ command=self.quit) quit_button.pack(side=tk.RIGHT,padx=8) #-------------------Stop button------------------- ''' self.stop_button=tk.Button(subframe,text='Stop',\ command=self.stop) self.stop_button.pack(side=tk.RIGHT,padx=8) ''' #-------------------Start button------------------- self.start_button=tk.Button(subframe,text='Start',\ command=self.start,state=tk.DISABLED) self.start_button.pack(side=tk.RIGHT,pady=8) #-------------------Help button------------------- self.help_button=tk.Button(subframe,text='Help',\ command=self.showHelp) self.help_button.pack(side=tk.RIGHT,padx=8) def setfolder(self,x): self.foldersmenu.selection_clear() self.menfolder=self.foldersmenu.get() self.foldersmenu.set(self.menfolder) if self.menfolder=='All': print('Work on all folders.') else: print('Select Mendeley folder: '+str(self.menfolder)) def doExport(self): if self.isexport.get()==1: print('Export annotated PDFs.') else: print('Dont export annotated PDFs.') self.checkReady() def doHighlight(self): if self.ishighlight.get()==1: print('Extract highlighted texts.') self.check_separate.configure(state=tk.NORMAL) else: print('Dont extract highlighted texts.') if self.isnote.get()==0: self.check_separate.configure(state=tk.DISABLED) self.checkReady() def doNote(self): if self.isnote.get()==1: print('Extract notes.') self.check_separate.configure(state=tk.NORMAL) else: print('Dont extract notes.') self.check_separate.state=tk.DISABLED if self.ishighlight.get()==0: self.check_separate.configure(state=tk.DISABLED) self.checkReady() def doSeparate(self): if self.isseparate.get()==1: print('Save annotations separately.') else: print('Save all annotations to single file.') def showHelp(self): helpstr=''' Menotexport v1.0\n\n - Export PDFs: Bulk export PDFs with annotations to <output folder>.\n - Extract highlights: Extract highlighted texts and output to a txt file in <output folder>.\n - Extract highlights: Extract notes and output to a txt file in <output folder>.\n - Save separately: If on, save each PDF's annotations to a separate txt.\n - See README.md for more info.\n ''' tkMessageBox.showinfo(title='Help', message=helpstr) print(self.menfolder.get()) def start(self): dbfile=self.db_entry.get() outdir=self.out_entry.get() action=[] if self.isexport.get()==1: action.append('e') if self.ishighlight.get()==1: action.append('m') if self.isnote.get()==1: action.append('n') if self.isseparate.get()==1: separate=True else: separate=False if 'e' in action or 'm' in action or 'n' in action: self.db_button.configure(state=tk.DISABLED) self.out_button.configure(state=tk.DISABLED) self.start_button.configure(state=tk.DISABLED) self.help_button.configure(state=tk.DISABLED) self.foldersmenu.configure(state=tk.DISABLED) self.check_export.configure(state=tk.DISABLED) self.check_highlight.configure(state=tk.DISABLED) self.check_note.configure(state=tk.DISABLED) self.check_separate.configure(state=tk.DISABLED) self.messagelabel.configure(text='Message (working...)') folder=None if self.menfolder=='All' else [self.menfolder,] args=[dbfile,outdir,action,folder,True,True,separate,True] self.workthread=WorkThread('work',False,self.stateq) self.workthread.deamon=True self.workthread.args=args self.workthread.start() self.reset() ''' self.workproc.apply_async(menotexport.main,args,\ callback=self.reset) self.workproc.join() ''' def reset(self): while self.stateq.qsize() and self.exit==False: try: msg=self.stateq.get() if msg=='done': self.db_button.configure(state=tk.NORMAL) self.out_button.configure(state=tk.NORMAL) self.start_button.configure(state=tk.NORMAL) self.help_button.configure(state=tk.NORMAL) self.foldersmenu.configure(state='readonly') self.check_export.configure(state=tk.NORMAL) self.check_highlight.configure(state=tk.NORMAL) self.check_note.configure(state=tk.NORMAL) self.check_separate.configure(state=tk.NORMAL) self.messagelabel.configure(text='Message') return except Queue.Empty: pass self.after(100,self.reset) def stop(self): #self.workthread.stop() pass def addMessageFrame(self): frame=Frame(self) frame.pack(fill=tk.BOTH,side=tk.TOP,\ expand=1,padx=8,pady=5) self.messagelabel=tk.Label(frame,text='Message',bg='#bbb') self.messagelabel.pack(side=tk.TOP,fill=tk.X) self.text=tk.Text(frame) self.text.pack(side=tk.TOP,fill=tk.BOTH,expand=1) self.text.height=10 scrollbar=tk.Scrollbar(self.text) scrollbar.pack(side=tk.RIGHT,fill=tk.Y) self.text.config(yscrollcommand=scrollbar.set) scrollbar.config(command=self.text.yview)
class MainFrame(Frame): def __init__(self, parent, stdoutq): Frame.__init__(self, parent) self.parent = parent self.width = 850 self.height = 650 self.title = menotexport.__version__ self.stdoutq = stdoutq self.initUI() self.hasdb = False self.hasout = False self.hasaction = False self.exit = False self.path_frame = self.addPathFrame() self.action_frame = self.addActionFrame() self.message_frame = self.addMessageFrame() self.printStr() self.stateq = Queue.Queue() #self.workproc=Pool(1) def centerWindow(self): sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() x = (sw - self.width) / 2 y = (sh - self.height) / 2 self.parent.geometry('%dx%d+%d+%d' \ %(self.width,self.height,x,y)) def initUI(self): self.parent.title(self.title) self.style = Style() #Choose from default, clam, alt, classic self.style.theme_use('alt') self.pack(fill=tk.BOTH, expand=True) self.centerWindow() def printStr(self): while self.stdoutq.qsize() and self.exit == False: try: msg = self.stdoutq.get() self.text.update() self.text.insert(tk.END, msg) self.text.see(tk.END) except Queue.Empty: pass self.after(100, self.printStr) def checkReady(self): if self.isexport.get()==1 or self.ishighlight.get()==1\ or self.isnote.get()==1 or self.isbib.get()==1: self.hasaction = True else: self.hasaction = False if self.hasdb and self.hasout and self.hasaction: self.start_button.configure(state=tk.NORMAL) print('# <Menotexport>: Menotexport Ready.') else: self.start_button.configure(state=tk.DISABLED) def addPathFrame(self): frame = Frame(self) frame.pack(fill=tk.X, expand=0, side=tk.TOP, padx=8, pady=5) frame.columnconfigure(1, weight=1) #------------------Database file------------------ label=tk.Label(frame,text='Mendeley Data file:',\ bg='#bbb') label.grid(row=0,column=0,\ sticky=tk.W,padx=8) self.db_entry = tk.Entry(frame) self.db_entry.grid(row=0, column=1, sticky=tk.W + tk.E, padx=8) self.db_button = tk.Button(frame, text='Open', command=self.openFile) self.db_button.grid(row=0, column=2, padx=8, sticky=tk.E) hint = ''' Default location on Linux: ~/.local/share/data/Mendeley\ Ltd./Mendeley\ Desktop/[email protected] Default location on Windows: C:\Users\Your_name\AppData\Local\Mendeley Ltd\Mendeley Desktop\[email protected]''' hint_label=tk.Label(frame,text=hint,\ justify=tk.LEFT,anchor=tk.NW) hint_label.grid(row=1,column=0,columnspan=3,\ sticky=tk.W,padx=8) #--------------------Output dir-------------------- label2=tk.Label(frame,text='Output folder:',\ bg='#bbb') label2.grid(row=2,column=0,\ sticky=tk.W,padx=8) self.out_entry = tk.Entry(frame) self.out_entry.grid(row=2, column=1, sticky=tk.W + tk.E, padx=8) self.out_button = tk.Button(frame, text='Choose', command=self.openDir) self.out_button.grid(row=2, column=2, padx=8, sticky=tk.E) def openDir(self): self.out_entry.delete(0, tk.END) dirname = askdirectory() self.out_entry.insert(tk.END, dirname) if len(dirname) > 0: print('# <Menotexport>: Output folder: %s' % dirname) self.hasout = True self.checkReady() def openFile(self): self.db_entry.delete(0, tk.END) ftypes = [('sqlite files', '*.sqlite'), ('ALL files', '*')] initialdir = '~/.local/share/data/Mendeley Ltd./Mendeley Desktop' initialdir = os.path.expanduser(initialdir) if os.path.isdir(initialdir): filename = askopenfilename(filetypes=ftypes, initialdir=initialdir) else: filename = askopenfilename(filetypes=ftypes) self.db_entry.insert(tk.END, filename) if len(filename) > 0: print('# <Menotexport>: Database file: %s' % filename) self.probeFolders() def probeFolders(self): dbfile = self.db_entry.get() try: db = sqlite3.connect(dbfile) self.menfolderlist = menotexport.getFolderList(db, None) #(id, name) self.foldernames = ['All'] + [ii[1] for ii in self.menfolderlist ] #names to display self.foldersmenu['values'] = tuple(self.foldernames) self.foldersmenu.current(0) db.close() self.hasdb = True self.checkReady() except Exception as e: print( '# <Menotexport>: Failed to recoganize the given database file.' ) print(e) def addActionFrame(self): frame = Frame(self, relief=tk.RAISED, borderwidth=1) frame.pack(fill=tk.X,side=tk.TOP,\ expand=0,padx=8,pady=5) label = tk.Label(frame, text='Actions:', bg='#bbb') label.grid(row=0, column=0, sticky=tk.W, padx=8) #---------------Action checkbuttons--------------- self.isexport = tk.IntVar() self.ishighlight = tk.IntVar() self.isnote = tk.IntVar() self.isbib = tk.IntVar() self.isris = tk.IntVar() self.isseparate = tk.IntVar() self.iszotero = tk.IntVar() self.iscustomtemp = tk.IntVar() self.check_export=tk.Checkbutton(frame,text='Export PDFs',\ variable=self.isexport,command=self.doExport) self.check_highlight=tk.Checkbutton(frame,\ text='Extract highlights',\ variable=self.ishighlight,command=self.doHighlight) self.check_note=tk.Checkbutton(frame,\ text='Extract notes',\ variable=self.isnote,command=self.doNote) self.check_bib=tk.Checkbutton(frame,\ text='Export .bib',\ variable=self.isbib,command=self.doBib) self.check_ris=tk.Checkbutton(frame,\ text='Export .ris',\ variable=self.isris,command=self.doRis) self.check_separate=tk.Checkbutton(frame,\ text='Save separately',\ variable=self.isseparate,command=self.doSeparate,\ state=tk.DISABLED) self.check_iszotero=tk.Checkbutton(frame,\ text='For import to Zotero',\ variable=self.iszotero,command=self.doIszotero,\ state=tk.DISABLED) self.check_custom_template=tk.Checkbutton(frame,\ text='Use custom template (experimental)',\ variable=self.iscustomtemp,command=self.doCustomTemp,\ state=tk.DISABLED) frame.columnconfigure(0, weight=1) self.check_export.grid(row=1, column=1, padx=8, sticky=tk.W) self.check_highlight.grid(row=1, column=2, padx=8, sticky=tk.W) self.check_note.grid(row=1, column=3, padx=8, sticky=tk.W) self.check_bib.grid(row=2, column=1, padx=8, sticky=tk.W) self.check_ris.grid(row=2, column=2, padx=8, sticky=tk.W) self.check_separate.grid(row=2, column=3, padx=8, sticky=tk.W) self.check_iszotero.grid(row=3, column=1, padx=8, sticky=tk.W) self.check_custom_template.grid(row=3, column=2, padx=8, sticky=tk.W) #---------------------2nd row--------------------- subframe = Frame(frame) subframe.grid(row=4,column=0,columnspan=6,sticky=tk.W+tk.E,\ pady=5) #-------------------Folder options------------------- folderlabel=tk.Label(subframe,text='Mendeley folder:',\ bg='#bbb') folderlabel.pack(side=tk.LEFT, padx=8) self.menfolder = tk.StringVar() self.menfolderlist = [ 'All', ] self.foldersmenu=Combobox(subframe,textvariable=\ self.menfolder,values=self.menfolderlist,state='readonly') self.foldersmenu.current(0) self.foldersmenu.bind('<<ComboboxSelected>>', self.setfolder) self.foldersmenu.pack(side=tk.LEFT, padx=8) #-------------------Quit button------------------- quit_button=tk.Button(subframe,text='Quit',\ command=self.quit) quit_button.pack(side=tk.RIGHT, padx=8) #-------------------Stop button------------------- ''' self.stop_button=tk.Button(subframe,text='Stop',\ command=self.stop) self.stop_button.pack(side=tk.RIGHT,padx=8) ''' #-------------------Start button------------------- self.start_button=tk.Button(subframe,text='Start',\ command=self.start,state=tk.DISABLED) self.start_button.pack(side=tk.RIGHT, pady=8) #-------------------Help button------------------- self.help_button=tk.Button(subframe,text='Help',\ command=self.showHelp) self.help_button.pack(side=tk.RIGHT, padx=8) def setfolder(self, x): self.foldersmenu.selection_clear() self.menfolder = self.foldersmenu.get() self.foldersmenu.set(self.menfolder) if self.menfolder == 'All': print('# <Menotexport>: Work on all folders.') else: print('# <Menotexport>: Select Mendeley folder: ' + str(self.menfolder)) def doExport(self): if self.isexport.get() == 1: print('# <Menotexport>: Export annotated PDFs.') else: print('# <Menotexport>: Dont export annotated PDFs.') self.checkReady() def doHighlight(self): if self.ishighlight.get() == 1: print('# <Menotexport>: Extract highlighted texts.') self.check_separate.configure(state=tk.NORMAL) self.check_custom_template.configure(state=tk.NORMAL) else: print('# <Menotexport>: Dont extract highlighted texts.') if self.isnote.get() == 0: self.check_separate.configure(state=tk.DISABLED) self.check_custom_template.configure(state=tk.DISABLED) self.checkReady() def doNote(self): if self.isnote.get() == 1: print('# <Menotexport>: Extract notes.') self.check_separate.configure(state=tk.NORMAL) self.check_custom_template.configure(state=tk.NORMAL) else: print('# <Menotexport>: Dont extract notes.') self.check_separate.state = tk.DISABLED if self.ishighlight.get() == 0: self.check_separate.configure(state=tk.DISABLED) self.check_custom_template.configure(state=tk.DISABLED) self.checkReady() self.checkReady() def doBib(self): if self.isbib.get() == 1: print('# <Menotexport>: Export to .bib file.') self.check_iszotero.configure(state=tk.NORMAL) else: print('# <Menotexport>: Dont export .bib file.') if self.isris.get() == 0: self.check_iszotero.configure(state=tk.DISABLED) self.checkReady() def doRis(self): if self.isris.get() == 1: print('# <Menotexport>: Export to .ris file.') self.check_iszotero.configure(state=tk.NORMAL) else: print('# <Menotexport>: Dont export .ris file.') if self.isbib.get() == 0: self.check_iszotero.configure(state=tk.DISABLED) self.checkReady() def doSeparate(self): if self.isseparate.get() == 1: print('# <Menotexport>: Save annotations separately.') else: print('# <Menotexport>: Save all annotations to single file.') def doIszotero(self): if self.iszotero.get() == 1: print( '# <Menotexport>: Save .bib/.ris file in Zotero preferred format.' ) else: print('# <Menotexport>: Save .bib/.ris file to default format.') def doCustomTemp(self): if self.iscustomtemp.get() == 1: print( '# <Menotexport>: Use custom template for exported annotations.' ) else: print( '# <Menotexport>: Use default template for exported annotations.' ) def showHelp(self): helpstr = ''' %s\n\n - Export PDFs: Bulk export PDFs.\n - Extract highlights: Extract highlighted texts and output to txt files.\n - Extract notes: Extract notes and output to txt files.\n - Export .bib: Export meta-data and annotations to .bib files.\n - Export .ris: Export meta-data and annotations to .ris files.\n - For import to Zotero: Exported .bib and/or .ris files have suitable format to import to Zotero.\n - Save separately: If on, save each PDF's annotations to a separate txt.\n - Use custom annotation template: Use a custom template to format the exported annotations. See annotation_template.py for details. - See README.md for more info.\n ''' % self.title tkMessageBox.showinfo(title='Help', message=helpstr) #print(self.menfolder.get()) def start(self): dbfile = self.db_entry.get() outdir = self.out_entry.get() self.menfolder = self.foldersmenu.get() # get (folderid, folder) for folder for ii in self.menfolderlist: if ii[1] == self.menfolder: folder_sel = [ii[0], ii[1].split('/')[-1]] action = [] if self.isexport.get() == 1: action.append('p') if self.ishighlight.get() == 1: action.append('m') if self.isnote.get() == 1: action.append('n') if self.isbib.get() == 1: action.append('b') if self.isris.get() == 1: action.append('r') if self.isseparate.get() == 1: separate = True else: separate = False if self.iszotero.get() == 1: iszotero = True else: iszotero = False if self.iscustomtemp.get() == 1: action.append('t') if 'p' in action or 'm' in action or 'n' in action or 'b' in action or 'r' in action: self.db_button.configure(state=tk.DISABLED) self.out_button.configure(state=tk.DISABLED) self.start_button.configure(state=tk.DISABLED) self.help_button.configure(state=tk.DISABLED) self.foldersmenu.configure(state=tk.DISABLED) self.check_export.configure(state=tk.DISABLED) self.check_highlight.configure(state=tk.DISABLED) self.check_note.configure(state=tk.DISABLED) self.check_bib.configure(state=tk.DISABLED) self.check_ris.configure(state=tk.DISABLED) self.check_separate.configure(state=tk.DISABLED) self.check_iszotero.configure(state=tk.DISABLED) self.check_custom_template.configure(state=tk.DISABLED) self.messagelabel.configure(text='Message (working...)') folder = None if self.menfolder == 'All' else folder_sel args = [dbfile, outdir, action, folder, separate, iszotero, True] self.workthread = WorkThread('work', False, self.stateq) self.workthread.deamon = True self.workthread.args = args self.workthread.start() self.reset() ''' self.workproc.apply_async(menotexport.main,args,\ callback=self.reset) self.workproc.join() ''' def reset(self): while self.stateq.qsize() and self.exit == False: try: msg = self.stateq.get() if msg == 'done': self.db_button.configure(state=tk.NORMAL) self.out_button.configure(state=tk.NORMAL) self.start_button.configure(state=tk.NORMAL) self.help_button.configure(state=tk.NORMAL) self.foldersmenu.configure(state='readonly') self.check_export.configure(state=tk.NORMAL) self.check_highlight.configure(state=tk.NORMAL) self.check_note.configure(state=tk.NORMAL) self.check_bib.configure(state=tk.NORMAL) self.check_separate.configure(state=tk.NORMAL) self.check_iszotero.configure(state=tk.NORMAL) self.check_custom_template.configure(state=tk.NORMAL) self.messagelabel.configure(text='Message') return except Queue.Empty: pass self.after(100, self.reset) def stop(self): #self.workthread.stop() pass def addMessageFrame(self): frame = Frame(self) frame.pack(fill=tk.BOTH,side=tk.TOP,\ expand=1,padx=8,pady=5) self.messagelabel = tk.Label(frame, text='Message', bg='#bbb') self.messagelabel.pack(side=tk.TOP, fill=tk.X) self.text = tk.Text(frame) self.text.pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.text.height = 10 scrollbar = tk.Scrollbar(self.text) scrollbar.pack(side=tk.RIGHT, fill=tk.Y) self.text.config(yscrollcommand=scrollbar.set) scrollbar.config(command=self.text.yview)
class DirList(object): def __init__(self, initdir=None): self.top = Tk() self.top.geometry('850x560+200+180') self.top.wm_title("SLA2.4") #Label(self.top, text='').pack() fm_title = Frame(self.top) self.label_title = Label(fm_title, text='Site Log Analyzer v2.4',\ font = ('Helvetica', 16, 'bold'), fg= my_color_blue_office) self.label_title.pack() fm_title.pack() self.top.iconbitmap(icon_path) fm_directory = Frame(self.top) self.entry_label = Label(fm_directory, text="Search in: ") self.cwd = StringVar(self.top) self.entry_dir = Entry(fm_directory, width=80, textvariable=self.cwd) self.entry_dir.bind('<Return>', self.enter_directory) self.button_dir = Button(fm_directory, text='List directory', \ command=self.choose_dir, activeforeground='white', activebackground='orange') self.button_dir.pack(side=RIGHT) self.entry_label.pack(side=LEFT) self.entry_dir.pack(side=LEFT) fm_directory.pack() fm_listbox = Frame(self.top) self.listbox_dirsby = Scrollbar(fm_listbox) self.listbox_dirsby.pack(side=RIGHT, fill=Y) self.listbox_dirsbx = Scrollbar(fm_listbox, orient=HORIZONTAL) self.listbox_dirsbx.pack(side=BOTTOM, fill=X) self.list_v = StringVar() #selectmode=EXTENDED,BROWSE,MULTIPLE,SINGLE #exportselection is used to enable "ctrl+c" to copy the content selected #in the listbox into the windows clipboard when =1 self.listbox_dirs = Listbox(fm_listbox, height=10, width=10, selectmode=EXTENDED,\ exportselection=1,listvariable=self.list_v) #2017.8.23 BUG: 滚动轴导致程序挂掉,原因可能是由于多线程子线程更新GUI界面 #产生内部错误导致 #2017.10.25,fixthis BUG, 要想thread-safe,使用python3,或者使用mttkinter模块! self.listbox_dirs.bind('<Double-1>', self.setDirAndGo) self.listbox_dirs.bind('<1>', lambda event: self.listbox_click(event)) self.listbox_dirs.bind('<ButtonRelease-1>', lambda event: self.listbox_click_release(event)) self.listbox_dirs.bind('<Return>', self.setDirAndGo) #self.listbox_dirs.bind('<Return>', self.start_thread_analyse) #self.listbox_dirs.bind('<3>', self.listbox_Rclick) self.listbox_dirs['yscrollcommand'] = self.listbox_dirsby.set self.listbox_dirsby.config(command=self.listbox_dirs.yview) self.listbox_dirs['xscrollcommand'] = self.listbox_dirsbx.set self.listbox_dirsbx.config(command=self.listbox_dirs.xview) self.listbox_dirs.pack(expand=YES, fill=BOTH) self.listbox_dirs.focus_set() fm_listbox.pack(expand=YES, fill=BOTH) fm_search = Frame(self.top) label_search = Label(fm_search, text="Search for: ") self.keyword = StringVar(self.top) self.keyword.set(PREDIFINED_KEYWORD) self.combo_search = Combobox(fm_search, width=30, textvariable=self.keyword) self.combo_search.bind('<KeyPress-Escape>', self.get_default_keywords) s = "keywords.csv is the predefined keywords data\nyou can input a specific keyword\nclick 'esc' for default" tooltip.ToolTip(self.combo_search, msg=None, msgFunc=lambda: s, follow=True, delay=0.2) #read the first 10 custom keywords in history file 'custom_keyword.txt' self.ck_list = [] self.ck_list = get_custom_keyword() if self.ck_list: value = self.ck_list[-10:] value.reverse() self.combo_search['values'] = value self.ck_list = [] else: self.ck_list = [] label_search.pack(side=LEFT) self.combo_search.pack(side=LEFT) #feature files type filtering Label(fm_search, text="in files of: ").pack(side=LEFT) self.v_files_types = StringVar() self.v_files_types.set('.*\.txt;.*\.out') self.entry_files_type = Entry(fm_search, width=30, textvariable=self.v_files_types) self.entry_files_type.pack(side=LEFT) self.entry_files_type.bind('<KeyPress-Escape>', self.get_default_files_filters) fs = "Refer to Python Regular Expression\n '.*'means any characters\n use ';' to seperate" tooltip.ToolTip(self.entry_files_type, msg=None, msgFunc=lambda: fs, follow=True, delay=0.2) #terminate button self.stop_b = Button(fm_search, text="Stop", command=self.terminate_threads) self.stop_b.pack(side=RIGHT) #search start button self.search_b = Button(fm_search, text="Auto analyse", command=self.start_thread_analyse, activeforeground\ ='white', activebackground='orange',bg = 'white', relief='raised', width=10) self.search_b.pack(side=RIGHT) fm_search.pack() tooltip.ToolTip( self.search_b, msg=None, msgFunc=\ lambda : 'To unpack, decode and search the selected files or directories', \ follow=True, delay=0.2) self.pro_fm = Frame(self.top) self.ptext = StringVar() self.ptext.set("") self.pro_label = Label(self.pro_fm, textvariable=self.ptext, justify='left') self.pro_label.grid(row=0, column=0) #.pack(side=LEFT) self.pro_fm.pack(side=LEFT) self.current_path_item_number = 0 self.current_path_item_selected_number = 0 ############# menu init ################################ menubar = Menu(self.top) #keyword update menu menubar.add_command(label='keywords', command=self.menu_keywords) #filter_menu self.search_filter = ['none'] filter_menu = Menu(menubar, tearoff=0) #all the module used for filter keyword belonging to that module out #['Telecom', 'Platform', 'OAM']) self.lf = list(set(zip(*PRE_KEYWORD_LIST)[1])) self.d_filter = {} for i in range(len(self.lf)): self.d_filter[self.lf[i]] = StringVar() #filter_menu filter_menu.add_command(label="select all", command=self.menu_selectall) filter_menu.add_separator() for item, v in self.d_filter.items(): #filter_menu.add_command(label = item,command=self.menu_hello) filter_menu.add_checkbutton(label = item,command=self.menu_filter,\ variable=v) #将menubar 的menu 属性指定为filemenu,即filemenu 为menubar 的下拉菜单 menubar.add_cascade(label='Filters', menu=filter_menu) #decode menue menubar.add_command(label='RTTP', command=self.menu_decode_log) #decode menue menubar.add_command(label='FTP', command=self.menu_start_monitor_ftp_download) #about menue about_menu = Menu(menubar, tearoff=0) about_menu.add_command(label='About', command=self.menu_about) about_menu.add_separator() about_menu.add_command(label='How To Use', command=self.menu_howto) menubar.add_cascade(label='About', menu=about_menu) self.top['menu'] = menubar ##popup menu self.popup_menu = Menu(self.top, tearoff=0) self.popup_menu.add_command(label='Open', command=self.cm_file_open) self.popup_menu.add_separator() self.popup_menu.add_command(label='Open folder', command=self.cm_folder_open) self.popup_menu.add_separator() self.popup_menu.add_command(label='Unpack', command=self.cm_start_unpack) self.popup_menu.add_separator() self.popup_menu.add_command(label='Search', command=self.cm_start_file_search) self.popup_menu.add_separator() self.popup_menu.add_command(label='Decode', command=self.cm_start_bsc_decode) self.popup_menu.add_separator() self.popup_menu.add_command(label='Lines Repetition', command=self.cm_start_logline_count) #popup_menu.entryconfig("Open", state="disable") ############# menu init ################################ #MAC OS GUI if (self.top.tk.call('tk', 'windowingsystem') == 'aqua'): self.listbox_dirs.bind( '<3>', lambda event: self.listbox_Rclick(event, self.popup_menu)) self.listbox_dirs.bind( '<Control-1>', lambda event: self.listbox_Rclick(event, self.popup_menu)) #Win32 else: #右击可以弹出菜单,用lambda的写法可以传递参数 self.listbox_dirs.bind( '<3>', lambda event: self.listbox_Rclick(event, self.popup_menu)) if initdir: #self.cwd.set(os.getcwd()) #desktop is default path self.cwd.set(DESKTOP_PATH) self.menu_selectall() self.enter_directory() self.dnd_enable(self.listbox_dirs) ############# menu function ############### def menu_keywords(self): kdir = os.path.join(WORKING_PATH, PREDIFINED_KEYWORD) cmd = [kdir] try: multi_operates.call_proc(cmd) except Exception as e: print "DEBUG call_proc error=", e self.listbox_dirs.config(selectbackground='red') def menu_decode_log(self): decode_window = RTTP_decoder.rttp(self.top) def monitor_ftp_download(self, ftp_top): global SEARCH_RESULT_LIST global NO_KEYWORD_FIND print("DEBUG monitor_ftp_download start") while 1: if not ftp_top.running: break else: if my_ftp.AUTOANA_ENABLE: #here should add mutext to dirlist or ptext or something #which maybe used by auto_analyse s = "Now detecting ftp downloaded files..." self.ptext.set(s) print("DEBUG wating to get file_path from FTP QUEUE..") file_path = my_ftp.FTP_FILE_QUE.get() #here also can use ftp.MONITOR_THREADS to make the stop #exit this circle if 'ftp quit' in file_path: break #display on the dirlist self.listbox_dirs.delete(0, END) current_dir = os.curdir.encode('gb2312').decode('utf-8') self.listbox_dirs.insert(END, current_dir) s = file_path.encode('gb2312').decode('utf-8') self.listbox_dirs.insert(END, s) #start search self.auto_analyse([file_path], PRE_KEYWORD_LIST) self.start_thread_progressbar() #record result in the file_path as a format of xx.res result_file = '' if os.path.isdir(file_path): result_file = os.path.join(file_path, 'search_result.txt') else: result_file = os.path.join(\ os.path.dirname(file_path), 'search_result.txt') record_result(SEARCH_RESULT_LIST, result_file) #send email if not NO_KEYWORD_FIND: print("DEBUG keyword find result=", multi_operates.search_result) print("Result has been saved in %s" % result_file) NO_KEYWORD_FIND = True else: print("DEBUG no keyword found") else: pass print("'mail monitor quit'") s = "Detecting stopped" self.ptext.set(s) return ####################monitor_ftp_download()####################### def menu_start_monitor_ftp_download(self): global FTP_TOP global l_threads print "hello this is ftp function" #how to singleton? ftp_top = my_ftp.My_Ftp(self.top) FTP_TOP = ftp_top if FTP_TOP: t = threading.Thread(target=self.monitor_ftp_download, args=(ftp_top, )) l_threads.append(t) t.start() print("monitor ftp thread:", t) else: print("DEBUG FTP_TOP none error") ##########menu_start_monitor_ftp_download()############# def menu_about(self): s = askyesnocancel(title='about', message = "SLA - Site Log Analyser v2.4, any idea, just feedback to us:",\ detail="[email protected]\[email protected]\[email protected]\[email protected]\[email protected]\[email protected]\n\ 2017 Qingdao GSM-A SLA Team" ,icon=INFO) ''' d = Dialog(None,title='about',text="SLA - Site Log Analyser v2.1\ \nAny idea, just feedback to us:\[email protected]\ \[email protected]\[email protected]",bitmap=DIALOG_ICON,default=0,strings=('OK','no')) d.num ''' def menu_howto(self): s = askyesno( title='How To', message="把要分析的trace文件夹直接拖放到显示目录框中,点击'Auto analyse'\n简单吧?\n") if s: print s else: print "no s=", s def filter_keyword(self): ''' filter the keyword list according to d_filter ''' global PRE_KEYWORD_LIST pre_k = PRE_KEYWORD_LIST filtered_keyword_list = copy.deepcopy(pre_k) k = self.keyword.get() if k == PREDIFINED_KEYWORD: ln = len(pre_k) for i in xrange(ln): if pre_k[i][1] in self.d_filter: if self.d_filter[pre_k[i][1]].get() == '0': filtered_keyword_list.remove(pre_k[i]) #print 'DEBUG filtered keyword_list=',filtered_keyword_list else: filtered_keyword_list[0][0] = k filtered_keyword_list[0][5] = "customized keyword" return filtered_keyword_list[:1] return filtered_keyword_list def menu_filter(self): self.search_filter = [] for fi, va in self.d_filter.items(): if va.get() == '1': self.search_filter.append(fi) s = "{0} of {1} items selected. Keyword filters: {2}".\ format(self.current_path_item_selected_number, self.current_path_item_number,self.search_filter) self.ptext.set(s) self.keyword.set(PREDIFINED_KEYWORD) def menu_selectall(self): all_true_flag = True for i in range(len(self.lf)): #print self.d_filter[self.lf[i]].get() if self.d_filter[self.lf[i]].get() == '0': all_true_flag = False if all_true_flag and self.d_filter[self.lf[0]].get() != '': for i in range(len(self.lf)): self.d_filter[self.lf[i]].set(False) self.search_filter = ['none'] else: self.search_filter = [] for i in range(len(self.lf)): self.d_filter[self.lf[i]].set(True) self.search_filter.append(self.lf[i]) s = "{0} items. Keyword filters: {1}".format( self.current_path_item_number, self.search_filter) self.ptext.set(s) self.keyword.set(PREDIFINED_KEYWORD) #print "filter:{0},value:{1}".format(self.lf[i],self.d_filter[self.lf[i]].get()) def menu_popup(self, event, m): #The curselection return a tuple of the selected indexs sel = self.listbox_dirs.curselection() if len(sel) == 1: check = self.listbox_dirs.get(self.listbox_dirs.curselection()) m.post(event.x_root, event.y_root) else: pass #by nearest(click y point)to locate the line in the listbox #print "DEBUG-",self.listbox_dirs.nearest(event.y) #line_index = self.listbox_dirs.nearest(event.y) #self.listbox_dirs.selection_set(line_index,line_index) #self.listbox_dirs.config(selectbackground=my_color_blue) #m.post(event.x_root,event.y_root) def cm_file_open(self, ev=None): #print "DEBUG print list_var=",self.list_v.get() print "cm_file_open called" select_file_list = [] index_list = self.listbox_dirs.curselection() for idx in index_list: select_file_list.append(self.listbox_dirs.get(idx)) print(select_file_list) for file in select_file_list: file = file.encode('gb2312') cmd = [file] try: multi_operates.call_proc(cmd) except Exception as e: print "DEBUG call_proc error=", e self.listbox_dirs.config(selectbackground='red') ############################## ###########context menu functions##################### def cm_start_file_search(self, ev=None): global l_threads print("Start_file_search") #There is a problem when no filter a crash will occur after do_search if self.search_filter[0] == 'none' and self.keyword.get( ) == PREDIFINED_KEYWORD: showwarning(title='No filters', message="No keywords to search!") #self._Thread__stop() return select_path_list = [] index_list = self.listbox_dirs.curselection() for idx in index_list: select_path_list.append(self.listbox_dirs.get(idx)) if len(select_path_list) > 0: filtered_keyword_list = self.filter_keyword() t = threading.Thread(target=self.file_search, \ args=(select_path_list, filtered_keyword_list)) l_threads.append(t) t.start() self.start_thread_progressbar() else: print("DEBUG no item seleted") def file_search(self, path_list, keyword_list): global l_threads s = "Please wait..." self.search_b.config(text=s, bg='orange', relief='sunken', state='disabled') self.popup_menu.entryconfig("Search", state="disable") #use multi_operates: multi_operates.PROGRESS_QUE.put("Search start") files_types_list = self.v_files_types.get().strip().split(';') search_result,searched_number = \ multi_operates.files_search(path_list, keyword_list, files_types_list) multi_operates.PROGRESS_QUE.put( "Search finished, generating results...") self.show_result(keyword_list, search_result) s = 'All done, %d files, %d keywords searched in %s'\ %(searched_number, len(keyword_list), multi_operates.used_time()) multi_operates.PROGRESS_QUE.put(s) self.search_b.config(text="Auto analyse", bg='white', relief='raised', state='normal') self.popup_menu.entryconfig("Search", state="normal") self.label_title.bell() print "file_search finished" ##################file_search()######################### def cm_folder_open(self, ev=None): #print "DEBUG print list_var=",self.list_v.get() print "cm_folder_open called" select_file_list = [] index_list = self.listbox_dirs.curselection() for idx in index_list: select_file_list.append(self.listbox_dirs.get(idx)) for file in select_file_list: file = file.encode('gb2312') p_folder = os.path.dirname(file) cmd = ['start', p_folder] try: multi_operates.call_proc(cmd) except Exception as e: print "DEBUG call_proc error=", e self.listbox_dirs.config(selectbackground='red') else: break pass def cm_start_bsc_decode(self, ev=None): print("DEBUG cm_start_bsc_decode") select_path_list = [] index_list = self.listbox_dirs.curselection() for idx in index_list: select_path_list.append(self.listbox_dirs.get(idx)) if len(select_path_list) > 0: t = threading.Thread(target=self.bsc_decode, args=(select_path_list, )) #for terminating purpose l_threads.append(t) t.start() self.start_thread_progressbar() else: print("DEBUG no select") pass def bsc_decode(self, path_list): s = u"{0} is under decode process. please wait...".format(path_list) multi_operates.PROGRESS_QUE.put(s) multi_operates.files_decode(path_list) tip = 'All done, decode finished, time uese:{0}'.format( multi_operates.used_time()) multi_operates.PROGRESS_QUE.put(tip) new_path = os.path.dirname(path_list[-1]) self.refresh_listbox(new_path) self.label_title.bell() print("DEBUG decode finished") def cm_start_logline_count(self, ev=None): print("DEBUG cm_start_logline_count") select_path_list = [] index_list = self.listbox_dirs.curselection() for idx in index_list: select_path_list.append(self.listbox_dirs.get(idx)) if len(select_path_list) > 0: top_rank = 10 t = threading.Thread(target=self.lines_count, args=(select_path_list, top_rank)) #for terminating purpose l_threads.append(t) print("DEBUG start repeat thread", t) t.start() self.start_thread_progressbar() else: print("DEBUG no select") pass def lines_count(self, path_list, top_rank): ''' counting the repeated log occurences ''' s = "Please wait..." self.search_b.config(text=s, bg='orange', relief='sunken', state='disabled') self.popup_menu.entryconfig("Search", state="disable") multi_operates.PROGRESS_QUE.put("Counting start") files_types_list = self.v_files_types.get().strip().split(';') l_result,counted_number = \ multi_operates.files_lines_count(path_list, top_rank, files_types_list) multi_operates.PROGRESS_QUE.put( "Counting finished, generating results...") self.listbox_dirs.delete(0, END) self.listbox_dirs.insert(END, os.curdir) s = u"-----------Counting Lines Repetition Top %d Results--------------------" % ( top_rank) self.listbox_dirs.insert(END, s) j = 0 for item in l_result: j += 1 sitem = '' #if 'str' in str(type(item[0])): # sitem = item[0].encode('gb2312') s = "No.{0} repeated:[{1} times]: {2}".format( str(j), item[1], item[0]) try: s = s.decode('gb2312') except Exception as e: print("error decode e:", e) self.listbox_dirs.insert(END, s) self.listbox_dirs.itemconfig(END, fg=my_color_blue) s = 'All done, counting finished, %d files, counted in %s'\ %(counted_number, multi_operates.used_time()) multi_operates.PROGRESS_QUE.put(s) self.search_b.config(text="Auto analyse", bg='white', relief='raised', state='normal') self.popup_menu.entryconfig("Search", state="normal") self.label_title.bell() print "lines count finished" def cm_start_unpack(self, ev=None): print("DEBUG cm_start_unpack") select_path_list = [] index_list = self.listbox_dirs.curselection() for idx in index_list: select_path_list.append(self.listbox_dirs.get(idx)) if len(select_path_list) > 0: t = threading.Thread(target=self.unpack, args=(select_path_list, )) #for terminating purpose l_threads.append(t) t.start() self.start_thread_progressbar() else: print("DEBUG no select") pass def unpack(self, path_list): #showinfo(title='Untar', message="To be done soon...") s = u"{0} is under untar process. please wait...".format(path_list) multi_operates.PROGRESS_QUE.put(s) multi_operates.files_unpack(path_list) tip = 'All done, unpack finished, time uese:{0}'.format( multi_operates.used_time()) multi_operates.PROGRESS_QUE.put(tip) new_path = os.path.dirname(path_list[-1]) self.refresh_listbox(new_path) self.label_title.bell() print("DEBUG unpack finished") #############context menu function############################# ###############Drag and Drop feature:######################## def dnd_enable(self, widget): dd = dnd.DnD(self.top) def drag(action, actions, type, win, X, Y, x, y, data): return action def drag_enter(action, actions, type, win, X, Y, x, y, data): widget.focus_force() return action def drop(action, actions, type, win, X, Y, x, y, data): self.listbox_dirs.delete(1, END) os_sep = os.path.sep print("data=", data) refined_data = self.refine_data(data) #for f in refine_data(data): for f in refined_data: if f.startswith('{'): #只去掉开头和结尾的{},其他的{}不动 #f = f.strip('{}') f = f[1:-1] #deal with file_list '/' with os.sep f = f.replace(r'/', os_sep) widget.insert('end', f) if os.path.isdir(f): widget.itemconfig(END, fg=my_color_blue_office) else: pass self.current_path_item_number = len(refined_data) s = "{0} files dropped in".format(self.current_path_item_number) #print s self.ptext.set(s) dd.bindtarget(widget, 'text/uri-list', '<Drag>', drag, ('%A', '%a', '%T', '%W', '%X', '%Y', '%x', '%y', '%D')) dd.bindtarget(widget, 'text/uri-list', '<DragEnter>', drag_enter, ('%A', '%a', '%T', '%W', '%X', '%Y', '%x', '%y', '%D')) dd.bindtarget(widget, 'text/uri-list', '<Drop>', drop, ('%A', '%a', '%T', '%W', '%X', '%Y', '%x', '%y', '%D')) #Drag and Drop def refine_data(self, data): flag = 0 for i in range(len(data)): if data[i] == '{': flag += 1 elif data[i] == '}': flag -= 1 if data[i] == ' ' and flag == 0: #print "DEBUG data[:i-1]",data[:i] data = data[:i] + "," + data[i + 1:] l = data.split(',') return l ###############Drag and Drop feature:######################## def syn_item_number(self, path): self.current_path_item_number = len(os.listdir(path)) def listbox_click(self, event): print "listbox L click" self.listbox_dirs.config(selectbackground=my_color_blue) #this function is ahead of dirlist selection #so can't get the selection from this function #use click release function def listbox_click_release(self, event): print("click release") #this function triggered is behind of dirlist selection #Thus, we can get the selections sel = self.listbox_dirs.curselection() select_path_list = [] index_list = self.listbox_dirs.curselection() for idx in index_list: select_path_list.append(self.listbox_dirs.get(idx)) ln = len(select_path_list) self.current_path_item_selected_number = ln s = "{0} of {1} items selected. Keyword filters: {2}".\ format(ln, self.current_path_item_number,self.search_filter) self.ptext.set(s) def listbox_Rclick(self, event, m): #实现右击弹出菜单,在选择的line上 print "listbox R click" #print "DEBUG- y",self.listbox_dirs.nearest(event.y) last_index = self.listbox_dirs.nearest(event.y_root) #找到鼠标点击事件的y(行坐标) line_index = self.listbox_dirs.nearest(event.y) #multi selection #self.listbox_dirs.selection_clear(0,last_index) self.listbox_dirs.selection_set(line_index, line_index) self.listbox_dirs.config(selectbackground=my_color_blue) self.current_path_item_selected_number = len( self.listbox_dirs.curselection()) #check untar possible: index_list = self.listbox_dirs.curselection() re_pattern = r'(\.tar\.gz$)|(\.gz$)|(\.tar$)|(\.tgz$)|(\.zip$)|(\.rar$)' for idx in index_list: path = self.listbox_dirs.get(idx) result = re.search(re_pattern, path.lower()) if not result: self.popup_menu.entryconfig("Unpack", state="disable") break else: self.popup_menu.entryconfig("Unpack", state="normal") #check decode possible: re_pattern = r'\.rtrc' for idx in index_list: path = self.listbox_dirs.get(idx) result = re.search(re_pattern, path) if (not result or path[-4:] == '.out') and not os.path.isdir(path): self.popup_menu.entryconfig("Decode", state="disable") break else: self.popup_menu.entryconfig("Decode", state="normal") #popup right contextual menu m.post(event.x_root, event.y_root) def choose_dir(self, ev=None): p = tkFileDialog.askdirectory() # 返回目录路径 print("open directory:", p) if 'unicode' in str(type(p)): p = p.encode('utf-8') #.decode('gb2312') elif 'str' in str(type(p)): p = p.decode('utf-8') self.cwd.set(p) self.enter_directory() def setDirAndGo(self, ev=None): print "setDirAndGo" self.last = self.cwd.get() #self.listbox_dirs.config(selectbackground='red') self.listbox_dirs.config(selectbackground='LightSkyBlue') #self.listbox_dirs.config(selectbackground=my_color_blue) path = self.listbox_dirs.get(self.listbox_dirs.curselection()) if not path: check = os.curdir print "DEBUG setDirAnd Go path error" #bug 11 if "str" in str(type(path)): path = path.decode('utf-8') self.cwd.set(path) self.enter_directory() def enter_directory(self, ev=None): global FTP_TOP #print "DEBUG print list_var=",self.list_v.get() print "enter_directory" error = '' tdir = self.cwd.get() if not tdir: tdir = os.curdir if not os.path.exists(tdir): error = tdir + ':no such file' elif not os.path.isdir(tdir): error = tdir + ':is not a directory!' if os.path.isfile(tdir): #bug11 #print "This is a file!" #here double click on a file and open it #print "DEBUG type(tdir)=",type(tdir) tdir = tdir.encode('gb2312') #print "DEBUG type(tdir)=",type(tdir) cmd = [tdir] try: multi_operates.call_proc(cmd) except Exception as e: print "DEBUG call_proc error=", e self.listbox_dirs.config(selectbackground='red') return if error: self.cwd.set(error) self.top.update() print "DEBUG error in enter_directory" sleep(0.2) #这个self.last是什么意思? if not (hasattr(self, 'last') and self.last): self.last = os.curdir self.cwd.set(self.last) self.listbox_dirs.config(selectbackground='Red') self.top.update() return else: self.refresh_listbox(tdir) self.cwd.set(os.getcwd()) self.syn_item_number(os.getcwd()) s = "{0} items. Keyword filters: {1}".format( self.current_path_item_number, self.search_filter) self.ptext.set(s) def refresh_listbox(self, dir_path): #print "DEBUG dir_path=",dir_path #print"DEBUG type(dir_path) = ",type(dir_path) dirlist = os.listdir(dir_path) dirlist.sort() os.chdir(dir_path) #全部删除 self.listbox_dirs.delete(0, END) #当前目录'.' #self.listbox_dirs.insert(END, os.curdir) #上一级目录'..' parent_dir = os.pardir.encode('gb2312').decode('utf-8') self.listbox_dirs.insert(END, parent_dir) #bug 11 #print"DEBUG type(dirlist[0]) = ",type(dirlist[0]) v_cwd = os.getcwd().decode('gb2312').encode('utf-8') for eachFile in dirlist: #s = os.path.join(os.getcwd(),eachFile) if 'unicode' in str(type(eachFile)): eachFile = eachFile.encode('utf-8') elif 'str' in str(type(eachFile)): #eachFIle = eachFile.decode('gb2312').encode('utf-8') #print("DEBUG after, type=",type(eachFile)) pass s = os.path.join(v_cwd, eachFile) #s = os.path.join(v_cwd,eachFile.encode('utf-8')) #在listbox中显示中文, windows support gbk or gb2123 coding #bug5 self.listbox_dirs.insert(END, s) if os.path.isdir(s): self.listbox_dirs.itemconfig(END, fg=my_color_blue_office) self.listbox_dirs.config(selectbackground=my_color_blue) ####################refresh_listbox()############################# def get_default_keywords(self, ev=None): self.keyword.set(PREDIFINED_KEYWORD) def get_default_files_filters(self, ev=None): self.v_files_types.set('.*\.txt;.*\.out') def start_thread_analyse(self, ev=None): global l_threads select_path_list = [] index_list = self.listbox_dirs.curselection() for idx in index_list: select_path_list.append(self.listbox_dirs.get(idx)) if len(select_path_list) > 0: #Check if keyword is filtered by filters or customized keyword filtered_keyword_list = self.filter_keyword() t = threading.Thread(target=self.auto_analyse, args=(select_path_list, filtered_keyword_list)) #for terminating purpose l_threads.append(t) t.start() self.start_thread_progressbar() else: print("No file selected") ##########start_thread_analyse()############### def auto_analyse(self, path_list, keyword_list): ''' one key automated analysing the directory ''' print "auto_analyse start:" self.search_b.config(text="Please wait...", bg='orange', relief='sunken', state='disabled', width=10) self.popup_menu.entryconfig("Search", state="disable") ########multi_operates 1.unpack, 2.decode, 3.search############### files_types_list = self.v_files_types.get().strip().split(';') search_result,searched_number = \ multi_operates.do_operates(path_list, keyword_list, files_types_list) multi_operates.PROGRESS_QUE.put( "Analysing finished, generating results...") self.show_result(keyword_list, multi_operates.search_result) #send 'All done flag to listdir.py' s = 'All done, %d files, %d keywords analysed in %s'\ %(searched_number, len(keyword_list), multi_operates.used_time()) multi_operates.PROGRESS_QUE.put(s) self.search_b.config(text="Auto analyse", bg='white', relief='raised', state='normal') self.popup_menu.entryconfig("Search", state="normal") print "auto_analyse finished" #sound a bell self.label_title.bell() ################auto_ananlyse()######################### def start_thread_progressbar(self): ''' this thread is for job process displaying in the bottom of sla ''' global l_threads t = threading.Thread(target=self.progressbar) l_threads.append(t) print("DEBUG start_thead_progressbar: thread=", t) t.start() def progressbar(self): global l_threads print "progressbar start" n = 0 s = "Analsis begins" self.ptext.set(s) #self.pro_label.update() pq = multi_operates.PROGRESS_QUE while 1: alive_number = 0 for thread_x in l_threads: if thread_x.is_alive(): alive_number += 1 if alive_number <= 1 and pq.empty(): break else: #bug 11 #s = pq.get() s = pq.get(True, 20) self.ptext.set(s) if "start" in s: sleep(0.2) if "finished" in s: sleep(0.5) #bug 11 if "All done" in s: break print("progressbar end") return ##################progressbar()################################ def show_result(self, key_words, d_result, is_incompleted=False): global SEARCH_RESULT_LIST global NO_KEYWORD_FIND srl = SEARCH_RESULT_LIST srl[:] = [] #写入dirs ln = len(key_words) print(' show_result start') self.listbox_dirs.delete(0, END) current_dir = os.curdir.encode('gb2312').decode('utf-8') #self.listbox_dirs.insert(END, os.curdir) self.listbox_dirs.insert(END, current_dir) srl.append(current_dir) no_find = True s = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.listbox_dirs.insert(END, s) if ln > 1: s = u" Predefined Keywords Searching" else: s = u" Customed Keyword Searching" s = '-' * 20 + s + '(' + self.v_files_types.get( ) + ') ' + 'Results ' + '-' * 20 if is_incompleted: s = '(incompleted)' + s self.listbox_dirs.insert(END, s) srl.append(s) j = 0 for i in range(ln): nn = 0 lk = key_words[i] if key_words[i][0] in d_result: nn = len(d_result[lk[0]]) if nn > 0: no_find = False j = j + 1 #s = self.searcher.l_keywords[i][0] #self.listbox_dirs.insert(END,s) #Keyword Name s = u"{0}".format(lk[0]) self.listbox_dirs.insert(END, s) srl.append(s) self.listbox_dirs.itemconfig(END, fg=my_color_blue_office) #Module Category module_category = lk[2].decode("gb2312") #.encode("utf-8") s = u"[Module]:{0}".format(module_category) self.listbox_dirs.insert(END, s) self.listbox_dirs.itemconfig(END, fg=my_color_light_green) srl.append(s) #Issue Category issue_category = lk[5].decode("gb2312") #.encode("utf-8") #s =u"issue category:---{0}---".format(lk[4]) s = u"[Issue Category]:{0}".format(issue_category) self.listbox_dirs.insert(END, s) self.listbox_dirs.itemconfig(END, fg=my_color_red) srl.append(s) cr_category = lk[6].decode("gb2312") #.encode("utf-8") #s =u"issue category:---{0}---".format(lk[4]) s = u"[Related CRs]:{0}".format(cr_category) self.listbox_dirs.insert(END, s) self.listbox_dirs.itemconfig(END, fg=my_color_orange) srl.append(s) s = u"[File Occurence]:{0}".format(nn) self.listbox_dirs.insert(END, s) srl.append(s) for file in d_result[lk[0]]: s = file if not s: print "DEBUG s= None:", s try: self.listbox_dirs.insert(END, s) srl.append(s) except Exception as e: print 'error here e=', e print "insert(END,s) where s=", s s = ' ' self.listbox_dirs.insert(END, s) srl.append(s) s = "-" * 20 + u"totally {0} keywords occured!".format(j) + "-" * 20 self.listbox_dirs.insert(END, s) srl.append(s) if no_find: if self.keyword.get() != PREDIFINED_KEYWORD: s = u"没有发现含有关键字'{0}'的文件, No findings".format( self.keyword.get()) else: s = u"没有发现含有任何关键字, No findings" self.listbox_dirs.insert(END, s) srl.append(s) #update custom keyword using history if self.keyword.get() != PREDIFINED_KEYWORD: self.ck_list.append(self.keyword.get()) value = list(self.combo_search['values']) value.insert(0, self.keyword.get()) self.combo_search['values'] = value #clear the search result which can not be used by terminate thread function d_result.clear() NO_KEYWORD_FIND = no_find ###############show_result####################### #########force to close thread############## def _async_raise(self, tid, exctype): """raises the exception, performs cleanup if needed""" tid = ctypes.c_long(tid) if not inspect.isclass(exctype): exctype = type(exctype) res = ctypes.pythonapi.PyThreadState_SetAsyncExc( tid, ctypes.py_object(exctype)) if res == 0: raise ValueError("invalid thread id") elif res != 1: # """if it returns a number greater than one, you're in trouble, # and you should call it again with exc=NULL to revert the effect""" ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None) raise SystemError("PyThreadState_SetAsyncExc failed") def terminate_threads(self): ''' 强制终止线程 ''' global l_threads global PRE_KEYWORD_LIST #print("DEBUG teminate thread list:",l_threads) alive_number = 0 for thread_x in l_threads: if thread_x.is_alive(): #print("thread:{} is still alive".format(thread_x)) alive_number += 1 #print("THere are still %d theads alive" % alive_number) if alive_number == 0: #print("DEBUG no alive threads, return") l_threads[:] = [] return if l_threads: for t in l_threads: if t.is_alive(): self._async_raise(t.ident, SystemExit) t._Thread__stop() self.search_b.config(text="Auto analyse", bg='white', relief='raised', state='normal') self.popup_menu.entryconfig("Search", state="normal") #list clear way: l_threads[:] = [] s = "stopped" self.ptext.set(s) #self.enter_directory() #if partial search_results have some results, printed out s_re = multi_operates.search_result if len(s_re) > 0: filtered_keyword_list = self.filter_keyword() self.show_result(PRE_KEYWORD_LIST, s_re, True)
def __init__(self, parent, controller): Frame.__init__(self, parent) #VARIABLES GLOBALES global codigo, direccion, piso, telefono, ciudad, zona, barrio, estrato, llaves, preguntarx, fin, vlrenta, vladmon, incluida, vlventa, vlavaluo, comiventa, pagoprop, fpagoprop, fpagoadmin, tpropiedad, area, lineas, habitaciones, closets, lamparas, duchas, lavamanos, tsala, tcocina, tpiso, tgarage, rutabus, aservicio, ascensor, citofono, aguacaliente, biblioteca, zverdes, terraza, trifilar, parqueadero, observaciones, lb, Cbx1, Cbx2, zona1, zona2, zona3, zona4, zona5, busqueda, dato, E #INSTANCIAS DE LOS WIDGETS global codE, adressE, comisionE, phoneE, cityCbx, Cbx1, Cbx2, estratoE, keysE, askforE, rent, arriendoE, admonE, include, sale, ventaE, avaluadoE, comiE, pagopropietarioE, diapagopropietarioE, diapagoadmonE, propertyCbx, areaE, lineasE, roomE, closetE, lampE, bathE, sinkE, salasCbx, cocinaCbx, pisoCbx, garageCbx, rutaE, chkb0, chkb1, chkb2, chkb3, chkb4, chkb5, chkb6, chkb7, chkb8, observaciones, add, delete, edit, clean, update #Variables codigo = IntVar() direccion = StringVar() piso = IntVar() telefono = StringVar() ciudad = StringVar() zona = StringVar() barrio = StringVar() estrato = StringVar() llaves = StringVar() preguntarx = StringVar() fin = IntVar() vlrenta = IntVar() vladmon = IntVar() incluida = IntVar() vlventa = IntVar() vlavaluo = IntVar() comiventa = DoubleVar() pagoprop = IntVar() fpagoprop = IntVar() fpagoadmin = IntVar() tpropiedad = StringVar() area = IntVar() lineas = IntVar() habitaciones = IntVar() closets = IntVar() lamparas = IntVar() duchas = IntVar() lavamanos = IntVar() tsala = StringVar() tcocina = StringVar() tpiso = StringVar() tgarage = StringVar() rutabus = StringVar() aservicio = IntVar() ascensor = IntVar() citofono = IntVar() aguacaliente = IntVar() biblioteca = IntVar() zverdes = IntVar() terraza = IntVar() trifilar = IntVar() parqueadero = IntVar() ciudades = [ 'Medellín', 'Envigado', 'Caldas', 'El Retiro', 'Guatapé', 'Bogotá D.C', 'Bello', 'Copacabana', 'Rionegro', 'Sabaneta', "Girardot", "Itaguí" ] zonas = ["Zona 1", "Zona 2", "Zona 3", "Zona 4", "Zona 5"] zona1 = [ 'Centro', 'Manrique', 'Aranjuez', 'Prado', 'Buenos Aires', 'Loreto', 'Milagrosa', 'Villa Hermosa', 'Boston', 'Campo Valdés' ] zona2 = [ 'Poblado', 'Patio Bonito', 'Provenza', 'Castropol', 'Manila', 'San Lucas', 'Envigado', 'El Dorado', 'Loma de Escobero', 'Sabaneta', 'San Diego', 'Las Palmas', 'La Sebastiana' ] zona3 = [ 'Laureles', 'La América', 'Estadio', 'Santa Mónica', 'Floresta', 'Conquistadores', 'Florida Nueva', 'Robledo', 'Los Colores', 'San Joaquín', 'Castilla', 'Pedregal', 'Tricentenario', 'Bello', 'Florencia', 'Boyacá las Brisas', 'Barrio Nuevo', 'La Mota', 'Calazans', 'Simón Bolivar', 'El Portal', 'Envigado' ] zona4 = [ 'Rosales', 'Guayabal', 'Belén', 'Itaguí', 'La Estrella', 'Manzanares', 'El Carmelo', 'Mayorca' ] zona5 = ['El Retiro'] negociacion = StringVar() propiedades = [ 'Casa', 'Apartamento', 'Local', 'Local comercial', 'Local industrial', 'Oficina', 'Bodega', 'Finca', 'Casa finca', 'Cabaña', 'Apartaestudio', 'Apartalock', 'Lote', 'Consultorio', 'Parqueadero' ] comodidades = [ "ALCOBA DE SERVICIO", "ASCENDOR", "CITÓFONO", "AGUA CALIENTE", "BIBLIOTECA", "ZONAS VERDES", "PARQUEADERO VISITANES", "TRIFILAR", "TERRAZA" ] salas = ['Salón', 'Salón comedor', 'Sala garage'] cocina = [ 'Integral', 'Semintegral', 'Sencilla', 'Mixta', 'Cocineta', 'Integral a gas' ] pisos = [ 'Baldosa', 'Mármol', 'Cerámica', 'Alfombra', 'Mármol y Cerámica', 'Alfombra y Cerámica', 'Reforzado', 'Porcelanato', 'Madera' ] garage = ['Cubierto', 'Eléctrico', 'Descubierto', 'Paralelo'] #busqueda = ["Código","Dirección"] busqueda = StringVar() busqueda.trace("w", lambda name, index, mode: buscar()) dato = IntVar() #WIDGETS #========================= HEADER =========================== self.header = Label(self, text="GESTIÓN DE IMNUEBLES", font="bold") self.header.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) #================ NOTEBOOK =============> self.nb = Notebook(self.wrapper) #-----------------------> TAB 1 self.tab1 = Frame(self.nb) self.f0 = Frame( self.tab1) #Es para dejar un espacio entre el Tab y el Label self.f0.pack(fill=X, pady=10) #------------------------------- self.f1 = Frame(self.tab1) #------------------------------- self.f1.pack(pady=5, fill=X) self.codL = Label(self.f1, text='Código:') self.codL.pack(side=LEFT) codE = Entry(self.f1, textvariable=codigo, width=5) codE.pack(side=LEFT) codE.focus_set() self.adressL = Label(self.f1, text='Dir. Casa:') self.adressL.pack(side=LEFT) adressE = Entry(self.f1, textvariable=direccion) adressE.pack(side=LEFT, fill=X, expand=1) adressE.bind("<KeyRelease>", caps) self.comisionL = Label(self.f1, text='Piso:') self.comisionL.pack(side=LEFT) comisionE = Entry(self.f1, textvariable=piso, width=5) comisionE.pack(side=LEFT) self.phoneL = Label(self.f1, text='Tel:') self.phoneL.pack(side=LEFT) phoneE = Entry(self.f1, textvariable=telefono, width=20) phoneE.pack(side=LEFT) self.f2 = Frame(self.tab1) self.f2.pack(pady=5, fill=X) #------------------------------------ self.cityL = Label(self.f2, text='Ciudad:') self.cityL.pack(side=LEFT) cityCbx = Combobox(self.f2, textvariable=ciudad, values=ciudades, width=10) cityCbx.set('') cityCbx.pack(side=LEFT, fill=X, expand=1) self.zoneL = Label(self.f2, text='Zona:') self.zoneL.pack(side=LEFT) Cbx1 = Combobox(self.f2, textvariable=zona, values=zonas, width=10) Cbx1.set('') Cbx1.bind("<<ComboboxSelected>>", zone) Cbx1.pack(side=LEFT, fill=X, expand=1) self.neighborL = Label(self.f2, text='Barrio:') self.neighborL.pack(side=LEFT) Cbx2 = Combobox(self.f2, textvariable=barrio, width=10) Cbx2.set('') Cbx2.pack(side=LEFT, fill=X, expand=1) self.estratoL = Label(self.f2, text='Estrato:') self.estratoL.pack(side=LEFT) estratoE = Entry(self.f2, textvariable=estrato, width=5) estratoE.pack(side=LEFT) self.f3 = Frame(self.tab1) self.f3.pack(pady=5, fill=X) #------------------------------------ self.keysL = Label(self.f3, text='Llaves en:') self.keysL.pack(side=LEFT) keysE = Entry(self.f3, textvariable=llaves, width=24) keysE.pack(side=LEFT, fill=X, expand=1) keysE.bind("<KeyRelease>", caps) self.askforL = Label(self.f3, text='Preguntar por:') self.askforL.pack(side=LEFT) askforE = Entry(self.f3, textvariable=preguntarx, width=24) askforE.pack(side=LEFT, fill=X, expand=1) askforE.bind("<KeyRelease>", caps) self.negociacionLF = LabelFrame(self.tab1, text="Valores Negociación") self.negociacionLF.pack(anchor=W, pady=5, fill=X) #---------------------- self.f5a = Frame(self.negociacionLF) self.f5a.pack(pady=5, fill=X) #--------------------------- rent = Radiobutton(self.f5a, text="Se Arrienda: ", variable=fin, value=1) rent.pack(side=LEFT) self.arriendoL = Label(self.f5a, text='Valor $') self.arriendoL.pack(side=LEFT) arriendoE = Entry(self.f5a, textvariable=vlrenta, width=15) arriendoE.pack(side=LEFT) self.admonL = Label(self.f5a, text='Administración $') self.admonL.pack(side=LEFT) admonE = Entry(self.f5a, textvariable=vladmon, width=15) admonE.pack(side=LEFT) include = Checkbutton(self.f5a, text="Admin. incluida", variable=incluida) include.pack(side=LEFT) self.f5b = Frame(self.negociacionLF) self.f5b.pack(pady=5, fill=X) #--------------------------- sale = Radiobutton(self.f5b, text="Se Vende: ", variable=fin, value=2) sale.pack(side=LEFT) self.ventaL = Label(self.f5b, text='Valor $') self.ventaL.pack(side=LEFT) ventaE = Entry(self.f5b, textvariable=vlventa, width=15) ventaE.pack(side=LEFT) self.avaluadoL = Label(self.f5b, text='Avaluado $') self.avaluadoL.pack(side=LEFT) avaluadoE = Entry(self.f5b, textvariable=vlavaluo, width=15) avaluadoE.pack(side=LEFT) self.comiL = Label(self.f5b, text='Comisión Venta') self.comiL.pack(side=LEFT) comiE = Entry(self.f5b, textvariable=comiventa, width=5) comiE.pack(side=LEFT) self.porcentL = Label(self.f5b, text='%') self.porcentL.pack(side=LEFT) self.pagoLF = LabelFrame(self.tab1, text="Detalles de pago") self.pagoLF.pack(anchor=W, pady=5, fill=X) #----------- self.f6 = Frame(self.pagoLF) self.f6.pack(pady=5, fill=X) #--------------------------- self.pagopropietarioL = Label(self.f6, text='$ Pago Propietario:') self.pagopropietarioL.pack(side=LEFT) pagopropietarioE = Entry(self.f6, textvariable=pagoprop, width=10) pagopropietarioE.pack(side=LEFT, fill=X, expand=1) self.diapagopropietarioL = Label(self.f6, text='Día Pago Propietario:') self.diapagopropietarioL.pack(side=LEFT) diapagopropietarioE = Entry(self.f6, textvariable=fpagoprop, width=5) diapagopropietarioE.pack(side=LEFT) self.diapagoadmonL = Label(self.f6, text='Día Pago Admon:') self.diapagoadmonL.pack(side=LEFT) diapagoadmonE = Entry(self.f6, textvariable=fpagoadmin, width=5) diapagoadmonE.pack(side=LEFT) self.tab1.pack() #-----------------------> TAB 2 self.tab2 = Frame(self.nb) self.tab2.pack() self.f0 = Frame(self.tab2) self.f0.pack(fill=X, pady=10) #------------------------------- self.f1 = Frame(self.tab2) self.f1.pack(fill=X) #------------------------------- self.propertyL = Label(self.f1, text='Tipo Propiedad:') self.propertyL.pack(side=LEFT) propertyCbx = Combobox(self.f1, textvariable=tpropiedad, values=propiedades, width=15) propertyCbx.set('') propertyCbx.pack(side=LEFT) self.areaL = Label(self.f1, text='Área:') self.areaL.pack(side=LEFT) areaE = Entry(self.f1, textvariable=area, width=5) areaE.pack(side=LEFT) self.m2L = Label(self.f1, text='m2') self.m2L.pack(side=LEFT) self.emptyL = Label(self.f1) ###VACIO### self.emptyL.pack(padx=5, side=LEFT) self.lineasL = Label(self.f1, text='# Líneas:') self.lineasL.pack(side=LEFT) lineasE = Entry(self.f1, textvariable=lineas, width=5) lineasE.pack(side=LEFT) self.roomL = Label(self.f1, text='# Habitaciones:') self.roomL.pack(side=LEFT) roomE = Entry(self.f1, textvariable=habitaciones, width=5) roomE.pack(side=LEFT) self.f2 = Frame(self.tab2) #------------------------------- self.f2.pack(pady=5, fill=X) self.closetL = Label(self.f2, text='# Closets:') self.closetL.pack(side=LEFT) closetE = Entry(self.f2, textvariable=closets, width=5) closetE.pack(side=LEFT) self.lampL = Label(self.f2, text='# Lámparas:') self.lampL.pack(side=LEFT) lampE = Entry(self.f2, textvariable=lamparas, width=5) lampE.pack(side=LEFT) self.bathL = Label(self.f2, text='# Baños:') self.bathL.pack(side=LEFT) bathE = Entry(self.f2, textvariable=duchas, width=5) bathE.pack(side=LEFT) self.sinkL = Label(self.f2, text='# Lavamanos:') self.sinkL.pack(side=LEFT) sinkE = Entry(self.f2, textvariable=lavamanos, width=5) sinkE.pack(side=LEFT) self.f4 = Frame(self.tab2) self.f4.pack(pady=5, fill=X) #------------------------------- self.salaL = Label(self.f4, text='Tipo Sala:') self.salaL.pack(side=LEFT) salasCbx = Combobox(self.f4, textvariable=tsala, values=salas) salasCbx.set('') salasCbx.pack(side=LEFT) self.cocinaL = Label(self.f4, text='Tipo Cocina:') self.cocinaL.pack(side=LEFT) cocinaCbx = Combobox(self.f4, textvariable=tcocina, values=cocina) cocinaCbx.set('') cocinaCbx.pack(side=LEFT) self.f5 = Frame(self.tab2) self.f5.pack(pady=5, fill=X) #------------------------------- self.pisoL = Label(self.f5, text='Tipo Piso:') self.pisoL.pack(side=LEFT) pisoCbx = Combobox(self.f5, textvariable=tpiso, values=pisos) pisoCbx.set('') pisoCbx.pack(side=LEFT) self.garageL = Label(self.f5, text='Tipo garage:') self.garageL.pack(side=LEFT) garageCbx = Combobox(self.f5, textvariable=tgarage, values=garage) garageCbx.set('') garageCbx.pack(side=LEFT) self.f6 = Frame(self.tab2) #------------------------------- self.f6.pack(pady=5, fill=X) self.rutaL = Label(self.f6, text='Ruta de Buses:') self.rutaL.pack(side=LEFT) rutaE = Entry(self.f6, textvariable=rutabus, width=30) rutaE.pack(side=LEFT) self.f7 = Frame(self.tab2) self.f7.pack(pady=5, fill=X) #------------------------------- self.comodidades = LabelFrame(self.f7, text="Comodidades:") self.comodidades.pack(anchor=W, pady=5, fill=X, expand=1) #---------------------- chkb0 = Checkbutton(self.comodidades, text="ALCOBA DE SERVICIO", variable=aservicio) chkb0.grid(row=0, column=0, sticky=W) chkb1 = Checkbutton(self.comodidades, text="ASCENSOR", variable=ascensor) chkb1.grid(row=0, column=1, sticky=W) chkb2 = Checkbutton(self.comodidades, text="CITÓFONO", variable=citofono) chkb2.grid(row=0, column=2, sticky=W) chkb3 = Checkbutton(self.comodidades, text="AGUA CALIENTE", variable=aguacaliente) chkb3.grid(row=0, column=3, sticky=W) chkb4 = Checkbutton(self.comodidades, text="BIBLIOTECA", variable=biblioteca) chkb4.grid(row=1, column=0, sticky=W) chkb5 = Checkbutton(self.comodidades, text="ZONAS VERDES", variable=zverdes) chkb5.grid(row=1, column=1, sticky=W) chkb6 = Checkbutton(self.comodidades, text="TERRAZA", variable=terraza) chkb6.grid(row=1, column=2, sticky=W) chkb7 = Checkbutton(self.comodidades, text="TRIFILAR", variable=trifilar) chkb7.grid(row=1, column=3, sticky=W) chkb8 = Checkbutton(self.comodidades, text="PARQUEADERO VISITANTES", variable=parqueadero) chkb8.grid(row=2, column=0, sticky=W) self.f9 = Frame(self.tab2) self.f9.pack(pady=5, fill=X) #------------------------------------ self.notesL = Label(self.f9, text='Observaciones:') self.notesL.pack(side=LEFT) self.f10 = Frame(self.tab2) self.f10.pack(pady=5, fill=X) #----------------------------------- observaciones = Text(self.f10, height=5) observaciones.pack(side=LEFT, fill=X, expand=1) #--------------------------------------------------------------- self.nb.add(self.tab1, text="Datos Generales") self.nb.add(self.tab2, text="Inventario y Comodidades") self.nb.pack() #=========================== BOTONES =========================== self.fBtn = Frame(self.wrapper) self.fBtn.pack() #------------------------------- clean = Button(self.fBtn, text='Limpiar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=limpiar) clean.pack(side=RIGHT) update = Button(self.fBtn, text='Actualizar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=actualizar, state=DISABLED) update.pack(side=RIGHT) add = Button(self.fBtn, text='Agregar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=Agregar) 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 INMUEBLES") 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, bg='#d8ecf3') scroll.config(command=lb.yview) lb.pack(fill=BOTH) lb.bind("<Double-Button-1>", callback) self.wrap2 = Frame(self.aside) self.wrap2.pack() self.updateBP = Button(self.wrap2, text='Cargar lista', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=cargar_lista) self.updateBP.pack(fill=X) delete = Button(self.wrap2, text='Borrar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=borrar) delete.pack(fill=X) edit = Button(self.wrap2, text='Modificar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=modificar) edit.pack(fill=X) buscador = Label(self.wrap2, text="Buscar por Código:") buscador.pack() E = Entry(self.wrap2, textvariable=busqueda, width=24) E.pack() E.bind("<KeyRelease>", caps)
def __init__(self, parent, controller): Frame.__init__(self, parent) global cedula, codigo, ref, nombre, direccion, ciudad, telefono, gcontribuyente, gcheque, titular, banco, tipocuenta, numcuenta, notas, busqueda global ccE, codE, tituloE, nameE, locacionE, cityE, niE, ch1, ch2, tnameE, bankCbx, tbankCbx, tcuentaE, note, lb, add, clean, delete, update global info #VARIABLES cedula = StringVar() codigo = IntVar() ref = StringVar() nombre = StringVar() direccion = StringVar() ciudad = StringVar() telefono = StringVar() gcontribuyente = IntVar() gcheque = IntVar() titular = StringVar() banco = StringVar() tipocuenta = StringVar() numcuenta = StringVar() notas = StringVar() tbancos = [ 'Bancolombia', "Banco Bogotá", "Banco Agrario", "Banco Occidente" ] tbanktype = ['Corriente', 'Ahorro'] #BUSQUEDA = ["Nombre","CC/Nit"] busqueda = StringVar() busqueda.trace("w", lambda name, index, mode: buscar()) info = IntVar() dato = StringVar() #WIDGETS #========================= HEADER ============================== self.titleL = Label(self, text="GESTIÓN DE TERCEROS", 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) self.f1 = Frame(self.wrapper) self.f1.pack(pady=5, fill=X) #----------------------------------- self.niL = Label(self.f1, text='CC/Nit:') self.niL.pack(side=LEFT) ccE = Entry(self.f1, textvariable=cedula) ccE.pack(side=LEFT) ccE.focus_set() l3 = Label(self.f1, text='Codigo:') l3.pack(side=LEFT) codE = Entry(self.f1, textvariable=codigo) codE.pack(side=LEFT) codE.bind("<KeyRelease>", caps) self.tituloL = Label(self.f1, text='Título:') self.tituloL.pack(side=LEFT) tituloE = Entry(self.f1, textvariable=ref) tituloE.pack(side=LEFT) #tituloE.bind("<KeyRelease>", caps) self.f2 = Frame(self.wrapper) self.f2.pack(fill=X) #------------------------------------------- self.nameL = Label(self.f2, text='Nombre:') self.nameL.pack(side=LEFT) nameE = Entry(self.f2, textvariable=nombre) nameE.pack(side=LEFT, fill=X, expand=1) nameE.bind("<KeyRelease>", caps) self.f3 = Frame(self.wrapper) self.f3.pack(pady=5, fill=X) #------------------------------------ self.locacionL = Label(self.f3, text='Dirección:') self.locacionL.pack(side=LEFT) locacionE = Entry(self.f3, textvariable=direccion) locacionE.pack(side=LEFT, fill=X, expand=1) locacionE.bind("<KeyRelease>", caps) self.f4 = Frame(self.wrapper) self.f4.pack(pady=5, fill=X) #------------------------------------ self.cityL = Label(self.f4, text='Ciudad de residencia:') self.cityL.pack(side=LEFT) cityE = Entry(self.f4, textvariable=ciudad) cityE.pack(side=LEFT, fill=X, expand=1) cityE.bind("<KeyRelease>", caps) self.niL = Label(self.f4, text='Teléfono:') self.niL.pack(side=LEFT) niE = Entry(self.f4, textvariable=telefono) niE.pack(side=LEFT, fill=X, expand=1) self.f5 = Frame(self.wrapper) self.f5.pack(pady=5, fill=X) #------------------------------------ ch1 = Checkbutton(self.f5, text="Gran Contribuyente", variable=gcontribuyente, state=DISABLED) ch1.pack(side=RIGHT) ch2 = Checkbutton(self.f5, text="Genera Cheque", variable=gcheque, state=DISABLED) ch2.pack(side=RIGHT) self.lf = LabelFrame(self.wrapper, text="Datos Titular") #======= self.f6 = Frame(self.lf) self.f6.pack(pady=5, fill=X) #------------------------------------ self.tnameL = Label(self.f6, text='Nombres:') self.tnameL.pack(side=LEFT) tnameE = Entry(self.f6, textvariable=titular) tnameE.pack(side=LEFT, fill=X, expand=1) tnameE.bind("<KeyRelease>", caps) self.f7 = Frame(self.lf) self.f7.pack( fill=X) #------------------------------------------------- self.tbancpL = Label(self.f7, text='Banco:') self.tbancpL.pack(side=LEFT) bankCbx = Combobox(self.f7, textvariable=banco, values=tbancos, width=12) bankCbx.set('') bankCbx.pack(side=LEFT) self.tbancpL = Label(self.f7, text='Tipo Cuenta:') self.tbancpL.pack(side=LEFT) tbankCbx = Combobox(self.f7, textvariable=tipocuenta, values=tbanktype, width=8) tbankCbx.set('') tbankCbx.pack(side=LEFT) self.tcuentaL = Label(self.f7, text='# Cuenta:') self.tcuentaL.pack(side=LEFT) tcuentaE = Entry(self.f7, textvariable=numcuenta) tcuentaE.pack(side=LEFT, fill=X, expand=1) self.lf.pack(fill=X, ipady=5) #================================ self.f9 = Frame(self.wrapper) self.f9.pack(pady=5, fill=X) #-------------------- self.notesL = Label(self.f9, text='Observaciones:') self.notesL.pack(side=LEFT) self.f10 = Frame(self.wrapper) self.f10.pack(pady=5, fill=X) #------------------- note = Text(self.f10, height=5) note.pack(fill=X, side=LEFT) self.fBtn = Frame(self.wrapper) self.fBtn.pack() #------------------------------- clean = Button(self.fBtn, text='Limpiar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=limpiar) clean.pack(side=RIGHT) update = Button(self.fBtn, text='Actualizar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=None, state=DISABLED) update.pack(side=RIGHT) add = Button(self.fBtn, text='Agregar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=Agregar) 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 TERCEROS") 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, bg='#d8ecf3') scroll.config(command=lb.yview) lb.pack(fill=BOTH) lb.bind("<Double-Button-1>", callback) self.wrap2 = Frame(self.aside) self.wrap2.pack() self.updateBP = Button(self.wrap2, text='Cargar lista', width=20, bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=cargar_lista) self.updateBP.pack(fill=X) delete = Button(self.wrap2, text='Borrar', bg='navy', width=20, foreground='white', activebackground='red3', activeforeground='white', command=borrar) delete.pack(fill=X) edit = Button(self.wrap2, text='Modificar', bg='navy', width=20, foreground='white', activebackground='red3', activeforeground='white', command=modificar) edit.pack(fill=X) self.wrap3 = Frame(self.aside) self.wrap3.pack() buscador = Label(self.wrap3, text="Buscar por:") buscador.pack(side=LEFT) R1 = Radiobutton(self.wrap3, text="CC", variable=info, value=1) R1.pack(side=LEFT) R2 = Radiobutton(self.wrap3, text="Nombre", variable=info, value=2) R2.pack(side=LEFT) info.set(1) self.wrap4 = Frame(self.aside) self.wrap4.pack() E = Entry(self.wrap4, textvariable=busqueda, width=24) E.pack() E.bind("<KeyRelease>", caps)
def __init__(self, parent, controller): Frame.__init__(self, parent) global cc, nombre, inmuebles, valor, mes, meses, cbox lupa = PhotoImage(file='img/lupa.gif') cc = StringVar() nombre = StringVar() inmuebles = StringVar() valor = DoubleVar() mes = StringVar() meses = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto","Septiembre", "Octubre", "Noviembre", "Diciembre"] #WIDGETS #=========================== HEADER ============================ self.titleL = Label(self, text="REAJUSTES A PROPIETARIOS", font="bold") self.titleL.pack(pady=20, side=TOP) #=========================== WRAPPER =========================== self.wrapper = Frame (self) self.wrapper.pack(side=TOP, fill=Y) lf = LabelFrame(self.wrapper, text="Propietario / Inmueble") lf.pack(fill=X) f = Frame(lf) f.pack(pady=5, fill=X)#----------------------------------- e = Entry (f, textvariable=cc, width=20) e.pack(side=LEFT) b1 = Button(f, image=lupa, command=buscar) b1.image = lupa b1.pack(side=LEFT) cbox = Combobox(f, textvariable=inmuebles, width=30) cbox.pack(side=LEFT, fill=X, expand=1) f0 = Frame(lf) f0.pack(side=TOP,pady=5, fill=X)#----------------------------------- e2 = Entry (f0, textvariable=nombre, width=60, state=DISABLED) e2.pack(side=LEFT, fill=X, expand=1) f1 = Frame(self.wrapper) f1.pack(pady=5, fill=X)#----------------------------------- l1 = Label(f1, text='Valor reajuste: ') l1.pack(side=LEFT) e1 = Entry (f1, textvariable=valor, width=20) e1.pack(side=LEFT) l2 = Label(f1, text='Mes: ') l2.pack(side=LEFT) Cbx2 = Combobox(f1, textvariable=mes, values=meses, width=10) Cbx2.set('') Cbx2.pack(side=LEFT) f2 = Frame(self.wrapper) f2.pack(pady=5, fill=X)#----------------------------------- b1 = Button (f2, text="Cancelar", command=cancelar) b1.pack(side=RIGHT) b2 = Button (f2, text="Grabar e Imprimir", command=guardar) b2.pack(side=RIGHT)
def __init__(self, parent, controller): Frame.__init__(self, parent) #VARIABLES GLOBALES global cod, cc, inquilino, codinm, inmueble, nit, owner, rel, vlrenta, duracion global contratos, tcontrato, incremento, gfacturaIni, facturaSgte, fecha, hoy global notas, anexos, destinacion, servicios, conexos, tercero, nombret, fecha global aplicado, cc_aplicado, n_aplicado, inm_aplicado, novedad, n_nombre, n_valor global h, busqueda, clean, update, add #INSTANCIEAS DE LOS WIDGETS global e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, Cbx1, chkb1, chkb2, lb, cedulaE, notas fecha = datetime.date.today() hoy = "%s" %fecha #ESTE NUESTRA LA FECHA EN FORMATO AÑO-MES-DIA (YYYY/MM/DD) #hoy = time.strftime("%d/%m/%y") #ESTO PARA VER FORMATO FECHA EN DIA/MES/AÑO #hoy = time.strftime("%y/%m/%d") h = hoy #VARIABLES lupa = PhotoImage(file='img/lupa.png') schedule = PhotoImage(file='img/calendar.gif') cod = IntVar() cc = StringVar() inquilino = StringVar() codinm = IntVar() inmueble = StringVar() nit = StringVar() owner = StringVar() rel = IntVar() vlrenta = DoubleVar() duracion = IntVar() contratos = ['Vivienda', 'Comercial', 'Mixta'] tcontrato = StringVar() incremento = DoubleVar() gfacturaIni = IntVar() facturaSgte = IntVar() fecha = StringVar() notas = StringVar() anexos = StringVar() destinacion = StringVar() servicios = StringVar() conexos = StringVar() tercero = StringVar() nombret = StringVar() aplicado = IntVar() cc_aplicado = StringVar() n_aplicado = StringVar() inm_aplicado = StringVar() novedad = StringVar() n_nombre = StringVar() n_valor = DoubleVar() #BUSQUEDA = ["Nombre","CC/Nit"] busqueda = StringVar() busqueda.trace("w", lambda name, index, mode: buscar()) dato = StringVar() #WIDGETS #========================= HEADER =========================== self.header = Label(self, text="CONTRATOS", font="bold") self.header.pack(pady=20, side=TOP) #========================== WRAPPER ========================== self.wrapper = Frame (self) self.wrapper.pack(side=LEFT, fill=Y) #================ NOTEBOOK =============> self.nb = Notebook(self.wrapper) #-----------------------> TAB 1 self.tab1 = Frame (self.nb) self.f0 = Frame(self.tab1)#------------------------------------- self.f0.pack(pady=5,fill=X) l1 = Label(self.f0, text='Código:') l1.pack(side=LEFT) e1 = Entry(self.f0, textvariable=cod, width=10) e1.pack(side=LEFT) self.f1 = Frame(self.tab1)#------------------------------------- self.f1.pack(pady=5,fill=X) l2 = Label(self.f1, text='Arrendatario:') l2.pack(side=LEFT, fill=X) e2 = Entry(self.f1, textvariable=cc, width=15) e2.pack(side=LEFT) e2.bind('<Return>', buscarA) b1 = Button(self.f1, image=lupa, command=topArrendatario) b1.image = lupa b1.pack(side=LEFT) e3 = Entry(self.f1, textvariable=inquilino, state=DISABLED) e3.pack(side=LEFT, fill=X, expand=1) self.f2 = Frame(self.tab1) self.f2.pack(pady=5,fill=X)#------------------------------------ l3 = Label(self.f2, text='Inmueble:') l3.pack(side=LEFT) e4 = Entry(self.f2, textvariable=codinm, width=10) e4.pack(side=LEFT) e4.bind('<Return>', buscarR) b2 = Button(self.f2, image=lupa, command=topRelacion) b2.pack(side=LEFT) e5 = Entry(self.f2, textvariable=inmueble, state=DISABLED) e5.pack(side=LEFT, fill=X, expand=1) self.f3 = Frame(self.tab1) self.f3.pack(pady=5,fill=X)#------------------------------------ l4 = Label(self.f3, text='Propietario:') l4.pack(side=LEFT) e6 = Entry(self.f3, width=15, textvariable=nit, state=DISABLED) e6.pack(side=LEFT) e7 = Entry(self.f3, width=5, textvariable=owner, state=DISABLED) e7.pack(side=LEFT, fill=X, expand=1) self.f4 = Frame(self.tab1) self.f4.pack(pady=5,fill=X)#------------------------------------ self.arriendo = Label(self.f4, text='Arriendo $:') self.arriendo.pack(side=LEFT) e8 = Entry(self.f4, textvariable=vlrenta, state=DISABLED, width=20) e8.pack(side=LEFT) self.duracion = Label(self.f4, text='Duración Contrato:') self.duracion.pack(side=LEFT) e9 = Entry(self.f4, textvariable=duracion, width=5) e9.pack(side=LEFT) self.meses = Label(self.f4, text='Meses') self.meses.pack(side=LEFT) self.f5 = Frame(self.tab1) self.f5.pack(pady=5,fill=X)#------------------------------------ self.tcontrato = Label(self.f5, text='Tipo Contrato:') self.tcontrato.pack(side=LEFT) Cbx1 = Combobox(self.f5, textvariable=tcontrato, values=contratos, width=10) Cbx1.set('') Cbx1.pack(side=LEFT) self.incremento = Label(self.f5, text='Incremento:') self.incremento.pack(side=LEFT) e10 = Entry(self.f5, textvariable=incremento, width=5) e10.pack(side=LEFT) chkb1 = Checkbutton(self.f5, text="General factura\n inicial", variable=gfacturaIni) chkb1.pack(side=LEFT) chkb2 = Checkbutton(self.f5, text="Facturar príodo\n siguiente", variable=facturaSgte) chkb2.pack(side=LEFT) self.f6 = Frame(self.tab1) self.f6.pack(pady=5,fill=X)#------------------------------------ btime = Button(self.f6, image=schedule, command=calendario) btime.image = schedule btime.pack(side=RIGHT) etime = Entry(self.f6, textvariable=fecha, width=10) fecha.set(hoy) etime.pack(side=RIGHT) #ltime = Label(self.f6, text=hoy, font="bold", foreground='red') #ltime.pack(side=RIGHT) self.fi = Label(self.f6, text='Fecha Inicio: ') self.fi.pack(side=RIGHT) self.tab1.pack() #-----------------------> TAB 2 self.tab2 = Frame (self.nb) self.tab2.pack() self.f7 = Frame(self.tab2)#------------------------------------- self.f7.pack(fill=X, pady=10) notas = Text(self.f7, height=5) notas.pack(side=LEFT, fill=X, expand=1) self.f8 = Frame(self.tab2) self.f8.pack(pady=5,fill=X)#------------------------------------------- self.destino = Label(self.f8, text='Destinación:') self.destino.pack(side=LEFT) self.destinoE = Entry(self.f8, textvariable=destinacion, width=5) self.destinoE.pack(side=LEFT, fill=X, expand=1) self.f9 = Frame(self.tab2) self.f9.pack(pady=5,fill=X)#------------------------------------------- self.servicios = Label(self.f9, text='Servicios adicionales:') self.servicios.pack(side=LEFT) self.serviciosE = Entry(self.f9, textvariable=servicios, width=5) self.serviciosE.pack(side=LEFT, fill=X, expand=1) self.f10 = Frame(self.tab2) self.f10.pack(pady=5,fill=X)#------------------------------------------- self.conexos = Label(self.f10, text='Conexos:') self.conexos.pack(side=LEFT) self.conexosE = Entry(self.f10, textvariable=conexos, width=5) self.conexosE.pack(side=LEFT, fill=X, expand=1) #-----------------------> TAB 3 self.tab3 = Frame (self.nb) self.tab3.pack() self.f11 = Frame(self.tab3)#------------------------------------- self.f11.pack(fill=X, pady=5) self.cedula = Label (self.f11, text='CC/Nit: ') self.cedula.pack(side=LEFT) cedulaE = Entry(self.f11, textvariable=tercero, width=15) cedulaE.pack(side=LEFT) cedulaE.bind('<Return>', buscarT) b4 = Button(self.f11, image=lupa, command=topTercero) b4.image = lupa b4.pack(side=LEFT) self.f12 = Frame(self.tab3) #------------------------------------- self.f12.pack(fill=X, pady=5) self.tercero = Label (self.f12, text='Nombre: ') self.tercero.pack(side=LEFT) self.terceroE = Entry(self.f12, textvariable=nombret, width=5, state=DISABLED) self.terceroE.pack(side=LEFT, fill=X, expand=1) #-----------------------> TAB 4 self.tab4 = Frame (self.nb) self.tab4.pack() self.f13 = Frame(self.tab4) #------------------------------------- self.f13.pack(fill=X, pady=5) l = Label (self.f13, text='Aplicar a: ') l.pack(side=LEFT) Ch = Checkbutton(self.f13, text="Propietario", variable=aplicado) Ch.pack(side=LEFT) self.f14 = Frame(self.tab4) #------------------------------------- self.f14.pack(fill=X, pady=5) l13 = Label (self.f14, text='CC/Nit: ') l13.pack(side=LEFT) e13 = Entry(self.f14, textvariable=cc_aplicado, width=15) e13.pack(side=LEFT) b13 = Button(self.f14, image=lupa, command=None) b13.image = lupa b13.pack(side=LEFT) e13 = Entry(self.f14, textvariable=n_aplicado, state=DISABLED) e13.pack(side=LEFT, fill=X, expand=1) self.f15 = Frame(self.tab4) self.f15.pack(fill=X, pady=5)#------------------------------------ l14 = Label(self.f15, text='Cod.Inmueble:') l14.pack(side=LEFT) e14 = Entry(self.f15, textvariable=inm_aplicado, width=5, state=DISABLED) e14.pack(side=LEFT, fill=X, expand=1) self.f16 = Frame(self.tab4) self.f16.pack(fill=X, pady=5)#------------------------------------ l16 = Label(self.f16, text='Novedad:') l16.pack(side=LEFT, fill=X) e16 = Entry(self.f16, textvariable=novedad, width=15) e16.pack(side=LEFT) b16 = Button(self.f16, image=lupa, command=None) b16.image = lupa b16.pack(side=LEFT) e16 = Entry(self.f16, textvariable=n_nombre, state=DISABLED) e16.pack(side=LEFT, fill=X, expand=1) self.f17 = Frame(self.tab4) self.f17.pack(fill=X, pady=5)#------------------------------------ l17 = Label(self.f17, text='Vlr Novedad:') l17.pack(side=LEFT, fill=X) e17 = Entry(self.f17, textvariable=n_valor, width=15) e17.pack(side=LEFT) #--------------------------------------------------------------- self.nb.add (self.tab1, text="General") self.nb.add(self.tab2, text="Anexos") self.nb.add(self.tab3, text="Tercero") self.nb.add(self.tab4, text="Gasto fijo") self.nb.pack() self.fBtn = Frame(self.wrapper) self.fBtn.pack()#------------------------------- clean = Button(self.fBtn, text='Limpiar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=limpiar) clean.pack(side=RIGHT) update = Button(self.fBtn, text='Actualizar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=actualizar, state=DISABLED) update.pack(side=RIGHT) add = Button(self.fBtn, text='Agregar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=agregar) 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 CONTRATOS") 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) lb.bind("<Double-Button-1>", callback) self.wrap2 = Frame(self.aside) self.wrap2.pack() show = Button(self.wrap2, text='Cargar lista', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=cargar) show.pack(fill=X) delete = Button(self.wrap2, text='Borrar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=borrar) delete.pack(fill=X) edit = Button(self.wrap2, text='Modificar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=modificar) edit.pack(fill=X) buscador = Label(self.wrap2, text="Buscar por CC:") buscador.pack() E = Entry(self.wrap2, textvariable=busqueda, width=24) E.pack()
class ConnectGui: def __init__(self,root): root.title("Connect Four") self.turn= 1 self.last_piece= None self.p1= None self.p2= None frame = Frame(root) frame.pack(side=TOP) label1 = Label(frame, text="Player 1:") label1.pack(side= LEFT) self.combobox = Combobox(frame, values= ('Human', 'Minimax', 'Random')) self.combobox.pack(side=LEFT) label2 = Label(frame, text="Player 2:") label2.pack(side=LEFT) self.combobox1 = Combobox(frame, values= ('Human', 'Minimax','Random')) self.combobox1.pack(side= LEFT) frame2= Frame(root) frame2.pack(side=TOP) label3= Label(frame2, text= "(If Minimax Chosen) Ply-Depth:") label3.pack(side= LEFT) self.spinner = Spinbox(frame2,width=5,from_=2, to=5) self.spinner.pack(side= LEFT ) playbutton = Button(frame2, text= "Start Game", command= self.play_game) playbutton.pack(side= LEFT, padx= 20) frame1= Frame(root) frame1.pack(side=TOP) for x in range(7): button0 = Button(frame1, text= "Column %i" %(x+1), command = functools.partial(self.human_turn,x)) button0.grid(row=0, column= x) self.b= connectfour.ConnectFour() self.board= Canvas(frame1, width= 705, height= 605) self.board.grid(row= 1, columnspan=7) #for x in range(7): # self.board.create_line(5, x*100+5, 705,x*100+5) #for x in range(8): # self.board.create_line(x*100+5, 5, x*100+5, 605) def human_turn(self, col): assert self.p1 and self.p2!= None assert self.b.is_game_over()== None if self.b.board[5][col]== None: y= 0 while self.b.board[y][col]!= None: y+=1 self.b.play_turn(self.turn, col) if self.last_piece!= None: self.board.itemconfig(self.last_piece, outline= "black", width= 1) if self.turn== 1: self.last_piece= self.board.create_oval(100*col+5,505-100*y,100*col+105,605-100*y, fill= "red", outline= "green", width= 5) self.turn=2 if self.b.is_game_over()!= None: win= self.b.is_game_over() for i in range(4): self.board.create_oval(100*(win[1]+i*win[3])+5,505-100*(win[0]+i*win[2]),100*(win[1]+i*win[3])+105,605-100*(win[0]+i*win[2]), outline= "blue", width= 7) return if self.p2== "Human": pass elif self.p2== "Random": return self.random_turn() elif self.p2== "Minimax": return self.minimax_turn() elif self.turn==2: self.last_piece=self.board.create_oval(100*col+5,505-100*y,100*col+105,605-100*y, fill= "yellow", outline= "green", width= 5) self.turn=1 if self.b.is_game_over()!= None: win= self.b.is_game_over() for i in range(4): self.board.create_oval(100*(win[1]+i*win[3])+5,505-100*(win[0]+i*win[2]),100*(win[1]+i*win[3])+105,605-100*(win[0]+i*win[2]), outline= "blue", width= 7) return if self.p1== "Human": pass elif self.p1== "Random": return self.random_turn() elif self.p1== "Minimax": return self.minimax_turn() def random_turn(self): if self.last_piece!= None: self.board.itemconfig(self.last_piece, outline= "black", width= 1) cols = [] for col in range(7): if self.b.get_position(5, col) == None: cols.append(col) col= random.choice(cols) if self.b.board[5][col]== None: y= 0 while self.b.board[y][col]!= None: y+=1 self.b.play_turn(self.turn, col) if self.turn== 1: self.last_piece= self.board.create_oval(100*col+5,505-100*y,100*col+105,605-100*y, fill= "red", outline= "green", width= 5) self.turn=2 elif self.turn==2: self.last_piece=self.board.create_oval(100*col+5,505-100*y,100*col+105,605-100*y, fill= "yellow", outline= "green", width= 5) self.turn=1 if self.b.is_game_over()!= None: win= self.b.is_game_over() for i in range(4): self.board.create_oval(100*(win[1]+i*win[3])+5,505-100*(win[0]+i*win[2]),100*(win[1]+i*win[3])+105,605-100*(win[0]+i*win[2]), outline= "blue", width= 7) def minimax_turn(self): if self.last_piece!= None: self.board.itemconfig(self.last_piece, outline= "black", width= 1) player= minimax.MinimaxPlayer(playernum=self.turn, ply_depth=int(self.spinner.get()), utility=utility.WithColumnUtility(5, 10, [1, 2, 3, 4, 3, 2, 1])) root = minimax.MinimaxNode.init_root(self.b, self.turn) childval = player.minimax(root, 0) for child in root.children: if child.get_minimax_value() == childval: col= child.from_parent_column y=0 while self.b.board[y][col]!= None: y+=1 self.b.play_turn(self.turn, col) if self.turn== 1: self.last_piece= self.board.create_oval(100*col+5,505-100*y,100*col+105,605-100*y, fill= "red", outline= "green", width= 5) self.turn=2 elif self.turn==2: self.last_piece=self.board.create_oval(100*col+5,505-100*y,100*col+105,605-100*y, fill= "yellow", outline= "green", width= 5) self.turn=1 if self.b.is_game_over()!= None: win= self.b.is_game_over() for i in range(4): self.board.create_oval(100*(win[1]+i*win[3])+5,505-100*(win[0]+i*win[2]),100*(win[1]+i*win[3])+105,605-100*(win[0]+i*win[2]), outline= "blue", width= 7) return def play_game(self): self.board.delete(ALL) self.b= connectfour.ConnectFour() self.turn= 1 self.last_piece= None for x in range(7): self.board.create_line(5, x*100+5, 705,x*100+5) for x in range(8): self.board.create_line(x*100+5, 5, x*100+5, 605) self.p1= self.combobox.get() self.p2= self.combobox1.get() assert self.p1 and self.p2 != None assert self.p1 or self.p2== "Human" if self.p1== "Human": pass elif self.p1== "Random": self.random_turn() elif self.p1== "Minimax": self.minimax_turn()
class CMDHost(object): def __init__(self): # Styles self.style = MainWindowStyles() self.mw = Tk() self.setup() def setup(self): self.mw.title("Python Z-5212 Command Host " + c.port + ", " + c.baud) resize_and_center(self.mw, 800, 600) # Variables self.cmd_message = StringVar(self.mw, "--empty--") self.conn_status = StringVar(self.mw, '...') # Top Frame (name entry box, buttons, conn status) self.login_frame = Frame(self.mw, **self.style.Frame) self.lower_frame = Frame(self.mw, **self.style.Frame) self.login_frame.pack(side="top", fill="x") self.lower_frame.pack(side="top", fill="both", expand=1) # The lower left (message entry, chat history) and lower right self.left_frame = Frame(self.lower_frame, **self.style.Frame) self.right_frame = Frame(self.lower_frame, **self.style.Frame) self.right_frame.pack(side="right", fill="y") self.left_frame.pack(side="right", fill="both", expand=1) # The cmd entry & history frames self.message_frame = Frame(self.login_frame, **self.style.Frame) self.dialogue_frame = Frame(self.left_frame, **self.style.Frame) self.message_frame.pack(side="top", fill="x") self.dialogue_frame.pack(side="top", fill="both", expand=1) ### # Top Frame Widgets ### self.enter_Connecte_button = Button(self.login_frame, text="Connect", command=self.conn, **self.style.Button) self.enter_Connecte_button.pack(side="left", padx=5, pady=5) self.status_label = Label(self.login_frame, textvariable=self.conn_status, **self.style.Label).pack(side="left", padx=5, pady=5) self.enter_Connecte_button = Button(self.login_frame, text="Send CMD", command=self.send, **self.style.Button).pack( side="right", padx=5, pady=5) self.ports_Combobox = Combobox(self.login_frame, values=c.port, width=8) # assign function to combobox self.ports_Combobox.bind('<<ComboboxSelected>>', self.port_on_select) self.ports_Combobox.current(portindex) self.ports_Combobox.pack(side="left", padx=5, pady=5) self.baud_rate_Combo = Combobox(self.login_frame, values=c.baud, width=8) self.baud_rate_Combo.bind('<<ComboboxSelected>>', self.baud_rate_on_select) self.baud_rate_Combo.current(baudindex) self.baud_rate_Combo.pack(side="left", padx=5, pady=5) ### # Message Frame Widgets ### self.message_entry = Entry(self.message_frame, textvariable=self.cmd_message, state="disabled", **self.style.Entry) self.message_entry.pack( side="top", fill="x", padx=10, pady=10, expand=1, ) ### # commandlist Frame Widgets ### self.commandlist_label = Label(self.right_frame, text="SSI Command List", anchor="w", **self.style.Label) self.commandlist_label.pack(side="top", fill="x") self.commandlist = Scrolled( self.right_frame, Listbox, attributes=self.style.Listbox, scrollbar=self.style.Scrollbar, ) self.commandlist.pack(side="top", fill="both", expand=1) # Add command self.commandlist.widget.insert(END, "0x10 FLUSH_MACRO_PDF") self.commandlist.widget.insert(END, "0x11 ABORT_MACRO_PDF") self.commandlist.widget.insert(END, "0x12 CUSTOM_DEFAULTS") self.commandlist.widget.insert(END, "0x80 SSI_MGMT_COMMAND") self.commandlist.widget.insert(END, "0xA3 REQUEST_REVISION") self.commandlist.widget.insert(END, "0xA4 REPLY_REVISION") self.commandlist.widget.insert(END, "0xB0 Reserved") self.commandlist.widget.insert(END, "0xB1 IMAGE_DATA") self.commandlist.widget.insert(END, "0xB4 VIDEO_DATA") self.commandlist.widget.insert(END, "0xC0 ILLUMINATION_OFF") self.commandlist.widget.insert(END, "0xC1 ILLUMINATION_ON") self.commandlist.widget.insert(END, "0xC4 AIM_OFF") self.commandlist.widget.insert(END, "0xC5 AIM_ON") self.commandlist.widget.insert(END, "0xC6 PARAM_SEND") self.commandlist.widget.insert(END, "0xC7 PARAM_REQUEST") self.commandlist.widget.insert(END, "0xC8 PARAM_DEFAULTS") self.commandlist.widget.insert(END, "0xC9 CHANGE_ALL_CODE_TYPES") self.commandlist.widget.insert(END, "0xCA PAGER_MOTOR_ACTIVATION") self.commandlist.widget.insert(END, "0xD0 CMD_ACK") self.commandlist.widget.insert(END, "0xD1 CMD_NAK") self.commandlist.widget.insert(END, "0xD2 FLUSH_QUEUE") self.commandlist.widget.insert(END, "0xD3 CAPABILITIES_REQUEST") self.commandlist.widget.insert(END, "0xD4 CAPABILITIES_REPLY") self.commandlist.widget.insert(END, "0xD5 BATCH_REQUEST") self.commandlist.widget.insert(END, "0xD6 BATCH_DATA") self.commandlist.widget.insert(END, "0xD8 CMD_ACK_ACTION") self.commandlist.widget.insert(END, "0xE4 START_SESSION") self.commandlist.widget.insert(END, "0xE5 STOP_SESSION") self.commandlist.widget.insert(END, "0xE6 BEEP") self.commandlist.widget.insert(END, "0xE7 LED_ON") self.commandlist.widget.insert(END, "0xE8 LED_OFF") self.commandlist.widget.insert(END, "0xE9 SCAN_ENABLE") self.commandlist.widget.insert(END, "0xEA SCAN_DISABLE") self.commandlist.widget.insert(END, "0xEB SLEEP") self.commandlist.widget.insert(END, "0xF3 DECODE_DATA") self.commandlist.widget.insert(END, "0xF6 EVENT") self.commandlist.widget.insert(END, "0xF7 IMAGER_MODE") self.commandlist.widget.insert(END, "N/A WAKEUP") ### # Dialogue Frame Widgets ### self.dialogue_text = Scrolled( self.dialogue_frame, Text, attributes=self.style.Dialogue, scrollbar=self.style.Scrollbar, ) self.chat_styles(self.dialogue_text.widget) self.dialogue_text.pack(side="top", fill="both", padx=10, pady=0, expand=1) # Dummy junk messages = [ [["[JK] ", "Host"], ["Welcome to the JK SSI tool."]], [["[JK] ", "Host"], ["There are only a few rules:"]], [["[JK] ", "Host"], [" Be respectful and sensitive to me"]], [["[JK] ", "Host"], [" And HAVE FUN!"]], [["[JK] ", "Host"], [""]], [["[JK] ", "Host"], ["Termination of use can happen without warning!"]], [["[JK] ", "Host"], [""]], [["[JK] ", "Host"], ["JK SSI Tool version v0.01"]], ] for line in messages: self.insert_readonly(self.dialogue_text, 0.0, "\n") line.reverse() for part in line: self.insert_readonly(self.dialogue_text, 0.0, *part) #self.insert_readonly(self.dialogue_text, END, "[Admin]", "admin") @staticmethod def chat_styles(widget): """Configure chat text styles.""" # User colors widget.tag_configure("user", foreground="#FFFFFF") widget.tag_configure("guest", foreground="#FF9900") widget.tag_configure("admin", foreground="#00FFFF") widget.tag_configure("server", foreground="#00FF00") widget.tag_configure("client", foreground="#FF0000") def insert_readonly(self, widget, *args): """Insert text into a readonly (disabled) widget.""" widget.widget.configure(state="normal") widget.widget.insert(*args) widget.widget.configure(state="disabled") def start(self): self.mw.mainloop() def exit(self): self.serConnector.close() def conn(self): self.serConnector = connect(c) serConnector = self.serConnector if serConnector.is_open: self.conn_status.set('Open') else: self.conn_status.set('Connect fail') def send(self): value = self.commandlist.getSelectedIndex() print(self.commandlist.get(value)) def baud_rate_on_select(self, event=None): print("event.widget:", event.widget.get()) def port_on_select(self, event=None): print("event.widget:", event.widget.get())
class App: def __init__(self, master,cam): self.cam = cam self.master = master self.frame = None self.canvas = None self.histCanvas = None self.video = None self.position = None ##window frame self.frame = tk.LabelFrame(self.master,text='Captured video') self.frame.pack() ##toolbar self.toolbar = tk.Frame(self.master) self.toolbar.configure(background='grey',borderwidth=2) self.toolbar.pack(side=tk.BOTTOM,padx=5,pady=5) #),expand=tk.YES,fill=tk.BOTH) ##adding buttons to toolbar self.button = tk.Button(self.toolbar, text="QUIT", fg="red", command=master.destroy) self.button.configure(background='tan') self.button.pack(side=tk.LEFT,padx=5, pady=5) ## ttk Combobox self.efLabel = Labelframe(self.toolbar, text="Choose an effect:") self.efLabel.pack(anchor = tk.W, padx=5, pady=2) self.efCombo = Combobox(self.efLabel, values = ['none','erode','smooth','dilate','laplace','threshold_otsu'], state='readonly') self.efCombo.current(0) self.efCombo.bind('<FocusIn>', self._update_values) self.efCombo.pack(anchor=tk.NW,padx=5, pady=5) ##fps ## for using of command binding see: 'Thinkink in Tkinter' tt077.py self.camon = tk.Button(self.toolbar, text="CAM on", fg="darkgreen", command=lambda: self.video.setOnoff(True)) self.camon.configure(background='tan') self.camon.pack(side=tk.LEFT,padx=5, pady=5) self.camoff = tk.Button(self.toolbar, text="CAM off", fg="blue", command=lambda: self.video.setOnoff(False)) self.camoff.configure(background='tan') self.camoff.pack(side=tk.LEFT,padx=5, pady=5) self.detector = tk.Button(self.toolbar, text="detect face", fg="blue", command=lambda: self.video.setDetection()) self.detector.configure(background='tan') self.detector.pack(side=tk.LEFT,padx=5, pady=5) self.effect = tk.Button(self.toolbar, text="effect", fg="yellow", command=lambda: self.video.setEffect(self.efCombo.get())) self.effect.configure(background='tan') self.effect.pack(side=tk.LEFT,padx=5, pady=5) self.hi_there = tk.Button(self.toolbar, text="Hello") #, command=self.say_hi) self.hi_there.bind("<Control-Button-1>", self.say_hi) #event binding self.hi_there.configure(background='tan') self.hi_there.pack(side=tk.LEFT,padx=5, pady=5) ##canvas to draw on self.canvas = tk.Canvas(self.frame, width=620,height=460) self.canvas.configure(background="black",relief='ridge',highlightthickness=5,borderwidth=5) self.canvas.pack(side=tk.RIGHT,padx=5,pady=5) #(expand=tk.YES,fill=tk.BOTH) ##canvas to draw histogram self.histLabel = Labelframe(self.frame, text="Histogram") self.histLabel.pack(anchor = tk.W, padx=5, pady=2) self.histCanvas = tk.Canvas(self.histLabel, width=300,height=240) self.histCanvas.configure(background="black",relief='ridge',highlightthickness=5,borderwidth=5) self.histCanvas.pack(side=tk.TOP,padx=5,pady=5) ##sliders var=tk.DoubleVar() self.contrast = tk.Scale(self.frame, orient=tk.HORIZONTAL, label='Contrast',variable=var,resolution=0.5,from_=0.0, to=100.0, command=self._update_contrast) self.contrast.pack(side=tk.LEFT, anchor=tk.NW, padx=5, pady=5) self.brightness = tk.Scale(self.frame, orient=tk.HORIZONTAL, label='Brightness',from_=0, to=100, command=self._update_brightness) #self.brightness.bind('<FocusIn>', self._update_brightness) self.brightness.pack(side=tk.LEFT, anchor=tk.NW, padx=5, pady=5) ##position label self.position = tk.StringVar() self.xyLabel = tk.Label(self.toolbar, textvariable = self.position, fg='red',width=30,justify='left').pack(padx=1, pady=5) ##set the camera self.video = Camera(self.cam,self.master,self.canvas,self.histCanvas,self.frame,self.position) self.video.setOnoff(False) ##============================================================================== ##pooling video from camera def pool(self): if self.video != None: self.id=self.master.after(33,lambda: self.video.update_video()) ## self.master.after(50, lambda: self.pool()) ##============================================================================== ##for test purposes only def say_hi(self, event): print "hi there, everyone!" ##============================================================================== ##combo event def _update_values(self, evt): # add entered text to combobox list of values widget = evt.widget # get widget txt = widget.get() # get current text #vals = widget.cget('values') # get values print txt #print vals ##for editable widgets: update list of items with entered value ## if not vals: ## widget.configure(values = (txt, )) ## elif txt not in vals: ## widget.configure(values = vals + (txt, )) return 'break' # don't propagate event ##============================================================================== def _update_brightness(self, val): self.video.setBrightness(float(val)) ##============================================================================== def _update_contrast(self, val): self.video.setContrast(float(val))
# Create a list of choices groceries = ['Eggs', 'Milk', 'Bread', 'Coffee', 'Tea', 'Lettuce', 'Tomatoes', 'Onions', 'Chicken', 'Cheese', 'Fish', 'Sugar', 'Rice', 'Pasta', 'Soup', 'Cereal', 'Yogurt'] # Function to display the current choice when the button is pushed def display_choice(): shopping_list.insert(END, choices.get() + '\n') # Create a text area to display the user's choice shopping_list = Text(window, width = 30, height = 10, borderwidth = 2, relief = 'groove') # Create a combo box widget whose parent container is the # window choices = Combobox(window, values = groceries) # Create a button to push when the user is happy with their choice add_to_list = Button(window, text = 'Add to list', command = display_choice) # Use the geometry manager to "pack" the widgets onto # the window (with a margin around the widgets for neatness) margin_size = 5 shopping_list.pack(padx = margin_size, pady = margin_size) choices.pack(pady = margin_size) add_to_list.pack(pady = margin_size) # Start the event loop to react to user inputs window.mainloop()
class App: def __init__(self, master, cam): self.cam = cam self.master = master self.frame = None self.canvas = None self.histCanvas = None self.video = None self.position = None ##window frame self.frame = tk.LabelFrame(self.master, text='Captured video') self.frame.pack() ##toolbar self.toolbar = tk.Frame(self.master) self.toolbar.configure(background='grey', borderwidth=2) self.toolbar.pack(side=tk.BOTTOM, padx=5, pady=5) # ),expand=tk.YES,fill=tk.BOTH) ##adding buttons to toolbar self.button = tk.Button(self.toolbar, text="QUIT", fg="red", command=master.destroy) self.button.configure(background='tan') self.button.pack(side=tk.LEFT, padx=5, pady=5) ## ttk Combobox self.efLabel = Labelframe(self.toolbar, text="Choose an effect:") self.efLabel.pack(anchor=tk.W, padx=5, pady=2) self.efCombo = Combobox(self.efLabel, values=['none', 'erode', 'smooth', 'dilate', 'laplace', 'threshold_otsu'], state='readonly') self.efCombo.current(0) self.efCombo.bind('<FocusIn>', self._update_values) self.efCombo.pack(anchor=tk.NW, padx=5, pady=5) ##fps ## for using of command binding see: 'Thinkink in Tkinter' tt077.py self.camon = tk.Button(self.toolbar, text="CAM on", fg="darkgreen", command=lambda: self.video.setOnoff(True)) self.camon.configure(background='tan') self.camon.pack(side=tk.LEFT, padx=5, pady=5) self.camoff = tk.Button(self.toolbar, text="CAM off", fg="blue", command=lambda: self.video.setOnoff(False)) self.camoff.configure(background='tan') self.camoff.pack(side=tk.LEFT, padx=5, pady=5) self.detector = tk.Button(self.toolbar, text="detect face", fg="blue", command=lambda: self.video.setDetection()) self.detector.configure(background='tan') self.detector.pack(side=tk.LEFT, padx=5, pady=5) self.effect = tk.Button(self.toolbar, text="effect", fg="yellow", command=lambda: self.video.setEffect(self.efCombo.get())) self.effect.configure(background='tan') self.effect.pack(side=tk.LEFT, padx=5, pady=5) self.hi_there = tk.Button(self.toolbar, text="Hello") # , command=self.say_hi) self.hi_there.bind("<Control-Button-1>", self.say_hi) # event binding self.hi_there.configure(background='tan') self.hi_there.pack(side=tk.LEFT, padx=5, pady=5) ##canvas to draw on self.canvas = tk.Canvas(self.frame, width=620, height=460) self.canvas.configure(background="black", relief='ridge', highlightthickness=5, borderwidth=5) self.canvas.pack(side=tk.RIGHT, padx=5, pady=5) # (expand=tk.YES,fill=tk.BOTH) ##canvas to draw histogram self.histLabel = Labelframe(self.frame, text="Histogram") self.histLabel.pack(anchor=tk.W, padx=5, pady=2) self.histCanvas = tk.Canvas(self.histLabel, width=300, height=240) self.histCanvas.configure(background="black", relief='ridge', highlightthickness=5, borderwidth=5) self.histCanvas.pack(side=tk.TOP, padx=5, pady=5) ##sliders var = tk.DoubleVar() self.contrast = tk.Scale(self.frame, orient=tk.HORIZONTAL, label='Contrast', variable=var, resolution=0.5, from_=0.0, to=100.0, command=self._update_contrast) self.contrast.pack(side=tk.LEFT, anchor=tk.NW, padx=5, pady=5) self.brightness = tk.Scale(self.frame, orient=tk.HORIZONTAL, label='Brightness', from_=0, to=100, command=self._update_brightness) # self.brightness.bind('<FocusIn>', self._update_brightness) self.brightness.pack(side=tk.LEFT, anchor=tk.NW, padx=5, pady=5) ##position label self.position = tk.StringVar() self.xyLabel = tk.Label(self.toolbar, textvariable=self.position, fg='red', width=30, justify='left').pack( padx=1, pady=5) ##set the camera self.video = Camera(self.cam, self.master, self.canvas, self.histCanvas, self.frame, self.position) self.video.setOnoff(False) ##============================================================================== ##pooling video from camera def pool(self): if self.video != None: self.id = self.master.after(33, lambda: self.video.update_video()) ## self.master.after(50, lambda: self.pool()) ##============================================================================== ##for test purposes only def say_hi(self, event): print "hi there, everyone!" ##============================================================================== ##combo event def _update_values(self, evt): # add entered text to combobox list of values widget = evt.widget # get widget txt = widget.get() # get current text # vals = widget.cget('values') # get values print txt # print vals ##for editable widgets: update list of items with entered value ## if not vals: ## widget.configure(values = (txt, )) ## elif txt not in vals: ## widget.configure(values = vals + (txt, )) return 'break' # don't propagate event ##============================================================================== def _update_brightness(self, val): self.video.setBrightness(float(val)) ##============================================================================== def _update_contrast(self, val): self.video.setContrast(float(val))
class Window(Tk): def __init__(self): Tk.__init__(self) # Global Elements self.main_color = '#333333' self.sub_color = '#444444' self.the_file = None self.upper_list = [ 'SELECT', 'FROM', 'ORDER', 'GROUP', 'BY', 'IS', 'NULL', 'ISNULL', 'NOTNULL', 'TRUE', 'FALSE', 'JOIN', 'LEFT', 'RIGHT', 'WHERE', 'HAVING', 'PARTITION', 'OVER', 'WITH', 'AS', 'NOT', 'AND', 'OR', 'ON', 'IN', 'BETWEEN', 'UNBOUNDED', 'PROCEEDING', 'FOLLOWING', 'UNION', 'ALL', 'CASE', 'WHEN', 'THEN', 'ELSE', 'END', 'COALESCE', 'NVL', 'AVG', 'MAX', 'SUM', 'COUNT', 'WITHIN', 'LISTAGG' ] text_box_font_options = { 'name': [ 'none', 'Courier', 'Georgia', 'Gothic', 'Impact', 'System', 'Tahoma', 'Times', 'Verdana' ], 'size': [] } for num in range(6, 101): text_box_font_options['size'].append(num) # Program attributes self.state('zoomed') # starts maximized self.title('Casing Formatter') self.config(bg=self.main_color) # Frames self.main_frame = Frame(self, bg=self.main_color, width=600, height=400) self.main_frame.pack(side=TOP, fill=BOTH, expand=TRUE) self.button_frame = Frame(self.main_frame, bg=self.main_color) self.button_frame.pack(side=LEFT, fill=BOTH) self.text_frame = Frame(self.main_frame, bg=self.main_color) self.text_frame.pack( side=LEFT, fill=BOTH, expand=TRUE, ) # Scrollbar self.text_scrollbar = Scrollbar(self.main_frame) self.text_scrollbar.pack(side=RIGHT, fill=BOTH) # Buttons button_font = 'helvetica 18 bold' self.open_file_button = Button(self.button_frame, text='Open File', command=self.open_file, font='helvetica 14', relief=RAISED, bg='deepskyblue4', fg='white') self.open_file_button.pack(side=TOP, padx=5, pady=4) self.upper_button = Button(self.button_frame, text='A', width=3, command=self.cap_file, font=button_font, relief=RAISED, bg=self.sub_color, fg='white') self.upper_button.pack(side=TOP, padx=5, pady=4) self.lower_button = Button(self.button_frame, text='a', width=3, command=self.lower_file, font=button_font, relief=RAISED, bg=self.sub_color, fg='white') self.lower_button.pack(side=TOP, padx=5, pady=4) self.semi_lower_button = Button(self.button_frame, text='Ab', width=3, command=self.semi_lower_file, font=button_font, relief=RAISED, bg=self.sub_color, fg='white') self.semi_lower_button.pack(side=TOP, padx=5, pady=4) self.semi_lower_button = Button(self.button_frame, text='Apply Font', command=self.text_box_font, font='helvetica 14', relief=RAISED, bg=self.sub_color, fg='white') self.semi_lower_button.pack(side=BOTTOM, padx=5, pady=4) # Font drop-down menus self.font_name_dropdown = Combobox( self.button_frame, values=text_box_font_options['name'], justify='center') self.font_name_dropdown.set(text_box_font_options['name'][0]) self.font_name_dropdown.pack(side=BOTTOM, padx=5, pady=4) self.font_style = self.font_name_dropdown.get() self.font_size_dropdown = Combobox( self.button_frame, values=text_box_font_options['size'], justify='center') self.font_size_dropdown.set(12) self.font_size_dropdown.pack(side=BOTTOM, padx=5, pady=4) self.text_font_size = self.font_size_dropdown.get() # Text boxes self.text_box_before = Text(self.text_frame, relief=SUNKEN, bg=self.sub_color, fg='grey', font=(self.font_style, self.text_font_size), wrap=WORD, yscrollcommand=self.text_scrollbar.set) self.text_box_before.pack(side=LEFT, fill=BOTH, expand=TRUE, padx=2) self.text_box_after = Text(self.text_frame, relief=SUNKEN, bg=self.sub_color, fg='grey', font=(self.font_style, self.text_font_size), wrap=WORD, yscrollcommand=self.text_scrollbar.set) self.text_box_after.pack(side=LEFT, fill=BOTH, expand=TRUE, padx=2) self.text_scrollbar.config(command=self.yview) # Bottom Status bar self.status_text = StringVar() self.status_text.set('') self.status_label = Label(self, textvariable=self.status_text, relief=SUNKEN, font='system 8', fg='#333333') self.status_label.pack(side=BOTTOM, fill=X) def yview(self, *args): # Used to make both text boxes scroll at the same time self.text_box_before.yview(*args) self.text_box_after.yview(*args) def create_output_file(self): # This allows you to choose a directory for the output file self.savedir = tkFileDialog.askdirectory( title='Select folder to save results') if self.savedir != '': self.output_file = open(self.savedir + '/' + self.open_file, 'w') else: self.status_text.set('') self.status_label.config(bg='white') def cap_file(self): if self.the_file != None: sql_file = self.the_file.read() self.create_output_file() self.output_file.write(sql_file.upper()) self.output_file.close() new_sql_file = open(self.savedir + '/' + self.open_file, 'r') self.text_box_before.insert(END, sql_file) self.text_box_after.insert(END, new_sql_file.read()) new_sql_file.close() self.status_text.set('Saved as: ' + self.open_file) self.status_label.config(bg='#777777') self.text_color() def lower_file(self): if self.the_file != None: sql_file = self.the_file.read() self.create_output_file() self.output_file.write(sql_file.lower()) self.output_file.close() new_sql_file = open(self.savedir + '/' + self.open_file, 'r') self.text_box_before.insert(END, sql_file) self.text_box_after.insert(END, new_sql_file.read()) new_sql_file.close() self.status_text.set('Saved as: ' + self.open_file) self.status_label.config(bg='#777777') self.text_color() def semi_lower_file(self): if self.the_file != None: sql_file = self.the_file.read() temp_split = sql_file.split(' ') sql_file_formatted = [] for item in temp_split: for word in re.sub(r'[^A-Za-z0-9._]', '\n', item).split('\n'): if word.upper() in self.upper_list: item = item.replace(word, word.upper()) else: item = item.replace(word, word.lower()) sql_file_formatted.append(item) sql_file_formatted = ' '.join(sql_file_formatted) self.create_output_file() self.output_file.write(sql_file_formatted) self.output_file.close() new_sql_file = open(self.savedir + '/' + self.open_file, 'r') self.text_box_before.insert(END, sql_file) self.text_box_after.insert(END, new_sql_file.read()) new_sql_file.close() self.status_text.set('Saved as: ' + self.open_file) self.status_label.config(bg='#777777') self.text_color() def open_file(self): self.text_box_before.delete(1.0, END) self.text_box_after.delete(1.0, END) self.the_file = tkFileDialog.askopenfile( parent=self, mode='r', title='Choose a file to format...') if self.the_file != None: self.open_file = re.sub( r'[^A-Za-z0-9._]', '', str(self.the_file).split(' ')[2].split('/')[-1]) self.status_text.set('Selected: ' + self.open_file) self.status_label.config(bg='lightblue') else: self.status_text.set('') self.status_label.config(bg='white') return self.the_file def text_color(self): # Colors the words in the before and after text boxes, for the words that are in the upper list temp_split = self.text_box_after.get(1.0, END) temp_split = temp_split.split('\n') line_count = 0 for line in temp_split: line_count += 1 temp_list = re.sub(r'[^A-Za-z0-9._]', ' ', line).split(' ') recon = [] for item in temp_list: recon.append(item) letter = len(' '.join(recon)) if item.upper() in self.upper_list: self.text_box_after.tag_add( "start", str(line_count) + "." + str(letter - len(item)), str(line_count) + "." + str(letter)) self.text_box_after.tag_config("start", foreground='orange', font=(self.font_style, self.text_font_size, ' bold')) self.text_box_before.tag_add( "start", str(line_count) + "." + str(letter - len(item)), str(line_count) + "." + str(letter)) self.text_box_before.tag_config("start", foreground='orange', font=(self.font_style, self.text_font_size, ' bold')) def text_box_font(self): self.text_box_after.tag_add("font", 1.0, END) self.text_box_after.tag_config("font", font=(self.font_name_dropdown.get(), self.font_size_dropdown.get())) self.text_box_before.tag_add("font", 1.0, END) self.text_box_before.tag_config("font", font=(self.font_name_dropdown.get(), self.font_size_dropdown.get()))
def InitializeUI(self): self.parent.title("PiCamera Interface") self.style = Style() self.style.theme_use("clam") # default, clam, alt, classic self.pack(fill=BOTH, expand=1) # Layout frameResolution = Frame(self, relief=RAISED, borderwidth=1) frameOptions = Frame(self, relief=RAISED, borderwidth=1) frameOptions1 = Frame(frameOptions, relief=RAISED, borderwidth=1) frameOptions2 = Frame(frameOptions, relief=RAISED, borderwidth=1) frameOptions3 = Frame(frameOptions, relief=RAISED, borderwidth=1) frameScales = Frame(self, relief=RAISED, borderwidth=1) frameButtons = Frame(self, relief=RAISED, borderwidth=1) # # CAMERA OPTIONS # # Left Frame []-- labelOptions1 = Label(frameOptions1, text="Exposure Modes") comboExpoOpt = Combobox(frameOptions1, state='readonly', textvariable=self._expoOpt, width=12) comboExpoOpt['values'] = ('off', 'auto', 'night', 'nightpreview', 'backlight', 'spotlight', 'sports', 'snow', 'beach', 'verylong', 'fixedfps', 'antishake', 'fireworks') # Center Frame -[]- labelOptions2 = Label(frameOptions2, text="Image Effects") comboImageOpt = Combobox(frameOptions2, state='readonly',textvariable=self._imageOpt, width=12) comboImageOpt['values'] = ('none', 'negative', 'solarize', 'sketch', 'denoise', 'emboss', 'oilpaint', 'hatch', 'gpen', 'pastel', 'watercolor', 'film', 'blur', 'saturation', 'colorswap', 'washedout', 'posterise', 'colorpoint', 'colorbalance', 'cartoon', 'deinterlace1', 'deinterlace2') # Right Frame --[] labelOptions3 = Label(frameOptions3, text="Misc. Options") check1 = Checkbutton(frameOptions3, text="Flip Horizontally", variable=self._hflip, onvalue=True, offvalue=False, padx=4, pady=4) check2 = Checkbutton(frameOptions3, text="Flip Vertically", variable=self._vflip, onvalue=True, offvalue=False, padx=4, pady=4) # Pack frameOptions frameOptions.pack(fill=BOTH, side=TOP) frameOptions1.pack(fill=BOTH, side=LEFT, expand=True) frameOptions2.pack(fill=BOTH, side=LEFT, expand=True) frameOptions3.pack(fill=BOTH, side=LEFT, expand=True) labelOptions1.pack(side=TOP) labelOptions2.pack(side=TOP) labelOptions3.pack(side=TOP) comboExpoOpt.pack(side=TOP) comboImageOpt.pack(side=TOP) check1.pack(side=TOP) check2.pack(side=TOP) # # PICTURE RESOLUTION # labelResolution = Label(frameResolution, text="Picture Resolution") R1 = Radiobutton(frameResolution, text="640 x 480", variable=self._resolution, value=1, padx=8, pady=8) R2 = Radiobutton(frameResolution, text="1280 x 720", variable=self._resolution, value=2, padx=8, pady=8) R3 = Radiobutton(frameResolution, text="1920 x 1080", variable=self._resolution, value=3, padx=8, pady=8) R4 = Radiobutton(frameResolution, text="2592 x 1944", variable=self._resolution, value=4, padx=8, pady=8) # Pack frameResolution frameResolution.pack(fill=BOTH, side=TOP) labelResolution.pack(fill=BOTH, side=TOP) R1.pack(side=LEFT) R2.pack(side=LEFT) R3.pack(side=LEFT) R4.pack(side=LEFT) # # SCALABLE SETTINGS (sliders) # labelScales = Label(frameScales, text="Scalable Settings") scaleRecord = Scale(frameScales, label="Recording Time (sec)", variable=self._recordTime, resolution=0.5, from_=5, to=30, orient=HORIZONTAL, length=400) scalePreview = Scale(frameScales, label="Preview Time (sec)", variable=self._previewTime, resolution=0.1, from_=1, to=10, orient=HORIZONTAL, length=400) scaleBright = Scale(frameScales, label="Brightness", variable=self._brightness, resolution=1, from_=0, to=100, orient=HORIZONTAL, length=400) scaleContrast = Scale(frameScales, label="Contrast", variable=self._contrast, resolution=1, from_=-100, to=100, orient=HORIZONTAL, length=400) # Pack frameScales frameScales.pack(fill=BOTH, side=TOP) labelScales.pack(fill=BOTH, side=TOP) scaleRecord.pack(side=TOP) scalePreview.pack(side=TOP) scaleBright.pack(side=TOP) scaleContrast.pack(side=TOP) # # BUTTONS # labelSpacer = Label(frameButtons) quitButton = Button(frameButtons, text="Quit", command=quit) button1 = Button(frameButtons, text="Take Picture", command=self.Picture) button2 = Button(frameButtons, text="Take Video", command=self.Video) button3 = Button(frameButtons, text="Defaults", command=self.Defaults) if _debug == True: buttonDebug = Button(frameButtons, text="DEBUG", command=self.Debug) # Pack frameButtons frameButtons.pack(fill=BOTH, side=TOP, expand=True) labelSpacer.pack() button1.pack(side=LEFT, anchor=NW) button2.pack(side=LEFT, anchor=NW) button3.pack(side=LEFT, anchor=NW) quitButton.pack(side=RIGHT, anchor=NE) if _debug == True: buttonDebug.pack(side=RIGHT, anchor=NE) # Start with default settings self.Defaults()
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 =========================== """
def __init__(self, parent, controller): Frame.__init__(self, parent) #VARIABLES GLOBALES global cedula, titulo, ingreso, rsocial, residencia, nombres, apellidos, direccion, telefono, oficina, tel, telfax, correo, cumpleanos, dia, mes, envio, celular, tipopersona, comision, retefuente, reteiva, gcontribuyente, gfactura, gcheque, reprecc, reprenombres, repredireccion, repretelefono, repreoficina, repretel, reprebanco, repretcuenta, reprenumcuenta, tit1cc, tit1nombres, tit1banco, tit1tcuenta, tit1numcuenta, tit2cc, tit2nombres, tit2banco, tit2tcuenta, tit2numcuenta, lb, note, popmenu, busqueda, dato, E #INSTANCIEAS DE LOS WIDGETS global ccE, refE, dateinE, socialE, cityE, nameE, lnameE, adressE, phoneE, officeE, officetelE, telfaxE, emailE, birthdayE, birthdayCbx, mailE, mobileE, personR1, personR2, comisionE, Ch1, Ch2, Ch3, Ch4, Ch5, note, cc0E, name0E, adress0E, phone0E, office0E, officetel0E, bank0Cbx, tbank0Cbx, tcuenta0E, cc1E, name1E, bank1Cbx, tbank1Cbx, tcuenta1E, cc2E, name2E, bank2Cbx, tbank2Cbx, tcuenta2E, add, update, delete, clean global info, lists, _propietarios _propietarios = dict() lists = [] #Variables cedula = StringVar() titulo = StringVar() ingreso = StringVar() rsocial = StringVar() residencia = StringVar() nombres = StringVar() apellidos = StringVar() direccion = StringVar() telefono = StringVar() oficina = StringVar() tel = StringVar() telfax = StringVar() correo = StringVar() dia = IntVar() mes = StringVar() envio = StringVar() celular = StringVar() tipopersona = IntVar() comision = DoubleVar() retefuente = IntVar() reteiva = IntVar() gcontribuyente = IntVar() gfactura = IntVar() gcheque = IntVar() notas = StringVar() #---------------------------- reprecc = StringVar() reprenombres = StringVar() repredireccion = StringVar() repretelefono = StringVar() repreoficina = StringVar() repretel = StringVar() reprebanco = StringVar() repretcuenta = StringVar() reprenumcuenta = StringVar() tit1cc = StringVar() tit1nombres = StringVar() tit1banco = StringVar() tit1tcuenta = StringVar() tit1numcuenta = StringVar() tit2cc = StringVar() tit2nombres = StringVar() tit2banco = StringVar() tit2tcuenta = StringVar() tit2numcuenta = StringVar() meses = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto","Septiembre", "Octubre", "Noviembre", "Diciembre"] tbancos = ['Bancolombia', "Banco Bogotá", "Banco Agrario", "Banco Occidente"] tbanktype = ['Corriente','Ahorro'] #BUSQUEDA = ["Nombre","CC/Nit"] busqueda = StringVar() busqueda.trace("w", lambda name, index, mode: buscar()) info = IntVar() #eleccion = IntVar() dato = StringVar() # MENU DEL MOUSE popmenu = Menu(self, tearoff=0) popmenu.add_command(label="Imprimir", command=hello) popmenu.add_command(label="Cargar", command=modificar) popmenu.add_command(label="Eliminar", command=borrar) #popmenu.add_separator() popmenu.bind('<Escape>', release) #WIDGETS #========================= HEADER ============================== self.header = Label(self, text="GESTIÓN DE PROPIETARIOS", font="bold") self.header.pack(pady=20, side=TOP) #========================== WRAPPER ============================ #Contiene los Notebooks con los campos formulario self.wrapper = Frame (self) self.wrapper.pack(side=LEFT, fill=Y) #Esto centro el wrapper #self.wrapper.pack(side=LEFT, fill=BOTH, expand=True) #================ NOTEBOOK =============> self.nb = Notebook(self.wrapper) #-----------------------> TAB 1 self.tab1 = Frame (self.nb) self.f0 = Frame(self.tab1)#Para dejar espacio entre Tab y Label self.f0.pack(fill=X, pady=10)#------------------------------- #========================= PERSONALES ========================== self.f1 = Frame(self.tab1)#------------------------------- self.f1.pack(pady=5,fill=X) self.ccL = Label(self.f1, text='CC/Nit:') self.ccL.pack(side=LEFT) ccE = Entry(self.f1, textvariable=cedula) ccE.pack(side=LEFT, fill=X, expand=1) ccE.focus_set() self.refL = Label(self.f1, text='Título:') self.refL.pack(side=LEFT) refE = Entry(self.f1, textvariable=titulo, width=10) refE.pack(side=LEFT) #refE.bind("<KeyRelease>", caps) self.dateinL = Label(self.f1, text='Fecha Ingreso:') self.dateinL.pack(side=LEFT) dateinE = Entry(self.f1, textvariable=ingreso, width=10, state=DISABLED) ingreso.set("0000-00-00") dateinE.pack(side=LEFT) self.f2 = Frame(self.tab1)#------------------------------- self.f2.pack(pady=5,fill=X) self.socialL = Label(self.f2, text='Razón Social:') self.socialL.pack(side=LEFT) socialE = Entry(self.f2, textvariable=rsocial) socialE.pack(side=LEFT, fill=X, expand=1) socialE.bind("<KeyRelease>", caps) self.cityL = Label(self.f2, text='Ciudad de residencia:') self.cityL.pack(side=LEFT) cityE = Entry(self.f2, textvariable=residencia, width=15) cityE.pack(side=LEFT) cityE.bind("<KeyRelease>", caps) self.f3 = Frame(self.tab1) self.f3.pack(pady=5,fill=X)#----------------------------------------- self.nameL = Label(self.f3, text='Nombres:') self.nameL.pack(side=LEFT) nameE = Entry(self.f3, textvariable=nombres) nameE.pack(side=LEFT, fill=X, expand=1) nameE.bind("<KeyRelease>", caps) self.lnameL = Label(self.f3, text='Apellidos:') self.lnameL.pack(side=LEFT) lnameE = Entry(self.f3, textvariable=apellidos) lnameE.pack(side=LEFT, fill=X, expand=1) lnameE.bind("<KeyRelease>", caps) self.f4 = Frame(self.tab1) self.f4.pack(pady=5,fill=X)#----------------------------------------- self.adressL = Label(self.f4, text='Dir. Casa:') self.adressL.pack(side=LEFT) adressE = Entry(self.f4, textvariable=direccion) adressE.pack(side=LEFT, fill=X, expand=1) adressE.bind("<KeyRelease>", caps) self.phoneL = Label(self.f4, text='Tel:') self.phoneL.pack(side=LEFT) phoneE = Entry(self.f4, textvariable=telefono, width=20) phoneE.pack(side=LEFT) self.f5 = Frame(self.tab1) self.f5.pack(pady=5,fill=X)#------------------------------------ self.officeL = Label(self.f5, text='Dir. Oficina:') self.officeL.pack(side=LEFT) officeE = Entry(self.f5, textvariable=oficina, width=20) officeE.pack(side=LEFT, fill=X, expand=1) officeE.bind("<KeyRelease>", caps) self.officetelL = Label(self.f5, text='Tel:') self.officetelL.pack(side=LEFT) officetelE = Entry(self.f5, textvariable=tel, width=15) officetelE.pack(fill=X, side=LEFT) self.telfaxL = Label(self.f5, text='Tel. Fax:') self.telfaxL.pack(side=LEFT) telfaxE = Entry(self.f5, textvariable=telfax, width=10) telfaxE.pack(side=LEFT) self.f6 = Frame(self.tab1) self.f6.pack(pady=5,fill=X)#------------------------------------ self.emailL = Label(self.f6, text='Email:') self.emailL.pack(side=LEFT) emailE = Entry(self.f6, textvariable=correo, width=30) emailE.pack(side=LEFT) self.birthdayL = Label(self.f6, text='Cumpleaños:') self.birthdayL.pack(side=LEFT) self.birthdayL2 = Label(self.f6, text='Día:') self.birthdayL2.pack(padx=5,side=LEFT) #s = Spinbox(self.f6, from_=1, to=31,textvariable=dia, width=3) #s.pack(side=LEFT) birthdayE = Entry(self.f6, textvariable=dia, width=3) birthdayE.pack(side=LEFT) self.birthdayL3 = Label(self.f6, text='Mes:') self.birthdayL3.pack(padx=5,side=LEFT) birthdayCbx = Combobox(self.f6, textvariable=mes, values=meses, width=10) birthdayCbx.set('Enero') birthdayCbx.pack(side=LEFT) self.f7 = Frame(self.tab1) self.f7.pack(pady=5,fill=X)#------------------------------------ self.mailL = Label(self.f7, text='Dir. Correspondencia:') self.mailL.pack(side=LEFT) mailE = Entry(self.f7, textvariable=envio) mailE.pack(side=LEFT, fill=X, expand=1) mailE.bind("<KeyRelease>", caps) self.mobileL = Label(self.f7, text='Celular:') self.mobileL.pack(side=LEFT) mobileE = Entry(self.f7, textvariable=celular, width=10) mobileE.pack(side=LEFT, fill=X, expand=1) self.f8 = Frame(self.tab1) self.f8.pack(pady=5,fill=X)#------------------------------------ self.personL = Label(self.f8, text='Tipo Persona:') self.personL.pack(side=LEFT) personR1 = Radiobutton(self.f8, text="Natural", variable=tipopersona, value=1) personR1.pack(padx=20,side=LEFT) personR2 = Radiobutton (self.f8, text="Jurídica", variable=tipopersona, value=2) personR2.pack(padx=20,side=LEFT) self.comisionL = Label(self.f8, text='$ Comisión:') self.comisionL.pack(side=LEFT) comisionE = Entry(self.f8, textvariable=comision, width=5) comisionE.pack(side=LEFT) self.f = Frame(self.tab1) self.f.pack(pady=5,fill=X)#------------------------------------ Ch1 = Checkbutton(self.f, text="Retefuente", variable=retefuente) Ch1.pack(side=LEFT) Ch2 = Checkbutton(self.f, text="Rete IVA", variable=reteiva) Ch2.pack(side=LEFT) Ch3 = Checkbutton(self.f, text="Gran Contribuyente", variable=gcontribuyente) Ch3.pack(side=LEFT) Ch4 = Checkbutton(self.f, text="Genera Factura", variable=gfactura) Ch4.pack(side=LEFT) Ch5 = Checkbutton(self.f, text="Genera Cheque", variable=gcheque) Ch5.pack(side=LEFT) self.f9 = Frame(self.tab1) self.f9.pack(pady=5,fill=X)#------------------------------------ self.notesL = Label(self.f9, text='Observaciones:') self.notesL.pack(side=LEFT) self.f10 = Frame(self.tab1) self.f10.pack(pady=5,fill=X)#------------------------------------ note = Text(self.f10, height=5) note.pack(side=LEFT, fill=X, expand=1) self.tab1.pack() #-----------------------> TAB 2 self.tab2 = Frame (self.nb) self.tab2.pack() self.f0 = Frame(self.tab2)#Para dejar espacio entre Tab y Label self.f0.pack(fill=X, pady=10)#---------------------------------- #======================= COMPLEMENTARIOS ======================= self.lf = LabelFrame(self.tab2, text="Datos Representante") self.f0 = Frame(self.lf) self.f0.pack(fill=X, pady=5)#------------------------------- self.ccRL = Label(self.f0, text='CC:') self.ccRL.pack(side=LEFT) cc0E = Entry(self.f0, textvariable=reprecc, width=10) cc0E.pack(side=LEFT, fill=X, expand=1) self.nameL = Label(self.f0, text='Nombres:') self.nameL.pack(side=LEFT) name0E = Entry(self.f0, textvariable=reprenombres) name0E.pack(side=LEFT, fill=X, expand=1) name0E.bind("<KeyRelease>", caps) self.f1 = Frame(self.lf) self.f1.pack(fill=X, pady=5)#------------------------------- self.adressL = Label(self.f1, text='Dir. Casa:') self.adressL.pack(side=LEFT) adress0E = Entry(self.f1, textvariable=repredireccion) adress0E.pack(side=LEFT, fill=X, expand=1) adress0E.bind("<KeyRelease>", caps) self.phoneL = Label(self.f1, text='Tel:') self.phoneL.pack(side=LEFT) phone0E = Entry(self.f1, textvariable=repretelefono, width=20) phone0E.pack(side=LEFT) self.f2 = Frame(self.lf) self.f2.pack(fill=X, pady=5)#------------------------------- self.officeL = Label(self.f2, text='Dir. Oficina:') self.officeL.pack(side=LEFT) office0E = Entry(self.f2, textvariable=repreoficina) office0E.pack(side=LEFT, fill=X, expand=1) office0E.bind("<KeyRelease>", caps) self.officetelL = Label(self.f2, text='Tel:') self.officetelL.pack(side=LEFT) officetel0E = Entry(self.f2, textvariable=repretel, width=20) officetel0E.pack(fill=X, side=LEFT) self.f3 = Frame (self.lf) self.f3.pack(fill=X)#------------------------------------------- self.tbancpL = Label(self.f3, text='Banco:') self.tbancpL.pack(side=LEFT) bank0Cbx = Combobox(self.f3, textvariable=reprebanco, values=tbancos, width=12) bank0Cbx.set('') bank0Cbx.pack(side=LEFT) self.tbancpL = Label(self.f3, text='Tipo Cuenta:') self.tbancpL.pack(side=LEFT) tbank0Cbx = Combobox(self.f3, textvariable=repretcuenta, values=tbanktype, width=8) tbank0Cbx.set('') tbank0Cbx.pack(side=LEFT) self.tcuentaL = Label(self.f3, text='# Cuenta:') self.tcuentaL.pack(side=LEFT) tcuenta0E = Entry(self.f3, textvariable=reprenumcuenta) tcuenta0E.pack(side=LEFT, fill=X, expand=1) self.lf.pack(fill=X, ipady=5)#================================== self.f0 = Frame(self.tab2)#Para dejar espacio entre Tab y Label self.f0.pack(fill=X, pady=10)#------------------------------- #--------------------------------------------------------------- self.lf1 = LabelFrame(self.tab2, text="Datos Titular 1") self.f4 = Frame(self.lf1) self.f4.pack(fill=X, pady=5)#------------------------------- self.ccL = Label(self.f4, text='CC:') self.ccL.pack(side=LEFT) cc1E = Entry(self.f4, textvariable=tit1cc) cc1E.pack(side=LEFT, fill=X, expand=1) self.nameL = Label(self.f4, text='Nombres:') self.nameL.pack(side=LEFT) name1E = Entry(self.f4, textvariable=tit1nombres) name1E.pack(side=LEFT, fill=X, expand=1) name1E.bind("<KeyRelease>", caps) self.f5 = Frame (self.lf1) self.f5.pack(fill=X)#------------------------------------------- self.tbancpL = Label(self.f5, text='Banco:') self.tbancpL.pack(side=LEFT) bank1Cbx = Combobox(self.f5, textvariable=tit1banco, values=tbancos, width=12) bank1Cbx.set('') bank1Cbx.pack(side=LEFT) self.tbancpL = Label(self.f5, text='Tipo Cuenta:') self.tbancpL.pack(side=LEFT) tbank1Cbx = Combobox(self.f5, textvariable=tit1tcuenta, values=tbanktype, width=8) tbank1Cbx.set('') tbank1Cbx.pack(side=LEFT) self.tcuentaL = Label(self.f5, text='# Cuenta:') self.tcuentaL.pack(side=LEFT) tcuenta1E = Entry(self.f5, textvariable=tit1numcuenta) tcuenta1E.pack(side=LEFT, fill=X, expand=1) self.lf1.pack(fill=X, ipady=5)#================================ self.f0 = Frame(self.tab2)#Para dejar espacio entre Tab y Label self.f0.pack(fill=X, pady=10)#------------------------------- #--------------------------------------------------------------- self.lf2 = LabelFrame(self.tab2, text="Datos Titular 2") self.f5 = Frame(self.lf2) self.f5.pack(fill=X, pady=5)#------------------------------- self.ccL = Label(self.f5, text='CC:') self.ccL.pack(side=LEFT) cc2E = Entry(self.f5, textvariable=tit2cc) cc2E.pack(side=LEFT, fill=X, expand=1) self.nameL = Label(self.f5, text='Nombres:') self.nameL.pack(side=LEFT) name2E = Entry(self.f5, textvariable=tit2nombres) name2E.pack(side=LEFT, fill=X, expand=1) name2E.bind("<KeyRelease>", caps) self.f6 = Frame (self.lf2) self.f6.pack(fill=X)#------------------------------------------- self.tbancpL = Label(self.f6, text='Banco:') self.tbancpL.pack(side=LEFT) bank2Cbx = Combobox(self.f6, textvariable=tit2banco, values=tbancos, width=12) bank2Cbx.set('') bank2Cbx.pack(side=LEFT) self.tbancpL = Label(self.f6, text='Tipo Cuenta:') self.tbancpL.pack(side=LEFT) tbank2Cbx = Combobox(self.f6, textvariable=tit2tcuenta, values=tbanktype, width=8) tbank2Cbx.set('') tbank2Cbx.pack(side=LEFT) self.tcuentaL = Label(self.f6, text='# Cuenta:') self.tcuentaL.pack(side=LEFT) tcuenta2E = Entry(self.f6, textvariable=tit2numcuenta) tcuenta2E.pack(side=LEFT, fill=X, expand=1) self.lf2.pack(fill=X, ipady=5)#================================ #--------------------------------------------------------------- self.nb.add (self.tab1, text="Personales") self.nb.add(self.tab2, text="Complementarios") self.nb.pack() #=========================== BOTONES =========================== self.btns = Frame(self.wrapper) self.btns.pack()#------------------------------- clean = Button(self.btns, text='Limpiar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=limpiar) clean.pack(side=RIGHT) update = Button(self.btns, text='Actualizar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=actualizar, state=DISABLED) update.pack(side=RIGHT) add = Button(self.btns, text='Agregar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=Agregar) add.pack(side=RIGHT) #========================= ASIDE =========================== self.aside = Frame(self) self.aside.pack(side=LEFT, fill=BOTH, expand=True) self.wrap1 = Frame(self.aside) self.wrap1.pack() self.viewer = Label(self.wrap1, text="LISTA DE PROPIETARIOS") 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, bg='#d8ecf3') scroll.config (command=lb.yview) lb.pack(fill=BOTH) lb.bind("<Double-Button-1>", callback) lb.bind("<Button-3>", popup) #lb.bind('<Escape>', release) self.wrap2 = Frame(self.aside) self.wrap2.pack() self.updateBP = Button(self.wrap2, text='Cargar lista', width=20, bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=cargar_lista) self.updateBP.pack() delete = Button(self.wrap2, text='Borrar', bg='navy', width=20, foreground='white', activebackground='red3', activeforeground='white', command=borrar) delete.pack() edit = Button(self.wrap2, text='Modificar', bg='navy', width=20, foreground='white', activebackground='red3', activeforeground='white', command=modificar) edit.pack() self.wrap3 = Frame(self.aside) self.wrap3.pack() buscador = Label(self.wrap3, text="Buscar por:") buscador.pack(side=LEFT) R1 = Radiobutton(self.wrap3, text="CC", variable=info, value=1) R1.pack(side=LEFT) R2 = Radiobutton (self.wrap3, text="Apellido", variable=info, value=2) R2.pack(side=LEFT) info.set(1) self.wrap4 = Frame(self.aside) self.wrap4.pack() E = Entry(self.wrap4, textvariable=busqueda, width=24) E.pack() E.bind("<KeyRelease>", caps)
class Admindocs(Frame): 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)#<--------------------------------------
msg.pack(side = "left", pady =30 ) #=========================================================================== """ From Label""" Label(f1, text="From",bg="white", fg = "navy blue", anchor="w", font=('Lucida Sans Typewriter',(15))).pack(side = LEFT, padx = 10, pady = 20) """ Como box for "From/ source" """ From = StringVar() Values = ["Bangalore", "Delhi", "Mumbai", "Chennai"] w = Combobox(f1,values = Values,width = 15, height = 4, textvariable= From) w.bind('<<ComboboxSelected>>', Fromcall) w.pack(side = LEFT, padx = 10, pady = 20) """ TO Label""" Label(f1, text="To",bg="white", fg = "navy blue",font=('Lucida Sans Typewriter',(15))).pack(side = LEFT,padx = 10, pady = 20) """ Como box for "To/Destination" """ To = StringVar() Values = ["Bangalore", "Delhi", "Mumbai", "Chennai", "Kolkata", "Cochin"] w = Combobox(f1,values = Values,width = 15, height = 4, textvariable= To) w.bind('<<ComboboxSelected>>', Tocall) w.pack(side = LEFT, padx = 10, pady = 20) #===========================================================================