python-simpletables 0.1.26__tar.gz → 0.1.28__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python_simpletables
3
- Version: 0.1.26
3
+ Version: 0.1.28
4
4
  Summary: Simple connection between SQL and tkinter.
5
5
  Author-email: Захар Васильев <vasilyev.zakhar@gmail.com>
6
6
  License: MIT
7
+ Requires-Dist: pandas
@@ -4,10 +4,13 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "python_simpletables"
7
- version = "0.1.26"
7
+ version = "0.1.28"
8
8
  description = "Simple connection between SQL and tkinter."
9
9
  authors = [{name = "Захар Васильев", email = "vasilyev.zakhar@gmail.com"}]
10
10
  license = {text = "MIT"}
11
-
11
+ dependencies = [
12
+ "pandas"
13
+ ]
14
+
12
15
  [tool.setuptools.packages.find]
13
16
  where = ["."]
@@ -0,0 +1,5 @@
1
+ from .table import Table,Field
2
+
3
+
4
+
5
+ #
@@ -0,0 +1,64 @@
1
+ import os,os.path as op,re,json,sqlite3,tkinter as tk,atexit
2
+ from tkinter import ttk
3
+ from . import Table,Field
4
+
5
+ def showid(table,field,value):
6
+ return str(value).rjust(5,"0")
7
+ def showbool(table,field,value):
8
+ return "Да" if value else "Нет"
9
+ class ExampleApp(tk.Tk):
10
+ def __init__(self,database_path):
11
+ conn = sqlite3.connect(database_path)
12
+ with open(op.join(op.dirname(__file__),"__main__.sql"),"r",encoding="utf8") as script:
13
+ for cmd in script.read().split(";"):
14
+ cmd=cmd.strip()
15
+ try: conn.execute(cmd) if cmd else None
16
+ except: print(repr(cmd))
17
+ super().__init__()
18
+ self.geometry("800x560")
19
+ self.minsize(400,300)
20
+ conn = sqlite3.connect(database_path)
21
+ tabs = tk.Frame(self)
22
+ tabs.pack(side="top",fill="x")
23
+ box = tk.Frame(self)
24
+ box.pack(side="top",fill="both",expand=True)
25
+ self.all_tables=[]
26
+ self.all_buttons={}
27
+ selector = lambda name: lambda: self.select_table(name)
28
+ for name,title,fields,primary in [
29
+ ("Customers","Заказчики",[
30
+ Field("id","ID",show=showid),
31
+ Field("name","ФИО / Организация"),
32
+ Field("inn","ИНН"),
33
+ Field("addres","Адрес"),
34
+ Field("phone","Телефон"),
35
+ Field("salesman","Продавец?",show=showbool),
36
+ Field("buyer","Покупатель?",show=showbool),
37
+ ],"id"),
38
+ ("Goods","Товары",[
39
+ Field("id","ID",show=showid),
40
+ Field("name","Наименование",multiply=2.5),
41
+ Field("price_for_unit","Цена за ед."),
42
+ Field("unit","Ед.изм."),
43
+ ],"id"),
44
+ ]:
45
+ self.all_tables.append(Table(conn,box,name,fields,primary))
46
+ self.all_buttons[name]=tk.Button(tabs,text=title,command=selector(name))
47
+ self.all_buttons[name].pack(side="left")
48
+ self.select_table(self.all_tables[0].name)
49
+ def select_table(self,name):
50
+ res=[t for t in self.all_tables if t.name==name]
51
+ if len(res)!=1: return
52
+ table=res[0]
53
+ for v in self.all_tables:
54
+ v.pack_forget()
55
+ for k,v in self.all_buttons.items():
56
+ v.config(relief="raised")
57
+ self.all_buttons[table.name].config(relief="sunken")
58
+ table.pack(fill="both",expand=True)
59
+ def example_main():
60
+ database=op.join(op.dirname(__file__),"__main__.db")
61
+ ExampleApp(database).mainloop()
62
+
63
+
64
+ if __name__=="__main__": example_main()
@@ -0,0 +1,155 @@
1
+ import tkinter as tk,json
2
+ from tkinter import ttk
3
+ from tkinter import messagebox as mb
4
+ from tkinter import simpledialog as sd
5
+ from tkinter import filedialog as fd
6
+ from dataclasses import dataclass
7
+
8
+ def q(s): return json.dumps(s,ensure_ascii=False)
9
+ @dataclass
10
+ class Field:
11
+ name:str
12
+ title:str
13
+ show:object = str
14
+ width:int = 0
15
+ multiply:float = 1
16
+ is_valid:object = lambda e: True
17
+ class Table(tk.Frame):
18
+ def __init__(self,conn,master,name,fields,primary):
19
+ self.conn = conn
20
+ self.name = name
21
+ self.fields = fields
22
+ self.primary = primary
23
+ super().__init__(master)
24
+ self.buttons = tk.Frame(self)
25
+ self.buttons.pack(side="bottom",fill="x")
26
+ for name,side,cmd in [
27
+ ("Создать","left",self.ui_create),
28
+ ("Изменить","left",self.ui_edit),
29
+ ("Удалить","left",self.ui_delete),
30
+ ("Импорт из JSON","right",self.ui_import_json),
31
+ ("Импорт из Excel","right",self.ui_import_excel),
32
+ ("Экспорт в JSON","right",self.ui_export_json),
33
+ ("Экспорт в Excel","right",self.ui_export_excel),
34
+ ]: tk.Button(self.buttons,text=name,command=cmd).pack(side=side)
35
+ self.tree = ttk.Treeview(self,columns=[f.name for f in self.fields],show="headings")
36
+ self.tree.pack(side="bottom",fill="both",expand=True)
37
+ for field in fields:
38
+ self.tree.column(field.name,width=field.width or int(max(30,len(field.title)*8)*field.multiply))
39
+ self.tree.heading(field.name,text=field.title)
40
+ self.update_values()
41
+ def update_values(self):
42
+ self.tree.delete(*self.tree.get_children())
43
+ for raw in self.conn.execute(f"SELECT * FROM {q(self.name)}").fetchall():
44
+ values = [e.show(self,e,raw[i]) for i,e in enumerate(self.fields)]
45
+ self.tree.insert("","end",values=values)
46
+ def ui_create(self): pass
47
+ def ui_create(self): pass
48
+ def ui_edit(self): pass
49
+ def ui_delete(self): pass
50
+ def ui_import_json(self):
51
+ file = fd.askopenfile(title="Имортировать файл",filetypes=[
52
+ ("JSON-файлы","*.json"),
53
+ ("Все файлы","*"),
54
+ ])
55
+ if file and not self.import_json(file): self.badfile()
56
+ def import_json(self,file):
57
+ with open(file,"r",encoding="utf8") as f:
58
+ data = json.loads(f.read())
59
+ if type(data)!=list: return False
60
+ for e in data:
61
+ if not self.is_valid(e): return False
62
+ self.data_add(data)
63
+ return True
64
+ def badfile(self): mb.showerror("Ошибка импортирования","Файл повреждён или имеет некорректную структуру.")
65
+ def ui_import_excel(self):
66
+ file = fd.askopenfile(title="Имортировать файл",filetypes=[
67
+ ("Таблицы","*.xlsx","*.xls"),
68
+ ("Все файлы","*"),
69
+ ])
70
+ if file and not self.import_excel(file): self.badfile()
71
+ def import_excel(file):
72
+ df=pd.read_excel(file,sheet_name=0)
73
+ started=False
74
+ for i in range(df.shape()[0]):
75
+ row=df.iloc(i)
76
+ if self.is_valid(row):
77
+ started=True
78
+ self.data_add(row)
79
+ elif started: break
80
+ else: pass
81
+ if not started: return False
82
+ return True
83
+ def data_get(self,primary_value,error_ok=False):
84
+ matches = self.conn.execute(f"SELECT * FROM {q(self.name)} WHERE {q(self.primary)} = ?",primary_value).fetchall()
85
+ if len(matches)==0:
86
+ if error_ok: return None
87
+ else: raise KeyError(f"cannot find row with key {primary_value!r}")
88
+ elif len(matches)==1:
89
+ return matches[0]
90
+ else:
91
+ raise RuntimeError("unexpected situation")
92
+ def data_add(self,row):
93
+ if not self.is_valid(row): raise ValueError(f"invalid line: {row!r}")
94
+ row = self.normalize(row)
95
+ actual = self.data_get(self.primary,True)
96
+ if actual==None:
97
+ self.data_create(row)
98
+ self.conn.commit()
99
+ else: self.data_set(row[0],row)
100
+ def data_create(self,row):
101
+ if not self.is_valid(row): raise ValueError(f"invalid line: {row!r}")
102
+ row = self.normalize(row)
103
+ self.conn.execute(f"INSERT INTO {q(self.name)} VALUES ("+",".join('?' for _ in self.fields)+")",row)
104
+ self.conn.commit()
105
+ def data_set(self,key,row):
106
+ if not self.is_valid(row): raise ValueError(f"invalid line: {row!r}")
107
+ row = self.normalize(row)
108
+ self.conn.execute(f"UPDATE {q(self.name)} SET "+", ".join(f"{q(f.name)} = ?" for _ in self.fields)+" WHERE {q(self.primary)} = ?",[*row,key])
109
+ self.conn.commit()
110
+ def data_readall(self):
111
+ return [self.normalize(e) for e in self.conn.execute(f"SELECT * FROM {q(self.name)}").fetchall()]
112
+ def is_valid(self,row):
113
+ if type(row)==dict:
114
+ row = [*row.items()]
115
+ pattern = dict((e.name,e) for e in self.fields)
116
+ while row:
117
+ key,value = row.pop(0)
118
+ field = pattern.get(key,None)
119
+ if field and field.is_valid(value):
120
+ del pattenr[key]
121
+ continue
122
+ else:
123
+ return False
124
+ return len(pattern)==0
125
+ else:
126
+ if len(row)<len(self.fields): return False
127
+ for i in range(len(self.fields)):
128
+ if not self.fields[i].is_valid(row[i]): return False
129
+ return True
130
+ def normalize(self,row):
131
+ if type(row)!=dict:
132
+ new={}
133
+ for i,field in self.fields:
134
+ new[field.name]=row[i]
135
+ return new
136
+ def ui_export_json(self):
137
+ file = fd.asksaveasfilename(title="Имортировать файл",filetypes=[
138
+ ("JSON-файлы","*.json"),
139
+ ("Все файлы","*"),
140
+ ])
141
+ if file: self.export_json(file)
142
+ def export_json(self,file):
143
+ with open(file,"w",encoding="utf8") as f:
144
+ file.write(json.dumps(self.data_readall(),ensure_ascii=False))
145
+
146
+
147
+
148
+
149
+
150
+
151
+
152
+
153
+
154
+
155
+ #
@@ -1,6 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python_simpletables
3
- Version: 0.1.26
3
+ Version: 0.1.28
4
4
  Summary: Simple connection between SQL and tkinter.
