Проблема записи в файл - PullRequest
0 голосов
/ 25 мая 2018

У меня проблемы с записью в мой HTML-файл.

Я хочу, чтобы мой код мог размещать то, что я написал в HTML, но мой код будет делать это только тогда, когда у меня его нетХотя / если заявления в этом определении.Если у меня есть Whiles / Ifs, мой HTML-файл просто станет пустым.Я понятия не имею, почему это происходит, и я не могу найти обходной путь.

Есть ли способ использовать Whiles / Ifs, не заставляя мой код удалять все в моем файле, а вместо этого заставлять его писать что?Я хочу туда?

def invoice_creator_window():
    global total_cost, total_cost_list, list_of_items, invoice_created

    invoice_created = Toplevel()
    invoice_created.focus_set()
    invoice_created.resizable(width = True, height = False)
    invoice_created.title("Invoice Created")
    invoice_created.geometry("300x300")
    invoice_created.geometry("+400+400")
    invoice_created.configure(bg = "limegreen")
    currentDisplay = 10

    print(total_cost, total_cost_list, list_of_items)

    done = Label(invoice_created, text = "Items have been purchased. Invoice has been created. Please check this program's file location.")
    invoice_created = Button(invoice_created, text = "Done", bg = "white", command = close_window)

    # 
    done.grid(row = 1, column = 1, padx = 7.5, pady = space_between)
    invoice_created.grid(row = 2, column = 1, padx = 7.5, pady = space_between)

    # This section is for the invoice creation with HTML.        
    html_formatting_start = """<!DOCTYPE html>
    <html>
    <head>
    <title>Games R Us - Invoice</title>
    </head>
    <body>


    <style>
    body {background-color: #F7D358;}
    h1   {color: #775A03;}
    p    {color: ; border: 1px solid #775A03; padding: 15px; width: 650px}
    </style>

    <center>
    <h1>Games R Us - Invoice Document</h1>    
    """
    counter = 0
    while len(list_of_items) > 0:
        global html_formatting_mid
        print(counter)
        html_formatting_mid = ("""
        <h3>
        <p>
        <img src="https://steamcdn-a.akamaihd.net/steam/apps/211420/header.jpg?t=1483694369"</img>
        <br>""" + str(list_of_items[counter]) + """<br>
        <i>$""" + str(total_cost_list[counter]) + """ AUD</i>   

        </p>
        </h3>
        """)

        if counter >= len(list_of_items) - 1:
            return
        else:
            counter += 1
    html_formatting_end = """
    <h2>In Total: $""" + str(total_cost) +""" AUD</h2>
    <br>

    <b>Information Grabbed from These Links: </b>
    <a href="https://store.steampowered.com/explore/new/">Steam's New Releases</a> [LIVE] - 
    <a href="https://store.steampowered.com/search/?filter=topsellers">Steam's Top Sellers</a> [LIVE] - 
    <a href="https://www.umart.com.au/Headphones_147C.html">Umart's Headphones</a> [PRE-DOWNLOADED] - 
    <a href="https://www.umart.com.au/Microphones_496C.html">Umart's Microphones</a> [PRE-DOWNLOADED]

    </center>
    </body>
    </html>"""

    invoice_creation = open(invoice_file, "w")

    invoice_creation.write(html_formatting_start)
    invoice_creation.write(html_formatting_mid)
    invoice_creation.write(html_formatting_end)

    invoice_creation.close()

#############################################################################

button_buy = Button(welcome_window, text = "Buy", fg = "white", bg = "goldenrod", font = gui_font_10,
                    command = invoice_creator_window)

Примечание: "total_cost_list" и "list_of_items" - это все списки."total_cost" является значением.Не слишком переживайте по поводу их контекста, но я хотел уточнить, может ли это на что-нибудь повлиять.

Ответы [ 3 ]

0 голосов
/ 26 мая 2018

Я нашел решение.

def invoice_creator_window():
    global total_cost, total_cost_list, list_of_items, invoice_created

    invoice_created = Toplevel()
    invoice_created.focus_set()
    invoice_created.resizable(width = True, height = False)
    invoice_created.title("Invoice Created")
    invoice_created.geometry("300x300")
    invoice_created.geometry("+400+400")
    invoice_created.configure(bg = "limegreen")
    currentDisplay = 10

    print(total_cost, total_cost_list, list_of_items)

    done = Label(invoice_created, text = "Items have been purchased. Invoice has been created. Please check this program's file location.")
    invoice_created = Button(invoice_created, text = "Done", bg = "white", command = close_window)

    # 
    done.grid(row = 1, column = 1, padx = 7.5, pady = space_between)
    invoice_created.grid(row = 2, column = 1, padx = 7.5, pady = space_between)

    # This section is for the invoice creation with HTML.        
    html_formatting_start = """<!DOCTYPE html>
    <html>
    <head>
    <title>Games R Us - Invoice</title>
    </head>
    <body>


    <style>
    body {background-color: #F7D358;}
    h1   {color: #775A03;}
    p    {color: ; border: 1px solid #775A03; padding: 15px; width: 650px}
    </style>

    <center>
    <h1>Games R Us - Invoice Document</h1>    
    """
    counter = 0
    html_formatting_mid = ""
    for items in list_of_items:
        print(counter)
        html_formatting_mid += ("""
        <h3>
        <p>
        <img src="https://steamcdn-a.akamaihd.net/steam/apps/211420/header.jpg?t=1483694369"</img>
        <br>""" + str(list_of_items[counter]) + """<br>
        <i>$""" + str(total_cost_list[counter]) + """ AUD</i>   

        </p>
        </h3>
        """)
        counter += 1
    html_formatting_end = """
    <h2>In Total: $""" + str(total_cost) +""" AUD</h2>
    <br>

    <b>Information Grabbed from These Links: </b>
    <a href="https://store.steampowered.com/explore/new/">Steam's New Releases</a> [LIVE] - 
    <a href="https://store.steampowered.com/search/?filter=topsellers">Steam's Top Sellers</a> [LIVE] - 
    <a href="https://www.umart.com.au/Headphones_147C.html">Umart's Headphones</a> [PRE-DOWNLOADED] - 
    <a href="https://www.umart.com.au/Microphones_496C.html">Umart's Microphones</a> [PRE-DOWNLOADED]

    </center>
    </body>
    </html>"""

    invoice_creation = open(invoice_file, "w")

    invoice_creation.write(html_formatting_start)
    invoice_creation.write(html_formatting_mid)
    invoice_creation.write(html_formatting_end)

    invoice_creation.close()

