Python.use(better,Tkinter)《余録》Checkbutton

記事一覧 Python.use(better, Tkinter)《Python3.1》

Checkbutton

《著》森こねこ・小粒ちゃん+∞《監修》小泉ひよ子とタマゴ倶楽部
第0版♪1993/11/25

概要

Tkinter/Python によるオブジェクト指向プログラミングへの扉を開きます。
※ Tcl/Tk で作成した例題を、Tkinter で再構成しました。

事例:

次のコードを実行すると、ウィンドウが現われます。

>>> tips()


  • 〔右側〕項目(ボタン)を選択すると、
  • 〔左側〕キャンバスの色が変化します。
    • キャンバスには、3原色を加法混色した色が表示されます。
def tips():
    class TIPS(object):
        colors = (
            "black", "red", "green", "yellow",
            "blue", "magenta", "cyan", "white",
            )

        def __init__(self, master, canvas, index, text, onvalue, values):
            self.values = values
            self.canvas = canvas
            self.widget = Checkbutton(
                master,
                text=text,
                onvalue=onvalue,
                offvalue=0,
                variable=values[index],
                command=self,
                )
            self.widget.pack(anchor=W)

        def __call__(self):
            bg = self.colors[sum(e.get() for e in self.values)]
            self.canvas.config(bg=bg)

    ## ----------------------------------------
    root = Tk()
    root.title("Checkbutton")
    root.config(padx=8, pady=4)

    canvas = Canvas(
        root,
        width=100, height=100, relief=RIDGE, borderwidth=5,
        )
    frame = Frame(root)

    s = "red", "green", "blue",
    values = [IntVar() for _ in s]
    for i, e in enumerate(s):
        onvalue = 2**i
        TIPS(frame, canvas, i, e, onvalue, values)
        
    canvas.grid(row=0, column=0)
    frame .grid(row=0, column=1)
    root.mainloop()