Python加密解密凯撒密码的窗口版本

凯撒密码的原理是将所有的字母向前移动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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值