PythonでGUIを作成する際には、Tkinterがよく使用されます。しかし、デザインが少し古めかしいと感じる方もいるかもしれません。そこで、今回はTomSchimanskyのCustomTkinterを使用して、おしゃれで学習量のちょうどいいGUIを作成してみましょう。

CustomTkinterの基本的なコード

まずは、CustomTkinterをインストールします。

pip install customtkinter

次に、テキスト入力欄とボタンがあるシンプルなGUIのコードを見てみましょう。

import customtkinter

FONT_TYPE = "meiryo"

class App(customtkinter.CTk):
    def __init__(self):
        super().__init__()
        self.fonts = (FONT_TYPE, 15)
        self.geometry("350x200")
        self.title("Basic GUI")
        self.setup_form()

    def setup_form(self):
        customtkinter.set_appearance_mode("dark")
        customtkinter.set_default_color_theme("blue")
        self.textbox = customtkinter.CTkEntry(master=self, placeholder_text="テキストを入力してください", width=220, font=self.fonts)
        self.textbox.place(x=60, y=50)
        self.button = customtkinter.CTkButton(master=self, text="クリックしてね", command=self.button_function, font=self.fonts)
        self.button.place(x=100, y=100)

    def button_function(self):
        print(self.textbox.get())

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

このコードでは、ウィジェットの配置にplaceを使用していますが、placeは極力使用せず、gridpackを使用することをおすすめします。

gridとFrameについて

ウィジェットをGUIに配置する際に、placeを使用して一つずつウィジェットの位置を指定すると、ボタンの配置を変えたくなったり、フォントサイズを変更したくなったときなどに、大変な変更対応をすることになります。そこで、ここではgridFrameを使用してみましょう。

gridは、ウィンドウをグリッド分割して、列、行(Col, Row)で指定した位置にウィジェットを置くことができます。例えば、以下のようにウィジェットを配置する際にplaceの代わりにgridを使用することで、ウィジェットの配置が容易になります。

self.textbox1 = customtkinter.CTkEntry(master=self, placeholder_text="テキストボックス1", width=150, font=self.fonts)
self.textbox1.grid(row=0, column=0, padx=10, pady=20)
self.button1 = customtkinter.CTkButton(master=self, text="ボタン1", command=self.button_function, font=self.fonts)
self.button1.grid(row=0, column=1, padx=10, pady=20)
self.textbox2 = customtkinter.CTkEntry(master=self, placeholder_text="テキストボックス2", width=150, font=self.fonts)
self.textbox2.grid(row=1, column=0, padx=10, pady=20)
self.button2 = customtkinter.CTkButton(master=self, text="ボタン2", command=self.button_function, font=self.fonts)
self.button2.grid(row=1, column=1, padx=10, pady=20)

以上、PythonでGUIレイアウトを作成する方法について説明しました。これらの知識を活用して、自分だけのGUIを作成してみてください。

投稿者 admin

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です