5
5
  Author-email: Захар Васильев <vasilyev.zakhar@gmail.com>
6
6
  License: MIT
7
+ Requires-Dist: pandas
@@ -1,9 +1,10 @@
1
1
  pyproject.toml
2
2
  python_simpletables/__init__.py
3
+ python_simpletables/__main__.py
3
4
  python_simpletables/app.py
4
- python_simpletables/example.py
5
5
  python_simpletables/table.py
6
6
  python_simpletables.egg-info/PKG-INFO
7
7
  python_simpletables.egg-info/SOURCES.txt
8
8
  python_simpletables.egg-info/dependency_links.txt
9
+ python_simpletables.egg-info/requires.txt
9
10
  python_simpletables.egg-info/top_level.txt
@@ -1,5 +0,0 @@
1
- from .table import Table
2
- from .example import ExampleApp
3
-
4
-
5
- #
@@ -1,14 +0,0 @@
1
- import os,os.path as op,re,json,sqlite3,tkinter as tk
2
- from tkinter import ttk
3
-
4
-
5
- class ExampleApp(tk.Tk):
6
- def __init__(self,database_path):
7
- super().__init__()
8
- self.geometry("600x480")
9
- conn = sqlite3.connect(database_path)
10
- tabs = tk.Frame(self)
11
- tabs.pack(side="top",fill="x")
12
- box = tk.Frame(self)
13
- box.pack(side="top",fill="both",expand=True)
14
-
@@ -1,53 +0,0 @@
1
- import tkinter as tk,json
2
- from tkinter import ttk
3
-
4
- def q(s): return json.dumps(s,ensure_ascii=False)
5
- class Table(tk.Frame):
6
- def __init__(self,conn,master,name,fields):
7
- super().__init__(master)
8
- tk.Label(self,text=name).pack(side="top",fill="x")
9
- self.tree = ttk.Treeview(self,columns=[f.name for f in self.fields],show="headings")
10
- self.tree.pack(side="top",fill="both",expand=True)
11
- self.buttons = tk.Frame(self)
12
- self.buttons.pack(side="bottom",fill="x")
13
- for name,side,cmd in [
14
- ("Создать","left",self.ui_create),
15
- ("Изменить","left",self.ui_edit),
16
- ("Удалить","left",self.ui_delete),
17
- ("Импорт из JSON","right",self.ui_import_json),
18
- ("Импорт из Excel","right",self.ui_import_excel),
19
- ("Экспорт в JSON","right",self.ui_export_json),
20
- ("Экспорт в Excel","right",self.ui_export_excel),
21
- ]: tk.Button().pack(side=side)
22
- self.update()
23
- def update(self):
24
- conn.execute(f"SELECT * FROM {q(self.name)}")
25
- def ui_create(self): pass
26
- def ui_create(self): pass
27
- def ui_edit(self): pass
28
- def ui_delete(self): pass
29
- def ui_import_json(self): pass
30
- def ui_import_excel(self): pass
31
- def ui_export_json(self): pass
32
- def ui_export_excel(self): pass
33
-
34
- class Example(tk.Tk):
35
- def __init__(self,database_path):
36
- super().__init__()
37
- self.geometry("600x480")
38
- self.conn = sqlite3.connect(database_path)
39
- tabs = tk.Frame(self)
40
- tabs.pack(side="top",fill="x")
41
- box = tk.Frame(self)
42
- box.pack(side="top",fill="both",expand=True)
43
-
44
-
45
-
46
-
47
-
48
-
49
-
50
-
51
-
52
-
53
- #