so the program that I am trying to make accepts only a valid month and year between 2018-2050 but pycharm crushes with the message "Process finished with exit code -1073740791 (0xC0000409)" and I know in which line it does that, but I dont know how to fix it, here is the code I am using and the error appers in the last elif when ok is clicked. I have tried reinstalling python and pycharm, as suggested in other posts but nothing happens.
import sys
from PyQt5.QtWidgets import (QVBoxLayout,QHBoxLayout,QPushButton,
QLineEdit,QApplication,QLabel,QCheckBox,QWidget)
class Window(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def accepted(month, year):
conf = True
try:
int(month)
int(year)
except ValueError:
conf = False
if conf:
if (int(month) > 12 or int(month) < 1) or (int(year) < 2019 or
int(year) > 2050):
conf = False
return conf
def init_ui(self):
self.btn1=QPushButton('OK')
self.btn2=QPushButton('Clear')
self.btn3=QPushButton('Cancel')
self.txt1=QLabel('Month input')
self.txt2=QLabel('Year Input')
self.b1=QLineEdit()
self.b2=QLineEdit()
h_box1: QHBoxLayout=QHBoxLayout()
h_box1.addWidget(self.txt1)
h_box1.addWidget(self.b1)
h_box2 = QHBoxLayout()
h_box2.addWidget(self.txt2)
h_box2.addWidget(self.b2)
h_box3=QHBoxLayout()
h_box3.addWidget(self.btn1)
h_box3.addWidget(self.btn2)
h_box3.addWidget(self.btn3)
layout=QVBoxLayout()
layout.addLayout(h_box1)
layout.addLayout(h_box2)
layout.addLayout(h_box3)
self.setLayout(layout)
self.setWindowTitle('Calendar Manager')
self.show()
self.btn1.clicked.connect(self.buttons)
self.btn2.clicked.connect(self.buttons)
self.btn3.clicked.connect(self.buttons)
def buttons(self):
clicked=self.sender()
if clicked.text() == 'Clear':
self.b1.clear()
self.b2.clear()
elif clicked.text() == 'Cancel':
sys.exit()
elif clicked.text() == 'OK':
if not accepted(self.b1.text(),self.b2.text()):
self.b1.clear()
self.b2.clear()
else:
pass
app=QApplication(sys.argv)
a_window=Window()
sys.exit(app.exec_())
So the problem is the self in two instances, first as an argument in def accepted and secondly the self.accepted when I call it.
As you mentioned, the problem is with function accepted. If you intended it to be a class method, it should have been defined as:
def accepted(self, month, year):
....
You don't use 'self' in the method, so it could be turned into a static method:
#staticmethod
def accepted(month, year):
....
Related
I'm using PyQt5 and Python3, I use 3 QThread classes to run something and after they are done I need to execute a 4th QThread class. But the execution of the 4th need to take place after all of the QThread classes finish work, or only 2 or only 1. It must not run while the first 3 are working.
I looked on the internet but I couldn't find a solution. My code looks like this:
class MyWindow(QtWidgets.QMainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
file_path = os.path.abspath('builder_gui.ui')
uic.loadUi(file_path, self)
self.obj1 = TasksThread1(self.comboBox.currentText(),self.comboBox_6.currentText())
self.obj2 = TasksThread2(self.comboBox_2.currentText(),self.comboBox_5.currentText())
self.obj3 = TasksThread3(self.comboBox_3.currentText(),self.comboBox_4.currentText())
self.obj4 = TasksThread4()
self.menubar.setNativeMenuBar(False)
self.progressVal = 1
self.cwd = os.getcwd()
self.obj1.newValueProgress.connect(self.increment_progress)
self.obj1.message.connect(self.status_bar)
self.obj2.newValueProgress.connect(self.increment_progress)
self.obj2.message.connect(self.status_bar)
self.obj3.newValueProgress.connect(self.increment_progress)
self.obj3.message.connect(self.status_bar)
self.obj4.newValueProgress.connect(self.increment_progress)
self.obj4.message.connect(self.status_bar)
self.obj4.doneSignal.connect(self.calculate_done_limit)
self.pushButton.pressed.connect(self.execute_build_script)
def calculate_done_limit(self):
limitCalc = 100 - int(self.progressBar.value())
self.increment_progress(limitCalc)
def run_gits_all(self):
if self.crowdTwistCheck.isChecked():
self.obj1.start()
else:
pass
if self.ThemeCheck.isChecked():
self.obj2.start()
else:
pass
if self.mainAwsCheck.isChecked():
self.obj3.start()
else:
pass
def execute_build_script(self):
self.progressBar.setValue(1)
self.progressVal = 1
self.run_gits_all()
def execute_last_part(self):
self.obj4.start()
def status_bar(self, value_in):
read1 = self.textBrowser.toPlainText()
self.textBrowser.setText(read1 + "\n" + value_in)
def increment_progress(self,valueIn):
self.progressVal += valueIn
self.progressBar.setValue(self.progressVal)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())
My first 3 QThreads are like this:
class TasksThread1(QThread):
newValueProgress = QtCore.pyqtSignal(int)
message = QtCore.pyqtSignal(str)
doneSignal = QtCore.pyqtSignal()
def __init__(self, branch, git):
QThread.__init__(self)
self.branch = branch
self.git = git
def remove_folder(self):
do_something_1
def CrowdTwistRepo(self):
do_something_2
def run(self):
self.remove_folder()
self.CrowdTwistRepo()
My last QThread looks like this:
class TasksThread4(QThread):
newValueProgress = QtCore.pyqtSignal(int)
message = QtCore.pyqtSignal(str)
doneSignal = QtCore.pyqtSignal()
def __init__(self):
QThread.__init__(self)
def gulp_sass_function(self):
do_something_1
def gulp_uglify_function(self):
do_something_2
def zipping_function(self):
do_something_3
def run(self):
self.gulp_sass_function()
self.gulp_uglify_function()
self.zipping_function()
If I run the code, all of the QThreads start and I want my 4th QThread to start only after the first 3 have done working. I used QThreads to improve the GUI experience, the GUI froze alot.
thanks,
When your first 3 threads are done, send a signal. Then connect this signal to a function that will start the last thread.
I am running a small unittest to check the roman number converter. Here is my code :-
class RomConverter(object):
def __init__(self):
self.digital_mapping = {"M":1000, "D":500, "C":100, "L":50, "X":10, "V":5, "I":1}
def convert(self, rom_num):
value = 0
for char in rom_num:
val += self.digital_mapping[char]
return value
import unittest
class RomConverterTest(unittest.TestCase):
def settingUp(self):
print ("Creating a new RomConverter...")
self.cvt = RomConverter()
def tearDown(self):
print ("Destroying the RomConverter...")
self.cvt = None
def test_empty_num(self):
self.assertTrue(self.cvt.convert("") == 0)
self.assertFalse(self.cvt.convert("") > 0)
def test_no_rom_num(self):
self.assertRaises(TypeError,self.cvt.convert, None)
if __name__ == "__main__":
unittest.main()
But I am getting this message when I run the code :-
Traceback (most recent call last):
File "receipe2 - Copy.py", line 31, in test_empty_roman_numeral
self.assertTrue(self.cvt.convert_to_decimal("") == 0)
AssertionError: False is not true
I see two problems in your code.
First def settingUp(self): should be def setUp(self):
And the return of def convert(self, rom_num): is indented to much. In result the method does not return 0 incase of an empty string.
Here is a working version:
class RomConverter(object):
def __init__(self):
self.digital_mapping = {"M":1000, "D":500, "C":100, "L":50, "X":10, "V":5, "I":1}
def convert(self, rom_num):
value = 0
for char in rom_num:
value += self.digital_mapping[char]
return value
import unittest
class RomConverterTest(unittest.TestCase):
def setUp(self):
print ("Creating a new RomConverter...")
self.cvt = RomConverter()
def tearDown(self):
print ("Destroying the RomConverter...")
self.cvt = None
def test_empty_num(self):
self.assertTrue(self.cvt.convert("") == 0)
self.assertFalse(self.cvt.convert("") > 0)
def test_no_rom_num(self):
self.assertRaises(TypeError,self.cvt.convert, None)
if __name__ == "__main__":
unittest.main()
import sys
import time
import logging, os
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class Watcher:
DirectoryToWatch = 'C:\\Users\\dbeiler\\Documents\\Visual Studio 2015\\Projects\\New folder\\'
def __init__(self):
self.observer = Observer()
def run(self):
event_handler = Handler()
self.observer.schedule(event_handler, self.DirectoryToWatch, recursive=True)
self.observer.start()
try:
while True:
time.sleep(5)
except:
self.observer.stop()
print ("Error")
self.observer.join()
class Handler(FileSystemEventHandler):
#staticmethod
def on_any_event(event):
if event.is_directory:
return None
elif event.event_type == 'modified':
# Take any action here when a file is first created.
os.system('python writetodata.py')
sys.exit
time.sleep(5)
if __name__ == '__main__':
w = Watcher()
w.run()
The application works when i copy a file to the location, it will execute my script, however the script keeps cycling, i would like it to stop and wait for another file once its already been written, not sure what im missing
I moved one of my directory folders, and now its writing to my output excel file twice, i assume its because 1.) its being opened, and 2.) its saving.
how about looking for a specific object type only like xlsx'?
My tkinter application runs fine, but to implement dbus functionality I had to use gobject. Got it working and all, except that, running both tkinter's and gobject's mainloops makes the "close window" button from the standard window manager ('x' button in the window interface) not to work. :/ Everything else works fine, including resizing, minimizing/maximizing, restoring, and moving the window.
Any help is appreciated,
Thanks,
Little code snippet:
import dbus
from dbus.service import Object
from dbus.mainloop.glib import DBusGMainLoop
class TBOPlayerDBusInterface (Object):
tboplayer_instance = None
def __init__(self, tboplayer_instance):
self.tboplayer_instance = tboplayer_instance
dbus_loop = DBusGMainLoop()
bus_name = dbus.service.BusName("org.tboplayer.TBOPlayer", bus = dbus.SessionBus(mainloop = dbus_loop))
Object.__init__(self, bus_name, "/org/tboplayer/TBOPlayer")
#dbus.service.method('org.tboplayer.TBOPlayer', in_signature = 'as')
def openFiles(self, files):
self.tboplayer_instance._add_files(files)
# ***************************************
# MAIN
# ***************************************
if __name__ == "__main__":
datestring=" 28 Fev 2017"
dbusif_tboplayer = None
try:
bus = dbus.SessionBus()
bus_object = bus.get_object("org.tboplayer.TBOPlayer", "/org/tboplayer>/TBOPlayer", introspect = False)
dbusif_tboplayer = dbus.Interface(bus_object, "org.tboplayer.TBOPlayer")
except Exception, e:
print e
if dbusif_tboplayer is None:
tk.CallWrapper = ExceptionCatcher
bplayer = TBOPlayer()
TBOPlayerDBusInterface(bplayer)
def refresh_player():
bplayer.root.update()
return True
def run_gobject():
gobject.MainLoop().run()
gobject.idle_add(refresh_player)
bplayer.root.after(100, run_gobject)
bplayer.root.mainloop()
else:
if len(sys.argv[1:]) > 0:
dbusif_tboplayer.openFiles(sys.argv[1:])
exit()
I found the problem. For some reason, using tkinter's and gobject's mainloops interferes with the behavior of the WM_DELETE_WINDOW event, which I was using for saving some data before closing the program. Solved the problem by binding to the Configure event instead. And now the main method is as follows:
if __name__ == "__main__":
datestring=" 28 Fev 2017"
dbusif_tboplayer = None
try:
bus = dbus.SessionBus()
bus_object = bus.get_object("org.tboplayer.TBOPlayer", "/org/tboplayer/TBOPlayer", introspect = False)
dbusif_tboplayer = dbus.Interface(bus_object, "org.tboplayer.TBOPlayer")
except Exception, e:
print e
if dbusif_tboplayer is None:
tk.CallWrapper = ExceptionCatcher
bplayer = TBOPlayer()
TBOPlayerDBusInterface(bplayer)
gobject_loop = gobject.MainLoop()
def refresh_player():
try:
bplayer.root.update()
return True
except Exception, e:
bplayer.quit_omx()
gobject_loop.quit()
def run_gobject():
gobject_loop.run()
gobject.idle_add(refresh_player)
bplayer.root.after(100, run_gobject)
bplayer.root.mainloop()
else:
if len(sys.argv[1:]) > 0:
dbusif_tboplayer.openFiles(sys.argv[1:])
exit()
I'm new to python, and I'm using python 3.5 on Ubuntu. I did some research about this question and i found a lot of answers. What I'm doing looks like what everyone is saying I'm supposed to do, but I'm still receiving errors.
import csv
import sys
Class State():
started = False
def waiting(self):
self.started
if self.started == False:
self.started = True
return
def buy_in(self, col):
if self.started == False:
return
else:
print(col)
def read_file(file):
csv_list = csv.reader(file)
header = True
for row in csv_list:
if header:
header = False
continue
col = float(row[5])
if col < 0 :
State.waiting()
if col >= 0:
State.buy_in(col)
file.close()
def main(filename):
file = open(filename)
read_file(file)
def __name__ == '__main__':
main(sys.argv[1])
I'm just trying to create a pseudo FSM in python, by using a class and methods. I just need to create a global bool. I don't really understand what I'm doing wrong. IF someone doesn't mind giving me some clarity, I would appreciate it. Thanks
To clarify, I'm getting the NameError on the if statement in the buy_in method.
Try:
class State():
started = False
def waiting(self):
if self.started == False:
self.started = True
return
def buy_in(self, col):
if self.started == False:
return
else:
print(col)
Since started is a class variable you need to use self. when calling it. It is not a global variable so you do not need the global call. Each of the methods inside of the class also needs self as an argument.