简体   繁体   中英

Disable tkinter checkbuttons when a button is pressed

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM