当你点击按钮时,我试图让按钮消失,并显示其他按钮。那么当"回来"单击按钮,我希望新按钮再次消失,原始按钮再次出现。
问题在于我不知道如何使函数从另一个函数中检索信息。如果我尝试对搜索(事件)函数中的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()
答案 0 :(得分:1)
最简单的方法是将所有内容都放入一个类中,其中所有函数都可以共享相同的self
命名空间。如果你想用另一个功能绑定按钮,请使用&#39;命令&#39;相反,除非您实际使用该事件。
这将结合在一起:
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()
在那里你可以调用小部件的destroy或pack_forget命令。