导入tkinter模块界面设计 利用随机函数实现验证码随机 忽略大小写验证
代码如下:
import random
from tkinter import *
from tkinter import messagebox
# 随机数实现6位验证码。
def createCode():
res = ''
for i in range(2):
num = random.randint(0, 9)
res += str(num)
num = random.randint(65, 90)
res += str(chr(num))
num = random.randint(97, 122)
res += str(chr(num))
string = str(res)
str_list = list(string) # 将循环到的6位字符串转化为列表
random.shuffle(str_list) # 用列表的shuffle函数随机打乱
shuffle_str = ''.join(str_list) # 连接列表中6位字符
txt.set(shuffle_str)
return txt
#确认按钮功能
def confirm():
t1 = text.get()
t2 = text_code.get()
if t1.upper() == t2.upper() or t1.lower() == t2.lower(): # 忽略大小写
messagebox.showinfo('window', '验证成功') # 弹出提示框
else:
messagebox.showerror('window', '验证失败')
'''主程序'''
root = Tk()
root.geometry('400x200+500+400')
code = Label(root, text=' 验证码:', fg='black', bg='turquoise')
code.place(x=56, y=60, width=50, height=20)
text = Entry(root)
text.place(x=118, y=60, width=110, height=20)
txt = StringVar()
txt.set('获取验证码')
codestr = Button(root, textvariable=txt, command=createCode, fg='black', relief=RIDGE)
codestr.place(x=240, y=60, width=115, height=20)
text_code = txt
buttonName = Button(root, text='确认', command=confirm, fg='blue', bg='lightblue')
buttonName.place(x=140, y=120, width=50, height=30)
if __name__ == '__main__':
root.mainloop()
运行结果如下:
感谢。