Using screens in Tkinter-Python

Asked

Viewed 860 times

1

You guys all right? So, I’m doing a screen test program, its function would be just a test consisting of: Open a screen (called by a button) and close the one that was open. I don’t know how to do this, I’ve tried using loops, but unsuccessfully... Code: from Tkinter import *

def bt_click():

    janela2 = Tk()
    teste2 = janela2
    janela2.title("Teste2")
    janela2.geometry("200x200+300+300")


janela = Tk()

bt1 = Button(janela, text = "Click me", command = bt_click)

bt1.place(x = 50, y = 100)

janela["bg"] = "green"
janela.geometry("300x300+300+300")
janela.mainloop()

my idea was: Put the whole window in a while loop, and do so:

teste = 1
while teste == 1:
   janela() ...

and when it called the other window(window 2), at the end of the function, make the test variable turn 2 or any other number, but I think that as the test variable falls within the function of the window2, it becomes local.. How to proceed? Hugs

  • Sorry for the mess of the code, when I passed to this text editor, it got messy :(

  • When paste code here, select it and click on the formatting button {} upstairs.

1 answer

1

You have to have a reference outside the function that creates the new window for the created window - then just call the method .destroy hers.
And that doesn’t have to be a global variable - you can have a list that contains all the windows created - without having a variable with a fixed name for each one.

import tkinter

raiz = None
janelas = []

def criar():
    janela = tkinter.Toplevel(raiz)
    janela.title("janela  {}".format(len(janelas)))
    janelas.append(janela)

def destruir():
    janelas.pop(0).destroy()

def principal():
    global raiz
    raiz = tkinter.Tk()
    bt_criar = tkinter.Button(raiz, text="criar", command=criar)
    bt_destruir = tkinter.Button(raiz, text="destruir", command=destruir)
    bt_criar.pack(side="left")
    bt_destruir.pack(side="right")

principal()
tkinter.mainloop()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.