import tkinter as tk from tkinter import messagebox import socket def receive(name=None,password=None): sk = socket.socket() # 创建客户套接字 sk.connect(('192.168.13.142', 8898)) # 尝试连接服务器 send=name+"|"+password send1=send.encode("utf-8") sk.send(send1) ret = sk.recv(1024) # 对话(发送/接收) ret1=ret.decode("utf-8") sk.close() return ret1 def denglu(): window = tk.Tk() window.title('欢迎登陆') window.geometry('400x250') canvas = tk.Canvas(window, height=100, width=200)#创建画布 image_file = tk.PhotoImage(file='logo.png')#加载图片文件 image = canvas.create_image(0,0, anchor='nw', image=image_file)#将图片置于画布上 canvas.pack(side='top')#放置画布(为上端) tk.Label(window, text='User name: ').place(x=50, y= 120)#创建一个`label`名为`User name: `置于坐标(50,150) tk.Label(window, text='Password: ').place(x=50, y= 150) var_usr_name = tk.StringVar()#定义变量 var_usr_name.set('example@oldboy.com')#变量赋值'example@python.com' entry_usr_name = tk.Entry(window, textvariable=var_usr_name)#创建一个`entry`,显示为变量`var_usr_name`即图中的`example@python.com` entry_usr_name.place(x=160, y=120) var_usr_pwd = tk.StringVar() entry_usr_pwd = tk.Entry(window, textvariable=var_usr_pwd, show='*')#`show`这个参数将输入的密码变为`***`的形式 entry_usr_pwd.place(x=160, y=150) flag=0 def usr_login(): nonlocal flag if flag<3: usr_name = var_usr_name.get() usr_pwd = var_usr_pwd.get() sign_s=receive(str(usr_name),str(usr_pwd)) # sign_s=sign_s.decode("utf-8") if sign_s=="登陆成功": messagebox.showinfo(title='', message='登陆成功') flag=0 exit() else: flag += 1 messagebox.showinfo(title='', message='账户或密码错误,剩余登录次数为%s' % (3 - flag)) if flag>=3: exit() btn_login = tk.Button(window, text='Login', command=usr_login)#定义一个`button`按钮,名为`Login`,触发命令为`usr_login` btn_login.place(x=160, y=180) window.mainloop() denglu()
客户端
import socket server = socket.socket() server.bind(('192.168.13.142',8001)) server.listen(5) while True: conn,addr = server.accept() # 字节类型 while True: data = conn.recv(1024) # 阻塞 if data == b'exit': break response = data + b' SB' conn.send(response) conn.close()