[Tutor] how to "forget" some checkbuttons on a window

Chris Roy-Smith chris_roysmith at internode.on.net
Tue May 19 04:37:25 EDT 2020


On 19/5/20 5:44 pm, Peter Otten wrote:
> 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.
Hi Peter,
Thank you for pointing this out, never thought of that.
> 
>>               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(...)

Perhaps I should use 2 lines for this always, I have been caught with 
this some time ago, but didn't understand why 2 lines needed here.
> 
> Also, when I ran your code
> 
> checkbutton.forget()
> 
> seemed to have no effect. Instead I had to use
> 
> checkbutton.grid_forget()

I got a bit confused here, as I found some people saying .grid_forget, 
and some saying forget_grid! ...I know, don't believe everything on the 
internet!
> 
>> Regards,
>> Chris Roy-Smith
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
> 



More information about the Tutor mailing list