If i have a main window in tkinter, then I click a button and it opens another window (secondary window) and minimize the first one and then i decide to click on a button on this second window to go back to the first window (like a "return button") how can i do this option of returning to the first window by pressing the botton on the second window in tkinter? Thanks!
import tkinter as tk
def funcion():
otra_ventana = tk.Toplevel(root)
root.iconify()
def funcion2():
vuelta_ventana.iconify()
root.deiconify()
root = tk.Tk()
boton = tk.Button(root, text="Abrir otra ventana", command=funcion)
boton2 = tk.Button(root, text="return", command=funcion2)
boton.pack()
root.mainloop()
2 Answers 2
Its pretty much the same, like you did with the first function "funcion". However you have to pack the button calling funcion2 in your tk.Toplevel.
Grouping your Windows / Frames in classes will help you in the long run, once your app gets larger.
import tkinter as tk
def main():
app = App()
app.mainloop()
class App(tk.Tk):
def __init__(self):
super().__init__()
self.geometry("300x300")
self.popup = None
self.buton = tk.Button(
self,
text="Abrir otra ventana",
command=self.funcion
)
self.buton.pack()
def funcion(self):
self.iconify()
if self.popup is None:
self.popup = MyToplevel(self)
else:
self.popup.deiconify()
class MyToplevel(tk.Toplevel):
def __init__(self, master):
super().__init__()
self.master = master
self.buton = tk.Button(
self,
text="Return",
command=self.funcion2
)
self.buton.pack()
def funcion2(self):
print("hello")
self.master.deiconify()
#self.destroy()#maybe more useful?
self.iconify()
if __name__ == '__main__':
main()
Comments
In addition to @caskuda 's answer, the directly corrected code of yours would be
import tkinter as tk
def funcion():
global otra_ventana
otra_ventana = tk.Toplevel(root)
return_button=tk.Button(otra_ventana,text='Return',command=funcion2).pack()
root.iconify()
def funcion2():
otra_ventana.iconify()
root.deiconify()
root = tk.Tk()
boton = tk.Button(root, text="Abrir otra ventana", command=funcion)
boton.pack()
root.mainloop()
And if your aim is to only switch windows, you could also try this approach
import tkinter as tk
def switch(target,window):
target.iconify()
window.deiconify()
root=tk.Tk()
button=tk.Button(root,text="Abrir otra ventana",command=lambda:switch(root,otra_ventana)).pack()
otra_ventana=tk.Toplevel(root)
return_button=tk.Button(otra_ventana,text='Return',command=lambda:switch(otra_ventana,root)).pack()
otra_ventana.withdraw()
root.mainloop()
Here I have initialized both the windows in the beginning and then used the .withdraw() method to hide/remove the second window from visibility. The use of lambda function lets us call the desired function along with the parameters when needed. The function switch() takes in 2 parameters, the former being the window to be iconified and the latter being the window to be deiconified.