2

I use this to get yes/no from user but it opens an empty window:

from Tkinter import *
from tkMessageBox import *
if askyesno('Verify', 'Really quit?'):
    print "ok"

enter image description here

And this empty window doesnt go away. How can I prevent this?

This won't work:

    Tk().withdraw()
    showinfo('OK', 'Select month')
    print "line 677"
    root = Tk()
    root.title("Report month")
    months = ["Jan","Feb","Mar"]
    sel_list = []
    print "line 682"

    def get_sel():
        sel_list.append(Lb1.curselection())
        root.destroy()

    def cancel():
        root.destroy()

    B = Button(root, text ="OK", command = get_sel)
    C = Button(root, text ="Cancel", command = cancel)
    Lb1 = Listbox(root, selectmode=SINGLE)

    for i,j in enumerate(months):
        Lb1.insert(i,j)


    Lb1.pack()
    B.pack()
    C.pack()
    print "line 702"
    root.mainloop()

    for i in sel_list[0]:
        print months[int(i)]
    return months[int(sel_list[0][0])] 
alwbtc
  • 28,057
  • 62
  • 134
  • 188

2 Answers2

6

Tkinter requires that a root window exist before you can create any other widgets, windows or dialogs. If you try to create a dialog before creating a root window, tkinter will automatically create the root window for you.

The solution is to explicitly create a root window, then withdraw it if you don't want it to be visible.

You should always create exactly one instance of Tk, and your program should be designed to exit when that window is destroyed.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
2

Create root window explicitly, then withdraw.

from Tkinter import *
from tkMessageBox import *
Tk().withdraw()
askyesno('Verify', 'Really quit?')

Not beautiful solution, but it works.


UPDATE

Do not create the second Tk window.

from Tkinter import *
from tkMessageBox import *

root = Tk()
root.withdraw()
showinfo('OK', 'Please choose')
root.deiconify()

# Do not create another Tk window. reuse root.

root.title("Report month")
...
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • But i use other dialogs after this dialog, and for some reason your solution halts my program. any idea why? – alwbtc Jul 29 '13 at 19:19
  • Tk().withdraw() showinfo('OK', 'Please choose') root = Tk() root.title("Report month") months = ["Jan","Feb","Mar"] def get_sel(): sel_list.append(Lb1.curselection()) root.destroy() def cancel(): root.destroy() B = Button(root, text ="OK", command = get_sel) C = Button(root, text ="Cancel", command = cancel) Lb1 = Listbox(root, selectmode=SINGLE) for i,j in enumerate(months): Lb1.insert(i,j) Lb1.pack() B.pack() C.pack() print "line 702" root.mainloop() return months[int(sel_list[0][0])] – alwbtc Jul 29 '13 at 19:23
  • Could you post that in the body of your question? It's difficult to see what exactly is going on. – Al.Sal Jul 29 '13 at 19:35
  • @falsetru nice! what happened? – alwbtc Jul 29 '13 at 19:52
  • @alwbtc, Read Bryan Oakley's explanation. – falsetru Jul 29 '13 at 19:55