简体   繁体   中英

Destroy tkinter frame within method

This is Python version 3.6.2

Below is my method of getting news through the Google New's RSS feed. I am trying to delete the frame so that when the method is called again the text is erased and replaced with new text. How would I go about removing the frame? I would like to delete it so when it is called only 5 news articles are displayed instead of stacking upon each other. I currently have a Bottom Frame and inside that I have a Bottom Left Frame, a News Frame which holds all the news article labels, and a Newspaper Image frame, which contains all the images. I am trying to delete the News Frame so when I call my get_news method it's a fresh frame with no labels. Any help would be appreciated. This is the GUI of the project

def get_news():
    try:
        feed = feedparser.parse(google_news_url)

        for post in feed.entries[0:5]:
            newspaper_image = Label(frame_newspaper, bg='black', fg='white')
            newspaper_image.configure(image=photo)
            newspaper_image.icon = photo

            label_news = Label(frame_news, bg='black', fg='white', font=newsFont)
            label_news['text'] = post['title']
            newspaper_image.pack(side=TOP, anchor=W)
            label_news.pack(side=TOP, anchor=W)
        frame_news.after(600000, get_news)

    except Exception as e:
        traceback.print_exc()
        print("Error: %s. Cannot get news." % e)

In the beginning of the method you have to get the children of the frames and destroy them. I did it like this:

    for widget in frame_news.winfo_children():
        widget.destroy()
    for i in frame_newspaper.winfo_children():
        i.destroy()

This clears all the labels that were created during the loop. Then when the loop is called new labels are created taking the place of the old ones.

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