使用 Tkinter 在Python中创建 MySQL 数据库登录页面
先决条件: Python GUI – tkinter、 Python MySQL – 选择查询
Tkinter是Python库之一,它包含许多用于开发图形用户界面页面和窗口的功能。登录页面对于开发任何类型的移动或 Web 应用程序都很重要。此页面对于用户身份验证而言是最重要的。
我们将使用mysql.connector库在Python项目和 MySQL 工作台之间建立连接。 Db 是使用 mysql.connector.connect 类创建的对象,它存储有关数据库的所有信息,例如数据库名称、密码和表名。
在下面的示例中,
- tk.label 和 tk.button 用于在 GUI 屏幕上创建标签和按钮。每个按钮都包含一个命令,其中包括单击按钮时要执行的函数。
- 创建函数logintodb以登录 MySQL 数据库。保存查询包括单击提交按钮时要执行的查询。
- X 和 Y 是用于调整 Tkinter 窗口上的对象的参数。
- Root.mainloop() 包含在最后,表示只有其中的组件包含在窗口中。
下面是实现:
Python3
import tkinter as tk
import mysql.connector
from tkinter import *
def submitact():
user = Username.get()
passw = password.get()
print(f"The name entered by you is {user} {passw}")
logintodb(user, passw)
def logintodb(user, passw):
# If password is enetered by the
# user
if passw:
db = mysql.connector.connect(host ="localhost",
user = user,
password = passw,
db ="College")
cursor = db.cursor()
# If no password is enetered by the
# user
else:
db = mysql.connector.connect(host ="localhost",
user = user,
db ="College")
cursor = db.cursor()
# A Table in the database
savequery = "select * from STUDENT"
try:
cursor.execute(savequery)
myresult = cursor.fetchall()
# Printing the result of the
# query
for x in myresult:
print(x)
print("Query Executed successfully")
except:
db.rollback()
print("Error occured")
root = tk.Tk()
root.geometry("300x300")
root.title("DBMS Login Page")
# Defining the first row
lblfrstrow = tk.Label(root, text ="Username -", )
lblfrstrow.place(x = 50, y = 20)
Username = tk.Entry(root, width = 35)
Username.place(x = 150, y = 20, width = 100)
lblsecrow = tk.Label(root, text ="Password -")
lblsecrow.place(x = 50, y = 50)
password = tk.Entry(root, width = 35)
password.place(x = 150, y = 50, width = 100)
submitbtn = tk.Button(root, text ="Login",
bg ='blue', command = submitact)
submitbtn.place(x = 150, y = 135, width = 55)
root.mainloop()
输出: