Code:
import tkinter as tk
win = tk.Tk()
def all_state():
button_list = [button1, button2, button3]
for i in button_list:
if i['state'] == 'disabled':
i['state'] = 'active'
button1 = tk.Button(win, text = 'Click me', state = 'disabled', command = all_state)
button1.grid(column = 0, row = 0)
button2 = tk.Button(win, text = 'Now me', state = 'active', command = all_state)
button2.grid(column = 1, row = 0)
button3 = tk.Button(win, text = 'Now', state = 'active', command = all_state)
button3.grid(column = 2, row = 0)
win.mainloop()
Output:
When I click any other button, I get:
All buttons get enabled.
Question:
After I’ve clicked one of the buttons which aren’t disabled, I want this one to get disabled. Let’s say I clicked button button2. Thus, button2 will get disabled as shown:
The reason why I haven’t found a solution is because the button that will be selected is arbitrary, so I can’t think of how to do it.
Advertisement
Answer
Pass index when you call the all_state() also place button_list = [button1, button2, button3] outside the function.
Example:
import tkinter as tk
win = tk.Tk()
def all_state(index):
for btn in button_list:
btn['state'] = 'active'
button_list[index]['state'] = 'disabled'
button1 = tk.Button(win, text = 'Click me', state = 'disabled', command = lambda :all_state(0))
button1.grid(column = 0, row = 0)
button2 = tk.Button(win, text = 'Now me', state = 'active', command = lambda :all_state(1))
button2.grid(column = 1, row = 0)
button3 = tk.Button(win, text = 'Now', state = 'active', command = lambda :all_state(2))
button3.grid(column = 2, row = 0)
button_list = [button1, button2, button3]
win.mainloop()
Alternatively use event.widget to get the current button:
import tkinter as tk
win = tk.Tk()
def all_state(event):
btn = event.widget
for button in win.winfo_children():
if isinstance(button, tk.Button):
button['state'] = 'active'
btn['state'] = 'disabled'
button1 = tk.Button(win, text = 'Click me', state = 'disabled')
button1.bind('<1>', all_state)
button1.grid(column = 0, row = 0)
button2 = tk.Button(win, text = 'Now me', state = 'active')
button2.bind('<1>', all_state)
button2.grid(column = 1, row = 0)
button3 = tk.Button(win, text = 'Now', state = 'active')
button3.bind('<1>', all_state)
button3.grid(column = 2, row = 0)
win.mainloop()


