How can I create a simple message box in Python?

后端 未结 17 1317
心在旅途
心在旅途 2020-11-30 16:44

I\'m looking for the same effect as alert() in JavaScript.

I wrote a simple web-based interpreter this afternoon using Twisted.web. You basically submit

相关标签:
17条回答
  • 2020-11-30 17:37

    The PyMsgBox module does exactly this. It has message box functions that follow the naming conventions of JavaScript: alert(), confirm(), prompt() and password() (which is prompt() but uses * when you type). These function calls block until the user clicks an OK/Cancel button. It's a cross-platform, pure Python module with no dependencies.

    Install with: pip install PyMsgBox

    Sample usage:

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

    Full documentation at http://pymsgbox.readthedocs.org/en/latest/

    0 讨论(0)
  • 2020-11-30 17:37

    I had to add a message box to my existing program. Most of the answers are overly complicated in this instance. For Linux on Ubuntu 16.04 (Python 2.7.12) with future proofing for Ubuntu 20.04 here is my code:

    Program top

    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"
    

    Regardless of which Python version is being run, the code will always be messagebox. for future proofing or backwards compatibility. I only needed to insert two lines into my existing code above.

    Message box using parent window geometry

    ''' 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
    

    I already had the code to return if song count was zero. So I only had to insert three lines in between existing code.

    You can spare yourself complicated geometry code by using parent window reference instead:

    parent=self.toplevel
    

    Another advantage is if the parent window was moved after program startup your message box will still appear in the predictable place.

    0 讨论(0)
  • 2020-11-30 17:42

    You could use an import and single line code like this:

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

    Or define a function (Mbox) like so:

    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)
    

    Note the styles are as follows:

    ##  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
    

    Have fun!

    Note: edited to use MessageBoxW instead of MessageBoxA

    0 讨论(0)
  • 2020-11-30 17:44

    Not the best, here is my basic Message box using only 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
    """
    
    0 讨论(0)
  • 2020-11-30 17:49

    ctype module with threading

    i was using the tkinter messagebox but it would crash my code. i didn't want to find out why so i used the ctypes module instead.

    for example:

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

    i got that code from Arkelis


    i liked that it didn't crash the code so i worked on it and added a threading so the code after would run.

    example for my code

    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)
    

    for button styles and icon numbers:

    ## 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
    
    0 讨论(0)
提交回复
热议问题