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
は極力使用せず、grid
やpack
を使用することをおすすめします。
gridとFrameについて
ウィジェットをGUIに配置する際に、place
を使用して一つずつウィジェットの位置を指定すると、ボタンの配置を変えたくなったり、フォントサイズを変更したくなったときなどに、大変な変更対応をすることになります。そこで、ここではgrid
とFrame
を使用してみましょう。
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を作成してみてください。