def select_period(window, command): period_screen = Toplevel(window) d_lbl = Label(period_screen, text="Select prefered period") d_lbl.grid(column=0, row=0) d_lbl2 = Label(period_screen, width=15, text="From") d_lbl2.grid(column=0, row=1) cal1 = DateEntry(period_screen, date_pattern='yyyy-mm-dd', width=12, background='darkblue', foreground='white', borderwidth=2) cal1.grid(column=0, row=2) current_date = get_date() cal1.set_date(current_date) d_lbl2 = Label(period_screen, width=15, text="To") d_lbl2.grid(column=1, row=1) cal2 = DateEntry(period_screen, date_pattern='yyyy-mm-dd', width=12, background='darkblue', foreground='white', borderwidth=2) cal2.grid(column=1, row=2) cal2.set_date(current_date) d_btn1 = Button(period_screen, text="Set period", command=lambda: [set_period(cal1, cal2, command), period_screen.destroy()]) d_btn1.grid(column=0, row=3)
def pick_specific_day(): def run_graph(): local_vales = [] print(type(cal.get_date())) datetime_object = cal.get_date() if(datetime_object >= epoch_values[0].date() and datetime_object <= epoch_values[len(epoch_values) - 1].date()): print("Showing: " + str(datetime_object)) for i in epoch_values: if(i.date() == datetime_object): local_vales.append(i) show_graph(local_vales) else: print("That date isn't possible, try again!") top = tk.Toplevel(root) message = "Select a day from, " + \ str(epoch_values[0].date()) + " to " + \ str(epoch_values[len(epoch_values)-1].date()) ttk.Label(top, text=message).pack(padx=10, pady=10) cal = DateEntry(top, width=12, background='darkblue', foreground='white', borderwidth=2) cal.set_date(epoch_values[0]) cal.pack(padx=10, pady=10) ttk.Button(top, text="Show graph", command=run_graph).pack()
class StatisticFrame(Frame): def __init__(self): Frame.__init__(self) self.pack() # Db db = Db() now = datetime.now() # Station selectbox stationOptions = {} for station in db.getStations(): stationOptions[station.name] = station.id self.stationSelect = Select(self, 'Station:', stationOptions) self.stationSelect.setEvent(self.updateStatistic) # Type selectbox self.statisticTypeSelect = Select(self, 'Type:', { 'Day': 'day', 'Month': 'month', 'Year': 'year' }) self.statisticTypeSelect.setEvent(self.updateStatistic) # Date from calendar self.dateFromSelect = DateEntry(self, selectmode='day', date_pattern='dd.mm.y') self.dateFromSelect.set_date(self.firstDayOfMonth(now)) self.dateFromSelect.bind("<<DateEntrySelected>>", self.updateStatistic) self.dateFromSelect.pack() # Date to calendar self.dateToSelect = DateEntry(self, selectmode='day', date_pattern='dd.mm.y') self.dateToSelect.set_date(self.lastDayOfMonth(now)) self.dateToSelect.bind("<<DateEntrySelected>>", self.updateStatistic) self.dateToSelect.pack() # Update statistic self.updateStatistic() def updateStatistic(self, *args): StatisticPrint(self, self.stationSelect.get(), self.dateFromSelect.get_date(), self.dateToSelect.get_date(), self.statisticTypeSelect.get()) def firstDayOfMonth(self, d): return d.replace(day=1, hour=0, minute=0, second=0, microsecond=0) def lastDayOfMonth(self, d): if d.month == 12: return d.replace(day=31) return d.replace(month=d.month + 1, day=1) - timedelta(days=1)
class StatisticFrame(Frame): def __init__(self): Frame.__init__(self) self.pack() # Db db = Db() # Datetime now now = datetime.now() # Station selectbox stationOptions = {} for station in db.getStations(): stationOptions[station.name] = station.id self.stationSelect = Select(self, 'Station:', stationOptions) self.stationSelect.setEvent(self.updateStatistic) # Type selectbox self.statisticTypeSelect = Select(self, 'Type:', { 'Day': 'D', 'Month': 'm', 'Year': 'Y' }) self.statisticTypeSelect.setEvent(self.updateStatistic) self.statisticTypeSelect.setValue('Day') # Date from calendar (7 Days before now) self.dateFromSelect = DateEntry(self, selectmode='day', date_pattern='dd.mm.y') self.dateFromSelect.set_date((now - timedelta(days=7))) self.dateFromSelect.bind("<<DateEntrySelected>>", self.updateStatistic) self.dateFromSelect.pack() # Date to calendar self.dateToSelect = DateEntry(self, selectmode='day', date_pattern='dd.mm.y') self.dateToSelect.set_date(now) self.dateToSelect.bind("<<DateEntrySelected>>", self.updateStatistic) self.dateToSelect.pack() # Statistic self.statistic = StatisticPrint(self, self.stationSelect.get(), self.dateFromSelect.get_date(), self.dateToSelect.get_date(), self.statisticTypeSelect.get()) def updateStatistic(self, *args): self.statistic.set(self.stationSelect.get(), self.dateFromSelect.get_date(), self.dateToSelect.get_date(), self.statisticTypeSelect.get())
class TimePicker(tk.Toplevel): def __init__(self, parent, **kw): chosen_stall = kw["chosen_stall"] kw.pop("chosen_stall") tk.Toplevel.__init__(self, parent, **kw) # Main Title main_title_label = tk.Label(self, text = "Select Timing", font = constants.MEDIUM_FONT) main_title_label.place(relx = 0.25, rely = 0.0625, relheight = 0.125, relwidth = 0.5) # Spinbox Frame spinbox_frame = tk.Frame(self) spinbox_frame.place(relx = 0.125, rely = 0.25, relheight = 0.25, relwidth = 0.75) # Spinboxes hour = tk.IntVar(value = datetime.now().time().hour) self.hour_spinbox = tk.Spinbox(spinbox_frame, from_ = 00, to = 23, increment = 1, textvariable = hour, format = "%02.0f", state = "readonly") self.hour_spinbox.place(relx = 0, rely = 0.25, relheight = 1, relwidth = 0.3) minute = tk.IntVar(value = (((datetime.now().time().minute // 10) * 10))) self.minute_spinbox = tk.Spinbox(spinbox_frame, from_ = 00, to = 50, increment = 10, textvariable = minute, format = "%02.0f", state = "readonly") self.minute_spinbox.place(relx = 0.3, rely = 0.25, relheight = 1, relwidth = 0.3) self.date_entry = DateEntry(spinbox_frame, state = "normal", firstweekday = "monday", mindate = datetime.today().date(), showweeknumbers = False, showothermonthdays = False, locale = "en_SG", date_pattern = "dd-mm-yyyy") self.date_entry.place(relx = 0.6, rely = 0.25, relheight = 1, relwidth = 0.4) # Buttons Frame buttons_frame = tk.Frame(self) buttons_frame.place(relx = 0.125, rely = 0.625, relheight = 0.25, relwidth = 0.75) # Current Time Button current_time_button = tk.Button(buttons_frame, text = "Now", command = lambda: self.current_time_button_pressed()) current_time_button.place(relx = 0.125, rely = 0.125, relheight = 0.25, relwidth = 0.75) # Submit button submit_button = tk.Button(buttons_frame, text = "Submit", command = lambda: self.submit_button_pressed(self.hour_spinbox.get(), self.minute_spinbox.get(), self.date_entry.get_date(), parent, chosen_stall)) submit_button.place(relx = 0.125, rely = 0.5, relheight = 0.25, relwidth = 0.75) # Takes entered Time from Spinboxes and updates the Menu List def submit_button_pressed(self, hour_time, minute_time, on_day, parent, chosen_stall): hour_time = int(hour_time) minute_time = int(minute_time) time = str(hour_time).format("%02.0f") + ":" + str(minute_time).format("%02.0f") parent.list_reload_data(chosen_stall, time, on_day.weekday()) self.destroy() # Resets Hour and Minute in Spinbox to Current Time def current_time_button_pressed(self): hour = tk.IntVar(value = datetime.now().time().hour) minute = tk.IntVar(value = (((datetime.now().time().minute // 10) * 10))) self.hour_spinbox["textvariable"] = hour self.minute_spinbox["textvariable"] = minute self.date_entry.set_date(datetime.now().date())
def select_date(window, command): date_screen = Toplevel(window) d_lbl = Label(date_screen, text="Select prefered date") d_lbl.grid(column=0, row=0) d_lbl2 = Label(date_screen, width=15, text="Click here") d_lbl2.grid(column=0, row=1) cal = DateEntry(date_screen, date_pattern='yyyy-mm-dd', width=12, background='darkblue', foreground='white', borderwidth=2) cal.grid(column=0, row=2) current_date = get_date() cal.set_date(current_date) d_btn1 = Button(date_screen, text="Set date", command=lambda: [set_date(cal, command, window), date_screen.destroy()]) d_btn1.grid(column=0, row=3)
def pick_date_range(): def run_graph(): local_vales = [] datetime_object_start = cal.get_date() datetime_object_end = cal_end.get_date() if(datetime_object_start >= epoch_values[0].date() and datetime_object_end <= epoch_values[len(epoch_values) - 1].date() and datetime_object_end > datetime_object_start): print("Showing: " + str(datetime_object_start) + " too " + str(datetime_object_end)) for i in epoch_values: if(i.date() >= datetime_object_start and i.date() <= datetime_object_end): local_vales.append(i) show_graph(local_vales) else: print("That date range isn't possible, try again!") top = tk.Toplevel(root) selected_day_start = "Select a start date after " + \ str(epoch_values[0].date()) selected_day_end = "Select a end date before " + \ str(epoch_values[0].date()) ttk.Label(top, text=selected_day_start).pack(padx=10, pady=10) cal = DateEntry(top, width=12, background='darkblue', foreground='white', borderwidth=2) cal.set_date(epoch_values[0]) cal.pack(padx=10, pady=10) tk.Label(top, text=selected_day_end).pack(padx=10, pady=10) cal_end = DateEntry(top, width=12, background='darkblue', foreground='white', borderwidth=2) cal_end.set_date(epoch_values[len(epoch_values) - 1]) cal_end.pack(padx=10, pady=10) ttk.Button(top, text="Show Graph", command=run_graph).pack()
class MyDateEntry(DateEntry): def __init__(self, master=None, **kw): #DateEntry.__init__(self, master=None, **kw) self.this_calendar = DateEntry()#.__init__(self, master = None, **kw) # add black border around drop-down calendar self._top_cal.configure(bg='black', bd=1) # add label displaying today's date below date_label = Label( self._top_cal, bg='gray90', anchor='w', text='Today: %s' % date.today().strftime('%x')) date_label.pack(fill='x') date_label.bind("<Button-1>", lambda e : self.this_calendar.set_date(date.today()))
def test_dateentry_functions(self): widget = DateEntry(self.window, width=12, background='darkblue', foreground='white', borderwidth=2) widget.pack() self.window.update() widget.set_date(format_date(date(2018, 12, 31), 'short')) self.assertEqual(widget.get_date(), date(2018, 12, 31)) with self.assertRaises(ValueError): widget.set_date("ab") widget.set_date(date(2015, 12, 31)) self.assertEqual(widget.get_date(), date(2015, 12, 31)) self.assertEqual(widget.get(), format_date(date(2015, 12, 31), 'short')) widget.delete(0, "end") widget.insert(0, "abc") self.window.focus_force() self.assertEqual(widget.get_date(), date(2015, 12, 31)) widget._on_motion(TestEvent(x=10, y=20)) widget._on_b1_press(TestEvent(x=10, y=20)) widget._on_b1_press(TestEvent(x=widget.winfo_width() - 2, y=2)) widget._on_focus_out_cal(TestEvent(x=10, y=20)) widget.state(("disabled", )) self.window.update() self.assertIn("disabled", widget.state()) widget.drop_down() self.window.update() widget._select() self.window.update() widget.drop_down() self.window.update() widget.drop_down() self.window.update() widget.configure(state='readonly') self.window.update() widget._select() self.assertIn('readonly', widget.state())
class App(tk.Frame): def __init__(self, master): super().__init__(master) self.master.title("Pilates Invoice Manager") tk.Label(text="Pick month of invoice (any day):").grid(row=0, column=0, sticky="E") # INITIATE DICTIONARY TO KEEP HOURS WORKED self.allentries = dict() self.cal = DateEntry(master, width=12, background='darkblue', foreground='white', borderwidth=2, date_pattern="dd/mm/yyyy") self.cal.set_date(dt.datetime.now()) self.cal.grid(row=0, column=1, sticky="W") tk.Label(text="Day rate in £ (ex: 30.00) :").grid(row=1, column=0, sticky="E") # GET WEEKDAY AND WEEKEND RATES self.default_rate = 30 self.default_rate_setter = tk.StringVar() self.default_rate_setter.set(str(self.default_rate)) self.weekendrate = tk.Entry(textvariable=self.default_rate_setter) self.weekendrate.grid(row=1, column=1, sticky="W") # self.weekendrate.bind('<Key-Return>', self.print_contents) # # DISPLAY CURRENT DATE # self.w = tk.Entry(master, fg="white", bg="black", font=("helvetica", 12)) # self.w.insert(0,f"{dt.datetime.now():%a, %b %d %Y}") # self.w.grid(row=2, column=1, sticky="E") # checkbox for weekend only display self.CheckVar1 = tk.IntVar() self.C1 = tk.Checkbutton(master, command=self.check_status, text="Display only Sundays", variable=self.CheckVar1, onvalue=1, offvalue=0) self.C1.grid(row=2, columnspan=2) # self.weekendmessage = tk.Label(text="All days will be displayed") # self.weekendmessage.grid(row=2, column=1, sticky="W") tk.Label(text="Enter number of hours worked: ").grid(row=3, columnspan=2) self.check_status() tk.Button(text="Save", command=self.savetotals).grid() tk.Button(text="Export to PDF", command=self.export_topdf).grid() # self.contents = tk.StringVar() # OPTIONS = ["egg", "bunny", "chicken"] # self.contents.set(OPTIONS[0]) # default value # self.w = tk.OptionMenu(master, self.contents, *OPTIONS) # self.w.pack() def export_topdf(self): # pd.DataFrame.from_dict(data=self.allentries, orient='index').to_csv('dict_file.csv', header=False) # save FPDF() class into a # variable pdf pdf = FPDF() # Add a page pdf.add_page() # set style and size of font # that you want in the pdf pdf.set_font("Arial", size=15) pdf.rect(5.0, 5.0, 200.0, 287.0) # create a cell pdf.cell(200, 10, txt="Eleni Theodoridou Pilates", ln=1, align='C') invoice_month = self.cal.get_date().strftime("%B") # add another cell pdf.cell(200, 10, txt=f"Invoice for {invoice_month} {self.cal.get_date().year}", ln=2, align='C') pdf.set_font("times", size=10) pdf.cell(75, 10, txt=f"Bill to:", border=0, ln=0, align='L') pdf.cell(75, 10, txt=f"Pepilates Limited", border=0, ln=1, align='L') pdf.cell(75, 10, txt=f"Date:", border=0, ln=0, align='L') pdf.cell(75, 10, txt=f"{dt.datetime.now():%d %b %Y}", border=0, ln=1, align='L') pdf.set_font("Arial", size=10) for day, entry in self.allentries.items(): if entry > 0: pdf.cell(100, 10, txt=f"{day}", border=1, ln=0, align='L') pdf.cell(50, 10, txt=f"£ {entry}", border=1, ln=1, align='L') monthly_total = sum(self.allentries.values()) pdf.cell(100, 10, txt=f"Monthly Total", border=1, ln=0, align='L') pdf.cell(50, 10, txt=f"£ {monthly_total}", border=1, ln=1, align='L') pdf.ln(5) pdf.cell(150, 10, txt=f"Please make payment to:", border=0, ln=1, align='L') pdf.cell(50, 10, txt=f"Account Name", border=0, ln=0, align='L') pdf.cell(50, 10, txt=f"Eleni Theodoridou", border=0, ln=1, align='L') pdf.cell(50, 10, txt=f"Bank", border=0, ln=0, align='L') pdf.cell(50, 10, txt=f"Lloyds Bank", border=0, ln=1, align='L') pdf.cell(50, 10, txt=f"Sort Code", border=0, ln=0, align='L') pdf.cell(50, 10, txt=f"30-94-21", border=0, ln=1, align='L') pdf.cell(50, 10, txt=f"Account No", border=0, ln=0, align='L') pdf.cell(50, 10, txt=f"32455260", border=0, ln=1, align='L') # save the pdf with name .pdf pdf.output(f"Invoice_{invoice_month}{self.cal.get_date().year}.pdf") def savetotals(self): self.default_rate = float(self.default_rate_setter.get()) self.allentries = dict( (day.cget("text"), float(entry.get()) * self.default_rate) if r.match(entry.get()) else (day.cget("text"), 0) for day, entry in alldays) self.monthly_total = sum(self.allentries.values()) print(self.monthly_total) def find_weekends(self, Sundayonly=False): year = self.cal.get_date().year month = self.cal.get_date().month first_day_of_month = dt.date(year, month, 1) first_saturday_of_month = first_day_of_month + dt.timedelta( days=5 - first_day_of_month.weekday()) first_sunday_of_month = first_saturday_of_month + dt.timedelta(days=1) if Sundayonly: while first_sunday_of_month.year == year and first_sunday_of_month.month == month: yield first_sunday_of_month first_sunday_of_month += dt.timedelta(days=7) else: while first_day_of_month.year == year and first_day_of_month.month == month: yield first_day_of_month first_day_of_month += dt.timedelta(days=1) def check_status(self): Sundayonly = bool(self.CheckVar1.get()) global alldays if not Sundayonly: alldays = [(tk.Label(text=f"{d}"), tk.Entry()) for d in self.find_weekends(Sundayonly=False)] row = 4 for label, entry in alldays: label.grid_remove() entry.grid_remove() label.grid(row=row, column=0, sticky="E") entry.grid(row=row, column=1, sticky="W") row += 1 elif Sundayonly: for label, entry in alldays: label.grid_remove() entry.grid_remove() alldays = [(tk.Label(text=f"{d}"), tk.Entry()) for d in self.find_weekends(Sundayonly=True)] row = 4 for label, entry in alldays: label.grid(row=row, column=0, sticky="E") entry.grid(row=row, column=1, sticky="W") row += 1 def print_contents(self, event): x = float(self.weekendrate.get().partition(" ")[0]) print("Hi. The current entry content and type are:", x, type(x))
class Form(Toplevel): def __init__(self, master, event, new=False): Toplevel.__init__(self, master) self.minsize(410, 402) if master.winfo_ismapped(): self.transient(master) self.protocol('WM_DELETE_WINDOW', self.cancel) self._only_nb = self.register(only_nb) self.event = event if new: self.title(_('New Event')) else: self.title(_('Edit Event')) self._new = new self._task = BooleanVar(self, bool(event['Task'])) self._whole_day = BooleanVar(self, event['WholeDay']) # --- style style = Style(self) active_bg = style.lookup('TEntry', 'selectbackground', ('focus', )) self.alarms = [] notebook = Notebook(self) notebook.pack(fill='both', expand=True) Button(self, text=_('Ok'), command=self.ok).pack(pady=(10, 6), padx=4) # --- event settings frame_event = Frame(notebook) notebook.add(frame_event, text=_('Event'), sticky='eswn', padding=4) frame_event.columnconfigure(1, weight=1) frame_event.rowconfigure(5, weight=1) self.img_moins = PhotoImage(master=self, file=IM_DEL) self.img_bell = PhotoImage(master=self, file=IM_BELL) Label(frame_event, text=_('Summary')).grid(row=0, column=0, padx=4, pady=6, sticky='e') Label(frame_event, text=_('Place')).grid(row=1, column=0, padx=4, pady=6, sticky='e') Label(frame_event, text=_('Start')).grid(row=2, column=0, padx=4, pady=6, sticky='e') self._end_label = Label(frame_event, text=_('End')) self._end_label.grid(row=3, column=0, padx=4, pady=6, sticky='e') frame_task = Frame(frame_event) frame_task.grid(row=4, column=1, padx=4, pady=6, sticky='w') Label(frame_event, text=_('Description')).grid(row=5, column=0, padx=4, pady=6, sticky='e') Label(frame_event, text=_('Category')).grid(row=6, column=0, padx=4, pady=6, sticky='e') Button(frame_event, image=self.img_bell, command=self.add_reminder, padding=0).grid(row=7, column=0, padx=4, pady=6, sticky='en') self.summary = Entry(frame_event, width=35) self.summary.insert(0, self.event['Summary']) self.summary.grid(row=0, column=1, padx=4, pady=6, sticky='ew') self.place = Entry(frame_event, width=35) self.place.insert(0, self.event['Place']) self.place.grid(row=1, column=1, padx=4, pady=6, sticky='ew') frame_start = Frame(frame_event) frame_start.grid(row=2, column=1, padx=4, pady=6, sticky='w') frame_end = Frame(frame_event) frame_end.grid(row=3, column=1, padx=4, pady=6, sticky='w') txt_frame = Frame(frame_event, style='txt.TFrame', border=1, relief='sunken') self.desc = Text(txt_frame, width=35, height=4, highlightthickness=0, relief='flat', selectbackground=active_bg) self.desc.insert('1.0', self.event['Description']) self.desc.pack(fill='both', expand=True) txt_frame.grid(row=5, column=1, padx=4, pady=6, sticky='ewsn') cats = list(CONFIG.options('Categories')) width = max([len(cat) for cat in cats]) self.category = Combobox(frame_event, width=width + 2, values=cats, state='readonly') self.category.set(event['Category']) self.category.grid(row=6, column=1, padx=4, pady=6, sticky='w') self.frame_alarms = Frame(frame_event) self.frame_alarms.grid(row=7, column=1, sticky='w') # --- *--- task Checkbutton(frame_task, text=_('Task'), command=self._change_label, variable=self._task).pack(side='left') self.task_progress = Combobox(frame_task, state='readonly', width=9, values=(_('Pending'), _('In Progress'), _('Completed'), _('Cancelled'))) self.task_progress.pack(side='left', padx=(8, 4)) self.in_progress = Combobox( frame_task, state='readonly', width=5, values=['{}%'.format(i) for i in range(0, 110, 10)]) self.in_progress.pack(side='left', padx=4) if not event['Task']: self.task_progress.set(_('Pending')) self.in_progress.set('0%') elif '%' in event['Task']: self.task_progress.set(_('In Progress')) self.in_progress.set(event['Task']) else: self.task_progress.set(_(event['Task'])) self.in_progress.set('0%') # calendar settings prop = { op: CONFIG.get('Calendar', op) for op in CONFIG.options('Calendar') } prop['font'] = "Liberation\ Sans 9" prop.update(selectforeground='white', selectbackground=active_bg) locale = CONFIG.get('General', 'locale') # --- *--- start date self.start_date = self.event['Start'] self.start_entry = DateEntry(frame_start, locale=locale, width=10, justify='center', year=self.start_date.year, month=self.start_date.month, day=self.start_date.day, **prop) self.start_hour = Combobox(frame_start, width=3, justify='center', state='readonly', exportselection=False, values=['%02d' % i for i in range(24)]) self.start_hour.set('%02d' % self.start_date.hour) self.start_min = Combobox(frame_start, width=3, justify='center', state='readonly', exportselection=False, values=['%02d' % i for i in range(0, 60, 5)]) self.start_min.set('%02d' % self.start_date.minute) self.start_entry.pack(side='left', padx=(0, 18)) self.start_hour.pack(side='left', padx=(4, 0)) self.start_date = self.start_date.date() Label(frame_start, text=':').pack(side='left') self.start_min.pack(side='left', padx=(0, 4)) Checkbutton(frame_start, text=_("whole day"), variable=self._whole_day, command=self._toggle_whole_day).pack(side='left', padx=4) # --- *--- end date self.end_date = self.event['End'] self.end_entry = DateEntry(frame_end, justify='center', locale=locale, width=10, year=self.end_date.year, month=self.end_date.month, day=self.end_date.day, **prop) self.end_hour = Combobox(frame_end, width=3, justify='center', state='readonly', exportselection=False, values=['%02d' % i for i in range(24)]) self.end_hour.set('%02d' % self.end_date.hour) self.end_min = Combobox(frame_end, width=3, justify='center', state='readonly', exportselection=False, values=['%02d' % i for i in range(0, 60, 5)]) self.end_min.set('%02d' % self.end_date.minute) self.end_entry.pack(side='left', padx=(0, 18)) self.end_hour.pack(side='left', padx=(4, 0)) Label(frame_end, text=':').pack(side='left') self.end_min.pack(side='left', padx=(0, 4)) self.end_date = self.end_date.date() for date in self.event['Reminders'].values(): self.add_reminder(date) self._toggle_whole_day() # --- repetition settings frame_rep = Frame(notebook) notebook.add(frame_rep, text=_('Repetition'), padding=4, sticky='eswn') frame_rep.columnconfigure(0, weight=1) frame_rep.columnconfigure(1, weight=1) frame_rep.rowconfigure(1, weight=1) self._repeat = BooleanVar(self, bool(self.event['Repeat'])) repeat = { 'Frequency': 'year', 'Limit': 'always', 'NbTimes': 1, 'EndDate': (datetime.now() + timedelta(days=1)).date(), 'WeekDays': [self.start_date.isocalendar()[2] - 1] } repeat.update(self.event['Repeat']) self._repeat_freq = StringVar(self, repeat['Frequency']) Checkbutton(frame_rep, text=_('Repeat event'), variable=self._repeat, command=self._toggle_rep).grid(row=0, column=0, columnspan=2, padx=4, pady=6, sticky='w') # --- *--- Frequency frame_freq = LabelFrame(frame_rep, text=_('Frequency')) frame_freq.grid(row=1, column=0, sticky='eswn', padx=(0, 3)) self._lfreq = Label(frame_freq, text=_('Every:')) self._lfreq.grid(row=0, column=0, padx=4, pady=2, sticky='e') self._freqs = [] for i, val in enumerate(['Year', 'Month', 'Week']): r = Radiobutton(frame_freq, text=_(val), variable=self._repeat_freq, value=val.lower(), command=self._toggle_wd) r.grid(row=i, column=1, padx=4, pady=2, sticky='nw') self._freqs.append(r) frame_days = Frame(frame_freq) frame_days.grid(row=2, column=2, padx=4, pady=2, sticky='nw') self._week_days = [] days = get_day_names("wide", locale=locale) days = [days[i] for i in range(7)] for day in days: ch = Checkbutton(frame_days, text=day) ch.pack(anchor='w') self._week_days.append(ch) for d in repeat['WeekDays']: self._week_days[int(d)].state(('selected', )) # --- *--- Limit frame_lim = LabelFrame(frame_rep, text=_('Limit')) frame_lim.grid(row=1, column=1, sticky='eswn', padx=(3, 0)) frame_lim.grid(row=1, column=1, sticky='eswn', padx=(3, 0)) self._repeat_lim = StringVar(self, repeat['Limit']) # always r1 = Radiobutton(frame_lim, text=_('Always'), value='always', variable=self._repeat_lim, command=self._toggle_lim) r1.grid(row=0, column=0, sticky='w') # until r2 = Radiobutton(frame_lim, text=_('Until'), value='until', variable=self._repeat_lim, command=self._toggle_lim) r2.grid(row=1, column=0, sticky='w') until_date = repeat['EndDate'] self.until_entry = DateEntry(frame_lim, width=10, justify='center', locale=locale, year=until_date.year, month=until_date.month, day=until_date.day, **prop) self.until_entry.grid(row=1, column=1, columnspan=2, sticky='w', padx=(4, 10), pady=2) # after r3 = Radiobutton(frame_lim, text=_('After'), value='after', variable=self._repeat_lim, command=self._toggle_lim) r3.grid(row=2, column=0, sticky='w') frame_after = Frame(frame_lim, style='txt.TFrame', relief='sunken', border=1) self.s_after = Spinbox(frame_after, from_=0, to=100, width=3, justify='center', relief='flat', highlightthickness=0, validate='key', validatecommand=(self._only_nb, '%P'), disabledbackground='white') self.s_after.pack() self.s_after.delete(0, 'end') self.s_after.insert(0, str(repeat['NbTimes'])) frame_after.grid(row=2, column=1, padx=4, pady=2, sticky='w') self._llim = Label(frame_lim, text=_('times')) self._llim.grid(row=2, column=2, padx=0, pady=2, sticky='w') self._rb_lim = [r1, r2, r3] self._toggle_rep() self._change_label() # --- bindings self.bind('<Configure>') self.task_progress.bind('<<ComboboxSelected>>', self._toggle_in_progress) self.start_entry.bind('<<DateEntrySelected>>', self._select_start) self.end_entry.bind('<<DateEntrySelected>>', self._select_end) self.start_hour.bind("<<ComboboxSelected>>", self._select_start_hour) self.start_min.bind("<<ComboboxSelected>>", self._select_start_min) self.end_min.bind("<<ComboboxSelected>>", self._select_end_time) self.end_hour.bind("<<ComboboxSelected>>", self._select_end_time) self.bind_class("TCombobox", "<<ComboboxSelected>>", self.__clear_selection, add=True) # self.wait_visibility(self) # self.grab_set() self.summary.focus_set() def _toggle_lim(self, val=True): if val: val = self._repeat_lim.get() if val == 'until': self.s_after.configure(state='disabled') self._llim.state(('disabled', )) self.until_entry.state(('!disabled', )) elif val == 'after': self._llim.state(('!disabled', )) self.s_after.configure(state='normal') self.until_entry.state(('disabled', )) else: self.s_after.configure(state='disabled') self._llim.state(('disabled', )) self.until_entry.state(('disabled', )) def _toggle_rep(self): rep = self._repeat.get() state = state = '!' * int(rep) + "disabled" for r in self._freqs: r.state((state, )) for r in self._rb_lim: r.state((state, )) self._lfreq.state((state, )) self._toggle_wd(rep) self._toggle_lim(rep) def _toggle_wd(self, val=True): if val: val = self._repeat_freq.get() state = '!' * int(val == 'week') + "disabled" for ch in self._week_days: ch.state((state, )) def _toggle_whole_day(self): if self._whole_day.get(): self.start_min.set('00') self.start_hour.set('00') self.end_min.set('59') self.end_hour.set('23') self.start_min.state(("disabled", )) self.start_hour.state(("disabled", )) self.end_min.state(("disabled", )) self.end_hour.state(("disabled", )) else: self.start_min.state(("!disabled", )) self.start_hour.state(("!disabled", )) self.end_min.state(("!disabled", )) self.end_hour.state(("!disabled", )) def _toggle_in_progress(self, event=None): if self.task_progress.get() == _('In Progress'): self.in_progress.state(('!disabled', )) else: if self.task_progress.get() == _('Completed'): self.in_progress.set('100%') self.in_progress.state(('disabled', )) def _change_label(self): if self._task.get(): self.task_progress.state(('!disabled', )) self._toggle_in_progress() self._end_label.configure(text=_('Deadline')) else: self.task_progress.state(('disabled', )) self.in_progress.state(('disabled', )) self._end_label.configure(text=_('End')) def _on_move(self, event): self.start_cal.withdraw() self.end_cal.withdraw() self.until_cal.withdraw() @staticmethod def __clear_selection(event): combo = event.widget combo.selection_clear() def _select_start(self, event=None): dt = self.start_entry.get_date() - self.start_date self.end_date = self.end_date + dt self.end_entry.set_date(self.end_date) self.start_date = self.start_entry.get_date() def _select_end(self, event=None): self.end_date = self.end_entry.get_date() start = self.start_entry.get_date() if start >= self.end_date: self.start_date = self.end_date self.start_entry.set_date(self.end_date) start_time = time(int(self.start_hour.get()), int(self.start_min.get())) end_time = time(int(self.start_hour.get()), int(self.end_min.get())) if start_time > end_time: self.start_hour.set(self.end_hour.get()) self.start_min.set(self.end_min.get()) def _select_start_hour(self, event): h = int(self.start_hour.get()) self.end_hour.set('%02d' % ((h + 1) % 24)) def _select_start_min(self, event): m = int(self.start_min.get()) self.end_min.set('%02d' % m) def _select_end_time(self, event): if self.start_entry.get() == self.end_entry.get(): start_time = time(int(self.start_hour.get()), int(self.start_min.get())) end_time = time(int(self.end_hour.get()), int(self.end_min.get())) if start_time > end_time: self.start_hour.set(self.end_hour.get()) self.start_min.set(self.end_min.get()) def add_reminder(self, date=None): def remove(): self.alarms.remove((when, what)) rem.destroy() rem = Frame(self.frame_alarms) frame_when = Frame(rem, style='txt.TFrame', relief='sunken', border=1) when = Spinbox(frame_when, from_=0, to=59, width=3, justify='center', relief='flat', highlightthickness=0, validate='key', validatecommand=(self._only_nb, '%P')) when.pack() when.delete(0, 'end') what = Combobox(rem, width=8, state='readonly', values=(_('minutes'), _('hours'), _('days'))) if date: hour = int(self.start_hour.get()) minute = int(self.start_min.get()) dt = datetime.combine(self.start_entry.get_date(), time(hour=hour, minute=minute)) - date if dt.days > 0: when.insert(0, str(dt.days)) what.set(_('days')) else: h, m, s = str(dt).split(':') if h != "0": when.insert(0, h) what.set(_('hours')) else: when.insert(0, str(int(m))) what.set(_('minutes')) else: when.insert(0, '15') what.set(_('minutes')) self.alarms.append((when, what)) Label(rem, text=_('Reminder:')).pack(side='left', padx=4, pady=4) frame_when.pack(side='left', pady=4, padx=4) what.pack(side='left', pady=4, padx=4) Button(rem, image=self.img_moins, padding=0, command=remove).pack(side='left', padx=4, pady=4) rem.pack() def ok(self): summary = self.summary.get() if not summary: showerror(_("Error"), _("The field 'Summary' cannot be empty."), parent=self) return self.event['Summary'] = summary self.event['Place'] = self.place.get() self.event['Start'] = "%s %s:%s" % ( self.start_entry.get_date().strftime("%Y-%m-%d"), self.start_hour.get(), self.start_min.get()) self.event['End'] = "%s %s:%s" % (self.end_entry.get_date().strftime( "%Y-%m-%d"), self.end_hour.get(), self.end_min.get()) self.event['Description'] = self.desc.get('1.0', 'end') self.event['Category'] = self.category.get() if not self._task.get(): self.event['Task'] = False else: prog = self.task_progress.get() if prog == _('In Progress'): self.event['Task'] = self.in_progress.get() else: self.event['Task'] = TASK_REV_TRANSLATION[prog] self.event["WholeDay"] = self._whole_day.get() if not self._repeat.get(): self.event['Repeat'] = {} else: days = [] for i in range(7): if "selected" in self._week_days[i].state(): days.append(i) repeat = { 'Frequency': self._repeat_freq.get(), 'Limit': self._repeat_lim.get(), 'NbTimes': int(self.s_after.get()), 'EndDate': self.until_entry.get_date(), 'WeekDays': days } self.event['Repeat'] = repeat self.event.reminder_remove_all() for when, what in self.alarms: dt = int(when.get()) unit = FREQ_REV_TRANSLATION[what.get()] date = self.event['Start'] - timedelta(**{unit: dt}) self.event.reminder_add(date) if self._new: self.master.event_add(self.event) else: self.master.event_configure(self.event.iid) self.destroy() def cancel(self): if not self._new: self.master.widgets['Calendar'].add_event(self.event) self.destroy()
class BudgetPlaner(): def __init__(self): self.PATH = r'E:Python\Projects\03_Budget_Planner' #self.bg = '#E64D2C' self.bg = '#0294A5' self.fg = 'white' #self.fg = '#A79C93' def create_main_window(self): window = tk.Tk() window.title('Budget Planner') window.geometry('530x680') window.resizable(width=False, height=False) window.config(bg=self.bg) fontStyle = tk.font.Font(size=20) lb_main = tk.Label(window, text='BUDGET PLANNER', fg=self.fg, bg=self.bg, font=fontStyle) lb_main.pack() frame1 = tk.Frame(window, bg=self.bg) self.frame2 = tk.Frame(window, bg=self.bg) frame3 = tk.Frame(window, bg=self.bg) frame4 = tk.Frame(window, bg=self.bg) frame5 = tk.Frame(window, bg=self.bg) frame6 = tk.Frame(window, bg=self.bg) frame1.pack(fill='both', padx=10, pady=5) self.frame2.pack() frame3.pack(fill='both', padx=10, pady=5) frame4.pack(fill='both', padx=10, pady=5) frame5.pack(fill='both', expand='yes', padx=10, pady=5) frame6.pack(fill='both', padx=10, pady=5) lf_create = tk.LabelFrame(frame1, text='CREATE NEW FILE', fg=self.fg, bg=self.bg) lf_load = tk.LabelFrame(frame1, text='LOAD FILE', fg=self.fg, bg=self.bg) lf_view = tk.LabelFrame(frame3, text='PROJECT DATA', fg=self.fg, bg=self.bg) lf_add = tk.LabelFrame(frame4, text='ADD DATA', fg=self.fg, bg=self.bg) self.lf_info = tk.LabelFrame(frame4, text='BUDGET INFORMATION', fg=self.fg, bg=self.bg) lf_budget = tk.LabelFrame(frame6, text='MODIFY BUDGET', fg=self.fg, bg=self.bg) lf_create.pack(side=tk.LEFT, padx=10) lf_load.pack(side=tk.RIGHT, padx=10) lf_view.pack(fill='both', padx=10, pady=5) lf_add.pack(side=tk.LEFT, padx=10) self.lf_info.pack(side=tk.RIGHT, padx=10) lf_budget.pack(pady=5) # Create file area lb_create = tk.Label(lf_create, text='ENTER FILE NAME', width=15) lb_create.grid(row=0, column=0, padx=5, pady=5) ent_create = tk.Entry(lf_create, width=15) ent_create.grid(row=0, column=1, padx=5) # Create new file def create_file(filename): # Check if file with same name exists if os.path.exists(self.PATH + '\\' + '02_Input' + '\\' + filename + '.xlsx'): messagebox.showwarning('Warning', 'A file with same name exist.') elif len(filename) == 0: messagebox.showerror('Error', 'Provide a file name.') else: infile = self.PATH + '\\' + '02_Input' + '\\' + 'template.xlsx' outfile = self.PATH + '\\' + '02_Input' + '\\' + filename + '.xlsx' shutil.copy(infile, outfile) ent_create.delete(0, tk.END) messagebox.showinfo('Info', 'New file created.') but_create = tk.Button(lf_create, text='CREATE', width=10, command=lambda: create_file(ent_create.get())) but_create.grid(row=1, column=0, columnspan=2, pady=5) # Load file area lb_load = tk.Label(lf_load, text='ENTER FILE NAME', width=15) lb_load.grid(row=0, column=0, padx=5, pady=5) ent_load = tk.Entry(lf_load, width=15) ent_load.grid(row=0, column=1, padx=5) # Load the file and display data def load_file(filename): self.fn = filename if os.path.exists(self.PATH + '\\' + '02_Input' + '\\' + filename + '.xlsx'): self.read_file(filename) self.close_file() ent_load.delete(0, tk.END) messagebox.showinfo('Info', 'File loaded.') elif len(filename) == 0: messagebox.showerror('Error', 'Provide a file name.') else: messagebox.showerror('Error', 'File does not exist.') but_load = tk.Button(lf_load, text='LOAD', width=10, command=lambda: load_file(ent_load.get())) but_load.grid(row=1, column=0, columnspan=2, pady=5) # Project data area lb_fileinfo = tk.Label(self.frame2, text='Current File Name', width=30) lb_fileinfo.grid(row=0, column=0, padx=10, pady=5) #lb_fileinfo.place(x=10) self.lb_filename = tk.Label(self.frame2, text='NO FILES LOADED', width=30) self.lb_filename.grid(row=0, column=1, padx=10, pady=5) #lb_filename.place(x=20, y=25) col_dict = { 0: ['Sl No', 50], 1: ['Date', 95], 2: ['Activity', 240], 3: ['Cost', 80] } self.trv = tk.ttk.Treeview(lf_view, columns=col_dict.keys(), show='headings', height=8) #self.trv.pack(fill='both', padx=10, pady=10) self.trv.grid(row=1, columnspan=5, column=0, padx=10, pady=10) for c in range(4): self.trv.heading(c, text=col_dict[c][0]) self.trv.column(c, width=col_dict[c][1]) # Bind for single click, action is defined by single_click() function. self.trv.bind('<ButtonRelease-1>', self.single_click) # Bind for double click, action is defined by self.select_item function. self.trv.bind('<Double-1>', self.double_click) # New data area lb1 = tk.Label(lf_add, text='Sl No', width=10) lb1.grid(row=0, column=0, padx=5, pady=5) self.entar1 = tk.Entry(lf_add, width=20) self.entar1.grid(row=0, column=1, padx=5, pady=5) lb2 = tk.Label(lf_add, text='Date', width=10) lb2.grid(row=1, column=0, padx=5, pady=5) self.entar2 = DateEntry(lf_add, width=17, date_pattern='dd.mm.yyyy') self.entar2.grid(row=1, column=1) lb3 = tk.Label(lf_add, text='Activity', width=10) lb3.grid(row=2, column=0, padx=5, pady=5) self.entar3 = tk.Entry(lf_add, width=20) self.entar3.grid(row=2, column=1, padx=5, pady=5) lb4 = tk.Label(lf_add, text='Cost', width=10) lb4.grid(row=4, column=0, padx=5, pady=5) self.entar4 = tk.Entry(lf_add, width=20) self.entar4.grid(row=4, column=1, padx=5, pady=5) self.entar4.insert(0, '0.0') self.info_area() # Create various buttons def add_data(): self.read_file(self.fn) # get all the sl_no from the file slno_range = 'A5:' + 'A' + str(self.nrows) slno_list = self.sheet.range(slno_range).value # Convert 'slno_list' to datatype list if there is only one row in the file if type(slno_list) == float: slno_list = [slno_list] new_row = self.nrows + 1 self.close_file() try: int(self.entar1.get()) float(self.entar4.get()) except ValueError: messagebox.showerror('Error', 'Sl No or Cost not a valid value.') return if self.entar1.get() == '' or self.entar2.get( ) == '' or self.entar3.get() == '' or self.entar4.get() == '': messagebox.showerror('Error', 'Missing mandatory values.') elif float(self.entar1.get()) in slno_list: messagebox.showerror('Error', 'Sl No should be unique.') else: self.read_file(self.fn) self.sheet.range(new_row, 1).value = self.entar1.get() self.sheet.range(new_row, 2).value = self.entar2.get() self.sheet.range(new_row, 3).value = self.entar3.get() self.sheet.range(new_row, 4).value = self.entar4.get() self.close_file(param='write') clear_entry() messagebox.showinfo('Info', 'Data added.') but_add = tk.Button(frame5, text='ADD', width=12, command=add_data) but_add.place(x=10, y=8) def update_data(): self.read_file(self.fn) # get all the sl_no from the file slno_range = 'A5:' + 'A' + str(self.nrows) slno_list = self.sheet.range(slno_range).value # Convert 'slno_list' to datatype list if there is only one row in the file if type(slno_list) == float: slno_list = [slno_list] sl_idx = 0 self.close_file() try: int(self.entar1.get()) float(self.entar4.get()) except ValueError: messagebox.showerror('Error', 'Sl No or Cost not a valid value.') return if self.entar1.get() == '' or self.entar2.get( ) == '' or self.entar3.get() == '' or self.entar4.get() == '': messagebox.showerror('Error', 'Missing mandatory values') elif float(self.entar1.get()) not in slno_list: messagebox.showerror('Error', 'Sl No does not exist.') else: for r in range(5, self.nrows + 1): if float(self.entar1.get()) == slno_list[sl_idx]: self.read_file(self.fn) self.sheet.range(r, 2).value = self.entar2.get() self.sheet.range(r, 3).value = self.entar3.get() self.sheet.range(r, 4).value = self.entar4.get() self.close_file(param='write') clear_entry() messagebox.showinfo('Info', 'Data updated.') break else: sl_idx += 1 but_update = tk.Button(frame5, text='UPDATE', width=12, command=update_data) but_update.place(x=142, y=8) def delete_data(): self.read_file(self.fn) sl_idx = 0 slno_range = 'A5:' + 'A' + str(self.nrows) slno_list = self.sheet.range(slno_range).value slno_to_delete = self.item['values'][0] if float(slno_to_delete) in slno_list: for r in range(5, self.nrows + 1): if float(slno_to_delete) == slno_list[sl_idx]: del_range = 'A' + str(r) + ':' + 'D' + str(r) self.sheet.range(del_range).api.Delete( constants.DeleteShiftDirection.xlShiftUp) self.close_file(param='write') clear_entry() messagebox.showinfo('Info', 'Selected row deleted.') break else: sl_idx += 1 else: self.close_file() messagebox.showerror('Error', 'Invalid Sl No.') but_delete = tk.Button(frame5, text='DELETE', width=12, command=delete_data) but_delete.place(x=274, y=8) # Clear entry field / set it to defaul value def clear_entry(): self.entar1.delete(0, tk.END) self.entar2.set_date(datetime.today()) self.entar3.delete(0, tk.END) self.entar4.delete(0, tk.END) self.entar4.insert(0, '0.0') but_clear = tk.Button(frame5, text='CLEAR', width=12, command=clear_entry) but_clear.place(x=406, y=8) # Create budget update area def modify_budget(): self.read_file(self.fn) self.sheet.range(1, 2).value = ent_budget.get() self.close_file('write') ent_budget.delete(0, tk.END) ent_budget.insert(0, '0.0') messagebox.showinfo('Info', 'Budget amount updated.') lb_budget = tk.Label(lf_budget, text='Budget Amount', width=20) lb_budget.grid(row=0, column=0, padx=10, pady=5) ent_budget = tk.Entry(lf_budget, width=10) ent_budget.grid(row=0, column=1, padx=10) ent_budget.insert(0, '0.0') bt_budget = tk.Button(lf_budget, text='ADD / UPDATE', width=12, command=modify_budget) bt_budget.grid(row=0, column=2, padx=10) window.mainloop() # Information area def info_area(self, budget_amt=0, total_spent=0, balance=0, status='Good'): lb_info1 = tk.Label(self.lf_info, text='Budget allocated', width=20) lb_info1.grid(row=0, column=0, padx=5, pady=5) lb_amt = tk.Label(self.lf_info, text=budget_amt, width=10) lb_amt.grid(row=0, column=1, padx=5, pady=5) lb_info2 = tk.Label(self.lf_info, text='Total Spent', width=20) lb_info2.grid(row=1, column=0, padx=5, pady=5) lb_tot = tk.Label(self.lf_info, text=total_spent, width=10) lb_tot.grid(row=1, column=1, padx=5, pady=5) lb_info3 = tk.Label(self.lf_info, text='Balance Available', width=20) lb_info3.grid(row=2, column=0, padx=5, pady=5) lb_bal = tk.Label(self.lf_info, text=balance, width=10) lb_bal.grid(row=2, column=1, padx=5, pady=5) lb_info4 = tk.Label(self.lf_info, text='Budget Status', width=20) lb_info4.grid(row=3, column=0, padx=5, pady=5) lb_stat = tk.Label(self.lf_info, text=status, width=10) lb_stat.grid(row=3, column=1, padx=5, pady=5) # Read file def read_file(self, filename): self.app = xw.App(visible=False, add_book=False) self.file = self.app.books.open(self.PATH + '\\' + '02_Input' + '\\' + self.fn + '.xlsx') self.sheet = self.file.sheets['data'] self.nrows = self.sheet.range(1, 1).end('down').row # Save and close file def close_file(self, param='read'): if param == 'write': self.file.save() self.nrows = self.sheet.range(1, 1).end('down').row self.get_amt_data() self.display_data() self.file.close() self.app.quit() # Get data to populate information area def get_amt_data(self): budget_amt = self.sheet.range('B1').value total_spent = self.sheet.range('B2').value balance = self.sheet.range('B3').value status = self.sheet.range('E1').value self.info_area(budget_amt, total_spent, balance, status) # Display data in treeview area def display_data(self): self.lb_filename = tk.Label(self.frame2, text=self.fn, width=30) self.lb_filename.grid(row=0, column=1, padx=10, pady=5) self.trv.delete(*self.trv.get_children()) data = [] for r in range(5, self.nrows + 1): sl_no = int(self.sheet.range(r, 1).value) date = self.sheet.range(r, 2).value activity = self.sheet.range(r, 3).value cost = self.sheet.range(r, 4).value data = [sl_no, date, activity, cost] self.trv.insert('', tk.END, values=data) # Function for tree view bind single click. def single_click(self, event): self.item = self.trv.item(self.trv.focus()) # Function for tree view bind double click. def double_click(self, event): try: self.item = self.trv.item(self.trv.focus()) self.entar1.delete(0, tk.END) self.entar1.insert(0, self.item['values'][0]) self.entar2.set_date(self.item['values'][1]) self.entar3.delete(0, tk.END) self.entar3.insert(0, self.item['values'][2]) self.entar4.delete(0, tk.END) self.entar4.insert(0, self.item['values'][3]) except IndexError: pass
outputs_filepath_entry = ttk.Entry(mainframe, textvariable=outputs_filepath) outputs_filepath_entry.grid(column=2, row=output_row, sticky=(W, E), columnspan=2) ttk.Button(mainframe, text="Browse", command=file_explore_outputs).grid(column=4, row=output_row, sticky=W) ttk.Label(mainframe, text="Delete entries from before:").grid(column=1, row=date_row, sticky=W) default_date = date.today() - timedelta(days=2) delete_before_entry = DateEntry(mainframe, locale='en_UK') delete_before_entry.set_date(default_date) delete_before_entry.grid(column=3, row=date_row, sticky=(W, E)) delete_before_entry.grid_remove() def show_or_hide_date(): check_flag = delete_flag.get() if check_flag == 0: delete_before_entry.grid_remove() elif check_flag == 1: delete_before_entry.grid(column=3, row=date_row, sticky=(W, E)) delete_flag = IntVar() delete_flag.set(1) date_toggle = ttk.Checkbutton(mainframe,
class RequestsPage(tk.Frame): def __init__(self, parent, controller, conn, **kwargs): tk.Frame.__init__(self, parent) self.controller = controller self.conn = conn self.controller.title('Майстерня "ПрацівничОк"') self.controller.iconphoto(False, tk.PhotoImage(file='spanner.png')) # Top frame for main label and icon top_frame = tk.Frame(self, borderwidth=10, bg='#9E9E9E') top_frame.pack(fill='x', side='top') #icon icon = tk.PhotoImage(file='spanner.png') icon_label = tk.Label(top_frame, image=icon, bg='#9E9E9E') icon_label.pack(side='left') icon_label.image = icon #main label heading_label = tk.Label(top_frame, text=' Запити', font=('dejavu sans mono', 40), pady=15, fg='#212121', bg='#9E9E9E') heading_label.pack(side="top") #label bellow main label selection_label = tk.Label(self, text='Оберіть запит та введіть дані:', font=('dejavu sans mono', 20), bg='#BDBDBD', fg='white', anchor='w') selection_label.pack(fill='x') #frame for requests requests_frame = tk.Frame(self, bg='#F5F5F5') requests_frame.pack(fill='both', expand=True) self.answer_message = tk.Message(requests_frame, width=600, font=('dejavu sans mono', 12), anchor='n', fg='#212121', bg='#F5F5F5') self.answer_message.grid(row=0, column=3, padx=10, pady=10, sticky='N', rowspan=20) req1_label = tk.Label( requests_frame, new_lbl_args, text= '1) Телефони та прізвища клієнтів, що замовили роботу, що коштує більше ніж X$' ) req1_label.grid(row=0, column=0, columnspan=2) self.req1_entry = tk.Entry(requests_frame) self.req1_entry.grid(row=1, column=0) req1_button = tk.Button(requests_frame, new_btn_args, command=self.proccess_req1) req1_button.grid(row=1, column=1, sticky='E') req2_label = tk.Label( requests_frame, new_lbl_args, text= '2) Коди та назви роботи, яку виконують майстри, винагорода яких менша за Х%' ) req2_label.grid(row=2, column=0, columnspan=2) self.req2_entry = tk.Entry(requests_frame) self.req2_entry.grid(row=3, column=0) req2_button = tk.Button(requests_frame, new_btn_args, command=self.proccess_req2) req2_button.grid(row=3, column=1, sticky='E') req3_label = tk.Label( requests_frame, new_lbl_args, text= '3) Коди та прізвища майстрів, що прийняли замовлення не раніше за день Х' ) req3_label.grid(row=4, column=0, columnspan=2) self.req3_entry = DateEntry(requests_frame, background='#7C4DFF', locale='uk', selectbackground='#7C4DFF') self.req3_entry.grid(row=5, column=0) req3_button = tk.Button(requests_frame, new_btn_args, command=self.proccess_req3) req3_button.grid(row=5, column=1, sticky='E') req4_label = tk.Label( requests_frame, new_lbl_args, text='4) Телефони та прізвища клієнтів, що замовили Х виробів') req4_label.grid(row=6, column=0, columnspan=2) self.req4_entry = tk.Entry(requests_frame) self.req4_entry.grid(row=7, column=0) req4_button = tk.Button(requests_frame, new_btn_args, command=self.proccess_req4) req4_button.grid(row=7, column=1, sticky='E') req5_label = tk.Label( requests_frame, new_lbl_args, text='5) Код та прізвище майстрів, що не виконують виріб Х') req5_label.grid(row=8, column=0, columnspan=2) self.req5_entry = ttk.Combobox(requests_frame, state='readonly') self.req5_entry.grid(row=9, column=0) req5_button = tk.Button(requests_frame, new_btn_args, command=self.proccess_req5) req5_button.grid(row=9, column=1, sticky='E') req6_label = tk.Label( requests_frame, new_lbl_args, text= '6) Код та прізвища майстрів, що виконують такі ж роботи, що й майстер Х' ) req6_label.grid(row=10, column=0, columnspan=2) self.req6_entry = ttk.Combobox(requests_frame, state='readonly') self.req6_entry.grid(row=11, column=0) req6_button = tk.Button(requests_frame, new_btn_args, command=self.proccess_req6) req6_button.grid(row=11, column=1, sticky='E') req7_label = tk.Label( requests_frame, new_lbl_args, text= '7) Телефони та прізвища клієнтів, що зробили замовлення раніше, за клієнта Х' ) req7_label.grid(row=12, column=0, columnspan=2) self.req7_entry = ttk.Combobox(requests_frame, state='readonly') self.req7_entry.grid(row=13, column=0) req7_button = tk.Button(requests_frame, new_btn_args, command=self.proccess_req7) req7_button.grid(row=13, column=1, sticky='E') req8_label = tk.Label( requests_frame, new_lbl_args, text='8) Код та назва роботи, що замовив тільки клієнт Х') req8_label.grid(row=14, column=0, columnspan=2) self.req8_entry = ttk.Combobox(requests_frame, state='readonly') self.req8_entry.grid(row=15, column=0) req8_button = tk.Button(requests_frame, new_btn_args, command=self.proccess_req8) req8_button.grid(row=15, column=1, sticky='E') #return to menu button back_button = tk.Button(requests_frame, button_args, command=lambda: self.return_clicked(), text='Повернутись до меню') back_button.grid(row=16, column=0, pady=20) def return_clicked(self): self.controller.show_frame('StartPage') self.clear_entries() self.clear_message() def clear_message(self): pass def clear_entries(self): self.req1_entry.delete(0, 'end') self.req2_entry.delete(0, 'end') self.req3_entry.set_date(datetime.datetime.now()) self.req4_entry.delete(0, 'end') self.req5_entry.set('') self.req6_entry.set('') self.req7_entry.set('') self.req8_entry.set('') def proccess_req8(self): x = re.findall( "\d+", self.req8_entry.get())[0] if self.req8_entry.get() else '' if not x: self.update_text('') return command = ''' SELECT p1.code, p1.work_name FROM pricelist AS p1 INNER JOIN order_details AS d2 ON p1.code = d2.work_code WHERE NOT EXISTS ( SELECT d1.work_code FROM order_details AS d1 INNER JOIN ( orders AS o1 INNER JOIN clients AS c1 ON o1.client_phone = c1.phone ) ON d1.order_code = o1.code WHERE p1.code = d1.work_code AND c1.phone != %s);''' self.proccess_query(x, command) def proccess_req7(self): x = re.findall( "\d+", self.req7_entry.get())[0] if self.req7_entry.get() else '' if not x: self.update_text('') return command = ''' SELECT c1.phone, c1.lastname FROM clients AS c1 INNER JOIN orders AS o1 ON c1.phone = o1.client_phone WHERE EXISTS ( SELECT 1 FROM clients AS c2 INNER JOIN orders AS o2 ON c2.phone = o2.client_phone WHERE c2.phone = %s AND o2.date > o1.date );''' self.proccess_query(x, command) def get_client_info(self): cur = self.conn.cursor() cur.execute('SELECT phone, lastname FROM clients;') res = cur.fetchall() cur.close() return tuple(res) def proccess_req6(self): x = re.findall( "\d+", self.req6_entry.get())[0] if self.req6_entry.get() else '' if not x: self.update_text('') return command = ''' SELECT m1.code, m1.lastname FROM masters AS m1 WHERE NOT EXISTS ( (SELECT DISTINCT d1.work_code FROM order_details AS d1 INNER JOIN masters AS m2 ON m2.code = d1.master_code WHERE m2.code = %s) EXCEPT ( SELECT DISTINCT d2.work_code FROM order_details AS d2 WHERE m1.code = d2.master_code) ); ''' self.proccess_query(x, command) def get_master_info(self): cur = self.conn.cursor() cur.execute('SELECT code, lastname FROM masters;') res = cur.fetchall() cur.close() return res def get_work_info(self): cur = self.conn.cursor() cur.execute('SELECT code, work_name FROM pricelist;') res = cur.fetchall() cur.close() return res def proccess_req5(self): x = re.findall( "\d+", self.req5_entry.get())[0] if self.req5_entry.get() else '' if not x: self.update_text('') return command = ''' SELECT m1.code, m1.lastname FROM masters AS m1 WHERE m1.code NOT IN ( SELECT m2.code FROM masters AS m2 INNER JOIN order_details AS d1 ON m2.code = d1.work_code WHERE d1.work_code = %s);''' self.proccess_query(x, command) def proccess_req4(self): x = self.req4_entry.get() if not x.isdigit(): self.update_text('') return command = ''' SELECT c1.phone, c1.lastname FROM clients AS c1 INNER JOIN ( orders AS o1 INNER JOIN order_details AS d1 ON o1.code = d1.order_code) ON c1.phone = o1.client_phone GROUP BY c1.phone HAVING COUNT(d1.work_code) = %s; ''' self.proccess_query(x, command) def proccess_req3(self): x = self.req3_entry.get_date() command = ''' SELECT DISTINCT masters.code, masters.lastname FROM masters INNER JOIN (order_details INNER JOIN orders ON order_details.order_code = orders.code ) ON masters.code = order_details.master_code WHERE orders.date >= %s''' self.proccess_query(x, command) def proccess_req2(self): x = self.req2_entry.get() if not x.isdigit(): self.update_text('') return command = ''' SELECT DISTINCT pricelist.code, pricelist.work_name FROM pricelist INNER JOIN ( order_details INNER JOIN masters ON order_details.master_code = masters.code ) ON pricelist.code = order_details.work_code WHERE masters.reward_percent < %s''' self.proccess_query(x, command) def proccess_req1(self): x = self.req1_entry.get() if not x.isdigit(): self.update_text('') return command = ''' SELECT DISTINCT clients.phone, clients.lastname FROM clients INNER JOIN ( orders INNER JOIN ( order_details INNER JOIN pricelist ON order_details.work_code = pricelist.code ) ON orders.code = order_details.order_code ) ON clients.phone = orders.client_phone WHERE pricelist.price > %s''' self.proccess_query(x, command) def proccess_query(self, x, command): cur = self.conn.cursor() cur.execute(command, [x]) res = cur.fetchall() cur.close() self.update_text(res) def update_text(self, info): if info == '': message = 'Неправильне введення' elif info == []: message = 'Порожній результат' else: message = '\n'.join([' '.join([str(j) for j in i]) for i in info]) self.answer_message.config(text=message) def update_data(self): self.req5_entry['values'] = self.get_work_info() self.req6_entry['values'] = self.get_master_info() self.req7_entry['values'] = self.get_client_info() self.req8_entry['values'] = self.get_client_info()
class change_table(tk.Frame): """Class for reminders creation and modification.""" def __init__(self, master=None, true_master=None, new_num=-1, **kw): """Initialize the window.""" super().__init__(master=true_master, **kw) self.master = master self.true_master = true_master self.num = new_num self.create_widg() def hour_change(self, movement): """Change hour field by these rules.""" day_delta = datetime.timedelta(days=1) where_to = int(movement) if (self.hour.get() != ''): num = int(self.hour.get()) if (where_to == -1): if (num < 23): self.hour.set(num + 1) elif (num == 23): self.hour.set(0) self.cal.set_date(self.cal.get_date() + day_delta) elif (where_to == 1): if (num > 0): self.hour.set(num - 1) elif (num == 0): self.cal.set_date(self.cal.get_date() - day_delta) self.hour.set(23) else: self.hour.set(0) def minute_change(self, movement): """Change minutes field by these rules.""" where_to = int(movement) if (self.minute.get() != ''): num = int(self.minute.get()) if (where_to == -1): if (num < 59): self.minute.set(num + 1) elif (num == 59): self.minute.set(0) self.hour_change(-1) elif (where_to == 1): if (num > 0): self.minute.set(num - 1) elif (num == 0): self.minute.set(59) self.hour_change(1) else: self.minute.set(0) def on_closing(self): """Do some actions if window is closing.""" if self.changed(): if tk.messagebox.askyesno(_("Quit"), _("Do you want to quit?\n" "To save the changes," "you have to press OK")): self.true_master.destroy() else: self.true_master.destroy() def changed(self): """Define if the window content changed.""" new_time = datetime.time(int(self.hour.get()), int(self.minute.get())) new_date = self.cal.get_date() in_date = datetime.datetime(new_date.year, new_date.month, new_date.day, new_time.hour, new_time.minute, new_time.second) return (((self.cur_description) != ( self.ent.get())) and ( self.ent.get() != '')) or ( ' '.join(self.cur_date_time) != str(in_date))\ and (in_date) def create_widg(self): """Creation of window widgets.""" self.tim_lab = tk.Label(self, text=_("Date:")) self.tim_lab.grid(row=0, column=0, sticky="NEWS", columnspan=4, padx=4) self.cal = DateEntry(self, width=10, background='darkblue', foreground='white', borderwidth=2) self.cal.grid(column=3, row=0, sticky="NEWS", columnspan=10, ipady=4, pady=10) self.hour = tk.StringVar() self.minute = tk.StringVar() hours = self.register(self.master.hours) minutes = self.register(self.master.minutes) self.tim_lab = tk.Label(self, text=_("Time:")) self.tim_lab.grid(row=2, column=0, sticky="NEWS", columnspan=3, padx=4) self.tim_h = tk.Entry(self, validate='key', textvariable=self.hour, validatecommand=(hours, '%P'), width=2, justify='center') self.tim_h.grid(row=2, column=3, sticky="E", ipady=2, pady=10) self.hour_scroll = tk.Scrollbar(self, command=self.hour_change) self.hour_scroll.grid(row=2, column=4, sticky="E", ipady=0, pady=10) self.two_dots = tk.Label(self, text=":") self.two_dots.grid(row=2, column=5, sticky="E", ipady=2, pady=10) self.tim_m = tk.Entry(self, validate='key', textvariable=self.minute, validatecommand=(minutes, '%P'), width=2, justify='center') self.tim_m.grid(row=2, column=6, sticky="E", ipady=2, pady=10) self.minute_scroll = tk.Scrollbar(self, command=self.minute_change) self.minute_scroll.grid(row=2, column=7, sticky="E", ipady=0, pady=10) self.ent_lab = tk.Label(self, text=_("Description:")) self.ent_lab.grid(row=3, column=0, columnspan=3, sticky="NEWS", padx=4) self.ent = tk.Entry(self, width=10, justify='center') self.ent.grid(row=3, column=3, columnspan=10, sticky="NEWS", ipady=5, pady=10) self.imp = tk.IntVar() self.imp_che = tk.Checkbutton(self, text=_("Important reminder"), variable=self.imp, onvalue=1, offvalue=0) self.imp_che.grid(row=4, column=0, columnspan=8, sticky="NEWS", padx=2) if (self.num != -1): self.cur_date_time = self.master.mas[4 * self.num + 1].split(' ') self.cur_date = self.cur_date_time[0] self.cur_time = self.cur_date_time[1] cur_hour_min = self.cur_time.split(':') cur_hour = cur_hour_min[0] cur_min = cur_hour_min[1] self.cur_date = self.cur_date.split('-') self.cal.set_date(datetime.date(int(self.cur_date[0]), int(self.cur_date[1]), int(self.cur_date[2]))) self.hour.set(cur_hour) self.minute.set(cur_min) self.cur_description = self.master.mas[4 * self.num + 2] self.ent.insert(0, self.cur_description) if (4 * self.num + 1 in self.master.imp_list): self.imp.set(1) self.old_imp = self.imp.get() self.B = tk.Button(self, text="OK") self.B.grid(row=5, column=0, columnspan=8, sticky="NEWS", padx=2, pady=2) if (self.num != -1): self.B.configure(command=self.ed_sel) else: self.B.configure(command=self.add_sel) def check_correct(self): """Check if the content of window is correct.""" correct = True if not (self.hour.get()) or not (self.minute.get()): tk.messagebox.showerror(_("Time Error"), _("Input hours and minutes!")) correct = False else: self.cur_time = datetime.time(int(self.hour.get()), int(self.minute.get())) if (self.ent.get() == ''): tk.messagebox.showerror(_("Description Error"), _("Input the description!")) correct = False else: self.cur_rem = self.ent.get() self.cur_date = self.cal.get_date() if (correct): self.in_date = datetime.datetime(self.cur_date.year, self.cur_date.month, self.cur_date.day, self.cur_time.hour, self.cur_time.minute, self.cur_time.second) if (datetime.datetime.now() > self.in_date): tkinter.messagebox.showerror(_("Wrong data"), _("Time travel, huh?\n" "Why do you need a reminder" "to a previous events?\n" "Change the date!")) correct = False return correct def add_sel(self): """Add Reminder to the list.""" if (self.check_correct()): if (self.master.Rlist.get( tk.END) == _("There's no reminders yet!")): self.master.Rlist.delete(tk.END) date_inp = 0 else: date_inp = self.master.date_in(self.in_date) self.add_el(date_inp) self.master.list.set(self.master.mas) self.master.color_change(date_inp, 4) self.master.outdated_events() if (self.imp.get()): self.master.imp_list.append(date_inp + 1) self.master.Rlist.itemconfig(date_inp + 1, foreground="red") self.master.im_count.set(len(self.master.imp_list)) self.master.new_num() self.master.ev_count.set(len(self.master.mas) // 4) self.true_master.destroy() def ed_sel(self): """Edit the Reminder from the list.""" if (self.check_correct()): self.master.mas[4 * self.num + 1] = str(self.in_date) self.master.mas[4 * self.num + 2] = self.cur_rem self.master.list.set(self.master.mas) if (self.imp.get() != self.old_imp): if (self.old_imp == 0): self.master.imp_list.append(4 * self.num + 1) else: self.master.imp_list.remove(4 * self.num + 1) self.master.set_imp() self.master.new_num() self.edit_list() self.true_master.destroy() def edit_list(self): """Modify list of all reminders, including important ones.""" old_date = self.master.mas.index(str(self.in_date)) if (old_date) in self.master.imp_list: self.master.imp_list.remove(old_date) del self.master.mas[old_date - 1:old_date + 3] self.master.list.set(self.master.mas) date_put = self.master.date_in(self.in_date) self.add_el(date_put) self.master.list.set(self.master.mas) forw = 2 * (date_put + 1 < old_date) - 1 for i in range(len(self.master.imp_list)): if (min(old_date, date_put + 1) <= self.master. imp_list[i] <= max(old_date, date_put + 1)): self.master.imp_list[i] += forw * 4 if (self.imp.get()): self.master.imp_list.append(date_put + 1) self.master.set_imp() def add_el(self, date_num): """Insert Reminder information into list.""" self.master.mas.insert(date_num, "") self.master.mas.insert(date_num + 1, "{a} {b}". format(a=self.cur_date, b=self.cur_time)) self.master.mas.insert(date_num + 2, self.cur_rem) self.master.mas.insert(date_num + 3, "")
class PaginaFactura(tk.Frame): def __init__(self, padre, controlador, cliente=None): """INICIAR LOS GRÁFICOS DE LA PÁGINA DE FACTURAS""" tk.Frame.__init__(self, padre) self.cliente = cliente self.controlador = controlador ###################################### #CABECERA ###################################### boton_inicio = tk.Button( self, text="INICIO", command=lambda: controlador.mostrar_marco("PaginaInicial")) boton_inicio.grid(row=00, column=0) boton_ver_clientes = tk.Button(self, text="Ver facturas", command=lambda: self.ver_facturas()) boton_ver_clientes.grid(row=1, column=0) boton_actualizar = tk.Button(self, text="actualizar facturas", command=lambda: self.editar_facturas()) boton_actualizar.grid(row=1, column=1) boton_añadir = tk.Button(self, text="Añadir factura", command=lambda: self.añadir_factura()) boton_añadir.grid(row=2, column=0) boton_eliminar = tk.Button(self, text="Eliminar factura", command=lambda: self.eliminar_factura()) boton_eliminar.grid(row=2, column=1) boton_borrar = tk.Button(self, text="Borrar cuadros", command=lambda: self.borrar()) boton_borrar.grid(row=2, column=2) #caja de facturas self.caja_facturas = tk.Listbox(self, height=10, width=70) self.caja_facturas.grid(row=0, column=4, rowspan=9, columnspan=5) self.scroll_facturas = tk.Scrollbar(self) self.scroll_facturas.grid(row=0, column=10, rowspan=9) self.caja_facturas.configure(yscrollcommand=self.scroll_facturas.set) self.scroll_facturas.configure(command=self.caja_facturas.yview) self.caja_facturas.bind('<<ListboxSelect>>', self.caja_factura_seleccionada) boton = ttk.Button( self, text="Elegir Cliente para la factura", command=lambda: controlador.mostrar_marco("PaginaCliente")) boton.grid(row=7, column=1) #ruta, factura, fecha, nombre, direccion, cp, dni, tratamientos, comentario, iva, descuento, total boton = ttk.Button(self, text="Imprimir PDF", command=self.imprimir) boton.grid(row=7, column=2) #título self.label = tk.Label(self, text="Factura", font=self.controlador.fuente_titulo) self.label.grid(row=10, column=0) self.texto_codigo = StringVar() self.etiqueta_codigo = tk.Label(self, text="Codigo de la factura") self.etiqueta_codigo.grid(row=11, column=0) self.cuadro_codigo = ttk.Entry(self, textvariable=self.texto_codigo, justify=tk.RIGHT) self.cuadro_codigo.grid(row=11, column=1) self.auto_id_factura = controlador.marcos[ 'PaginaInicial'].cuadro_resultado.get() self.cuadro_codigo.insert(END, self.auto_id_factura) self.texto_id_factura = StringVar() self.texto_id_factura.set("Factura no seleccionada") self.etiqueta_id_factura = tk.Label(self, text="ID Factura") self.etiqueta_id_factura.grid(row=11, column=2) self.cuadro_id_factura = ttk.Label(self, textvariable=self.texto_id_factura, justify=tk.RIGHT) self.cuadro_id_factura.grid(row=11, column=3) self.texto_cliente = StringVar() self.texto_cliente.set("Sin cliente seleccionado") self.etiqueta_cliente = tk.Label(self, text="Nº Cliente asociado:") self.etiqueta_cliente.grid(row=11, column=4) self.etiqueta_cliente_asignado = ttk.Label( self, textvariable=self.texto_cliente, justify=tk.RIGHT) self.etiqueta_cliente_asignado.grid(row=11, column=5) self.texto_nombre = StringVar() self.etiqueta_nombre = tk.Label(self, text="Nombre: ") self.etiqueta_nombre.grid(row=12, column=0) self.cuadro_nombre = ttk.Entry(self, textvariable=self.texto_nombre, justify=tk.RIGHT) self.cuadro_nombre.grid(row=12, column=1) self.texto_dni = StringVar() self.etiqueta_dni = tk.Label(self, text="DNI") self.etiqueta_dni.grid(row=12, column=2) self.cuadro_dni = ttk.Entry(self, textvariable=self.texto_dni, justify=tk.RIGHT) self.cuadro_dni.grid(row=12, column=3) self.texto_direccion = StringVar() self.etiqueta_direccion = tk.Label(self, text="Direccion") self.etiqueta_direccion.grid(row=13, column=0) self.cuadro_direccion = ttk.Entry(self, textvariable=self.texto_direccion, justify=tk.RIGHT) self.cuadro_direccion.grid(row=13, column=1) self.texto_cp = StringVar() self.etiqueta_cp = tk.Label(self, text="Código postal") self.etiqueta_cp.grid(row=13, column=2) self.cuadro_cp = ttk.Entry(self, textvariable=self.texto_cp, justify=tk.RIGHT) self.cuadro_cp.grid(row=13, column=3) self.etiqueta_fecha = tk.Label(self, text="Fecha factura") self.etiqueta_fecha.grid(row=14, column=0) self.cal = DateEntry(self, width=12, background='darkblue', foreground='white', borderwidth=2, locale='es_ES') self.cal.grid(row=14, column=1) self.etiqueta_comentarios = tk.Label(self, text="Comentarios") self.etiqueta_comentarios.grid(row=15, column=0) self.cuadro_comentarios = tk.Text(self, width=70, height=10, wrap='word') self.cuadro_comentarios.grid(row=15, column=1, columnspan=3, rowspan=5) ############################### #SERVICIOS ############################## self.label = tk.Label(self, text="Servicios", font=self.controlador.fuente_titulo) self.label.grid(row=129, column=0) #caja de servicios self.caja_servicios = tk.Listbox(self, height=10, width=35) self.caja_servicios.grid(row=130, column=1, rowspan=9) self.scroll_servicios = tk.Scrollbar(self) self.scroll_servicios.grid(row=130, column=2, rowspan=9) self.caja_servicios.configure(yscrollcommand=self.scroll_servicios.set) self.scroll_servicios.configure(command=self.caja_servicios.yview) self.caja_servicios.bind('<<ListboxSelect>>', self.caja_servicio_seleccionado) boton_añadir_servicio = tk.Button( self, text="Añadir servicio", command=lambda: self.añadir_servicio()) boton_añadir_servicio.grid(row=130, column=4) boton_eliminar_servicio = tk.Button( self, text="Eliminar servicio", command=lambda: self.eliminar_servicio()) boton_eliminar_servicio.grid(row=131, column=4) boton_editar_servicio = tk.Button( self, text="Editar servicio", command=lambda: self.editar_servicio()) boton_editar_servicio.grid(row=132, column=4) self.etiqueta_fecha_servicio = tk.Label(self, text="Fecha servicio") self.etiqueta_fecha_servicio.grid(row=133, column=3) self.cal_servicio = DateEntry(self, width=12, background='darkblue', foreground='white', borderwidth=2, locale='es_ES') self.cal_servicio.grid(row=133, column=4) self.texto_tratamiento = StringVar() self.etiqueta_tratamiento = tk.Label(self, text="Tratamiento: ") self.etiqueta_tratamiento.grid(row=134, column=3) self.cuadro_tratamiento = ttk.Entry( self, textvariable=self.texto_tratamiento, justify=tk.RIGHT) self.cuadro_tratamiento.grid(row=134, column=4) self.cuadro_tratamiento.delete(0, END) self.cuadro_tratamiento.insert(END, "Sesión de Fisioterapia") self.texto_precio_tratamiento = StringVar() self.etiqueta_precio_tratamiento = tk.Label(self, text="€: ") self.etiqueta_precio_tratamiento.grid(row=135, column=3) self.cuadro_precio_tratamiento = ttk.Entry( self, textvariable=self.texto_precio_tratamiento, justify=tk.RIGHT) self.cuadro_precio_tratamiento.grid(row=135, column=4) self.cuadro_precio_tratamiento.delete(0, END) self.cuadro_precio_tratamiento.insert(END, 28) ############################### #PIE DE FACTURA ############################## self.label = tk.Label(self, text="Calculos", font=self.controlador.fuente_titulo) self.label.grid(row=140, column=0) #calculos self.etiqueta_iva = tk.Label(self, text="IVA") self.etiqueta_iva.grid(row=141, column=0) self.combo_iva = ttk.Combobox(self) self.combo_iva["values"] = [0, 4, 16, 21] self.combo_iva.set(0) self.combo_iva.bind("<<ComboboxSelected>>", self.combo_seleccionado) self.combo_iva.grid(row=141, column=1) self.texto_descuento = StringVar() self.etiqueta_descuento = tk.Label(self, text="Descuento") self.etiqueta_descuento.grid(row=150, column=0) self.cuadro_descuento = ttk.Entry(self, textvariable=self.texto_descuento, justify=tk.RIGHT) self.cuadro_descuento.grid(row=150, column=1) self.cuadro_descuento.bind('<Return>', self.combo_seleccionado) self.cuadro_descuento.insert(END, "0") self.texto_total = StringVar() self.etiqueta_total = tk.Label(self, text="TOTAL") self.etiqueta_total.grid(row=160, column=0) self.cuadro_total = ttk.Entry(self, textvariable=self.texto_total, justify=tk.RIGHT) self.cuadro_total.grid(row=160, column=1) # iniciar el cuadro con las facturas self.ver_facturas() ############################### #FUNCIONES ############################## def imprimir(self): print("impresión pulsado") print(self.controlador.ruta, self.cuadro_codigo.get(), self.cal.get(), self.cuadro_nombre.get(), self.cuadro_direccion.get(), self.cuadro_cp.get(), self.cuadro_dni.get(), self.ver_servicios(), self.cuadro_comentarios.get("1.0", END), self.combo_iva.get(), self.cuadro_descuento.get(), self.cuadro_total.get()) imprimir(self.controlador.ruta, self.cuadro_codigo.get(), self.cal.get(), self.cuadro_nombre.get(), self.cuadro_direccion.get(), self.cuadro_cp.get(), self.cuadro_dni.get(), self.ver_servicios(), self.cuadro_comentarios.get("1.0", END), self.combo_iva.get(), self.cuadro_descuento.get(), self.cuadro_total.get()) def combo_seleccionado(self, event): iva_seleccionado = self.combo_iva.get() actualizarRegistro("FACTURA", "IVA_ID", self.combo_iva.get(), "ID", self.texto_id_factura.get()) actualizarRegistro("FACTURA", "DESCUENTO", self.cuadro_descuento.get(), "ID", self.texto_id_factura.get()) self.ver_facturas() self.actualizar_total() def editar_facturas(self): actualizarRegistro("FACTURA", "CODIGO_FACTURA", self.cuadro_codigo.get(), "ID", self.texto_id_factura.get()) actualizarRegistro("FACTURA", "FECHA_FACTURA", cal2fecha(self.cal.get()), "ID", self.texto_id_factura.get()) actualizarRegistro("FACTURA", "IVA_ID", self.combo_iva.get(), "ID", self.texto_id_factura.get()) actualizarRegistro("FACTURA", "DESCUENTO", self.cuadro_descuento.get(), "ID", self.texto_id_factura.get()) actualizarRegistro("FACTURA", "CLIENTE_ID", self.texto_cliente.get(), "ID", self.texto_id_factura.get()) actualizarRegistro("FACTURA", "COMENTARIO", self.cuadro_comentarios.get("1.0", END), "ID", self.texto_id_factura.get()) self.ver_facturas() self.actualizar_total() def añadir_factura(self): datos = [(self.cuadro_codigo.get(), cal2fecha(self.cal.get()), self.combo_iva.get(), self.cuadro_descuento.get(), self.ID_cliente_asociado, self.cuadro_comentarios.get("1.0", END))] print(self.cuadro_comentarios.get("1.0", END)) crearFactura(datos) self.borrar() self.texto_id_factura.set(leerTodo("FACTURA")[-1][0]) self.ver_facturas() self.controlador.marcos["PaginaInicial"].siguienteNumero() def editar_servicio(self): #FECHA_SERVICIO , TRATAMIENTO, PRECIO_FINAL, FACTURA_ID actualizarRegistro("SERVICIO", "FECHA_SERVICIO", cal2fecha(self.cal_servicio.get()), "ID", tupla_servicios_seleccionados[0]) actualizarRegistro("SERVICIO", "TRATAMIENTO", self.cuadro_tratamiento.get(), "ID", tupla_servicios_seleccionados[0]) actualizarRegistro("SERVICIO", "PRECIO_FINAL", self.cuadro_precio_tratamiento.get(), "ID", tupla_servicios_seleccionados[0]) self.ver_servicios() self.actualizar_total() def añadir_servicio(self): if self.texto_id_factura.get() != "Factura no seleccionada": datos = [ (cal2fecha(self.cal_servicio.get()), self.cuadro_tratamiento.get(), self.cuadro_precio_tratamiento.get(), self.texto_id_factura.get()) ] #fecha, tratamiento, precio y factura a la que pertenece crearServicio(datos) self.ver_servicios() self.actualizar_total() else: print("No hay factura seleccionada para asociarle el servicio") def eliminar_factura(self): borrarRegistro("FACTURA", "ID", self.texto_id_factura.get()) self.ver_facturas() def eliminar_servicio(self): borrarRegistro("SERVICIO", "ID", tupla_servicios_seleccionados[0]) self.ver_servicios() self.actualizar_total() def set_cliente(self, cliente): self.cliente = cliente id_seleccionado = cliente[0] self.cuadro_dni.delete(0, END) self.cuadro_dni.insert(END, cliente[1]) self.ID_cliente_asociado = cliente[0] self.texto_cliente.set(cliente[0]) self.cuadro_nombre.delete(0, END) self.cuadro_nombre.insert(END, cliente[2]) self.cuadro_nombre.insert(END, " ") self.cuadro_nombre.insert(END, cliente[3]) self.cuadro_direccion.delete(0, END) self.cuadro_direccion.insert(END, cliente[4]) self.cuadro_direccion.insert(END, ". ") self.cuadro_direccion.insert(END, cliente[5]) self.cuadro_direccion.insert(END, ". ") self.cuadro_direccion.insert(END, cliente[6]) self.cuadro_cp.delete(0, END) self.cuadro_cp.insert(END, cliente[7]) self.ver_facturas() def caja_factura_seleccionada(self, evento): global tupla_facturas_seleccionadas global id_factura if (self.caja_facturas.curselection()): indice = self.caja_facturas.curselection()[0] #print("Al pulsar se ve esto: "+ str(self.caja_facturas.curselection())) tupla_facturas_seleccionadas = self.caja_facturas.get(indice) cliente_factura = leerRegistro("CLIENTE", "ID", tupla_facturas_seleccionadas[5]) id_factura = str(tupla_facturas_seleccionadas[0]) self.texto_id_factura.set(id_factura) self.set_cliente(cliente_factura[0]) lista_fecha = (str(tupla_facturas_seleccionadas[2]).split("-")) self.cal.set_date( datetime(int(lista_fecha[0]), int(lista_fecha[1]), int(lista_fecha[2]))) self.cuadro_codigo.delete(0, END) self.cuadro_codigo.insert(END, tupla_facturas_seleccionadas[1]) self.cuadro_comentarios.delete("1.0", END) self.cuadro_comentarios.insert(END, tupla_facturas_seleccionadas[6]) self.combo_iva.set(tupla_facturas_seleccionadas[3]) self.cuadro_descuento.delete(0, END) self.cuadro_descuento.insert(END, tupla_facturas_seleccionadas[4]) self.caja_facturas.itemconfigure( indice, bg="#00aa00", fg="#fff") #darle colorcito verde a lo seleccionado self.caja_facturas.see( indice ) # esto es para que se centre en el que que has seleccionado self.ver_servicios() self.actualizar_total() def caja_servicio_seleccionado(self, evento): global tupla_servicios_seleccionados indice_servicio = self.caja_servicios.curselection()[0] tupla_servicios_seleccionados = self.caja_servicios.get( indice_servicio) lista_fecha = (str(tupla_servicios_seleccionados[1]).split("-")) self.cal_servicio.set_date( datetime(int(lista_fecha[0]), int(lista_fecha[1]), int(lista_fecha[2]))) self.cuadro_tratamiento.delete(0, END) self.cuadro_tratamiento.insert(END, tupla_servicios_seleccionados[2]) self.cuadro_precio_tratamiento.delete(0, END) self.cuadro_precio_tratamiento.insert(END, tupla_servicios_seleccionados[3]) self.caja_servicios.itemconfigure( indice_servicio, bg="#00aa00", fg="#fff") #darle colorcito verde a lo seleccionado self.caja_servicios.see( indice_servicio ) # esto es para que se centre en el que que has seleccionado self.ver_servicios() self.actualizar_total() def borrar(self): self.cuadro_dni.delete(0, END) self.cuadro_nombre.delete(0, END) self.cuadro_direccion.delete(0, END) self.cuadro_cp.delete(0, END) self.texto_id_factura.set("Factura no seleccionada") self.cuadro_comentarios.delete("1.0", END) self.cuadro_codigo.delete(0, END) self.caja_servicios.delete(0, END) self.combo_iva.set(0) self.cuadro_descuento.delete(0, END) self.cuadro_descuento.insert(END, "0") self.cuadro_total.delete(0, END) self.controlador.marcos['PaginaInicial'].actualizar() def ver_facturas(self): self.caja_facturas.delete(0, END) for fila in leerTodo("FACTURA"): self.caja_facturas.insert(END, fila) def ver_servicios(self): servicios_factura = [] self.caja_servicios.delete(0, END) for fila in leerRegistro("SERVICIO", "FACTURA_ID", self.texto_id_factura.get()): servicios_factura.append(fila) self.caja_servicios.insert(END, fila) return servicios_factura def actualizar_total(self): total = 0 for fila in leerRegistro("SERVICIO", "FACTURA_ID", self.texto_id_factura.get()): total += float(fila[3]) total_calculado = total * (1 - float(self.cuadro_descuento.get()) * 0.01) * (1 + float(self.combo_iva.get()) * 0.01) total_calculado = round(total_calculado, 2) print("Total actualizado a ", total_calculado) self.cuadro_total.delete(0, END) self.cuadro_total.insert(END, total_calculado)
class SetNewReport(ttk.Frame): geo = '600x800' def __init__(self, parent, controller): """ parent = Frame container, controller = class SeReporter() """ super().__init__(parent) self.controller = controller self.parent = parent gl.next_step = 'empty' self.url_fields = [] self.titel_var = tk.StringVar() self.choice_var = tk.StringVar() self.protocol_var = tk.StringVar() self.val_strt_hr = tk.StringVar() self.val_strt_min = tk.StringVar() self.val_end_hr = tk.StringVar() self.val_end_min = tk.StringVar() # periode definitions self.period_start = '' self.period_end = '' self.period_unit = '' self.start_it = datetime.now() self.stop_it = func.add_one_month(datetime.now()) # accept value self.p_start = '' self.p_stop = '' self.p_mode = '' self.p_unit = '' # defenitions background Frame self.grid_rowconfigure(1, weight=1) self.grid_rowconfigure(1, weight=1) self.grid_columnconfigure(0, weight=1) self.configure(style='Panel.TFrame') # definitions inside_frame, an internal 2 column frame self.inside_frame = ttk.Frame(self, width=600, style='Panel.TFrame') self.inside_frame.grid(padx=30, pady=30) # row 0 of inside_frame: page_label page_label = ttk.Label( self.inside_frame, textvariable=self.titel_var, text=' Rapport ....', style='PanelLabel.TLabel', width=40, # Width in chars anchor=tk.CENTER) page_label.grid(row=0, column=0, pady=(0, 5)) # row 1 of inside_frame: info_frame, info_frame_label = tk.Label(self.inside_frame, text=' Aanwijzingen ', font=cnf.fh12, fg='black', bg='#ffefd8') self.info_frame = ttk.LabelFrame(self.inside_frame, text='', style='Panel.TFrame', labelwidget=info_frame_label, relief=tk.GROOVE) self.info_choice = ttk.Label(self.info_frame, textvariable=self.choice_var, text='choice', style='StatusText.TLabel', width=40) self.info_choice.grid(row=0, column=0, columnspan=2, padx=5, pady=(5, 5)) self.info_protocol = ttk.Label(self.info_frame, textvariable=self.protocol_var, text='protocol', style='StatusText.TLabel', width=40) self.info_protocol.grid(row=1, column=0, columnspan=2, padx=5, pady=(5, 5)) self.infotext = tk.Text(self.info_frame, bg='#fffae3', wrap=tk.WORD, height=3, width=40, font=cnf.fh12, bd=2, padx=5, pady=5) self.infotext.grid(row=2, column=0, columnspan=2, padx=10, pady=10, ipadx=10, ipady=10) self.infotext.insert(tk.END, 'Info text') self.info_frame.grid(row=1, column=0, pady=(10, 0), padx=(0, 0)) # Settings frame contains all settings grouped by row settings_frame_label = tk.Label(self.inside_frame, text=' Instellingen ', font=cnf.fa12, fg='black', bg='#ffefd8') self.fr_settings = ttk.LabelFrame(self.inside_frame, text='--', labelwidget=settings_frame_label, style='Panel.TFrame', relief=tk.GROOVE) self.fr_settings.grid(row=2, padx=20, pady=10) # self.fr_settings.grid_propagate(0) # row 1 = Date frames # left = start date fr_strt_date_label = tk.Label(self.fr_settings, text=' Startdatum ', font=cnf.fa12, fg='black', bg='#ffefd8') self.fr_strt_date = ttk.LabelFrame(self.fr_settings, text=' Begin ', width=175, height=80, labelwidget=fr_strt_date_label, style='Panel.TFrame', relief=tk.GROOVE) self.fr_strt_date.grid(row=0, column=0, sticky='W', pady=(5, 10), padx=(10, 10)) self.fr_strt_date.grid_propagate(0) self.start_date = DateEntry( self.fr_strt_date, width=12, date_pattern='yyy-mm-dd', font=cnf.fa12, # year=self.strt_year, month=self.strt_month, day=self.strt_day, background='#0000ff', foreground='white') self.start_date.grid(row=0, column=0, padx=20, pady=10) self.start_date.set_date(self.start_it) # std_width = self.fr_strt_date.winfo_width() # right = stop date fr_stop_date_label = tk.Label(self.fr_settings, text=' Stopdatum ', font=cnf.fa12, fg='black', bg='#ffefd8') self.fr_stop_date = ttk.LabelFrame(self.fr_settings, text=' ', width=175, height=80, labelwidget=fr_stop_date_label, style='Panel.TFrame', relief=tk.GROOVE) self.stop_date = DateEntry( self.fr_stop_date, width=12, date_pattern='yyy-mm-dd', font=cnf.fh12, # year=self.stop_year, month=self.stop_month, day=self.stop_day, background='blue', foreground='white') self.stop_date.grid(row=0, column=1, padx=20, pady=10) self.stop_date.set_date(self.stop_it) self.fr_stop_date.grid(row=1, column=1, sticky='E', pady=(5, 10), padx=(10, 10)) self.fr_stop_date.grid_propagate(0) # row 2 = Time frames # r2 - left = start time fr_strt_time_label = tk.Label(self.fr_settings, text=' Starttijd ', font=cnf.fa12, fg='black', bg='#ffefd8') self.fr_strt_time = ttk.LabelFrame(self.fr_settings, text=' Begin ', width=175, height=80, labelwidget=fr_strt_time_label, style='Panel.TFrame', relief=tk.GROOVE) self.fr_strt_time.grid(row=1, column=0, sticky='W', pady=(5, 10), padx=(10, 0)) self.fr_strt_time.grid_propagate(0) self.start_time_hr = ttk.Combobox(self.fr_strt_time, textvariable=self.val_strt_hr, values=gl.hrlist, font=cnf.fa12, width=2) self.start_time_hr.grid(row=0, column=0, padx=(20, 0), pady=(10, 20)) self.start_time_hr.current(2) dd1 = tk.Label(self.fr_strt_time, text=' : ', font=cnf.fh14, fg='black', bg='#ffefd8') dd1.grid(row=0, column=1, pady=(10, 20)) self.start_time_min = ttk.Combobox(self.fr_strt_time, textvariable=self.val_strt_min, values=gl.mnlist, font=cnf.fa12, width=2) self.start_time_min.grid(row=0, column=2, padx=(0, 20), pady=(10, 20)) self.start_time_min.current(0) # r2 - right = stop time fr_stop_time_label = tk.Label(self.fr_settings, text=' Stoptijd ', font=cnf.fa12, fg='black', bg='#ffefd8') self.fr_stop_time = ttk.LabelFrame(self.fr_settings, text=' Eind ', width=175, height=80, labelwidget=fr_stop_time_label, style='Panel.TFrame', relief=tk.GROOVE) self.stop_time_hr = ttk.Combobox(self.fr_stop_time, textvariable=self.val_end_hr, values=gl.hrlist, font=cnf.fa12, width=2) self.stop_time_hr.grid(row=0, column=0, padx=(20, 0), pady=(10, 20)) self.stop_time_hr.current(16) dd2 = tk.Label(self.fr_stop_time, text=' : ', font=cnf.fh14, fg='black', bg='#ffefd8') dd2.grid(row=0, column=1, pady=(10, 20)) self.stop_time_min = ttk.Combobox(self.fr_stop_time, textvariable=self.val_end_min, values=gl.mnlist, font=cnf.fa12, width=2) self.stop_time_min.grid(row=0, column=2, padx=(0, 20), pady=(10, 20)) self.stop_time_min.current(0) self.fr_stop_time.grid(row=1, column=1, sticky='E', pady=(5, 10), padx=(10, 10)) self.fr_stop_time.grid_propagate(0) # r3 - right = Unit frame fr_unit_label = tk.Label(self.fr_settings, text=' Interval ', font=cnf.fa12, fg='black', bg='#ffefd8') self.fr_unit = ttk.LabelFrame(self.fr_settings, text=' Begin ', width=175, height=100, labelwidget=fr_unit_label, style='Panel.TFrame', relief=tk.GROOVE) self.unit_var = tk.StringVar() self.unit_var.set(gl.list_of_units_nl[0]) self.unit = ttk.OptionMenu(self.fr_unit, self.unit_var, *gl.list_of_units_nl, command=lambda x: self.set_time_unit(x) ) # in original self was forwarded also self.unit_var.set(gl.list_of_units_nl[0]) self.unit['menu'].configure(font=cnf.fa12) self.unit.configure(style='ChoiceButton.TButton') self.unit.grid(row=0, column=0, pady=(10, 10), padx=(20, 10)) # , padx=20, pady=10, sticky='E' self.fr_unit.grid(row=2, column=1, pady=(10, 10), padx=(10, 10)) self.fr_unit.grid_propagate(0) self.acceptbutton = tk.Button(self.inside_frame, text='Verder', background='black', foreground='white', width=20, height=2, font=cnf.fa12, command=lambda: self.accept()) self.acceptbutton.grid(row=6, column=0, sticky='E', padx=0, pady=20) backbutton = tk.Button(self.inside_frame, text='Terug', background='black', foreground='white', width=20, height=2, font=cnf.fa12, command=lambda: self.go_back()) backbutton.grid(row=6, column=0, sticky='W', padx=0, pady=20) @staticmethod def set_time_unit(val): # For future improvements only print(f'returned val: {val}') pass def go(self): """ User has chosen for a new report of a particular type Hide or show widgets dependent on api.name and get the right start values (from history database or defaults) into the widgets. :return: """ # api.name = self.parent.report_type self.titel_var.set( f' Rapportperiode samenstellen en rapport opvragen ') self.choice_var.set(f' Raportkeuze = "{cnf.all_titles.get(api.name)}"') self.protocol_var.set(f' Protocolnaam = "{api.name}"') # Get values to complete the arg list api_args = cnf.all_args[api.name][ 1:] # args needed for the choosen api, skip translated title api.num_args = len(api_args) selogger.info( f'Gekozen titel: {cnf.all_titles[api.name]}, ' f'de api naam is {api.name}, aantal args = {api.num_args}') self.infotext.delete('1.0', tk.END) self.infotext.insert(tk.END, cnf.api_config[api.name]['info']) print( f'{__name__}-{lineno()}: cnf.all_args[my.name] = {cnf.all_args[api.name]}' ) print(f'{__name__}-{lineno()}: api.num_args = {api.num_args}') # print(cnf.api_config[api.name]['info']) if api.num_args == 0: # Requests without period definitions self.fr_unit.grid_remove() self.fr_strt_date.grid_remove() self.fr_stop_date.grid_remove() self.fr_strt_time.grid_remove() self.fr_stop_time.grid_remove() self.fr_settings.grid_remove() else: # Requests with date and/or date-time definitions self.fr_settings.grid(row=2, padx=20, pady=10) api.url_args.clear() # in case user chooses new report type # Possible arguments are: startDate + endDate OR startTime + endTime AND OPTIONAL timeUnit for next_arg in api_args: if next_arg == 'startDate': # Set both date entries visible self.fr_strt_date.grid(row=0, column=0, sticky='W', pady=(10, 10), padx=(10, 10)) self.fr_stop_date.grid(row=0, column=1, sticky='E', pady=(10, 10), padx=(10, 10)) api.url_args['startDate'] = '' api.url_args['endDate'] = '' elif next_arg == 'startTime': # Set both date + time entries visible self.fr_strt_date.grid(row=0, column=0, sticky='W', pady=(10, 10), padx=(10, 10)) self.fr_stop_date.grid(row=0, column=1, sticky='E', pady=(10, 10), padx=(10, 10)) self.fr_strt_time.grid(row=1, column=0, sticky='W', pady=(10, 10), padx=(10, 0)) self.fr_stop_time.grid(row=1, column=1, sticky='E', pady=(10, 10), padx=(10, 10)) api.url_args['startTime'] = '' api.url_args['endTime'] = '' elif next_arg in 'timeUnit': # Set interval choice visible self.fr_unit.grid(row=2, column=1, pady=(10, 10), padx=(10, 10)) api.url_args['timeUnit'] = '' # Fill widgets with last saved values arg_db_values = func.get_api_values(api.name) # database action if 'startDate' in arg_db_values: if len(arg_db_values['startDate']): self.start_date.set_date(arg_db_values['startDate']) if 'endDate' in arg_db_values: if len(arg_db_values['endDate']): self.stop_date.set_date(arg_db_values['endDate']) if 'timeUnit' in api_args: p_unit = arg_db_values['timeUnit'] self.url_fields.append('timeUnit') else: p_unit = '' self.fr_unit.grid_forget() if 'startDate' in api_args: self.p_start = arg_db_values['startDate'] self.p_mode = 'date' self.url_fields.append('startDate') self.fr_strt_time.grid_forget() self.fr_stop_time.grid_forget() elif 'startTime' in api_args: self.p_start = arg_db_values['startTime'] self.p_mode = 'time' self.url_fields.append('startTime') if 'endDate' in api_args: self.p_stop = arg_db_values['endDate'] self.url_fields.append('endDate') elif 'endTime' in api_args: self.p_stop = arg_db_values['endTime'] self.url_fields.append('endTime') # self.p_start = '2020-01-01 12:00:00' # api compatible yyyy-mm-dd (and if time defined) hh:mm:ss # self.p_end = '2020-01-01 12:00:00' # api compatible yyyy-mm-dd (and if time defined) hh:mm:ss if p_unit != '': self.unit_var.set('Dag') if len(self.p_unit) > 1: self.unit_var.set(self.p_unit) print(lineno(), f'self.url_fields = {self.url_fields}') base_width = self.info_frame.winfo_width() self.fr_settings.configure(width=base_width) print(f"Var's in {__name__}: {dir()}") def go_back(self): self.controller.lastframe() def accept(self): # User pushed ready button if api.num_args == 0: self.controller.show_frame('GetNewReport') return # entered values must be api formatted and checked self.period_start = str(self.start_date.get_date()) if self.p_mode != 'date': self.period_start += ' ' self.period_start += str(self.val_strt_hr.get()) self.period_start += ':' self.period_start += str(self.val_strt_min.get()) self.period_start += ':00' self.period_end = str(self.stop_date.get_date()) if self.p_mode != 'date': self.period_end += ' ' self.period_end += str(self.val_end_hr.get()) self.period_end += ':' self.period_end += str(self.val_strt_min.get()) self.period_end += ':00' self.period_unit = self.unit_var.get() if len(self.period_unit): print(f'self.period_unit = {self.period_unit}') idx = gl.list_of_units_nl.index(self.period_unit) self.period_unit = gl.list_of_units_en[idx] print( lineno(), f'self.period_start = {self.period_start}, ' f'self.period_end = {self.period_end}, \nself.period_unit = {self.period_unit}' ) if not self.check_request(api.name, str(self.period_start), str(self.period_end), self.period_unit): TopMessage( cnf.wfquit, 'Foutje', 'De ingevoerde waarden in dit verzoek zijn niet toegestaan') return else: dp = dict() dp.clear() dp['title'] = 'Vraagje ..' dp['message'] = 'De ingevoerde waarden zijn toegestaan dus ...' dp['deny'] = 'Terug' dp['accept'] = 'OK, Doorgaan' self.call_dialog(**dp) if gl.next_step == 'no action': return if api.num_args > 0: # Ask for saving (modified) parameters dp.clear() dp['title'] = 'Nog een vraagje ..' dp['message'] = 'Instellingen eerst opslaan (in database) als nieuwe basiswaarde?' dp['deny'] = 'Terug' dp['accept'] = 'Opslaan graag' self.call_dialog(**dp) if gl.next_step == 'no action': return # Save new values in database print(f'{__name__}-{lineno()}: api.url_args = {api.url_args}') query = 'UPDATE settings SET ' for name in api.url_args: val = '' if name == 'timeUnit': val = self.period_unit if val in gl.list_of_units_en: val = gl.list_of_units_nl[ gl.list_of_units_en.index(val)] elif name in ('startTime', 'startDate'): val = self.period_start elif name in ('endTime', 'endDate'): val = self.period_end query += f'{name} = "{val}", ' query = query[0:-2] # remove last comma-space query += f' WHERE name = "{api.name}"' print(lineno(), f'query = {query}') rows = func.actdb.exec_update(query) if rows > 0: selogger.info('Laatste instellingen opgeslagen.') # self.controller.set_trigger('newReport') self.controller.show_frame('GetNewReport') # ========================================================================================= @staticmethod def check_request(api_choice, strt_moment, end_moment, unit): """ Validate user choices of 'energy', 'timeFrameEnergy','power','powerDetails','energyDetails' """ ret_val = False # Checking settings per api d = dict() d['strt'] = strt_moment d['end'] = end_moment if api_choice == 'energy': # Periodeopbrengst in detail if unit in 'DAY': # Max 1 year d['delta'] = 'year' res = func.check_periode_limit(None, **d) if res == 1: msg = 'De gekozen periode is te lang voor de waarden per: dag' TopMessage(cnf.wfquit, 'Foutje', msg) ret_val = False elif res == -1: msg = 'De start- en einddatums zijn omgedraaid' TopMessage(cnf.wfquit, 'Foutje', msg) ret_val = False else: ret_val = True elif unit in ('QUARTER_OF_AN_HOUR', 'HOUR'): # Max 1 month d['delta'] = 'month' res = func.check_periode_limit(None, **d) if res == 1: msg = 'De gekozen periode is te lang bij waarden per: uur of kwartier' TopMessage(cnf.wfquit, 'Foutje', msg) ret_val = False elif res == -1: msg = 'De start- en einddatums zijn omgedraaid' TopMessage(cnf.wfquit, 'Foutje', msg) ret_val = False else: ret_val = True else: ret_val = True elif api_choice == 'timeFrameEnergy': # Periodeopbrengst samenvatting # Total over given period, no limits if strt_moment == end_moment: msg = 'Dezelfde dag en zonder tijden is niet logisch, ' \ 'probeer dan liever \n"Periodeopbrengst in detail"\n' \ 'want daar kun je ook de tijd aangeven' TopMessage(cnf.wfquit, 'Foutje', msg) ret_val = False else: d['delta'] = '' res = func.check_periode_limit(None, **d) if res == -1: msg = 'Stopdatum dient ná Startdatum te liggen' TopMessage(cnf.wfquit, 'Foutje', msg) ret_val = False else: ret_val = True elif api_choice == 'power': # Periodeopbrengst per kwartier # Max 1 month!! d['delta'] = 'month' res = func.check_periode_limit(None, **d) if res == 1: msg = 'Dit rapport levert kwartierwaarden en mag daarom niet langer zijn dan één maand\n' \ 'Tip: let op de tijden!' TopMessage(cnf.wfquit, 'Foutje', msg) ret_val = False elif res == -1: msg = 'Stopdatum (plus tijd) dient ná Startdatum (plus tijd) te liggen' TopMessage(cnf.wfquit, 'Foutje', msg) ret_val = False else: ret_val = True elif api_choice in ( 'overview', # Overzicht 'details', # Installatie details 'dataPeriod', # start- and enddate of installation 'inventory', # List of technical installation details 'envBenefits'): # Environment benefits like CO2 ret_val = True else: pass return ret_val def call_report(self): api_conn = CallApi content = api_conn.get_report(api.name, api.url_args) if len(content): pass def set_text(self, txt): pass def call_dialog(self, *args, **kwargs): d = DialogBox(self, *args, **kwargs) d.grab_set() self.wait_window(d) d.grab_release() # print(f'BACK after wait with gl.next_step = {gl.next_step}') return
class SelectorPanel(ttk.Frame): # SelectorPanel outputs the following operation parameters # invoice_ent: the full path to the invoice (統一發票開票紀錄檔) # gl_ent: the full path to the general ledger (總帳紀錄檔案) # cal_stt: the start date of the invoice matching # cal_end: the end date of the invoice matching def __init__(self, master, msgtxt): ttk.Frame.__init__(self, master) self.pack(side=TOP, fill=X) # resized with parent title_label_font = font.Font(family="新細明體", size=12, weight="bold") self.msg = Label(self, wraplength='4i', justify=LEFT, font=title_label_font, pady=5) self.msg['text'] = ''.join(msgtxt) self.msg.pack(fill=X, padx=5, pady=5) self._fill_upper_frame() self._fill_middle_frame() self._fill_bottom_frame() # Upper frame constructed to accept the invoice issue record selected, # this selected invoice is of file type .xls def _fill_upper_frame(self): file_type = constant.ENTRY_TYPE_INVOICE_RECORD frame = ttk.Frame(self) lbl = ttk.Label(frame, width=20, text="統一發票開票紀錄", anchor='w') lbl.pack(side=LEFT) self.invoice_ent = ttk.Entry(frame, width=60) self.invoice_ent.pack(side=LEFT, expand=Y, padx=5) btn = ttk.Button(frame, text="選取", command=lambda e=self.invoice_ent, t=file_type: self._file_dialog(e, t)) btn.pack(side=LEFT, padx=5) frame.pack(side=TOP, padx='1c', pady=3) # Middle frame constructed to accept the general ledger selected, # this selected general ledger is of file type .xlsx def _fill_middle_frame(self): file_type = constant.ENTRY_TYPE_GENERAL_LEDGER frame = ttk.Frame(self) lbl = ttk.Label(frame, width=20, text="總帳紀錄", anchor='w') lbl.pack(side=LEFT) self.gl_ent = ttk.Entry(frame, width=60) self.gl_ent.pack(side=LEFT, expand=Y, padx=5) btn = ttk.Button(frame, text="選取", command=lambda e=self.gl_ent, t=file_type: self._file_dialog(e, t)) btn.pack(side=LEFT, padx=5) frame.pack(side=TOP, padx='1c', pady=3) # bottom frame includes two pairs of label and DateEntry objects to accept # start date and end date def _fill_bottom_frame(self): frame = ttk.Frame(self) self.cal_stt_chk = IntVar() self.datechk_btn = Checkbutton(frame, text="發票日期檢查", variable=self.cal_stt_chk, width=15, onvalue=1, offvalue=0, anchor="w") self.datechk_btn.pack(side=LEFT) lbl_stt = ttk.Label(frame, width=15, text="起始日期", anchor="e") lbl_stt.pack(side=LEFT) self.cal_stt = DateEntry(frame, width=20, background="darkblue", date_pattern="yyyy/MM/dd", foreground="white", borderwidth=2) self.cal_stt.set_date(date.today()) self.cal_stt.pack(side=LEFT, padx=5) lbl_end = ttk.Label(frame, width=15, text="結束時間", anchor="e") lbl_end.pack(side=LEFT) # self.cal_end_chk = IntVar() # self.chkbtn_end = Checkbutton(frame, text="發票結束日期", variable=self.cal_end_chk, width=15, # onvalue=1, offvalue=0) # self.chkbtn_end.pack(side=LEFT, padx=5) self.cal_end = DateEntry(frame, width=20, background="darkblue", date_pattern="yyyy/MM/dd", foreground="white", borderwidth=2) self.cal_end.set_date(date.today()) self.cal_end.pack(side=LEFT, padx=5) frame.pack(side=TOP, padx='1c', pady=3) # This is the file selector handler def _file_dialog(self, entry, file_type): fn = None op_pnl = self.master.op_pnl if file_type == constant.ENTRY_TYPE_GENERAL_LEDGER: opts = {"initialfile": entry.get(), "filetypes": (('Excel Workbook', "*.xlsx"), ("All Files", "*.*"),), "title": "選擇總帳紀錄檔" } fn = fdlg.askopenfilename(**opts) op_pnl.print_log("選取總帳檔案: " + "\n\t" + fn) if file_type == constant.ENTRY_TYPE_INVOICE_RECORD: opts = {"initialfile": entry.get(), "filetypes": (('Excel 97-2003 Workbook', "*.xls"), ("All Files", "*.*"),), "title": "選擇統一發票開票紀錄檔" } fn = fdlg.askopenfilename(**opts) op_pnl.print_log("選取發票檔案: "+ "\n\t" + fn) if fn: entry.delete(0, END) entry.insert(END, fn)
class oneway: def __init__(self, user, window): self.search_by = StringVar() self.search_txt = StringVar() self.list2 = [{ 'name': 'Select', 'price': [] }, { 'name': 'Economy', 'price': 3000 }, { 'name': 'Premium Economy', 'price': 4000 }, { 'name': 'Business Class', 'price': 5000 }, { 'name': 'First Class', 'price': 6000 }] # Get the names of the all flights name self.names = list(map(lambda x: x.get('name'), self.list2)) print(self.names) self.window = window self.user_id = user self.item_index = [] self.user = user self.window.title('User Form') self.window.geometry('1100x650+90+40') self.frame1 = Frame(self.window, bg='#37474F') self.frame1.place(x=0, y=0, height=650, width=1100) self.frame2 = Frame(self.frame1, bg='white', bd=1, relief=RIDGE) self.frame2.place(x=390, y=130, height=360, width=630) self.label_name = Label(self.frame1, text="One Way Flight", font=('Impact', 20, 'bold'), fg="white", bg='#37474F') self.label_name.place(x=300, y=15) time1 = StringVar() time1.set(time.strftime('%H:%M:%S:%p')) self.ent_where = Label(self.frame1, font=('times new roman', 25), fg='white', bg='#37474F', textvariable=time1) self.ent_where.place(x=60, y=5) self.label_name = Label(self.frame1, text="Where From:", font=('Goudy old style', 12, 'bold'), fg='white', bg='#37474F') self.label_name.place(x=50, y=90) self.ent_where = Entry(self.frame1, font=('times new roman', 9), bg='lightgray') self.ent_where.place(x=170, y=90, width=200, height=30) self.label_name = Label(self.frame1, text="Where To:", font=('Goudy old style', 12, 'bold'), fg='white', bg='#37474F') self.label_name.place(x=50, y=140) self.ent_to = Entry(self.frame1, font=('times new roman', 9), bg='lightgray') self.ent_to.place(x=170, y=140, width=200, height=30) self.label_name = Label(self.frame1, text="Departure Date:", font=('Goudy old style', 12, 'bold'), fg='white', bg='#37474F') self.label_name.place(x=50, y=190) self.ent_dpt = DateEntry(self.frame1, width=12, background='darkblue', foreground='white', borderwidth=2) self.ent_dpt.place(x=170, y=190, width=200) ttk.Button(self.frame1, text="ok") self.combo = Label(self.frame1, text="Age Selection:", font=('Goudy old style', 12, 'bold'), fg='white', bg='#37474F').place(x=50, y=240) self.txt_combo = ttk.Combobox(self.frame1, font=('times new roman', 9), state='readonly', justify=CENTER) self.txt_combo['values'] = ('select', 'Adult', 'Children', 'Infant', 'Old age') self.txt_combo.place(x=170, y=240) self.txt_combo.current(0) self.label_name = Label(self.frame1, text="Count:", font=('Goudy old style', 12, 'bold'), fg='white', bg='#37474F') self.label_name.place(x=50, y=290) self.ent_count = Entry(self.frame1, font=('times new roman', 9), bg='lightgray') self.ent_count.place(x=170, y=290, width=200, height=30) self.classcombo = Label(self.frame1, text="Class Selection:", font=('Goudy old style', 12, 'bold'), fg='white', bg='#37474F').place(x=50, y=340) self.txt_classcombo = ttk.Combobox(self.frame1, font=('times new roman', 9), state='readonly', justify=CENTER, values=self.names) # self.txt_classcombo['values'] = ('Economy', 'Premium Economy', 'Business Class', 'First Class') self.txt_classcombo.bind('<<ComboboxSelected>>', self.fetch_data) self.txt_classcombo.place(x=170, y=340) self.txt_classcombo.current(0) self.label_price = Label(self.frame1, text="Price:", font=('Goudy old style', 12, 'bold'), fg='white', bg='#37474F') self.label_price.place(x=50, y=390) self.ent_price = Entry(self.frame1, font=('times new roman', 9), bg='lightgray') self.ent_price.place(x=170, y=390, width=200, height=30) self.ent_price.insert(0, '') self.flight = Label(self.frame1, text="Flight Selection:", font=('Goudy old style', 12, 'bold'), fg='white', bg='#37474F').place(x=50, y=440) self.txt_flight = ttk.Combobox(self.frame1, font=('times new roman', 9), state='readonly', justify=CENTER) self.txt_flight['values'] = ('select', 'Buddha Air', 'Yeti Airlines', 'Surya Airline', 'Nepal Airlines', 'Tara Airlines') self.txt_flight.place(x=170, y=440) self.txt_flight.current(0) self.item_entry = Entry(self.window, textvariable=self.search_txt) self.item_entry.place(x=400, y=90) self.txt_combo_1 = ttk.Combobox(self.frame1, textvariable=self.search_by, font=('times new roman', 9), state='readonly', justify=CENTER) self.txt_combo_1['values'] = ('flight_name', 'destination', 'class_selection') self.txt_combo_1.place(x=600, y=90) self.txt_combo_1.current(0) self.btn_add = Button(self.window, text="Search", command=self.Search_items) self.btn_add.place(x=800, y=90) self.btn_book = Button(self.frame1, text="Book Flight", relief=RAISED, bg='#001C55', font=('arial', 14, 'bold'), fg='white', command=self.book_flight) self.btn_book.place(x=100, y=550) self.btn_book = Button(self.frame1, text="Cancel Flight", relief=RAISED, bg='#00072D', font=('arial', 14, 'bold'), fg='white', command=self.delete_item) self.btn_book.place(x=540, y=550) self.btn_book = Button(self.frame1, text="Bill", relief=RAISED, bg='#00072D', font=('arial', 14, 'bold'), fg='white', command=self.generate_bill) self.btn_book.place(x=700, y=550) self.btn_book = Button(self.frame1, text="Update", relief=RAISED, bg='#00072D', font=('arial', 14, 'bold'), fg='white', command=self.update) self.btn_book.place(x=800, y=550) scroll_x = Scrollbar(self.frame2, orient=HORIZONTAL) self.bg1 = ImageTk.PhotoImage( file= 'C:\\Users\\Dell\\PycharmProjects\\untitled3\\project\\Webp.net-resizeimage (3).png' ) self.btn4 = Button(self.window, image=self.bg1, text='Logout', relief=RAISED, bg='#37474F', font=('arial', 14, 'bold'), fg='white', bd=0, command=exit) self.btn4.place(x=1000, y=7, width=90) self.item_tree = ttk.Treeview( self.frame2, selectmode='browse', columns=('ID', 'Where from', 'Where to', 'Departure Date', 'Age Selection', 'Count', 'Class Selection', 'User_id', 'Flight_Name', 'Price'), xscrollcommand=scroll_x.set) self.item_tree.pack(fill=BOTH, expand=1) #self.item_tree.place(x=390,y=120) scroll_x.pack(side=BOTTOM, fill=X) scroll_x.config(command=self.item_tree.xview) self.item_tree['show'] = 'headings' self.item_tree.column('ID', width=90, anchor='center') self.item_tree.column('Where from', width=90, anchor='center') self.item_tree.column('Where to', width=90, anchor='center') self.item_tree.column('Departure Date', width=90, anchor='center') self.item_tree.column('Age Selection', width=90, anchor='center') self.item_tree.column('Count', width=90, anchor='center') self.item_tree.column('Class Selection', width=90, anchor='center') self.item_tree.column('User_id', width=90, anchor='center') self.item_tree.column('Flight_Name', width=90, anchor='center') self.item_tree.column('Price', width=90, anchor='center') self.item_tree.heading('ID', text="ID") self.item_tree.heading('Where from', text="Where from") self.item_tree.heading('Where to', text="Where to") self.item_tree.heading('Departure Date', text="Departure Date") self.item_tree.heading('Age Selection', text="Age Selection") self.item_tree.heading('Count', text="Count") self.item_tree.heading('Class Selection', text="Class Selection") self.item_tree.heading('User_id', text="User ID") self.item_tree.heading('Flight_Name', text="Flight_Name") self.item_tree.heading('Price', text="Price") # scroll_x = Scrollbar(manage_teacher_frame2_1, orient=HORIZONTAL) # # scroll_x.pack(side=BOTTOM, fill=X) # scroll_x.config(command=self.teacher_tree.xview) # scroll_y.pack(side=RIGHT, fill=Y) # self.item_treeScrollbar=ttk.Scrollbar(self.window,orient='horizontal',command=self.item_tree.xview) # self.item_tree.configure(xscroll=self.item_treeScrollbar.set) # self.item_treeScrollbar.pack(side=BOTTOM,fill=X) self.show_in_treeview() def clear(self): self.ent_where.delete(0, END) self.ent_to.delete(0, END) self.ent_dpt.delete(0, END) self.txt_combo.set('') self.ent_count.delete(0, END) self.txt_classcombo.set('') # def logout(self): # messagebox.showinfo('Message','Do you want to log out') # import login2 # self.window.withdraw() # dd = Toplevel(self.window) # # login2.Login(dd) def update(self): selected_item = self.item_tree.selection()[0] self.item_index = self.item_tree.item(selected_item, 'text') item_data = self.item_tree.item(selected_item, 'values') if item_data[0] == '': messagebox.showerror('error', 'select a row') else: if form2.Item_dlt().update_items(item_data[0], self.ent_where.get(), self.ent_to.get(), self.ent_dpt.get_date(), self.txt_combo.get(), self.ent_count.get(), self.txt_classcombo.get(), self.txt_flight.get(), self.ent_price.get(), self.user_id): messagebox.showinfo("Item", "Booking Updated") self.show_in_treeview() else: messagebox.showerror("Error", "Booking Details cannot be added") def book_flight(self): if self.ent_where.get() == "" or self.ent_to.get( ) == "" or self.ent_dpt.get() == "" or self.txt_combo.get( ) == "" or self.ent_count.get() == "" or self.txt_classcombo.get( ) == "": messagebox.showerror('Error', 'please enter all required fields') else: try: form2.oneway_flight().oneway_reg(self.ent_where.get(), self.ent_to.get(), self.ent_dpt.get_date(), self.txt_combo.get(), self.ent_count.get(), self.txt_classcombo.get(), self.user_id, self.txt_flight.get(), self.ent_price.get()) messagebox.showinfo('success', 'Register successfull', parent=self.window) self.show_in_treeview() #self.clear() except Exception as e: messagebox.showerror('error', f'error:{str(e)}', parent=self.window) def fetch_data(self, *args): va = filter(lambda x: x.get('name') == self.txt_classcombo.get(), self.list2) self.ent_price.delete(0, END) self.ent_price.insert(0, next(va).get('price')) def select_item(self, event): selected_item = self.item_tree.selection()[0] self.item_index = self.item_tree.item(selected_item, 'text') item_data = self.item_tree.item(selected_item, 'values') self.ent_where.delete(0, END) self.ent_where.insert(0, item_data[1]) self.ent_to.delete(0, END) self.ent_to.insert(0, item_data[2]) #dpt_date_f=datetime.datetime.strptime(int(item_data[2]/3), '%Y-%m-%d').strftime('%m/%d/%y') dpt_date = datetime.datetime(int(item_data[3][0:4]), int(item_data[3][5:7]), int(item_data[3][8:10])) dpt_date_f = dpt_date.strftime('%m/%d/%y') self.ent_dpt.set_date(dpt_date_f) self.txt_combo.set(item_data[4]) self.txt_combo.current() self.ent_count.delete(0, END) self.ent_count.insert(0, item_data[5]) self.txt_classcombo.set(item_data[6]) self.txt_classcombo.current() self.txt_flight.set(item_data[8]) self.txt_flight.current() self.ent_price.delete(0, END) self.ent_price.insert(0, item_data[9]) def show_in_treeview(self): # # qry = 'select * from oneway where user_id=%s' # self.my_cursor.execute(qry,(self.user_id)) row = form2.show_flight().show_in_treeview(self.user_id) # spot_marker = 0 # while spot_marker < len(row): # for num in range(spot_marker, len(row)): # if row[num] < row[spot_marker]: # row[spot_marker], row[num] = row[num], row[spot_marker] # spot_marker += 1 # print(row) if row: self.item_tree.delete(*self.item_tree.get_children()) for i in row: #self.tree.item(idx)['text'] self.item_tree.insert("", "end", text=i[0], value=(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8], i[9])) # self.my_connection.commit() self.item_tree.bind('<Double-1>', self.select_item) def Search_items(self): con = mysql.connector.connect(host='localhost', user='******', password='', database='register') cur = con.cursor() values = ( str(self.search_by.get()), '"{}"'.format(str(self.search_txt.get() + '%')), ) qry = ( f"SELECT ID,destination,source,dpt,combo,count_no,class_selection,user_id,flight_name,price FROM oneway WHERE user_id={self.user_id} AND {values[0]} LIKE {values[1]} " ) cur.execute(qry) rows = cur.fetchall() if len(rows) != 0: self.item_tree.delete(*self.item_tree.get_children()) for row in rows: self.item_tree.insert("", END, values=row) con.commit() def valid(self): if self.ent_where.get() == "" or self.ent_to.get( ) == "" or self.ent_dpt.get() == "" or self.txt_combo.get( ) == "" or self.ent_count.get() == "" or self.txt_classcombo.get( ) == "": messagebox.showerror('Error', 'please enter all required fields') return False else: return True def delete_item(self): selected_item = self.item_tree.selection()[0] item_data = self.item_tree.item(selected_item, 'text') index = item_data if form2.Item_dlt().delete_items(index): messagebox.showinfo('Item', 'Item Deleted') self.show_in_treeview() # selected_item = self.item_tree.selection() # self.item_tree.delete(selected_item) else: messagebox.showerror("Error", "Item cannot be deleted", parent=self.window) def generate_bill(self): all_orders = self.item_tree.get_children() bill_list = [] total = 0 # tbl=self.order_tree.item(all_orders[0],'values')[0] # name=self.order_tree.item(all_orders[1],'values')[1] for i in all_orders: order = self.item_tree.item(i, 'values') amt = float(order[5]) * float(order[9]) bill_list.append((order[2], order[3], order[4], order[5], order[6], order[8], order[9], amt)) total += amt BillView(bill_list, total, self.user)
class UpdateStudent(Toplevel): def backf(self, event=""): self.destroy() self.root.deiconify() def c_w(self, event=""): m = messagebox.askyesno("School Software", "Are you Want to Close Application?", parent=self.root) if m > 0: query4 = "update staff set currentuser = 0 where currentuser = 1;" self.conn.execute(query4) self.conn.commit() self.main_root.destroy() else: return def des(self, event=""): self.firstnamelabel.destroy() self.firstnameentry.destroy() self.middlenamelabel.destroy() self.middlenameentry.destroy() self.lastnamelabel.destroy() self.lastnameentry.destroy() self.addresslabel.destroy() self.addressentry.destroy() self.studentphnolabel.destroy() self.studentphnoentry.destroy() self.parentphnoentry.destroy() self.parentphnolabel.destroy() self.emailentry.destroy() self.emaillabel.destroy() self.parentofficeaddentry.destroy() self.parentofficeaddlabel.destroy() self.parentofficephnoentry.destroy() self.parentofficephnolabel.destroy() self.casteentry.destroy() self.castelabel.destroy() self.selectcategorylabel.destroy() self.selectcategoryentry.destroy() self.bloodgrouplabel.destroy() self.bloodgroupentry.destroy() self.dateofbirthentry.destroy() self.dateofbirthlabel.destroy() self.rollnolabel.destroy() self.rollnoentry.destroy() self.stdentry.set("Select Standard") self.detailcounter = 0 def validNumber(self, s): Pattern = re.compile("(0/91)?[6-9][0-9]{9}") return Pattern.match(s) def rollno(self, event=""): if self.rollcounter == 0: self.rollnolabel = Label(self.lf2, text="Roll Number", bd=2, bg=self.bgclr1, fg="black", font=(self.f1, 15), relief=GROOVE) self.rollnolabel.place(x=600, y=20, height=30) query1 = """ select rollno, fname, mname, lname from master where standard = ?""" a = self.conn.execute(query1, (self.stdentry.get(), )).fetchall() self.rno = [] for i in a: self.rno.append(i) self.rno.sort() self.rollno_var = StringVar() self.rollnoentry = ttk.Combobox(self.lf2, state="readonly", textvariable=self.rollno_var, font=(self.f1, 10)) self.rollnoentry.place(x=900, y=20, height=30) self.rollnoentry['values'] = self.rno self.rollnoentry.bind("<<ComboboxSelected>>", self.details) self.rollnoentry.set("Select") self.rollcounter = 1 else: self.rollnolabel.destroy() self.rollnoentry.destroy() self.rollcounter = 0 self.rollno() def details(self, event=""): if self.detailcounter == 0: rno = self.rollnoentry.get().split(" ") query = """ select * from master where standard = ? and rollno = ? """ self.data = self.conn.execute( query, (self.stdentry.get(), rno[0])).fetchone() self.firstnamelabel = Label(self.lf2, text="First Name", bd=2, bg=self.bgclr1, fg="black", font=(self.f1, 15), relief=GROOVE) self.firstnamelabel.place(x=50, y=80) self.firstname_var = StringVar() self.firstnameentry = Entry(self.lf2, textvariable=self.firstname_var, font=(self.f1, 15)) self.firstnameentry.place(x=300, y=80, height=30, width=200) self.firstname_var.set(self.data[4]) self.middlenamelabel = Label(self.lf2, text="Middle Name", bd=2, bg=self.bgclr1, fg="black", font=(self.f1, 15), relief=GROOVE) self.middlenamelabel.place(x=50, y=130) self.middlename_var = StringVar() self.middlenameentry = Entry(self.lf2, textvariable=self.middlename_var, font=(self.f1, 15)) self.middlenameentry.place(x=300, y=130, height=30, width=200) self.middlename_var.set(self.data[5]) self.lastnamelabel = Label(self.lf2, text="Lastname", bd=2, bg=self.bgclr1, fg="black", font=(self.f1, 15), relief=GROOVE) self.lastnamelabel.place(x=50, y=180) self.lastname_var = StringVar() self.lastnameentry = Entry(self.lf2, textvariable=self.lastname_var, font=(self.f1, 15)) self.lastnameentry.place(x=300, y=180, height=30, width=200) self.lastname_var.set(self.data[6]) self.addresslabel = Label(self.lf2, text="Address", bd=2, bg=self.bgclr1, fg="black", font=(self.f1, 15), relief=GROOVE) self.addresslabel.place(x=50, y=230) self.address_var = StringVar() self.addressentry = Text(self.lf2, font=(self.f1, 10)) self.addressentry.place(x=300, y=230, width=200, height=60) self.addressentry.insert(INSERT, self.data[7]) self.studentphnolabel = Label(self.lf2, text="Student Phone No.", bd=2, bg=self.bgclr1, fg="black", font=(self.f1, 15), relief=GROOVE) self.studentphnolabel.place(x=50, y=320) self.studentphno_var = StringVar() self.studentphnoentry = Entry(self.lf2, textvariable=self.studentphno_var, font=(self.f1, 15)) self.studentphnoentry.place(x=300, y=320, height=30, width=200) self.studentphno_var.set(self.data[8]) self.parentphnolabel = Label(self.lf2, text="Parent Phone No.", bd=2, bg=self.bgclr1, fg="black", font=(self.f1, 15), relief=GROOVE) self.parentphnolabel.place(x=50, y=370) self.parentphno_var = StringVar() self.parentphnoentry = Entry(self.lf2, textvariable=self.parentphno_var, font=(self.f1, 15)) self.parentphnoentry.place(x=300, y=370, height=30, width=200) self.parentphno_var.set(self.data[9]) self.emaillabel = Label(self.lf2, text="E-mail Id", bd=2, bg=self.bgclr1, fg="black", font=(self.f1, 15), relief=GROOVE) self.emaillabel.place(x=50, y=420) self.email_var = StringVar() self.emailentry = Entry(self.lf2, textvariable=self.email_var, font=(self.f1, 15)) self.emailentry.place(x=300, y=420, height=30, width=200) self.email_var.set(self.data[10]) self.parentofficeaddlabel = Label(self.lf2, text="Parent Office Add.", bd=2, bg=self.bgclr1, fg="black", font=(self.f1, 15), relief=GROOVE) self.parentofficeaddlabel.place(x=600, y=80) self.parentofficeadd_var = StringVar() self.parentofficeaddentry = Text(self.lf2, font=(self.f1, 10)) self.parentofficeaddentry.place(x=900, y=80, height=60, width=200) self.parentofficeaddentry.insert(INSERT, self.data[11]) self.parentofficephnolabel = Label(self.lf2, text="Parent Office Phone No.", bd=2, bg=self.bgclr1, fg="black", font=(self.f1, 15), relief=GROOVE) self.parentofficephnolabel.place(x=600, y=170) self.parentofficephno_var = StringVar() self.parentofficephnoentry = Entry( self.lf2, textvariable=self.parentofficephno_var, font=(self.f1, 15)) self.parentofficephnoentry.place(x=900, y=170, height=30, width=200) self.parentofficephno_var.set(self.data[12]) self.dateofbirthlabel = Label(self.lf2, text="Date Of Birth", bd=2, bg=self.bgclr1, fg="black", font=(self.f1, 15), relief=GROOVE) self.dateofbirthlabel.place(x=600, y=220) self.dateofbirth_var = StringVar() self.dateofbirthentry = DateEntry(self.lf2, width=12, background='darkblue', font=(self.f1, 15), date_pattern='dd/mm/yyyy', foreground='white', borderwidth=2, state="readonly") self.dateofbirthentry.place(x=900, y=220, width=200, height=30) date_time_str = self.data[16] date_time_obj = datetime.strptime(date_time_str, '%Y-%m-%d') self.dateofbirthentry.set_date(date_time_obj.date()) self.selectcategorylabel = Label(self.lf2, text="Select Category", bd=2, bg=self.bgclr1, fg="black", font=(self.f1, 15), relief=GROOVE) self.selectcategorylabel.place(x=600, y=270) self.selectcategory_var = StringVar() self.selectcategoryentry = Combobox( self.lf2, state="readonly", font=(self.f1, 15), textvariable=self.selectcategory_var) self.selectcategoryentry.place(x=900, y=270, height=30, width=200) self.selectcategoryentry['values'] = [ "ST", "SC", "OBC", "OPEN", "Other" ] self.selectcategory_var.set(self.data[17]) self.bloodgrouplabel = Label(self.lf2, text="Blood Group", bd=2, bg=self.bgclr1, fg="black", font=(self.f1, 15), relief=GROOVE) self.bloodgrouplabel.place(x=600, y=320) self.bloodgroup_var = StringVar() self.bloodgroupentry = Combobox(self.lf2, state="readonly", font=(self.f1, 15), textvariable=self.bloodgroup_var) self.bloodgroupentry.place(x=900, y=320, height=30, width=200) self.bloodgroupentry['values'] = [ "A+", "B+", "A-", "B-", "AB+", "O+", "O-" ] self.bloodgroup_var.set(self.data[18]) self.castelabel = Label(self.lf2, text="Caste", bd=2, bg=self.bgclr1, fg="black", font=(self.f1, 15), relief=GROOVE) self.castelabel.place(x=600, y=370) self.caste_var = StringVar() self.casteentry = Entry(self.lf2, textvariable=self.caste_var, font=(self.f1, 15)) self.casteentry.place(x=900, y=370, height=30, width=200) self.caste_var.set(self.data[19]) self.detailcounter = 1 else: self.des() self.details() def update(self): try: if self.firstnameentry.get() == "": raise ValueError except: m = messagebox.showerror("School Software", "Please enter First Name", parent=self) self.firstnameentry.focus_set() return try: if self.middlenameentry.get() == "": raise ValueError except: m = messagebox.showerror("School Software", "Please enter middle Name", parent=self) self.middlenameentry.focus_set() return try: if self.lastnameentry.get() == "": raise ValueError except: m = messagebox.showerror("School Software", "Please enter Last Name", parent=self) self.lastnameentry.focus_set() return try: if self.addressentry.get(1.0, END) == "": raise ValueError except: m = messagebox.showerror("School Software", "Please enter Address", parent=self) self.addressentry.focus_set() return try: if self.studentphnoentry.get() == "": raise ValueError except: m = messagebox.showerror("School Software", "Please enter Student Phone Number", parent=self) self.studentphnoentry.focus_set() return try: if self.parentphnoentry.get() == "": raise ValueError except: m = messagebox.showerror("School Software", "Please enter Parent Phone Number", parent=self) self.parentphnoentry.focus_set() return try: if self.emailentry.get() == "": raise ValueError except: m = messagebox.showerror("School Software", "Please enter E-mail ID", parent=self) self.emailentry.focus_set() return try: if self.parentofficeaddentry.get(1.0, END) == "": raise ValueError except: m = messagebox.showerror("School Software", "Please enter Parent Office Address", parent=self) self.parentofficeaddentry.focus_set() return try: if self.parentofficephnoentry.get() == "": raise ValueError except: m = messagebox.showerror("School Software", "Please enter Parent Office Phone Number", parent=self) self.parentofficephnoentry.focus_set() return try: if self.selectcategoryentry.get() == "Select Category": raise ValueError except: m = messagebox.showerror("School Software", "Please Select Category", parent=self) return try: if self.bloodgroupentry.get() == "Select Blood Group": raise ValueError except: m = messagebox.showerror("School Software", "Please Select Blood Group", parent=self) return try: if self.casteentry.get() == "": raise ValueError except: m = messagebox.showerror("School Software", "Please enter caste", parent=self) self.casteentry.focus_set() return try: if not self.firstnameentry.get().isalpha(): raise ValueError except: m = messagebox.showerror("School Software", "Please enter valid first name ", parent=self) self.firstnameentry.focus_set() return try: if not self.middlenameentry.get().isalpha(): raise ValueError except: m = messagebox.showerror("School Software", "Please enter valid middle name ", parent=self) self.middlenameentry.focus_set() return try: if not self.lastnameentry.get().isalpha(): raise ValueError except: m = messagebox.showerror("School Software", "Please enter valid last name", parent=self) self.lastnameentry.focus_set() return try: if not (self.validNumber(self.studentphnoentry.get()) and len(self.studentphnoentry.get()) == 10): raise ValueError except: m = messagebox.showerror("School Software", "Please enter valid Student phone number", parent=self) self.studentphnoentry.focus_set() return try: if not (self.validNumber(self.parentphnoentry.get()) and len(self.parentphnoentry.get()) == 10): raise ValueError except: m = messagebox.showerror("School Software", "Please enter valid Parent phone number", parent=self) self.parentphnoentry.focus_Set() return try: valid = validate_email(self.emailentry.get()) if not valid: raise ValueError except: m = messagebox.showerror("School Software", "Please enter valid E-mail address", parent=self) self.emailentry.focus_set() return try: if not (self.validNumber(self.parentofficephnoentry.get()) and len(self.parentofficephnoentry.get()) == 10): raise ValueError except: m = messagebox.showerror( "School Software", "Please enter valid Parent office phone number", parent=self) self.parentofficephnoentry.focus_set() return try: if not self.casteentry.get().isalpha(): raise ValueError except: m = messagebox.showerror("School Software", "Please enter valid caste", parent=self) self.casteentry.focus_set() return try: if (self.dateofbirthentry.get_date() >= date.today()): raise ValueError except: messagebox.showerror("School Software", "Invalid date of birth!!") return m = messagebox.askokcancel("School Software", " Are want to update data", parent=self) if m: query = """UPDATE master SET fname = ?, mname = ?, lname = ?, address = ?, student_phno = ?, parents_phno = ?, email = ?, parent_office_address = ?, parents_office_phno = ?, date_of_birth = ?, category = ?, blood_group = ?, cast = ? WHERE grno = ?""" self.conn.execute( query, (self.firstnameentry.get(), self.middlenameentry.get(), self.lastnameentry.get(), self.addressentry.get(1.0, END), self.studentphnoentry.get(), self.parentphnoentry.get(), self.emailentry.get(), self.parentofficeaddentry.get( 1.0, END), self.parentofficephnoentry.get(), self.dateofbirthentry.get_date(), self.selectcategoryentry.get(), self.bloodgroupentry.get(), self.casteentry.get(), self.data[0])) self.conn.commit() m = messagebox.showinfo("School Software", "Student data update succesfully", parent=self) self.des() else: self.des() def __init__(self, root, main_root): try: self.conn = sqlite3.connect('sinfo.db') except: m = messagebox.showerror("School Software", "Couldn't Connect With Database !", parent=self) self.main_root = main_root self.root = root Toplevel.__init__(self) self.lift() self.focus_force() self.grab_set() self.grab_release() self.bgclr1 = "#0080c0" self.bgclr2 = "#e7d95a" self.f1 = "Arial Bold" self.f2 = "times new roman" self.title("UPDATE STUDENT") self.config(background=self.bgclr1) self.geometry("1350x700+0+0") self.resizable(False, False) self.rollcounter = 0 self.detailcounter = 0 ##======================================================frame 1========================================================= imagel = Image.open("left-arrow.png") imagel = imagel.resize((60, 15)) imgl = ImageTk.PhotoImage(imagel) self.lf1 = LabelFrame(self, text="NAME", bd=2, bg=self.bgclr1, fg="black", font=(self.f1, 20), relief=GROOVE) self.lf1.place(x=0, y=0, height=150, width=1350) bb = Button(self.lf1, image=imgl, bg=self.bgclr2, bd=5, font=(self.f1, 20), command=self.backf) bb.place(x=10, y=10) ##=============================================frame 2================================================================== self.lf2 = LabelFrame(self, text="UPDATE STUDENT", bd=2, bg=self.bgclr1, fg="black", font=(self.f1, 20), relief=GROOVE) self.lf2.place(x=0, y=150, height=550, width=1350) self.stdlabel = Label(self.lf2, text="Standard", bd=2, bg=self.bgclr1, fg="black", font=(self.f1, 15), relief=GROOVE) self.stdlabel.place(x=50, y=20, height=30) query = """select standard from master """ a = self.conn.execute(query).fetchall() b = set(a) self.cals = [] for i in b: self.cals.append(str(i[0])) self.cals.sort() self.std_var = StringVar() self.stdentry = ttk.Combobox(self.lf2, state="readonly", textvariable=self.std_var, font=(self.f1, 10)) self.stdentry.place(x=300, y=20, height=30, width=200) self.stdentry['values'] = self.cals self.stdentry.bind("<<ComboboxSelected>>", self.rollno) self.std_var.set("Select Standard") self.submitbutton = Button(self.lf2, text="UPDATE", bg=self.bgclr2, font=(self.f2, 15), bd=5, command=self.update) self.submitbutton.place(x=1200, y=200, width=100, height=30) self.protocol("WM_DELETE_WINDOW", self.c_w) self.mainloop()
class Echo(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.client = self.parent.client self.clientTextVar = StringVar() self.clientTextVar.set(self.client) self.loadData() f1 = Frame(self) f1.pack(fill=X) # Labels for each field LABEL_WIDTH1 = 6 LABEL_WIDTH2 = 5 LABEL_WIDTH3 = 5 LABEL_WIDTH4 = 16 LABEL_WIDTH5 = 5 LABEL_WIDTH6 = 8 LABEL_WIDTH7 = 8 LABEL_WIDTH8 = 10 Label(f1, anchor="w", width=LABEL_WIDTH1, text="Client").grid(row=0, column=0) Label(f1, anchor="w", width=LABEL_WIDTH2, textvariable=self.clientTextVar).grid(row=0, column=1) Label(f1, anchor="w", width=LABEL_WIDTH1, text="Date").grid(row=1, column=0) Label(f1, anchor="w", width=LABEL_WIDTH1, text="Tape").grid(row=2, column=0) self.date = DateEntry(f1) self.date.grid(row=1, column=1, padx=2) self.tape = Text(f1, width=12, height=1) self.tape.grid(row=2, column=1, padx=2) # Delete button self.delete = Button(f1, text="Delete", fg="Black", state="disabled") self.delete.grid(row=4, column=1) Label(f1, anchor="w", width=LABEL_WIDTH2, text="LBS").grid(row=1, column=2) Label(f1, anchor="w", width=LABEL_WIDTH2, text="KGS").grid(row=2, column=2) Label(f1, anchor="w", width=LABEL_WIDTH2, text="BSA").grid(row=3, column=2) Label(f1, anchor="w", width=LABEL_WIDTH2, text="HR").grid(row=4, column=2) Label(f1, anchor="w", width=LABEL_WIDTH2, text="RR").grid(row=5, column=2) self.lbs = Text(f1, width=4, height=1) self.lbs.grid(row=1, column=3, padx=2) self.kgs = Text(f1, width=4, height=1) self.kgs.grid(row=2, column=3, padx=2) self.bsa = Text(f1, width=4, height=1) self.bsa.grid(row=3, column=3, padx=2) self.hr = Text(f1, width=4, height=1) self.hr.grid(row=4, column=3, padx=2) self.rr = Text(f1, width=4, height=1) self.rr.grid(row=5, column=3, padx=2) Label(f1, anchor="w", width=LABEL_WIDTH3, text="Ao").grid(row=1, column=4) Label(f1, anchor="w", width=LABEL_WIDTH3, text="LA").grid(row=2, column=4) Label(f1, anchor="w", width=LABEL_WIDTH3, text="LA2").grid(row=3, column=4) Label(f1, anchor="w", width=LABEL_WIDTH3, text="LA2D").grid(row=4, column=4) Label(f1, anchor="w", width=LABEL_WIDTH3, text="EPSS").grid(row=5, column=4) self.ao = Text(f1, width=4, height=1) self.ao.grid(row=1, column=5, padx=2) self.la = Text(f1, width=4, height=1) self.la.grid(row=2, column=5, padx=2) self.la2 = Text(f1, width=4, height=1) self.la2.grid(row=3, column=5, padx=2) self.la2d = Text(f1, width=4, height=1) self.la2d.grid(row=4, column=5, padx=2) self.epss = Text(f1, width=4, height=1) self.epss.grid(row=5, column=5, padx=2) Label(f1, anchor="w", width=LABEL_WIDTH4, text="Calculation Group").grid(row=1, column=6) self.calcgroup = ttk.Combobox(f1, width=LABEL_WIDTH4, values=CLINICIANS) self.calcgroup.grid(row=2, column=6, padx=20) Label(f1, anchor="w", width=LABEL_WIDTH5, text="RV").grid(row=1, column=7) Label(f1, anchor="w", width=LABEL_WIDTH5, text="IVS").grid(row=2, column=7) Label(f1, anchor="w", width=LABEL_WIDTH5, text="LVID").grid(row=3, column=7) Label(f1, anchor="w", width=LABEL_WIDTH5, text="LVW").grid(row=4, column=7) Label(f1, anchor="w", width=LABEL_WIDTH5, text="VIDX").grid(row=5, column=7) Label(f1, width=LABEL_WIDTH6, text="Systole").grid(row=0, column=8) self.rv = CustomText(f1, width=LABEL_WIDTH6, height=1) self.rv.grid(row=1, column=8, padx=2) self.ivs = CustomText(f1, width=LABEL_WIDTH6, height=1) self.ivs.grid(row=2, column=8, padx=2) self.lvid = CustomText(f1, width=LABEL_WIDTH6, height=1) self.lvid.grid(row=3, column=8, padx=2) self.lvw = CustomText(f1, width=LABEL_WIDTH6, height=1) self.lvw.grid(row=4, column=8, padx=2) self.vidxtext = StringVar() self.vidx = Entry(f1, textvariable=self.vidxtext, width=LABEL_WIDTH8, state='readonly') self.vidx.grid(row=5, column=8, padx=2) Label(f1, width=LABEL_WIDTH7, text="Diastole").grid(row=0, column=9) self.rv2 = CustomText(f1, width=LABEL_WIDTH7, height=1) self.rv2.grid(row=1, column=9, padx=2) self.ivs2 = CustomText(f1, width=LABEL_WIDTH7, height=1) self.ivs2.grid(row=2, column=9, padx=2) self.lvid2 = CustomText(f1, width=LABEL_WIDTH7, height=1) self.lvid2.grid(row=3, column=9, padx=2) self.lvw2 = CustomText(f1, width=LABEL_WIDTH7, height=1) self.lvw2.grid(row=4, column=9, padx=2) self.vidxtext2 = StringVar() self.vidx2 = Entry(f1, textvariable=self.vidxtext2, width=LABEL_WIDTH8, state='readonly') self.vidx2.grid(row=5, column=9, padx=2) self.rv.bind("<<TextModified>>", self.updateDeltas) self.rv2.bind("<<TextModified>>", self.updateDeltas) self.ivs.bind("<<TextModified>>", self.updateDeltas) self.ivs2.bind("<<TextModified>>", self.updateDeltas) self.lvid.bind("<<TextModified>>", self.updateDeltas) self.lvid2.bind("<<TextModified>>", self.updateDeltas) self.lvw.bind("<<TextModified>>", self.updateDeltas) self.lvw2.bind("<<TextModified>>", self.updateDeltas) Label(f1, width=LABEL_WIDTH8, text="Δ").grid(row=0, column=10) self.delt1 = StringVar() self.delt2 = StringVar() self.delt3 = StringVar() self.delt4 = StringVar() self.ivs3 = Entry(f1, textvariable=self.delt1, width=LABEL_WIDTH8, state='readonly') self.ivs3.grid(row=2, column=10, padx=2) self.lvid3 = Entry(f1, textvariable=self.delt2, width=LABEL_WIDTH8, state='readonly') self.lvid3.grid(row=3, column=10, padx=2) self.lvw3 = Entry(f1, textvariable=self.delt3, width=LABEL_WIDTH8, state='readonly') self.lvw3.grid(row=4, column=10, padx=2) self.vidx3 = Entry(f1, textvariable=self.delt4, width=LABEL_WIDTH8, state='readonly') self.vidx3.grid(row=5, column=10, padx=2) self.indices = Button(f1, text="Indices", fg="Black", command=self.indices) self.indices.grid(row=2, column=11) self.submit = Button(f1, text="Submit", fg="Black", command=self.submit) self.submit.grid(row=3, column=11) self.clearButton = Button(f1, text="New", fg="Black", command=self.clearFields) self.clearButton.grid(row=4, column=11) # Fills with the form information. f2 = ScrollableFrame(self, height=150) # Listbox all the basic pet information self.numEntries = 0 self.listBox = ttk.Treeview(f2.scrollable_frame, columns=list(self.data.columns), show='headings') i = 0 for col in self.data.columns[1:]: self.listBox.heading(i, text=col) self.listBox.column(i, width=columnWidth(len(self.data.columns))) i += 1 for item in self.data.values: if (item[0] == self.client): self.listBox.insert("", "end", values=list(item)[1:]) self.numEntries += 1 self.listBox.configure(height=max(self.numEntries, 6)) # Get info on click self.listBox.bind("<Double-1>", self.onSelection) self.listBox.pack(fill=BOTH, expand=True) f2.pack(fill=BOTH, expand=True, pady=10) def updateDeltas(self, event=None): #TODO: Find out how these delts work try: self.delt1.set( float(self.ivs.get("1.0", "end-1c")) - float(self.ivs2.get("1.0", "end-1c"))) except ValueError: self.delt1.set("") try: self.delt2.set( float(self.lvid.get("1.0", "end-1c")) - float(self.lvid2.get("1.0", "end-1c"))) except ValueError: self.delt2.set("") try: self.delt3.set( float(self.lvw.get("1.0", "end-1c")) - float(self.lvw2.get("1.0", "end-1c"))) except ValueError: self.delt3.set("") def loadData(self): # Read data if path.exists(DATA_PATH_ECHO): self.data = pd.read_pickle(DATA_PATH_ECHO) else: self.initializeData() def initializeData(self): d = { 'ClientNum': [], 'Date': [], 'Tape': [], 'LBS': [], 'HR': [], 'RR': [], 'RVd': [], 'IVSd': [], 'LVIDd': [], 'LVWd': [], 'RVs': [], 'IVSs': [], 'LVIDs': [], 'LVWs': [], 'Ao': [], 'LA': [], 'LAm': [], 'EPSS': [], 'SAxLA D': [], 'SAx Ao D': [], 'SAx LA A': [], 'LAx LA D': [], 'Dep': [], 'Len': [], 'Gir': [], 'Wld': [] } self.data = pd.DataFrame(d) def onSelection(self, event=None): if self.listBox.selection(): item = self.listBox.selection()[0] values = self.listBox.item(item, "values") self.fillFields(values) self.delete.configure(state="normal", command=lambda: self.deleteDataItem(item)) self.submit.configure(text="Modify", command=lambda: self.modify(item)) def fillFields(self, values): self.date.set_date(values[0]) setText(self.tape, values[1]) setText(self.lbs, values[2]) setText(self.kgs, "") #TODO: Where are some of these fields stored? setText(self.bsa, "") setText(self.hr, values[3]) setText(self.rr, values[4]) setText(self.ao, values[13]) setText(self.la, values[14]) setText(self.la2, "") setText(self.la2d, "") setText(self.epss, values[16]) self.calcgroup.set("") setText(self.rv, values[9]) setText(self.rv2, values[5]) setText(self.ivs, values[10]) setText(self.ivs2, values[6]) setText(self.lvid, values[11]) setText(self.lvid2, values[7]) setText(self.lvw, values[12]) setText(self.lvw2, values[8]) self.vidxtext.set("") self.vidxtext2.set("") self.updateDeltas() def clearFields(self): self.date.set_date(date.today()) setText(self.tape, "") setText(self.lbs, "") setText(self.kgs, "") setText(self.bsa, "") setText(self.hr, "") setText(self.rr, "") setText(self.ao, "") setText(self.la, "") setText(self.la2, "") setText(self.la2d, "") setText(self.epss, "") self.calcgroup.set("") setText(self.rv, "") setText(self.rv2, "") setText(self.ivs, "") setText(self.ivs2, "") self.delt1.set("") setText(self.lvid, "") setText(self.lvid2, "") self.delt2.set("") setText(self.lvw, "") setText(self.lvw2, "") self.delt3.set("") self.vidxtext.set("") self.vidxtext2.set("") self.delt4.set("") self.delete.configure(state="disabled", command=None) self.submit.configure(text="Submit", command=self.submit) def deleteDataItem(self, item): row = self.listBox.index(item) self.listBox.delete(item) self.numEntries -= 1 self.listBox.configure(height=max(self.numEntries, 6)) self.data = self.data.drop( self.data[self.data["ClientNum"] == self.client].index[row]) self.saveData() self.clearFields() def modify(self, item): moddedData = { 'ClientNum': self.client, 'Date': self.date.get(), 'Tape': self.tape.get("1.0", "end-1c"), 'LBS': self.lbs.get("1.0", "end-1c"), 'HR': self.hr.get("1.0", "end-1c"), 'RR': self.rr.get("1.0", "end-1c"), 'RVd': self.rv2.get("1.0", "end-1c"), 'IVSd': self.ivs2.get("1.0", "end-1c"), 'LVIDd': self.lvid2.get("1.0", "end-1c"), 'LVWd': self.lvw2.get("1.0", "end-1c"), 'RVs': self.rv.get("1.0", "end-1c"), 'IVSs': self.ivs.get("1.0", "end-1c"), 'LVIDs': self.lvid.get("1.0", "end-1c"), 'LVWs': self.lvw.get("1.0", "end-1c"), 'Ao': self.ao.get("1.0", "end-1c"), 'LA': self.la.get("1.0", "end-1c"), 'LAm': "", # TODO: What are these fields? 'EPSS': "", 'SAxLA D': "", 'SAx Ao D': "", 'SAx LA A': "", 'LAx LA D': "", 'Dep': "", 'Len': "", 'Gir': "", 'Wld': "" } self.listBox.item(item, values=list(moddedData.values())[1:]) row = self.listBox.index(item) index = self.data[self.data["ClientNum"] == self.client].index[row] self.data.loc[index] = list(moddedData.values()) self.clearFields() self.saveData() def indices(self): print("Indices") def submit(self): newData = { 'ClientNum': self.client, 'Date': self.date.get(), 'Tape': self.tape.get("1.0", "end-1c"), 'LBS': self.lbs.get("1.0", "end-1c"), 'HR': self.hr.get("1.0", "end-1c"), 'RR': self.rr.get("1.0", "end-1c"), 'RVd': self.rv2.get("1.0", "end-1c"), 'IVSd': self.ivs2.get("1.0", "end-1c"), 'LVIDd': self.lvid2.get("1.0", "end-1c"), 'LVWd': self.lvw2.get("1.0", "end-1c"), 'RVs': self.rv.get("1.0", "end-1c"), 'IVSs': self.ivs.get("1.0", "end-1c"), 'LVIDs': self.lvid.get("1.0", "end-1c"), 'LVWs': self.lvw.get("1.0", "end-1c"), 'Ao': self.ao.get("1.0", "end-1c"), 'LA': self.la.get("1.0", "end-1c"), 'LAm': "", # TODO: What are these fields? 'EPSS': "", 'SAxLA D': "", 'SAx Ao D': "", 'SAx LA A': "", 'LAx LA D': "", 'Dep': "", 'Len': "", 'Gir': "", 'Wld': "" } self.listBox.insert("", "end", values=list(newData.values())[1:]) self.data = self.data.append(newData, ignore_index=True) self.clearFields() self.numEntries += 1 self.listBox.configure(height=max(self.numEntries, 6)) self.saveData() def updateClient(self, client): if len(client) > 2: self.client = client[1] self.clientTextVar.set(client[2]) self.listBox.delete(*self.listBox.get_children()) self.numEntries = 0 for item in self.data.values: if (item[0] == self.client): self.listBox.insert("", "end", values=list(item)[1:]) self.numEntries += 1 self.listBox.configure(height=max(self.numEntries, 6)) else: self.client = None self.clientTextVar.set('') self.listBox.delete(*self.listBox.get_children()) self.numEntries = 0 self.listBox.configure(height=max(self.numEntries, 6)) def saveData(self): saveData(self.data, DATA_PATH_ECHO) def modifiedClient(self, client): # We need to update the corresponding client number here when it's updated in Client for item in self.data.values: if (item[0] == self.client): item[0] = client[1] self.updateClient(client) self.saveData()
entry2.insert(0, demandante) # Crear caja de texto 3, nombre del demandado. entry_var3 = tk.StringVar() entry3 = ttk.Entry(root, textvariable=entry_var3, justify=tk.CENTER) label3 = ttk.Label(root, text="Nombre del demandado", background="#ffffff") if demandado: entry3.insert(0, demandado) # Crear caja de fecha 4, fecha de acta. entry_var4 = tk.StringVar() entry4 = DateEntry(root, textvariable=entry_var4, date_pattern='dd/mm/Y', width=17, background='gray', foreground='white', borderwidth=1) label4 = ttk.Label(root, text="Fecha del Acta de Infracción", background="#ffffff") if actainfraccion: entry4.set_date(actainfraccion) # Crear caja de fecha 5, fecha resolucion impugnada. entry_var5 = tk.StringVar() entry5 = DateEntry(root, textvariable=entry_var5, date_pattern='dd/mm/Y', width=17, background='gray', foreground='white', borderwidth=1) label5 = ttk.Label(root, text="Fecha de la Resolución impugnada", background="#ffffff") if resolucionrecargo: entry5.set_date(resolucionrecargo) # Crear caja de texto 15, porcentaje impuesto por la Inspección. entry_var15 = tk.StringVar() entry15 = ttk.Entry(root, textvariable=entry_var15, justify=tk.CENTER) label15 = ttk.Label(root, text="Porcentaje impuesto por la Inspección", background="#ffffff") if recargo: entry15.insert(0, recargo)
loadgrid(date, data=[]) insertgrid(button_list) picker_frame = LabelFrame(root) picker_frame.grid(row=7, column=0, columnspan=25) cal = DateEntry(picker_frame, width=12, background='darkblue', foreground='white', borderwidth=2, date_pattern='dd-mm-yyyy') cal.grid(row=0, column=1, padx=10) cal.bind('<<DateEntrySelected>>', when_date_changed) cal.set_date(date) def r_arrow(): global date _date = date + timedelta(1) cal.set_date(_date) when_date_changed(0) r_arrow = Button(picker_frame, text='🢂', command=r_arrow) r_arrow.grid(row=0, column=2) def l_arrow(): global date
class Toplevel1: def __init__(self, top=None): '''This class configures and populates the toplevel window. top is the toplevel containing window.''' _bgcolor = '#40e0d0' # X11 color: 'gray85' _fgcolor = '#000000' # X11 color: 'black' _compcolor = '#40e0d0' # X11 color: 'gray85' _ana1color = '#40e0d0' # X11 color: 'gray85' _ana2color = '#ececec' # Closest X11 color: 'gray92' self.style = ttk.Style() if sys.platform == "win32": self.style.theme_use('winnative') self.style.configure('.', background=_bgcolor) self.style.configure('.', foreground=_fgcolor) self.style.configure('.', font="TkDefaultFont") self.style.map('.', background=[ ('selected', _compcolor), ('active', _ana2color)]) self.db = DataBase() top.geometry("1300x760+20+20") top.minsize(800, 500) top.maxsize(1500, 750) top.resizable(0, 0) top.title("New Toplevel") top.configure(background="#78909C") top.configure(highlightbackground="#d9d9d9") top.configure(highlightcolor="black") self.Gid_10 = tk.Label(top) self.Gid_10.place(relx=0.427, rely=0.021, height=38, width=209) self.Gid_10.configure(activebackground="#f9f9f9") self.Gid_10.configure(activeforeground="black") self.Gid_10.configure(background="#d9d9d9") self.Gid_10.configure(disabledforeground="#a3a3a3") self.Gid_10.configure(font="-family {Segoe UI} -size 20 -weight bold") self.Gid_10.configure(foreground="#000000") self.Gid_10.configure(highlightbackground="#d9d9d9") self.Gid_10.configure(highlightcolor="black") self.Gid_10.configure(text='''ADD GOAT''') self.isBornOrBought = IntVar(None, 0) self.Rbtnborn = tk.Radiobutton(top, command=self.disableVaccination) self.Rbtnborn.place(relx=0.427, rely=0.095, relheight=0.034, relwidth=0.075) self.Rbtnborn.configure(activebackground="#ececec") self.Rbtnborn.configure(activeforeground="#000000") self.Rbtnborn.configure(background="#d9d9d9") self.Rbtnborn.configure(disabledforeground="#a3a3a3") self.Rbtnborn.configure(foreground="#000000") self.Rbtnborn.configure(highlightbackground="#d9d9d9") self.Rbtnborn.configure(highlightcolor="black") self.Rbtnborn.configure(justify='left') self.Rbtnborn.configure(text='''BORN''') self.Rbtnborn.configure(value=0) self.Rbtnborn.configure(variable=self.isBornOrBought) self.Rbtnbought = tk.Radiobutton(top, command=self.disableMotherId) self.Rbtnbought.place(relx=0.513, rely=0.095, relheight=0.034, relwidth=0.075) self.Rbtnbought.configure(activebackground="#ececec") self.Rbtnbought.configure(activeforeground="#000000") self.Rbtnbought.configure(background="#d9d9d9") self.Rbtnbought.configure(disabledforeground="#a3a3a3") self.Rbtnbought.configure(foreground="#000000") self.Rbtnbought.configure(highlightbackground="#d9d9d9") self.Rbtnbought.configure(highlightcolor="black") self.Rbtnbought.configure(justify='left') self.Rbtnbought.configure(text='''BOUGHT''') self.Rbtnbought.configure(value=1) self.Rbtnbought.configure(variable=self.isBornOrBought) self.gdetails = tk.Label(top) self.gdetails.place(x=130,y=100, height=35, width=130) self.gdetails.configure(activebackground="#f9f9f9") self.gdetails.configure(activeforeground="black") self.gdetails.configure(background="#d9d9d9") self.gdetails.configure(disabledforeground="#a3a3a3") self.gdetails.configure(font="-family {Segoe UI} -size 13") self.gdetails.configure(foreground="#000000") self.gdetails.configure(highlightbackground="#d9d9d9") self.gdetails.configure(highlightcolor="black") self.gdetails.configure(text='''GOAT DETAILS''') self.Gid = tk.Label(top) self.Gid.place(x=80,y=155, height=35, width=98) self.Gid.configure(activebackground="#f9f9f9") self.Gid.configure(activeforeground="black") self.Gid.configure(background="#d9d9d9") self.Gid.configure(disabledforeground="#a3a3a3") self.Gid.configure(foreground="#000000") self.Gid.configure(highlightbackground="#d9d9d9") self.Gid.configure(highlightcolor="black") self.Gid.configure(text='''Goat ID''') self.TEntry1 = ttk.Entry(top) self.TEntry1.place(x=250,y=155, height=35, width=140) self.TEntry1.configure(takefocus="") self.breed = tk.Label(top) self.breed.place(x=80,y=200, height=35, width=98) self.breed.configure(activebackground="#f9f9f9") self.breed.configure(activeforeground="black") self.breed.configure(background="#d9d9d9") self.breed.configure(disabledforeground="#a3a3a3") self.breed.configure(foreground="#000000") self.breed.configure(highlightbackground="#d9d9d9") self.breed.configure(highlightcolor="black") self.breed.configure(text='''Breed''') self.TEntry1_22 = ttk.Entry(top) self.TEntry1_22.place(x=250,y=200,height=35, width=140) self.TEntry1_22.configure(takefocus="") self.DOB = tk.Label(top) self.DOB.place(x=80,y=245, height=35, width=98) self.DOB.configure(activebackground="#f9f9f9") self.DOB.configure(activeforeground="black") self.DOB.configure(background="#d9d9d9") self.DOB.configure(disabledforeground="#a3a3a3") self.DOB.configure(foreground="#000000") self.DOB.configure(highlightbackground="#d9d9d9") self.DOB.configure(highlightcolor="black") self.DOB.configure(text='''DOB''') self.goatDob = DateEntry(top, width=12, year=2019, month=6, day=22, background='darkblue', foreground='white', borderwidth=2) self.goatDob.place(x=250,y=245, height=35, width=140) self.mother_id = tk.Label(top) self.mother_id.place(x=80,y=290, height=35, width=98) self.mother_id.configure(activebackground="#f9f9f9") self.mother_id.configure(activeforeground="black") self.mother_id.configure(background="#d9d9d9") self.mother_id.configure(disabledforeground="#a3a3a3") self.mother_id.configure(foreground="#000000") self.mother_id.configure(highlightbackground="#d9d9d9") self.mother_id.configure(highlightcolor="black") self.mother_id.configure(text='''Mother ID''') self.TEntry1_24 = ttk.Entry(top) self.TEntry1_24.place(x=250,y=335,height=35, width=140) self.TEntry1_24.configure(takefocus="") self.weight = tk.Label(top) self.weight.place(x=80,y=335, height=35, width=98) self.weight.configure(activebackground="#f9f9f9") self.weight.configure(activeforeground="black") self.weight.configure(background="#d9d9d9") self.weight.configure(disabledforeground="#a3a3a3") self.weight.configure(foreground="#000000") self.weight.configure(highlightbackground="#d9d9d9") self.weight.configure(highlightcolor="black") self.weight.configure(text='''Weight''') self.TEntry1_25 = ttk.Entry(top) self.TEntry1_25.place(x=250,y=290,height=35, width=140) self.TEntry1_25.configure(takefocus="") self.gender = tk.Label(top) self.gender.place(x=80,y=395, height=40, width=98) self.gender.configure(activebackground="#f9f9f9") self.gender.configure(activeforeground="black") self.gender.configure(background="#d9d9d9") self.gender.configure(disabledforeground="#a3a3a3") self.gender.configure(foreground="#000000") self.gender.configure(highlightbackground="#d9d9d9") self.gender.configure(highlightcolor="black") self.gender.configure(text='''Gender''') self.genderVal = IntVar() self.RbtnMale = tk.Radiobutton(top) self.RbtnMale.place(x=250,y=380,height=30,width=80) self.RbtnMale.configure(activebackground="#ececec") self.RbtnMale.configure(activeforeground="#000000") self.RbtnMale.configure(background="#d9d9d9") self.RbtnMale.configure(disabledforeground="#a3a3a3") self.RbtnMale.configure(foreground="#000000") self.RbtnMale.configure(highlightbackground="#d9d9d9") self.RbtnMale.configure(highlightcolor="black") self.RbtnMale.configure(justify='left') self.RbtnMale.configure(text='''MALE''') self.RbtnMale.configure(value=0) self.RbtnMale.configure(variable=self.genderVal) self.RbtnFemale = tk.Radiobutton(top) self.RbtnFemale.place(x=250,y=420,height=30,width=80) self.RbtnFemale.configure(activebackground="#ececec") self.RbtnFemale.configure(activeforeground="#000000") self.RbtnFemale.configure(background="#d9d9d9") self.RbtnFemale.configure(disabledforeground="#a3a3a3") self.RbtnFemale.configure(foreground="#000000") self.RbtnFemale.configure(highlightbackground="#d9d9d9") self.RbtnFemale.configure(highlightcolor="black") self.RbtnFemale.configure(justify='left') self.RbtnFemale.configure(text='''FEMALE''') self.RbtnFemale.configure(value=1) self.RbtnFemale.configure(variable=self.genderVal) self.health = tk.Label(top) self.health.place(x=890,y=100, height=35, width=150) self.health.configure(activebackground="#f9f9f9") self.health.configure(activeforeground="black") self.health.configure(background="#d9d9d9") self.health.configure(disabledforeground="#a3a3a3") self.health.configure(font="-family {Segoe UI} -size 12") self.health.configure(foreground="#000000") self.health.configure(highlightbackground="#d9d9d9") self.health.configure(highlightcolor="black") self.health.configure(text='''LAST VACCINATED''') self.v1 = tk.Label(top) self.v1.place(x=800,y=155, height=35, width=98) self.v1.configure(activebackground="#f9f9f9") self.v1.configure(activeforeground="black") self.v1.configure(background="#d9d9d9") self.v1.configure(disabledforeground="#a3a3a3") self.v1.configure(foreground="#000000") self.v1.configure(highlightbackground="#d9d9d9") self.v1.configure(highlightcolor="black") self.v1.configure(text='''V1''') self.cal1 = DateEntry(top, width=12, year=2020, month=6, day=22, background='darkblue', foreground='white', borderwidth=2) self.cal1.place(x=1000,y=155, height=35, width=98) self.v2 = tk.Label(top) self.v2.place(x=800,y=200, height=35, width=98) self.v2.configure(activebackground="#f9f9f9") self.v2.configure(activeforeground="black") self.v2.configure(background="#d9d9d9") self.v2.configure(disabledforeground="#a3a3a3") self.v2.configure(foreground="#000000") self.v2.configure(highlightbackground="#d9d9d9") self.v2.configure(highlightcolor="black") self.v2.configure(text='''V2''') self.cal2 = DateEntry(top, width=12, year=2019, month=6, day=22, background='darkblue', foreground='white', borderwidth=2) self.cal2.place(x=1000,y=200, height=35, width=98) self.v3 = tk.Label(top) self.v3.place(x=800,y=245, height=35, width=98) self.v3.configure(activebackground="#f9f9f9") self.v3.configure(activeforeground="black") self.v3.configure(background="#d9d9d9") self.v3.configure(disabledforeground="#a3a3a3") self.v3.configure(foreground="#000000") self.v3.configure(highlightbackground="#d9d9d9") self.v3.configure(highlightcolor="black") self.v3.configure(text='''V3''') self.cal3 = DateEntry(top, width=12, year=2019, month=6, day=22, background='darkblue', foreground='white', borderwidth=2) self.cal3.place(x=1000,y=245, height=35, width=98) self.v4 = tk.Label(top) self.v4.place(x=800,y=290, height=35, width=98) self.v4.configure(activebackground="#f9f9f9") self.v4.configure(activeforeground="black") self.v4.configure(background="#d9d9d9") self.v4.configure(disabledforeground="#a3a3a3") self.v4.configure(foreground="#000000") self.v4.configure(highlightbackground="#d9d9d9") self.v4.configure(highlightcolor="black") self.v4.configure(text='''V4''') self.cal4 = DateEntry(top, width=12, year=2019, month=6, day=22, background='darkblue', foreground='white', borderwidth=2) self.cal4.place(x=1000,y=290, height=35, width=98) self.v5 = tk.Label(top) self.v5.place(x=800,y=335, height=35, width=98) self.v5.configure(activebackground="#f9f9f9") self.v5.configure(activeforeground="black") self.v5.configure(background="#d9d9d9") self.v5.configure(disabledforeground="#a3a3a3") self.v5.configure(foreground="#000000") self.v5.configure(highlightbackground="#d9d9d9") self.v5.configure(highlightcolor="black") self.v5.configure(text='''V5''') self.cal5 = DateEntry(top, width=12, year=2019, month=6, day=22, background='darkblue', foreground='white', borderwidth=2) self.cal5.place(x=1000,y=335, height=35, width=98) self.v6 = tk.Label(top) self.v6.place(x=800,y=380, height=35, width=98) self.v6.configure(activebackground="#f9f9f9") self.v6.configure(activeforeground="black") self.v6.configure(background="#d9d9d9") self.v6.configure(disabledforeground="#a3a3a3") self.v6.configure(foreground="#000000") self.v6.configure(highlightbackground="#d9d9d9") self.v6.configure(highlightcolor="black") self.v6.configure(text='''V6''') self.cal6 = DateEntry(top, width=12, year=2019, month=6, day=22, background='darkblue', foreground='white', borderwidth=2) self.cal6.place(x=1000,y=380, height=35, width=98) self.v7 = tk.Label(top) self.v7.place(x=800,y=425, height=35, width=98) self.v7.configure(activebackground="#f9f9f9") self.v7.configure(activeforeground="black") self.v7.configure(background="#d9d9d9") self.v7.configure(disabledforeground="#a3a3a3") self.v7.configure(foreground="#000000") self.v7.configure(highlightbackground="#d9d9d9") self.v7.configure(highlightcolor="black") self.v7.configure(text='''V7''') self.cal7 = DateEntry(top, width=12, year=2019, month=6, day=22, background='darkblue', foreground='white', borderwidth=2) self.cal7.place(x=1000,y=425, height=35, width=98) self.v8 = tk.Label(top) self.v8.place(x=800,y=470, height=35, width=98) self.v8.configure(activebackground="#f9f9f9") self.v8.configure(activeforeground="black") self.v8.configure(background="#d9d9d9") self.v8.configure(disabledforeground="#a3a3a3") self.v8.configure(foreground="#000000") self.v8.configure(highlightbackground="#d9d9d9") self.v8.configure(highlightcolor="black") self.v8.configure(text='''V8''') self.cal8 = DateEntry(top, width=12, year=2019, month=6, day=22, background='darkblue', foreground='white', borderwidth=2) self.cal8.place(x=1000,y=470, height=35, width=98) self.Submit = tk.Button(top, command=self.acceptValues) self.Submit.place(relx=0.550, rely=0.842, height=30, width=59) self.Submit.configure(activebackground="#ececec") self.Submit.configure(activeforeground="#000000") self.Submit.configure(background="#d9d9d9") self.Submit.configure(disabledforeground="#a3a3a3") self.Submit.configure(foreground="#000000") self.Submit.configure(highlightbackground="#d9d9d9") self.Submit.configure(highlightcolor="black") self.Submit.configure(pady="0") self.Submit.configure(text='''SUBMIT''') self.Cancel = tk.Button(top, command=lambda: addGoat_support.destroy_window()) self.Cancel.place(relx=0.430, rely=0.842, height=30, width=59) self.Cancel.configure(activebackground="#ececec") self.Cancel.configure(activeforeground="#000000") self.Cancel.configure(background="#d9d9d9") self.Cancel.configure(disabledforeground="#a3a3a3") self.Cancel.configure(foreground="#000000") self.Cancel.configure(highlightbackground="#d9d9d9") self.Cancel.configure(highlightcolor="black") self.Cancel.configure(pady="0") self.Cancel.configure(text='''CANCEL''') self.goatDob.set_date(datetime.date(datetime.now())) self.cal1.set_date(datetime.date(datetime.now())) self.cal2.set_date(datetime.date(datetime.now())) self.cal3.set_date(datetime.date(datetime.now())) self.cal4.set_date(datetime.date(datetime.now())) self.cal5.set_date(datetime.date(datetime.now())) self.cal6.set_date(datetime.date(datetime.now())) self.cal7.set_date(datetime.date(datetime.now())) self.cal8.set_date(datetime.date(datetime.now())) self.disableVaccination() def acceptValues(self): try: goat_id = int(self.TEntry1.get()) g_breed = self.TEntry1_22.get() g_dob = self.goatDob.get_date() g_weight = int(self.TEntry1_24.get()) g_motherId = self.TEntry1_25.get() g_gender = 'm' if int(self.genderVal.get()) == 0 else 'f' g_isBornOrBought = self.isBornOrBought.get() v1Date = self.cal1.get_date() v2Date = self.cal2.get_date() v3Date = self.cal3.get_date() v4Date = self.cal4.get_date() v5Date = self.cal5.get_date() v6Date = self.cal6.get_date() v7Date = self.cal7.get_date() v8Date = self.cal8.get_date() # born = 0 print(g_isBornOrBought) addGoatData = {'goat_id': goat_id, 'breed': g_breed, 'date_of_birth': g_dob, 'weight': g_weight, 'gender': g_gender, 'pregnant': 'No', 'v1': str(v1Date), 'v2': str(v2Date), 'v3': str(v3Date), 'v4': str(v4Date), 'v5': str(v5Date), 'v6': str(v6Date), 'v7': str(v7Date), 'v8': str(v8Date), 'curdate': datetime.date(datetime.now())} if g_gender == 'f' and g_isBornOrBought == 0: self.db.insertGoatRecord(addGoatData, mother_id=g_motherId) elif g_gender == 'f' and g_isBornOrBought == 1: self.db.insertGoatRecord(addGoatData, mother_id='null') elif g_gender == 'm' and g_isBornOrBought == 0: self.db.insertGoatRecord(addGoatData, mother_id=g_motherId) elif g_gender == 'm' and g_isBornOrBought == 1: self.db.insertGoatRecord(addGoatData, mother_id='null') except: self.errorMsg() else: self.showSuccess() print({'goat_id': goat_id, 'breed': g_breed, 'date_of_birth': g_dob, 'weight': g_weight, 'gender': g_gender, 'pregnant': 'No', 'v1': str(v1Date), 'v2': str(v2Date), 'v3': str(v3Date), 'v4': str(v4Date), 'v5': str(v5Date), 'v6': str(v6Date), 'v7': str(v6Date), 'v8': str(v6Date)}) addGoat_support.destroy_window() def disableVaccination(self): self.TEntry1_25.config(state=NORMAL) self.cal1.config(state=DISABLED) self.cal2.config(state=DISABLED) self.cal3.config(state=DISABLED) self.cal4.config(state=DISABLED) self.cal5.config(state=DISABLED) self.cal6.config(state=DISABLED) self.cal7.config(state=DISABLED) self.cal8.config(state=DISABLED) def disableMotherId(self): self.TEntry1_25.config(state=DISABLED) self.cal1.config(state=NORMAL) self.cal2.config(state=NORMAL) self.cal3.config(state=NORMAL) self.cal4.config(state=NORMAL) self.cal5.config(state=NORMAL) self.cal6.config(state=NORMAL) self.cal7.config(state=NORMAL) self.cal8.config(state=NORMAL) def errorMsg(self): tk.messagebox.showerror("Input Error","Incorrect Data!") def showSuccess(self): tk.messagebox.showinfo("Success","Successfully Inserted")
class PaginaResumen(tk.Frame): def __init__(self, padre, controlador): ##################################### #CARGA INICIAL DEL OBJETO PÁGINA# ##################################### tk.Frame.__init__(self, padre) ##setup para archivos excel self.controlador = controlador self.ruta=controlador.ruta self.archivo="Asesor.xlsx" self.salida = os.path.join(self.ruta,self.archivo) ##################################### #GRÁFICOS# ##################################### label = tk.Label(self, text="Resumen de Facturas", font=controlador.fuente_titulo) label.pack(side="top", fill="x", pady=10) button = tk.Button(self, text="Ir al principio", command=lambda: controlador.mostrar_marco("PaginaInicial")) self.etiqueta_fecha_inicio = tk.Label(self, text="Fecha inicial para el EXCEL") self.cal_inicio = DateEntry(self, width=12, background='darkblue', foreground='white', borderwidth=2, locale='es_ES') self.cal_inicio.set_date(datetime(2000+int(self.controlador.marcos["PaginaInicial"].configuracion["año"]),1,1)) self.etiqueta_fecha_final = tk.Label(self, text="Fecha final para el EXCEL") self.cal_fin = DateEntry(self, width=12, background='darkblue', foreground='white', borderwidth=2, locale='es_ES') self.cal_fin.set_date(datetime(2000+int(self.controlador.marcos["PaginaInicial"].configuracion["año"]),12,31)) button2 = tk.Button(self, text="Facturado entre fechas", command=lambda: self.trimestral(self.cal_inicio.get(),self.cal_fin.get())) button3 = tk.Button(self, text="Facturado anual", command=lambda: self.trimestral(datetime(2000+int(self.controlador.marcos["PaginaInicial"].configuracion["año"]),1,1),datetime(2000+int(self.controlador.marcos["PaginaInicial"].configuracion["año"]),12,31))) button4 = tk.Button(self, text="Facturado 1T", command=lambda: self.trimestral(datetime(2000+int(self.controlador.marcos["PaginaInicial"].configuracion["año"]),1,1),datetime(2000+int(self.controlador.marcos["PaginaInicial"].configuracion["año"]),3,31))) button5 = tk.Button(self, text="Facturado 2T", command=lambda: self.trimestral(datetime(2000+int(self.controlador.marcos["PaginaInicial"].configuracion["año"]),4,1),datetime(2000+int(self.controlador.marcos["PaginaInicial"].configuracion["año"]),6,30))) button6 = tk.Button(self, text="Facturado 3T", command=lambda: self.trimestral(datetime(2000+int(self.controlador.marcos["PaginaInicial"].configuracion["año"]),6,30),datetime(2000+int(self.controlador.marcos["PaginaInicial"].configuracion["año"]),9,30))) button7 = tk.Button(self, text="Facturado 4T", command=lambda: self.trimestral(datetime(2000+int(self.controlador.marcos["PaginaInicial"].configuracion["año"]),10,1),datetime(2000+int(self.controlador.marcos["PaginaInicial"].configuracion["año"]),12,31))) button.pack() self.etiqueta_fecha_inicio.pack() self.cal_inicio.pack() self.etiqueta_fecha_final.pack() self.cal_fin.pack() button2.pack() button3.pack() button4.pack() button5.pack() button6.pack() button7.pack() datos_cliente_inicial=[('','Clientes contado','','','','','','','')] try: crearCliente(datos_cliente_inicial) except: print('Cliente ya creado') try: self.controlador.marcos['PaginaInicial'].actualizar()#hasta que no están todas las páginas creadas no puedo asignar la numeración automática, esta es la última página en inicializarse, por eso lo pongo aquí except: print('Sin id_factura') ##################################### #FUNCIONES# ##################################### def trimestral(self, fecha_inicial, fecha_final): #facturas = leerTodo("FACTURA") #clientes = leerTodo("CLIENTE") consulta = todoFacturasClientes("CODIGO_FACTURA", "FECHA_FACTURA", fecha_inicial, fecha_final) print ("Esta es la consulta que recibe antes de pasar a excel: \n",consulta) excel = Workbook() hoja= excel.active hoja.title = "Facturado" fila_ptr = 1 #los utilizo a modo de punteros columna_ptr = 1 #1ª fila hoja.cell(column=columna_ptr, row=fila_ptr, value=f"Declarado entre {fecha_inicial} y {fecha_final}") fila_ptr +=1 #2ª fila hoja.cell(column=columna_ptr, row=fila_ptr, value="Factura") columna_ptr +=1 hoja.cell(column=columna_ptr, row=fila_ptr, value="Fecha") columna_ptr +=1 hoja.cell(column=columna_ptr, row=fila_ptr, value="Cliente") columna_ptr +=1 hoja.cell(column=columna_ptr, row=fila_ptr, value="DNI") columna_ptr +=1 hoja.cell(column=columna_ptr, row=fila_ptr, value="Fecha Factura") columna_ptr +=1 hoja.cell(column=columna_ptr, row=fila_ptr, value="Servicios realizados") columna_ptr +=1 hoja.cell(column=columna_ptr, row=fila_ptr, value="€") columna_ptr +=1 hoja.cell(column=columna_ptr, row=fila_ptr, value="IVA %") columna_ptr +=1 hoja.cell(column=columna_ptr, row=fila_ptr, value="Descuento % ") columna_ptr +=1 hoja.cell(column=columna_ptr, row=fila_ptr, value="Total facturado €(Impuestos y descuentos incluidos") columna_ptr =1 fila_ptr +=1 #3ª fila factura_leida = "ninguna" acumulado = 0 servicios_contados=1 for info in consulta: if factura_leida == info[1]: servicios_contados+=1 acumulado +=info[-2] print ("se tiene en cuenta ", acumulado) hoja.cell(column=columna_ptr+5, row=fila_ptr-1, value=f"{servicios_contados} Tratamientos") hoja.cell(column=columna_ptr+6, row=fila_ptr-1, value=acumulado) hoja.cell(column=columna_ptr+9, row=fila_ptr-1, value=round((acumulado*(1+info[3]/100))*(1-info[4]/100),2)) continue else: acumulado = 0 servicios_contados=1 factura_leida = info[1] hoja.cell(column=columna_ptr, row=fila_ptr, value=factura_leida)#codigo columna_ptr +=1 hoja.cell(column=columna_ptr, row=fila_ptr, value=info[2])#fecha columna_ptr +=1 hoja.cell(column=columna_ptr, row=fila_ptr, value=info[9]+' '+info[10]) #nombre columna_ptr +=1 hoja.cell(column=columna_ptr, row=fila_ptr, value=info[8])#DNI columna_ptr +=1 hoja.cell(column=columna_ptr, row=fila_ptr, value=info[-4])#fecha último servicio columna_ptr +=1 hoja.cell(column=columna_ptr, row=fila_ptr, value=info[-3])#tratamiento columna_ptr +=1 hoja.cell(column=columna_ptr, row=fila_ptr, value=info[-2])#Precio del tratamiento columna_ptr +=1 hoja.cell(column=columna_ptr, row=fila_ptr, value=info[3])#IVA columna_ptr +=1 hoja.cell(column=columna_ptr, row=fila_ptr, value=info[4])#Descuento columna_ptr +=1 acumulado += info[-2]*(1+float(info[3])/100)*(1-float(info[4])/100) acumulado = round(acumulado, 2) hoja.cell(column=columna_ptr, row=fila_ptr, value=acumulado) columna_ptr =1 fila_ptr +=1 print(info) #Grabar el archivo excel.save(filename=self.salida) comando = "start excel.exe "+"\""+ self.salida +"\""+" &" os.system(comando)
def __init__(self): def frame_state(frame): global checkVar if(checkVar == 1): for child in frame.winfo_children(): child.configure(state='disable') checkVar = 0 else: for child in frame.winfo_children(): child.configure(state='normal') checkVar = 1 raiz = Tk() raiz.geometry('780x300') raiz.configure(bg=_from_rgb((67, 151, 209))) raiz.title('CsvDownloader') config = configparser.ConfigParser() config.read(('config.txt')) frameBottom = Frame(raiz, width=100, height=130, bg='green') frameTopLeft = Frame(raiz, width=200, height=250, bg='white') frameTopRigth = Frame(raiz, width=400, height=350, bg='white') checkbutton = Checkbutton(raiz, text="Enable download", bg=_from_rgb( (67, 151, 209)), command=partial(frame_state, frameTopLeft)) checkbutton.select() checkbutton.grid(row=0, sticky=W, padx=20, pady=10) frameTopLeft.grid(row=1, sticky=W, padx=20, pady=10, ipadx=10, ipady=10) frameTopRigth.grid(row=1, column=1, padx=30, pady=25, sticky=N) frameBottom.grid(row=2, column=1, padx=30, sticky=E) login = [] label1str = StringVar() label2str = StringVar() login = get_login_config() Label(frameTopLeft, text="Code:").grid( row=0, column=0, sticky=W, pady=13) Label(frameTopLeft, text="User:"******"Password:"******"Date:").grid( row=3, column=0, sticky=W, pady=13) codeEntry = Entry(frameTopLeft) userEntry = Entry(frameTopLeft) passEntry = Entry(frameTopLeft) dateEntry = DateEntry(frameTopLeft) codeEntry.grid(row=0, column=1) userEntry.grid(row=1, column=1) passEntry.grid(row=2, column=1) dateEntry.grid(row=3, column=1) codeEntry.insert(0, login[0]) userEntry.insert(0, login[1]) passEntry.insert(0, login[2]) dateEntry.set_date(login[3]) def get_entry(): global checkVar stra = [" ", " ", " ", " "] stra[0] = codeEntry.get() stra[1] = userEntry.get() stra[2] = passEntry.get() stra[3] = dateEntry.get() submit(checkVar, stra) label1 = Label(frameTopRigth, textvariable=label1str) label2 = Label(frameTopRigth, textvariable=label2str) label1str.set(config.get('SECTION_PATHS', 'download_path')) label2str.set(config.get('SECTION_PATHS', 'output_path')) label1.grid(row=0, sticky=W) label2.grid(row=1, sticky=W) ttk.Button(frameTopRigth, text='Seleccionar Carpeta Descargas', command=partial(search_path, label1str)).grid(row=0, column=1) ttk.Button(frameTopRigth, text='Seleccionar Carpeta Destino', command=partial(output_path, label2str)).grid(row=1, column=1) ttk.Button(frameBottom, text='Salir', command=raiz.destroy).grid(row=0, column=0) ttk.Button(frameBottom, text='Descargar', command=get_entry).grid(row=0, column=1) raiz.mainloop()
def _make_query_frame( self, parent, ): """ make parameter frame for queries Return: a frame with the controls in it """ a_frame = Frame(parent, width=600, height=200, bg=self.bkg_color, relief=RAISED, borderwidth=1) # add some more for db, different style, which do I like best? lrow = 0 lcol = 0 # some spacers might be nice -- may put back as we play with the look # a_spacer = Frame( a_frame, width=60, height=60, bg ="green", relief=RAISED, borderwidth=1 ) # a_spacer.grid( row = 0, column = lcol, sticky = E + W + N + S, rowspan = 2 ) # ------------------------------------ # !! do not need to save lables lrow += 1 (lrow, lcol, self.lbl_start) = self._make_label( a_frame, lrow, lcol, "Start date and hour:", ) (lrow, lcol, self.lbl_end) = self._make_label( a_frame, lrow, lcol, "End date and hour:", ) #( lrow, lcol, self.lbl_db_user ) = self._make_label( a_frame, lrow, lcol, "user", ) lrow = 0 lcol = 2 cal = DateEntry( a_frame, width=12, background='darkblue', foreground='white', borderwidth=2, year=2010, bordercolor="red", ) cal.grid(row=lrow, column=lcol, sticky=E + W + N + S) cal.configure(date_pattern="yyyy/mm/dd") cal.set_date(self.parameters.graph_begin_date) self.cal_begin = cal cal = DateEntry( a_frame, width=12, background='darkblue', foreground='white', borderwidth=2, year=2010, bordercolor="red", ) cal.grid(row=lrow + 1, column=lcol, sticky=E + W + N + S) cal.configure(date_pattern="yyyy/mm/dd") cal.set_date(self.parameters.graph_end_date) self.cal_end = cal # save for later #------------------------------------- lrow = 0 lcol = 3 a_widget = ttk.Combobox(a_frame, values=AppGlobal.dd_hours, state='readonly') a_widget.grid(row=lrow, column=lcol, rowspan=1, sticky=E + W + N + S) # sticky=W+E+N+S ) # relief = RAISED) a_widget.set(self.parameters.graph_begin_hr) self.time_begin = a_widget a_widget = ttk.Combobox(a_frame, values=AppGlobal.dd_hours, state='readonly') a_widget.grid(row=lrow + 1, column=lcol, rowspan=1, sticky=E + W + N + S) # sticky=W+E+N+S ) # relief = RAISED) a_widget.set(self.parameters.graph_end_hr) self.time_end = a_widget #------------- some of this may be added back later or not --------------- lrow = 0 lcol = 4 a_rb = Radiobutton(a_frame, text="From Parms ", variable=self.rb_var, value=0, command=self.controller.cb_rb_select) a_rb.grid(row=lrow, column=lcol) #lrow = 1 lcol += 1 a_rb = Radiobutton(a_frame, text="Today", variable=self.rb_var, value=1, command=self.controller.cb_rb_select) a_rb.grid(row=lrow, column=lcol) #lrow = 0 lcol += 1 a_rb = Radiobutton(a_frame, text="From Now - 1hr ", variable=self.rb_var, value=6, command=self.controller.cb_rb_select) a_rb.grid(row=lrow, column=lcol) # ------- ikd buttons that could come back # lcol += 1 # a_rb = Radiobutton( a_frame, text = "From Sun - 2 ", variable = self.rb_var, value=2, command=self.controller.cb_rb_select ) # a_rb.grid( row = lrow, column = lcol ) # # lrow = 1 # lcol = 4 # a_rb = Radiobutton( a_frame, text = "From Sun - 3 ", variable = self.rb_var, value=3, command=self.controller.cb_rb_select ) # a_rb.grid( row = lrow, column = lcol ) # # #lrow = 0 # lcol += 1 # a_rb = Radiobutton( a_frame, text = "From Sun - 4 ", variable = self.rb_var, value=4, command=self.controller.cb_rb_select ) # a_rb.grid( row = lrow, column = lcol ) # # #lrow = 1 # lcol += 1 # a_rb = Radiobutton( a_frame, text = "From Sun - 5 ", variable = self.rb_var, value=5, command=self.controller.cb_rb_select ) # a_rb.grid( row = lrow, column = lcol ) # lrow = 0 # lcol += 1 # a_rb = Radiobutton( a_frame, text = "From Now - 1hr ", variable = self.rb_var, value=6, command=self.controller.cb_rb_select ) # a_rb.grid( row = lrow, column = lcol ) # lrow = 1 # #lcol += 1 # a_rb = Radiobutton( a_frame, text = "From Now - 3 ", variable = self.rb_var, value=7, command=self.controller.cb_rb_select ) # a_rb.grid( row = lrow, column = lcol ) # # # ------------------------------ # lrow = 0 # lcol += 1 # #lrow += 1 # # a_spacer = Frame( a_frame, width=60, height=60, bg ="green", relief=RAISED, borderwidth=1 ) # a_spacer.grid( row = lrow, column = lcol, sticky = E + W + N + S, rowspan = 2 ) # ------------------------------ # lrow = 0 # lcol += 1 # # if lrow >= 2: # lrow = 0 # lcol += 1 # # a_label = ( Label( a_frame, text = "status", relief = RAISED, ) ) # a_label.grid( row=lrow, column=lcol, sticky=E + W + N + S ) # sticky=W+E+N+S ) # relief = RAISED) # self.lbl_db_status = a_label # # ( lrow, lcol, self.lbl_db_connect ) = self._make_label( a_frame, lrow, lcol, "connect", ) # ( lrow, lcol, self.lbl_db_host ) = self._make_label( a_frame, lrow, lcol, "host", ) # ( lrow, lcol, self.lbl_db_db ) = self._make_label( a_frame, lrow, lcol, "db", ) # ( lrow, lcol, self.lbl_db_user ) = self._make_label( a_frame, lrow, lcol, "user", ) return a_frame
class UpdateStudent(Toplevel): updater = 0 def backf(self, event=""): self.destroy() self.root.deiconify() def c_w(self, event=""): m = messagebox.askyesno("School Software", "Are you Want to Close Application?", parent=self.root) if m > 0: query4 = "update staff set currentuser = 0 where currentuser = 1;" self.conn.execute(query4) self.conn.commit() self.main_root.destroy() else: return def start(self): self.updater = 0 self.stds = StringVar() self.stds.set("Select Standard") self.rno = StringVar() self.rno.set("Select Roll number") self.caste = StringVar() self.category = StringVar() self.bloodg = StringVar() self.dob = StringVar() self.grno = StringVar() self.rollno = StringVar() self.std = StringVar() # self.div = StringVar() self.fname = StringVar() self.mname = StringVar() self.lname = StringVar() self.address = StringVar() self.phnos = StringVar() self.phnop = StringVar() self.email = StringVar() self.poadd = StringVar() self.pophno = StringVar() self.fee = StringVar() print(self.stds.get()) text = Label(self.lf2, text="Select Standard : ", bd=2, bg="black", fg="White", font=(self.f1, 15), relief=GROOVE) text.place(x=50, y=10, height=25) self.stdchoosen = Combobox(self.lf2, state="readonly", textvariable=self.stds, font=(self.f1, 10)) self.stdchoosen.place(x=250, y=10, height=25, width=200) self.stdchoosen['values'] = self.getStd() self.stdchoosen.bind("<<ComboboxSelected>>", self.nextStep) # ========================================================validation function============================================================ def validNumber(self, s): Pattern = re.compile("(0/91)?[6-9][0-9]{9}") return Pattern.match(s) def validEmail(self, s): Pattern = re.compile("^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$") return Pattern.match(s) def validName(self, s): Pattern = re.compile("([A-Za-z]+)*$") return Pattern.match(s) def validRollno(self, s): Pattern = re.compile("^[0-9]*$") return Pattern.match(s) def validDivision(self, s): Pattern = re.compile("([A-Za-z]+)*$") return Pattern.match(s) def validFee(self, s): Pattern = re.compile("^[0-9]*$") return Pattern.match(s) # ========================================================to Update record============================================================ def UpdateVaribleIntoTable(self, fname, mname, lname, address, phnos, phnop, email, poadd, pophno, fees, dob, category, bloodg, caste, grno): try: sqliteConnection = sqlite3.connect('sinfo.db') cursor = sqliteConnection.cursor() print("Connected to SQLite") sqlite_update = """UPDATE master SET fname = ?, mname = ?, lname = ?, address = ?, student_phno = ?, parents_phno = ?, email = ?, parent_office_address = ?, parents_office_phno = ?, fee = ?, date_of_birth = ?, category = ?, blood_group = ?, cast = ? WHERE grno = ?;""" data_tuple = ( fname, mname, lname, address, phnos, phnop, email, poadd, pophno, fees, dob, category, bloodg, caste, grno) cursor.execute(sqlite_update, data_tuple) sqliteConnection.commit() print("Python Variables Updated successfully into detail table") messagebox.showinfo('Successfully done', 'Entry is done in database') self.updater = 1 cursor.close() except sqlite3.Error as error: print("update") print("Failed to insert Python variable into sqlite table", error) finally: if (sqliteConnection): sqliteConnection.close() print("The SQLite connection is closed") # ==========================================================to check validation========================================================== def submitvalue(self): self.dob = str(self.dobentry.get_date()) self.address = self.addressentry.get(1.0, END) self.poadd = self.poaddentry.get(1.0, END) try: if (len(self.address) != 1): pass else: raise ValueError except: messagebox.showerror("School Software", "Please enter address") return try: if (len(self.poadd) != 1): pass else: raise ValueError except: messagebox.showerror("School Software", "Please enter parent office address") return """try: if self.category.get() != "Select Category": pass else: raise ValueError except: messagebox.showerror("School Software", "Please select category") return""" try: if self.caste.get() != "": pass else: raise ValueError except: messagebox.showerror("School Software", "Please enter caste") self.casteentry.focus_set() return """try: if self.dobentry.get_date() != self.today_date: pass else: raise ValueError except: messagebox.showerror("School Software", "Please select date of birth") return""" """try: if self.bloodg.get() != "Select Blood Group": pass else: raise ValueError except: messagebox.showerror("School Software", "Please select blood group") return""" """try: if ((self.std.get() != "") and (int(self.std.get()) >= 1) and (int(self.std.get()) <= 12)): pass else: raise ValueError except: messagebox.showerror("School Software", "Please enter valid standard") self.stdentry.focus_set() return""" try: if ((self.validFee(self.fee.get())) and (self.fee.get() != "")): pass else: raise ValueError except: messagebox.showerror("School Software", "Please enter valid fee") self.feesentry.focus_set() return try: if ((self.validName(self.fname.get())) and (self.fname.get() != "")): pass else: raise ValueError except: messagebox.showerror("School Software", "Please enter valid first name") self.fnameentry.focus_set() return try: if ((self.validName(self.mname.get())) and (self.mname.get() != "")): pass else: raise ValueError except: messagebox.showerror("School Software", "Please enter valid middle name") self.mnameentry.focus_set() return try: if ((self.validName(self.lname.get())) and (self.lname.get() != "")): pass else: raise ValueError except: messagebox.showerror("School Software", "Please enter valid last name") self.lnameentry.focus_set() return """try: if (self.medium.get() != "Select Medium"): pass else: raise ValueError except: messagebox.showerror('Error', 'please select medium but select medium after entering standard') return""" try: if ((self.validNumber(self.phnos.get())) and (len(self.phnos.get()) == 10)): pass else: raise ValueError except: messagebox.showerror("School Software", "Please enter valid student phone number") self.phnosentry.focus_set() return try: if ((self.validNumber(self.phnop.get())) and (len(self.phnop.get()) == 10)): pass else: raise ValueError except: messagebox.showerror("School Software", "Please enter valid parent phone number") self.phnopentry.focus_set() return try: if ((self.validNumber(self.pophno.get())) and (len(self.pophno.get()) == 10)): pass else: raise ValueError except: messagebox.showerror("School Software", "Please enter valid parent office phone number") self.pophnoentry.focus_set() return try: if (self.validEmail(self.email.get())): pass else: raise ValueError except: messagebox.showerror("School Software", "Please enter valid email address") self.emailentry.focus_set() return """if (self.validNumber(self.phnop.get()) and self.validNumber(self.phnos.get()) and self.validNumber( self.pophno.get()) and (len(self.phnos.get()) == 10) and (len(self.phnop.get()) == 10) and ( len(self.pophno.get()) == 10)): if (self.validEmail(self.email.get())): if (self.validName(self.fname.get()) and self.validName(self.mname.get()) and self.validName( self.lname.get()) and (self.fname.get() != "") and (self.mname.get() != "") and ( self.lname.get() != "")): if ((self.fee.get() != "") and self.validFee(self.fee.get())):""" self.grn = str(self.getGrn(self.stds.get(), self.rnochoosen.get())[0][0]) self.UpdateVaribleIntoTable(self.fname.get(), self.mname.get(), self.lname.get(), self.address, self.phnos.get(), self.phnop.get(), self.email.get(), self.poadd, self.pophno.get(), self.fee.get(), self.dob, self.category.get(), self.bloodg.get(), self.caste.get(), self.grn) self.setValue() print("done") """else: if ((self.rno.get() == "") or (not(self.validRollno(self.rno.get())))): self.rnoentry.focus_set() messagebox.showinfo('Error', 'Please enter valid Roll number') elif (self.div.get() == ""): self.diventry.focus_set() messagebox.showinfo('Error', 'Please enter Division') if ((self.stds.get() == "") or (self.stds.get() < "1") or (self.stds.get() > "12")): self.stdentry.focus_set() messagebox.showinfo('Error', 'Please enter valid standard') if ((not (self.validFee(self.fee.get()))) or (self.fee.get() == "")): self.feesentry.focus_set() messagebox.showinfo('Error', 'Please enter valid fees') else: if ((not (self.validName(self.fname.get()))) or (self.fname.get() == "")): self.fnameentry.focus_set() messagebox.showinfo('Error', 'Invalid first name') elif ((not (self.validName(self.mname.get()))) or (self.mname.get() == "")): self.mnameentry.focus_set() messagebox.showinfo('Error', 'Invalid middle name') elif ((not (self.validName(self.lname.get()))) or (self.lname.get() == "")): self.lnameentry.focus_set() messagebox.showinfo('Error', 'Invalid last name') else: self.emailentry.focus_set() messagebox.showinfo('Error', 'Invalid email address') else: if ((not (self.validNumber(self.phnop.get()))) or (len(self.phnop.get()) != 10)): self.phnopentry.focus_set() messagebox.showinfo('Error', 'Invalid parent mobile number') elif ((not (self.validNumber(self.phnos.get()))) or (len(self.phnos.get()) != 10)): self.phnosentry.focus_set() messagebox.showinfo('Error', 'Invalid student mobile number') elif ((not (self.validNumber(self.pophno.get()))) or (len(self.pophno.get()) != 10)): self.pophnoentry.focus_set() messagebox.showinfo('Error', 'Invalid parent office mobile number')""" # ============================================================to set all field as null======================================================== def setValue(self): self.rno = "-" self.std = "-" # self.div.set("") self.fname.set("") self.mname.set("") self.lname.set("") self.addressentry.delete(1.0, END) self.phnos.set("") self.phnop.set("") self.email.set("") self.poaddentry.delete(1.0, END) self.pophno.set("") self.fee.set("") # ========================================================to get standard============================================================ def getStd(self): try: sqliteConnection = sqlite3.connect('sinfo.db') cursor = sqliteConnection.cursor() print("Connected to SQLite") sqlite_getstd = """SELECT DISTINCT standard FROM master;""" cursor.execute(sqlite_getstd) # sqliteConnection.commit() # print("Python Variables deleted successfully from detail table") # messagebox.showinfo('Successfully done', 'Deletion is done in database') return cursor.fetchall() cursor.close() except sqlite3.Error as error: print("Failed to delete Python variable into sqlite table", error) finally: if (sqliteConnection): sqliteConnection.close() print("The SQLite connection is closed") # ========================================================to get standard============================================================ def getRoll(self, stds, ): try: sqliteConnection = sqlite3.connect('sinfo.db') cursor = sqliteConnection.cursor() print("Connected to SQLite") sqlite_getrno = """SELECT rollno FROM master WHERE standard = ?;""" data_tuple = (stds,) cursor.execute(sqlite_getrno, data_tuple) # sqliteConnection.commit() # print("Python Variables deleted successfully from detail table") # messagebox.showinfo('Successfully done', 'Deletion is done in database') return cursor.fetchall() cursor.close() except sqlite3.Error as error: print("Failed to delete Python variable into sqlite table", error) finally: if (sqliteConnection): sqliteConnection.close() print("The SQLite connection is closed") # ========================================================to get current values============================================================ def getRow(self, stds, rno): try: sqliteConnection = sqlite3.connect('sinfo.db') cursor = sqliteConnection.cursor() print("Connected to SQLite") sqlite_getrow = """SELECT * FROM master WHERE standard = ? AND rollno = ?;""" data_tuple = (stds, rno) cursor.execute(sqlite_getrow, data_tuple) # sqliteConnection.commit() # print("Python Variables deleted successfully from detail table") # messagebox.showinfo('Successfully done', 'Deletion is done in database') return cursor.fetchall() cursor.close() except sqlite3.Error as error: print("roll") print("Failed to delete Python variable into sqlite table", error) finally: if (sqliteConnection): sqliteConnection.close() print("The SQLite connection is closed") # ========================================================to get gr number============================================================ def getGrn(self, stds, rno): try: sqliteConnection = sqlite3.connect('sinfo.db') cursor = sqliteConnection.cursor() print("Connected to SQLite") sqlite_getgr = """SELECT grno FROM master WHERE standard = ? AND rollno = ?;""" data_tuple = (stds, rno) cursor.execute(sqlite_getgr, data_tuple) # sqliteConnection.commit() # print("Python Variables deleted successfully from detail table") # messagebox.showinfo('Successfully done', 'Deletion is done in database') return cursor.fetchall() cursor.close() except sqlite3.Error as error: print("roll") print("Failed to delete Python variable into sqlite table", error) finally: if (sqliteConnection): sqliteConnection.close() print("The SQLite connection is closed") # ========================================================1st next============================================================ def nextStep(self, event): if (self.stds.get() == "Select Standard"): messagebox.showerror('Error', 'Please select standard') else: text = Label(self.lf2, text="Select Rollno : " ,bd=2, bg="black", fg="White", font=(self.f1, 15), relief=GROOVE) text.place(x=550, y=10, height=25) self.rnochoosen = Combobox(self.lf2, state="readonly", textvariable=self.rno, font=(self.f1,10)) self.rnochoosen.place(x=800, y=10, height=25, width=200) self.rnochoosen['values'] = self.getRoll(self.stds.get(), ) self.rnochoosen.bind("<<ComboboxSelected>>", self.nextStep2) # Create a Button """self.btn2 = Button(self, text='Next', bd='5', command=self.nextStep2) # Set the position of button on the top of window. self.btn2.place(x=100, y=550, height=25, width=150)""" # ========================================================2nd next============================================================ def nextStep2(self, event): if (self.rnochoosen.get() == "Select Roll number"): messagebox.showerror('Error', 'Please select roll number') else: self.row = self.getRow(self.stds.get(), self.rnochoosen.get()) self.grno = (self.row[0][0]) self.rollno = (self.row[0][1]) self.std = (self.row[0][2]) # self.div = (self.row[0][2].split("-")[1]) self.fname.set(self.row[0][4]) self.mname.set(self.row[0][5]) self.lname.set(self.row[0][6]) self.address = (self.row[0][7]) self.phnos.set(self.row[0][8]) self.phnop.set(self.row[0][9]) self.email.set(self.row[0][10]) self.poadd = (self.row[0][11]) self.pophno.set(self.row[0][12]) self.fee.set(self.row[0][13]) self.dob = (self.row[0][16]) print(self.dob) self.category.set(self.row[0][17]) self.bloodg.set(self.row[0][18]) self.caste.set(self.row[0][19]) print(self.row[0][0]) text = Label(self.lf2,text="GRno" ,bd=2, bg="black", fg="White", font=(self.f1, 15), relief=GROOVE) text.place(x=550, y=50, height=25) self.grnotext = Label(self.lf2,text=self.grno ,bd=2, bg="black", fg="White", font=(self.f1, 15), relief=GROOVE) self.grnotext.place(x=800, y=50, height=25) text = Label(self.lf2,text="Rollno" ,bd=2, bg="black", fg="White", font=(self.f1, 15), relief=GROOVE) text.place(x=550, y=90, height=25) self.rollnotext = Label(self.lf2,text=self.rollno ,bd=2, bg="black", fg="White", font=(self.f1, 15), relief=GROOVE) self.rollnotext.place(x=800, y=90, height=25) text = Label(self.lf2,text="Std." ,bd=2, bg="black", fg="White", font=(self.f1, 15), relief=GROOVE) text.place(x=50, y=50, height=25) self.stdentry = Label(self.lf2,text=self.std ,bd=2, bg="black", fg="White", font=(self.f1, 15), relief=GROOVE) self.stdentry.place(x=250, y=50, height=25) self.stdentry.focus_set() text = Label(self.lf2,text="Date of birth" ,bd=2, bg="black", fg="White", font=(self.f1, 15), relief=GROOVE) text.place(x=550, y=300, height=25) self.dobentry = DateEntry(self.lf2, date_pattern='yyyy/mm/dd', state="readonly", font=(self.f1,10)) self.dobentry.place(x=800, y=300, height=25, width=150) self.dobentry.set_date((datetime.datetime.strptime(self.dob, "%Y-%m-%d").date())) text = Label(self.lf2, text="Category" ,bd=2, bg="black", fg="White", font=(self.f1, 15), relief=GROOVE) text.place(x=550, y=330, height=25) self.categorychoosen = Combobox(self.lf2, state="readonly", textvariable=self.category, font=(self.f1,10)) self.categorychoosen.place(x=800, y=330, height=25, width=200) self.categorychoosen['values'] = ["ST", "SC", "OBC", "OPEN", "Other"] text = Label(self.lf2, text="Blood group" ,bd=2, bg="black", fg="White", font=(self.f1, 15), relief=GROOVE) text.place(x=550, y=360, height=25) self.bloodgchoosen = Combobox(self.lf2, state="readonly", textvariable=self.bloodg, font=(self.f1,10)) self.bloodgchoosen.place(x=800, y=360, height=25, width=200) self.bloodgchoosen['values'] = ["A+", "B+", "A-", "B-", "AB+", "O+", "O-"] text = Label(self.lf2, text="caste" ,bd=2, bg="black", fg="White", font=(self.f1, 15), relief=GROOVE) text.place(x=550, y=390, height=25) self.casteentry = Entry(self.lf2, textvariable=self.caste, font=(self.f1,10)) self.casteentry.place(x=800, y=390, height=25, width=150) """text = Label(self.lf2,text="Div.") text.place(x=5, y=65, height=25) self.diventry = Entry(self.lf2, textvariable=self.div) self.diventry.place(x=100, y=65, height=25, width=150)""" text = Label(self.lf2,text="First name" ,bd=2, bg="black", fg="White", font=(self.f1, 15), relief=GROOVE) text.place(x=50, y=90, height=25) self.fnameentry = Entry(self.lf2, textvariable=self.fname, font=(self.f1,10)) self.fnameentry.place(x=250, y=90, height=25, width=150) text = Label(self.lf2,text="Middle name" ,bd=2, bg="black", fg="White", font=(self.f1, 15), relief=GROOVE) text.place(x=50, y=130, height=25) self.mnameentry = Entry(self.lf2, textvariable=self.mname, font=(self.f1,10)) self.mnameentry.place(x=250, y=130, height=25, width=150) text = Label(self.lf2,text="Last name" ,bd=2, bg="black", fg="White", font=(self.f1, 15), relief=GROOVE) text.place(x=50, y=170, height=25) self.lnameentry = Entry(self.lf2, textvariable=self.lname, font=(self.f1,10)) self.lnameentry.place(x=250, y=170, height=25, width=150) text = Label(self.lf2,text="Address" ,bd=2, bg="black", fg="White", font=(self.f1, 15), relief=GROOVE) text.place(x=50, y=210, height=25) self.addressentry = Text(self.lf2, width=20, height=5, padx=2, pady=2, wrap=WORD, font=(self.f1,10)) self.addressentry.place(x=250, y=210, height=75, width=150) self.addressentry.insert(INSERT, self.address) text = Label(self.lf2,text="Student ph." ,bd=2, bg="black", fg="White", font=(self.f1, 15), relief=GROOVE) text.place(x=50, y=300, height=25) self.phnosentry = Entry(self.lf2, textvariable=self.phnos, font=(self.f1,10)) self.phnosentry.place(x=250, y=300, height=25, width=150) text = Label(self.lf2,text="Parent ph." ,bd=2, bg="black", fg="White", font=(self.f1, 15), relief=GROOVE) text.place(x=50, y=340, height=25) self.phnopentry = Entry(self.lf2, textvariable=self.phnop, font=(self.f1,10)) self.phnopentry.place(x=250, y=340, height=25, width=150) text = Label(self.lf2,text="Email id" ,bd=2, bg="black", fg="White", font=(self.f1, 15), relief=GROOVE) text.place(x=50, y=380, height=25) self.emailentry = Entry(self.lf2, textvariable=self.email, font=(self.f1,10)) self.emailentry.place(x=250, y=380, height=25, width=150) text = Label(self.lf2,text="Parent office add." ,bd=2, bg="black", fg="White", font=(self.f1, 15), relief=GROOVE) text.place(x=550, y=130, height=25) self.poaddentry = Text(self.lf2, width=20, height=5, padx=2, pady=2, wrap=WORD, font=(self.f1,10)) self.poaddentry.place(x=800, y=130, height=75, width=150) self.poaddentry.insert(INSERT, self.poadd) text = Label(self.lf2,text="Parent office ph." ,bd=2, bg="black", fg="White", font=(self.f1, 15), relief=GROOVE) text.place(x=550, y=220, height=25) self.pophnoentry = Entry(self.lf2, textvariable=self.pophno, font=(self.f1,10)) self.pophnoentry.place(x=800, y=220, height=25, width=150) text = Label(self.lf2,text="Fees" ,bd=2, bg="black", fg="White", font=(self.f1, 15), relief=GROOVE) text.place(x=550, y=260, height=25) self.feesentry = Entry(self.lf2, textvariable=self.fee, font=(self.f1,10)) self.feesentry.place(x=800, y=260, height=25, width=150) # Create a Button self.btn3 = Button(self.lf2, text='Update', bd='5', font=(self.f2, 15), command=self.lastStep) # Set the position of button on the top of window. self.btn3.place(x=550, y=450, height=25, width=150) # ========================================================Last Step============================================================ def lastStep(self): self.submitvalue() if (self.updater == 1): self.rnochoosen.destroy() self.grnotext.destroy() self.rollnotext.destroy() self.stdentry.destroy() self.fnameentry.destroy() self.mnameentry.destroy() self.lnameentry.destroy() self.addressentry.destroy() self.phnosentry.destroy() self.phnopentry.destroy() self.emailentry.destroy() self.poaddentry.destroy() self.pophnoentry.destroy() self.feesentry.destroy() self.casteentry.destroy() self.categorychoosen.destroy() self.dobentry.destroy() self.bloodgchoosen.destroy() self.btn3.destroy() self.start() # ========================================================Main============================================================ def __init__(self, root, main_root): self.main_root = main_root self.root = root try: self.conn = sqlite3.connect('sinfo.db') except: messagebox.showerror("School Software", "Database Connection Error.") Toplevel.__init__(self) self.lift() self.focus_force() self.grab_set() self.grab_release() self.bgclr1 = "#0080c0" self.bgclr2 = "#e7d95a" self.f1 = "Arial Bold" self.f2 = "times new roman" self.title("UPDATE STUDENT") self.config(background=self.bgclr1) self.geometry("1350x700+0+0") self.resizable(False, False) ##===================================================frame1 ==================================================== imagel = Image.open("left-arrow.png") imagel = imagel.resize((60, 15)) imgl = ImageTk.PhotoImage(imagel) self.lf1 = LabelFrame(self, text="NAME", bd=2, bg="black", fg="white", font=(self.f1, 20), relief=GROOVE) self.lf1.place(x=0, y=0, height=150, width=1350) bb = Button(self.lf1, image=imgl, bd=5, font=(self.f1, 20), bg="white", command=self.backf) bb.place(x=10, y=10) ##===============================================frame 2======================================================== self.lf2 = LabelFrame(self, text="UPDATE STUDENT", bd=2, bg="black", fg="white", font=(self.f1, 20), relief=GROOVE) self.lf2.place(x=0, y=150, height=550, width=1350) self.start() # Create a Button """self.btn = Button(self, text='Next', bd='5', command=self.nextStep) # Set the position of button on the top of window. self.btn.place(x=100, y=550, height=25, width=150)""" self.protocol("WM_DELETE_WINDOW", self.c_w) self.mainloop()
entry_demandado.insert(0, demandado) # Crear caja de fecha 4, fecha de acta. entry_var_actainfraccion = tk.StringVar() entry_actainfraccion = DateEntry(principal, textvariable=entry_var_actainfraccion, date_pattern='dd/mm/Y', width=17, background='gray', foreground='white', borderwidth=1) label_actainfraccion = ttk.Label(principal, text="Fecha del Acta de Infracción", background="#ffffff") if actainfraccion: entry_actainfraccion.set_date(actainfraccion) # Crear caja de fecha 5, fecha resolucion impugnada. entry_var_resolucionrecargo = tk.StringVar() entry_resolucionrecargo = DateEntry(principal, textvariable=entry_var_resolucionrecargo, date_pattern='dd/mm/Y', width=17, background='gray', foreground='white', borderwidth=1) label_resolucionrecargo = ttk.Label(principal, text="Fecha de la Resolución impugnada", background="#ffffff") if resolucionrecargo: entry_resolucionrecargo.set_date(resolucionrecargo)
class Funcionario_view(tk.Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.pack() self.criar_widget_funcionario() self.funcionario = Funcionario("", 0, 0, "", "", "", 0) def criar_widget_funcionario(self): # Título self.container_titulo = tk.Frame(self.master) self.container_titulo["pady"] = 10 self.container_titulo["padx"] = 20 self.container_titulo.pack() self.titulo_dados = tk.Label(self.container_titulo, text="CADASTRAR NOVO FUNCIONÁRIO") self.titulo_dados.pack() # Campo id self.container_id = self.criar_container_padrao() self.id_label = tk.Label(self.container_id, text="Id") self.id_label["width"] = 20 self.id_label["anchor"] = tk.NW self.id_label.pack(side=tk.LEFT) self.id = tk.Entry(self.container_id) self.id["width"] = 10 self.id.pack(side=tk.LEFT) self.botao_buscar = tk.Button(self.container_id) self.botao_buscar["text"] = "Buscar" self.botao_buscar["command"] = self.buscar_funcionario self.botao_buscar.pack(side=tk.LEFT) # Campo nome self.container_nome = self.criar_container_padrao() self.nome_label = tk.Label(self.container_nome, text="Nome") self.nome_label["width"] = 20 self.nome_label["anchor"] = tk.NW self.nome_label.pack(side=tk.LEFT) self.nome = tk.Entry(self.container_nome) self.nome["width"] = 20 self.nome.pack(side=tk.LEFT) # Campo nascimento self.container_nascimento = self.criar_container_padrao() self.nascimento_label = tk.Label(self.container_nascimento, text="Data de nascimento") self.nascimento_label["width"] = 20 self.nascimento_label["anchor"] = tk.NW self.nascimento_label.pack(side=tk.LEFT) self.nascimento = DateEntry(self.container_nascimento, width=18, background='darkblue', foreground='white', borderwidth=2) self.nascimento.pack(side=tk.LEFT) # Campo sexo self.container_sexo = self.criar_container_padrao() self.sexo_label = tk.Label(self.container_sexo, text="Sexo") self.sexo_label["width"] = 20 self.sexo_label["anchor"] = tk.NW self.sexo_label.pack(side=tk.LEFT) self.sexo = tk.StringVar(self.container_sexo) self.sexo.set("") # default value self.sexo_combo = tk.OptionMenu(self.container_sexo, self.sexo, "Masculino", "Feminino", "") self.sexo_combo["width"] = 15 self.sexo_combo.pack(side=tk.LEFT) # Campo cargo self.container_cargo = self.criar_container_padrao() self.cargo_label = tk.Label(self.container_cargo, text="Cargo") self.cargo_label["width"] = 20 self.cargo_label["anchor"] = tk.NW self.cargo_label.pack(side=tk.LEFT) self.cargo = tk.Entry(self.container_cargo) self.cargo["width"] = 20 self.cargo.pack(side=tk.LEFT) # Campo qtde dependentes self.container_qtde_dependetes = self.criar_container_padrao() self.qtde_dependetes_label = tk.Label(self.container_qtde_dependetes, text="Dependentes") self.qtde_dependetes_label["width"] = 20 self.qtde_dependetes_label["anchor"] = tk.NW self.qtde_dependetes_label.pack(side=tk.LEFT) self.qtde_dependetes = tk.StringVar(self.container_qtde_dependetes) self.qtde_dependetes.set("0") # default value self.qtde_dependetes_combo = tk.OptionMenu(self.container_qtde_dependetes, self.qtde_dependetes, "0", "1", "2", "3", "4", "5") self.qtde_dependetes_combo["width"] = 15 self.qtde_dependetes_combo.pack(side=tk.LEFT) # Botões self.container_botoes = self.criar_container_padrao() self.botao_criar = tk.Button(self.container_botoes) self.botao_criar["text"] = "Criar" self.botao_criar["command"] = self.add_funcionario self.botao_criar["bg"] = "blue" self.botao_criar["fg"] = "white" self.botao_criar.pack(side=tk.LEFT) self.botao_atualizar = tk.Button(self.container_botoes) self.botao_atualizar["text"] = "Atualizar" self.botao_atualizar["command"] = self.atualizar_funcionario self.botao_atualizar["bg"] = "green" self.botao_atualizar["fg"] = "white" self.botao_atualizar["state"] = "disabled" self.botao_atualizar.pack(side=tk.LEFT) self.botao_excluir = tk.Button(self.container_botoes) self.botao_excluir["text"] = "Excluir" self.botao_excluir["command"] = self.excluir_funcionario self.botao_excluir["bg"] = "red" self.botao_excluir["fg"] = "white" self.botao_excluir["state"] = "disabled" self.botao_excluir.pack(side=tk.LEFT) self.botao_limpar = tk.Button(self.container_botoes) self.botao_limpar["text"] = "Limpar" self.botao_limpar["command"] = self.limpar_tela self.botao_limpar.pack() # Mensagem self.container_mensagem = self.criar_container_padrao() self.mensagem = tk.Label(self.container_mensagem, text="") self.mensagem.pack() def criar_container_padrao(self): container = tk.Frame(self.master) container["padx"] = 20 container["pady"] = 5 container.pack() return container def add_funcionario(self): self.funcionario.nome = self.nome.get() self.funcionario.cargo = self.cargo.get() self.funcionario.id_setor = 0 self.funcionario.qtd_dependentes = self.qtde_dependetes.get() self.funcionario.sexo = self.sexo.get() self.funcionario.data_nascimento = self.nascimento.get() self.funcionario.salario = 950 status, id_gerado, mensagem = self.funcionario.insert_funcionario() if status: self.id.insert(0, id_gerado) self.botao_criar.config(state="disabled") self.botao_excluir.config(state="normal") self.botao_atualizar.config(state="normal") self.mensagem["text"] = mensagem def limpar_tela(self): self.id.delete(0, tk.END) self.nome.delete(0, tk.END) self.nascimento.delete(0, tk.END) self.cargo.delete(0, tk.END) self.sexo.set("") self.qtde_dependetes.set("0") self.mensagem["text"] = "" self.funcionario = Funcionario("", 0, 0, "", "", "", 0) self.botao_criar.config(state="normal") self.botao_excluir.config(state="disabled") self.botao_atualizar.config(state="disabled") def buscar_funcionario(self): status, mensagem = self.funcionario.select_funcionario(self.id.get()) if status: self.nome.insert(0, self.funcionario.nome) self.nascimento.set_date(self.funcionario.data_nascimento) self.cargo.insert(0, self.funcionario.cargo) self.sexo.set(self.funcionario.sexo) self.qtde_dependetes.set(self.funcionario.qtd_dependentes) self.botao_criar.config(state="disabled") self.botao_excluir.config(state="normal") self.botao_atualizar.config(state="normal") else: self.limpar_tela() self.mensagem["text"] = mensagem def atualizar_funcionario(self): self.funcionario.nome = self.nome.get() self.funcionario.cargo = self.cargo.get() self.funcionario.id_setor = 0 self.funcionario.qtd_dependentes = self.qtde_dependetes.get() self.funcionario.sexo = self.sexo.get() self.funcionario.data_nascimento = self.nascimento.get() self.funcionario.salario = 950 status, mensagem = self.funcionario.update_funcionario() if status: self.limpar_tela() self.mensagem["text"] = mensagem def excluir_funcionario(self): self.funcionario.id_funcionario = self.id.get() status, mensagem = self.funcionario.delete_funcionario() if status: self.limpar_tela() self.mensagem["text"] = mensagem