upload project

newBranch
bettleChen 1 year ago
parent 322a036fc5
commit f0a03788f1

@ -0,0 +1,17 @@
import tkinter.font as tkFont
import tkinter
from tkinter import *
from tkinter import ttk, messagebox
import pymysql
class BaseWindow(Frame):
def __init__(self, master, attr):
super().__init__(master)
self.attr = attr
self.master = master
self.font_style = tkFont.Font(family="Lucida Grande", size=20)
self.button_font = tkFont.Font(family="Lucida Grande", size=10)
self.conn = pymysql.connect(user="root", password="cyh0110", database="SCT", host="127.0.0.1", port=3306)

@ -1,2 +1,171 @@
# StuSystem # 项目编程基本原则
## 文档及代码编辑的注意事项
### 进度汇报
**查文档和编程任务是否符合。**
首先自查一遍文档,每个编程任务是否符合文档上编程任务的要求---请在进度表中标示【自查:符合 或 不符合】是按编程任务不是按X1,X2...
**查命名问题,函数框架,函数名称,和变量名规范**
(2)按我们前两天讨论的,主函数框架、函数关系调用图、函数名称与变量名称规范化等方面回复【已优化完成,未优化完成】
### 主函数框架示例:
```python
# 需要导入的库
import tkinter as tk # UI界面
from tkinter import scrolledtext # 下拉框
from tkinter import END # 下拉框自动下拉到最后一行
import random # 随机数
import time # 应用sleep函数睡眠
import threading # 多线程任务
from pymouse import PyMouse # 模拟鼠标自动点击
import win32gui # 获取扫雷窗口信息
"""
所有的系统库或第三方库,一次性引出,避免因为确少库而导致运行不了。
如果是自写的模块,可以在函数前引出
"""
#方式1--在文件中定义全局变量,加载全局变量定义文件(如果全局变量实在太多)
from setting import * # setting为自定义程序存放的是全局变量导入全局变量
# setting中定义了哪些全局变量及其定义
#方式2--直接定义全局变量(一般多)
GLOBAL ... ... # 常量用大写
###########
'此处说明是放函数定义的地方'
###########
# 主控函数, 将函数定义拷贝到main函数上面将函数调用放在main函数
if __name__ == '__main__':
pass
###########
'此处说明是函数调用的地方'
###########
"""
要求主函数框架单独运行不报错
"""
```
```python
# 文档贴函数提示说明 如下图所示
###########################################################################
# 以func1()[编程章节]==>func2()[编程章节]的方式说明调用当前函数要用的前述函数。
set_random_state()[5.1]==>create_boards()[5.4]==>show_window()[5.4]
```
![img_2.png](img_2.png)
### 根据不同情况不同的贴程序方法
```python
# 情况一
##### 第一次出现init初始化方法需要写全 #####
##### 在类里面增添方法,需要将类名写出,再写方法 #####
X2:
class MineSweeper: # 建立扫雷类
def __init__(self): # 第一次出现init初始化方法需要写全
def f2():
pass
# 情况二
##### 如果函数实在太多,需要标出函数调用关系图,同时将贴合编程要求的程序给出 #####
X3: # f1(), f2(), f3(), f4(), ..., f10() 本段仅给出f4(), 完整的在[位置](可以在文档末尾建立附录)。
Class Class_some
def f4(): 体现核心功能的函数给出。
pass
# 情况三
##### 如果需要在后续编程章节中扩充原有的功能,可以扩写函数,#####
##### 而且不要出现已经出现过的代码,已经出现过的代码用...代指 #####
X4: 【友好阅读性原则;最小重复代码原则;递增式代码表达原则;界面元素处理与业务逻辑完全分开原则】
class MineSweeper: # 扩展扫雷类--在X2基础上进一步定义
# _init_(self), f2(), 一并处理
def _init_(self): #在原函数基础上增加/调整
...
self.par = "example"
def f3():
...
def f4():
...
每个函数不超一页,原则上就是半页。
```
## 项目编程的普遍要求
### GUI界面和数据结构分开
借用前后端分离的架构模式。
GUI界面负责处理用户界面的展示和交互数据结构部分负责处理业务逻辑和数据处理。
将GUI界面负和数据结构分为两个独立的部分各自负责不同的功能和任务。GUI界面通过接口函数与更新和加载数据结构。
### 代码命名规则:
在Python中有一些命名规则和约定被广泛遵循以提高代码的可读性和一致性。
变量和函数名使用小写字母单词之间使用下划线snake_case进行分隔。例如my_variable, calculate_result。
常量使用全大写字母单词之间使用下划线进行分隔。例如MAX_VALUE, PI。
类名使用驼峰命名法CamelCase即首字母大写不使用下划线。例如MyClass, Calculator。
模块名使用小写字母单词之间使用下划线进行分隔。例如my_module, utils。
- 首先是做好程序的优化,即做好程序函数的封装。 每个函数的函数名尽可能符合文档的编程任务及其要求--要让读者看到函数名就能想到编程任务,这样会更易于理解。
- 函数调用关系图的理解是正确的,就是要有一张全局关系图。
- 正确理解X1、X2、X3、X4和X5。通常X1仅是围绕数据结构赋值和界面或者界面元素坐标无关。X2是依据数据结构中的数据做输出通常是仅输出。X3通常可以定义函数或者定义类及其中的函数。X4是在X2基础上做界面交互元素同时将界面交互元素相关的事件/消息绑定X3或X5的函数。X5也是一些函数。这样界面逻辑和业务逻辑是完全分离的。
- 注意自前向后编程是越来越复杂但不要用后面的编程直接替代前面的编程任务中的程序前面是简单的后面是复杂的。例如“Select Sno from Student”,这是前面的编程Select :attr1 from :table1"尽管将attr1赋值成Sno将table1赋值成Student,也能实现前面的语句,但不可用后面的替换前面的。
### 函数调用关系图:
函数调用图Function Call Graph是用于描述程序中函数之间调用关系的图形表示。它展示了函数之间的依赖关系和调用流程帮助我们理解程序的执行流程和函数之间的交互
在函数调用图中,函数被表示为节点,函数之间的调用关系被表示为边。每个函数调用都会生成一个新的节点和一条连接调用者和被调用者的边。函数调用图可以是有向图或无向图,具体取决于函数调用的方向性。
调用图可以用软件生成。
![img.png](img.png)
### 项目文件应包含(后续规范)
项目应该包含以下基本文件:
1. README.md项目的说明文档包含项目的介绍、使用方法、安装指南、贡献指南等重要信息。README.md通常是其他开发者了解和使用项目的入口。
2. LICENSE项目的开源许可证明确了项目的使用条件和权利限制。选择适合项目的开源许可证对于保护项目的权益和推动开源合作非常重要。
3. .gitignoreGit版本控制系统的忽略文件配置用于指定哪些文件或目录应该被忽略不纳入版本控制。通常包括一些编译生成的文件、临时文件、敏感信息等。
4. requirements.txt项目的依赖项清单列出了项目所需的外部库、框架和工具的版本信息。这样其他开发者可以方便地安装相同的依赖项确保项目的可重复性和一致性。
5. setup.py 或者 setup.cfg用于打包和发布项目的配置文件。可以定义项目的元数据、依赖关系、安装过程等以便其他人能够方便地安装和使用项目。
6. docs 目录包含项目的文档例如用户手册、API文档、开发者指南等。良好的文档对于其他开发者和用户理解和使用项目非常重要。
7. tests 目录:包含项目的测试代码和测试数据,用于验证项目的正确性和稳定性。包括单元测试、集成测试等,帮助开发者确保项目的质量和可靠性。
8. src 或者 lib 目录:包含项目的源代码文件。根据项目的规模和结构,可以进一步组织成子目录或包,方便代码的组织和维护。
除了上述基本文件,根据项目的特点和需求,还可以包含其他文件,如配置文件、示例代码、演示视频等。重要的是根据项目的具体情况进行文件的组织和描述,确保项目的可理解性、可维护性和可扩展性。
```bash
# 将输出重定向到文件:
pip freeze > requirements.txt
# 老师一键安装项目所有依赖一般像Pycharm会自动识别这个文件按提示安装即可
pip install -r requirements.txt
```

@ -0,0 +1,52 @@
import pymysql
# 创建mysql连接
conn = pymysql.connect(user="root", password="cyh0110", host="127.0.0.1", port=3306)
def create_database():
cursor = conn.cursor() # 创建游标
cursor.execute("DROP DATABASE IF EXISTS SCT")
# 创建数据库
cursor.execute("CREATE DATABASE SCT CHARACTER SET utf8 COLLATE utf8_general_ci")
cursor.close() # 关闭游标
def create_table():
cursor = conn.cursor() # 创建游标
cursor.execute("USE SCT") # 指定数据库
# 创建student数据表
cursor.execute("""
CREATE TABLE IF NOT EXISTS student
(
sid CHAR(8) PRIMARY KEY,
sname CHAR(10),
ssex CHAR(2),
sage INTEGER,
sclass CHAR(6)
)
""")
# 创建Course数据表
cursor.execute("""
CREATE TABLE IF NOT EXISTS course
(
cid CHAR(4) PRIMARY KEY,
cname CHAR(30),
credit FLOAT(1),
chours INTEGER,
t CHAR(3)
)
""")
# 创建SC数据表
cursor.execute("""
CREATE TABLE IF NOT EXISTS sc
(
sid CHAR(8),
cid CHAR(4),
score FLOAT(1),
CONSTRAINT sc_course_cid_fk
FOREIGN KEY (cid) REFERENCES course (cid),
CONSTRAINT sc_student_sid_fk
FOREIGN KEY (sid) REFERENCES student (sid)
)
""")
cursor.close()
conn.close() # 关闭链接

