[英]How to create back button with Tkinter in python
我正在嘗試創建一個對我已實現的按鈕做出反應的 GUI。
預期 output:按下“返回”按鈕將恢復第一個 window。 [主窗口]
目前 output:按“返回”按鈕將回調 function [刪除輔助窗口的按鈕並調用原始窗口] 但不會恢復原始 Z05B8C74CBD96FBF2DE4C1A352702FFF4Z
這是我的實現:
import tkinter
from tkinter import *
from PIL import ImageTk, Image
applied_logo_path = r'C:\Users\e174701\OneDrive - Applied Materials\Desktop\amatlogo.png'
logo_path = r'C:\Users\e174701\OneDrive - Applied Materials\Desktop\amatmain.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() function 中可以看到,您沒有破壞 window,而是調用了按鈕。
在 def Second_window() function 中,您將 GUI 命名為與主窗口相同的名稱,這將在嘗試調用其中任何一個時導致錯誤,因為代碼將不知道要恢復哪個 window。 將第二個 window 更改為 Second_window 將有助於解決此問題
def back():
Second_window.destroy()
main_window()
使用框架或為每個按鈕創建一個新的 window 可能會有所幫助並使導航更容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.