Python 程序卡住了
我刚开始学习Python,正在写一个有趣的程序。我的程序由三个.py文件组成(我们称它们为a.py、b.py和c.py)。a.py会根据用户的选择调用b.py或c.py中的函数。在完成第一次操作后,它会询问用户是否想继续,或者直接退出程序。如果用户选择继续,它会再次询问是运行b还是c。
我遇到的问题是,第一次运行时,a.py可以正常调用b或c中的函数,一切都很顺利。但当我选择继续时,它再次调用函数也没问题,函数进入后却在第一步卡住了。
程序没有终止,也没有报错。它可以接受用户输入的变量,但就是不继续往下走。我在想有没有办法强制它接受这个变量,然后继续执行(让它“解卡”)。我已经尝试在下一行加上pass,但没有效果。
以下是从请求继续开始的步骤:
Continue = tkMessageBox.askyesno('Cypher Program', 'I have completed the task'
+ '\nWould you like to do anything else?')
## This is in a.py;
if Continue == True:
cyp()
def cyp():
global root
root = Tk()
root.title("Cypher Program")
root['padx'] = 40
root['pady'] = 20
textFrame = Frame(root)
Label(root, text = 'What would you like to do?').pack(side = TOP)
widget1 = Button(root, text = 'Encrypt a file', command = encrypt)
widget1.pack(side = LEFT)
widget2 = Button(root, text = 'Decrypt a file', command = decrypt)
widget2.pack(side = RIGHT)
widget3 = Button(root, text = 'Quit', command = quitr)
widget3.pack(side = BOTTOM)
root.mainloop()
def encrypt():
root.destroy()
encrypt3.crypt()
##Then from there it goes to b.py;
def crypt():
entry('Enter a file to encrypt:', selectFile)
def entry(msg1, cmd):
global top
top = Toplevel() ##changed it to Toplevel
top.title("File Encrypion")
top['padx'] = 40
top['pady'] = 20
textFrame = Frame(top)
entryLabel = Label(textFrame)
entryLabel['text'] = msg1
entryLabel.pack(side = LEFT)
global entryWidget
entryWidget = Entry(textFrame)
entryWidget['width'] = 50
entryWidget.pack(side = LEFT)
textFrame.pack()
button = Button(top, text = "Submit", command = cmd)
button.pack()
button.bind('<Return>', cmd)
top.mainloop()
def selectFile():
if entryWidget.get().strip() == "":
tkMessageBox.showerror("File Encryption", "Enter a file!!")
else:
global enc
enc = entryWidget.get().strip() + '.txt'
top.destroy() ##gets stuck here
##This is the rest of crypt(). It never returns to the try statement
try:
view = open(enc)
except:
import sys
sys.exit(badfile())
text = ''
1 个回答
2
你需要调整一下你的代码,只创建一次主窗口,并且只调用一次 mainloop
。Tkinter 这个库并不支持在同一个程序里多次创建和销毁主窗口。
如果你需要多个窗口,可以使用 Toplevel
命令来创建额外的窗口。