凯撒密码的原理是将所有的字母向前移动3位,即
A 加密后为D ,B加密后为E,以此类推最后一个字母Z加密后为C
运行结果如下:
生成一个标题为“凯撒密码”的窗口
在明文部分输入需要加密的内容后点击 “加密” 就会自己生成密文,
相应的在密文部分输入需要解密的内容点击解密按钮就会自己生成明文:
完整代码如下:
import tkinter as tk #窗口package
def jia_mi(text, num): #加密函数定义
result = ''
for char in text:
if char.isalpha():
#加密算式
ascii_code = ord(char.lower())
encrypted_code = ((ascii_code - 97 + num) % 26) + 97
result += chr(encrypted_code)
else:
#输出
result += char
return result
def jie_mi(jie_mi_text, num): # 解密函数定义
result = ''
for char in jie_mi_text:
if char.isalpha():
# 解密算式
ascii_code = ord(char.lower())
decrypted_code = (ascii_code - 97 - num) % 26 + 97
result += chr(decrypted_code)
else:
#输出
result += char
return result
def on_jia_mi_click():
global input_text
global output_text
num = 3
input_text = entry1.get()
encrypted_text = jia_mi(input_text, num)
output_text = encrypted_text
entry2.delete(0, tk.END)
entry2.insert(0, output_text)
def on_jie_mi_click():
global input_text
global output_text
num = 3
input_text = entry2.get()
decrypted_text = jie_mi(input_text, num)
output_text = decrypted_text
entry1.delete(0, tk.END)
entry1.insert(0, output_text)
#生成窗口
root = tk.Tk()
root.title("凯撒密码")
root.geometry("300x200")
#标签占位
label = tk.Label(root, text=" ")
label.grid(column=0, row=0, padx=10, pady=10, sticky='nsew')
#明文框
label1 = tk.Label(root, text="明文")
label1.grid(row=1, column=1,)
entry1 = tk.Entry(root)
entry1.grid(row=1, column=2)
#加密按钮
label2 = tk.Label(root, text="加密")
button1 = tk.Button(root, text="加密", command=on_jia_mi_click)
button1.grid(row=3, column=1)
#解密按钮
label3 = tk.Label(root, text="解密")
button2 = tk.Button(root, text="解密", command=on_jie_mi_click)
button2.grid(row=3, column=2)
#密文框
label4 = tk.Label(root, text="密文")
label4.grid(row=2, column=1)
entry2 = tk.Entry(root)
entry2.grid(row=2, column=2)
#run
root.mainloop()