@ -0,0 +1,90 @@
# encoding: utf8
import time
import pymysql
import random
last_names = "李,王,张,刘,陈,杨,黄,赵,周,吴,徐,孙,朱,马,胡,郭,林,何,高,梁,郑,罗,宋,谢,唐,韩,曹,许,邓,萧,冯,曾,程,蔡,彭,潘,袁,于,董,余,苏,叶,吕,魏,蒋,田,杜,丁,沈,姜,范,江,傅,钟,卢,汪,戴,崔,任,陆,廖,姚,方,金,邱,夏,谭,韦,贾,邹,石,熊,孟,秦,阎,薛,侯,雷,白,龙,段,郝,孔,邵,史,毛,常,万,顾,赖,武,康,贺,严,尹,钱,施,牛,洪,龚"
last_names_list = last_names.split("")
course_names = "语文、数学、外语、历史、思想政治、地理、 化学、物理、生物、体育、美术、音乐、技术、微积分、体育、毛泽东思想概论、思想道德修养、高等数学、线性代数、概率论与数理统计、离散数学、计算机原理、人工智能、程序设计基础、面向对象程序设计、数字逻辑电路、电路电子技术、数据结构与算法、WEB程序设计、计算机组成与结构、操作系统、数据库系统原理、编译原理、计算机网络"
course_names_list = course_names.split("")
# 创建mysql连接
conn = pymysql.connect(user="root", password="cyh0110", database="SCT", host="127.0.0.1", port=3306)
# 创建游标
cursor = conn.cursor()
sid_list = [] # 用于存储生成的sid
cid_list = [] # 用于存储生成的cid
def student_random_record():
"""
# 随机生成10000条学生表数据
:return:
"""
year = time.localtime().tm_year # 获取当前系统时间的年份
num = 1
class_num = 1
class_id = 1
for i in range(10000):
sid = "%d" % year + "%04d" % num
sname = random.choice(last_names_list) + sid
ssex = random.choice(["", ""])
sage = random.randint(15, 35)
sclass = "%d" % year + "%02d" % class_id
sql = f"INSERT INTO student VALUES ('{sid}', '{sname}', '{ssex}', {sage}, '{sclass}')"
cursor.execute(sql)
sid_list.append(sid)
if num == 2500:
year += 1
num = 1
class_id = 1
if class_num == 30:
class_id += 1
class_num = 1
num += 1
class_num += 1
conn.commit()
def course_random_record():
"""
随机生成1000条课程表数据
:return:
"""
hours = [i for i in range(8, 192 + 1, 8)]
for i in range(1000):
cid = "%03d" % (i + 1)
cname = random.choice(course_names_list)
hour = random.choice(hours)
credit = round(hour / 16, 2)
sql = f"INSERT INTO course (cid, cname, credit, chours) VALUES ('{cid}', '{cname}', {credit}, {hour})"
cursor.execute(sql)
cid_list.append(cid)
conn.commit()
def sc_random_record():
"""
随机生成10000 * 30条以上选课表数据
:return:
"""
for sid in sid_list:
year = int(sid[:4]) # 取sid的前四位学年
for i in range((year - time.localtime().tm_year + 1) * 16):
cid = random.choice(cid_list)
score = random.randint(0, 101)
sql = f"INSERT INTO sc(sid, cid, score) VALUES ('{sid}', '{cid}', {score})"
cursor.execute(sql)
conn.commit()
student_random_record()
course_random_record()
sc_random_record()
# 关闭数据库连接
cursor.close()
conn.close()

@ -0,0 +1,31 @@
import pymysql
# 创建mysql连接连接并打开数据库
conn = pymysql.connect(user="root", password="cyh0110", database="SCT", host="127.0.0.1", port=3306)
cursor = conn.cursor() # 游标的定义、打开
# 字符串型SQL语句的执行
SQLString = "INSERT INTO student VALUES ('20230001', '张三', '', 20, '01')"
cursor.execute(SQLString)
SQLString = "INSERT INTO course VALUES ('1001', '数据库', 3, 48, 'T01')"
cursor.execute(SQLString)
SQLString = "INSERT INTO sc VALUES ('20230001', '1001', 85)"
cursor.execute(SQLString)
conn.commit()
def query_data(table_name):
"""
游标数据的读写处理读写游标数据
:param table_name: 表名称
:return: 游标数据
"""
SQLString = f"SELECT * FROM {table_name}"
cursor.execute(SQLString) # 执行查询sql语句
data = cursor.fetchall() # 获取游标中的数据
return data
StudentList = query_data("student")
CourseList = query_data("course")
SCList = query_data("sc")
# 关闭数据库连接
cursor.close()
conn.close()

@ -0,0 +1,183 @@
from tkinter import Frame
import tkinter.font as tkFont
from ttkbootstrap import *
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
import pandas as pd
import pymysql
from ttkbootstrap.tableview import Tableview
from BaseWindow import BaseWindow
def get_text_content(text):
return text.get("0.0", "end").replace("\n", " ")
conn = pymysql.connect(user="root", password="cyh0110", database="SCT", host="127.0.0.1", port=3306)
class LoadElement(Frame):
def __init__(self, master, table_name):
super().__init__(master)
self.master = master
self.table_name = table_name
self.TableList = pd.read_sql(f"select * from {self.table_name} limit 0", conn)
self.font_style = tkFont.Font(family="Lucida Grande", size=20)
self.button_font = tkFont.Font(family="Lucida Grande", size=10)
self.create_widget()
self.create_tree_widget()
def create_widget(self):
# 创建装载按钮
label = Label(self, width=10, font=self.font_style, text=self.table_name, style="inverse-secondary")
label.grid(column=0, row=0)
Button(self, text="装载", width=10, command=self.load).grid(column=1, row=0, padx=5, sticky=NSEW)
def create_tree_widget(self):
frame = Frame(self, width=50, height=220)
frame.grid(row=1, column=0, columnspan=2, sticky=NSEW, pady=5)
frame.grid_columnconfigure(0, weight=1)
frame.grid_rowconfigure(0, weight=1)
columns = self.TableList.keys().tolist()
style = ttk.Style()
style.configure("Custom.Treeview.Heading", font=("宋体", 15))
style.configure("Custom.Treeview", rowheight=30, font=("宋体", 15))
tree = ttk.Treeview(frame, columns=columns, show="headings", style="Custom.Treeview", selectmode=BROWSE)
# 根据dataFrame结构生成表
for i in columns:
tree.heading(column=i, text=i)
for i in columns:
tree.column(i, anchor=CENTER, width=80)
if columns.index(i) == 1 or columns.index(i) == 0:
tree.column(i, anchor=CENTER, width=120)
for row in self.TableList.itertuples():
tree.insert(parent="", index=END, values=[row[i] for i in range(1, len(row))])
y_scrollbar = ttk.Scrollbar(self, orient='vertical', command=tree.yview)
x_scrollbar = ttk.Scrollbar(frame, orient="horizontal", command=tree.xview)
tree.configure(yscrollcommand=y_scrollbar.set)
tree.config(height=6)
tree.grid(row=0, column=0, columnspan=2, sticky=NSEW, pady=5)
y_scrollbar.grid(row=1, column=3, sticky='ns')
x_scrollbar.grid(row=2, column=0, columnspan=2, sticky='ew')
frame.grid_propagate(False)
def load(self):
"""
加载数据
:return:
"""
SQLString = f"select * from {self.table_name}"
# 执行SQL语句 并返回列表数据
self.TableList = pd.read_sql(SQLString, conn)
# 调用X2界面函数将数据展示出来
self.create_tree_widget()
class FormElement(Frame):
def __init__(self, master):
super().__init__(master)
self.master = master
self.data = []
self.conn = pymysql.connect(user="root", password="cyh0110", database="SCT", host="127.0.0.1", port=3306)
self.font_style = tkFont.Font(family="Lucida Grande", size=20)
self.button_font = tkFont.Font(family="Lucida Grande", size=10)
self.default_query_sql = "select * from student"
self.create_form()
self.create_treeview(pd.read_sql(self.default_query_sql, con=self.conn))
def create_form(self):
# 创建表单区域
self.sql_text = Text(self, width=75, height=4, font=self.font_style)
self.sql_text.grid(row=0, column=0, rowspan=2)
Button(self, text="\n\n执行SQL\n\n", command=self.execute_sql, width=7, style=INFO, compound=TOP).grid(column=1, row=0, rowspan=2, padx=10)
self.sql_text.insert(1.0, self.default_query_sql)
def execute_sql(self):
"""
执行sql方法
:return:
"""
# 获取text组件中用户输入的值
sql = get_text_content(self.sql_text).lower().strip()
print(sql)
def create_treeview(self, data_frame):
"""
创建数据列表展示组件
:param data_frame:
:return:
"""
frame = Frame(self, height=700)
frame.grid(row=10, column=0, columnspan=10, rowspan=5, sticky=NSEW)
frame.grid_columnconfigure(0, weight=1)
frame.grid_rowconfigure(0, weight=1)
columns = data_frame.keys().tolist()
tree = ttk.Treeview(frame, columns=columns, show="headings", style="mystyle.Treeview", height=50,
selectmode=BROWSE)
style = ttk.Style()
style.configure("Treeview.Heading", font=self.font_style)
style.configure("Treeview", rowheight=30, font=self.font_style, borderwidth=1)
# 根据dataFrame结构生成表
for i in columns:
tree.heading(column=i, text=i)
for i in columns:
tree.column(i, anchor=CENTER, minwidth=100, width=100)
for row in data_frame.itertuples():
tree.insert(parent="", index=END, values=[row[i] for i in range(1, len(row))])
tree.grid(row=0, column=0, sticky=NSEW, pady=10)
y_scrollbar = ttk.Scrollbar(frame, orient='vertical', command=tree.yview)
tree.configure(yscrollcommand=y_scrollbar.set)
y_scrollbar.grid(row=0, column=1, sticky='ns')
frame.grid_propagate(False)
class StuSys_X2(BaseWindow):
def __init__(self, master, attr):
super().__init__(master, attr)
self.create_left_plate()
self.create_right_plate()
def create_left_plate(self):
# 创建左侧装载区域的组件
self.left_frame = Frame(self.master, height=self.attr["height"])
self.left_frame.pack(side=LEFT, anchor=NW, pady=10, padx=10)
load_element1 = LoadElement(self.left_frame, "student")
load_element1.pack(side=TOP, pady=10)
load_element2 = LoadElement(self.left_frame, "course")
load_element2.pack(side=TOP, pady=10)
load_element2 = LoadElement(self.left_frame, "sc")
load_element2.pack(side=TOP, pady=10)
def create_right_plate(self):
# 创建右侧表单以及数据展示的组件
self.right_frame = Frame(self.master, height=self.attr["height"])
self.right_frame.pack(side=LEFT, anchor=NW, pady=10, padx=10)
form_element = FormElement(self.right_frame)
form_element.pack(side=TOP, pady=10, anchor=NE)
if __name__ == '__main__':
"""
minty, lumen, sandstone, yeti, pulse, united, morph, journal, darkly, superhero, solar
cyborg, vapor, simplex, cerculean,
"""
style = "morph"
root = Window(themename=style)
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
root.columnconfigure(0, weight=1)
root.rowconfigure(1, weight=1)
root_attr = {
"width": screenwidth * 0.83,
"height": screenheight * 0.85,
}
alignstr = '%dx%d+%d+%d' % (root_attr['width'], root_attr['height'], (screenwidth - root_attr['width']) / 2,
(screenheight - root_attr['height']) / 2)
root.geometry(alignstr)
root.resizable(width=False, height=False)
app = StuSys_X2(root, root_attr)
ttk.Style().configure("TButton", font="-size 18")
root.mainloop()

