I'm developing an application using Python 3.4 and PyQt4 with LiClipse as the IDE and have an issue with plotting graphs closing the entire program with no error after I've compiled the program into an executable. I've pin-pointed the problem area and know that calling matplotlib.figure.Figure() is the crash culprit but I don't know where to go from here.
import matplotlib
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
class GraphWidget(FigureCanvas):
def __init__(self,parent=None,width = 500, height = 600, dpi = 100):
self.width = width/dpi
self.height = height/dpi
self.dpi = dpi
#================crashes here=============#
self.figure = Figure((self.width,self.height), dpi=self.dpi)
#=========================================#
alert = QMessageBox()
alert.setText("Passed Figure()")
alert.exec_()
FigureCanvas.__init__(self,self.figure)
alert = QMessageBox()
alert.setText("Passed super init")
alert.exec_()
self.canvas = self
self.axis = self.figure.add_subplot(111)
self.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding)
self.parent = parent
def set_new_graph(self,data,labels):
self.layoutVert = QVBoxLayout(self)
size = QSize(self.width*self.dpi,self.height*self.dpi)
self.axis.hold(False)
mined = min(data.totalamount) - round(min(data.totalamount)*.1,0)
if mined > 0: mined = 0
maxed = max(data.totalamount) + round(max(data.totalamount)*.1,0)
if maxed == mined: maxed += 5
data.plot(x = data.totalamount
, ax = self.axis
, kind = 'bar'
, rot=0
, legend = False
, sharex = True
, sharey = True
# , xticks = labels
, ylim = (mined,maxed)
, table = False)
# self.axis.set_ylim(mined,maxed)
self.axis.set_xticklabels(labels, fontsize = 'small')
self.axis.set_title("Sales History over Past Year")
self.canvas.draw()
self.resize(size)
self.layoutVert.addWidget(self.canvas)
My py2exe setup script produces a usable executable for all functions except when a graph is initialized on the page:
mpld = matplotlib.get_py2exe_datafiles()
include = ['sip','pandas','reportlab'
, 'PyQt4'
, 'PyQt4.QtGui'
, 'PyQt4.QtCore'
, 'PyQt4.Qt'
,'reportlab.rl_settings','scipy','win32com'
,'win32com.client'
, 'matplotlib'
, 'matplotlib.backends'
, 'matplotlib.backends.backend_qt4agg'
, 'matplotlib.figure'
]
exclude = ['nbformat','win32com.gen_py',"six.moves.urllib.parse",
'_gtkagg', '_tkagg', '_agg2',
'_cairo', '_cocoaagg',
'_fltkagg', '_gtk', '_gtkcairo']
setup(name="ServiceMgmt",
# console based executables
console=[],
# windows subsystem executables (no console)
windows=['ServiceMgmt.py'],
# py2exe options
#zipfile=None,
options={"py2exe": py2exe_options},
data_files=mpld
)
I am able to run all other functions of my application in the executable but without issue. No visible error is shown, and the application works fine prior to compiling.
Thank you for your help.
My troubleshooting found numpy.core to be the culprit of my issue. I re-installed numpy and the executable runs properly now.
Related
Python Code to generate QR Code in GUI
from tkinter import *
import datetime
import qrcode
def img_taker():
cs = Tk()
cs.title('qr_code')
img = PhotoImage(file='imgdt2.png')
Label(
cs,
image=img
).pack()
cs.mainloop()
def i_saver():
# Importing library
today = datetime.datetime.now()
date_time = today.strftime("%d/%m/%Y, %H:%M:%S")
# print("date and time:",date_time)
# Data to encode
data = (f"System_no = 1 \n Date and Time:{date_time}")
# Creating an instance of QRCode class
qr = qrcode.QRCode(version = 1,
box_size = 10,
border = 5)
# Adding data to the instance 'qr'
qr.add_data(data)
qr.make(fit = True)
img = qr.make_image(fill_color = 'black',
back_color = 'white')
img.save('imgdt2.png')
i_saver()
img_taker()
Above code is generating qrcode in GUI window that is correct but
I want to convert py to exe that I have already done but ,I want the system name to be dynamic as an option during the setting up of an application(exe file configuration)
Here I want a dynamic system number configuration as system number is different for the different device:
I am trying to do Catia V5 automation using python. I managed to create my baseline sketch without any problem however, I am unable to set axis for volumic operations. Here is a simple example that (should) create a round ball by revolving around the global Z axis :
import os
from win32com.client import Dispatch
CATIA = Dispatch('CATIA.Application')
CATIA.Visible = True
from pathlib import Path
# Creating the part and the sketch
partDocument1 = CATIA.Documents.Add("Part")
part1 = partDocument1.Part
bodies1 = part1.Bodies
body1 = bodies1.Item("PartBody")
sketches1 = body1.Sketches
originElements1 = part1.OriginElements
reference1 = originElements1.PlaneYZ
sketch1 = sketches1.Add(reference1)
# Creating the baseline sketch
sketch1.OpenEdition()
geometricElements1 = sketch1.GeometricElements
axis2D1 = geometricElements1.Item("AbsoluteAxis")
circle2D1 = sketch1.Factory2D.CreateCircle(0.000000, 0.000000, 100, 1.570796, 4.712389)
# Volumic operation
shapeFactory1 = part1.ShapeFactory
reference8 = part1.CreateReferenceFromName("")
shaft1 = shapeFactory1.AddNewShaftFromRef(reference8)
reference9 = part1.CreateReferenceFromObject(sketch1)
shaft1.SetProfileElement(reference9)
hybridShapes1 = body1.HybridShapes
hybridShapeLineExplicit1 = hybridShapes1.Item("Z Axis")
reference10 = part1.CreateReferenceFromObject(hybridShapeLineExplicit1)
shaft1.RevoluteAxis = reference10
part1.UpdateObject(shaft1)
part1.Update()
And here is the traceback :
hybridShapeLineExplicit1 = hybridShapes1.Item("Z Axis")
File "<COMObject <unknown>>", line 2, in Item
I think my problem comes from the fact that this axis is located "outside" the sketch used for the shaft. I dont know how to define an axis in this python "vba-like" code.
Could you help me ?
Thank you very much !
I am trying to convert this code:
import pandas as pd
import matplotlib.pyplot as plt
import readTrc
path = 'C:/filepath/data.trc'
datX, datY, m = readTrc.readTrc(path)
srx, sry = pd.Series(datX * 1000), pd.Series(datY * 1000)
df = pd.concat([srx, sry], axis = 1)
df.set_index(0, inplace = True)
df.plot(grid = 1,
linewidth = 0.5,
figsize = (9,5),
legend = False,
xlim = (df.index[0] , df.index[-1]),
xticks = [-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9])
plt.xlabel('Zeit in ms')
plt.ylabel('Spannung in mV')
plt.savefig('test.png', dpi = 600)
into an executable with cx_Freeze.
Setup.py :
import cx_Freeze
import sys
import matplotlib
base = None
if sys.platform == "win32":
base = "Win32GUI"
executables = [
cx_Freeze.Executable("read_trc.py", base = base),
]
build_exe_options = {"includes":["matplotlib.backends.backend_tkagg"],
"include_files":[(matplotlib.get_data_path(), "mpl-data"),
('C:/filepath', 'data.trc')],
"excludes":[],
}
cx_Freeze.setup(
name = "script",
options = {"build_exe": build_exe_options},
version = "0.0",
description = "A basic example",
executables = executables)
The conversion works but when I try to run the .exe I get this error:
Is there a way to make this work? I am using Python 3.6 on Windows 10.
I have already tried the fixes found on Stackoverflow regarding Numpy import errors but it does not seem to help.
Edit:
Thanks to comments I solved the Error. Unfortunately now I get another Error when I try to execute the converted file:
Edit2:
I tried to include tkinter in my code but it doesn't work. I have a standard python 3.6 distribution installed which should include tkinter. tkinter.test() works. I assume that there is something wrong with the tkinter.ddls import. How would I do that correctly?
import cx_Freeze
import sys
import os
import matplotlib
os.environ['TCL_LIBRARY'] = r"C:\Users\Artur\AppData\Local\Programs\Python\Python36\DLLs\tcl86t.dll"
os.environ['TK_LIBRARY'] = r"C:\Users\Artur\AppData\Local\Programs\Python\Python36\DLLs\tk86t.dll"
base = None
if sys.platform == "win32":
base = "Win32GUI"
executables = [
cx_Freeze.Executable("plt_test.py", base = base),
]
include_files = [(matplotlib.get_data_path(), "mpl-data"),
('C:/Users/Artur/Desktop/Nellingen/Messdaten/20180104_Zyl_NiCr_DCneg_5bar_HSC/20180104_04_Zyl_NiCr_DCneg_5bar_170kV_HSC_Firefly/C220180104_ch2_UHF00000.trc',
'C220180104_ch2_UHF00000.trc'),
(r"C:\Users\Artur\AppData\Local\Programs\Python\Python36\DLLs\tcl86t.dll",
r"C:\Users\Artur\AppData\Local\Programs\Python\Python36\DLLs\tk86t.dll")]
build_exe_options = {"includes":["matplotlib.backends.backend_tkagg"],
"include_files":include_files,
"excludes":[],
"packages":["numpy", "matplotlib", "pandas", 'tkinter', 'os'],
}
cx_Freeze.setup(
name = "script",
options = {"build_exe": build_exe_options},
version = "0.0",
description = "A basic example",
executables = executables)
Output in windows console:
I have an application in which the (tkinter) LabelFrame widget on the tab of a ttk Notebook will not update itself. In a much simplified version of that program (code extracts below) the widget will not even appear on the GUI.
Everything else on the GUI works properly, including updating the tab titles, the application title (and icon) and updating the Label, Checkbutton and Radiobutton widgets on all notebook tabs. Using the ttk versions (e.g. ttk.LabelFrame) to create those widgets did not fix the issue. I also tried using “update_idletasks” (some think this as a kludge) immediately after updating the widget attributes without success.
In the real application the text of all GUI widgets change according to the state of a “choose language” widget on the same GUI (for details, see: Need Python/tkinter GUI to dynamically update itself (for a multi-lingual GUI)). It’s known that all GUI text values (the WidgetName["text”] attribute), including the missing LabelFrame, are being correctly updated to match the state of that widget.
Is there something “special” about LabelFrame widgets on Notebook tabs? What (probably simple) thing am I overlooking?
Also, any confirmation/denial by others will help determine if the problem is unique to my system - a distinct possiblity since my machine is administered by corporate IM (who don't have the best record when handling the needs of unusual users like me).
Thanks
The following is a complete example of the problem. When run, the LabelFrame widget (which should appear at (0, 0) of Tab 1) does not appear. Clicking on the "language" widget causes everything else to display text in the language selected by the "language" widget.
From “LanguageInUse.py” the code that switches languages:
import sys
c_cedille_lower = "\u00E7" # UTF 8/16 (code page 863?) French character
e_circumflex_lower = "\u00EA"
English = 'English' # string shown on GUI
Francais = 'Fran' + c_cedille_lower + 'ais' # string shown on GUI
DefaultLanguage = Francais
DefaultLanguage = English # comment out this line to use French
user_language = DefaultLanguage # set up language shown on GUI
# Define all language-dependent GUI strings (as "Application-Level" globals)
ComplianceMessage = None
ReportTab1Title = None
ReportTab2Title = None
XCheckbuttonMessage = None
XLabelFrameMessage = None
XLabelMessage = None
XRadioButtonMessage = None
'''=========================================================================='''
def SetGuiLanguage( user_language ) :
global ComplianceMessage, LanguagePrompt
global ReportTab1Title, ReportTab2Title
global XLabelFrameMessage, XCheckbuttonMessage, XLabelMessage, XRadioButtonMessage
if ( user_language == English ):
LanguagePrompt = "Language"
ReportTab1Title = "Message Counts"
ReportTab2Title = "Communications Compliance"
XLabelFrameMessage = "LabelFrame"
XCheckbuttonMessage = "Checkbox"
XLabelMessage = "Label"
XRadioButtonMessage = 'Radiobutton'
ComplianceMessage = "Compliance (engish)"
elif ( user_language == Francais ):
LanguagePrompt = "Langage"
ReportTab1Title = "Comtes de message"
ReportTab2Title = "Compliance Communications"
XLabelFrameMessage = "LabelFrame en " + Francais
XCheckbuttonMessage = "Checkbox en " + Francais
XLabelMessage = "Label en " + Francais
XRadioButtonMessage = "Radiobutton en " + Francais
ComplianceMessage = "Compliance - " + Francais
else:
print (' An unknown user language was specified' )
sys.exit()
return
'''=========================================================================='''
SetGuiLanguage( user_language ) # initialize all tkinter strings at startup
'''========================== End of File ================================'''
From “SelectReports.py”) the code that builds the notebook:
from tkinter import Checkbutton, Radiobutton, Label, LabelFrame, Frame
from tkinter import ttk
import LanguageInUse
# Locally defined entities importable by other modules (often
# Tkinter Application level objects whose language can be changed)
ComplianceMessageText = None
NotebookFrame = None
XCheckbutton = None
XLabel = None
XLabelFrame = None # NOT APPEARING ON THE GUI
XRadiobutton = None
'''=========================================================================='''
def TabbedReports( ParentFrame ) :
global ComplianceMessageText, NotebookFrame
global SelectReportFrame, UplinkFileWarningText
global XCheckbutton, XLabel, XLabelFrame, XRadiobutton
# Builds the notebook and it's widgits
NotebookFrame = ttk.Notebook( ParentFrame )
NotebookFrame.grid( row = 0, column = 1 )
Tab1Frame = Frame( NotebookFrame )
Tab2Frame = Frame( NotebookFrame )
NotebookFrame.add( Tab1Frame )
NotebookFrame.add( Tab2Frame )
# Create widgets on Tab 1
XLabelFrame = LabelFrame( Tab1Frame ) # NOT APPEARING ON GUI
XCheckbutton = Checkbutton( Tab1Frame )
XLabel = Label( Tab1Frame )
XRadiobutton = Radiobutton( Tab1Frame )
XLabelFrame.grid( row = 1, column = 0 ) # NOT ON GUI
XCheckbutton.grid( row = 1, column = 1 )
XLabel.grid( row = 2, column = 0 )
XRadiobutton.grid( row = 2, column = 1 )
XLabelFrame.configure( text = LanguageInUse.XLabelFrameMessage ) # NOT ON GUI
XCheckbutton.configure( text = LanguageInUse.XCheckbuttonMessage )
XLabel.configure( text = LanguageInUse.XLabelMessage )
XRadiobutton.configure( text = LanguageInUse.XRadioButtonMessage )
# .tab() gives same effect as .configure() for other widget types
NotebookFrame.tab( 0 , text = LanguageInUse.ReportTab1Title )
NotebookFrame.tab( 1 , text = LanguageInUse.ReportTab2Title )
# Create the only widget on Tab 2 (uses other method to specify text)
ComplianceMessageText = Label( Tab2Frame )
ComplianceMessageText.grid( row = 0, column = 0 )
ComplianceMessageText['text'] = LanguageInUse.ComplianceMessage
return
From “ChangeLanguageOnGui.py” the code that updates all notebook widgets:
import sys, os
from tkinter import StringVar, Radiobutton, PhotoImage
#from TkinterRoot import root
import LanguageInUse
import SelectReports
'''=========================================================================='''
def ChangeLanguageOnGui() :
SelectReports.XLabelFrame.configure( text = LanguageInUse.XLabelFrameMessage ) # NOT ON GUI
SelectReports.XCheckbutton.configure( text = LanguageInUse.XCheckbuttonMessage )
SelectReports.XLabel.configure( text = LanguageInUse.XLabelMessage )
SelectReports.XRadiobutton.configure( text = LanguageInUse.XRadioButtonMessage )
# .tab() gives the same effect as .configure() for other widget types
SelectReports.NotebookFrame.tab( 0 , text = LanguageInUse.ReportTab1Title )
SelectReports.NotebookFrame.tab( 1 , text = LanguageInUse.ReportTab2Title )
SelectReports.ComplianceMessageText['text'] = LanguageInUse.ComplianceMessage
'''=========================================================================='''
def SetUpGuiLanguage( LanguageFrame ) :
GUI_Language = StringVar( value = LanguageInUse.user_language )
#---------------------------------------------------------------------------
def switchLanguage():
LanguageInUse.user_language = GUI_Language.get()
LanguageInUse.SetGuiLanguage( LanguageInUse.user_language )
ChangeLanguageOnGui()
return
#---------------------------------------------------------------------------
UsingEnglish = Radiobutton( LanguageFrame, indicatoron = False,
variable = GUI_Language,
command = lambda: switchLanguage(),
value = LanguageInUse.English )
UsingFrancais = Radiobutton( LanguageFrame, indicatoron = False,
variable = GUI_Language,
command = lambda: switchLanguage(),
value = LanguageInUse.Francais )
UsingEnglish.grid( row = 0, column = 0 )
UsingFrancais.grid( row = 1, column = 0 )
UsingEnglish.configure( text = LanguageInUse.English )
UsingFrancais.configure( text = LanguageInUse.Francais )
From "TkinterRoot.py" the code that makes root importable everywhere (explictly importing this avoided problems such as IntVar() being unavailable during the intitialization phase of other modules):
from tkinter import Tk # possibly the worlds shortest useful python module
root = Tk() # makes root an importable "Application Level" global
And finally "A.py", the mainline file:
from TkinterRoot import root
from tkinter import LabelFrame
from tkinter import ttk
import ChangeLanguageOnGui, LanguageInUse, SelectReports, sys
LanguageFrame = None
if __name__ == "__main__":
LanguageChoice = LanguageInUse.English
if ( LanguageChoice == LanguageInUse.English ) :
LanguageInUse.user_language = LanguageChoice
elif ( LanguageChoice == 'Francais' ) :
LanguageInUse.user_language = LanguageInUse.Francais
else :
print( "Unknown Language: " + LanguageChoice )
sys.exit()
mainframe = ttk.Frame( root )
mainframe.grid( row = 0, column = 0 )
LanguageFrame = LabelFrame( mainframe, text = LanguageInUse.LanguagePrompt )
LanguageFrame.grid( row = 0, column = 0 )
ChangeLanguageOnGui.SetUpGuiLanguage( LanguageFrame )
SelectReports.TabbedReports( mainframe )
try:
root.mainloop()
except:
print( 'Exception Occurred' )
sys.exit()
The Environment is 64-bit Python 3.5.1, 64-bit Win 7 Enterprise SP 1, 64-bit Eclipse Mars 2 (the Java EE IDE edition) running 64-bit PyDev 5.1.2.201606231256. The "one user" (no admin rights) version of Pydev was used, this required Microsoft patch KB2999226 (part of Win10) to run on Win7. Eventual target distribution is a 32-bit Windows app (so it can run on 32 & 64 bit Windows) - and if/when time permits - Linux.
There’s one minor complication to keep in mind: In the real program several packages are being used. Inside each package each function is isolated inside its own file. All objects (e.g. the tkinter widgets) that must be externally visible (or need be shared amongst the package’s files) are declared in the package’s _ _ init.py _ _ file. Functions that must be externally visible are explicitly imported into _ _ init.py _ _ by using relative imports (e.g. “from .Function1 import Function1” ).
Your title is misleading because you place the LabelFrame in a Frame, not directly on a Notebook tab. Your problem is that the labelframe does not appear in its parent frame. The Notebook is irrelevant and all associated code should have been deleted before posting.
Even the frame is irrelevant in that the same problem arises when putting the labelframe directly in root. Here is minimal code that demonstrate both the problem and a solution.
from tkinter import Tk
from tkinter import ttk
root = Tk()
lf1 = ttk.LabelFrame(root, text='labelframe 1')
lf2 = ttk.LabelFrame(root, text='labelframe 2', width=200, height=100)
lf1.pack()
lf2.pack()
I ran this on Win 10 with 3.6a2, which comes with tk 8.6.4. Only lf2 is visible because the default size of a labelframe, as with a frame, is 0 x 0. A non-default size arises either from explicit sizing or from contents. Somewhat surprisingly, the label does not count as content and does not force a non-default size. I reproduced the same result with the labelframe in a frame (your situation) and on a tab.
I've started working with IronPython in #Develop, and i love the integration with IronPython and Windows Forms, it lets you create the GUI like is were Visual Basic or C#
The question i have is simple, how to draw a line into a PictureBox when it's clicked? I've found this code about drawing lines, but i know how to adapt it to a PictureBox.
This is the code i've found:
http://www.zetcode.com/tutorials/ironpythontutorial/painting/
So, what should i put in "def PictureBox1Click(self, sender, e):"?
Any help or guide would be gratly appreciated.
Here is a simple example that draws a line on a picture box when it is clicked.
import System.Drawing
import System.Windows.Forms
from System.Drawing import *
from System.Windows.Forms import *
class MainForm(Form):
def __init__(self):
self.InitializeComponent()
self.pen = System.Drawing.Pen(System.Drawing.Color.Black);
def InitializeComponent(self):
self._pictureBox1 = System.Windows.Forms.PictureBox()
self._pictureBox1.BeginInit()
self.SuspendLayout()
#
# pictureBox1
#
self._pictureBox1.Location = System.Drawing.Point(13, 13)
self._pictureBox1.Name = "pictureBox1"
self._pictureBox1.Size = System.Drawing.Size(259, 237)
self._pictureBox1.TabIndex = 0
self._pictureBox1.TabStop = False
self._pictureBox1.Click += self.PictureBox1Click
#
# MainForm
#
self.ClientSize = System.Drawing.Size(284, 262)
self.Controls.Add(self._pictureBox1)
self.Name = "MainForm"
self.Text = "PyWinForm"
self._pictureBox1.EndInit()
self.ResumeLayout(False)
def PictureBox1Click(self, sender, e):
g = self._pictureBox1.CreateGraphics()
g.DrawLine(self.pen, 10, 10, 400, 200)