删除其他函数中定义的按钮

delete buttons defined in other function

我试图让一个按钮在您单击时消失,而其他按钮出现。然后,当单击 "back" 按钮时,我希望较新的按钮再次消失,并再次出现原始按钮。

问题是我不知道如何让一个函数从另一个函数检索信息。如果我尝试对搜索(事件)函数中的 search_button 执行任何操作,则 search_button 未定义,因为它仅在 main() 函数中定义。

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()

最简单的方法是将所有内容都放入 class,其中所有函数都可以共享相同的 self 命名空间。而且,如果您想将按下的按钮与另一个功能绑定,请改用 'command' ,除非您实际使用该事件。

这将归结为:

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()

您可以在那里调用小部件的销毁或 pack_forget 命令。