@ -0,0 +1,129 @@
from tkinter import Frame
import tkinter.font as tkFont
from ttkbootstrap import *
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
import pandas as pd
import pymysql
from ttkbootstrap.toast import ToastNotification
from BaseWindow import BaseWindow
from X2.StuSys_X2_bootstrap import LoadElement
def get_text_content(text):
return text.get("0.0", "end").replace("\n", " ")
class FormElement(Frame):
def __init__(self, master):
super().__init__(master)
self.master = master
self.data = []
self.conn = pymysql.connect(user="root", password="cyh0110", database="SCT", host="127.0.0.1", port=3306)
self.font_style = tkFont.Font(family="Lucida Grande", size=20)
self.button_font = tkFont.Font(family="Lucida Grande", size=10)
self.default_query_sql = "select * from student"
self.create_form()
self.create_treeview(pd.read_sql(self.default_query_sql, con=self.conn))
def create_form(self):
# 创建表单区域
self.sql_text = Text(self, width=75, height=6, font=self.font_style)
self.sql_text.grid(row=0, column=0, rowspan=2)
Button(self, text="\n\n执行SQL\n\n", command=self.execute_sql, width=8,
).grid(column=1, row=0, rowspan=2, padx=10)
self.sql_text.insert(1.0, self.default_query_sql)
def sql_query(self, SQLString):
SQLResultList = pd.read_sql(SQLString, self.conn)
return SQLResultList
def execute_sql(self):
# 执行sql并将sql执行后查询的数据展示
sql = get_text_content(self.sql_text).lower().strip()
if sql.startswith("select"):
data_frame = self.sql_query(sql)
self.create_treeview(data_frame)
ToastNotification(message="语句执行成功",
title="提示",
duration=1500,
position=(int(self.winfo_screenwidth() / 2) - 150, 80, "ne"),
bootstyle="success",
icon="").show_toast()
def create_treeview(self, data_frame):
frame = Frame(self, height=700)
frame.grid(row=10, column=0, columnspan=10, rowspan=5, sticky=NSEW)
frame.grid_columnconfigure(0, weight=1)
frame.grid_rowconfigure(0, weight=1)
columns = data_frame.keys().tolist()
tree = ttk.Treeview(frame, columns=columns, show="headings", style="mystyle.Treeview", height=50,
selectmode=BROWSE)
style = ttk.Style()
style.configure("Treeview.Heading", font=self.font_style)
style.configure("Treeview", rowheight=30, font=self.font_style, borderwidth=1)
# 根据dataFrame结构生成表
for i in columns:
tree.heading(column=i, text=i)
for i in columns:
tree.column(i, anchor=CENTER, minwidth=100, width=100)
for row in data_frame.itertuples():
tree.insert(parent="", index=END, values=[row[i] for i in range(1, len(row))])
tree.grid(row=0, column=0, sticky=NSEW, pady=10)
y_scrollbar = ttk.Scrollbar(frame, orient='vertical', command=tree.yview)
tree.configure(yscrollcommand=y_scrollbar.set)
y_scrollbar.grid(row=0, column=1, sticky='ns')
frame.grid_propagate(False)
class StuSys_X3(BaseWindow):
def __init__(self, master, attr):
super().__init__(master, attr)
self.create_left_plate()
self.create_right_plate()
def create_left_plate(self):
self.left_frame = Frame(self.master, height=self.attr["height"])
self.left_frame.pack(side=LEFT, anchor=NW, pady=10, padx=10)
load_element1 = LoadElement(self.left_frame, "student")
load_element1.pack(side=TOP, pady=10)
load_element2 = LoadElement(self.left_frame, "course")
load_element2.pack(side=TOP, pady=10)
load_element2 = LoadElement(self.left_frame, "sc")
load_element2.pack(side=TOP, pady=10)
def create_right_plate(self):
self.right_frame = Frame(self.master, height=self.attr["height"])
self.right_frame.pack(side=LEFT, anchor=NW, pady=10, padx=10)
form_element = FormElement(self.right_frame)
form_element.pack(side=TOP, pady=10, anchor=NE)
if __name__ == '__main__':
"""
minty, lumen, sandstone, yeti, pulse, united, morph, journal, darkly, superhero, solar
cyborg, vapor, simplex, cerculean,
"""
style = "morph"
root = Window(themename=style)
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
root.columnconfigure(0, weight=1)
root.rowconfigure(1, weight=1)
root_attr = {
"width": screenwidth * 0.83,
"height": screenheight * 0.85,
}
alignstr = '%dx%d+%d+%d' % (root_attr['width'], root_attr['height'], (screenwidth - root_attr['width']) / 2,
(screenheight - root_attr['height']) / 2)
root.geometry(alignstr)
root.resizable(width=False, height=False)
app = StuSys_X3(root, root_attr)
ttk.Style().configure("TButton", font="-size 18")
root.mainloop()

@ -0,0 +1,197 @@
from tkinter import Frame
import tkinter.font as tkFont
from ttkbootstrap import *
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
import pandas as pd
import pymysql
from ttkbootstrap.toast import ToastNotification
from BaseWindow import BaseWindow
from X2.StuSys_X2_bootstrap import LoadElement
def get_text_content(text):
return text.get("0.0", "end").replace("\n", " ")
class FormElement(Frame):
def __init__(self, master):
super().__init__(master)
self.master = master
self.data = []
self.conn = pymysql.connect(user="root", password="cyh0110", database="SCT", host="127.0.0.1", port=3306)
self.font_style = tkFont.Font(family="Lucida Grande", size=20)
self.button_font = tkFont.Font(family="Lucida Grande", size=10)
self.default_query_sql = "select * from student"
self.create_form()
self.create_treeview(pd.read_sql(self.default_query_sql, con=self.conn))
def create_form(self):
"""
创建表单
:return:
"""
self.sid_var = IntVar()
self.sname_var = IntVar()
self.sclass_var = IntVar()
self.ssex_var = IntVar()
self.sage_var = IntVar()
Label(self, text="学号", font=self.font_style).grid(row=0, column=0, sticky=W)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.sid_var).grid(row=0, column=1, sticky=W)
self.sid = Entry(self, width=20, font=self.font_style)
self.sid.grid(row=0, column=2, sticky=W)
Label(self, text="姓名", font=self.font_style).grid(row=0, column=3, sticky=W)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.sname_var).grid(row=0, column=4, sticky=W)
self.sname = Entry(self, width=20, font=self.font_style)
self.sname.grid(row=0, column=5, sticky=W)
Label(self, text="班级", font=self.font_style).grid(row=1, column=0, sticky=W)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.sclass_var).grid(row=1, column=1, sticky=W)
self.sclass = Entry(self, width=20, font=self.font_style)
self.sclass.grid(row=1, column=2, sticky=W)
Label(self, text="性别", font=self.font_style).grid(row=1, column=3, sticky=W)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.ssex_var).grid(row=1, column=4, sticky=W)
self.ssex = Entry(self, width=20, font=self.font_style)
self.ssex.grid(row=1, column=5, sticky=W, pady=10)
Label(self, text="年龄自", font=self.font_style).grid(row=2, column=0, sticky=W)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.sage_var).grid(row=2, column=1, sticky=W)
self.start_age = Entry(self, width=20, font=self.font_style)
self.start_age.grid(row=2, column=2, sticky=W)
Label(self, text="", font=self.font_style).grid(row=2, column=3, sticky=W)
Label(self, text="", font=self.font_style).grid(row=2, column=4, sticky=W)
self.end_age = Entry(self, width=20, font=self.font_style)
self.end_age.grid(row=2, column=5, sticky=W, pady=10)
Button(self, text="\n\n构造SQL\n\n", command=self.make_sql, width=8,
).grid(column=8, row=0, rowspan=3)
self.sql_text = Text(self, height=3, font=self.font_style, width=75)
self.sql_text.grid(row=4, column=0, rowspan=2, columnspan=7, sticky=W)
Button(self, text="\n执行SQL\n", command=self.execute_sql, width=8,
).grid(column=8, row=4, rowspan=2, padx=10)
self.sql_text.insert(1.0, self.default_query_sql)
def execute_sql(self):
sql = get_text_content(self.sql_text).lower().strip()
if sql.startswith("select"):
data_frame = pd.read_sql(sql, con=self.conn)
self.create_treeview(data_frame)
ToastNotification(message="语句执行成功",
title="提示",
duration=1500,
position=(int(self.winfo_screenwidth() / 2) - 150, 80, "ne"),
bootstyle="success",
icon="").show_toast()
def create_treeview(self, data_frame):
frame = Frame(self, height=600)
frame.grid(row=10, column=0, columnspan=10, rowspan=5, sticky=NSEW)
frame.grid_columnconfigure(0, weight=1)
frame.grid_rowconfigure(0, weight=1)
columns = data_frame.keys().tolist()
tree = ttk.Treeview(frame, columns=columns, show="headings", style="mystyle.Treeview", height=50,
selectmode=BROWSE)
style = ttk.Style()
style.configure("Treeview.Heading", font=self.font_style)
style.configure("Treeview", rowheight=30, font=self.font_style, borderwidth=1)
# 根据dataFrame结构生成表
for i in columns:
tree.heading(column=i, text=i)
for i in columns:
tree.column(i, anchor=CENTER, minwidth=100, width=100)
for row in data_frame.itertuples():
tree.insert(parent="", index=END, values=[row[i] for i in range(1, len(row))])
tree.grid(row=0, column=0, sticky=NSEW, pady=10)
y_scrollbar = ttk.Scrollbar(frame, orient='vertical', command=tree.yview)
tree.configure(yscrollcommand=y_scrollbar.set)
y_scrollbar.grid(row=0, column=1, sticky='ns')
frame.grid_propagate(False)
def make_sql(self):
"""
获取用户输入进行条件判断进行SQLString的构造
:return:
"""
# 根据表单条件生成sql语句
SQLString = "select * from student where 1=1"
if self.sid.get() != "":
SQLString += f" and (sid like '{self.sid.get()}')"
if self.sname.get() != "":
SQLString += f" and (sname like '{self.sname.get()}')"
if self.sclass.get() != "":
SQLString += f" and (sclass like '{self.sclass.get()}')"
if self.ssex.get() != "":
SQLString += f" and (ssex like '{self.ssex.get()}')"
if self.start_age.get() != "":
SQLString += f" and (sage > '{self.start_age.get()}')"
if self.end_age.get() != "":
SQLString += f" and (sage < '{self.end_age.get()}')"
if SQLString == "select * from student where 1=1":
SQLString = "select * from student"
SQLString = SQLString.replace("1=1 and", "")
if (self.sid_var and self.ssex_var and self.sage_var and self.sclass_var and self.sname_var == 0):
pass
else:
data = []
data.append("sid")if self.sid_var.get() == 1 else ""
data.append("sname")if self.sname_var.get() == 1 else ""
data.append("ssex")if self.ssex_var.get() == 1 else ""
data.append("sage")if self.sage_var.get() == 1 else ""
data.append("sclass")if self.sclass_var.get() == 1 else ""
SQLString = SQLString.replace("select *", f"select {', '.join(data)} ")
self.sql_text.delete(0.0, END)
self.sql_text.insert(1.0, SQLString)
class StuSys_X4(BaseWindow):
def __init__(self, master, attr):
super().__init__(master, attr)
self.create_left_plate()
self.create_right_plate()
def create_left_plate(self):
self.left_frame = Frame(self.master, height=self.attr["height"])
self.left_frame.pack(side=LEFT, anchor=NW, pady=10, padx=10)
load_element1 = LoadElement(self.left_frame, "student")
load_element1.pack(side=TOP, pady=10)
load_element2 = LoadElement(self.left_frame, "course")
load_element2.pack(side=TOP, pady=10)
load_element2 = LoadElement(self.left_frame, "sc")
load_element2.pack(side=TOP, pady=10)
def create_right_plate(self):
self.right_frame = Frame(self.master, height=self.attr["height"])
self.right_frame.pack(side=LEFT, anchor=NW, pady=10, padx=10, fill=BOTH)
form_element = FormElement(self.right_frame)
form_element.pack(side=TOP, pady=10, anchor=NE, fill=BOTH)
if __name__ == '__main__':
"""
minty, lumen, sandstone, yeti, pulse, united, morph, journal, darkly, superhero, solar
cyborg, vapor, simplex, cerculean,
"""
style = "morph"
root = Window(themename=style)
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
root.columnconfigure(0, weight=1)
root.rowconfigure(1, weight=1)
root_attr = {
"width": screenwidth * 0.83,
"height": screenheight * 0.85,
}
alignstr = '%dx%d+%d+%d' % (root_attr['width'], root_attr['height'], (screenwidth - root_attr['width']) / 2,
(screenheight - root_attr['height']) / 2)
root.geometry(alignstr)
root.resizable(width=False, height=False)
app = StuSys_X4(root, root_attr)
ttk.Style().configure("TButton", font="-size 18")
root.mainloop()

