基于tkinter的Python登录/注册界面
登录界面
使用python自带库tkinter 创建窗口,设置窗口大小,背景颜色等。
确认思路,在登录界面我们需要两个label标签(账号密码提升),两个输入文本框(输入账号密码),两个button组件对于登录,注册功能。
本文我们不使用tk.Toplevel()子窗口,在点击登录/注册时弹出子窗口,而使用subprocess模块启动新进程(即打开另一个.py文件)这样我们可以将登录,注册,首页,放在三个.py文件中,便于各个板块的维护调试。使用方法:
#这是登录.py文件
import subprocess
subprocess.Popen(['python', '注册.py'])
'''以python文件形式打开(注册.py)文件,在 注册.py文件中不需要任何操作使用此语句会直接运行 注册.py文件 '''
创建登录窗口:
# 编译:GOD-CHEN
""" 登录界面 """
import tkinter as tk
from tkinter import messagebox
import subprocess
Lo = tk.Tk() # 创建窗口
Lo.title("登陆 (Login)") #窗口标题
screen_width = Lo.winfo_screenwidth()
screen_height = Lo.winfo_screenheight() #获取整个屏幕宽高
width = 600 #设置窗口宽/高像素
height = 500
# 计算窗口左上角的坐标
x = (screen_width - width) // 2
y = (screen_height - height) // 2
Lo.geometry(f'{width}x{height}+{x}+{y}') #设置窗口大小和位置坐标
Lo.configure(bg='#add8e6') #设置背景颜色
Lo.iconbitmap('登录.ico') #设置窗口左上角图标必须是.ico文件
Lo.mainloop() #主事件循环 这个函数必须放在最后,否则在其之后的功能无法在窗口上显示
.geometry(宽x高+距离屏幕左方像素+距离屏幕上方像素)
添加标签,文本框,按钮组件
'''按钮点击对于事件'''
def M_interface():
pass
'''标签组件'''
La_Ac = tk.Label(Lo,text="账号:", font=('黑体',18), fg= 'black', bg='#add8e6')
La_Pa = tk.Label(Lo,text="密码:", font=('黑体',18), fg= 'black',bg="#add8e6")
'''位置设置'''
La_Ac.place(x=110, y=148) #设置组件位置,距离左x,距离高y
La_Pa.place(x=110, y=208)
'''获取文本框输入内容 字符串形式'''
text_Ac = tk.StringVar()
text_Pa = tk.StringVar()
'''文本框组件'''
entry_Ac = tk.Entry(Lo, width=22, font=('黑体', 18),textvariable=text_Ac)
entry_Pa = tk.Entry(Lo, width=22, font=('黑体', 18),textvariable=text_Pa, show='*')
'''文本框输入内容'''
entry_Ac.insert('end',"请输入账号密码")
entry_Ac.place(x=180, y=150 )
entry_Pa.place(x=180, y=210)
'''按钮组件——command=函数名 按钮对于的函数要写在按钮组件上方'''
bt_lo = tk.Button(Lo, text="登录", width=15, command=M_interface)
bt_re = tk.Button(Lo, text="注册", width=15, command=Re_interface)
bt_lo.place(x=240, y=280)
bt_re.place(x=240, y=330)
这里使用组件名.place()布局组件位置,x,y对应距离窗口左方和上方像素值。
在 Tkinter 中,有三种主要的方式来放置组件,分别是:
1. pack()
2. grid()
3. place()
每种方式都有其特点和适用场景,以下是对这三种布局管理方法的具体介绍:
1. `pack()` 方法
pack()` 方法是一种简单易用的布局管理方法,通过将组件依次“打包”到窗口中,按顺序排列它们。组件会按照指定的方向(如 top、bottom、left、right)进行排列。
import tkinter as tk
root = tk.Tk()
root.title("pack() 示例")
# 创建三个按钮
button1 = tk.Button(root, text="按钮1")
button2 = tk.Button(root, text="按钮2")
button3 = tk.Button(root, text="按钮3")
# 使用 pack() 方法放置按钮
button1.pack(side=tk.TOP)
button2.pack(side=tk.TOP)
button3.pack(side=tk.BOTTOM)
root.mainloop()
2. `grid()` 方法
`grid()` 方法通过将组件放置在一个网格系统中来管理布局。你可以指定组件所在的行和列,类似于电子表格的布局方式。
import tkinter as tk
root = tk.Tk()
root.title("grid() 示例")
# 创建三个按钮
button1 = tk.Button(root, text="按钮1")
button2 = tk.Button(root, text="按钮2")
button3 = tk.Button(root, text="按钮3")
# 使用 grid() 方法放置按钮
button1.grid(row=0, column=0)
button2.grid(row=0, column=1)
button3.grid(row=1, column=0, columnspan=2)
root.mainloop()
```
place() 方法
place()`方法通过指定组件的绝对位置或相对位置来放置组件。这种方式提供了最大的灵活性,但也可能使布局变得复杂。
import tkinter as tk
root = tk.Tk()
root.title("place() 示例")
# 创建三个按钮
button1 = tk.Button(root, text="按钮1")
button2 = tk.Button(root, text="按钮2")
button3 = tk.Button(root, text="按钮3")
# 使用 place() 方法放置按钮
button1.place(x=10, y=10)
button2.place(x=50, y=50)
button3.place(x=100, y=100)
root.mainloop()
总结
pack():适合简单、线性的布局。
grid():适合网格状的布局,尤其是当你需要复杂的表格结构时。
place():适合需要精确控制组件位置的复杂布局。
选择哪种方法取决于你的具体需求和布局的复杂程度。
完善登录界面事件,判断账号密码
def Re_interface():
Lo.withdraw()
Lo.destroy()
subprocess.Popen(['python', 'Register.py']) #进入注册线程
def read_credentials(filename):
"""从文件中读取账号和密码"""
credentials = {}
try:
with open(filename, 'r') as file:
for line in file:
account, password = line.strip().split(',')
credentials[account] = password
except FileNotFoundError:
messagebox.showerror('文件错误', 'data.txt 文件未找到')
return credentials
def M_interface():
account = text_Ac.get()
password = text_Pa.get()
credentials = read_credentials('data.txt')
if account not in credentials:
messagebox.showerror('登陆错误',"账号不存在!")
elif credentials[account] != password:
messagebox.showerror('登录错误', "账号或密码错误")
else:
messagebox.showinfo('登录成功','登录成功')
subprocess.Popen(['python', 'Homepage.py']) #进入新线程
Lo.destroy() #销毁窗口
编写注册界面
# 编译:GOD-CHEN
''' 注册界面 '''
import subprocess
import tkinter as tk
from tkinter import messagebox
def read_credentials(filename):
"""从文件中读取账号和密码"""
credentials = {}
try:
with open(filename, 'r') as file:
for line in file:
account, password = line.strip().split(',')
credentials[account] = password
except FileNotFoundError:
pass
return credentials
def write_credentials(filename, credentials):
"""将账号和密码写入文件"""
with open(filename, 'w') as file:
for account, password in credentials.items():
file.write(f"{account},{password}\n")
def register():
account = text_pa1.get()
password = text_pa2.get()
password2 = text_pa3.get()
# 读取现有账号和密码
credentials = read_credentials('data.txt')
# 检查账号是否已经存在
if account in credentials:
messagebox.showerror('注册错误', "账号已存在!")
elif account == '':
messagebox.showerror('账号错误','账号不能为空!')
elif password == '' or password2 == '':
messagebox.showerror('密码错误','密码不能为空!')
elif password != password2:
messagebox.showerror('注册错误','两次密码不一致')
else:
# 将新账号和密码写入文件
credentials[account] = password
write_credentials('data.txt', credentials)
messagebox.showinfo('注册成功', "账号注册成功!")
Re.withdraw()
subprocess.Popen(['python', 'Login.py'])
Re.destroy()
Re = tk.Tk()
Re.title("注册账号")
screen_width = Re.winfo_screenwidth()
screen_height = Re.winfo_screenheight() #获取屏幕宽高
width = 400
height = 380
# 计算窗口左上角的坐标
x = (screen_width - width) // 2
y = (screen_height - height) // 2
Re.geometry(f'{width}x{height}+{x}+{y}') #设置窗口大小和位置坐标
Re.configure(bg='#efefef') #设置背景颜色
La_1= tk.Label(Re,text="新账号\t:", font=('黑体',12), fg= 'black')
La_1.place(x=60, y=100)
La_2= tk.Label(Re,text="新密码\t:", font=('黑体',12), fg= 'black')
La_2.place(x=60, y=140)
La_3= tk.Label(Re,text="重复密码:", font=('黑体',12), fg= 'black')
La_3.place(x=60, y=180)
text_pa1 = tk.StringVar()
text_pa2 = tk.StringVar()
text_pa3 = tk.StringVar()
en1 = tk.Entry(width=20, font=('黑体', 12),textvariable=text_pa1)
en2 = tk.Entry(width=20, font=('黑体', 12),textvariable=text_pa2)
en3 = tk.Entry(width=20, font=('黑体', 12),textvariable=text_pa3)
en1.place(x=150, y=102)
en2.place(x=150, y=142)
en3.place(x=150, y=182)
bt_re2 = tk.Button(Re, text="确认注册", width=13, command=register)
bt_re2.place(x=145, y=250)
# 运行主循环
Re.mainloop()
两个界面功能组件都差不多就不详细介绍了,其功能函数创建存放,账号密码,即一些简单判断都在上面源码中。
作者:GOD.CHEN