How to delete (or de-grid) Tkinter GUI objects stored in a list (Python)

三世轮回 提交于 2019-12-24 14:58:27

问题


I'm trying to make a program that creates some random amount of GUI objects in Tkinter and stores them in a list. Here (in the code below) I have a for loop that creates a random amount of radio buttons. Each time a radio button object is created it is stored in the list 'GUIobjects'. I do this because otherwise I have no way of accessing the GUI objects later on. What I need to know, now, is how to delete or de-grid the objects.

I have tried self.radioButton.grid_forget(), but this only de-grids the last object created. I'm not sure of there's a way to access each object in the list and use .grid_forget(). If there is, that would be an option.

For now all I need to know is how to delete or de-grid the GUI objects after I create all of them.

from tkinter import *
import random

class App(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.addButton()

    def addButton(self)
        GUIobjects = []

        randInt = random.randint(3, 10)
        self.radVar = IntVar()
        for x in range(2, randInt):
            self.radioButton = Radiobutton(self, text = "Button", variable = self.RadVar, value = x)
            self.radioButton.grid(row = x)

    print(GUIobjects)
    # This is to show that one more object has been created than appears on the screen

    self.radioButton.grid_forget()
    # This de-grid's the last object created, but I need to de-grid all of them

def main():
    a = App()
    a.mainloop()

if __name__ == "__main__":
    main()

As of right now, I try to de-grid the objects right after creating all of them. Once I find out how to de-grid each object, I will somehow need to make a button that de-grid's them (as compared to de-griding them right after they have been created). This button should be able to be put in a method other than 'addButtons' but still in the 'App' class.

Thanks!


回答1:


You need to store references to each object. Create an empty list and append the reference to the list inside your loop.

self.radioButtons = []
for x in range(2, randInt):
        self.radioButtons.append(Radiobutton(self, text = "Button", variable = self.RadVar, value = x))
        self.radioButtons[-1].grid(row = x) # layout the most recent one

They won't be garbage collected unless you delete the reference as well.

for button in self.radioButtons:
    button.grid_forget()
del self.radioButtons


来源:https://stackoverflow.com/questions/34054619/how-to-delete-or-de-grid-tkinter-gui-objects-stored-in-a-list-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!