@ -0,0 +1,242 @@
from tkinter import Frame
import tkinter.font as tkFont
from ttkbootstrap import *
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
import pandas as pd
import pymysql
from ttkbootstrap.toast import ToastNotification
from BaseWindow import BaseWindow
from X2.StuSys_X2_bootstrap import LoadElement
def get_text_content(text):
return text.get("0.0", "end").replace("\n", " ")
class FormElement(Frame):
def __init__(self, master):
super().__init__(master)
self.master = master
self.data = []
self.conn = pymysql.connect(user="root", password="cyh0110", database="SCT", host="127.0.0.1", port=3306)
self.font_style = tkFont.Font(family="Lucida Grande", size=20)
self.button_font = tkFont.Font(family="Lucida Grande", size=10)
self.default_query_sql = "select * from student"
self.create_form()
self.create_treeview(pd.read_sql(self.default_query_sql, con=self.conn))
def create_form(self):
self.sid_var = IntVar()
self.sname_var = IntVar()
self.sclass_var = IntVar()
self.ssex_var = IntVar()
self.sage_var = IntVar()
self.score_var = IntVar()
self.courseId_var = IntVar()
self.cname_var = IntVar()
self.credit_var = IntVar()
self.chours_var = IntVar()
Label(self, text="学生/student", font=("Lucida Grande", 20), style="inverse").grid(row=0, column=0, sticky=W)
Label(self, text="学号", font=self.font_style).grid(row=1, column=0, sticky=E)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.sid_var).grid(row=1, column=1, sticky=W)
self.sid = Entry(self, width=20, font=self.font_style)
self.sid.grid(row=1, column=2, sticky=W)
Label(self, text="姓名", font=self.font_style).grid(row=1, column=3, sticky=E)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.sname_var).grid(row=1, column=4, sticky=W)
self.sname = Entry(self, width=20, font=self.font_style)
self.sname.grid(row=1, column=5, sticky=W)
Label(self, text="班级", font=self.font_style).grid(row=2, column=0, sticky=E)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.sclass_var).grid(row=2, column=1, sticky=W)
self.sclass = Entry(self, width=20, font=self.font_style)
self.sclass.grid(row=2, column=2, sticky=W)
Label(self, text="性别", font=self.font_style).grid(row=2, column=3, sticky=E)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.ssex_var).grid(row=2, column=4, sticky=W)
self.ssex = Entry(self, width=20, font=self.font_style)
self.ssex.grid(row=2, column=5, sticky=W, pady=10)
Label(self, text="年龄自", font=self.font_style).grid(row=3, column=0, sticky=E)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.sage_var).grid(row=3, column=1, sticky=W)
self.start_age = Entry(self, width=20, font=self.font_style)
self.start_age.grid(row=3, column=2, sticky=W)
Label(self, text="", font=self.font_style).grid(row=3, column=3, sticky=E)
Label(self, text="", font=self.font_style).grid(row=3, column=4, sticky=W)
self.end_age = Entry(self, width=20, font=self.font_style)
self.end_age.grid(row=3, column=5, sticky=W, pady=10)
Label(self, text="课程/course", font=("Lucida Grande", 20), style="inverse").grid(row=4, column=0, sticky=W)
Label(self, text="课号", font=self.font_style).grid(row=5, column=0, sticky=E)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.courseId_var).grid(row=5, column=1, sticky=W)
self.course_id = Entry(self, width=20, font=self.font_style)
self.course_id.grid(row=5, column=2, sticky=W)
Label(self, text="课名", font=self.font_style).grid(row=5, column=3, sticky=E)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.cname_var).grid(row=5, column=4, sticky=W)
self.course_name = Entry(self, width=20, font=self.font_style)
self.course_name.grid(row=5, column=5, sticky=W, pady=10)
Label(self, text="选课/sc", font=("Lucida Grande", 20), style="inverse").grid(row=6, column=0, sticky=W)
Label(self, text="成绩大于", font=self.font_style).grid(row=7, column=0, sticky=E)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.score_var).grid(row=7, column=1, sticky=W)
self.sc_start = Entry(self, width=20, font=self.font_style)
self.sc_start.grid(row=7, column=2, sticky=W)
Label(self, text="小于", font=self.font_style).grid(row=7, column=3, sticky=E)
Label(self, text="", font=self.font_style).grid(row=7, column=4, sticky=W)
self.sc_end = Entry(self, width=20, font=self.font_style)
self.sc_end.grid(row=7, column=5, sticky=W, pady=10)
Button(self, text="\n\n构造SQL\n\n", command=self.make_sql, width=8,
).grid(column=8, row=0, rowspan=8)
self.sql_text = Text(self, height=3, font=self.font_style, width=75)
self.sql_text.grid(row=8, column=0, rowspan=2, columnspan=7, sticky=W)
Button(self, text="\n执行SQL\n", command=self.execute_sql, width=8,
).grid(column=8, row=8, rowspan=2, padx=10)
self.sql_text.insert(1.0, self.default_query_sql)
def execute_sql(self):
sql = get_text_content(self.sql_text).lower().strip()
if sql.startswith("select"):
data_frame = pd.read_sql(sql, con=self.conn)
self.create_treeview(data_frame)
ToastNotification(message="语句执行成功",
title="提示",
duration=1500,
position=(int(self.winfo_screenwidth() / 2) - 150, 80, "ne"),
bootstyle="success",
icon="").show_toast()
def create_treeview(self, data_frame):
frame = Frame(self, height=400)
frame.grid(row=10, column=0, columnspan=10, rowspan=5, sticky=NSEW)
frame.grid_columnconfigure(0, weight=1)
frame.grid_rowconfigure(0, weight=1)
columns = data_frame.keys().tolist()
tree = ttk.Treeview(frame, columns=columns, show="headings", style="mystyle.Treeview", height=50,
selectmode=BROWSE)
style = ttk.Style()
style.configure("Treeview.Heading", font=self.font_style)
style.configure("Treeview", rowheight=30, font=self.font_style, borderwidth=1)
# 根据dataFrame结构生成表
for i in columns:
tree.heading(column=i, text=i)
for i in columns:
tree.column(i, anchor=CENTER, minwidth=100, width=100)
for row in data_frame.itertuples():
tree.insert(parent="", index=END, values=[row[i] for i in range(1, len(row))])
tree.grid(row=0, column=0, sticky=NSEW, pady=10)
y_scrollbar = ttk.Scrollbar(frame, orient='vertical', command=tree.yview)
tree.configure(yscrollcommand=y_scrollbar.set)
y_scrollbar.grid(row=0, column=1, sticky='ns')
frame.grid_propagate(False)
def make_sql(self):
sql = "select * from student where 1=1"
if self.course_id and self.course_name and self.sc_start and self.sc_end != "":
sql = "select * from student s join sc on sc.sid=s.sid join course c on c.cid=sc.cid"
if self.sid.get() != "":
sql += f" and (s.sid like '{self.sid.get()}')"
if self.sname.get() != "":
sql += f" and (s.sname like '{self.sname.get()}')"
if self.sclass.get() != "":
sql += f" and (s.sclass like '{self.sclass.get()}')"
if self.ssex.get() != "":
sql += f" and (s.ssex like '{self.ssex.get()}')"
if self.start_age.get() != "":
sql += f" and (s.sage > '{self.start_age.get()}')"
if self.end_age.get() != "":
sql += f" and (s.sage < '{self.end_age.get()}')"
if self.course_id.get() != "":
sql += f" and (c.cid like '{self.course_id.get()}')"
if self.course_name.get() != "":
sql += f" and (c.cname like '{self.course_name.get()}')"
if self.sc_start.get() != "":
sql += f" and (sc.score > {self.sc_start.get()})"
if self.sc_end.get() != "":
sql += f" and (sc.score < {self.sc_end.get()})"
else:
if self.sid.get() != "":
sql += f" and (sid like '{self.sid.get()}')"
if self.sname.get() != "":
sql += f" and (sname like '{self.sname.get()}')"
if self.sclass.get() != "":
sql += f" and (sclass like '{self.sclass.get()}')"
if self.start_age.get() != "":
sql += f" and (sage > '{self.start_age.get()}')"
if self.end_age.get() != "":
sql += f" and (sage < '{self.end_age.get()}')"
if sql == "select * from student where 1=1":
sql = "select * from student"
if (self.sid_var and self.ssex_var and self.sage_var and self.sclass_var and self.sname_var and self.score_var and self.cname_var and self.credit_var and self.chours_var == 0):
pass
else:
data = []
data.append("s.sid")if self.sid_var.get() == 1 else ""
data.append("s.sname")if self.sname_var.get() == 1 else ""
data.append("s.ssex")if self.ssex_var.get() == 1 else ""
data.append("s.sage")if self.sage_var.get() == 1 else ""
data.append("s.sclass")if self.sclass_var.get() == 1 else ""
data.append("sc.score")if self.score_var.get() == 1 else ""
data.append("c.cid")if self.courseId_var.get() == 1 else ""
data.append("c.cname")if self.cname_var.get() == 1 else ""
data.append("c.credit")if self.credit_var.get() == 1 else ""
data.append("c.chours")if self.chours_var.get() == 1 else ""
sql = sql.replace("select *", f"select {', '.join(data)} ")
sql = sql.replace("1=1 and", "")
self.sql_text.delete(0.0, END)
self.sql_text.insert(1.0, sql)
class StuSys_X4(BaseWindow):
def __init__(self, master, attr):
super().__init__(master, attr)
self.create_left_plate()
self.create_right_plate()
def create_left_plate(self):
self.left_frame = Frame(self.master, height=self.attr["height"])
self.left_frame.pack(side=LEFT, anchor=NW, pady=10, padx=10)
load_element1 = LoadElement(self.left_frame, "student")
load_element1.pack(side=TOP, pady=10)
load_element2 = LoadElement(self.left_frame, "course")
load_element2.pack(side=TOP, pady=10)
load_element2 = LoadElement(self.left_frame, "sc")
load_element2.pack(side=TOP, pady=10)
def create_right_plate(self):
self.right_frame = Frame(self.master, height=self.attr["height"])
self.right_frame.pack(side=LEFT, anchor=NW, pady=10, padx=10)
form_element = FormElement(self.right_frame)
form_element.pack(side=TOP, pady=10, anchor=NE)
if __name__ == '__main__':
"""
minty, lumen, sandstone, yeti, pulse, united, morph, journal, darkly, superhero, solar
cyborg, vapor, simplex, cerculean,
"""
style = "morph"
root = Window(themename=style)
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
root.columnconfigure(0, weight=1)
root.rowconfigure(1, weight=1)
root_attr = {
"width": screenwidth * 0.83,
"height": screenheight * 0.85,
}
alignstr = '%dx%d+%d+%d' % (root_attr['width'], root_attr['height'], (screenwidth - root_attr['width']) / 2,
(screenheight - root_attr['height']) / 2)
root.geometry(alignstr)
root.resizable(width=False, height=False)
app = StuSys_X4(root, root_attr)
ttk.Style().configure("TButton", font="-size 18")
root.mainloop()

