Applied Programming/GUI/Python3

gui.py

edit
"""This program demonstrates Python GUI using tkinter and saving text as HTML pages.

Input:
    Text window

Output:
    HTML file

Global variables:
    root (tkinter.root): top-level window
    scrolledtext (tkinter.scrolledtext): window scrolled-textbox

References:
    https://www.tutorialspoint.com/python/python_gui_programming.htm
    https://www.python-course.eu/python_tkinter.php
    https://wiki.python.org/moin/EscapingHtml

"""

import html
import tkinter.filedialog
import tkinter.scrolledtext
import webbrowser

root = None
scrolledtext = None


def create_root():
    """Creates top-level window.

    Args:
        None
    
    Returns:
        None

    Modifies:
        global root
        
    """
    global root

    root = tkinter.Tk()
    root.title("Python GUI Example")
    root.geometry("%dx%d+0+0" % root.maxsize())


def text_to_html(title, text):
    """Converts given text to HTML with the given page title.

    HTML text is escaped (< = &lt; > = &gt;, etc.)

    Args:
        title (string): The title of the web page
        text (string):  The text to be converted
    
    Returns:
        string: The converted text

    """
    text = html.escape(text, False)
    text = text.replace("\n", "<br>\n")
    text = "<!DOCTYPE html>\n<html>\n<head>\n<meta charset=""UTF-8"">\n" + \
        ("<title>%s</title>\n</head>\n<body>\n" % title) + \
        text + \
        "</body>\n</html>"
    return text


def save_file():
    """Saves the current scrolledtext to root.filename.

    Args:
        None
    
    Returns:
        None

    Accesses:
        global root, scrolledtext
        
    """
    global root, scrolledtext

    title = "HTML Example"
    text = scrolledtext.get(1.0, tkinter.END)
    text = text_to_html(title, text)

    try:
        with open(root.filename, "w") as file:
            file.write(text)
    except Exception as exception:
        print(exception)


def save_as():
    """Displays a Save As dialog box and calls save_file if successful.
    
    Args:
        None
    
    Returns:
        None

    Modifies:
        global root

    """
    global root

    root.filename =  tkinter.filedialog.asksaveasfilename(
        defaultextension=".html",
        filetypes = (("HTML","*.html"),("all files","*.*")),
        initialdir = ".",
        title = "Save As")
    
    if root.filename != "":
        save_file()


def add_menu():
    """Adds the menu bar to the top-level window.
    
    Args:
        None
    
    Returns:
        None

    Modifies:
        global root

    """
    global root

    main_menu = tkinter.Menu(root)

    file_menu = tkinter.Menu(main_menu, tearoff=0)
    file_menu.add_command(label="Save As...", command=save_as)
    file_menu.add_separator()
    file_menu.add_command(label="Exit", command=root.quit)
    main_menu.add_cascade(label="File", menu=file_menu)

    root.config(menu=main_menu)


def add_textbox():
    """Adds the scrolled textbox to the top-level window.
    
    Args:
        None
    
    Returns:
        None

    Modifies:
        global root

    """
    global root, scrolledtext

    scrolledtext = tkinter.scrolledtext.ScrolledText(root)
    scrolledtext.pack(fill="both", expand=True)

    text = \
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do " \
        "eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim " \
        "ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut " \
        "aliquip ex ea commodo consequat. Duis aute irure dolor in " \
        "reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla " \
        "pariatur. Excepteur sint occaecat cupidatat non proident, sunt in " \
        "culpa qui officia deserunt mollit anim id est laborum."

    scrolledtext.insert(tkinter.INSERT, text)


def main():
    """Runs the main program logic."""
    create_root()
    add_menu()
    add_textbox()
    root.mainloop()


main()

Try It

edit

Copy and paste the code above into one of the following free online development environments or use your own Python3 compiler / interpreter / IDE.

See Also

edit