Elliott Johnson
Elliott Johnson

Reputation: 59

delete buttons defined in other function

I'm trying to get a button to dissapear when you click it, and other buttons to appear. Then when the "back" button is clicked, I want the newer buttons to dissapear again, and the original button to appear again.

The problem is that I don't know how to make a function retrieve information from another function. If I try to do anything to the search_button in the search(event) function, the search_button is not defined because it was only defined in the main() function.

import tkinter as tk
window = tk.Tk()
def search(event):

    #insert "delete search_button" logic here

    easy_button = tk.Button(window, text = "Easy")
    easy_button.bind("<Button-1>", easy_search)    
    easy_button.pack()

    back_button = tk.Button(window, text = "Back")
    back_button.bind("<Button-1>", back_button1) #had to put 1 on end here. It seems back_button is predefined as an object
    back_button.pack()

def easy_search(event):
    #does a bunch of stuff that doesn't matter for this question
    pass

def back_button1(event):
    #this should delete easy_button and reinitiate search_button
    pass

def main():

    search_button = tk.Button(window, text = "Search")
    search_button.bind("<Button-1>", search)    
    search_button.pack()

main()
window.mainloop()

Upvotes: 0

Views: 536

Answers (1)

Taku
Taku

Reputation: 33754

The easiest way is to make everything into a class, in which all your functions could share the same self namespace. And that if you want to bind the button pressed with another function, use 'command' instead, unless you're actually using the event.

That will come together to this:

import tkinter as tk
window = tk.Tk()


class Search:
    def __init__(self):
        self.search_button = tk.Button(window, text = "Search")
        self.search_button['command'] = self.search   
        self.search_button.pack()
    def search(self):
        self.search_button.pack_forget() # or .destroy() if you're never going to use it again
        self.easy_button = tk.Button(window, text = "Easy")
        self.easy_button['command'] = self.easy_search   
        self.easy_button.pack()

        self.back_button = tk.Button(window, text = "Back")
        self.back_button['command'] = self.back_button1
        self.back_button.pack()

    def easy_search(self):
        #does a bunch of stuff that doesn't matter for this question
        pass

    def back_button1(self):
    #this should delete easy_button and reinitiate search_button
        pass


widgets = Search()
window.mainloop()

There you can call the widget's destroy or pack_forget command.

Upvotes: 1

Related Questions