Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from tkinter import *
- # from tkinter.ttk import * изпада в комфликт по отношение настройките на frame с tkinter
- from tkinter import ttk
- from tkinter.ttk import Treeview, Combobox
- from tkinter.ttk import Style
- from Opiti.from_excel.classes.global_inc import registry
- from json_file_io import JsonFileIo
- class AccCalculator(Tk):
- def __init__(self):
- super().__init__()
- self.check_assets = IntVar()
- self.check_amort = IntVar()
- self.sel = int()
- self.last_code_entry = None
- self.last_amount_entry = None
- self.entry_asset_prd_amount = IntVar()
- self.acc_data = {}
- self.scr_bar = None
- self.account = None
- self.calc_text = None
- self.btn_plus = None
- self.btn_min = None
- # self.sel_acc = { # Данни за избора на юзъра
- # 'code': None, # Код на сметката, която юзъра е избрал от treeview-то
- # 'key': None, # Какво юзъра е избрал в combobox-а (едно от "close_d", "turn_d" и т.н.)
- # 'value': None, # Какво юзъра е избрал в combobox-а (стойността на избраното)
- # }
- self.sel_acc_code = None # Код на сметката, която юзъра е избрал от treeview-то
- self.sel_acc_key = None # Какво юзъра е избрал в combobox-а (едно от "close_d", "turn_d" и т.н.)
- self.sel_acc_human = None # Какво юзъра е избрал в combobox-а (едно от "close_d", "turn_d" и т.н.)
- self.sel_acc_value: None # Какво юзъра е избрал в combobox-а (стойността на избраното)
- self.account_key_options = [
- { "key": "open_d", "prefix": "Н.Салдо Дт:" },
- { "key": "open_c", "prefix": "Н.Салдо Кт:" },
- { "key": "turn_d", "prefix": "Оборот Дт:" },
- { "key": "turn_c", "prefix": "Оборот Кт:" },
- { "key": "close_d", "prefix": "К.Салдо Дт:" },
- { "key": "close_c", "prefix": "К.Салдо Кт:" },
- ]
- self.chain = []
- # Create Label
- def label_n(self, geo, text_l, x, y, p=None, w=15, color='black', bg_color=None, bg_border=None, j=None):
- border_colour = Frame(geo, background=bg_border)
- border_colour.pack(padx=40, pady=40)
- border_colour.place(x=x, y=y)
- label = Label(border_colour, text=text_l, font=('Times New Roman', 10, 'italic'), bg=bg_color,
- padx=5, pady=5, bd=-1, width=w, anchor=p, fg=color, justify=j)
- label.pack(padx=0, pady=(0, 1))
- #
- #
- # # Create Entry
- def entry_n(self, geo, x, y, w):
- entry = Entry(geo, bd=4, width=w)
- entry.place(x=x, y=y)
- return entry
- def find_acc_data(self, acc_code):
- for i in range(0, len(self.acc_data)):
- #if isinstance(self.acc_data[i]['code'], str) or isinstance(self.acc_data[i]['code'], num):
- #print(f"acc_data[{i}][code]: {self.acc_data[i]['code']}")
- if self.acc_data[i]['code'] is not None:
- if str(acc_code) == self.acc_data[i]['code']:
- return self.acc_data[i]
- return None
- def on_selected_acc(self, source_treeview):
- #self.account['values'] = []
- current_item = source_treeview.focus()
- values = source_treeview.item(current_item)["values"]
- if not isinstance(values, list):
- #print("values не е списък")
- return
- code = values[0]
- acc_data = self.find_acc_data(code)
- print("code", code, "acc_data", acc_data)
- self.account.delete('0', END)
- self.account.insert('0', code) #NEW
- self.sel_acc_code = code
- # self.account['values'] = [f"Н.Салдо Дт: {acc_data['open_d']}",
- # f"Н.Салдо Кт: {acc_data['open_c']}",
- # f"Оборот Дт: {acc_data['turn_d']}",
- # f"Оборот Кт: {acc_data['turn_c']}",
- # f"К.Салдо Дт: {acc_data['close_d']}",
- # f"К.Салдо Кт: {acc_data['close_c']}"]
- option_values = []
- for acc_key_option in self.account_key_options:
- prefix = acc_key_option['prefix']
- key = acc_key_option['key']
- value = acc_data[key]
- option_values.append(f"{prefix} {value}")
- self.account['values'] = option_values
- # Да се извика когато юзъра избере от combobox-а стойност от сметката
- def on_selected_acc_key(self):
- #print("self.account.get()", self.account.get(), "self.account.current()", self.account.current())
- idx = self.account.current()
- option = self.account_key_options[idx]
- print("idx", idx, "opt", option)
- self.sel_acc_key = option["key"]
- self.sel_acc_human = self.account.get()
- acc_data = self.find_acc_data(self.sel_acc_code)
- self.sel_acc_value = acc_data[self.sel_acc_key]
- #print("self.sel_acc", self.sel_acc)
- #self.chain.append(self.sel_acc)
- #print("self.chain", self.chain)
- self.btn_plus.config(state=NORMAL)
- self.btn_min.config(state=NORMAL)
- def on_selected_operator(self, operator, btn):
- if btn["state"] == "disabled":
- return
- if operator in ["+", "-"]:
- self.chain.append({
- "code": self.sel_acc_code,
- "key": self.sel_acc_key,
- "value": self.sel_acc_value,
- "human": self.sel_acc_human,
- })
- self.chain.append(operator)
- print("self.chain", self.chain)
- self.show_result()
- def show_result(self):
- self.calc_text.delete('1.0', END)
- result = 0
- #isFirst = True
- operator = "+"
- text = ""
- for node in self.chain:
- if isinstance(node, dict): # Брънката е речник
- text += f"{operator} "
- text += node["human"]
- text += "\n"
- if operator == "+":
- result += node["value"]
- elif operator == "-":
- result -= node["value"]
- else: # Брънката е стринг +/-
- operator = node
- #isFirst = False
- text += '----------------\n'
- text += '=' + str(result)
- self.calc_text.insert(INSERT, text)
- def on_entry_key_release(self, entry, target_treeview, amount_entry):
- self.last_code_entry = entry
- self.last_amount_entry = amount_entry
- entry_text = entry.get()
- if len(entry_text) < 2:
- print("Няма достатъчно знаци:", entry_text)
- return
- term = entry_text
- print("Има поне два знака:", term)
- # TODO Намираме записите дето почват с t
- self.found_rows_all_data = []
- found_rows = []
- term_len = len(term)
- for i in range(0, len(self.acc_data)):
- if isinstance(self.acc_data[i]['code'], str):
- code_piece = self.acc_data[i]['code'][0:term_len]
- if term == code_piece:
- found_rows.append([
- self.acc_data[i]['code'],
- self.acc_data[i]['name'],
- self.acc_data[i]['close_c'],
- ])
- target_treeview.delete(*target_treeview.get_children())
- count_rows = len(found_rows)
- target_treeview.config(height=count_rows)
- i = 0
- for found_row in found_rows:
- print("В treeview добавяме ред", found_row)
- target_treeview.insert('', END, values=found_row, tags=['t']) # ????
- target_treeview.tag_configure('t', background='SystemButtonFace')
- i += 1
- if i > 12:
- target_treeview.configure(height=13)
- def acc_choice(self):
- pass
- def calculator(self):
- json_file_io = JsonFileIo(file_name=registry["trial_balance_file_name"])
- self.acc_data = json_file_io.read_content()
- self.title('Калкулатор')
- self.geometry('1060x480+200+150') #1060
- self.resizable(False, False)
- self.attributes('-topmost', 'true')
- # #Активи label_n(geo, text_l, x, y, p=None, w=15, color='black', bg_color=None, bg_border=None) w- ширина, р - подравняване
- self.label_n(self, 'СМЕТКА:', 20, 20, 'w', 8, 'black', bg_color=None, bg_border='red')
- self.label_n(self, 'Налични сметки:', 560, 20, 'w', 20, 'black', bg_color=None, bg_border='red')
- self.entry_assets_prd = self.entry_n(self, 20, 60, 5)
- # TODO COMBObox
- acc_option = StringVar()
- self.account = Combobox(self, textvariable=acc_option, width=22)
- self.account.place(x=70, y=60)
- self.account.bind('<<ComboboxSelected>>', lambda event: self.on_selected_acc_key())
- self.account['state'] = 'normal'
- #account.insert('0', "с/ка 409")
- #account.bind('<<ComboboxSelected>>', lambda: acc_choice(self))
- #self.entry_asset_prd_amount = self.entry_n(self, 420, 100, 14)
- self.entry_assets_prd.bind("<KeyRelease>", lambda e: self.on_entry_key_release(self.entry_assets_prd,
- self.treeview_acc, self.entry_asset_prd_amount))
- self.tv_frame = Frame(self)
- self.tv_frame.place(x=560, y=60)
- # TODO TREEVIEW
- cols = ("code", "acc_name", "close_ap")
- self.treeview_acc = Treeview(self.tv_frame, columns=cols, show='headings', height=0)
- self.treeview_acc.heading('# 1', text='код', anchor='w')
- self.treeview_acc.heading('# 2', text='сметка', anchor='w')
- self.treeview_acc.heading('# 3', text='салдо', anchor='center')
- # treeview_acc.configure(background='SystemButtonFace') # 'systemWindowBody'
- style = Style(self) # #D3D3D3, 'default', 'alt', 'clam', #40E0D0
- style.theme_use('default')
- print("style.theme_use() AAA", style.theme_use())
- style.configure('Treeview',
- background='lightgrey',
- foreground='black',
- rowheight=25,
- fieldbackground='red'
- )
- # Change selected color
- style.map('Treeview', background=[('selected', 'blue')])
- # TODO Scroll_bar
- self.scr_bar = Scrollbar(self.tv_frame, orient=VERTICAL)
- self.scr_bar.pack(side=RIGHT, fill=Y)
- self.treeview_acc.config(yscrollcommand=self.scr_bar.set)
- self.scr_bar.config(command=self.treeview_acc.yview, bg="red", activebackground="orange")
- self.treeview_acc.column("code", width=60, anchor='w')
- self.treeview_acc.column("acc_name", width=300, anchor='w')
- self.treeview_acc.column("close_ap", width=100, anchor='e')
- self.treeview_acc.bind('<ButtonRelease-1>', lambda e: self.on_selected_acc(self.treeview_acc))
- #self.treeview_acc.place(x=560, y=60)
- self.treeview_acc.pack(side=LEFT)
- # TODO TEXT field
- self.calc_text = Text(self, width=40, height=21, bg='grey71', fg='#fff', font=('Sans Serif', 10, 'italic bold'))
- # Insert text
- self.calc_text.insert(INSERT, "Write Something\nAbout Yourself")
- # Position
- self.calc_text.place(x=240, y=60)
- # Button cancel
- butt_note = Button(self, text='Назад', font=('Bookman Old Style Bold', 8), fg='brown', height=1, width=7)
- butt_note.place(x=20, y=240)
- butt_note.bind('<ButtonRelease-1>')
- # Button COPY
- butt_note = Button(self, text='Копирай', font=('Bookman Old Style Bold', 8), fg='blue', height=1, width=7)
- butt_note.place(x=20, y=280)
- butt_note.bind('<ButtonRelease-1>')
- # Button Изчисти
- butt_note = Button(self, text='Изчисти', font=('Bookman Old Style Bold', 8), fg='red', height=1, width=7)
- butt_note.place(x=20, y=320)
- butt_note.bind('<ButtonRelease-1>')
- # Button +
- self.btn_plus = Button(self, text='+', font=('Bookman Old Style Bold', 8), fg='blue', height=1, width=7, state=DISABLED)
- self.btn_plus.place(x=100, y=240)
- self.btn_plus.bind('<ButtonRelease-1>', lambda e: self.on_selected_operator("+", self.btn_plus))
- # Button -
- self.btn_min = Button(self, text='-', font=('Bookman Old Style Bold', 8), fg='red', height=1, width=7, state=DISABLED)
- self.btn_min.place(x=100, y=280)
- self.btn_min.bind('<ButtonRelease-1>', lambda e: self.on_selected_operator("-", self.btn_min))
- # Button =
- butt_note = Button(self, text='=', font=('Bookman Old Style Bold', 8), fg='black', height=1, width=7)
- butt_note.place(x=100, y=320)
- butt_note.bind('<ButtonRelease-1>')
- # Button Помощ
- butt_help = Button(self, text='Помощ', font=('Bookman Old Style Bold', 8), fg='black', height=1, width=10)
- butt_help.place(x=20, y=430)
- butt_help.bind('<ButtonRelease-1>')
- # Button OK
- butt_ok = Button(self, text='OK', font=('Bookman Old Style Bold', 8), fg='green', height=1, width=10)
- butt_ok.place(x=830, y=430)
- butt_ok.bind('<ButtonRelease-1>')
- # Button Отказ
- butt_exit = Button(self, text='ОТКАЗ', font=('Bookman Old Style Bold', 8), fg='red', height=1, width=10,
- command=self.destroy)
- butt_exit.place(x=930, y=430)
- self.mainloop()
- if __name__ == '__main__':
- calc = AccCalculator()
- calc.calculator()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement