[英]Why is encrypt() returning None?
我知道要求一群人浏览几个代码块有点胆怯,但是我还是会尝试的。 我正在尝试使用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()
顶部附近的字母都相同。 如果问题解决,我将更改此设置。 谢谢。
我的猜测是encrypt
将引发一个异常,该异常将由Tk转换为警报。 如果从命令行启动程序,则可能会看到异常。
如果是例外,我的猜测是您正在尝试通过执行new_message[a] = ...
来修改new_message
。 如果new_message
是字符串(或元组),则在Python中这是不允许的,因为字符串是不可变的。 而是使用一个列表:
new_message = list(message)
并在返回时加入消息:
return ''.join(new_message)
该行似乎在错误的时间执行:
input = entry.get()
我假设您要在用户单击按钮时而不是在程序运行开始时获取数据。 由于在用户单击按钮时不会获取数据,因此message
仍为空字符串, new_message
变为空字符串,并且new_message
encrypt()
返回空字符串。
一个可能的解决方案是修改encrypt()
:
def encrypt():
input = entry.get()
new_message = input[3:]
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.