下面是我目前为简单的Caesar密码程序编写的代码,我在尝试将编码数据输出到图形窗口时遇到问题。
该程序运行正常。但是屏幕上显示的唯一输出是编码消息的第一个字母,我需要整个编码消息出现在图形窗口中。
我认为这可能是我的循环问题,但无法弄明白。我尝试移动循环,但只是重复了第一个字母的两次或三次。
任何帮助都将不胜感激。
from graphics import*
def main():
win = GraphWin("Caeser Cipher",500,500)
win.setCoords(0.0,0.0,5.0,5.0)
Text(Point(2,4.8),"Caesar Ciper").draw(win)
label1 = Text(Point(1,4),"Please input file:").draw(win)
inputFileName = Entry(Point(2.5,4,),20)
inputFileName.draw(win)
button1 = Text(Point(2.5,3.5),"Open").draw(win)
Rectangle(Point(2.25,3.3),Point(2.75,3.7)).draw(win)
label = Text(Point(1,2.5),"Please input step:")
label.draw(win)
inputstep = Entry(Point(2.5,2.5),20)
inputstep.draw(win)
button2 = Text(Point(2.5,2.0),"Encode").draw(win)
Rectangle(Point(2.25,1.8),Point(2.75,2.2)).draw(win)
button3 = Text(Point(4,1),"Save").draw(win)
Rectangle(Point(3.75,0.8),Point(4.25,1.2)).draw(win)
button4 = Text(Point(4,0.5),"Quit").draw(win)
Rectangle(Point(3.75,0.3),Point(4.25,0.7)).draw(win)
output2 = Text(Point(2.5,1.5),' ')
output2.setTextColor('blue')
output2.draw(win)
while True:
P = win.getMouse()
if(P.getX()>2.25 and P.getX()<2.75 and P.getY()>3.3 and P.getY()<3.7):
fnamein = inputFileName.getText()
infile = open(fnamein, encoding='utf-16', mode='r')
content = infile.read()
output = Text(Point(2.5,3),100)
output.setText(content)
output.setTextColor('red')
output.draw(win)
#infile.close()
if(P.getX()>2.25 and P.getX()<2.7 and P.getY()>1.8 and P.getY()<2.2):
content.strip()
words = content.split()
inputstep1 = inputstep.getText()
#print(inputstep1)
encodedcontent = ' '
for numStr in content:
codeNum = ord(numStr)
#print(codeNum)
encodedcontent = chr(codeNum-eval(inputstep1))
encodedcontent_ascii = ord(numStr)-int(inputstep1)
#print(encodedcontent)
#encodedcontent = encodedcontent + ''
print(encodedcontent)
if(encodedcontent_ascii)<ord('a'):
encodedcontent_ascii = encodedcontent_ascii + 26
#print(encodedcontent_ascii)
'''if str.isalpha(encodedcontent):
encodedcontent = encodedcontent + chr(encodedcontent_ascii)
else:
label.setTextColor('red')'''
encodedcontent = encodedcontent + chr(encodedcontent_ascii)
output2.setText(encodedcontent)
if(P.getX()>3.75 and P.getX()<4.25 and P.getY()>0.8 and P.getY()<1.2):
fnameout = 'encrypt.txt'
data = encodedcontent
outfile = open(fnameout,encoding='utf-16',mode='w')
outfile.write(data)
outfile.close()
if(P.getX()>3.75 and P.getX()<4.25 and P.getY()>0.3 and P.getY()<0.7):
win.close()
main()
答案 0 :(得分:0)
我认为问题在于这个循环:
encodedcontent = ' ' # initialise
for numStr in content:
...
encodedcontent = chr(codeNum-eval(inputstep1)) # overwrite
...
encodedcontent = encodedcontent + chr(encodedcontent_ascii) # add
encodedcontent
最多只能是两个字符,大概是你想要构建整个字符串。
更一般地说,将所有代码放在一个地方会使调试变得困难。我建议把它分成更小的功能;至少,将字符串的加密与用户界面分开。