Tkinter Grid_Forget Is Clearing the Frame

Tkinter grid_forget is clearing the frame

seperate the grid method and it will work. Every function in Python needs to return something and if nothing is returned 'None' will set by default. So your variable will become myLabel = None.

Now that you know why that is bad behavior your should also do it for every other widget in your code.

.

Explaination

To show you what went wrong in your code look at this bit of code here:

import tkinter as tk

root = tk.Tk()
x1 = tk.Label(text='x1')
x1.pack()
print(x1)
root.mainloop()

the Output should be:

.!label

This tells me that x1 is assigned to the label.

Now take a look at this:

import tkinter as tk

root = tk.Tk()

x1 = tk.Label(text='x1')
returned_by_layoutmanager = x1.pack()
print(x1)
print(returned_by_layoutmanager)
root.mainloop()

Your Output will be:

.!label
None

If you may noticed, None was returned by the layoutmanger.
This is how python works, as soon as somthing is returned by a method/function the interpreter returns to the point he started reading the function/method. It's like the function tells I'm done keep going.

So if you do this:

import tkinter as tk

root = tk.Tk()
x2 = tk.Label(text='x2').pack()
print(x2)
root.mainloop()

Your Output will be:

None

To understand why None is assigned to x2 and not to .!label by this line here:

x2 = tk.Label(text='x2').pack()

Try this:

import tkinter as tk

root = tk.Tk()

x1 = tk.Label(text='x1')
x1 = x1.pack()
print(x1)

root.mainloop()

Your Output will be:

None

Its just the same as you do it in your oneliner. First you assign x1 to the instance of Label class and then you assign x1 to None.

Python Tkinter clearing a frame

pack_forget and grid_forget will only remove widgets from view, it doesn't destroy them. If you don't plan on re-using the widgets, your only real choice is to destroy them with the destroy method.

To do that you have two choices: destroy each one individually, or destroy the frame which will cause all of its children to be destroyed. The latter is generally the easiest and most effective.

Since you claim you don't want to destroy the container frame, create a secondary frame. Have this secondary frame be the container for all the widgets you want to delete, and then put this one frame inside the parent you do not want to destroy. Then, it's just a matter of destroying this one frame and all of the interior widgets will be destroyed along with it.

Python, Tkinter; How to use grid_forget() when deselecting a check box?

Would something like this work?

def show_name3():
if self.check_var4.get() == 1:
self.name3.grid(row=3, column=1, sticky='E', padx=15, pady=5, ipadx=15, ipady=5)
else:
self.name3.grid_forget()

It will get the value of check_var, which indicates if the Checkbutton is on or off. If it is on, it will place name3 with the grid manager. If it is off, it will remove name3 from the grid manager.



Related Topics



Leave a reply



Submit