How can I create a simple message box in Python?

后端 未结 17 1315
心在旅途
心在旅途 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:23

    Have you looked at easygui?

    import easygui
    
    easygui.msgbox("This is a message!", title="simple gui")
    
    0 讨论(0)
  • 2020-11-30 17:25

    On Mac, the python standard library has a module called EasyDialogs. There is also a (ctypes based) windows version at http://www.averdevelopment.com/python/EasyDialogs.html

    If it matters to you: it uses native dialogs and doesn't depend on Tkinter like the already mentioned easygui, but it might not have as much features.

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

    Use

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

    The master window has to be created before. This is for Python 3. This is not fot wxPython, but for tkinter.

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

    The code you presented is fine! You just need to explicitly create the "other window in the background" and hide it, with this code:

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

    Right before your messagebox.

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

    In Windows, you can use 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")
    
    0 讨论(0)
  • 2020-11-30 17:31

    Also you can position the other window before withdrawing it so that you position your message

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

    Please Note: This is Lewis Cowles' answer just Python 3ified, since tkinter has changed since python 2. If you want your code to be backwords compadible do something like this:

    try:
        import tkinter
        import tkinter.messagebox
    except ModuleNotFoundError:
        import Tkinter as tkinter
        import tkMessageBox as tkinter.messagebox
    
    0 讨论(0)
提交回复
热议问题