当前位置:   article > 正文

Python tk 仿excel表格_python tkinter 表格

python tkinter 表格

Python tk 仿excel表格

一、介面。

二,源代码

源代码 0.py

  1. import tkinter as tk
  2. import tkinter.filedialog as fd
  3. import os
  4. import sqlite3
  5. import csv
  6. def creat_database():
  7. # 连接到数据库(如果不存在则会新建)
  8. conn = sqlite3.connect('example.db')
  9. cursor = conn.cursor()
  10. # 创建表格
  11. create_table_query = '''CREATE TABLE my_table (
  12. my_column_0 varchar(50),
  13. my_column_1 varchar(50),
  14. my_column_2 varchar(50),
  15. my_column_3 varchar(50),
  16. my_column_4 varchar(50),
  17. my_column_5 varchar(50),
  18. my_column_6 varchar(50),
  19. my_column_7 varchar(50),
  20. my_column_8 varchar(50),
  21. my_column_9 varchar(50),
  22. my_column_10 varchar(50),
  23. my_column_11 varchar(50),
  24. my_column_12 varchar(50),
  25. my_column_13 varchar(50),
  26. my_column_14 varchar(50),
  27. my_column_15 varchar(50),
  28. my_column_16 varchar(50)
  29. )'''
  30. cursor.execute(create_table_query)
  31. # 提交更改并关闭连接
  32. conn.commit()
  33. conn.close()
  34. def insert_database(rows_num):
  35. # 连接到已有的数据库
  36. conn = sqlite3.connect('example.db')
  37. cursor = conn.cursor()
  38. # 执行插入语句
  39. insert_data_query = f'''INSERT INTO my_table (
  40. my_column_0 ,
  41. my_column_1 ,
  42. my_column_2 ,
  43. my_column_3 ,
  44. my_column_4 ,
  45. my_column_5 ,
  46. my_column_6 ,
  47. my_column_7 ,
  48. my_column_8 ,
  49. my_column_9 ,
  50. my_column_10 ,
  51. my_column_11 ,
  52. my_column_12 ,
  53. my_column_13 ,
  54. my_column_14 ,
  55. my_column_15 ,
  56. my_column_16
  57. ) VALUES ('{rows_num}','','','','','','','','','','','','','','','','')'''
  58. cursor.execute(insert_data_query)
  59. # 提交更改并关闭连接
  60. conn.commit()
  61. conn.close()
  62. def select_database(page):
  63. # 连接到已有的数据库
  64. conn = sqlite3.connect('example.db')
  65. cursor = conn.cursor()
  66. # 执行查询语句
  67. select_data_query = 'SELECT * FROM my_table LIMIT 0,2'
  68. cursor.execute(select_data_query)
  69. result = cursor.fetchall()
  70. # 执行查询语句
  71. select_data_query = f'SELECT * FROM my_table LIMIT {page*45+2},45'
  72. cursor.execute(select_data_query)
  73. result1 = cursor.fetchall()
  74. for row in result1:
  75. result.append(row)
  76. file_show(result)
  77. # 关闭连接
  78. conn.close()
  79. def update_database(row):
  80. if(len(row)<17):
  81. for i in range(17-len(row)):
  82. row.append('')
  83. # 连接到已有的数据库
  84. conn = sqlite3.connect('example.db')
  85. cursor = conn.cursor()
  86. # 执行更新语句
  87. update_data_query = f'''UPDATE my_table SET
  88. my_column_1 = '{row[1]}' ,
  89. my_column_2 = '{row[2]}' ,
  90. my_column_3 = '{row[3]}' ,
  91. my_column_4 = '{row[4]}' ,
  92. my_column_5 = '{row[5]}' ,
  93. my_column_6 = '{row[6]}' ,
  94. my_column_7 = '{row[7]}' ,
  95. my_column_8 = '{row[8]}' ,
  96. my_column_9 = '{row[9]}' ,
  97. my_column_10 = '{row[10]}' ,
  98. my_column_11 = '{row[11]}' ,
  99. my_column_12 = '{row[12]}' ,
  100. my_column_13 = '{row[13]}' ,
  101. my_column_14 = '{row[14]}' ,
  102. my_column_15 = '{row[15]}' ,
  103. my_column_16 = '{row[16]}'
  104. WHERE
  105. my_column_0 = '{row[0]}' '''
  106. cursor.execute(update_data_query)
  107. # 提交更改并关闭连接
  108. conn.commit()
  109. conn.close()
  110. def on_scroll(*args):
  111. pos = scrollbar_v.get()
  112. print(pos)
  113. if args[0]=='scroll':
  114. if args[2]=='units':
  115. first = pos[0] + int(args[1])* 0.01
  116. elif args[2]=='pages':
  117. first = pos[0] + int(args[1])* 0.1
  118. else:
  119. first = 0
  120. elif args[0]=='moveto':
  121. first = float(args[1])
  122. else:
  123. first = 0
  124. print(first)
  125. scrollbar_v.set(first,first + 0.1)
  126. def file_new():
  127. for i in range(1,227):
  128. row=[]
  129. row.append(str(i))
  130. update_database(row)
  131. select_database(0)
  132. root.title('工作簿')
  133. def file_show(str_table):
  134. for x in range(len(str_table)):
  135. for y in range(len(str_table[0])):
  136. table_column=table[x][y]
  137. table_column.delete(0,'end') # 清空
  138. table_column.insert(0,str_table[x][y])#写入
  139. if(x==0):
  140. table_column.config(state='normal')
  141. table_column.delete(0,'end') # 清空
  142. table_column.insert(0,str_table[x][y])#写入
  143. table_column.config(state='disabled')
  144. if(y==0):
  145. table_column.config(state='normal')
  146. table_column.delete(0,'end') # 清空
  147. table_column.insert(0,str_table[x][y])#写入
  148. table_column.config(width=3)
  149. table_column.config(state='disabled')
  150. fname=''
  151. def file_open():
  152. global fname
  153. mydir='D:/'
  154. fname = fd.askopenfilename(title='选择文件',initialdir =mydir,filetypes=[("CSV file", "*.csv;*.CSV")])
  155. if(fname==''):
  156. return
  157. root.title(os.path.basename(fname))
  158. with open(fname, 'r', encoding="gbk",newline='') as file:
  159. reader=csv.reader(file)
  160. column0=1
  161. for row in reader:
  162. rows=[]
  163. rows.append(str(column0))
  164. for i in row:
  165. rows.append(i)
  166. update_database(rows)
  167. column0+=1
  168. select_database(0)
  169. def file_save():
  170. str_table=[]
  171. for x in range(len(table)):
  172. str_table_columns=[]
  173. for y in range(len(table[0])):
  174. str_table_columns.append(table[x][y].get())
  175. str_table.append(str_table_columns)
  176. for row in str_table[1:]:
  177. update_database(row)
  178. # 连接到已有的数据库
  179. conn = sqlite3.connect('example.db')
  180. cursor = conn.cursor()
  181. # 执行查询语句
  182. select_data_query = 'SELECT * FROM my_table'
  183. cursor.execute(select_data_query)
  184. result = cursor.fetchall()
  185. result1=[]
  186. for row in result:
  187. result1.append(row[1:])
  188. # 关闭连接
  189. conn.close()
  190. global fname
  191. if(fname==''):
  192. mydir='D:/'
  193. fname = fd.asksaveasfilename(title='另存为',initialdir =mydir,filetypes=[("CSV file", "*.csv;*.CSV")],defaultextension='.csv')
  194. if(fname==''):
  195. return
  196. with open(fname, 'w',encoding="gbk", newline='') as file:
  197. writer = csv.writer(file)
  198. writer.writerows(result1[1:])
  199. def file_asave():
  200. global fname
  201. fname=''
  202. file_save()
  203. root.title(os.path.basename(fname))
  204. def popup(event):
  205. right_menu.post(event.x_root, event.y_root)# post在指定的位置显示弹出菜单
  206. w=event.widget
  207. #print(w.get())
  208. right_menu.entryconfigure("剪切",command=lambda: w.event_generate("<<Cut>>"))
  209. right_menu.entryconfigure("复制",command=lambda: w.event_generate("<<Copy>>"))
  210. right_menu.entryconfigure("粘贴",command=lambda: w.event_generate("<<Paste>>"))
  211. page=0
  212. #鼠标滚动
  213. def app_mousewheel(event):
  214. global page
  215. if event.delta==120:
  216. #上滚
  217. if(page!=0):
  218. page=page-1
  219. select_database(page)
  220. if event.delta==-120:
  221. #下滚
  222. if(page!=4):
  223. page=page+1
  224. select_database(page)
  225. first_row=['0','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P']
  226. def db_firing():
  227. global first_row
  228. file_path='example.db'
  229. if(os.path.exists(file_path)):
  230. if(os.stat(file_path).st_size==0):
  231. os.remove(file_path)
  232. creat_database()
  233. for i in range(227):
  234. insert_database(i)
  235. update_database(first_row)
  236. else:
  237. creat_database()
  238. for i in range(227):
  239. insert_database(i)
  240. update_database(first_row)
  241. db_firing()
  242. root = tk.Tk()
  243. root.geometry(f'{root.winfo_screenwidth()}x{root.winfo_screenheight()}+0+0')
  244. #创建菜单栏
  245. m=tk.Menu(root)
  246. #定义一个父菜单
  247. file=tk.Menu(m,tearoff=False)
  248. #将上面定义的父菜单命名为File,放在菜单栏中
  249. m.add_cascade(label='文件', menu=file)
  250. #在File中加入下拉菜单,并添加对应命令操作。
  251. #如果点击这些选项, 就会触发相应的功能
  252. file.add_command(label='新建',accelerator='Ctrl+N',command=file_new)
  253. file.add_command(label='打开', accelerator='Ctrl+O',command=file_open)
  254. file.add_command(label='保存', accelerator='Ctrl+S',command=file_save)
  255. file.add_command(label='另存为', accelerator='Ctrl+Shift+S',command=file_asave)
  256. #添加一条分割线
  257. file.add_separator()
  258. file.add_command(label='退出',command=root.quit,accelerator='Ctrl+Q')
  259. edit= tk.Menu(m,tearoff=False)
  260. m.add_cascade(label='编辑', menu=edit)
  261. edit.add_command(label='剪切',accelerator='Ctrl+X')
  262. edit.add_command(label='复制',accelerator='Ctrl+C')
  263. edit.add_command(label='粘贴',accelerator='Ctrl+V')
  264. #二级菜单
  265. s= tk.Menu(file,tearoff=False)
  266. file.add_cascade(label='导入', menu=s)
  267. s.add_command(label="模块")
  268. s.add_command(label="文本文件")
  269. #三级菜单
  270. z=tk.Menu(s,tearoff=False)
  271. s.add_cascade(label='图片',menu=z)
  272. z.add_command(label="gif")
  273. z.add_command(label="jpg")
  274. z.add_command(label="png")
  275. z.add_command(label="bmp")
  276. root.configure(menu=m)
  277. '''创建一个弹出菜单'''
  278. right_menu = tk.Menu(root,tearoff=False,)
  279. right_menu.add_command(label="剪切")
  280. right_menu.add_command(label="复制")
  281. right_menu.add_command(label="粘贴")
  282. table=[]
  283. rows = 47
  284. columns = 17
  285. for x in range(rows):
  286. table_columns=[]
  287. for y in range(columns):
  288. table_column = tk.Entry(root, width=15, fg='blue', font=('Timew New Roman',13,'italic'))
  289. table_column.bind("<Button-3>", popup)
  290. table_column.grid(row=x, column=y)
  291. table_column.insert(0,'')#写入
  292. if(x==0):
  293. table_column.delete(0,'end') # 清空
  294. table_column.insert(0,first_row[y])#写入
  295. table_column.config(state='disabled')
  296. if(y==0):
  297. table_column.delete(0,'end') # 清空
  298. table_column.insert(0,x)#写入
  299. table_column.config(width=3)
  300. table_column.config(state='disabled')
  301. if y in (3,4,10,11,12):
  302. table_column.config(width=7)
  303. table_columns.append(table_column)
  304. table.append(table_columns)
  305. print(len(table))
  306. print(len(table[0]))
  307. '''
  308. tk.Button(root,width=14, fg='red', font=('Timew New Roman',13,'italic'),text='↑').grid(row=rows,column=0)
  309. tk.Button(root,width=14, fg='red', font=('Timew New Roman',13,'italic'),text='↓').grid(row=rows,column=1)
  310. tk.Button(root,width=14, fg='red', font=('Timew New Roman',13,'italic'),text='←').grid(row=rows,column=2)
  311. tk.Button(root,width=14, fg='red', font=('Timew New Roman',13,'italic'),text='→').grid(row=rows,column=3)
  312. tk.Button(root,command=file_new,width=14, fg='red', font=('Timew New Roman',13,'italic'),text='新建').grid(row=rows,column=14)
  313. tk.Button(root,command=file_open,width=14, fg='red', font=('Timew New Roman',13,'italic'),text='打开').grid(row=rows,column=15)
  314. tk.Button(root,command=file_save,width=14, fg='red', font=('Timew New Roman',13,'italic'),text='保存').grid(row=rows,column=16)
  315. '''
  316. scrollbar_v = tk.Scrollbar(root,orient=tk.VERTICAL)
  317. scrollbar_v.grid(row=0, column=columns,rowspan=rows,sticky='nesw')
  318. scrollbar_v.config(command=on_scroll)
  319. root.bind("<MouseWheel>", app_mousewheel)
  320. #root.after(1000,file_new)
  321. root.mainloop()

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号