簡體   English   中英

在 Tkinter 中無按鈕切換框架

[英]Switch frames in Tkinter without a button

我正在使用以下代碼創建 Tkinter window 並切換它顯示的幀。

import tkinter

class GUI(tkinter.Tk):
    def __init__(self):
        tkinter.Tk.__init__(self)
        self._frame = None
        self.switch(Frame1)

    def switch(self, frame_class):
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()


class Frame1(tkinter.Frame):
    def __init__(self, parent):
        tkinter.Frame.__init__(self, parent)
        tkinter.Label(self, text="Frame1").pack()

        parent.switch(Frame2) # not working
        tkinter.Button(self, text="switch", command=lambda: parent.switch(Frame2)).pack() # working


class Frame2(tkinter.Frame):
    def __init__(self, parent):
        tkinter.Frame.__init__(self, parent)
        tkinter.Label(self, text="Frame2").pack()


if __name__ == '__main__':
    gui = GUI()
    gui.mainloop()

請注意,開關 function 無需按鈕即可執行,但僅在單擊時有效。

這是正在發生的事情:

  1. GUI開始切換到第 1 幀
  2. Frame1 被創建並切換到 frame 2
  3. GUI完成切換到第 1 幀

因此,該應用程序在第 1 幀結束

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM