LoginSignup
2
5

More than 3 years have passed since last update.

Tkinterで押したボタンだけの色を変える方法

Posted at
example.py
def setnumber():
    column = -1
    row = 0
    root = tk.Tk()
    root.title('numbers')
    root.geometry('470x310')
    for i in range(101):
        if i > 0:
            if i%10 == 1:
                row += 1 
                column = -1
            column += 1
            text=f'{i}'
            btn = tk.Button(root, text=text)
            btn.grid(column=column, row=row)
            btn.config(command=collback(btn))
    root.mainloop()

def collback(btn):
    def nothing():
        btn.config(bg='#008000')
    return nothing

まず、setnumber()のところで1〜100までのボタンを作っています。すこしややこしく見えるのは10個作ったら改行するようにしたためです。そして、最後にコールバック関数としてcollback(btn)を指定し、変数btnを引数として渡します。その関数内でさらにnothingという関数を呼び出して色を変えるようにします。
これを実行すると以下のように押されたボタンだけが緑色になります。
Adobe_20200622_150740.jpg

2
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5