簡體   English   中英

tkinter中不同幀之間的切換

[英]Switching between different frames in tkinter

我正在嘗試學習如何使用 tkinter 中的框架,以每頁不同的 class 的方式編寫它:

import tkinter as tk


class App(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        self.title("Multiple Frames Test")
        self.resizable(False, False)
        StartPage().pack()

    def switch_frames(self, to_remove, to_add):
        to_remove.pack_forget()
        to_add.pack()


class StartPage(tk.Frame, App):

    def __init__(self):
        tk.Frame.__init__(self)
        self.title1 = tk.Label(self, text="This is an awesome label")
        self.title1.grid(row=0, column=0, padx=(20, 20), pady=(20, 20))
        self.switch_btn1 = tk.Button(self, text="Switch to SecondaryPage", command=lambda: self.switch_frames(self, SecondaryPage))
        self.switch_btn1.grid(row=1, column=0, padx=(20, 20), pady=(0, 20))


class SecondaryPage(tk.Frame, App):

    def __init__(self):
        tk.Frame.__init__(self)
        self.title2 = tk.Label(self, text="This is also an awesome label")
        self.title2.grid(row=0, column=0, padx=(20, 20), pady=(20, 20))
        self.switch_btn2 = tk.Button(self, text="Switch to StartPage")
        self.switch_btn2.grid(row=1, column=0, padx=(20, 20), pady=(0, 20))


my_app = App()
my_app.mainloop()

按下按鈕切換到 SecondaryPage 后,出現錯誤:

文件“c:\Users...”,第 23 行,在

self.switch_btn1 = tk.Button(self, text="切換到 SecondaryPage", command=lambda: self.switch_frames(self, SecondaryPage))

文件“c:\Users...”,第 14 行,在 switch_frames

to_add.pack()

類型錯誤:pack_configure() 缺少 1 個必需的位置參數:'self'

您將 class 傳遞給switch_frames ,但 switch_frames 旨在接受實例。 您需要做以下兩件事之一:要么創建兩個類的實例,然后將適當的實例傳遞給 function,要么重新定義switch_frames以按需創建實例。

這是第一個解決方案的樣子:

class App(tk.Tk):

    def __init__(self):
        ...
        self.start_page = StartPage()
        self.secondary_page = SecondaryPage()

        # initially hide the secondary page and show the start page
        self.switch_frames(self.secondary_page, self.start_page)

另一種解決方案需要更改switch_frames以接受 class,然后在切換到它之前創建它。 它可能看起來像這樣:

class App(tk.Tk):
    def __init__(self):
        ...
        self.current_page = None
        self.switch_frames(StartPage)
        ...

    def switch_frames(self, new_frame_cls):
        if self.current_page is not None:
            self.current_page.destroy()
        self.current_page = new_frame_cls()
        self.current_page.pack()

兩者之間的區別在於,在第一種情況下,您是在開始時創建頁面,而第二種情況是您僅在准備好顯示頁面時才創建頁面。

暫無
暫無

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

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