アドバンストなTkinter:クラスを使った作業

今日は、Tkinterのクラスを使って作業をします。もし以前にTkinterを使ったことがあれば、アプリケーションを作成するために使える多くのGUI機能があることをおそらく知っているでしょう。

しかし、アプリケーションを作成する際には、見た目以上のモジュールの重要性にすぐに気付きます。

tkinterにはたくさんの隠れた機能がありますが、その中の一つはモジュール内でクラスを使用する方法です。

Tkinterモジュールの設定

どんなモジュールをインストールする必要もありません。なぜなら、tkinterモジュールはPythonの標準ライブラリの一部だからです。

ただし、この記事ではtkinterモジュールのやや高度な形式について取り上げますので、初心者向けのシリーズを読むことをおすすめします。

次に進む前に、こちらのTKinterの基本チュートリアルを読むのを忘れないでください。

  • Tkinter Part – 1
  • Tkinter Part – 2
  • Tkinter Part – 3

基本的なチュートリアルが終わったら、tkinterモジュールの操作に入りましょう。

クラスを使うためには、tkinterモジュールをインポートする必要があります。

# Importing the tkinter module
import tkinter as tk

# Used for styling the GUI
from tkinter import tkk

使いやすさのため、ttkパッケージも別途インポートします。

Tkinterを使ったクラスの操作

私たちがTkinterでクラスを使う方法を理解しましょう。アプリケーションの動作方法は非常にシンプルです。

最初に根ウィンドウを作成し、その上に1つのフレームを配置します。

異なるウィンドウを持つアプリケーションのように見せるために、フレーム間を切り替える機能も作成します。

これにより、ユーザーは別のウィンドウ/タブにリダイレクトされているように錯覚しますが、実際にはフレーム間を切り替えているだけです。

私たちが使用するフレームは、メインページ、サイドページ、完了画面です。

私たちがそれらを切り替えるために使用する方法は、show_frame()メソッドです。

コードを手掛けています。 (Kōdo wo tegakete imasu.)

さあ、他のすべてのクラス/フレームにアクセスするための基底クラスを作成しましょう。

# Allowing us to extend from the Tk class
class testClass(tk.Tk):

tk.Tkのクラスを拡張することで、Tk()クラスに存在するコンポーネントと一緒に作業することができます。

クラスを初期化する。

クラスを初期化するために、__init__関数を使用します。これにより、クラスからオブジェクトを作成する際に自動的に実行されるメソッドが作成されます。

同様に、私たちはtk.Tk __init__ を通じてクラスを初期化しています。

import tkinter as tk
from tkinter import ttk

class windows(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        # Adding a title to the window
        self.wm_title("Test Application")

        # creating a frame and assigning it to container
        container = tk.Frame(self, height=400, width=600)
        # specifying the region where the frame is packed in root
        container.pack(side="top", fill="both", expand=True)

        # configuring the location of the container using grid
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        # We will now create a dictionary of frames
        self.frames = {}
        # we'll create the frames themselves later but let's add the components to the dictionary.
        for F in (MainPage, SidePage, CompletionScreen):
            frame = F(container, self)

            # the windows class acts as the root window for the frames.
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        # Using a method to switch frames
        self.show_frame(MainPage)

2. ビューフレームを切り替えるための方法を作成する

「__init__」を作成し、使用するフレームを指定したので、表示しているフレームを切り替えるメソッドを作成することができます。

    def show_frame(self, cont):
        frame = self.frames[cont]
        # raises the current frame to the top
        frame.tkraise()

3. フレーム用の複数のクラスを作成する

今、私たちはshow_frame()メソッドを使用して切り替えられるフレームとして機能する異なるクラスを作成しています。

class MainPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Main Page")
        label.pack(padx=10, pady=10)

        # We use the switch_window_button in order to call the show_frame() method as a lambda function
        switch_window_button = tk.Button(
            self,
            text="Go to the Side Page",
            command=lambda: controller.show_frame(SidePage),
        )
        switch_window_button.pack(side="bottom", fill=tk.X)


class SidePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="This is the Side Page")
        label.pack(padx=10, pady=10)

        switch_window_button = tk.Button(
            self,
            text="Go to the Completion Screen",
            command=lambda: controller.show_frame(CompletionScreen),
        )
        switch_window_button.pack(side="bottom", fill=tk.X)


class CompletionScreen(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Completion Screen, we did it!")
        label.pack(padx=10, pady=10)
        switch_window_button = ttk.Button(
            self, text="Return to menu", command=lambda: controller.show_frame(MainPage)
        )
        switch_window_button.pack(side="bottom", fill=tk.X)

もし気づいたら、これらのクラスは、self.frames変数を使ってメインクラスに追加されています。

メインの __name__==”main” 内でクラスの実装コマンドを保持しますが、直接使用することもできます。

if __name__ == "__main__":
    testObj = windows()
    testObj.mainloop()

前進する (Zenshin suru)

クラスとメソッドの定義が完了しましたので、このスクリプトを実行することができます。

ボタンをクリックすることで、フレーム間を切り替えることができる、小さなウィンドウが表示されるはずです。

より高いレベルでは、アプリケーションの上部にあるメニューバーでフレームを切り替える機能を持つこともできます。

結論 (けつろん)

「tkinter」モジュールでクラスを使用することは、さまざまなアプリケーションの開発や作成に多くの可能性を広げる。

本日はかなりの量のコードを作業しましたが、確認のために要点をまとめますね!

もし実際の例を見たいと思うならば、Eisenのチケットという私のプロジェクトをチェックしてみてください。このプロジェクトではTkinterのクラスを含む多くの機能を実装し、SQLite3を使用して動作します。

参考文献

  • Tkinter Documentation
  • Tkinter Classes
コメントを残す 0

Your email address will not be published. Required fields are marked *