您的位置:首页 > 编程语言 > Python开发

python验证码生成器

2018-06-13 22:29 429 查看

导入依赖

[code]import random
import string
from tkinter import *
  • 定义验证码生成器类
[code]# 验证码生成器
class VerifyingCodeGenerator:
# charsPerGroup=每组字符数
# groups=生成的组数
# 默认生成一组4*10的验证码
def __init__(self, charsPerGroup=4, groups=5):
# 窗口和标题
window = Tk()
window.title("验证码生成器")

# 定义输入框控件的变量存储器
self.entValue1 = StringVar()
self.entValue2 = StringVar()

# 默认设置为外界输入的参数
self.entValue1.set(charsPerGroup)
self.entValue2.set(groups)

# 打包一个面板到窗口
frame = Frame()
frame.pack(padx=5, pady=(5, 0))  # y方向的上下边距分别为5和0

# 在面板上横排4个控件
Label(frame, text="每组字符数").grid(row=1, column=1)
Entry(frame, textvariable=self.entValue1).grid(row=1, column=2)  # 输入框的值丢给entValue1动态保管
Label(frame, text="生成组数").grid(row=1, column=3, padx=(10, 0))
Entry(frame, textvariable=self.entValue2).grid(row=1, column=4)  # 输入框的值丢给entValue2动态保管

# 打包一个按钮到窗口,其监听由doGenerate函数实现
btn = Button(width=60, height=1, text="生成验证码", command=self.doGenerate)
btn.pack(padx=5, pady=5)

# 打包一个文本域控件到窗口
self.text = Text(width=60, height=10)
self.text.pack(padx=5, pady=(0, 5))

# 开启消息循环
window.mainloop()

# 生成一组charsPerGroup*groups的验证码
def generate(self, charsPerGroup, groups):
# 定义字符样本
population = string.ascii_uppercase + string.digits
# print(population)

# 预定义
codelist = []

# 生成若干组
for i in range(groups):
# 从样本中随机选取若干字符,形成列表
mlist = random.sample(population, charsPerGroup)

# 将列表转化为字符串
mstr = "".join(mlist)

# 添加当前生成字符串到总列表
codelist.append(mstr)

# 将总列表转换为字符串
code = "-".join(codelist)
return code

# 按钮的点击监听
def doGenerate(self):
# 获取控件输入的值
arg1 = int(self.entValue1.get())
arg2 = int(self.entValue2.get())

# 生成验证码
code = self.generate(arg1, arg2)

# 将验证码显示到文本域中
self.text.insert(END, code + "\n")
pass
  •  

创建验证码生成器

[code]if __name__ == '__main__':
VerifyingCodeGenerator(4, 10)
pass


 

版权声明:本文为博主原创文章,未经博主允许不得转载。https://my.csdn.net/pangzhaowen

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: