简体   繁体   English

没有按钮的tkinter消息框

[英]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 . tkMessageBox只是围绕一个简单的包装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). 但是tkSimpleDialog.Dialog甚至比tkCommonDialog更简单(因此得名)。 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. Dialog WindowstkSimpleDialog的来源有更多详细信息。


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 . 第二个问题甚至更容易解决:如果您不希望使用模式对话框,那么您所想要的只是一个普通的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. 您可能希望它是transient ,因此它会停留在母版之上,与母版一起隐藏,不在任务栏上显示等,并且您可能还想配置各种其他内容。 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: 现在您可以调用wait()并继续运行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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