-1

Here is my code:

from tkinter import *

OPTIONS = ["Available","Busy","Invisible","Away"]

now = Toplevel()
variable = StringVar(now)
variable.set(OPTIONS[0]) # default value
details = {"U_status":""}
def verify():
    global u_status
    details["U_status"]=variable.get()
    print ("value is:" + variable.get())
    now.destroy()
def status():
    w = OptionMenu(now, variable, *OPTIONS)
    w.pack()
    button = Button(now, text="OK", command=verify, relief='flat')
    button.pack()
if __name__=='__main__':
    status()
    mainloop()

While running the above code, along with the window (I wanted) another empty window appears. Can anyone figure out what is wrong in this code?

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
Code Carbonate
  • 640
  • 10
  • 18

2 Answers2

2

Here now = Toplevel() should be replaced with Tk(), like:

now = Tk()

When you use Toplevel() a Tk() window is made in the background, if its not already made(your case), and that is the reason you are getting a blank new window. Actually that blank window is your main window.

Toplevel() is used to make child windows for the parent Tk() windows,ie, if you want sub windows within your main window(now), you will use Toplevel(). Because more than one Tk() in your code will cause some errors later on.

Delrius Euphoria
  • 14,910
  • 3
  • 15
  • 46
0

The blank window is actually the root window of your app that tkinter creates by default. You probably want to be explicit, and create a tk.Tk() root, and keep a reference to it.

New windows can be spawned and destroyed at leisure; your app will continue to exist as long as you keep the root active.

Maybe something like this:

import tkinter as tk


def verify():
    now = tk.Toplevel(root)
    details["U_status"] = variable.get()
    txt = f'value is: {details["U_status"]}'
    tk.Label(now, text=txt).pack()
    now.after(3000, now.destroy)
    
def status():
    tk.OptionMenu(root, variable, *OPTIONS).pack()
    tk.Button(root, text="OK", command=verify, relief='flat').pack()
    
    
if __name__=='__main__':
    
    OPTIONS = ["Available", "Busy", "Invisible", "Away"]
    
    root = tk.Tk()
    variable = tk.StringVar(root)
    variable.set(OPTIONS[0])
    details = {"U_status": ""}
    status()
    root.mainloop()
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80