在Python中,可以使用各种库来编写数据库界面,其中最常用的库之一是Tkinter。以下是使用Tkinter编写一个简单的数据库界面的示例代码:
```python
import tkinter as tk
import sqlite3
def create_table():
conn = sqlite3.connect('mydatabase.db')
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS students (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)')
conn.commit()
conn.close()
def insert_data():
name = name_entry.get()
age = age_entry.get()
conn = sqlite3.connect('mydatabase.db')
c = conn.cursor()
c.execute('INSERT INTO students (name, age) VALUES (?, ?)', (name, age))
conn.commit()
conn.close()
name_entry.delete(0, tk.END)
age_entry.delete(0, tk.END)
def display_data():
conn = sqlite3.connect('mydatabase.db')
c = conn.cursor()
c.execute('SELECT * FROM students')
data = c.fetchall()
conn.close()
for row in data:
print(row)
root = tk.Tk()
name_label = tk.Label(root, text="Name:")
name_label.pack()
name_entry = tk.Entry(root)
name_entry.pack()
age_label = tk.Label(root, text="Age:")
age_label.pack()
age_entry = tk.Entry(root)
age_entry.pack()
create_table_button = tk.Button(root, text="Create Table", command=create_table)
create_table_button.pack()
insert_data_button = tk.Button(root, text="Insert Data", command=insert_data)
insert_data_button.pack()
display_data_button = tk.Button(root, text="Display Data", command=display_data)
display_data_button.pack()
root.mainloop()
```
这个例子创建了一个基本的Tkinter窗口,可以输入学生姓名和年龄,并将数据插入到SQLite数据库中。还提供了一个按钮来创建数据表,插入数据和显示数据。