python cx_Freeze askopenfile

折月煮酒 提交于 2019-12-24 15:31:34

问题


Following file (Python 3.7) does everything it is supposed to do. When I press the “Open file” button it opens “askopenfilename” dialog.

import tkinter as tk
from tkinter import ttk
from tkinter import filedialog as fd
from tkinter import messagebox
from os import path

class GUI(tk.Tk):
    def __init__(self):
        self.win=tk.Tk()
        self.create_widgets()

    def exitfcn(self):
        result = tk.messagebox.askquestion('Warning', 'Exit?')      
        if result == 'yes':
            self.win.destroy()

    # Button callback
    def getFileName(self):
        self.fDir = path.dirname(__file__)
        self.fname=fd.askopenfilename(parent=self.win, initialdir=self.fDir)
        if self.fname != '':
            self.getFile(self.fname)

    def getFile(self, file):
        print(self.fname)

    def create_widgets(self):
        self.mainButtons=ttk.Frame(self.win)
        self.mainButtons.grid(column=0, row=0, padx=100, pady=200)

        # Adding a Button - Open file
        self.openFilebtn=ttk.Button(self.mainButtons, text='Open file', command=self.getFileName)
        self.openFilebtn.grid(column=0, row=0, padx=10, pady=20)

        # Adding a Button - Exit
        self.exitbtn=ttk.Button(self.mainButtons, text='Exit', command=self.exitfcn)
        self.exitbtn.grid(column=0, row=1)

gui = GUI()
gui.win.mainloop()

When I use cx_Freeze (5.1.1) with following setup file:

import os
import sys
from tkinter import filedialog
from cx_Freeze import setup, Executable

PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__))
os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6')
os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tk8.6')

build_exe_options={
        'packages':['tkinter', 'tkinter.filedialog', 'os'],
        'include_files':[
        os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tcl86t.dll'),
        os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tk86t.dll'),]
            }

base = None
if sys.platform == 'win32':
    base = 'Win32GUI'

executables=[Executable("dialog_test.py", base=base)]

setup(name='dialog_test',
version=0.1,
description='Test file for cx_Freezer',
options={"build_exe": build_exe_options},
executables=executables
)

“Exit” button works, “Open file” button doesn’t open “askopenfilename” dialog. Where can be the problem?


回答1:


As an alternative you could try using pyinstaller instead of cx_freeze to create the frozen application. When I freeze your script with pyinstaller, it creates a frozen application with a properly working file-open dialog.

You can install the pyinstaller package through pip:

pip install pyinstaller

and afterwards you can create the frozen application with just the command:

pyinstaller dialog_test.py


来源:https://stackoverflow.com/questions/52237533/python-cx-freeze-askopenfile

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