首页 文章

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

提问于
浏览
83

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

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

我试过tkMessageBox:

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

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

12 回答

  • 42

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

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

    就在你的留言箱之前 .

  • 2
    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

    enter image description here

  • 1

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

    安装时间: 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

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

    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 | No 
    ##  6 : Cancel | Try Again | Continue
    

    玩得开心!

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

  • 0

    您也可以在退出之前定位另一个窗口,以便定位消息

    #!/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!")
    
  • 1

    使用

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

    必须先创建主窗口 . 这适用于Python 3.这不是fot wxPython,而是适用于tkinter .

  • 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
    """
    
  • 16

    你看过easygui吗?

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

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

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

  • 9
    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
    
  • 182

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

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

  • 21

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

相关问题