Convert .py/.pyw to .exe [duplicate]

有些话、适合烂在心里 提交于 2020-11-25 04:38:46

问题


I want to create an .exe file from a .py file.

How can I do this?

There is many different approaches.

I prefer using cx_Freeze, because it is simple and fast to create an .exe file with.


回答1:


----- Creating the file -----

  1. Download cx_Freeze (if you didn't do that) at this page.
  2. Create a new Python file and paste the following code:

.

import os
import time
from tkinter import *
from tkinter.filedialog import askopenfile
from tkinter.scrolledtext import ScrolledText
from tkinter.messagebox import *

tk = Tk()
tk.title(".py -> .exe")
tk.resizable(0, 0)

f = None # file chosen

def browse():
    global f, btn
    try:
        f = askopenfile().name # get the path of the chosen file
        btn["text"] = os.path.basename(f)
    except:
        f = None

def convert():
    global f, btn, ver, des
    OK = False
    try:
        dots = 0
        for x in ver.get():
            if x == ".":
                dots += 1
            else:
                x = int(x)
        if dots < 4:
            OK = True # check the number of dots in the version
    except:
        showwarning("","The version must be int.int.int... with max 3 dots.")
    if OK:
        try:
            if f is None:
                showwarning("","You must choose a file to convert.")
                btn.focus()
            elif ver.get() == "":
                showwarning("","You must enter a version.")
                ver.focus()
            else:
                # create and fill the launch files
                with open("setup.py", "w") as f_:
                    f_.write("NAME = '" + f +
                        "'\nVERSION = '" + ver.get() +
                        "'\nDESCRIPTION = \"\"\"" + des.get(1.0, "end") +
                        "\"\"\"\n\nfrom cx_Freeze import setup, Executable\nsetup(name = NAME, version = VERSION, description = DESCRIPTION, executables = [Executable(NAME)])")
                with open("start.bat", "w") as f_:
                    f_.write("py setup.py build")
                os.system("start.bat") # run the launch file

                os.remove("setup.py")  # remove the created files
                os.remove("start.bat") #
                showinfo("Information","End. Your exe file is in folder 'build'.")
        except:
            showerror("Error","Unknown error detected.") # any unknown error

# GUI
Label(text="File to convert").grid(column=0, row=0, sticky="w")
btn = Button(text="Browse...", command=browse)
btn.grid(column=1, row=0)
Label(text="Version").grid(column=0, row=2, sticky="w")
ver = Entry(width=23)
ver.grid(column=1, row=2, padx=5)
ver.insert(0, "1.0")
Label(text="Description").grid(column=0, row=3, sticky="w")
des = ScrolledText(width=15, height=5, wrap=WORD)
des.grid(column=1, row=3)
Label(text="Convert to .exe").grid(column=0, row=4, sticky="w")
Button(text="Convert", command=convert).grid(column=1, row=4, pady=5)

tk.mainloop()
  1. Run the code. Choose a file. Click the convert button.

  2. A command prompt window allows you to see the progress.

  3. Your .exe file is created!

----- Errors -----

  1. The command prompt was stayed open a very short time?
  • Change

      with open("start.bat", "w") as f_:
          f_.write("py setup.py build")
    

    by

      with open("start.bat", "w") as f_:
          f_.write("py setup.py build")
          f_.write("pause")
    

    Then, search the error on the Internet.

  • Check if you have selected a .py or .pyw file.

  1. The folder "build" isn't created?
  • check the path of the file to convert: does it contains characters like éèàçùîïäü, some spaces ? >> put the file for example on your desktop, or in a flash drive
  • check the description: does it contains characters like éèàçùîïäü? Remove them.
  • Have you installed cx_Freeze?
  1. Your .exe file cannot be opened?
  • If your code needs others files, like images, musics, then copy them in the current folder.
  • Have you checked your file? Does it contains some errors?
  • If you use tkinter: have you looped the window?
  1. A message box tells you that an unknown error is detected?

    Sorry, in this case I can't help you...



来源:https://stackoverflow.com/questions/62406974/convert-py-pyw-to-exe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!