@ -0,0 +1,301 @@
from tkinter import Frame
import tkinter.font as tkFont
from ttkbootstrap import *
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
import pandas as pd
import pymysql
from ttkbootstrap.toast import ToastNotification
from BaseWindow import BaseWindow
def get_text_content(text):
return text.get("0.0", "end").replace("\n", " ")
class LoadElement(Frame):
def __init__(self, master, table_name):
super().__init__(master)
self.master = master
self.table_name = table_name
self.data = []
self.conn = pymysql.connect(user="root", password="cyh0110", database="SCT", host="127.0.0.1", port=3306)
self.data_frame = pd.read_sql(f"select * from {self.table_name} limit 0", self.conn)
self.font_style = tkFont.Font(family="Lucida Grande", size=20)
self.button_font = tkFont.Font(family="Lucida Grande", size=10)
self.create_widget()
self.select_value(None)
self.create_tree_widget()
def select_value(self, event):
self.table_name = self.select_stringVar.get()
def create_widget(self):
data_frame = pd.read_sql("show tables", self.conn)
tables = [i[0] for i in data_frame.values.tolist()]
style = ttk.Style()
self.select_stringVar = StringVar()
self.select_stringVar.set(self.table_name)
combo = ttk.Combobox(self, width=10, textvariable=self.select_stringVar,font=self.font_style, style="TCombobox")
combo["values"] = tables
combo.bind('<<ComboboxSelected>>', self.select_value)
combo.grid(column=0, row=0)
Button(self, text="装载", width=10, command=self.load).grid(column=1, row=0, padx=5)
def create_tree_widget(self):
frame = Frame(self, width=50, height=220)
frame.grid(row=1, column=0, columnspan=2, sticky=NSEW, pady=5)
frame.grid_columnconfigure(0, weight=1)
frame.grid_rowconfigure(0, weight=1)
columns = self.data_frame.keys().tolist()
style = ttk.Style()
style.configure("Custom.Treeview.Heading", font=("宋体", 15))
style.configure("Custom.Treeview", rowheight=30, font=("宋体", 15))
tree = ttk.Treeview(frame, columns=columns, show="headings", style="Custom.Treeview", selectmode=BROWSE)
# 根据dataFrame结构生成表
for i in columns:
tree.heading(column=i, text=i)
for i in columns:
tree.column(i, anchor=CENTER, width=80)
if columns.index(i) == 1 or columns.index(i) == 0:
tree.column(i, anchor=CENTER, width=120)
for row in self.data_frame.itertuples():
tree.insert(parent="", index=END, values=[row[i] for i in range(1, len(row))])
y_scrollbar = ttk.Scrollbar(self, orient='vertical', command=tree.yview)
x_scrollbar = ttk.Scrollbar(frame, orient="horizontal", command=tree.xview)
tree.configure(yscrollcommand=y_scrollbar.set)
tree.config(height=6)
tree.grid(row=0, column=0, columnspan=2, sticky=NSEW, pady=5)
y_scrollbar.grid(row=1, column=3, sticky='ns')
x_scrollbar.grid(row=2, column=0, columnspan=2, sticky='ew')
frame.grid_propagate(False)
def load(self):
# 加载数据
self.data_frame = pd.read_sql(f"select * from {self.table_name}", self.conn)
self.create_tree_widget()
class FormElement(Frame):
def __init__(self, master):
super().__init__(master)
self.master = master
self.data = []
self.conn = pymysql.connect(user="root", password="cyh0110", database="SCT", host="127.0.0.1", port=3306)
self.font_style = tkFont.Font(family="Lucida Grande", size=20)
self.button_font = tkFont.Font(family="Lucida Grande", size=10)
self.default_query_sql = "select * from student"
self.create_form()
self.create_treeview(pd.read_sql(self.default_query_sql, con=self.conn))
def create_form(self):
self.sid_var = IntVar()
self.sname_var = IntVar()
self.sclass_var = IntVar()
self.ssex_var = IntVar()
self.sage_var = IntVar()
self.score_var = IntVar()
self.courseId_var = IntVar()
self.cname_var = IntVar()
self.credit_var = IntVar()
self.chours_var = IntVar()
Label(self, text="学生/student", font=("Lucida Grande", 20), style="inverse").grid(row=0, column=0, sticky=W)
Label(self, text="学号", font=self.font_style).grid(row=1, column=0, sticky=E)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.sid_var).grid(row=1, column=1, sticky=W)
self.sid = Entry(self, width=20, font=self.font_style)
self.sid.grid(row=1, column=2, sticky=W)
Label(self, text="姓名", font=self.font_style).grid(row=1, column=3, sticky=E)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.sname_var).grid(row=1, column=4, sticky=W)
self.sname = Entry(self, width=20, font=self.font_style)
self.sname.grid(row=1, column=5, sticky=W)
Label(self, text="班级", font=self.font_style).grid(row=2, column=0, sticky=E)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.sclass_var).grid(row=2, column=1, sticky=W)
self.sclass = Entry(self, width=20, font=self.font_style)
self.sclass.grid(row=2, column=2, sticky=W)
Label(self, text="性别", font=self.font_style).grid(row=2, column=3, sticky=E)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.ssex_var).grid(row=2, column=4, sticky=W)
self.ssex = Entry(self, width=20, font=self.font_style)
self.ssex.grid(row=2, column=5, sticky=W, pady=10)
Label(self, text="年龄自", font=self.font_style).grid(row=3, column=0, sticky=E)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.sage_var).grid(row=3, column=1, sticky=W)
self.start_age = Entry(self, width=20, font=self.font_style)
self.start_age.grid(row=3, column=2, sticky=W)
Label(self, text="", font=self.font_style).grid(row=3, column=3, sticky=E)
Label(self, text="", font=self.font_style).grid(row=3, column=4, sticky=W)
self.end_age = Entry(self, width=20, font=self.font_style)
self.end_age.grid(row=3, column=5, sticky=W, pady=10)
Label(self, text="课程/course", font=("Lucida Grande", 20), style="inverse").grid(row=4, column=0, sticky=W)
Label(self, text="课号", font=self.font_style).grid(row=5, column=0, sticky=E)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.courseId_var).grid(row=5, column=1, sticky=W)
self.course_id = Entry(self, width=20, font=self.font_style)
self.course_id.grid(row=5, column=2, sticky=W)
Label(self, text="课名", font=self.font_style).grid(row=5, column=3, sticky=E)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.cname_var).grid(row=5, column=4, sticky=W)
self.course_name = Entry(self, width=20, font=self.font_style)
self.course_name.grid(row=5, column=5, sticky=W, pady=10)
Label(self, text="选课/sc", font=("Lucida Grande", 20), style="inverse").grid(row=6, column=0, sticky=W)
Label(self, text="成绩大于", font=self.font_style).grid(row=7, column=0, sticky=E)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.score_var).grid(row=7, column=1, sticky=W)
self.sc_start = Entry(self, width=20, font=self.font_style)
self.sc_start.grid(row=7, column=2, sticky=W)
Label(self, text="小于", font=self.font_style).grid(row=7, column=3, sticky=E)
Label(self, text="", font=self.font_style).grid(row=7, column=4, sticky=W)
self.sc_end = Entry(self, width=20, font=self.font_style)
self.sc_end.grid(row=7, column=5, sticky=W, pady=10)
Button(self, text="\n\n构造SQL\n\n", command=self.make_sql, width=8,
).grid(column=8, row=0, rowspan=8)
self.sql_text = Text(self, height=3, font=self.font_style, width=75)
self.sql_text.grid(row=8, column=0, rowspan=2, columnspan=7, sticky=W)
Button(self, text="\n执行SQL\n", command=self.execute_sql, width=8,
).grid(column=8, row=8, rowspan=2, padx=10)
self.sql_text.insert(1.0, self.default_query_sql)
def execute_sql(self):
sql = get_text_content(self.sql_text).lower().strip()
if sql.startswith("select"):
data_frame = pd.read_sql(sql, con=self.conn)
self.create_treeview(data_frame)
ToastNotification(message="语句执行成功",
title="提示",
duration=1500,
position=(int(self.winfo_screenwidth() / 2) - 150, 80, "ne"),
bootstyle="success",
icon="").show_toast()
def create_treeview(self, data_frame):
frame = Frame(self, height=400)
frame.grid(row=10, column=0, columnspan=10, rowspan=5, sticky=NSEW)
frame.grid_columnconfigure(0, weight=1)
frame.grid_rowconfigure(0, weight=1)
columns = data_frame.keys().tolist()
tree = ttk.Treeview(frame, columns=columns, show="headings", style="mystyle.Treeview", height=50,
selectmode=BROWSE)
style = ttk.Style()
style.configure("Treeview.Heading", font=self.font_style)
style.configure("Treeview", rowheight=30, font=self.font_style, borderwidth=1)
# 根据dataFrame结构生成表
for i in columns:
tree.heading(column=i, text=i)
for i in columns:
tree.column(i, anchor=CENTER, minwidth=100, width=100)
for row in data_frame.itertuples():
tree.insert(parent="", index=END, values=[row[i] for i in range(1, len(row))])
tree.grid(row=0, column=0, sticky=NSEW, pady=10)
y_scrollbar = ttk.Scrollbar(frame, orient='vertical', command=tree.yview)
tree.configure(yscrollcommand=y_scrollbar.set)
y_scrollbar.grid(row=0, column=1, sticky='ns')
frame.grid_propagate(False)
def make_sql(self):
sql = "select * from student where 1=1"
if self.course_id and self.course_name and self.sc_start and self.sc_end != "":
sql = "select * from student s join sc on sc.sid=s.sid join course c on c.cid=sc.cid"
if self.sid.get() != "":
sql += f" and (s.sid like '{self.sid.get()}')"
if self.sname.get() != "":
sql += f" and (s.sname like '{self.sname.get()}')"
if self.sclass.get() != "":
sql += f" and (s.sclass like '{self.sclass.get()}')"
if self.ssex.get() != "":
sql += f" and (s.ssex like '{self.ssex.get()}')"
if self.start_age.get() != "":
sql += f" and (s.sage > '{self.start_age.get()}')"
if self.end_age.get() != "":
sql += f" and (s.sage < '{self.end_age.get()}')"
if self.course_id.get() != "":
sql += f" and (c.cid like '{self.course_id.get()}')"
if self.course_name.get() != "":
sql += f" and (c.cname like '{self.course_name.get()}')"
if self.sc_start.get() != "":
sql += f" and (sc.score > {self.sc_start.get()})"
if self.sc_end.get() != "":
sql += f" and (sc.score < {self.sc_end.get()})"
else:
if self.sid.get() != "":
sql += f" and (sid like '{self.sid.get()}')"
if self.sname.get() != "":
sql += f" and (sname like '{self.sname.get()}')"
if self.sclass.get() != "":
sql += f" and (sclass like '{self.sclass.get()}')"
if self.start_age.get() != "":
sql += f" and (sage > '{self.start_age.get()}')"
if self.end_age.get() != "":
sql += f" and (sage < '{self.end_age.get()}')"
if sql == "select * from student where 1=1":
sql = "select * from student"
if (self.sid_var and self.ssex_var and self.sage_var and self.sclass_var and self.sname_var and self.score_var and self.cname_var and self.credit_var and self.chours_var == 0):
pass
else:
data = []
data.append("s.sid")if self.sid_var.get() == 1 else ""
data.append("s.sname")if self.sname_var.get() == 1 else ""
data.append("s.ssex")if self.ssex_var.get() == 1 else ""
data.append("s.sage")if self.sage_var.get() == 1 else ""
data.append("s.sclass")if self.sclass_var.get() == 1 else ""
data.append("sc.score")if self.score_var.get() == 1 else ""
data.append("c.cid")if self.courseId_var.get() == 1 else ""
data.append("c.cname")if self.cname_var.get() == 1 else ""
data.append("c.credit")if self.credit_var.get() == 1 else ""
data.append("c.chours")if self.chours_var.get() == 1 else ""
sql = sql.replace("select *", f"select {', '.join(data)} ")
sql = sql.replace("1=1 and", "")
self.sql_text.delete(0.0, END)
self.sql_text.insert(1.0, sql)
class StuSys_X4(BaseWindow):
def __init__(self, master, attr):
super().__init__(master, attr)
self.create_left_plate()
self.create_right_plate()
def create_left_plate(self):
self.left_frame = Frame(self.master, height=self.attr["height"])
self.left_frame.pack(side=LEFT, anchor=NW, pady=10, padx=10)
load_element1 = LoadElement(self.left_frame, "student")
load_element1.pack(side=TOP, pady=10)
load_element2 = LoadElement(self.left_frame, "course")
load_element2.pack(side=TOP, pady=10)
load_element2 = LoadElement(self.left_frame, "sc")
load_element2.pack(side=TOP, pady=10)
def create_right_plate(self):
self.right_frame = Frame(self.master, height=self.attr["height"])
self.right_frame.pack(side=LEFT, anchor=NW, pady=10, padx=10)
form_element = FormElement(self.right_frame)
form_element.pack(side=TOP, pady=10, anchor=NE)
if __name__ == '__main__':
"""
minty, lumen, sandstone, yeti, pulse, united, morph, journal, darkly, superhero, solar
cyborg, vapor, simplex, cerculean,
"""
style = "morph"
root = Window(themename=style)
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
root.columnconfigure(0, weight=1)
root.rowconfigure(1, weight=1)
root_attr = {
"width": screenwidth * 0.83,
"height": screenheight * 0.85,
}
alignstr = '%dx%d+%d+%d' % (root_attr['width'], root_attr['height'], (screenwidth - root_attr['width']) / 2,
(screenheight - root_attr['height']) / 2)
root.geometry(alignstr)
root.resizable(width=False, height=False)
app = StuSys_X4(root, root_attr)
ttk.Style().configure("TButton", font="-size 18")
root.mainloop()

