Cardboard
Cardboard

Reputation: 11

Python 3 Tkinter, Create window if window is not already created

I have been creating a very simple password generator. In the brackets var is the password which has been generated. I have been trying to create a window for my output. The Idea is if the window exists then the program lifts the window. Otherwise it creates the window. Then the program creates a label which is the password.

The Issue is, it creates a new window every time.

def outpt_(var):
    try: 
        outpt.lift()
    except:
        outpt = tk.Toplevel()
        outpt.title("Output Secure")
        outpt.geometry("350x120")
    outpot = tk.Label(outpt, text = var, font=("DejaVu Sans", 11)).pack()

Upvotes: 0

Views: 90

Answers (2)

Kevin Mayo
Kevin Mayo

Reputation: 1159

The problem is that:

outpt is a local variable in the function.

The issue is, it creates a new window every time.

That's because it will always raise NameError exception. The next time you call this function.python wouldn't find your outpt.

Three solutions:

  1. Use a global variable.
  2. Use OOP
  3. You also could try:
root = tk.Tk()

def outpt_(var):
    try: 
        root.outpt.lift()
    except:
        root.outpt = tk.Toplevel()
        root.outpt.title("Output Secure")
        root.outpt.geometry("350x120")
    outpot = tk.Label(root.outpt, text = var, font=("DejaVu Sans", 11)).pack()

Upvotes: 1

10 Rep
10 Rep

Reputation: 2270

The reason it generates a new window every time is that when you call tk.Toplevel, it creates a new window. Even if name it the same thing, it won't recall it, it will create a new one.

I think you need to use .withdraw(). The idea is you create the window at the beginning, then you .withdraw() it. This will simply hide it, and when you need it back you can use .deiconify().

Read about .withdraw() and deiconify().

Full code:

def outpt_(var):
    try: 
        outpt.withdraw()
    except:
        outpt.deiconify()
    outpt = tk.Label(outpt, text = var, font=("DejaVu Sans", 11)).pack()

Hope this helps!

Upvotes: 0

Related Questions