python cx_Freeze askopenfile

时间:2018-09-08 17:08:42

标签: python tkinter cx-freeze filedialog

以下文件(Python 3.7)完成了应做的一切。当我按下“打开文件”按钮时,它会打开“ askopenfilename”对话框。

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()

当我将cx_Freeze(5.1.1)与以下安装文件一起使用时:

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
)

“退出”按钮有效,“打开文件”按钮无法打开“ askopenfilename”对话框。问题出在哪里?

1 个答案:

答案 0 :(得分:0)

作为替代方案,您可以尝试使用pyinstaller而不是cx_freeze创建冻结的应用程序。当我用pyinstaller冻结脚本时,它将创建一个冻结的应用程序,并带有一个可以正常工作的文件打开对话框。

您可以通过pyinstaller安装pip软件包:

pip install pyinstaller

然后,您可以仅使用以下命令来创建冻结的应用程序:

pyinstaller dialog_test.py