@ -0,0 +1,315 @@
from tkinter import Frame, messagebox
import tkinter.font as tkFont
from pandas import DataFrame
from ttkbootstrap import *
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
import pandas as pd
import pymysql
from ttkbootstrap.toast import ToastNotification
from BaseWindow import BaseWindow
def get_text_content(text):
return text.get("0.0", "end").replace("\n", " ")
class LoadElement(Frame):
def __init__(self, master, table_name):
super().__init__(master)
self.master = master
self.table_name = table_name
self.data = []
self.conn = pymysql.connect(user="root", password="cyh0110", database="SCT", host="127.0.0.1", port=3306)
self.data_frame = pd.read_sql(f"select * from {self.table_name} limit 0", self.conn)
self.font_style = tkFont.Font(family="Lucida Grande", size=20)
self.button_font = tkFont.Font(family="Lucida Grande", size=10)
self.create_widget()
self.select_value(None)
self.create_tree_widget()
def select_value(self, event):
self.table_name = self.select_stringVar.get()
def get_table(self) -> DataFrame:
TableList = pd.read_sql("show tables", self.conn)
return TableList
def create_widget(self):
data_frame = self.get_table()
tables = [i[0] for i in data_frame.values.tolist()]
style = ttk.Style()
# 设置字体和字体大小
style.configure('TCombobox', font=('Arial', 100))
self.select_stringVar = StringVar()
self.select_stringVar.set(self.table_name)
self.combo = ttk.Combobox(self, width=10, height=1, textvariable=self.select_stringVar, font=self.font_style, style="TCombobox")
self.combo["values"] = tables
self.combo.bind('<<ComboboxSelected>>', self.select_value)
self.combo.grid(column=0, row=0)
Button(self, text="装载", width=10, command=self.load).grid(column=1, row=0, padx=5)
def create_tree_widget(self):
frame = Frame(self, width=50, height=220)
frame.grid(row=1, column=0, columnspan=2, sticky=NSEW, pady=5)
frame.grid_columnconfigure(0, weight=1)
frame.grid_rowconfigure(0, weight=1)
columns = self.data_frame.keys().tolist()
style = ttk.Style()
style.configure("Custom.Treeview.Heading", font=("宋体", 15))
style.configure("Custom.Treeview", rowheight=30, font=("宋体", 15))
tree = ttk.Treeview(frame, columns=columns, show="headings", style="Custom.Treeview", selectmode=BROWSE)
# 根据dataFrame结构生成表
for i in columns:
tree.heading(column=i, text=i)
for i in columns:
tree.column(i, anchor=CENTER, width=80)
if columns.index(i) == 1 or columns.index(i) == 0:
tree.column(i, anchor=CENTER, width=120)
for row in self.data_frame.itertuples():
tree.insert(parent="", index=END, values=[row[i] for i in range(1, len(row))])
y_scrollbar = ttk.Scrollbar(self, orient='vertical', command=tree.yview)
x_scrollbar = ttk.Scrollbar(frame, orient="horizontal", command=tree.xview)
tree.configure(yscrollcommand=y_scrollbar.set)
tree.config(height=6)
tree.grid(row=0, column=0, columnspan=2, sticky=NSEW, pady=5)
y_scrollbar.grid(row=1, column=3, sticky='ns')
x_scrollbar.grid(row=2, column=0, columnspan=2, sticky='ew')
frame.grid_propagate(False)
def load(self):
# 加载数据
self.data_frame = pd.read_sql(f"select * from {self.table_name}", self.conn)
self.create_tree_widget()
class FormElement(Frame):
def __init__(self, master):
super().__init__(master)
self.master = master
self.data = []
self.conn = pymysql.connect(user="root", password="cyh0110", database="SCT", host="127.0.0.1", port=3306)
self.font_style = tkFont.Font(family="Lucida Grande", size=20)
self.button_font = tkFont.Font(family="Lucida Grande", size=10)
self.default_query_sql = "select * from student"
self.create_form()
self.create_treeview(pd.read_sql(self.default_query_sql, con=self.conn))
def create_form(self):
self.sid_var = IntVar()
self.sname_var = IntVar()
self.sclass_var = IntVar()
self.ssex_var = IntVar()
self.sage_var = IntVar()
self.score_var = IntVar()
self.courseId_var = IntVar()
self.cname_var = IntVar()
self.credit_var = IntVar()
self.chours_var = IntVar()
Label(self, text="学生/student", font=("Lucida Grande", 20), style="inverse").grid(row=0, column=0, sticky=W)
Label(self, text="学号", font=self.font_style).grid(row=1, column=0, sticky=E)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.sid_var).grid(row=1, column=1, sticky=W)
self.sid = Entry(self, width=20, font=self.font_style)
self.sid.grid(row=1, column=2, sticky=W)
Label(self, text="姓名", font=self.font_style).grid(row=1, column=3, sticky=E)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.sname_var).grid(row=1, column=4, sticky=W)
self.sname = Entry(self, width=20, font=self.font_style)
self.sname.grid(row=1, column=5, sticky=W)
Label(self, text="班级", font=self.font_style).grid(row=2, column=0, sticky=E)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.sclass_var).grid(row=2, column=1, sticky=W)
self.sclass = Entry(self, width=20, font=self.font_style)
self.sclass.grid(row=2, column=2, sticky=W)
Label(self, text="性别", font=self.font_style).grid(row=2, column=3, sticky=E)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.ssex_var).grid(row=2, column=4, sticky=W)
self.ssex = Entry(self, width=20, font=self.font_style)
self.ssex.grid(row=2, column=5, sticky=W, pady=10)
Label(self, text="年龄自", font=self.font_style).grid(row=3, column=0, sticky=E)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.sage_var).grid(row=3, column=1, sticky=W)
self.start_age = Entry(self, width=20, font=self.font_style)
self.start_age.grid(row=3, column=2, sticky=W)
Label(self, text="", font=self.font_style).grid(row=3, column=3, sticky=E)
Label(self, text="", font=self.font_style).grid(row=3, column=4, sticky=W)
self.end_age = Entry(self, width=20, font=self.font_style)
self.end_age.grid(row=3, column=5, sticky=W, pady=10)
Label(self, text="课程/course", font=("Lucida Grande", 20), style="inverse").grid(row=4, column=0, sticky=W)
Label(self, text="课号", font=self.font_style).grid(row=5, column=0, sticky=E)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.courseId_var).grid(row=5, column=1, sticky=W)
self.course_id = Entry(self, width=20, font=self.font_style)
self.course_id.grid(row=5, column=2, sticky=W)
Label(self, text="课名", font=self.font_style).grid(row=5, column=3, sticky=E)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.cname_var).grid(row=5, column=4, sticky=W)
self.course_name = Entry(self, width=20, font=self.font_style)
self.course_name.grid(row=5, column=5, sticky=W, pady=10)
Label(self, text="选课/sc", font=("Lucida Grande", 20), style="inverse").grid(row=6, column=0, sticky=W)
Label(self, text="成绩大于", font=self.font_style).grid(row=7, column=0, sticky=E)
Checkbutton(self, onvalue=1, offvalue=0, variable=self.score_var).grid(row=7, column=1, sticky=W)
self.sc_start = Entry(self, width=20, font=self.font_style)
self.sc_start.grid(row=7, column=2, sticky=W)
Label(self, text="小于", font=self.font_style).grid(row=7, column=3, sticky=E)
Label(self, text="", font=self.font_style).grid(row=7, column=4, sticky=W)
self.sc_end = Entry(self, width=20, font=self.font_style)
self.sc_end.grid(row=7, column=5, sticky=W, pady=10)
Button(self, text="\n\n构造SQL\n\n", command=self.make_sql, width=8,
).grid(column=8, row=0, rowspan=8)
self.sql_text = Text(self, height=3, font=self.font_style, width=75)
self.sql_text.grid(row=8, column=0, rowspan=2, columnspan=7, sticky=W)
Button(self, text="\n执行SQL\n", command=self.execute_sql, width=8,
).grid(column=8, row=8, rowspan=2, padx=10)
self.sql_text.insert(1.0, self.default_query_sql)
def execute_sql(self):
cursor = self.conn.cursor()
try:
sql = get_text_content(self.sql_text).lower().strip()
cursor.execute(sql)
if sql.startswith("select"):
data_frame = pd.read_sql(sql, con=self.conn)
self.create_treeview(data_frame)
ToastNotification(message="语句执行成功",
title="提示",
duration=1500,
position=(int(self.winfo_screenwidth() / 2) - 150, 80, "ne"),
bootstyle="success",
icon="").show_toast()
except pymysql.Error as e:
messagebox.showerror(str(e.args[0]), str(e.args[1]))
finally:
cursor.close()
def create_treeview(self, data_frame):
frame = Frame(self, height=400)
frame.grid(row=10, column=0, columnspan=10, rowspan=5, sticky=NSEW)
frame.grid_columnconfigure(0, weight=1)
frame.grid_rowconfigure(0, weight=1)
columns = data_frame.keys().tolist()
tree = ttk.Treeview(frame, columns=columns, show="headings", style="mystyle.Treeview", height=50,
selectmode=BROWSE)
style = ttk.Style()
style.configure("Treeview.Heading", font=self.font_style)
style.configure("Treeview", rowheight=30, font=self.font_style, borderwidth=1)
# 根据dataFrame结构生成表
for i in columns:
tree.heading(column=i, text=i)
for i in columns:
tree.column(i, anchor=CENTER, minwidth=100, width=100)
for row in data_frame.itertuples():
tree.insert(parent="", index=END, values=[row[i] for i in range(1, len(row))])
tree.grid(row=0, column=0, sticky=NSEW, pady=10)
y_scrollbar = ttk.Scrollbar(frame, orient='vertical', command=tree.yview)
tree.configure(yscrollcommand=y_scrollbar.set)
y_scrollbar.grid(row=0, column=1, sticky='ns')
frame.grid_propagate(False)
def make_sql(self):
sql = "select * from student where 1=1"
if self.course_id and self.course_name and self.sc_start and self.sc_end != "":
sql = "select * from student s join sc on sc.sid=s.sid join course c on c.cid=sc.cid"
if self.sid.get() != "":
sql += f" and (s.sid like '{self.sid.get()}')"
if self.sname.get() != "":
sql += f" and (s.sname like '{self.sname.get()}')"
if self.sclass.get() != "":
sql += f" and (s.sclass like '{self.sclass.get()}')"
if self.ssex.get() != "":
sql += f" and (s.ssex like '{self.ssex.get()}')"
if self.start_age.get() != "":
sql += f" and (s.sage > '{self.start_age.get()}')"
if self.end_age.get() != "":
sql += f" and (s.sage < '{self.end_age.get()}')"
if self.course_id.get() != "":
sql += f" and (c.cid like '{self.course_id.get()}')"
if self.course_name.get() != "":
sql += f" and (c.cname like '{self.course_name.get()}')"
if self.sc_start.get() != "":
sql += f" and (sc.score > {self.sc_start.get()})"
if self.sc_end.get() != "":
sql += f" and (sc.score < {self.sc_end.get()})"
else:
if self.sid.get() != "":
sql += f" and (sid like '{self.sid.get()}')"
if self.sname.get() != "":
sql += f" and (sname like '{self.sname.get()}')"
if self.sclass.get() != "":
sql += f" and (sclass like '{self.sclass.get()}')"
if self.start_age.get() != "":
sql += f" and (sage > '{self.start_age.get()}')"
if self.end_age.get() != "":
sql += f" and (sage < '{self.end_age.get()}')"
if sql == "select * from student where 1=1":
sql = "select * from student"
if (self.sid_var and self.ssex_var and self.sage_var and self.sclass_var and self.sname_var and self.score_var and self.cname_var and self.credit_var and self.chours_var == 0):
pass
else:
data = []
data.append("s.sid")if self.sid_var.get() == 1 else ""
data.append("s.sname")if self.sname_var.get() == 1 else ""
data.append("s.ssex")if self.ssex_var.get() == 1 else ""
data.append("s.sage")if self.sage_var.get() == 1 else ""
data.append("s.sclass")if self.sclass_var.get() == 1 else ""
data.append("sc.score")if self.score_var.get() == 1 else ""
data.append("c.cid")if self.courseId_var.get() == 1 else ""
data.append("c.cname")if self.cname_var.get() == 1 else ""
data.append("c.credit")if self.credit_var.get() == 1 else ""
data.append("c.chours")if self.chours_var.get() == 1 else ""
sql = sql.replace("select *", f"select {', '.join(data)} ")
sql = sql.replace("1=1 and", "")
self.sql_text.delete(0.0, END)
self.sql_text.insert(1.0, sql)
class StuSys_X4(BaseWindow):
def __init__(self, master, attr):
super().__init__(master, attr)
self.create_left_plate()
self.create_right_plate()
def create_left_plate(self):
self.left_frame = Frame(self.master, height=self.attr["height"])
self.left_frame.pack(side=LEFT, anchor=NW, pady=10, padx=10)
load_element1 = LoadElement(self.left_frame, "student")
load_element1.pack(side=TOP, pady=10)
load_element2 = LoadElement(self.left_frame, "course")
load_element2.pack(side=TOP, pady=10)
load_element2 = LoadElement(self.left_frame, "sc")
load_element2.pack(side=TOP, pady=10)
def create_right_plate(self):
self.right_frame = Frame(self.master, height=self.attr["height"])
self.right_frame.pack(side=LEFT, anchor=NW, pady=10, padx=10)
form_element = FormElement(self.right_frame)
form_element.pack(side=TOP, pady=10, anchor=NE)
if __name__ == '__main__':
"""
minty, lumen, sandstone, yeti, pulse, united, morph, journal, darkly, superhero, solar
cyborg, vapor, simplex, cerculean,
"""
style = "morph"
root = Window(themename=style)
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
root.columnconfigure(0, weight=1)
root.rowconfigure(1, weight=1)
root_attr = {
"width": screenwidth * 0.83,
"height": screenheight * 0.85,
}
alignstr = '%dx%d+%d+%d' % (root_attr['width'], root_attr['height'], (screenwidth - root_attr['width']) / 2,
(screenheight - root_attr['height']) / 2)
root.geometry(alignstr)
root.resizable(width=False, height=False)
app = StuSys_X4(root, root_attr)
ttk.Style().configure("TButton", font="-size 18")
root.mainloop()

