[Tutor] how to "forget" some checkbuttons on a window
Peter Otten
__peter__ at web.de
Tue May 19 03:44:08 EDT 2020
Chris Roy-Smith wrote:
> Hi
> Python 3.6
> Ubuntu 18.04
>
> I am trying to hide some Checkbuttons.
>
> here is my code:
> =====================================
> #! /usr/bin/python3
> from tkinter import *
> testDat=[0,1,2,3,4,5,6,7,8,9]
> def remove(e):
> for i in range(9):
> r=var[i].get()
> if r==True:
Everytime you do this a kitten dies ;)
Don't compare to True or False, write
if r:
instead. You are around long enough to know.
> e[i].forget()
>
> master=Tk()
> master.title('experiment')
>
> e=[" " for i in range(len(testDat))]
> var=[IntVar() for i in range(len(testDat))]
> for i in range(len(testDat)):
> e[i]=Checkbutton(master, text=str(i), variable=var[i],
> onvalue=True, offvalue=False).grid(row=i, column=0)
> Button(master, text='remove checked', command=lambda i=e:
> remove(i)).grid(row=11, column=0)
>
> master.mainloop()
>
> ===================================
> I get the following error
> ===================================
>
> Exception in Tkinter callback
> Traceback (most recent call last):
> File "/usr/lib/python3.6/tkinter/__init__.py", line 1705, in __call__
> return self.func(*args)
> File "./frames.py", line 17, in <lambda>
> Button(master, text='remove checked', command=lambda i=e:
> remove(i)).grid(row=11, column=0)
> File "./frames.py", line 8, in remove
> e[i].forget()
> AttributeError: 'NoneType' object has no attribute 'forget'
>
> =================================
>
> I was expecting that any checked Checkbuttons to disappear, Obviously
> this doesn't happen, as I get the error on that line.
>
> How do I go about correcting my code?
You cannot chain
checkbutton = Checkbutton(...).grid(...)
assert checkbutton is None
because the grid() returns None. You need to proceed in steps:
checkbutton = Checkbutton(...)
assert checkbutton is not None
checkbutton.grid(...)
Also, when I ran your code
checkbutton.forget()
seemed to have no effect. Instead I had to use
checkbutton.grid_forget()
> Regards,
> Chris Roy-Smith
More information about the Tutor
mailing list