#############################################################################

button_buy = Button(welcome_window, text = "Buy", fg = "white", bg = "goldenrod", font = gui_font_10,
                    command = invoice_creator_window)

Я вернулся к своему старому использованию цикла for и попытался использовать его.За исключением этого времени, я добавил html_formatting_mid + = ("" "к нему, а затем перед циклом for просто добавил html_formatting_mid =" ", как показал Minion Jim.

Теперь он работает полностью.

0 голосов
/ 26 мая 2018

Короткий ответ будет, вы можете просто написать в режиме добавления.open (filename, 'a') вместо open (filename, 'w').Это добавит к тому, что уже есть в файле, поэтому вы можете сначала его обрезать.

0 голосов
/ 25 мая 2018

Вот исправленная версия вашего кода в максимально простом контейнере.

from tkinter import *
import webbrowser
root = Tk ()

space_between, invoice_file = 5, "Invoice.html"
total_cost, total_cost_list, list_of_items = 10, [1, 9], ["Something", "Something 2"]

def close_window (): root.destroy ()

def invoice_creator_window():
    global total_cost, total_cost_list, list_of_items, invoice_created

    invoice_created = Toplevel()
    invoice_created.focus_set()
    invoice_created.resizable(width = True, height = False)
    invoice_created.title("Invoice Created")
    invoice_created.geometry("300x300")
    invoice_created.geometry("+400+400")
    invoice_created.configure(bg = "limegreen")
    currentDisplay = 10

    print(total_cost, total_cost_list, list_of_items)

    done = Label(invoice_created, text = "Items have been purchased. Invoice has been created.")
    invoice_created = Button(invoice_created, text = "Done", bg = "white", command = close_window)

    # 
    done.grid(row = 1, column = 1, padx = 7.5, pady = space_between)
    invoice_created.grid(row = 2, column = 1, padx = 7.5, pady = space_between)

    # This section is for the invoice creation with HTML.        
    html_formatting_start = """<!DOCTYPE html>
    <html>
    <head>
    <title>Games R Us - Invoice</title>
    </head>
    <body>


    <style>
    body {background-color: #F7D358;}
    h1   {color: #775A03;}
    p    {color: ; border: 1px solid #775A03; padding: 15px; width: 650px}
    </style>

    <center>
    <h1>Games R Us - Invoice Document</h1>    
    """
    counter = 0
    html_formatting_mid = ""
    while len(list_of_items) > 0:
        print(counter)
        html_formatting_mid += """
        <h3>
        <p>
        <img src="https://steamcdn-a.akamaihd.net/steam/apps/211420/header.jpg?t=1483694369"</img>
        <br>""" + str(list_of_items[counter]) + """<br>
        <i>$""" + str(total_cost_list[counter]) + """ AUD</i>   

        </p>
        </h3>
        """

        if counter >= len(list_of_items) - 1:
            break
        else:
            counter += 1
    html_formatting_end = """
    <h2>In Total: $""" + str(total_cost) +""" AUD</h2>
    <br>

    <b>Information Grabbed from These Links: </b>
    <a href="https://store.steampowered.com/explore/new/">Steam's New Releases</a> [LIVE] - 
    <a href="https://store.steampowered.com/search/?filter=topsellers">Steam's Top Sellers</a> [LIVE] - 
    <a href="https://www.umart.com.au/Headphones_147C.html">Umart's Headphones</a> [PRE-DOWNLOADED] - 
    <a href="https://www.umart.com.au/Microphones_496C.html">Umart's Microphones</a> [PRE-DOWNLOADED]

    </center>
    </body>
    </html>"""

    invoice_creation = open(invoice_file, "w")

    invoice_creation.write (html_formatting_start + html_formatting_mid + html_formatting_end)

    invoice_creation.close ()

    webbrowser.open (invoice_file)

#############################################################################

button_buy = Button(root, text = "Buy", fg = "white", bg = "goldenrod",
                    command = invoice_creator_window).pack ()
root.mainloop ()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...