Python is crashing while trying to clear combobox in pyqt5 - python

I started today with qt compiler, so I don't have much experience in building gui. My project is about to create dynamic smart check boxes to define axes and at the end to plot several subplots to a figure.
I tried to create dynamic combo boxes that change every time I change my current selection in the combo box.
The big issue is that it crash every time i try to change a selection in the combo box.
I tried to use .clear() method but it crash every time I clicked on it.
Edit: I changed the code to make producible code. After clicking on "Load Files", you will be able the combo boxes filled. If you will change the combo box "Choose message" for example, the python crash.
The GUI
# ------------------------------------------------- -----
# ---------------------- main.py ------------------- ----
# --------------------------------------------- ---------
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.uic import loadUi
from PyQt5.QtCore import pyqtSlot
import threading , os, subprocess, importlib, platform
# Decode_class = 'MAVLinkBinFileDecoder'
# Module = importlib.import_module(Decode_class)
from matplotlib.backends.backend_qt5agg import (NavigationToolbar2QT as NavigationToolbar )
import numpy as np
import random
class MatplotlibWidget(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
loadUi("gui.ui", self)
self.setWindowTitle ( "PyQt5 & Matplotlib Example GUI" )
self.loadfiles = 0
self.first_run = 0
self.progressBar.setProperty("value", 0)
# self.pushButton_load_files.setEnabled(False)
self.pushButton_add_to_graph.setEnabled(False)
self.pushButton_choose_xml_file.clicked.connect(self.open_xml_FileNamesDialog)
self.pushButton_choose_bin_files.clicked.connect(self.open_bin_FileNamesDialog)
self.pushButton_load_files.clicked.connect(self.load_files)
self.comboBox_choose_file.currentIndexChanged.connect(self.selectionchange_file)
self.comboBox_message.currentIndexChanged.connect(self.selectionchange_message)
self.comboBox_system_id.currentIndexChanged.connect(self.selectionchange_system_id)
self.pushButton_save_plot.clicked.connect(self.update_graph)
self.file_to_graph_demo = [({'HEARTBEAT':[{'type':[12],'autopilot':[0]},{'type':[2,2,0],'autopilot':[0,0,0]}], 'CHAMBER_STATUS':[{'time_boot_ms':[1,1,1], 'chamber_num':[1,2,3]}], 'ATTITUDE':[{'test':[0,0,0,],'check':[1,1,1]}, {'test':[0,0,0,],'check':[1,1,1]}, 0 , 0, {'test':[0,0,0,],'check':[1,1,1]}]},'test')]
self.addToolBar(NavigationToolbar(self .MplWidget.canvas, self))
#pyqtSlot()
def open_xml_FileNamesDialog(self):
self.loadfiles += 1
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
self.filename, _ = QFileDialog.getOpenFileNames(self, "QFileDialog.getOpenFileNames()", "",
"Xml Files (*.xml)", options=options)
if self.loadfiles == 2:
self.pushButton_load_files.setEnabled(True)
self.pushButton_choose_xml_file.setVisible(False)
#pyqtSlot()
def open_bin_FileNamesDialog(self):
self.loadfiles += 1
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
self.list_of_file_paths, _ = QFileDialog.getOpenFileNames(self, "QFileDialog.getOpenFileNames()", "",
"Bin Files (*.bin)", options=options)
if self.loadfiles == 2:
self.pushButton_load_files.setEnabled(True)
self.pushButton_choose_bin_files.setVisible(False)
#pyqtSlot()
def load_files(self):
# parse = Module.Logic_bin_to_mat_parser(self.filename[0])
# parse.generate_dialect_from_xml() # Run Mavgenerate xml function
# value = 19
# self.progressBar.setProperty("value", value)
# self.file_to_graph = []
# for path in self.list_of_file_paths: # Parse and create Matlab from each bin file
# parse.decode_messages(path)
# parse.create_dictionary_of_amount_of_messages_by_type()
# parse.parse_bin_to_mat()
# self.file_to_graph.append((parse.save, parse.file_base_name))
# parse.convert_parse_dictionary_to_mat()
# value += (100 - 20) / len(self.list_of_file_paths)
# self.progressBar.setProperty("value", value)
# value = 100
# self.progressBar.setProperty("value", value)
# self.pushButton_load_files.setVisible(False)
# self.progressBar.setVisible(False)
for option in self.file_to_graph_demo:
self.comboBox_choose_file.addItem(option[1])
#pyqtSlot()
def selectionchange_file(self):
self.first_run += 1
combobox_enty = self.comboBox_choose_file.currentText()
self.file_idx = self.comboBox_choose_file.findText(combobox_enty)
list_of_messages = []
for message in self.file_to_graph_demo[self.file_idx][0].items():
list_of_messages.append(message[0])
if self.first_run >= 1:
self.comboBox_message.clear()
self.comboBox_message.addItems(list_of_messages)
#pyqtSlot()
def selectionchange_message(self):
self.first_run += 1
self.combobox_entry_message = self.comboBox_message.currentText()
self.message_idx = self.comboBox_message.findText(self.combobox_entry_message)
list_of_system_ids = []
count = 0
for idx, system_id in enumerate(self.file_to_graph_demo[self.file_idx][0][self.combobox_entry_message]):
if system_id != 0:
count += 1
list_of_system_ids.append(str(idx+1))
if self.first_run >= 2:
self.comboBox_system_id.clear()
self.comboBox_system_id.addItems(list_of_system_ids)
#pyqtSlot()
def selectionchange_system_id(self):
self.combobox_entry_system_id = int(self.comboBox_system_id.currentText())-1
self.system_id_idx = self.comboBox_system_id.findText(str(self.combobox_entry_system_id))
for field in self.file_to_graph_demo[self.file_idx][0][self.combobox_entry_message][self.system_id_idx]:
self.comboBox_y_axis.addItem(field)
self.comboBox_x_axis.addItem(field)
def update_graph(self):
fs = 500
f = random.randint(1, 100)
ts = 1 / fs
length_of_signal = 100
t = np . linspace (0, 1, length_of_signal )
cosinus_signal = np . cos ( 2 * np . pi * f * t )
sinus_signal = np . sin ( 2 * np . pi * f * t )
self.MplWidget.canvas.axes.clear()
self.MplWidget.canvas.axes.plot(t,cosinus_signal)
self.MplWidget.canvas.axes.plot(t,sinus_signal)
self.MplWidget.canvas.axes.legend(('cosinus', 'sinus'), loc='upper right')
self.MplWidget.canvas.axes.set_title(' Cosinus - Sinus Signal')
self.MplWidget.canvas.draw()
if __name__ == '__main__':
app=QApplication([])
app.setStyle('Fusion')
window=MatplotlibWidget()
window.show()
app.exec_()

Your issue seems to be in MatplotlibWidget.selectionchange_system_id(). You are trying to cast the current text of self.comboBox_system_id to an int, but this will cause an exception when the current text can't be converted. This is the case just after self.comboBox_system_id is cleared because at that point the current text of the combi box is an empty string. The easiest way to get around this is to test if the current text can be cast to an integer first before continuing, i.e.
def selectionchange_system_id(self):
if self.comboBox_system_id.currentText().isdigit():
self.combobox_entry_system_id = int(self.comboBox_system_id.currentText())-1
...

Related

QTextTable Insert a Line in a Cell

I'm trying to put a line in the header of a QTextTable.
I have tried three ways to do it:
Option 1 - I have used the option to modify the background color of the cell. The problem is, I can't narrow the line.
Option 2 - I insert an Html code, but I cannot modify the properties of the line.
Option 3 - I have created an image, I have drawn a line, but when I put that the length of the line is the width of the page the table deforms. I can see the line in the screen, but not when I print it.
Option 4 - Suggestion of musicamente. Not works because not write a red line, but background is blue, so the format is tranfer.
Option 1
Option 2
Option 3
Option 4
The code is:
from PyQt5.QtWidgets import QApplication ,QWidget
from PyQt5.QtPrintSupport import QPrinter,QPrintPreviewDialog
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QTextDocument,QTextCursor,QPainter,QFont,QImage,QTextTableFormat,QPixmap,QTextLength,QPixmap,QTextBlockFormat,QTextCharFormat,QPen,QTextFrameFormat,QIcon,QColor,QBrush
class QPrint_Table(QWidget):
def __init__(self,table,fields):
super().__init__()
self.table=table
self.fields=fields
self.printer = QPrinter(QPrinter.HighResolution)
dialog = QPrintPreviewDialog()
dialog.paintRequested.connect(self.handlePaintRequest)
dialog.exec_()
def handlePaintRequest(self, printer):
document = self.makeTableDocument()
document.print_(printer)
def makeTableDocument(self):
document = QTextDocument()
cursor = QTextCursor(document)
rows = len(self.table)
columns = len(self.fields)
self.pageSize = self.printer.pageRect().size()
tableFormat = QTextTableFormat()
#tableFormat.setAlignment(QtCore.Qt.AlignRight) # Justify Table
#tableFormat.setBackground(QtGui.QColor('#e0e0e0'))
tableFormat.setCellPadding(4)
tableFormat.setCellSpacing(0)
tableFormat.setBorder(0)
tableFormat.setWidth(QTextLength(QTextLength.PercentageLength, 100))
table_text = cursor.insertTable(rows + 2, columns, tableFormat)
format = table_text.format()
format.setHeaderRowCount(1)
table_text.setFormat(format)
format = cursor.blockCharFormat()
format.setFontWeight(QFont.Bold)
for column in range(columns):
cursor.setCharFormat(format)
cursor.insertText(fields[column])
cursor.movePosition(QTextCursor.NextCell)
table_text.mergeCells(1,0,1,columns)
cell=table_text.cellAt(1,0)
format =cell.format()
line_option=4
if line_option==1:
# Option 1 - For black Line
format =cell.format()
format.setBackground(Qt.black)
cell.setFormat(format)
format_low=cursor.blockCharFormat()
font=QFont ( "Arial" , 0 )
font.setPointSizeF(0.9)
format_low.setFont(font)
cursor.setCharFormat(format_low)
cursor.insertText('.')
elif line_option==2:
# Option 2
cursor.insertHtml('<html> <body> <hr style="height:5px;border-width:3px;color:red;background-color:green"></body> </html>')
elif line_option==3:
# Option 3
height=20
line_width=self.pageSize.width()
image = QImage(line_width,height,QImage.Format_RGB32)
ratio=self.printer.resolution()/60
image.setDevicePixelRatio(ratio)
painter = QPainter(image)
pen = QPen(Qt.red, height*2)
painter.setPen(pen)
painter.drawLine(0, 0, line_width, 0)
cursor.insertImage(image)
painter.end()
elif line_option==4:
# Option 4
format_cell=format.toTableCellFormat()
format_cell.setBackground(Qt.blue)
format_cell.setBorder(100)
format_cell.setBottomBorder(10)
format_cell.setBottomBorderBrush(QBrush(QColor("red")))
cell.setFormat(format_cell)
cursor.movePosition(QTextCursor.NextCell)
for row in range(rows):
for column in range(columns):
cursor.insertText(str(self.table[row][column]))
cursor.movePosition(QTextCursor.NextCell)
return document
def create_table():
list=[]
for i in range(10):
list.append([i,'Name '+str(i),'Address '+str(i),'City '+str(i),'Country '+str(i)])
fields=['Id','Name','Address','City','Country']
return list,fields
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
table,fields=create_table()
QPrint_Table(table,fields)

Seperating concerns in PyQt5 GUI app. Need seperate Qthread for concurrency

I have a simple GUI window made using PyQt5 Library.
`
import sys, csv, time
from datetime import datetime
from time import strftime,localtime
import threading
import pandas as pd
import numpy as np
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QLabel, QTextEdit, QInputDialog, QLineEdit
from PyQt5 import QtCore
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtGui import QIcon
from PyQt5 import uic
from trade import trade
from pyqtgraph import PlotWidget
import pyqtgraph as pg
from itertools import islice
class UpdateThread(QThread):
signal = pyqtSignal()
def __init__(self, gui):
QThread.__init__(self)
self.gui = gui
def run(self):
try:
# timer = pg.QtCore.QTimer()
# timer.timeout.connect(UI.update_plot(self))
# timer.start(50)
while(True):
self.signal.emit()
time.sleep(5)
except Exception as e:
print(e)
class UI(QMainWindow):
gui = None
p_l = 0.0
display_trades = ''
def __init__(self):
super(UI, self).__init__()
global gui
gui = uic.loadUi('rightside.ui', self)
self.initUI()
self.timer_thread = UpdateThread(gui)
self.timer_thread.signal.connect(self.update_plot)
self.timer_thread.start()
def initUI(self):
self.prices = self.read_prices()
trades = self.get_trades()
list_trade_prices = trades[0].values.tolist()
list_trade_sizes = trades[1].values.tolist()
list_trade_ids = trades[4].drop_duplicates().values.tolist()
as_floats = np.array(list_trade_prices).astype(np.float)
self.set_fields(self.prices)
gui.update_button.clicked.connect(self.on_click)
gui.cancel_button.clicked.connect(self.on_exit)
self.show()
def get_trades(self):
df = pd.DataFrame()
# Get 50 most recent trades
trades = islice(trade.get_product_trades(), 192)
for x in reversed(list(trades)):
# if x['trade_id'] > last_id:
if x['side'] == 'buy':
#more trades that hit the bid force price down
new_row = {0:x['price'], 1:x['size'], 2:1, 3:time.mktime(datetime.timetuple(datetime.now())), 4:x['trade_id']}
df = df.append(new_row, ignore_index=True)
bid_side = True
else:
#more trades that hit the offer force force price up
new_row = {0:x['price'], 1:x['size'], 2:0, 3:time.mktime(datetime.timetuple(datetime.now())), 4:x['trade_id']}
df = df.append(new_row, ignore_index=True)
df = df.drop_duplicates([4], keep='last')
return df
def update_plot(self):
global gui
#set results_chart
trades = UI.get_trades(self)
list_trade_prices = trades[0].values.tolist()
last_price = list_trade_prices[-1]
as_floats = np.array(list_trade_prices).astype(np.float)
gui.results.setText("{0:,.2f}".format(float(last_price)))
gui.results_chart.clear()
gui.results_chart.plot(as_floats)
gui.statusBar().showMessage('Connected')
self.monitor_prices(last_price)
prices = self.read_prices()
self.set_fields(prices)
def get_open_trades(self, btc):
sum_buys = 0.0
open_trades = []
if float(btc) != 0:
for i in trade.get_last_fills():
if i['side'] == 'buy':
sum_buys += float(i['size'])
open_trades.append([i['price'], i['size']])
if sum_buys >= float(btc):
break
return open_trades
def monitor_prices(self, last_price):
global gui
date_local = strftime("%A, %d %b %Y %H:%M:%S", localtime())
stop_enter_price = float(gui.enter_box.toPlainText())
usd = gui.usd_display.text().replace(',', '')
btc = gui.btc_display.text()
trade_amount = ''
if float(last_price) > stop_enter_price and stop_enter_price != 0.0:
if float(usd) > 10.00:
trade_amount = "{0:.2f}".format((float(usd)+(float(btc)*float(last_price)))*0.02718)
result = trade.buy_market(trade_amount)
gui.statusBar().showMessage(str(result))
gui.enter_box.setText('')
with open('stop_enter.txt', 'w') as enter:
enter.write('0.0')
with open('../trades/buys.csv','a') as buys:
writer = csv.writer(buys)
writer.writerow([date_local, last_price, trade_amount, result])
open_trades = self.get_open_trades(btc)
display_trades = ''
trade_amount = 0.0
total_amount = 0.0
STOP_RATE = 0.02
if len(open_trades) != 0:
highest_entry_price = float(open_trades[0][0])
lowest_entry_price = float(open_trades[0][0])
#find lowest price and set stop-loss 2% below that and increment it up
for i,j in enumerate(open_trades):
difference = (float(last_price) - float(open_trades[i][0]))*float(open_trades[i][1])
total_amount += difference
per_diff = str((float(last_price) - float(open_trades[i][0])) / float(open_trades[i][0]))
display_trades += f'{"{0:.3f}".format(float(per_diff)*100)}%\t'
gui.statusBar().showMessage(display_trades)
if highest_entry_price < float(open_trades[i][0]):
highest_entry_price = float(open_trades[i][0])
if lowest_entry_price > float(open_trades[i][0]):
lowest_entry_price = float(open_trades[i][0])
#1R
if float(per_diff) < -STOP_RATE:
if float(btc) > 0.001:
trade_amount = "{0:.8f}".format(float(j[1]))
response = trade.sell_market(trade_amount)
with open('stop_loss.txt', 'w') as enter:
enter.write('0.0')
gui.statusBar().showMessage(str(response))
if float(last_price) < float(gui.stop_box.toPlainText()):
if float(btc) > 0.001:
trade_amount = "{0:.8f}".format(float(btc))
response = trade.sell_market(trade_amount)
gui.statusBar().showMessage(str(response))
def on_click(self):
global gui
enter_price = gui.enter_box.toPlainText()
stop_price = gui.stop_box.toPlainText()
self.write_prices('stop_enter.txt', enter_price)
self.write_prices('stop_loss.txt', stop_price)
gui.statusBar().showMessage('Updated Successfully!')
time.sleep(1.618)
gui.statusBar().showMessage('')
def on_exit(self):
sys.exit(0)
def write_disk(self, date_local, current_price, trade_amount, note, response):
with open('../trades/sells.csv','a') as sells:
writer = csv.writer(sells)
writer.writerow([date_local, current_price, trade_amount, note, response])
def take_it(self, risk_reward, btc):
if float(btc) > 0.001:
response = trade.sell_market(btc)
# playsound(path+'/sounds/sellit.mp3')
write_disk(date_local, current_price, trade_amount, risk_reward, response)
def write_prices(self, file_name, price):
with open(file_name, 'w') as file:
file.write(price)
def set_fields(self, prices):
global gui, p_l
last_price_data = trade.get_last_price()
last_price = last_price_data['price']
last_fill_data = None
while(True):
last_fill_data = trade.get_last_fill()
if 'trade_id' in last_fill_data:
break
last_fill = '0.0'
if last_fill_data['side'] != 'sell':
last_fill = last_fill_data['price']
p_l = float(last_price) - float(last_fill)
gui.enter_box.setText(prices[0])
gui.stop_box.setText(prices[1])
gui.results.setText("{0:,.2f}".format(p_l))
gui.in_price.setText("{0:,.2f}".format(float(last_fill)))
gui.usd_display.setText("{0:,.2f}".format(float(trade.get_usd())))
gui.btc_display.setText("{0:,.8f}".format(float(trade.get_btc())))
def read_prices(self):
content = []
with open('stop_enter.txt', 'r') as enter:
stop_enter = enter.readlines()
content.append(stop_enter[0].rstrip())
with open('stop_loss.txt', 'r') as stop:
stop_loss = stop.readlines()
content.append(stop_loss[0].rstrip())
return content
app = QApplication(sys.argv)
ex = UI()
app.exec_()
`
I am not too familiar with qthreads and how to get them to work. And advice would be greatly appreciated. I just want to Updatethread to call the update_plot once every like 2 seconds or so. Thought this would be pretty simple but this is giving me a headache at this point.
I tried putting the Qtimer in the other thread but then I get an error like 'cannot start timer from other thread'
Thanks for all you help my programmer friends.
For some timing updates it's better to use QTimer and its signal timeout:
from PyQt5.QtCore import QTimer
class UI(QMainWindow):
def __init__(self):
super(UI, self).__init__()
self.timer = QTimer(self)
self.timer.timeout.connect(self.self.update_plot)
# Set 2 seconds interval and start the timer
self.timer.start(2000)
def update_slot(self):
#...

Why after calling a function from an imported python file within a file the PyQt app stops responding?

I have created a PyQt5 GUI in my main.py file which is in a main app folder. In the file for the interface, a button initiates a new class called Calculation (in the file entry.py) passing in the values of several inputs on the page and in this class the startCalculation() method is called. In this method, the different variables are passed to methods in imported python files, then the result of those calculation is returned and passed to the next calculation in another python file. These returns are in the form of arrays containing values (for the y axis which is then displayed using numpy and plotly).
When I run the app and click on the button in the main interface, the app starts loading (rainbow animation on Mac) and it says it is not responding. It is not a problem with the class itself as a normal print test works in the startCalculation() method, but the function from the imported file causes this to happen. Also, no errors are given in the terminal.
The following is code in the PyQt interface file (main.py)
from app import entry
def startButton(self):
massaTotale = float(self.lineEdit.text())
dragCoefficient = float(self.lineEdit_5.text())
liftCoefficient = float(self.lineEdit_6.text())
powerAvionics = float(self.lineEdit_3.text())
powerPayload = float(self.lineEdit_4.text())
airSpeed = float(self.lineEdit_8.text())
valoreUnico = float(self.valoreUnicoEdit.text())
engineEfficiency = float(self.lineEdit_9.text())
turbolenceCoeff = float(self.lineEdit_10.text())
dayOfYear = float(self.day_LineEdit.text())
latitude = float(self.latitude_LineEdit.text())
sunsetHourAngle = float(self.sunsetHourAngle_LineEdit.text())
declination = float(self.declination_LineEdit.text())
newCaluclation = entry.Calculation(massaTotale, dragCoefficient, liftCoefficient, powerAvionics, powerPayload, airSpeed, valoreUnico, engineEfficiency, turbolenceCoeff, dayOfYear, latitude, sunsetHourAngle, declination)
newCaluclation.startCalculation()
And this is the code in the class calling the function in the external file
from app.mainFunctions import pLevel
#constructor method
def __init__(self, massaTotale, dragCoefficient, liftCoefficient, powerAvionics, powerPayload, airSpeed, valoreUnico, efficiencyEngine, turbolenceCoeff, dayOfYear, latitude, sunsetHourAngle, declination):
# calculate plevel
self.totM = massaTotale
self.vair = airSpeed
self.cl = liftCoefficient
self.cd = dragCoefficient
self.efficiencyEngine = efficiencyEngine
self.valoreUnico = valoreUnico
self.powerAvionics = powerAvionics
self.powerPayload = powerPayload
self.turbolenceCoeff = turbolenceCoeff
self.day_of_year = dayOfYear
self.latitude = latitude
self.sunset_hour_angle = sunsetHourAngle
self.declination = declination
#starting the calculation
def startCalculation(self):
self.x_values, self.pLevel_values = pLevel.calculate_pLevel(self.valoreUnico, self.cd, self.cl, self.totM)
'''
self.pEngine_values = pEngine.calculate_pEngine(self.x_values, self.pLevel_values, self.efficiencyEngine, self.turbolenceCoeff)
self.pOut_values = pOut.calculate_pOut(self.x_values, self.pEngine_values, self.powerAvionics, self.powerPayload)
self.I_loctime = I_loctime.calculate_I_loctime(self.day_of_year, self.latitude, self.sunset_hour_angle, self.declination)
self.asm_values = area_Solar_Module.calculate_asm(self.x_values, self.pOut_values, self.I_loctime)
'''
The pLevel.py file has the following code in it and should return the array of values to pass to the second function in the entry Calculation class file.
import math
import numpy as np
import plotly as py
import plotly.graph_objs as go
import ipywidgets as widgets
import plotly.io as pio
import sys
sys.dont_write_bytecode = True
py.offline.init_notebook_mode(connected=True)
pio.renderers.default = "browser"
# calculating pLevel
x_values = []
y_values = []
layoutPLevel = go.Layout(
title="pLevel",
yaxis=dict(
title='pLevel'
),
xaxis=dict(
title='Surface Area Wing'
)
)
def calculate_pLevel(valoreUnico, cd, cl, totM):
x_values = []
count = 0
while (count < 5):
x_values.append(count)
count = count + 0.01
y_values = []
iteration = 0
while (iteration < len(x_values)):
x_value = x_values[iteration]
if (x_value == 0):
y_value = 0
y_values.append(y_value)
else:
if (valoreUnico == 0.0):
# nessun dato per valoreUnico dato, utilizza i due valori separati
y_value = firstPart(cd, cl) * math.sqrt(secondPart(x_value, totM))
y_values.append(y_value)
else:
y_value = valoreUnico * \
math.sqrt(secondPart(x_value, totM))
y_values.append(y_value)
iteration = iteration + 1
else:
yNpArray = np.array(y_values)
xNpArray = np.array(x_values)
tracePLevel = go.Scatter(
x=xNpArray,
y=yNpArray,
mode='lines',
name='pLevel',
line=dict(
shape='spline'
)
)
figPLevel = go.Figure(data=[tracePLevel], layout=layoutPLevel)
figPLevel.show()
return x_values, y_values
def firstPart(cd, cl):
return (cd / cl**(3/2))
def secondPart(x_value, totM):
return (2*(totM * 9.81)**3) / (1.225 * x_value)
The structure of the files is as follows:
-app
-- __main__.py
-- entry.py
-- __init__.py
-- mainFunctions
--- pLevel.py
--- __init__.py
The loop for the x_values in the pLevel function was not adding one to the iteration so the loop went on forever. I just did not notice my error.
Instead of being
while (iteration < len(x_values)):
x_value = x_values[iteration]
if (x_value == 0):
y_value = 0
y_values.append(y_value)
It should be
while (iteration < len(x_values)):
x_value = x_values[iteration]
if (x_value == 0):
y_value = 0
y_values.append(y_value)
iteration = iteration+1

Add UserControl on WinForm pythonnet

I am trying to add UserControl to a WinForm using PythonNet but not having any luck. For testing, I added a button and that shows up but not the UserControl and I am not sure what I a doing wrong.
All the code can be placed into one py file. I broke into a few sections hoping it will be easier to read.
USER CONTROL
class Field(WinForms.UserControl):
def __init__(self):
self.InitializeComponents()
pass
def InitializeComponents(self):
self.components = System.ComponentModel.Container()
self.label = WinForms.Label()
self.textBox = WinForms.Label()
## Label
# self.label.Anchor = ((WinForms.AnchorStyles)(
# ((WinForms.AnchorStyles.Top | WinForms.AnchorStyles.Bottom)
# | WinForms.AnchorStyles.Left)))
self.label.AutoSize = True
self.label.Location = System.Drawing.Point(3, 7)
self.label.Name = "label"
self.label.Size = System.Drawing.Size(29, 13)
self.label.TabIndex = 0
self.label.Text = "label"
## TextBox
# self.textBox.Anchor = ((WinForms.AnchorStyles)(
# (((WinForms.AnchorStyles.Top | WinForms.AnchorStyles.Bottom)
# | WinForms.AnchorStyles.Left)
# | WinForms.AnchorStyles.Right)))
# self.textBox.Location = System.Drawing.Point(115, 3)
self.textBox.Name = "textBox"
self.textBox.Size = System.Drawing.Size(260, 20)
self.textBox.TabIndex = 1
## Control
self.AutoScaleMode = WinForms.AutoScaleMode.Font
self.Controls.Add(self.textBox)
self.Controls.Add(self.label)
self.Name = "Field"
self.Size = System.Drawing.Size(378, 26)
# self.PerformLayout()
PARENT FORM
class ParentForm(WinForms.Form):
def __init__(self):
self.InitializeComponents()
# region Form Design
def InitializeComponents(self):
self.components = System.ComponentModel.Container()
self.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
self.ClientSize = System.Drawing.Size(385, 180)
self.Name = "ParentForm"
self.Text = "Parent Form"
self.field1 = Field()
self.field1.Location = Point(13, 13)
self.field1.Name = "field1"
self.field1.Size = Size(378, 26)
self.field1.TabIndex = 1
self.Controls.Add(self.field1)
self.button1 = WinForms.Button()
self.button1.Location = Point(13, 50)
self.button1.Size = Size(50, 20)
self.button1.Text = "Button1"
self.Controls.Add(self.button1)
pass
def Dispose(self):
self.components.Dispose()
WinForms.Form.Dispose(self)
ENTRY POINT AND IMPORTS
import clr
import System
import System.Windows.Forms as WinForms
from System.IO import File
from System.Text import Encoding
from System.Drawing import Color, Point, Size
from System.Threading import ApartmentState, Thread, ThreadStart
def appThread():
app = ParentForm()
WinForms.Application.Run(app)
app.Dispose()
def appEntry():
thread = Thread(ThreadStart(appThread))
thread.SetApartmentState(ApartmentState.STA)
thread.Start()
thread.Join()
if __name__ == '__main__':
appEntry()

wxPython show image certain amount of time

I am using code in wxPython to show images.
I created a screen with 2 panels, one left and right.
In one of the panels (randomly chosen), I want do display an image for exactly 150ms.
How can I program this? I am relatively new to Python, and I don't find any clear way on the internet.
My code for now (without the 150ms):
import wxversion
wxversion.select("3.0")
import wx
import random
import timeclass Screen_1(wx.Dialog):
ri = 0
def __init__(self,parent,id,title):
wx.Dialog.__init__(self,parent,id,title,size=(400,300))
self.randomImage = random.randrange(1,3)
self.randomSlot = random.randrange(1,3)
Screen_1.ri = self.randomImage
if(self.randomSlot == 1):
self.side = 'Left'
else:
self.side = 'Right'
file = open('User.txt','a')
panel_left = wx.Panel(self,11,(-1,-1),(200,200))
self.picture_left = wx.StaticBitmap(panel_left)
font = wx.Font(13,wx.DEFAULT,wx.NORMAL,wx.BOLD)
panel_centre = wx.Panel(self,12,(200,70),(10,100))
msg = wx.StaticText(panel_centre,-1,'+',size=(10,100))
msg.SetFont(font)
panel_right = wx.Panel(self,13,(210,0),(200,200))
self.picture_right = wx.StaticBitmap(panel_right)
**self.imageName = 'im_'+str(self.randomImage)+'.png'**
if self.randomSlot == 1:
self.picture_left.SetBitmap(wx.Bitmap(self.imageName))
else:
self.picture_right.SetBitmap(wx.Bitmap(self.imageName))
wx.FutureCall(1000,self.Destroy)
self.Centre()
self.ShowModal()
def OnClick(self,event):
self.Close()
Thanks a lot!
def OnTimeUp(self,e):
#change images
self.timer.Start(15,oneShot=True) # if you want to call it again in 15 ms
def StartTimer(self):
self.timer = wx.Timer()
self.timer.Bind(wx.EVT_TIMER,self.OnTimeUp)
self.timer.Start(15,oneShot=True)
something like that ... although 15ms is very fast ...

Categories

Resources