tkinterのクラス化の例

ソースコードを、クラス構造に書き換える手順を、より細かく説明します。

ステップ 0: ソースコードの準備

まず、これから編集するソースコードを準備しましょう。

クラス構造のソース

import tkinter as tk

class App(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.pack() #selfがframeになる
        self.create_widgets()

    def create_widgets(self):
        self.n = 0
        self.label =tk.Label(self, text="LABEL")
        self.Button = tk.Button(self,text="Button",command=self.btn_pushed)
        self.label.pack() #frameにlabelが追加される
        self.Button.pack() 

    def btn_pushed(self):
        self.n += 1
#        self.label.configure(text="button_pushed %d" % self.n)
        self.label.configure(text="button_pushed {}".format(self.n)) 
 #classの後に記入する 
root = tk.Tk()
root.title("Tkinter Class1")
app = App(master=root)
root.geometry("200x100")
app.mainloop()

ソースコード

import tkinter as tk

# Main Window 
root = tk.Tk()
root.title("Tkinter:Scale")
root.geometry("300x200")

# Define the scales
# スケール値を読み書きするIntVarオブジェクトの定義
red = tk.IntVar()
red.set(0)
blue = tk.IntVar()
blue.set(0)
green = tk.IntVar()
green.set(0)

# Change background color 
# n: ツマミを動かした位置の文字列(不使用)
# スケール位置を示すIntVarオブジェクトred,green,blueで値を読み取り
# ラベルの背景色を設定する。
def change_color(n):
#   color = '#%02x%02x%02x' % (red.get(), green.get(), blue.get())
    color = '#{:02x}{:02x}{:02x}'.format(red.get(), green.get(), blue.get())
    color_label.configure(bg=color)

# color_Label 
color_label = tk.Label(root, text='COLOR', bg='#000')
color_label.pack(fill='both');

# label: ラベル色を設定
# orient: 'h' 水平に設定
# length: スケールの幅を300ピクセルに設定
# from_, to: スケールの範囲を0から255 に設定
# variable: スケール値を読み書きするIntVarオブジェクトを設定
# command: ツマミを動かしたときに呼び出される関数 change_color を設定
s1 = tk.Scale(root, label='red', orient='h', length=300,
           from_=0, to=255, variable=red,
           command=change_color)

s2 = tk.Scale(root, label='blue', orient='h', length=300,
           from_=0, to=255, variable=blue,
           command=change_color)

s3 = tk.Scale(root, label='green', orient='h', length=300,
           from_=0, to=255, variable=green,
           command=change_color)

# Layout and styling widged
s1.pack(fill='both')
s2.pack(fill='both')
s3.pack(fill='both')

# Main
root.mainloop()

ステップ 1: Appクラスの枠組みを作る

これから、ソースコードの内容を整理するための「Appクラス」を作ります。

まず、空のクラスの枠組みだけを作ります。

import tkinter as tk

class App(tk.Frame):  # Appクラスの定義
    def __init__(self, master=None): # 初期化メソッドの定義
        super().__init__(master)
        self.pack()
        # ここにウィジェット定義を追加していく予定です
    
    # ここに他のメソッドを追加していく予定です

ステップ 2: ウィジェットの定義部分を移動する

ソースコードの `# Define the scales` から `s3.pack(fill='both')` までの部分を、`App` クラスの `init` メソッド 内に移動します。

移動する際に、`self.` を各ウィジェット名の前に追加します。例えば `red = tk.IntVar()` は `self.red = tk.IntVar()` に、`color_label = tk.Label(...)` は `self.color_label = tk.Label(...)` のように変更します。

import tkinter as tk

class App(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.pack()

        # Define the scales
        # スケール値を読み書きするIntVarオブジェクトの定義
        self.red = tk.IntVar() 
        self.red.set(0)
        self.blue = tk.IntVar()
        self.blue.set(0)
        self.green = tk.IntVar()
        self.green.set(0)

        # --- 省略 ---

        # Layout and styling widged
        self.s1.pack(fill='both')
        self.s2.pack(fill='both')
        self.s3.pack(fill='both')

# --- 省略 --- 

ステップ 3: change_color関数をメソッドに変更する

`change_color` 関数を `App` クラスのメソッドに変更します。

  • 関数定義をクラス内に移動します。

  • 第一引数に `self` を追加します。

  • 関数内で使用されている変数 (`red`, `green`, `blue`, `color_label`) の前に `self.` を追加します。

import tkinter as tk

class App(tk.Frame):
    # ... (ステップ 2 のコード)

    def change_color(self, n):
        color = '#{:02x}{:02x}{:02x}'.format(self.red.get(), self.green.get(), self.blue.get())
        self.color_label.configure(bg=color)
    
    # ... (ステップ 2 のコード)

ステップ 4: `command` の設定を修正する

`tk.Scale` の `command` に指定している `change_color` を、`self.change_color` に変更します。

        # ...

        self.s1 = tk.Scale(self, label='red', orient='h', length=300,
                          from_=0, to=255, variable=self.red,
                          command=self.change_color) #ここを変更 

        # ...

ステップ 5: Appクラスのインスタンス化

最後に、 `App` クラスのインスタンスを作成し、メインウィンドウに配置します。

import tkinter as tk

# ... (ステップ 1~4 の Appクラスの定義)

# Main Window 
root = tk.Tk()
root.title("Tkinter:Scale")
root.geometry("300x200")

# Appクラスのインスタンスを作成
app = App(master=root) 

# Main
root.mainloop()

これで、ソースコードがクラス構造に書き換えられました。

完成したソース

import tkinter as tk

class App(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.pack()

        # Define the scales
        self.red = tk.IntVar()
        self.red.set(0)
        self.blue = tk.IntVar()
        self.blue.set(0)
        self.green = tk.IntVar()
        self.green.set(0)

        # color_Label 
        self.color_label = tk.Label(self, text='COLOR', bg='#000')
        self.color_label.pack(fill='both')

        self.s1 = tk.Scale(self, label='red', orient='h', length=300,
                          from_=0, to=255, variable=self.red,
                          command=self.change_color)

        self.s2 = tk.Scale(self, label='blue', orient='h', length=300,
                          from_=0, to=255, variable=self.blue,
                          command=self.change_color)

        self.s3 = tk.Scale(self, label='green', orient='h', length=300,
                          from_=0, to=255, variable=self.green,
                          command=self.change_color)

        self.s1.pack(fill='both')
        self.s2.pack(fill='both')
        self.s3.pack(fill='both')

    # change_colorメソッド
    def change_color(self, n):
        color = '#{:02x}{:02x}{:02x}'.format(self.red.get(), self.green.get(), self.blue.get())
        self.color_label.configure(bg=color)

# Main Window 
root = tk.Tk()
root.title("Tkinter:Scale")
root.geometry("300x200")

app = App(master=root) 

# Main
root.mainloop()

この記事が気に入ったらサポートをしてみませんか?