如何在python中使用Tkinter创建返回按钮



我正在尝试创建一个对我实现的按钮做出反应的GUI。

预期输出:推送";背面";按钮将恢复第一个窗口。[主窗口]

当前输出:推送";背面";按钮将调用回功能[删除辅助窗口的按钮并调用原始窗口],但不恢复原始窗口

这是我的实现:

import tkinter
from tkinter import *
from PIL import ImageTk, Image
applied_logo_path = r'C:Userse174701OneDrive - Applied MaterialsDesktopamatlogo.png'
logo_path = r'C:Userse174701OneDrive - Applied MaterialsDesktopamatmain.png'
font1 = ('Helvetica 15', 20)
# -----------------------------------------------------------------------------------------------------

def main_window():
def Second_window():
def back():
button_previous.destroy()
button_execute.destroy()
main_window()
# Second window: [User pressed "next"]
main_window.title('MC installer')
main_window.geometry("800x600")
# Presenting Applied Materials logo:
main_window_logo = ImageTk.PhotoImage(Image.open(logo_path))
main_window_logo_label = Label(image=main_window_logo, width=800, height=300)
main_window_logo_label.place(x=5, y=100)
button_next.destroy()
button_readME.destroy()
# execute button: [will start the process]
pixel = tkinter.PhotoImage(width=1, height=1)
button_execute = Button(main_window, text="Execute", image=pixel, width=80, height=30, compound="c")
button_execute.place(x=700, y=550)
# previous button: [will return the user to the main window]
button_previous = Button(main_window, text="Previous", image=pixel, width=80, height=30, compound="c",
command=lambda: back())
button_previous.place(x=10, y=550)
main_window.mainloop()
# main window general definitions:
main_window = Tk()
main_window.title('MC installer')
# instead this comment need to define the upper toolbar logo.
main_window.geometry("800x600")
# Presenting Applied Materials logo:
main_window_logo = ImageTk.PhotoImage(Image.open(logo_path))
main_window_logo_label = Label(image=main_window_logo, width=800, height=300)
main_window_logo_label.place(x=5, y=100)
# next button: [will take the user to the next window]
pixel = tkinter.PhotoImage(width=1, height=1)
button_next = Button(main_window, text="Next", image=pixel, width=80, height=30, compound="c", command=lambda: Second_window())
button_next.place(x=700, y=550)
# exit button: [will close the installer.]
button_exit = Button(main_window, text="Exit", image=pixel, width=80, height=30, compound="c", command=lambda: main_window.quit())
button_exit.place(x=10, y=550)
# read me button: [will guide the user]
button_readME = Button(main_window, text="Read me", image=pixel, width=80, height=30, compound="c")
button_readME.place(x=345, y=550)
main_window.mainloop()

从def-back((函数中可以看到,您并没有破坏窗口,而是调用按钮。

在def Second_window((函数中,您为GUI提供了与主GUI相同的名称,这将在尝试调用其中任何一个时导致错误,因为代码不知道要还原哪个窗口。将第二个窗口更改为second_window将有助于解决此问题

def back():
Second_window.destroy()
main_window()

使用框架或为每个按钮创建一个新窗口可能会有所帮助,并使导航更容易。

最新更新