【问题标题】:Creating a back button in tkinter?在 tkinter 中创建后退按钮?
【发布时间】:2015-10-24 08:53:43
【问题描述】:

我有一个按钮,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 错误)

【问题讨论】:

    标签: python button tkinter destroy pack


    【解决方案1】:

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

    最简单的解决方案是让每个“页面”成为一个框架。确保该框架的句柄是全局的,或者如果您使用类,则为实例属性。

    完成后,只需删除当前页面的框架并为其他页面重新创建框架。删除框架时,所有子框架也将自动被删除。

    【讨论】:

      猜你喜欢
      • 2016-07-31
      • 2013-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-04
      • 1970-01-01
      • 2019-07-26
      • 1970-01-01
      相关资源
      最近更新 更多