【Tkinter】イベント作業用のGUI画面をTkinterで作成してみた
はじめに
こんにちは、がんがんです。
インターン獲得に向けた就活を開始したり、講義や課題をこなしたりと
昨年よりも慌ただしく頑張っております。
以前からダンスイベントの業務改善についての記事を書いております。
最新記事ではLINE Botを作りました。
現在、8月に行われるイベントに向けてコードの改善を進めています。
せっかくならGUIにした方が楽かなと考え、とりあえず作ってみました。
参考記事
クラスのはなし
bindメソッドについて
サブウィンドウのはなし
STEP1 Tkinterの復習
まずはPythonのドキュメントなども使いながら使い方を復習します。
docs.python.org
作り直してみたコードはこんな感じです。
from tkinter import * class Application(Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.pack() master.title("Event GUI") master.configure(width="400", height="300", bg="blue") # master.geometry("400x300") # ボタンの追加 self.create_widgets() def create_widgets(self, side="top", text=None): self.quit = Button(self, text="QUIT", fg="red", command=self.master.destroy) self.quit.pack(side="top", fill="x") # Button self.button = Button(self, text="Hello World!", command=self.say_hi) self.btn1.pack(side=side, fill="x") def say_hi(self): print("hi there, everyone!") """ メイン部分 """ root = Tk() app = Application(master=root) root.mainloop()
ちゃんとQUITボタンが表示できています。
メモ:fill="x"
fill="x"
があるおかげでButton
を画面端まで広げることができました。
STEP2 イベント用に作り変える
次にcreate_widgets()
を改良して、自分が使いやすいようにします。
ボタンを押したときの動作は適当なものにしておきます。
def create_widgets(self, side="top", text=None): self.quit = Button(self, text="QUIT", fg="red", command=self.master.destroy) self.quit.pack(side="top", fill="x") self.cv = Canvas(self, width="400", height="30", bg="lightblue") self.cv.pack(fill="x") self.cv = Canvas(self, height="30", bg="lightblue") self.cv.pack(side="bottom", fill="x") # solo self.btn1 = Button(self, text="ソロのリストをシャッフル", command=self.say_hi) self.btn1.pack(side=side, fill="x") # 2on2 self.btn2 = Button(self, text="2on2のリストをシャッフル", command=self.say_hi) self.btn2.pack(side=side, fill="x") # rand self.btn_rand = Button(self, text="乱数開始", command=self.rand) self.btn_rand.pack(side=side, fill="x") def rand(self): sub_win = Toplevel() sub_win.geometry("200x100") button = Button(sub_win, text="サブウィンドウを閉じる", command=sub_win.destroy) button.grid()
ボタンを等間隔に上手く貼り付けられなかったのが改善点です。
Canvas()
を追加することにより色のゾーンを配置したりできました。
実行すると以下の画面になります。まずまずの出来です。
メモ:サブウインドウも作成可能
solo
や2on2
は別のクラスとつなぐ予定ですが、
乱数は別ウィンドウで扱ったほうが確認しやすいです。
そのため、ひな形としてrand関数はサブウィンドウにしています。