@ -0,0 +1,299 @@
import uuid
from tkinter import messagebox
import tkinter.font as tkFont
from ttkbootstrap import *
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
import pandas as pd
import pymysql
from ttkbootstrap.toast import ToastNotification
from BaseWindow import BaseWindow
def get_text_content(text):
return text.get("0.0", "end").replace("\n", " ")
class LoadElement(Frame):
def __init__(self, master, table_name):
super().__init__(master)
self.master = master
self.table_name = table_name
self.data = []
self.conn = pymysql.connect(user="root", password="cyh0110", database="SCT", host="127.0.0.1", port=3306)
self.data_frame = pd.read_sql(f"select * from {self.table_name} limit 0", self.conn)
self.font_style = tkFont.Font(family="Lucida Grande", size=20)
self.button_font = tkFont.Font(family="Lucida Grande", size=10)
self.create_widget()
self.select_value(None)
self.create_tree_widget()
def select_value(self, event):
self.table_name = self.select_stringVar.get()
def create_widget(self):
data_frame = pd.read_sql("show tables", self.conn)
tables = [i[0] for i in data_frame.values.tolist()]
style = ttk.Style()
# 设置字体和字体大小
style.configure('TCombobox', font=('Arial', 100))
self.select_stringVar = StringVar()
self.select_stringVar.set(self.table_name)
combo = ttk.Combobox(self, width=10, height=1, textvariable=self.select_stringVar, font=self.font_style,
style="TCombobox")
combo["values"] = tables
combo.bind('<<ComboboxSelected>>', self.select_value)
combo.grid(column=0, row=0)
Button(self, text="装载", width=10, command=self.load).grid(column=1, row=0, padx=5)
def create_tree_widget(self):
# 创建画布,用于展示装载后的数据
frame = Frame(self, width=50, height=180)
frame.grid(row=1, column=0, columnspan=2, sticky=NSEW, pady=5)
frame.grid_columnconfigure(0, weight=1)
frame.grid_rowconfigure(0, weight=1)
columns = self.data_frame.keys().tolist()
style = ttk.Style()
style.configure("Custom.Treeview.Heading", font=("宋体", 15))
style.configure("Custom.Treeview", rowheight=30, font=("宋体", 15))
tree = ttk.Treeview(frame, columns=columns, show="headings", style="Custom.Treeview", selectmode=BROWSE)
# 根据dataFrame结构生成表
for i in columns:
tree.heading(column=i, text=i)
for i in columns:
tree.column(i, anchor=CENTER, width=80)
if columns.index(i) == 1 or columns.index(i) == 0:
tree.column(i, anchor=CENTER, width=120)
for row in self.data_frame.itertuples():
tree.insert(parent="", index=END, values=[row[i] for i in range(1, len(row))])
y_scrollbar = ttk.Scrollbar(self, orient='vertical', command=tree.yview)
x_scrollbar = ttk.Scrollbar(frame, orient="horizontal", command=tree.xview)
tree.configure(yscrollcommand=y_scrollbar.set)
tree.config(height=6)
tree.grid(row=0, column=0, columnspan=2, sticky=NSEW, pady=5)
y_scrollbar.grid(row=1, column=3, sticky='ns')
x_scrollbar.grid(row=2, column=0, columnspan=2, sticky='ew')
frame.grid_propagate(False)
def load(self):
# 加载数据
self.data_frame = pd.read_sql(f"select * from {self.table_name}", self.conn)
self.create_tree_widget()
class FormElement(Frame):
def __init__(self, master, node):
super().__init__(master)
self.node = node
self.data = []
self.conn = pymysql.connect(user="root", password="cyh0110", database="SCT", host="127.0.0.1", port=3306)
self.font_style = tkFont.Font(family="Lucida Grande", size=20)
self.button_font = tkFont.Font(family="Lucida Grande", size=10)
self.table_names = []
self.form_content = {}
self.get_table_names()
self.table_name = self.table_names[0]
self.default_query_sql = f"SELECT * FROM {self.table_name}"
self.create_form()
self.select_table(None)
self.create_treeview(pd.read_sql(self.default_query_sql, con=self.conn))
def get_table_names(self):
"""
获取该数据库下所有的表
:return:
"""
data_frame = pd.read_sql("show tables", self.conn)
self.table_names = [i[0] for i in data_frame.values.tolist()]
def select_table(self, event):
"""
当下拉框选择表之后触发该函数并将tableName改为选择的tableName
:param event:
:return:
"""
for value in self.form_content.values():
value[0].grid_forget()
value[2].grid_forget()
value[3].grid_forget()
self.form_content.clear()
self.table_name = self.select_table_name.get()
self.create_form()
self.sql_text.delete(0.0, END)
self.sql_text.insert(1.0, f"SELECT * FROM {self.table_name}")
def get_field_names(self):
"""
获取所有数据表的所有字段
:return: 返回表内的所有字段
"""
data_frame = pd.read_sql(f"desc {self.table_name}", self.conn)
return data_frame["Field"].tolist()
def create_form(self):
"""
创建表单区域根据数据表自动生成表单
:return:
"""
self.select_table_name = StringVar()
self.select_table_name.set(self.table_name)
combo = ttk.Combobox(self, width=10, height=1, textvariable=self.select_table_name, font=self.font_style,
style="TCombobox")
combo["values"] = self.table_names
combo.bind('<<ComboboxSelected>>', self.select_table)
combo.grid(column=0, row=0, sticky=W)
fields = self.get_field_names()
num_fields = len(fields)
num_rows = (num_fields + 1) // 2
for i in range(num_rows):
for j in range(2):
field_idx = i * 2 + j
if field_idx >= num_fields:
break
field_name = fields[field_idx]
label = Label(self, text=field_name, font=self.font_style)
label.grid(row=i + 1, column=j * 2, padx=5, pady=5, sticky=W)
checkbutton_var = IntVar()
checkbutton = Checkbutton(self, text='', variable=checkbutton_var)
checkbutton.grid(row=i + 1, column=j * 2, padx=5, pady=5, sticky=E)
entry = Entry(self, font=self.font_style)
entry.grid(row=i + 1, column=j * 2 + 1, padx=5, pady=5, sticky=W)
self.form_content[field_name] = (entry, checkbutton_var, label, checkbutton)
style = Style()
style.configure("custom.TButton", padding=(10, 40, 10, 40))
Button(self, text="构造SQL", command=self.make_sql, width=8, style="custom.TButton"
).grid(column=8, row=0, rowspan=8)
self.sql_text = Text(self, height=3, font=self.font_style, width=75)
self.sql_text.grid(row=8, column=0, rowspan=2, columnspan=7, sticky=W)
Button(self, text="\n执行SQL\n", command=self.execute_sql, width=8,
).grid(column=8, row=8, rowspan=2, padx=10)
self.sql_text.insert(1.0, self.default_query_sql)
def execute_sql(self):
cursor = self.conn.cursor()
sql = get_text_content(self.sql_text).lower().strip()
try:
cursor.execute(sql)
if sql.startswith("select"):
data_frame = pd.read_sql(sql, con=self.conn)
self.create_treeview(data_frame)
self.node.message.insert(0, f"{sql}执行成功!共查询到{len(data_frame)}条数据-{uuid.uuid4()}-true")
return
self.node.message.insert(0, f"{sql}执行成功!-{uuid.uuid4()}-true")
except pymysql.Error as e:
messagebox.showerror(str(e.args[0]), str(e.args[1]))
self.node.message.insert(0, f"{sql}执行失败!{e}-{uuid.uuid4()}-false")
finally:
cursor.close()
self.node.update_message()
def create_treeview(self, data_frame):
frame = Frame(self, height=580)
frame.grid(row=10, column=0, columnspan=10, rowspan=5, sticky=NSEW, pady=10)
frame.grid_columnconfigure(0, weight=1)
frame.grid_rowconfigure(0, weight=1)
columns = data_frame.keys().tolist()
tree = ttk.Treeview(frame, columns=columns, show="headings", style="mystyle.Treeview", height=50, selectmode=BROWSE)
style = ttk.Style()
style.configure("Treeview.Heading", font=self.font_style)
style.configure("Treeview", rowheight=30, font=self.font_style, borderwidth=1)
# 根据dataFrame结构生成表
for i in columns:
tree.heading(column=i, text=i)
for i in columns:
tree.column(i, anchor=CENTER, minwidth=100, width=100)
for row in data_frame.itertuples():
tree.insert(parent="", index=END, values=[row[i] for i in range(1, len(row))])
tree.grid(row=0, column=0, sticky=NSEW, pady=10)
y_scrollbar = ttk.Scrollbar(frame, orient='vertical', command=tree.yview)
tree.configure(yscrollcommand=y_scrollbar.set)
y_scrollbar.grid(row=0, column=1, sticky='ns')
frame.grid_propagate(False)
def make_sql(self):
sql = f"SELECT * FROM {self.table_name}"
conditions = []
select_fields = []
for field, (entry, checkbox_var, i, j) in self.form_content.items():
if entry.get():
conditions.append("{} like '{}'".format(field, entry.get()))
if checkbox_var.get() == 1:
select_fields.append("{}".format(field))
if conditions:
sql = "SELECT * FROM {} WHERE {}".format(self.table_name, " AND ".join(conditions))
if select_fields:
sql = sql.replace("*", ",".join(select_fields))
self.sql_text.delete(0.0, END)
self.sql_text.insert(1.0, sql)
class StuSys_X4(BaseWindow):
def __init__(self, master, attr):
super().__init__(master, attr)
self.create_left_plate()
self.create_right_plate()
self.message = []
def create_left_plate(self):
self.left_frame = Frame(self.master, height=self.attr["height"])
self.left_frame.pack(side=LEFT, anchor=NW, pady=10, padx=10)
load_element1 = LoadElement(self.left_frame, "student")
load_element1.pack(side=TOP, pady=10)
load_element2 = LoadElement(self.left_frame, "course")
load_element2.pack(side=TOP, pady=10)
load_element2 = LoadElement(self.left_frame, "sc")
load_element2.pack(side=TOP, pady=10)
message_frame = Frame(self.left_frame, width=50, height=180)
message_frame.pack(side=TOP, pady=10, fill=BOTH)
self.canvas = Canvas(message_frame, width=50, height=180, bg="#f0f5fa")
self.canvas.configure(background="#f0f5fa")
y_scrollbar = Scrollbar(message_frame, orient="vertical", command=self.canvas.yview)
x_scrollbar = Scrollbar(message_frame, orient="horizontal", command=self.canvas.xview)
y_scrollbar.pack(side=RIGHT, fill=BOTH)
x_scrollbar.pack(side=BOTTOM, fill=BOTH)
self.canvas.pack(side=TOP, fill=BOTH)
self.canvas.configure(yscrollcommand=y_scrollbar.set)
self.canvas.configure(xscrollcommand=x_scrollbar.set)
def update_message(self):
self.canvas.delete(ALL)
for message in self.message:
index = self.message.index(message)
self.canvas.create_text(0, 20 * index, anchor="nw",
text=message.split("-")[0], font=("", 15), fill="black" if message.split("-")[-1] == "true" else "red")
self.canvas.update()
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
def create_right_plate(self):
self.right_frame = Frame(self.master, height=self.attr["height"])
self.right_frame.pack(side=LEFT, anchor=NW, pady=10, padx=10)
form_element = FormElement(self.right_frame, self)
form_element.pack(side=TOP, pady=10, anchor=NE)
if __name__ == '__main__':
"""
minty, lumen, sandstone, yeti, pulse, united, morph, journal, darkly, superhero, solar
cyborg, vapor, simplex, cerculean,
"""
style = "morph"
root = Window(themename=style)
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
root.columnconfigure(0, weight=1)
root.rowconfigure(1, weight=1)
root_attr = {
"width": screenwidth * 0.83,
"height": screenheight * 0.85,
}
alignstr = '%dx%d+%d+%d' % (root_attr['width'], root_attr['height'], (screenwidth - root_attr['width']) / 2,
(screenheight - root_attr['height']) / 2)
root.geometry(alignstr)
root.resizable(width=False, height=False)
app = StuSys_X4(root, root_attr)
ttk.Style().configure("TButton", font="-size 18")
root.mainloop()

