Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

python - Tkinter: Change button background when pressed

I know that I should use bttn['text'] = 'text', but I'm creating buttons by for. I want to button changing its colour for red when it presssed.

Example code:

from tkinter import *

root = Tk()

btn = [i for i in range(10)]

for i in range(len(btn)):
    b = Button(root, text=str(i), command=lambda c=i: print(i))
    b.pack()

root.mainloop()

What need I replace instead print(i)?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To do that you need to pass the Button object "b" into the callback function. In order to do that you need to set the command on the next line, so that the "b" object is available. Like this:

from tkinter import *

root = Tk()

def change_to_red(bttn):
    bttn.config(bg='red', activebackground='red') # same as bttn['bg'] = 'red';  bttn['activebackground'] = 'red'
    print(bttn['text'])

btn = [i for i in range(10)]

for i in range(len(btn)):
    b = Button(root, text=str(i), width=6)
    b.config(command=lambda c=b: change_to_red(c))
    b.pack()

root.mainloop()

But actually this would be a great place to learn about subclasses. You can modify tkinter's Button to make your own type of Button that does what you want in addition to it's normal actions:

import tkinter as tk

class Desync192Button(tk.Button):
    def __init__(self, master=None, **kwargs):
        self.command = kwargs.pop('command', None)
        super().__init__(master, command=self.on_click, **kwargs)
    def on_click(self):
        self.config(bg='red', activebackground='red')
        if self.command: self.command()

# demo:
root = tk.Tk()

for i in range(10):
    b = Desync192Button(root, text=i, width=6, command=lambda c=i: print(c))
    b.pack()

root.mainloop()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...