python gui交互界面与学生信息管理系统数据库连接 代码
时间: 2023-09-13 13:04:48 浏览: 148
这里提供一个简单的示例代码,演示如何连接Python GUI交互界面和学生信息管理系统的数据库。
我们假设使用MySQL作为数据库,Python的GUI库使用Tkinter,具体代码如下:
```python
import tkinter as tk
import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="database_name"
)
# 创建GUI窗口
root = tk.Tk()
root.title("学生信息管理系统")
# 定义GUI控件
label_name = tk.Label(root, text="姓名")
entry_name = tk.Entry(root)
label_age = tk.Label(root, text="年龄")
entry_age = tk.Entry(root)
button_add = tk.Button(root, text="添加")
# 定义添加函数
def add_student():
name = entry_name.get()
age = entry_age.get()
cursor = mydb.cursor()
sql = "INSERT INTO students (name, age) VALUES (%s, %s)"
val = (name, age)
cursor.execute(sql, val)
mydb.commit()
print(cursor.rowcount, "记录插入成功。")
# 将控件添加到GUI窗口
label_name.grid(row=0, column=0)
entry_name.grid(row=0, column=1)
label_age.grid(row=1, column=0)
entry_age.grid(row=1, column=1)
button_add.grid(row=2, column=1)
# 绑定添加函数
button_add.config(command=add_student)
# 运行GUI程序
root.mainloop()
```
以上代码中,我们首先连接了MySQL数据库。然后,创建了一个Tkinter的GUI窗口,并定义了三个控件:一个Label和两个Entry,分别用于输入学生的姓名和年龄;还有一个Button,用于添加学生信息。在定义Button的时候,我们将它绑定到了add_student函数上。这个函数会从Entry中读取学生的姓名和年龄,然后将它们插入到数据库中。
当我们运行这个程序时,会弹出一个GUI窗口,我们可以在窗口中输入学生的姓名和年龄,然后点击"添加"按钮将学生信息保存到数据库中。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)