'Font not defined' in Tkinter application freezed by cx_Freeze - python

I have freezed a Tkinter-using GUI Python 3.4 app with cx_Freeze and when I tried to run it, I was presented the following error:
NameError: name 'font' is not defined.
When I remove all references to font from my code (i. e., if I don't set ttk Label fonts anywhere In the code), it works just fine and the exe runs nicely. I have checked the library.zip archive created by the freeze script and it does contain the font.pyc file in the tkinter directory.
This is what my setup.py file looks like:
import cx_Freeze
import sys
import tkinter
base = None
if sys.platform == 'win32':
base = "Win32GUI"
executables = [cx_Freeze.Executable("rocnikovka.py", base=base)]
cx_Freeze.setup(
name = "Number evolution",
options = {"build_exe": {"packages":["tkinter", "tkinter.font"], "includes": ["tkinter", "tkinter.font"]}},
version = "0.01",
description = "Rocnikovka",
executables = executables
)
Any help is appreciated.
UPDATE: I have also tried making an executable out of the script with py2exe but ended up with the same result. Seems like a problem with tkinter rather than with cx_Freeze.
UPDATE #2: I import tkinter and ttk in the script like this:
from tkinter import *
from tkinter import ttk
I have a few fonts defined in the script, like this one:
font_title = font.Font(family = "Exo 2", size = 20, weight = "bold")
which I then use as the font parameter of ttk.Label objects.
This all works just fine when run as a script in IDLE.

Thanks to Arden, I was able to get it to work adding an explicit font sub-module import:
from tkinter import font
Works perfectly good now.

Related

freezing Matplotlib Widget in QT app does not work when the widget is part of submodule

I've devellopped an app using PySide2 with two modules. A first module "targetQt.py" make the general display while the second "Score.py" is dealing with data and build some graph widgets and canvas using PySide2 and matplotlib with it's QT5Agg backend. The definition of the widget is in the second module since it depends on the data.
This app works fine while launched with python, I now wan't to build it using cx_freeze. All the graphical elements built in targetQt.py (including the ones using matplolib) works fine, QTableModels defined in Score.py works fine too but the matplotlib canvas widget defined in Score.py does not show.
Here is my setup file:
import sys,matplotlib
from cx_Freeze import Executable, setup
try:
from cx_Freeze.hooks import get_qt_plugins_paths
except ImportError:
get_qt_plugins_paths = None
include_files = []
if get_qt_plugins_paths:
for plugin_name in (
"accessible",
"iconengines",
"platforminputcontexts",
"xcbglintegrations",
"egldeviceintegrations",
"wayland-decoration-client",
"wayland-graphics-integration-client",
"wayland-graphics-integration-server",
"wayland-shell-integration",
):
include_files += get_qt_plugins_paths("PySide2", plugin_name)
# base="Win32GUI" should be used only for Windows GUI app
base = "Win32GUI" if sys.platform == "win32" else None
build_exe_options = {
# exclude packages that are not really needed
"includes":["matplotlib.backends.backend_qtagg",'Score'],
"excludes": ["tkinter","PyQt5"],
"include_files": include_files+[(matplotlib.get_data_path(), "mpl-data")],
"zip_include_packages": ["PySide2"],
}
executables = [Executable("targetQt.py", base=base)]
setup(
name="DartGame",
version="0.5",
description="An app with 2 modules",
options={"build_exe": build_exe_options},
executables=executables,
)
I've tried without putting Score.py in includes, relying on cx_freeze hability to search for dependencies, the results is the same. The way to freeze PySide2 and matplotlib app is mainly inspired by cx_freeze's samples.
I'm working with python3.7 on Windows 10
Does anyone has an idea on how to make it work?
Thanks!

cx_freeze Error: Module not found tkinter

I started having some issues with miniconda and PyCharm so I had to reinstall them. However, now when I use cx_freeze to create .exe I get the error below.
Here is my code:
from tkinter import *
from tkinter import ttk
from ttkthemes import ThemedTk
from ttkthemes import themed_tk as tk
import os
from tkinter import messagebox
import getpass
import pyodbc
import test
import time
class Application(object):
def __init__(self,master):
self.master=master
self.itemIn = ttk.Button(master, text="In", width=35,
command=self.itemIn).grid(row=2, column=0, padx=10,pady=15)
self.itemOut = ttk.Button(master, text="Out", width=35,
command=self.itemOut).grid(row=3, column=0, padx=10)
def itemIn(self):
pass
def itemOut(self):
pass
def main():
global userList
strForDB = os.getcwd() + '\DBINFO.txt'
openDBFile = open(strForDB, 'r')
currentDirForDB = openDBFile.read()
openDBFile.close()
dbPath = currentDirForDB
conToSubmit = pyodbc.connect(dbPath)
curToSubmit = conToSubmit.cursor()
userName = getpass.getuser()
root = tk.ThemedTk()
root.get_themes()
root.set_theme("radiance")
app=Application(root)
root.title("Main Menu v:5.1")
root.configure(background="#F4F3F1")
root.resizable(0, 0)
# Change Application Icon with below:
root.wm_iconbitmap(os.getcwd()+'/Z Logo.ico')
### To maximize
# w, h = root.winfo_screenwidth(), root.winfo_screenheight()
# root.geometry("%dx%d+0+0" % (w, h))
root.geometry('340x510+300+80')
root.mainloop()
#else:
# messagebox.showerror("Access Denied", "You are not allowed to access this application.")
# return
if __name__=='__main__':
main()
This is cx_freeze build script, where I have imported all the relevant modules.
import cx_Freeze
import os
from cx_Freeze import *
import sys
if sys.platform == "win32":
base = "Win32GUI"
imodules=['tkinter','pyodbc','getpass','pathlib','openpyxl','datetime','os','win32print','win32ui'] #modules to include
emodules=[] ###modules to NOT include
#(useful if a module is forcefully installed
#even if you don't want that module)
build_exe_options={"packages":imodules,"excludes":emodules}
setup(
name= "WMS System",
options={"build_exe":build_exe_options},description="App to track Inventory",author="VM",
executables=[
Executable(
"WMS.py", base=base, icon="Z logo.ico"
)
]
)
I have been using cx_freeze for quite some time but I have never seen this error.
I was having identical problem as you and after a long troubleshooting session I found out that
in /lib folder of my build i had "Tkinter" folder, renaming it to "tkinter" solved the above issue
any following errors of the type module not found could be solved by either adding them to the "includes" tag of build options or finding and copying the whole module folder yourself from python installation folder
The folder name in project must be "lib/tkinter", but maybe it is "lib/Tkinter", then you must rename the folder from "Tkinter" to "tkinter".

cx_freeze debugging console?

I try to build my (fine working) python 3.6 tkinter gui app to a windows excecutable. After hours of trial an error (with some name and dll issues) I got it to run. But it seems to have varoius of bugs. Some functions seem not to work and I have no console output of the produced error... is there a way to debug the exe?
this is my setup.py
import sys
from cx_Freeze import setup, Executable
import os
os.environ['TCL_LIBRARY'] = r'C:\Users\xxx\AppData\Local\Programs\Python\Python36\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\Users\xxx\AppData\Local\Programs\Python\Python36\tcl\tk8.6'
base = None
if sys.platform == 'win32':
base = 'Win32GUI'
executables = [
Executable('myApp.py', base=base)
]
build_exe_options = {"packages": ["tkinter",
"PIL",
"savReaderWriter",
"numpy",
"scipy",
"os"],
"include_files": ["tcl86t.dll",
"tk86t.dll"]}
setup(name='myApp',
version='0.1',
description='some description',
options = {'build_exe': build_exe_options},
executables=executables
)
myApp.py
is too big to post it here. This is a snippet that only works 'unfreezed'. You need an spss.sav file like this to try this out.
from tkinter import *
from tkinter import ttk, filedialog, messagebox
from PIL import Image, ImageTk, ImageDraw
from savReaderWriter import SavReader
import numpy as np
from scipy.ndimage import gaussian_filter
import os
class MyApp:
spss_file = None
def import_spss(self, *args):
filename = filedialog.askopenfilename()
if filename:
try:
with SavReader(filename, returnHeader=True, ioUtf8=True) as reader:
spss_file = reader.all()
self.spss_file = np.array(spss_file)
except Exception as ex:
messagebox.showinfo(title="Import SPSS File",
message="Warning: wrong file format chosen! \nAccepted formats: sav")
print(ex)
return
else:
return
def main():
App = MyApp()
App.import_spss()
print("everything works fine")
main()
if you want the console window to appear, after it is frozen, just remove this code from the setup script:
if sys.platform == 'win32':
base = 'Win32GUI'
what that code does is it tells cx_Freeze to have the console window not show up, after frozen. this is only required on windows, because on other OSes,it depends on whether or not it was run from a terminal. make sure though, when you have finished debugging it, to put that code back in, or the console window will show up in your app.
by the way, one of the most annoying problems I've ever had was when making a program with tkinter and cx_Freeze. the problem was that it was starting in the wrong directory and not able to find the TK Dll. If when you run this with the console, and you see something about a file not found, chances are you are not including it or it is in the wrong directory.
have a good day!

(Python3.4) tkinter messagebox not work when it executed by cx_freeze

import sys
from cx_Freeze import setup, Executable
build_exe_options = {'packages': ['os','tkinter','random',
'heapq','collections','sys','pickle']}
base = None
if sys.platform == "win32":
base = "Win32GUI"
setup( name = 'Game',
version = '0.02',
description = 'My GUI application!',
options = {'build_exe': build_exe_options},
executables = [Executable('Game.py', base=base)])
here's the code of the setup
from tkinter import *
value_a = 'hahaha'
a =messagebox.showinfo('laugh',value_a)
and the code that would executed
the erorr is Nameerorr : name "messagebox" is not defined when I typed python 123.py build or python haha.py build in cmd
I already used import *, if I run the code it shows message but neither in cmd nor .exe
Should I use import tkinter as tk? But it is difficult to read my code by adding "tk", I want to keep import * so that no "tk.xxx" is needed and it will still works on exe.
from tkinter import * does not work for messagebox, so you must import the message box individually like below
from tkinter import messagebox
I had this problem too. It worked OK in the IDE but not in direct run mode.
Adding import tkinter.messagebox as messagebox fixed the problem.
Thanks, G.

Using ttk with Py2App

I'm trying to figure out how to use Py2App to make one of my scripts less user hostile. The script is written using Tkinter using "notebook" from ttk, and I can't figure out how to include the ttk thing! It compiles as it should but when I try to run I get a console error: _tkinter.TclError: can't find package tile.
The problem can be replicated with:
test.py
#!/usr/bin/python2.7
from Tkinter import Tk
from ttk import Notebook
if __name__ == '__main__':
gui = Tk()
gui.wm_title("Py2App testing")
gui.wm_minsize(450, 300)
main = Notebook(gui)
main.pack(fill='both', expand='yes')
gui.mainloop()
I use a simple file which looks like:
setup.py
from setuptools import setup
APP = ['test.py']
DATA_FILES = []
OPTIONS = {'argv_emulation': True,}
setup(
app=APP,
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app',],
)
I've tried a number of combinations of 'packages': ['ttk'], 'includes': ['ttk'],, setup_requires=['py2app', 'ttk'],, but I can't get it to work so I figured maybe someone can explain how this actually works! =)
I don't know about tile either, how do I include that?

Categories