PythonのGUIアプリ CustomTkinter クラス化テンプレート

まくまく
まくまく
CustomTkinter クラス化を用いてプログラムを書くときのテンプレートです。基本はこれらに個別の処理を追加していけばOK!!



CustomTkinter公式docより

以下は、CustomTkinter公式docに記載されているクラス化手法によるサンプルプログラムです。

import customtkinter
class App(customtkinter.CTk):
    def __init__(self):
        super().__init__()

        self.title("minimal example app")
        self.minsize(400, 300)

        self.button = customtkinter.CTkButton(master=self, command=self.button_callback)
        self.button.pack(padx=20, pady=20)

    def button_callback(self):
        print("button pressed")


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


↑実行するとウインドウが作成されボタンが表示されるだけ。押すと「button pressed」が出力されます。

ラベルとエントリーを追加

よく使うラベルとエントリーを追加したものがこちら。

import customtkinter

class App(customtkinter.CTk):
    def __init__(self):
        super().__init__()

        self.title("minimal example app")
        self.minsize(400, 300)

        self.button = customtkinter.CTkButton(master=self, command=self.button_callback)
        self.button.pack(pady=20)

        self.label = customtkinter.CTkLabel(master=self, text="CTkLabel")
        self.label.pack(pady=20)

        self.entry = customtkinter.CTkEntry(master=self, placeholder_text="CTkEntry")
        self.entry.pack(padx=20, pady=10)

    def button_callback(self):
        print("button pressed")

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

フレームにウィジェットを配置するならこちら

フレームを作成して、その上にボタンやラベルなどを配置してみました。さきほどと同様にクラスを用いて書いています。main関数を使ってるので若干変更してます。

import customtkinter

class Testclass(customtkinter.CTkFrame):
    def __init__(self,master=None):
        super().__init__(master)

        self.frame = customtkinter.CTkFrame(self.master,
                            width=400,
                            height=200,
                            corner_radius=10)
        #self.frame.grid_propagate(False)
        self.frame.place(x=20, y=20)

        self.button = customtkinter.CTkButton(self.frame, command=self.button_callback)
        self.button.place(x=20, y=20)

        self.label = customtkinter.CTkLabel(self.frame, text="CTkLabel")
        self.label.place(x=20, y=60)

        self.entry = customtkinter.CTkEntry(self.frame, placeholder_text="CTkEntry")
        self.entry.place(x=20, y=100)

    def button_callback(self):
        print("button pressed")

def main():
    customtkinter.set_appearance_mode("dark")  # Modes: "System" (standard), "Dark", "Light"
    customtkinter.set_default_color_theme("blue")  # Themes: "blue" (standard), "green", "dark-blue"
    app = customtkinter.CTk()
    app.geometry("600x300+50+50")
    app.title("sample")
    Testclass(app)
    app.mainloop()

if __name__ == "__main__":
    main()


タイトルとURLをコピーしました