Use button to call a file.py with glade - python-3.x

i'm trying through a python script in conjunction with glade, create a button that opens me a file in python so I can edit if I want to make some changes later. Can anyone help me if you please ?
What i did was this:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import GObject as gobject
import pygtk
import gtk
def show_script(button):
dialog = gtk.FileChooserDialog("Open...", None, gtk.FILE_CHOOSER_ACTION_OPEN, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
dialog.set_default_response(gtk.RESPONSE_OK)
filter = gtk.FilerFilter()
filter.set_name("All files")
filter.add_pattern("*")
dialog.add_filter(filter)
response = dialog.run()
if response == gtk.RESPONSE_OK:
print (dialog.get_filename(), 'selected')
elif response == gtk.RESPONSE_CANCEL:
print ('Closed, you didnt choose any files')
dialog.destroy()
builder = Gtk.Builder()
builder.add_from_file("Wi_Green_Sheddule_v1.glade")
handlers = {
"action_show_script": show_script
}
}
builder.connect_signals(handlers)
window = builder.get_object("window")
window.show_all()
Gtk.main()
The error that my program does when i click the button is:
Traceback (most recent call last):
File "/home/pi/Downloads/showShedduleWiGreen.py", line 70, in show_script
dialog = gtk.FileChooserDialog("Open...", None, gtk.FILE_CHOOSER_ACTION_OPEN, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
File "/usr/lib/python3/dist-packages/gi/__init__.py", line 62, in __getattr__
raise AttributeError(_static_binding_error)
AttributeError: When using gi.repository you must not import static modules like "gobject". Please change all occurrences of "import gobject" to "from gi.repository import GObject". See: https://bugzilla.gnome.org/show_bug.cgi?id=709183

For starters, you are mixing up Python2 and Python3, and modules from introspection and older non-introspection modules:
from gi.repository import Gtk
from gi.repository import GObject as gobject
import pygtk
import gtk
You are importing Gtk and gtk, which are not mixable. You also don't use GObject in your code, so don't import it.
Leave just
from gi.repository import Gtk
and change all 'gtk's in your code to Gtk.
Then, take care of the indenting - else you'll still have errors. And I couldn't test anymore, as the glade file is not included...

Related

ModuleNotFoundError in Python 3.8.3

I've a problem with the importations of modules in Python. I'm doing a project with PyQt and I'm trying to refactor and restructure it.
The hierarchy is the next:
./main.py
./logic/__init__.py
./logic/transforms.py
./logic/hopfield.py
./gui/__init__.py
./gui/interface.py
./gui/mplwidget.py
./img
The error:
Traceback (most recent call last):
File "...\main.py", line 5, in <module>
from gui.interface import Ui_MainWindow
File ...\gui\interface.py", line 215, in <module>
from mplwidget import MplWidget
ModuleNotFoundError: No module named 'mplwidget'
The file interface.py
class Ui_MainWindow(object):
.
.
.
from mplwidget import MplWidget
The file main.py
import sys
import matplotlib
import numpy as np
from gui.interface import Ui_MainWindow
from gui.weightMatrix import Ui_Dialog
from gui.table import TableModel
from logic.hopfield import learn, searchPattern
from logic.transforms import transformVector, transformVectors
from PyQt5 import QtCore, QtGui, QtWidgets
class Actions(Ui_MainWindow):
def __init__(self):
.
.
.
I don't understand why it doesn't work, since inside the module if I run the interface file it works fine together with mplwidget as a module.
File ...\gui\interface.py", line 215, in
from mplwidget import MplWidget
your interface.py should have
absolute import:
from gui.mplwidget import MplWidget
or
relative import:
from .mplwidget import MplWidget
In addition, a great blog that explains the two different imports

Pyinstaller --- Not compiling my GUI script

Been playing around with pyinstaller and cx_freeze the last couple of days trying to get my app to run as a .exe.
In python everything works as intended.
I have the following items in a folder ready for compile...
rawCodes.py is my main.
mcnc.py is my PyQt5 GUI.
mcnclogo_rc.py contains all the images i used in my GUI.
The following is a list of my imports in my main...
import sqlite3
from mcnc import Ui_MainWindow
import mcnclogo_rc
from PyQt5 import QtCore,QtGui,QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidgetItem,
QDialog, QComboBox
import sys
import math
It seems that when i run pyinstaller it completes the process and produces 3 folders as expected.
The exe is clearly inside the dist folder and all appears to have worked.
However i run the exe and it just opens then closes again and nothing comes up.
I am convinced that my mcnc.py file is not being included and therefore i am not seeing a GUI (pyqt5).
Does anyone know how to specifically list mcnc.py in my SPEC file to make sure it is included...same with mcnclogo_rc.
EDIT
I have run the .exe from CMD and i am getting the following traceback...
G:\Yans work in progress\Yans python\Qt\to
compile\dist\rawCodes>rawCodes.exe
Traceback (most recent call last):
File "rawCodes.py", line 3287, in <module>
File "rawCodes.py", line 22, in __init__
File "rawCodes.py", line 3101, in Load_StainlessDb
sqlite3.OperationalError: no such table: stainless
[13020] Failed to execute script rawCodes
Could it be that my database isnt getting packed properly in to the dist/build?
EDIT 2
I have changed the sqlite3 pathing so it is dynamic however it is still giving exactly the same error...
import sqlite3
import mcnc
from mcnc import Ui_MainWindow
import mcnclogo_rc
from PyQt5 import QtCore,QtGui,QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidgetItem,
QDialog, QComboBox
import sys
import math
import os
package_dir = os.path.abspath(os.path.dirname(__file__))
db_dir = os.path.join(package_dir, 'codes.db')
print(db_dir)
conn = sqlite3.connect(db_dir)
c = conn.cursor()
c.execute('')
def stainless_list(self):
stainless_getlist = []
content = 'SELECT grade FROM stainless ORDER BY prefix ASC'
res = conn.execute(content)
for row in res:
stainless_getlist.append(row[0])
conn.close
stainless_getlist.insert(0, "Select...")
self.comboBox_2.clear()
self.comboBox_2.addItems(stainless_getlist)
#print(stainless_getlist)
return
Then i still get the following error...
G:\Yans work in progress\Yans python\Qt\to
compile\dist\rawCodes>rawCodes.exe
Traceback (most recent call last):
File "rawCodes.py", line 3287, in <module>
File "rawCodes.py", line 22, in __init__
File "rawCodes.py", line 3101, in Load_StainlessDb
sqlite3.OperationalError: no such table: stainless
[14664] Failed to execute script rawCodes
EDIT 3
Here is the print of my dir paths once compiled...
G:\Yans work in progress\Yans python\Qt\to
compile\dist\rawCodes>rawCodes.exe
G:\Yans work in progress\Yans python\Qt\to compile\dist\rawCodes
G:\Yans work in progress\Yans python\Qt\to compile\dist\rawCodes\codes.db
Here is my code and imports...
import sqlite3
import mcnc
from mcnc import Ui_MainWindow
import mcnclogo_rc
from PyQt5 import QtCore,QtGui,QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidgetItem,
QDialog, QComboBox
import sys
import math
import os
import os.path as op
try:
this_file = __file__
except NameError:
this_file = sys.argv[0]
this_file = op.abspath(this_file)
if getattr(sys, 'frozen', False):
application_path = getattr(sys, '_MEIPASS',
op.dirname(sys.executable))
else:
application_path = op.dirname(this_file)
sqlite_conn = os.path.join(application_path, 'codes.db')
print(application_path)
print(sqlite_conn)
conn = sqlite3.connect(sqlite_conn)
c = conn.cursor()
c.execute('')
but once compiled and trying to run from the dist it can no longer see the tables in the db.
EDIT 4
I changed my code to the following...
import sqlite3
import mcnc
from mcnc import Ui_MainWindow
import mcnclogo_rc
from PyQt5 import QtCore,QtGui,QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidgetItem,
QDialog, QComboBox
import sys
import math
import os
import os.path as op
try:
this_file = __file__
except NameError:
this_file = sys.argv[0]
this_file = op.abspath(this_file)
if getattr(sys, 'frozen', False):
application_path = getattr(sys, '_MEIPASS', op.dirname(sys.executable))
else:
application_path = op.dirname(this_file)
sqlite_conn = os.path.join(QApplication.applicationDirPath(), 'codes.db')
print(application_path)
print(sqlite_conn)
conn = sqlite3.connect(sqlite_conn)
c = conn.cursor()
c.execute('')
I now get the following traceback...
G:\Yans work in progress\Yans python\Qt\to
compile\dist\rawCodes>rawCodes.exe
QCoreApplication::applicationDirPath: Please instantiate the QApplication
object first
G:\Yans work in progress\Yans python\Qt\to compile\dist\rawCodes
codes.db
Traceback (most recent call last):
File "rawCodes.py", line 3303, in <module>
File "rawCodes.py", line 38, in __init__
File "rawCodes.py", line 3117, in Load_StainlessDb
sqlite3.OperationalError: no such table: stainless
[3268] Failed to execute script rawCodes
EDIT 5
app = QApplication(sys.argv)
sqlite_conn = os.path.join(QApplication.applicationDirPath(), 'codes.db')
G:\Yans work in progress\Yans python\Qt
C:/Program Files (x86)/Python37-32\codes.db
Got a straight up error and couldnt connect to the db at all.
The db folder now points to C: drive.
After many hours i noticed that the script was failing at the point where it tried to access the tables of the db and not at the connect statement in my compile.
Upon further inspection i noticed that after the compile has run the codes.db was missing until i clicked the .exe to run. Then a codes.db popped out of the exe with 0kb and no tables.
I have concluded that i need to research how to include the original .db file in the compile and not allow it to create a new empty .db in its absence.
I have tested this by over writing the empty .db with the original .db and suddenly my .exe works perfectly.
I believe the answer is simple. Let's analyse the stacktrace
The red part is the error name: OperationalError. From the docs:
Exception raised for errors that are related to the database’s operation and not necessarily under the control of the programmer, e.g. an unexpected disconnect occurs, the data source name is not found, a transaction could not be processed, etc. It is a subclass of DatabaseError.
But, the green part tells us:
no such table: stainless
which simply means the table is not found as it was either deleted or it was not created at all.
And, as far as i can see, no table creation code is to be found. It's not a PyInstaller error.
Your exe closes then opens up because you have no body code. In your main code's body add this:
input()
That should fix it.

gtk3 Windows - Exe made by cx_freeze gives ValueError : Namespace Gtk not available

I have an app built in Gtk3 Python3.4(Windows) which works fine on Pycharm but when I create an exe using cx_freeze , It gives the following error -
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\cx_Freeze\initscripts\Console.py", line 27, in <module>
exec(code, m.__dict__)
File "obfuscated.py", line 2, in <module>
File "C:\Python34\lib\site-packages\gi\__init__.py", line 118, in require_version
raise ValueError('Namespace %s not available' % namespace)
ValueError: Namespace Gtk not available
The imports I've done in my app are -
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, Gio, GObject
import sqlite3
My setup.py file -
from cx_Freeze import setup, Executable
#import os
#os.environ['TCL_LIBRARY'] = "C:\\Users\\BRAHMDEV\\AppData\\Local\\Programs\\Python\\Python36\\tcl\\tcl8.6"
#os.environ['TK_LIBRARY'] = "C:\\Users\\BRAHMDEV\\AppData\\Local\\Programs\\Python\\Python36\\tcl\\tk8.6"
executables = [
Executable("obfuscated.py",
icon="evm_bg_KYa_icon.ico")
]
buildOptions = {"packages":["sqlite3", "gi"], "include_files":["mydatabase.db", "AgeSearch.png", "android.png", "candidate.jpg",
"CasteSearch.png", "duplicate.png", "FileStyle.css", "GenSearch.png", "Hof.png", "Placeholder.png", "voter slip.png"]}
setup(name="Voter Search Engine",
version="2.1.3",
description="Voter Search Engine Setup",
options={"build_exe":buildOptions},
executables=executables,
)
And when I executed python setup.py build this was what took place -
https://pastebin.com/uutDJ8at
Well , I tried this on Pyinstaller as well got the same error , but found the solution
here

Python version related error

I am trying to generate an HTML test report by using Selenium webdriver library HTMLTestRunner. I am using Python 3.4 version and I have a version related error. Refer following snippet.
import unittest`enter code here`
import HTMLTestRunner
from selenium import webdriver
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.common.keys import Keys
class GreenlamTest(unittest.TestCase):
#classmethod
def setUp(cls):
cls.driver=webdriver.Firefox()
cls.driver.implicitly_wait(30)
cls.driver.maximize_window()
cls.driver.get('https://www.google.co.in')
def test_checkTitle(self):
assert "Google" in self.driver.title
def test_searchtest(self):
driver = self.driver
elem = self.driver.find_element_by_name("q")
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
#classmethod
def tearDown(cls):
cls.driver.quit()
if __name__ == '__main__':
HTMLTestRunner.main
Output
Finding files... done.
Traceback (most recent call last):
File "C:\Users\vaibhav\Desktop\Selenium Softwares\eclipse-jee-luna-SR2-win32-x86_64\eclipse\plugins\org.python.pydev_4.0.0.201504132356\pysrc\pydev_runfiles.py", line 468, in __get_module_from_str
mod = __import__(modname)
File "C:\Users\vaibhav\Desktop\Selenium Softwares\Practice\pythondemo\Htmlreport.py", line 2, in <module>
import HTMLTestRunner
File "C:\Users\vaibhav\Desktop\Selenium Softwares\Practice\pythondemo\HTMLTestRunner.py", line 94, in <module>
import StringIO
ImportError: No module named 'StringIO'
ERROR: Module: Htmlreport could not be imported (file: C:\Users\vaibhav\Desktop\Selenium Softwares\Practice\pythondemo\Htmlreport.py).
Importing test modules ... done.
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
You are getting error because your folder name Selenium Softwares has a space in it where your Htmlreport is present. Replace the folder name to exclude space out of it, probably an underscore or camelCase, etc... like this Selenium_Softwares . Here's how -
file: C:\Users\vaibhav\Desktop\Selenium_Softwares\Practice\pythondemo\Htmlreport.py)
Hope this helps.

Error to compile file PyObject (Gtk ) with Pydev

I'm build application with pyobject (gtk) in Pydev , but i'm try to create a window
the following way:
Class Ventana
from gi.overrides import Gtk
class Ventana( Gtk.Window ):
def __init__( self,titulo ):
Gtk.Window.__init__(self,title=titulo )
self.connect("delete-event",Gtk.main_quit )
Class Aplicacion( Main):
def main():
win = Ventana()
if __name__ == '__main__':
main()
but I'm try to compile te App, show the following mistake:
Traceback (most recent call last):
File "/home/demian/workspace/NidhugsRPG/nidhugs/presentacion/Consola.py", line 6, in
<module>
from gi.overrides import Gtk
File "/usr/lib/python3/dist-packages/gi/overrides/Gtk.py", line 35, in <module>
Gtk = modules['Gtk']._introspection_module
KeyError: 'Gtk'
I'm try use the import
from gi.repository import Gtk
but, not works,because moudule not found.So i'm use the import:
from gi.overrides import Gtk
¿How to fix my trouble?
Sorry for my bad English
Thanks.

Resources