How can I create a simple message box in Python?

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

    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.

提交回复
热议问题