这几天自己鼓捣了下,觉得需要增加一个是否去重复字符的选项以满足实际需求,于是小改了一下代码(其他很多生成器都有的前后缀和批量生成等功能我认为会降低安全性,不符合我的初衷,包括生成和复制按钮在一起也是为了有人获取剪切板信息后起混淆作用).
新的代码如下:[Python] 纯文本查看 复制代码 import random
import string
import tkinter as tk
def generate_random_string():
try:
length = int(entry_length.get())
if length <= 0:
label_result.config(text="错误:长度必须是正整数")
return ""
except ValueError:
label_result.config(text="错误:请输入一个整数")
return ""
allowed_chars = ""
if var_upper.get():
allowed_chars += string.ascii_uppercase
if var_lower.get():
allowed_chars += string.ascii_lowercase
if var_digit.get():
allowed_chars += string.digits
if var_punct.get():
allowed_chars += string.punctuation
if not allowed_chars:
label_result.config(text="错误:请至少选择一种字符集")
return ""
random_string = "".join(random.choice(allowed_chars)
for _ in range(length))
def has_duplicates(s):
return len(s) != len(set(s))
def replace_duplicates(s):
new_s = ""
for ch in s:
if s.count(ch) > 1:
new_ch = random.choice(allowed_chars)
new_s += new_ch
else:
new_s += ch
return new_s
def remove_duplicates(s):
while has_duplicates(s):
s = replace_duplicates(s)
return s
if var_remove.get():
rs = remove_duplicates(random_string)
else:
rs = random_string
return rs
def show_and_copy_random_string():
random_string = generate_random_string()
if random_string:
label_result.config(text=random_string)
window.clipboard_clear()
window.clipboard_append(random_string)
window = tk.Tk()
window.title("随机字符串生成器")
window.geometry("400x300")
label_welcome = tk.Label(window, text="欢迎使用随机字符串生成器!")
label_welcome.pack()
label_length = tk.Label(window, text="请输入你想要生成的字符串长度(正整数):")
label_length.pack()
entry_length = tk.Entry(window)
entry_length.pack()
var_upper = tk.BooleanVar()
var_lower = tk.BooleanVar()
var_digit = tk.BooleanVar()
var_punct = tk.BooleanVar()
check_upper = tk.Checkbutton(window, text="大写字母", variable=var_upper)
check_upper.pack()
check_lower = tk.Checkbutton(window, text="小写字母", variable=var_lower)
check_lower.pack()
check_digit = tk.Checkbutton(window, text="数字", variable=var_digit)
check_digit.pack()
check_punct = tk.Checkbutton(window, text="特殊字符", variable=var_punct)
check_punct.pack()
var_remove = tk.BooleanVar()
check_remove = tk.Checkbutton(window, text="去重复字符", variable=var_remove)
check_remove.pack()
button_generate = tk.Button(window, text="一键生成并复制",
command=show_and_copy_random_string)
button_generate.pack()
label_result = tk.Label(window, text="")
label_result.pack()
window.mainloop()
|