Home > other >  Disable tkinter checkbuttons when a button is pressed
Disable tkinter checkbuttons when a button is pressed

Time:06-18

I am working with Tkinter and I am trying to use some checkbuttons.

Here's what I am doing:

  1. get a list with some ingredients
  2. get a tkinter GUI with some checkbuttons (one for each ingredient)
  3. select some of the checkbuttons (tick them)
  4. press a button and obtain a list containing the ingredients I selected

What I am trying to do now is the following:

  1. make the checkbuttons unusable (so, disable them) after the "confirmation" button is pressed.

My code is from the accepted answer here of my other question (I did not make much further progress in the checkbuttons of my application). I report it below:

import tkinter as tk

root = tk.Tk() 
INGREDIENTS = ['cheese', 'ham', 'pickle', 'mustard', 'lettuce'] 
txt = tk.Text(root, width=40, height=20) 
variables = [] 
for i in INGREDIENTS: 
    variables.append( tk.IntVar( value = 0 ) ) 
    cb = tk.Checkbutton( txt, text = i, variable = variables[-1] ) 
    txt.window_create( "end", window=cb ) 
    txt.insert( "end", "\n" ) 
txt.pack() 
 
def read_ticks():  
    result = [ ing for ing, cb in zip( INGREDIENTS, variables ) if cb.get()>0 ] 
    print( result ) 
  
but = tk.Button( root, text = 'Read', command = read_ticks) 
but.pack()  
  
root.mainloop()

Thank you in advance.

CodePudding user response:

Below a solution based on remembering references to the checkbuttons in a list, but it should be also possible to get these references by querying all of the children of root excluding the tk.Button from being disabled.

import tkinter as tk

root = tk.Tk() 
INGREDIENTS = ['cheese', 'ham', 'pickle', 'mustard', 'lettuce'] 
txt = tk.Text(root, width=40, height=20) 
variables = []
buttons   = []

for i in INGREDIENTS: 
    variables.append( tk.IntVar( value = 0 ) ) 
    cb = tk.Checkbutton( txt, text = i, variable = variables[-1] )
    buttons.append(cb)
    txt.window_create( "end", window=cb ) 
    txt.insert( "end", "\n" ) 
txt.pack() 
 
def read_ticks():  
    result = [ ing for ing, cb in zip( INGREDIENTS, variables ) if cb.get()>0 ] 
    print( result )
    for button in buttons:
        button.config(state = 'disabled')
            
  
but = tk.Button( root, text = 'Read', command = read_ticks) 
but.pack()  
  
root.mainloop()
  • Related