简体   繁体   中英

tkinter messagebox without buttons

在我的程序中,我只需要通知用户不要在没有键盘或鼠标的系统中按下物理按钮,而是要弹出等待消息,当系统再次就绪时该消息消失

There are two reasons you don't want a message box here.

First, the whole point of a message box is that it's a modal dialog with some standardized buttons, and you don't want those buttons.

Second, the whole point of a modal dialog is that it's modal—it runs its own event loop, and doesn't return until the dialog is dismissed. This means (unless you're using background threads) your app can't do anything while displaying it.


The first problem is easy to solve. tkMessageBox is just a simple wrapper around tkCommonDialog.Dialog . It's worth looking at the source to see just how simple it is to construct a dialog box that does what you want. But tkSimpleDialog.Dialog is even simpler than tkCommonDialog (hence the name). For example:

class WaitDialog(tkSimpleDialog.Dialog):
    def __init__(self, parent, title, message):
        self.message = message
        Dialog.__init__(self, parent, title=title, message=message)
    def body(self, master):
        Label(self, text=self.message).pack()
    def buttonbox(self):
        pass

def wait(message):
    WaitDialog(root, title='Wait', message=message)

That's all it takes to create a modal dialog with no buttons. Dialog Windows and the source to tkSimpleDialog have more details.


The second problem is even easier to solve: If you don't want a modal dialog, then all you want is a plain old Toplevel . You may want it to be transient , so it stays on top of the master, hides with it, doesn't show up on the taskbar, etc., and you may want to configure all kinds of other things. But basically, it's this simple:

def wait(message):
    win = Toplevel(root)
    win.transient()
    win.title('Wait')
    Label(win, text=message).pack()
    return win

Now you can call wait() and continue to run:

def wait_a_sec():
    win = wait('Just one second...')
    root.after(1000, win.destroy)

root = Tk()
button = Button(root, text='do something', command=wait_a_sec)
root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM