【问题标题】:How can I create a simple message box in Python?如何在 Python 中创建一个简单的消息框?
【发布时间】:2011-02-27 03:24:09
【问题描述】:

我正在寻找与 JavaScript 中的 alert() 相同的效果。

今天下午我使用 Twisted.web 编写了一个简单的基于 Web 的解释器。你基本上是通过一个表单提交一个 Python 代码块,然后客户端来抓取它并执行它。我希望能够制作一个简单的弹出消息,而不必每次都重新编写一大堆样板 wxPython 或 TkInter 代码(因为代码是通过表单提交然后消失的)。

我试过 tkMessageBox:

import tkMessageBox
tkMessageBox.showinfo(title="Greetings", message="Hello World!")

但这会在后台打开另一个带有 tk 图标的窗口。我不想要这个。我一直在寻找一些简单的 wxPython 代码,但它总是需要设置一个类并进入一个应用程序循环等。在 Python 中制作消息框没有简单、无捕获的方法吗?

【问题讨论】:

    标签: python wxpython tkinter


    【解决方案1】:

    您可以像这样使用导入和单行代码:

    import ctypes  # An included library with Python install.   
    ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1)
    

    或者像这样定义一个函数(Mbox):

    import ctypes  # An included library with Python install.
    def Mbox(title, text, style):
        return ctypes.windll.user32.MessageBoxW(0, text, title, style)
    Mbox('Your title', 'Your text', 1)
    

    注意样式如下:

    ##  Styles:
    ##  0 : OK
    ##  1 : OK | Cancel
    ##  2 : Abort | Retry | Ignore
    ##  3 : Yes | No | Cancel
    ##  4 : Yes | No
    ##  5 : Retry | Cancel 
    ##  6 : Cancel | Try Again | Continue
    

    玩得开心!

    注意:编辑为使用MessageBoxW 而不是MessageBoxA

    【讨论】:

    • 正是我想要的。 OP 听起来也是如此。应该标记为答案!
    • 嗯。也许我说得太早了。对于标题和消息,我只得到一个字符。奇怪...
    • 必须使用 MessageBoxW 而不是 MessageBoxA。
    • @CodeMonkey 在 python 3 中,使用 MessageBoxW 而不是 MessageBoxA
    • 如果要将消息框提升到其他窗口之上,请将其最后一个参数设置为 0x00001000
    【解决方案2】:

    你看过easygui吗?

    import easygui
    
    easygui.msgbox("This is a message!", title="simple gui")
    

    【讨论】:

    • 这不是tkinter,默认不发货,奇怪,谁有兴趣引入这么简单的功能带来不必要的依赖?
    • 实际上 gekannt,easygui 是 tkinter 的封装。是的,它是一个额外的依赖项,但它是一个单独的 python 文件。一些开发人员可能认为依赖项对于实现非常简单的 GUI 是值得的。
    【解决方案3】:

    您提供的代码很好!您只需要使用以下代码显式创建“后台的其他窗口”并将其隐藏:

    import Tkinter
    window = Tkinter.Tk()
    window.wm_withdraw()
    

    就在您的消息框之前。

    【讨论】:

    • 我必须在最后添加“window.destroy()”才能让它干净地退出。
    【解决方案4】:

    您还可以在撤回之前定位另一个窗口,以便定位您的消息

    #!/usr/bin/env python
    
    from Tkinter import *
    import tkMessageBox
    
    window = Tk()
    window.wm_withdraw()
    
    #message at x:200,y:200
    window.geometry("1x1+200+200")#remember its .geometry("WidthxHeight(+or-)X(+or-)Y")
    tkMessageBox.showerror(title="error",message="Error Message",parent=window)
    
    #centre screen message
    window.geometry("1x1+"+str(window.winfo_screenwidth()/2)+"+"+str(window.winfo_screenheight()/2))
    tkMessageBox.showinfo(title="Greetings", message="Hello World!")
    

    【讨论】:

    • 有什么方法可以让我们不用在tkMessageBox中点击ok按钮,自动处理?
    • @varsha_holla 这不是消息框的工作方式。您可能想考虑创建一个带有计时器的标准窗口。
    【解决方案5】:

    PyMsgBox 模块正是这样做的。它具有遵循 JavaScript 命名约定的消息框函数:alert()、confirm()、prompt() 和 password()(即 prompt(),但在键入时使用 *)。这些函数调用会阻塞,直到用户单击“确定/取消”按钮。它是一个跨平台的纯 Python 模块,在 tkinter 之外没有依赖项。

    安装:pip install PyMsgBox

    示例用法:

    import pymsgbox
    pymsgbox.alert('This is an alert!', 'Title')
    response = pymsgbox.prompt('What is your name?')
    

    完整文档在http://pymsgbox.readthedocs.org/en/latest/

    【讨论】:

    • 奇怪。你写它没有依赖关系,但是当我尝试使用它时它会打印AssertionError: Tkinter is required for pymsgbox
    • 我应该改变这一点:pymsgbox 在标准库之外没有依赖项,tkinter 是其中的一部分。你使用的是什么版本的 Python 和什么操作系统?
    • 对不起,我是Python的菜鸟,我以为所有的python库都是通过pip安装的,但实际上部分库是通过另一种方式安装的——使用系统包管理器。所以我使用我的包管理器安装了python-tk。我在 Debian 上使用 Python 2.7。
    • offtopic:但是 PyMsgBox/Tk 创建的消息框在我的 Debian 上看起来很丑
    【解决方案6】:

    在 Mac 上,python 标准库有一个名为 EasyDialogs 的模块。 http://www.averdevelopment.com/python/EasyDialogs.html也有一个(基于ctypes的)windows版本@

    如果它对您很重要:它使用原生对话框并且不像已经提到的easygui 那样依赖于 Tkinter,但它可能没有那么多功能。

    【讨论】:

      【解决方案7】:

      在 Windows 中,您可以使用ctypes with user32 library

      from ctypes import c_int, WINFUNCTYPE, windll
      from ctypes.wintypes import HWND, LPCSTR, UINT
      prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
      paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
      MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)
      
      MessageBox()
      MessageBox(text="Spam, spam, spam")
      MessageBox(flags=2, text="foo bar")
      

      【讨论】:

        【解决方案8】:
        import ctypes
        ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1)
        

        最后一个数字(这里是 1)可以改变窗口样式(不仅仅是按钮!):

        ## Button styles:
        # 0 : OK
        # 1 : OK | Cancel
        # 2 : Abort | Retry | Ignore
        # 3 : Yes | No | Cancel
        # 4 : Yes | No
        # 5 : Retry | No 
        # 6 : Cancel | Try Again | Continue
        
        ## To also change icon, add these values to previous number
        # 16 Stop-sign icon
        # 32 Question-mark icon
        # 48 Exclamation-point icon
        # 64 Information-sign icon consisting of an 'i' in a circle
        

        例如,

        ctypes.windll.user32.MessageBoxW(0, "That's an error", "Warning!", 16)
        

        会给this:

        【讨论】:

          【解决方案9】:

          使用

          from tkinter.messagebox import *
          Message([master], title="[title]", message="[message]")
          

          必须先创建主窗口。这是针对 Python 3 的。这不是针对 wxPython,而是针对 tkinter。

          【讨论】:

          • 在罗伯特的回答中查看我关于“import *”的评论。
          【解决方案10】:
          import sys
          from tkinter import *
          def mhello():
              pass
              return
          
          mGui = Tk()
          ment = StringVar()
          
          mGui.geometry('450x450+500+300')
          mGui.title('My youtube Tkinter')
          
          mlabel = Label(mGui,text ='my label').pack()
          
          mbutton = Button(mGui,text ='ok',command = mhello,fg = 'red',bg='blue').pack()
          
          mEntry = entry().pack 
          

          【讨论】:

          • 另外,为了大家对 PEP8 和 pythonic 的热爱,请戒掉“import *”。这很糟糕,好吗?
          【解决方案11】:

          您还可以在撤回之前定位另一个窗口,以便您定位您的消息

          from tkinter import *
          import tkinter.messagebox
          
          window = Tk()
          window.wm_withdraw()
          
          # message at x:200,y:200
          window.geometry("1x1+200+200")  # remember its.geometry("WidthxHeight(+or-)X(+or-)Y")
          tkinter.messagebox.showerror(title="error", message="Error Message", parent=window)
          
          # center screen message
          window.geometry(f"1x1+{round(window.winfo_screenwidth() / 2)}+{round(window.winfo_screenheight() / 2)}")
          tkinter.messagebox.showinfo(title="Greetings", message="Hello World!")
          

          请注意:这是 Lewis Cowles 的回答,只是 Python 3ified,因为自 python 2 以来 tkinter 发生了变化。如果您希望您的代码与 backwords 兼容,请执行以下操作:

          try:
              import tkinter
              import tkinter.messagebox
          except ModuleNotFoundError:
              import Tkinter as tkinter
              import tkMessageBox as tkinter.messagebox
          

          【讨论】:

            【解决方案12】:

            您可以使用pyautoguipymsgbox

            import pyautogui
            pyautogui.alert("This is a message box",title="Hello World")
            

            使用pymsgbox与使用pyautogui是一样的:

            import pymsgbox
            pymsgbox.alert("This is a message box",title="Hello World")
            

            【讨论】:

              【解决方案13】:

              不是最好的,这是我只使用 tkinter 的基本消息框。

              #Python 3.4
              from    tkinter import  messagebox  as  msg;
              import  tkinter as      tk;
              
              def MsgBox(title, text, style):
                  box = [
                      msg.showinfo,       msg.showwarning,    msg.showerror,
                      msg.askquestion,    msg.askyesno,       msg.askokcancel,        msg.askretrycancel,
              ];
              
              tk.Tk().withdraw(); #Hide Main Window.
              
              if style in range(7):
                  return box[style](title, text);
              
              if __name__ == '__main__':
              
              Return = MsgBox(#Use Like This.
                  'Basic Error Exemple',
              
                  ''.join( [
                      'The Basic Error Exemple a problem with test',                      '\n',
                      'and is unable to continue. The application must close.',           '\n\n',
                      'Error code Test',                                                  '\n',
                      'Would you like visit http://wwww.basic-error-exemple.com/ for',    '\n',
                      'help?',
                  ] ),
              
                  2,
              );
              
              print( Return );
              
              """
              Style   |   Type        |   Button      |   Return
              ------------------------------------------------------
              0           Info            Ok              'ok'
              1           Warning         Ok              'ok'
              2           Error           Ok              'ok'
              3           Question        Yes/No          'yes'/'no'
              4           YesNo           Yes/No          True/False
              5           OkCancel        Ok/Cancel       True/False
              6           RetryCancal     Retry/Cancel    True/False
              """
              

              【讨论】:

              • 你导入格式完全是疯子。您是老 COBOL 或 FORTRAN 程序员吗? ;-)
              【解决方案14】:

              查看我的 python 模块:pip install quickgui(需要 wxPython,但不需要 wxPython 知识) https://pypi.python.org/pypi/quickgui

              可以创建任意数量的输入,(比率、复选框、输入框),在单个 gui 上自动排列它们。

              【讨论】:

                【解决方案15】:

                最近的消息框版本是 prompt_box 模块。它有两个包:警报和消息。消息让您可以更好地控制该框,但输入时间更长。

                示例警报代码:

                import prompt_box
                
                prompt_box.alert('Hello') #This will output a dialog box with title Neutrino and the 
                #text you inputted. The buttons will be Yes, No and Cancel
                

                示例消息代码:

                import prompt_box
                
                prompt_box.message('Hello', 'Neutrino', 'You pressed yes', 'You pressed no', 'You 
                pressed cancel') #The first two are text and title, and the other three are what is 
                #printed when you press a certain button
                

                【讨论】:

                  【解决方案16】:

                  带线程的ctype模块

                  我正在使用 tkinter 消息框,但它会使我的代码崩溃。我不想找出原因,所以我改用 ctypes 模块。

                  例如:

                  import ctypes
                  ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1)
                  

                  我从 Arkelis

                  获得了该代码

                  我喜欢它不会使代码崩溃,因此我对其进行了处理并添加了一个线程,以便之后的代码可以运行。

                  我的代码示例

                  import ctypes
                  import threading
                  
                  
                  def MessageboxThread(buttonstyle, title, text, icon):
                      threading.Thread(
                          target=lambda: ctypes.windll.user32.MessageBoxW(buttonstyle, text, title, icon)
                      ).start()
                  
                  messagebox(0, "Your title", "Your text", 1)
                  

                  按钮样式和图标编号:

                  ## Button styles:
                  # 0 : OK
                  # 1 : OK | Cancel
                  # 2 : Abort | Retry | Ignore
                  # 3 : Yes | No | Cancel
                  # 4 : Yes | No
                  # 5 : Retry | No
                  # 6 : Cancel | Try Again | Continue
                  
                  ## To also change icon, add these values to previous number
                  # 16 Stop-sign icon
                  # 32 Question-mark icon
                  # 48 Exclamation-point icon
                  # 64 Information-sign icon consisting of an 'i' in a circle
                  

                  【讨论】:

                    【解决方案17】:

                    我必须在我现有的程序中添加一个消息框。在这种情况下,大多数答案都过于复杂。对于 Ubuntu 16.04 (Python 2.7.12) 上的 Linux 以及 Ubuntu 20.04 的未来校对,这是我的代码:

                    节目顶部

                    from __future__ import print_function       # Must be first import
                    
                    try:
                        import tkinter as tk
                        import tkinter.ttk as ttk
                        import tkinter.font as font
                        import tkinter.filedialog as filedialog
                        import tkinter.messagebox as messagebox
                        PYTHON_VER="3"
                    except ImportError: # Python 2
                        import Tkinter as tk
                        import ttk
                        import tkFont as font
                        import tkFileDialog as filedialog
                        import tkMessageBox as messagebox
                        PYTHON_VER="2"
                    

                    无论运行的是哪个 Python 版本,代码都将始终为 messagebox.,以供将来校对或向后兼容。我只需要在上面现有的代码中插入两行。

                    使用父窗口几何的消息框

                    ''' At least one song must be selected '''
                    if self.play_song_count == 0:
                        messagebox.showinfo(title="No Songs Selected", \
                            message="You must select at least one song!", \
                            parent=self.toplevel)
                        return
                    

                    如果歌曲计数为零,我已经有代码返回。所以我只需要在现有代码之间插入三行。

                    您可以通过使用父窗口引用来节省自己复杂的几何代码:

                    parent=self.toplevel
                    

                    另一个好处是,如果父窗口在程序启动后被移动,您的消息框仍会出现在可预测的位置。

                    【讨论】:

                      【解决方案18】:

                      如果你想要一个如果没有及时点击就会退出的消息框

                      import win32com.client
                      
                      WshShell = win32com.client.DispatchEx("WScript.Shell")
                      
                      # Working Example BtnCode = WshShell.Popup("Next update to run at ", 10, "Data Update", 4 + 32)
                      
                      # discriptions BtnCode = WshShell.Popup(message, delay(sec), title, style)
                      

                      【讨论】:

                        猜你喜欢
                        • 2015-05-13
                        • 1970-01-01
                        • 1970-01-01
                        • 2012-08-02
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 2022-01-18
                        相关资源
                        最近更新 更多