代码之家  ›  专栏  ›  技术社区  ›  Carson Myers

如何在Python中创建一个简单的消息框?

  •  87
  • Carson Myers  · 技术社区  · 14 年前

    我在寻找和你一样的效果 alert()

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

    我试过tkMessageBox:

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

    但这会在后台打开另一个带有tk图标的窗口。我不要这个。我正在寻找一些简单的wxPython代码,但它总是需要设置一个类和进入一个应用程序循环等,有没有简单的,捕捉免费的方式在Python消息框?

    12 回复  |  直到 14 年前
        1
  •  293
  •   agcala    4 年前

    您可以使用如下导入和单行代码:

    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

        2
  •  56
  •   Ryan Ginstrom    14 年前

    easygui ?

    import easygui
    
    easygui.msgbox("This is a message!", title="simple gui")
    
        3
  •  22
  •   Lewis Cowles    13 年前

    #!/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!")
    
        4
  •  20
  •   Jotaf    14 年前

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

    就在你的信箱前面。

        5
  •  13
  •   Roelant    4 年前

    安装方式: 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/

        6
  •  10
  •   Steven    14 年前

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

    easygui ,但它可能没有那么多功能。

        7
  •  10
  •   nbro kai    9 年前

    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
  •  7
  •   not2qubit    6 年前
    import ctypes
    ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 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 :

    enter image description here

        9
  •  1
  •   HD1920    11 年前

    使用

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

        10
  •  1
  •   Sanoob    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 
    
        11
  •  1
  •   Hexiro    5 年前

    此外,您还可以在撤消前定位另一个窗口,以便定位邮件

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

    try:
        import tkinter
        import tkinter.messagebox
    except ModuleNotFoundError:
        import Tkinter as tkinter
        import tkMessageBox as tkinter.messagebox
    
        12
  •  1
  •   Some Guy    5 年前

    你可以用 pyautogui pymsgbox :

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

    使用 pymsgbox公司 与使用相同 自动图形用户界面 :

    import pymsgbox
    pymsgbox.alert("This is a message box",title="Hello World")
    
        13
  •  0
  •   Creuil    9 年前

    不是最好的,这里是我的基本信息框只使用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
    """
    
        14
  •  0
  •   Jerry T    9 年前

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

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

        15
  •  0
  •   AtomProgrammer    5 年前

    最新的消息框版本是提示消息框模块。它有两个包:alert和message。消息使您可以更好地控制框,但需要更长的时间来键入。

    警报代码示例:

    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
  •  0
  •   Emerald Workers    5 年前

    带线程的ctype模块

    我使用的是tkinter messagebox,但它会使我的代码崩溃。我不想找出原因所以我用了 C类型 而不是模块。

    例如:

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

    我是从 阿凯利斯


    我喜欢它没有崩溃的代码,所以我在它的工作,并添加了线程,使代码后可以运行。

    我的代码示例

    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
  •  0
  •   WinEunuuchs2Unix    4 年前

    我不得不在我现有的程序中添加一个消息框。在这种情况下,大多数答案都过于复杂。对于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
    

    如果song count为零,我已经有了返回的代码。所以我只需要在现有代码之间插入三行代码。

    您可以使用父窗口参照来替代复杂的几何图形代码:

    parent=self.toplevel