为什么encrypt()返回None?

时间:2013-04-09 03:22:46

标签: python

我知道要求一群人查看几段代码是有点大胆的,但无论如何我都会尝试。我试图用tk在python中创建一个enigma(第二次世界大战中使用的德语加密机器)的克隆。从逻辑上查看我的代码,方法encrypt()要么返回字符串“Alert”,这是非常不可能的,要么返回None。有人请给它快速但专注的一瞥,以便我可以解决这个问题吗?谢谢。

from Tkinter import *
from string import letters
import tkMessageBox

root = Tk()
root.title("EnigmaTK")

def rank(x, d = dict((letr,n%26+1) for n,letr in enumerate(letters[0:52]))):
    return d[x]


def shift(key, array):
    counter = range(len(array))
    new = counter
    for i in counter:
        new[i] = array[i-key]
    return new

alph = ["a", "b", "c", "d", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", " "]
rotI = ["a", "b", "c", "d", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", " "]
rotII = ["a", "b", "c", "d", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", " "]
rotIII = ["a", "b", "c", "d", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", " "]
ref = ["a", "b", "c", "d", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "e", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", " "]

label = Label(root, text="Input:")
label.pack(side = LEFT)
entry = Entry(root)
entry.pack(side = RIGHT)
input = entry.get()
rotor_set = map(rank, input[:3])
message = input[3:]


def encrypt():
    new_message = message
    for a in xrange(len(message)):
        for e in range(rotor_set[2]):
            new_message[a] = alph[rotI.index(rotII[rotIII.index(ref[rotIII.index(rotII[rotI.index(alph[a])])])])]
            a = a + 1
            rotIII = shift(1, rotIII)
        for i in range(rotor_set[1]):
            new_message[a] = alph[rotI.index(rotII[rotIII.index(ref[rotIII.index(rotII[rotI.index(alph[a])])])])]
            a = a + 1
            rotII = shift(1, rotII)
        for o in range(rotor_set[0]):
            new_message[a] = alph[rotI.index(rotII[rotIII.index(ref[rotIII.index(rotII[rotI.index(alph[a])])])])]
            a = a + 1
            rotI = shift(1, rotI)
    return new_message


def show():
    tkMessageBox.showinfo( "English to Enigma", encrypt())


e = Button(root, text = "encrypt", command = show)
e.pack()
root.mainloop()

顶部附近的字母都是一样的。如果问题解决了,我会改变这个。谢谢。

2 个答案:

答案 0 :(得分:0)

我的猜测是encrypt正在抛出由Tk转换为警报的异常。如果从命令行启动程序,则可能会看到异常。

如果是例外情况,我的猜测是您尝试通过new_message修改new_message[a] = ...。如果new_message是一个字符串(或元组),则Python中不允许这样做,因为字符串是不可变的。相反,请使用列表:

new_message = list(message)

并在您返回时加入消息:

return ''.join(new_message)

答案 1 :(得分:0)

此行似乎在错误的时间执行:

input = entry.get()

我认为您想要在用户单击按钮时获取数据,而不是在程序运行开始时获取数据。由于您在使用单击按钮时未获取数据,message仍为空字符串,new_message变为空字符串,encrypt()返回空字符串。

可能的解决方案是修改encrypt()

def encrypt():
    input = entry.get()
    new_message = input[3:]
    ...
相关问题