Binary file not shown.

@ -0,0 +1,9 @@
import pandas as pd
import pymysql
conn = pymysql.connect(user="root", password="cyh0110", database="stu_sys", host="127.0.0.1", port=3306)
data_frame = pd.read_sql("select * from student limit 10", conn)
print(data_frame.keys().tolist())
for row in data_frame.itertuples():
print([row[i] for i in range(1, len(row))])

@ -0,0 +1,36 @@
import ttkbootstrap as ttk
from ttkbootstrap.style import StyleBuilderTTK, Style
from ttkbootstrap.tableview import Tableview
from ttkbootstrap.constants import *
app = ttk.Window()
app.geometry("400x300")
colors = app.style.colors
coldata = [
{"text": "LicenseNumber", "stretch": False},
"CompanyName",
{"text": "UserCount", "stretch": False},
]
rowdata = [
('A123', 'IzzyCo', 12),
('A136', 'Kimdee Inc.', 45),
('A158', 'Farmadding Co.', 36)
]
labe = ttk.Labelframe(app, text="fdas")
dt = Tableview(
master=labe,
coldata=coldata,
paginated=True,
bootstyle=PRIMARY,
height=80
)
dt.insert_rows(END, rowdata)
dt.load_table_data()
ttk.Style().configure("TLabelframe", font="-size 18")
labe.pack()
dt.pack(fill=BOTH, expand=YES, padx=10, pady=10)
app.mainloop()
Loading…
Cancel
Save