Tkinter で 2 つのフレームを切り替えるには? 質問する

Tkinter で 2 つのフレームを切り替えるには? 質問する

チュートリアルで説明されているように、私は小さな GUI を備えた最初のいくつかのスクリプトを作成しましたが、より複雑なプログラムで何をすべきかについては説明されていません。

開始画面に「スタート メニュー」があり、ユーザーが選択するとプログラムの別のセクションに移動して画面を適切に再描画する場合、これをエレガントに行う方法は何でしょうか?

「スタート メニュー」フレームだけを作成.destroy()してから、別の部分のウィジェットで埋め尽くされた新しいフレームを作成しますか? また、戻るボタンを押すと、このプロセスが逆になりますか?

ベストアンサー1

1 つの方法は、フレームを互いに重ねて、積み重ねる順序で 1 つを他のフレームより上に上げることです。一番上にあるフレームが見えるようになります。この方法は、すべてのフレームが同じサイズの場合に最も効果的ですが、少し作業すれば、任意のサイズのフレームでも機能させることができます。

注記: これが機能するには、ページのすべてのウィジェットがそのページ (つまりself) またはその子孫を親 (または好みの用語によってはマスター) として持つ必要があります。

一般的な概念を示すために、少し無理のある例を挙げます。

try:
    import tkinter as tk                # python 3
    from tkinter import font as tkfont  # python 3
except ImportError:
    import Tkinter as tk     # python 2
    import tkFont as tkfont  # python 2

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, PageOne, PageTwo):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()


class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is the start page", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)

        button1 = tk.Button(self, text="Go to Page One",
                            command=lambda: controller.show_frame("PageOne"))
        button2 = tk.Button(self, text="Go to Page Two",
                            command=lambda: controller.show_frame("PageTwo"))
        button1.pack()
        button2.pack()


class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()


class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 2", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()


if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

スタートページ ページ1 2ページ

クラス内でインスタンスを作成するという概念がわかりにくい場合、または構築中にページごとに異なる引数が必要な場合は、各クラスを明示的に個別に呼び出すことができます。ループは主に、各クラスが同一であることを示すために使用されます。

たとえば、クラスを個別に作成するには、for F in (StartPage, ...)次のようにループ ( ) を削除します。

self.frames["StartPage"] = StartPage(parent=container, controller=self)
self.frames["PageOne"] = PageOne(parent=container, controller=self)
self.frames["PageTwo"] = PageTwo(parent=container, controller=self)

self.frames["StartPage"].grid(row=0, column=0, sticky="nsew")
self.frames["PageOne"].grid(row=0, column=0, sticky="nsew")
self.frames["PageTwo"].grid(row=0, column=0, sticky="nsew")

時間が経つにつれて、このコード (またはこのコードをコピーしたオンライン チュートリアル) を出発点として、他の質問が寄せられるようになりました。これらの質問に対する回答を読んでみるとよいでしょう。

おすすめ記事