Python: tkinter askyesno method opens an empty window

纵然是瞬间 提交于 2019-12-11 10:29:41

问题


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"

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])] 

回答1:


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")
...



回答2:


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.



来源:https://stackoverflow.com/questions/17931107/python-tkinter-askyesno-method-opens-an-empty-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!