在tkinter中创建后退按钮?

时间:2015-10-24 08:53:44

标签: python button tkinter destroy pack

我有一个按钮encrypt_button,它会破坏屏幕上最初的内容并在def encrypt()下显示新内容。我想创建一个后退按钮,它可以恢复上一个屏幕被破坏后的内容。我尝试过以下操作,但不会破坏def encrypt()下的内容,如果再次单击该按钮,原始标签也不会被销毁。

import tkinter

window = tkinter.Tk()
entry = tkinter.Entry(window)

def encrypt():
    encrypt_label = tkinter.Label(window, text="Please enter the message you'd like to encrypt", font=('Helvetica', 14))
    encrypt_label.pack()
    entry = tkinter.Entry(window)
    entry.pack()
    encrypt_confirm = tkinter.Button(window, text="Confirm")
    encrypt_confirm.pack()
    back_button = tkinter.Button(window, text="Back", command=back)
    back_button.pack()
    encrypt_button.destroy()
    title_header.destroy() 
    title_label.destroy()
    heading_label.destroy()

def back():
    title_header = tkinter.Label(window, text="ENCRYPTION/DECRYPTION", font=('Helvetica', 16))
    title_header.pack()
    title_label = tkinter.Label(window, text="Welcome to this encryption and decryption program")
    title_label.pack()
    heading_label = tkinter.Label(window, text="When you are ready, press a button to continue")
    heading_label.pack()
    encrypt_button = tkinter.Button(window, text="Encrypt", command=encrypt)
    encrypt_button.pack()
    encrypt_label.destroy()
    entry.destroy()
    encrypt_confirm.destroy()
    back_button.destroy()

title_header = tkinter.Label(window, text="ENCRYPTION/DECRYPTION", font=('Helvetica', 16))
title_header.pack()

title_label = tkinter.Label(window, text="Welcome to this encryption and decryption program")
title_label.pack()

heading_label = tkinter.Label(window, text="When you are ready, press a button to continue")
heading_label.pack()

encrypt_button = tkinter.Button(window, text="Encrypt", command=encrypt)
encrypt_button.pack()

encrypt_label = tkinter.Label(window, text="Please enter the message you'd like to encrypt", font=('Helvetica', 14))

entry = tkinter.Entry(window)

encrypt_confirm = tkinter.Button(window, text="Confirm")

back_button = tkinter.Button(window, text="Back", command=back)

window.mainloop()

我也试过没有定义每个标签和按钮,但这也不起作用。 (显然我得到x is not defined错误)

1 个答案:

答案 0 :(得分:1)

代码中的问题是所有变量都是局部变量,所以它们只能在创建它们的函数中可见。

最简单的解决方案是制作每个"页面"是一个框架。确保该框架的句柄是全局的,或者如果您正在使用类,则确保实例属性。

完成后,只需删除当前页面的框架并重新创建另一页面的框架即可。删除框架时,任何子项也将自动删除。