Why is the dictionary not translated with Flask-Babel - flask

I am writing a website in Flask. I use Flask-Babel for translation into different languages. I use lazy_gettext to translate dictionary values. When changing the language on the site, all phrases and sentences that I wrapped should be translated. Everything is translated besides the words that are wrapped in this mqtt.py file in the MgttTOAA class. Tell me what the problem might be or suggest some other translation option. Thanks
# mqtt.py
from app import socketio, app
from flask import request
from flask_mqtt import Mqtt
from flask_babel import lazy_gettext as _l
from app.tasks import SchedulerTask
import json
import copy
import logging
mqtt = Mqtt(app)
logger = logging.getLogger('flask.flask_mqtt')
logger.disabled = True
class MqttTOAA(object):
# топик контроля воротами забора, топик данных воротами забора, топик контроля гаражными, топик данных гаражными
type_topic = ["/Control", "/Data"]
m_request_state = {"comm": "3"} # запрос на получение статуса ворот
m_start = {"Gate": "Start"} # сообщение для открытия/закрытия ворот
m_stop = {"Gate": "Stop"} # сообщение для остановки ворот
qos_request = 1
qos_sub = 2
struct_state_devices = None # словарь информации о состоянии устройств
# состояние ворот: действие
# действие: статус, отображаемый на странице
# поля: текст кнопки, отображаемый статус, код устройства
# статус ворот # предыдущая позиция ворот и отметка о том, были ли отсановленны
dict_gate = {"dict_state_button": {'con_Clos': _l(u'Открыть'),
'con_Open': _l(u'Закрыть'),
"fl_OpenClos": (_l(u'Продолжить'),
_l(u'Остановить'),
_l(u'Прервать'))},
"dict_state_text": {_l(u'Открыть'): _l(u'закрыты'),
_l(u'Закрыть'): _l(u'открыты'),
_l(u'Продолжить'): _l(u'остановлены'),
_l(u'Прервать'): _l(u'закрываются'),
_l(u'Остановить'): (_l(u'открываются'),
_l(u'закрываются'),
_l(u'в движении'))},
"dict_type_element": {"button": u'', "text": u'', "device_code": u'', },
"state_gate": {},
"position": {"state": u'', "stop": False},
"reverse": False,
}
close_msg = _l(u'закрываются')
open_msg = _l(u'открываются')
POOL_TIME = 2 # Интервал отправки запроса брокеру
end_publish = None
devices = None
app_now = None
schedulers_list = list()
sch_task = None
code_list = list()
def __init__(self, devices, app):
mqtt._connect()
self.devices = devices
self.app_now = app
self.sch_task = SchedulerTask()
self.create_devices_dict()
self.handle_mqtt_connect()
self.mqtt_onmessage = mqtt.on_message()(self._handle_mqtt_message)
self.mqtt_onlog = mqtt.on_log()(self._handle_logging)
self.socketio_error = socketio.on_error()(self._handle_error)
self.handle_change_state = socketio.on('change_state')(self._handle_change_state)
self.handle_unsubscribe_all = socketio.on('unsubscribe_all')(self._handle_unsubscribe_all)
# ожидание подключения к брокеру,
# затем подписка на топик и запуск потока для постоянной отсылки сообщений в топик Control
def handle_mqtt_connect(self):
task = None
for dev in self.devices:
if dev.device_code not in self.code_list: # запущен ли уже поток с таким кодом
mqtt.subscribe("BK" + dev.device_code + self.type_topic[1], self.qos_sub)
self.code_list.append(dev.device_code)
task = self.sch_task.add_scheduler_publish(dev.device_code,
mqtt,
"BK" + dev.device_code +
self.type_topic[0],
self.m_request_state,
self.qos_request,
self.POOL_TIME)
if task is not None:
self.schedulers_list.append(task)
if len(self.schedulers_list) > 0:
self.sch_task.start_schedulers()
self.code_list.clear()
# обработчик ошибок
#staticmethod
def _handle_error():
print(request.event["message"]) # "my error event"
print(request.event["args"]) # (data,)
# отмена подписки на топик
#staticmethod
def _handle_unsubscribe_all():
mqtt.unsubscribe_all()
# функция изменения состояния ворот по нажатию
def _handle_change_state(self, code):
print(code)
# print(self.struct_state_devices[code])
message = None
if code is not None:
try:
type_g = self.struct_state_devices[code]["state_gate"]
if type_g["fl_OpenClos"] == 1: # ворота в движении -> остановка
message = self.m_stop
else:
if self.struct_state_devices[code]["reverse"] is True:
# остановились и двигаются в обратном направлении -> остановка
if self.struct_state_devices[code]["position"]["state"] == self.close_msg:
message = self.m_stop
self.struct_state_devices[code]["position"]["state"] = self.open_msg
else:
message = self.m_start
else: # ворота остановленны -> продолжение движения
message = self.m_start
print("Msg:" + str(message))
except Exception as ex:
print(ex)
if message is not None:
mqtt.publish("BK" + code + self.type_topic[0], json.dumps(message), self.qos_request)
else:
print("Error change state " + code)
# обработка принятых сообщений от топика, на который подписан
def _handle_mqtt_message(self, client, userdata, message):
# print("Get message")
data = dict(
topic=message.topic,
payload=message.payload.decode(),
qos=message.qos,
)
try:
data = json.loads(data['payload'])
self.gate_msg(data)
except Exception as ex:
print("Exception: " + str(ex))
# логирование
#staticmethod
def _handle_logging(self, client, userdata, level, buf):
print(level, buf)
pass
# создание словаря устройств
def create_devices_dict(self):
if self.struct_state_devices is None:
self.struct_state_devices = dict()
for dev in self.devices:
self.struct_state_devices[dev.device_code] = self.dict_gate.copy() # добавление словаря устройства
if dev.typedev.reverse:
self.struct_state_devices[dev.device_code]['reverse'] = True
# функция измения состояния гаражных ворот (с реверсом)
def gate_msg(self, data):
k = ""
code = data["esp_id"][2:]
dict_dev = copy.deepcopy(self.struct_state_devices[code])
dict_dev["state_gate"] = data.copy()
try:
if dict_dev["state_gate"]["con_Clos"] == 0: # ворота закрыты
# print("1")
k = "con_Clos"
dict_dev["position"]["state"] = k
dict_dev["position"]["stop"] = False
elif dict_dev["state_gate"]["con_Open"] == 0: # ворота открыты
# print("2")
k = "con_Open"
dict_dev["position"]["state"] = k
dict_dev["position"]["stop"] = False
elif dict_dev["state_gate"]["fl_OpenClos"] == 0: # ворота остановленны/движение прервано
# print("3")
k = "fl_OpenClos"
# обратный ход ворот при закрытии
if dict_dev["position"]["state"] == self.close_msg and dict_dev["reverse"] is True:
# print("4")
k1 = 1
k2 = 0
dict_dev["dict_type_element"]["text"] = \
dict_dev["dict_state_text"][dict_dev["dict_state_button"][k][k1]][k2]
dict_dev["position"]["stop"] = False
else:
# print("5")
k1 = 0
dict_dev["dict_type_element"]["text"] = \
dict_dev["dict_state_text"][dict_dev["dict_state_button"][k][k1]]
dict_dev["position"]["stop"] = True
elif dict_dev["state_gate"]["fl_OpenClos"] == 1: # ворота в движении
# print("6")
k = "fl_OpenClos"
# Если невозможно определить открываются или закрываются ворота
if len(dict_dev["position"]["state"]) == 0:
# print("7")
k1 = 1
k2 = 2
dict_dev["dict_type_element"]["text"] = \
dict_dev["dict_state_text"][dict_dev["dict_state_button"][k][k1]][k2]
# определение - закрываются или открываются ворота
elif dict_dev["position"]["state"] == "con_Clos" or \
dict_dev["position"]["state"] == self.open_msg:
if dict_dev["position"]["stop"]:
# print("8")
k1 = 1
k2 = 1
dict_dev["position"]["stop"] = False
dict_dev["dict_type_element"]["text"] = \
dict_dev["dict_state_text"][dict_dev["dict_state_button"][k][k1]][k2]
else:
# print("9")
k1 = 1
k2 = 0
dict_dev["dict_type_element"]["text"] = \
dict_dev["dict_state_text"][dict_dev["dict_state_button"][k][k1]][k2]
elif dict_dev["position"]["state"] == "con_Open" or \
dict_dev["position"]["state"] == self.close_msg:
if dict_dev["reverse"]:
# print("10")
k1 = 2
dict_dev["dict_type_element"]["text"] = \
dict_dev["dict_state_text"][dict_dev["dict_state_button"][k][k1]]
else:
if dict_dev["position"]["stop"]:
# print("11")
k1 = 1
k2 = 0
dict_dev["position"]["stop"] = False
dict_dev["dict_type_element"]["text"] = \
dict_dev["dict_state_text"][dict_dev["dict_state_button"][k][k1]][k2]
else:
# print("12")
k1 = 1
k2 = 1
dict_dev["dict_type_element"]["text"] = \
dict_dev["dict_state_text"][dict_dev["dict_state_button"][k][k1]][k2]
if dict_dev["position"]["state"] != dict_dev["dict_type_element"]["text"]:
# print("13")
dict_dev["position"]["state"] = dict_dev["dict_type_element"]["text"]
if k == "fl_OpenClos":
dict_dev["dict_type_element"]["button"] = dict_dev["dict_state_button"][k][k1]
else:
dict_dev["dict_type_element"]["button"] = dict_dev["dict_state_button"][k]
dict_dev["dict_type_element"]["text"] = \
dict_dev["dict_state_text"][dict_dev["dict_state_button"][k]]
except Exception as ex:
print("Exception (gate_msg): " + str(ex))
dict_dev["dict_type_element"]["device_code"] = data["esp_id"][2:]
dict_dev["dict_type_element"]["temp"] = data["temp_1"]
dict_dev["dict_type_element"]["button"] = copy.deepcopy(str(dict_dev["dict_type_element"]["button"]))
dict_dev["dict_type_element"]["text"] = copy.deepcopy(str(dict_dev["dict_type_element"]["text"]))
self.struct_state_devices[code] = copy.deepcopy(dict_dev)
socketio.emit('mqtt_message', data=dict_dev["dict_type_element"])

Related

Optmizing 2 loops in sequence

I'm trying to collect data of Investment Funds in a API, there's a list of Fund Codes and a List of days in format that I want.
I create a routine in a For by day, and after a For by fund. But to complete all data frame, this take me 30 minutes.
I would like to know how to optmize it
Here's the part of code:
dataPosicao_list is a list of days, and fundo_id_list is a list o funds by ID that API recognize
df_geral = pd.DataFrame()
df_day = pd.DataFrame()
for day in dataPosicao_list:
#df_day = pd.DataFrame()
for fundo_id in fundo_id_list:
try:
url_api = f'https://modal-pp.totvs.amplis.com.br/amplisapi/ws/v2/rendavariavel/avista/movimentos/carteira/{fundo_id}/data/{day}?pagina=0&tamanhoPagina=100'
session_api = requests.Session()
response = session_api.get(url_api, verify=False)
payload_api = ''
headers_api = {'Content-Type': 'application/json',
'charset': 'UTF-8',
'Authorization': token }
posicoes_api = session_api.request('GET', url_api, headers = headers_api, data = payload_api)
posicoes = json.loads(posicoes_api.text)
df_total = pd.DataFrame()
for linha in posicoes['conteudo']:
try:
bolsa = linha['bolsa']['codigo']
except:
bolsa = "None"
try:
ativo = linha['ativo']['codigo']
except:
ativo = "None"
try:
bolsa_internacional = linha['bolsa']['bolsaInternacional']
except:
bolsa_internacional = "None"
try:
localidade = linha['bolsa']['localidade']['codigo']
except:
localidade = "None"
try:
moeda = linha['bolsa']['moeda']['internationalCode']
except:
moeda = "None"
try:
fundo = linha['carteira']['administrador']['codigoB3']
except:
fundo = "None"
try:
Fundo_ou_Clube = linha['carteira']['administrador']['administradorClubeInvestimento']
except:
Fundo_ou_Clube = "None"
try:
carteira = linha['carteira']['administrador']['codigo']
except:
carteira = "None"
try:
class_fundo = linha['carteira']['classificacaoFundo']['classificacao']
except:
class_fundo = "None"
try:
cota_fidic = linha['carteira']['classificacaoFundo']['tipoCotaFIDC']
except:
cota_fidic = "None"
try:
mov_cetip = linha['carteira']['codAtivoMnemonicoCetip']
except:
mov_cetip = "None"
try:
controlador = linha['carteira']['controlador']['codigo']
except:
controlador = linha['carteira']['controlador']
try:
custodiante = linha['carteira']['custodiante']['nome']
except:
custodiante = "None"
try:
data = linha['data']
except:
data = "None"
try:
nome_fundo = fundo_id
except:
nome_fundo = "None"
try:
taxa_performance = linha['carteira']['taxaPerformance']
except:
taxa_performance = "None"
try:
mercado = linha['mercado']['descricao']
except:
mercado = "None"
try:
calculo_corretagem_emulamentos = linha['corretagem']['calculaCorretagemEmolumentos']
except:
calculo_corretagem_emulamento = "None"
try:
porcentagemDevolucaoCorretagemCorretora = linha['corretagem']['porcentagemDevolucaoCorretagemCorretora']
except:
porcentagemDevolucaoCorretagemCorretora = "None"
try:
modalidade = linha['modalidadeMovimento']['descricao']
except:
modalidade = "None"
try:
preco = linha['preco']
except:
preco = "None"
try:
quantidade = linha['quantidade']
except:
quantidade = "None"
try:
valor_bruto = linha['valorBruto']
except:
valor_bruto = "None"
try:
id = linha['id']
except:
id = 'None'
serie = {'id' : id, 'controlador': controlador,'taxa_performance': taxa_performance, 'nome_fundo': nome_fundo, 'modalidade':modalidade, 'mercado': mercado, 'preco': preco, 'quantidade':quantidade, 'valor_bruto': valor_bruto, 'cota_fidic': cota_fidic,'porcentagemDevolucaoCorretagemCorretora': porcentagemDevolucaoCorretagemCorretora, 'calculo_corretagem_emulamentos': calculo_corretagem_emulamentos, 'data': data, 'custodiante':custodiante, 'controlador': controlador, 'mov_cetip': mov_cetip, 'bolsa': bolsa, 'ativo' : ativo, 'bolsa_internacional': bolsa_internacional, 'localidade': localidade , 'moeda': moeda, 'fundo': fundo, 'Fundo_ou_Clube': Fundo_ou_Clube, 'carteira': carteira, ' class_fundo': class_fundo }
serie = pd.Series(serie)
df_total = df_total.append(serie, ignore_index=True)
#df_geral = df_geral.append(df_total, ignore_index=True)
df_day = df_day.append(df_total, ignore_index=True)
except:
continue
df_geral = df_geral.append(df_day, ignore_index=True)
df_geral = df_geral.drop_duplicates(subset=['id'])
df_geral.head()
print(df_geral)

Cart Item Update(add or Remove) throwing Type Error

TypeError("'%s' instance expected, got %r" % (
TypeError: 'CartItem' instance expected, got
I am getting this error when I tried to add or remove the product obj from cartItem. Help me to overcome this error.
CartUpdate view
def cart_update(request):
product_id = request.POST.get('product_id')
print(product_id)
try:
qty = request.POST.get('qty')
update_qty = True
except:
qty = None
update_qty = False
if product_id is not None:
try:
product_obj = Product.objects.get(id=product_id)
except Product.DoesNotExist:
print("Show message to user, product is gone?")
return redirect("cart:cart")
cart_obj, new_obj = Cart.objects.new_or_get(request)
cart_item, created = CartItem.objects.get_or_create(cart=cart_obj, product=product_obj)
if created:
print("created")
if update_qty and qty:
if int(qty) == 0:
cart_item.delete()
else:
cart_item.quantity = qty
cart_item.save()
else:
pass
if product_obj in cart_obj.cartitem_set.all():
cart_obj.cartitem_set.remove(product_obj)
added = False
else:
cart_obj.cartitem_set.add(product_obj)
added = True
new_total = 0.0
for x in cart_obj.cartitem_set.all():
line_item = float(x.product.price) * x.quantity
new_total += line_item
request.session['cart_items'] = cart_obj.cartitem_set.count()
cart_obj.subtotal = new_total
if cart_obj.subtotal > 0:
cart_obj.total = Decimal(cart_obj.subtotal) * Decimal(1.08)
else :
cart_obj.total = 0.00
cart_obj.save()

Facing the StaleElementReferenceException: Message: Element is no longer valid issue. please check if there is wayout

def ServerTimeWait(self):
driver = GenericFunctionLibrary.get_webdriver_instance()
try:
ElemStatus = WebDriverWait(driver, 60).until(ec.presence_of_element_located(
(By.XPATH, "//td/span[contains(text(),'server time:')]/following::span[2]")
))
AppServerTime = driver.find_element_by_xpath("//td/span[contains(text(),'server time:')]/following::span[2]").text
if AppServerTime.endswith(' (UTC+2)'):
UAppServerTime = AppServerTime[:-8]
#print("AppServerTime :",AppServerTime)
formatAppServerTime = datetime.strptime(UAppServerTime, '%m/%d/%Y %H:%M')
print ("formatAppServerTime:",formatAppServerTime)
fmt = "%m/%d/%Y %H:%M"
now_utc = datetime.now(timezone('UTC'))
#print ("now_utc.strftime(fmt):",now_utc.strftime(fmt))
now_paris = now_utc.astimezone(timezone('Europe/Paris'))
# #print "now_paris.strftime(fmt):",now_paris.strftime(fmt)
# now_kolkata = now_paris.astimezone(timezone('Asia/Kolkata'))
# #print ("now_kolkata.strftime(fmt)",now_kolkata.strftime(fmt))
finalSysDate = now_paris.strftime(fmt)
print ("finalSysDate",finalSysDate)
if formatAppServerTime == finalSysDate:
print("Application server time is matched to current date")
else:
print("Application server time is not matched to current date")
except Exception as e:
raise e

How to add a widget in QmdiArea in pyqt?

I'm trying to add a window to Qmdi area when user clicks a button inside another widget in Qmdi area.
Codes i have written so far is:
from __future__ import print_function
from PyQt4.QtGui import *
import csv
import subprocess
import sys
from PyQt4 import QtGui
from PyQt4.QtCore import *
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.le = QLineEdit()
self.le.setObjectName("host")
self.lee = QLineEdit()
self.lee.setObjectName("hosta")
self.pb = QPushButton()
self.pb.setObjectName("connect")
self.pb.setText("inject")
layout = QFormLayout()
layout.addWidget(self.le)
layout.addWidget(self.lee)
layout.addWidget(self.pb)
self.setLayout(layout)
self.connect(self.pb, SIGNAL("clicked()"), self.button_click)
self.setWindowTitle("Stuck-at-0")
def button_click(self):
# shost is a QString object
n = int(self.le.text())
line = str(self.lee.text())
print(n, line)
with open('main.txt', 'r') as files:
# read a list of lines into data
data = files.readlines()
# now inject fault in nth level, note that you have to add a newline
print
data[1]
if line in data[0]:
data.insert(n + 1, '0' + ',' + line + '\n')
# and write everything back
with open('main.txt', 'w') as files:
files.writelines(data)
res = subprocess.call(['python stuck.py'], shell=True)
res = subprocess.call(['python comp.py'], shell=True)
class UserWindow(QtGui.QMainWindow):
def __init__(self):
super(UserWindow, self).__init__()
self.ctr_frame = QtGui.QWidget()
self.specTable = QtGui.QTableView()
self.specModel = QtGui.QStandardItemModel(self)
self.specList = self.createSpecTable()
self.initUI()
def specData(self):
with open('tests.csv', 'rb') as csvInput:
for row in csv.reader(csvInput):
if row > 0:
items = [QtGui.QStandardItem(field) for field in row]
self.specModel.appendRow(items)
def createSpecTable(self):
# This is a test header - different from what is needed
specHdr = ['Test', 'Date', 'Time', 'Type']
self.specData()
specM = specTableModel(self.specModel, specHdr, self)
self.specTable.setModel(specM)
self.specTable.setShowGrid(False)
v_head = self.specTable.verticalHeader()
v_head.setVisible(False)
h_head = self.specTable.horizontalHeader()
h_head.setStretchLastSection(True)
self.specTable.sortByColumn(3, Qt.DescendingOrder)
return self.specTable
def initUI(self):
self.specList.setModel(self.specModel)
p_grid = QtGui.QGridLayout()
p_grid.setSpacing(5)
p_grid.addWidget(self.specList, 2, 5, 13, 50)
self.ctr_frame.setLayout(p_grid)
self.setCentralWidget(self.ctr_frame)
self.statusBar()
bar = self.menuBar()
menu_item1 = bar.addMenu("Circuit Details")
fault_inject = bar.addMenu("Fault Injection")
fault_inject_sa = fault_inject.addMenu("Stuck-at Fault")
fault_inject_sa.addAction("Stuck-at-0")
fault_inject_sa.addAction("Stuck-at-1")
fault_inject_bridge = fault_inject.addMenu("Bridging Fault")
fault_inject_bridge.addAction("Bridging-OR")
fault_inject_bridge.addAction("Bridging-AND")
fault_inject_cross = fault_inject.addMenu("Crosspoint Fault")
fault_inject_cross.addAction("Crosspoint-Appearance")
fault_inject_cross.addAction("Crosspoint-Dissappearence")
fault_inject_mgf = fault_inject.addMenu("Missing Gate Fault")
fault_inject_mgf.addAction("Single-MGF")
fault_inject_mgf.addAction("Multiple-MGF")
fault_inject_mgf.addAction("Repeated-MGF")
fault_inject_mgf.addAction("Partial-MGF")
self.setWindowTitle('Truth Table')
fault_inject.triggered[QAction].connect(self.fault_injection)
def fault_injection(self, q):
print("triggered")
if q.text() == "Stuck-at-0":
print(q.text())
exx = Form()
self.mdi.addSubWindow(exx)
exx.show()
if q.text() == "Stuck-at-1":
print(q.text())
if q.text() == "Bridging-OR":
print(q.text())
if q.text() == "Bridging-AND":
print(q.text())
if q.text() == "Crosspoint-Appearance":
print(q.text())
if q.text() == "Crosspoint-Dissappearence":
print(q.text())
if q.text() == "Single-MGF":
print(q.text())
if q.text() == "Multiple-MGF":
print(q.text())
if q.text() == "Repeated-MGF":
print(q.text())
if q.text() == "Partial-MGF":
print(q.text())
class specTableModel(QAbstractTableModel):
def __init__(self, datain, headerData, parent=None, *args):
QAbstractTableModel.__init__(self, parent, *args)
self.arrayData = datain
self.headerData = headerData
def rowCount(self, parent):
return 0
def columnCount(self, parent):
return 0
def data(self, index, role):
if not index.isValid():
return QVariant()
elif role != Qt.DisplayRole:
return QVariant()
return QVariant(self.arraydata[index.row()][index.column()])
def headerData(self, col, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self.headerdata[col]
return None
class MainWindow(QMainWindow):
count = 0
filename = 0
def test_display(self,q):
self.mdi.tileSubWindows()
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.mdi = QMdiArea()
self.setCentralWidget(self.mdi)
bar = self.menuBar()
menu_item1 = bar.addMenu("About Tool")
menu_item_tool = menu_item1.addMenu("User Manual")
menu_item_example = menu_item1.addMenu("Example and Demos")
menu_item2 = bar.addMenu("Reversible Computing")
menu_item_rc = menu_item2.addMenu("RC vs Conventional")
menu_item_rcg = menu_item2.addMenu("RC Gates")
menu_item_rcp = menu_item2.addMenu("Properties of RC")
menu_item_rcl = menu_item2.addMenu("RC Gate Libraries")
menu_item = bar.addMenu("Benchmark Circuits")
menu_item_gate = menu_item.addMenu("Functions")
menu_item_realize = menu_item.addMenu("Realization Library")
menu_item_nct = menu_item_realize.addMenu("NCT")
menu_item_gt = menu_item_realize.addMenu("GT")
menu_item_nctf = menu_item_realize.addMenu("NCTF")
menu_item_gf = menu_item_realize.addMenu("GF")
menu_item_4b1_5g = menu_item_gate.addMenu("4b1_5g")
menu_item_4b1_5g.addAction("4b1_5g_1")
menu_item_4b1_5g.addAction("4b1_5g_2")
menu_item_4b1_5g.addAction("4b1_5g_3")
menu_item_4b1_5g.addAction("4b1_5g_4")
menu_item_4b1_5g.addAction("4b1_5g_5")
menu_item_adder = menu_item_gate.addMenu("Adders")
menu_item_adder.addAction("1bitadder(rd32)")
menu_item_adder.addAction("5bitadder")
menu_item_adder.addAction("8bitadder")
menu_item_div_checker = menu_item_gate.addMenu("Divisiblity Checkers")
menu_item_div_checker.addAction("4mod5")
menu_item_div_checker.addAction("5mod5")
menu_item_cyclic = menu_item_gate.addMenu("Cycle Functions")
menu_item_cyclic.addAction("cycle10_2")
menu_item_cyclic.addAction("cycle17_3")
menu_item_galois = menu_item_gate.addMenu("Galois Field Multipliers")
menu_item_galois.addAction("gf2^3mult")
menu_item_galois.addAction("gf2^4mult")
menu_item_galois.addAction("gf2^5mult")
menu_item_galois.addAction("gf2^6mult")
menu_item_galois.addAction("gf2^7mult")
menu_item_galois.addAction("gf2^8mult")
menu_item_galois.addAction("gf2^9mult")
menu_item_galois.addAction("gf2^10mult")
menu_item_galois.addAction("gf2^11mult")
menu_item_galois.addAction("gf2^12mult")
menu_item_galois.addAction("gf2^13mult")
menu_item_galois.addAction("gf2^14mult")
menu_item_galois.addAction("gf2^15mult")
menu_item_galois.addAction("gf2^16mult")
menu_item_galois.addAction("gf2^17mult")
menu_item_galois.addAction("gf2^18mult")
menu_item_galois.addAction("gf2^19mult")
menu_item_galois.addAction("gf2^20mult")
menu_item_galois.addAction("gf2^32mult")
menu_item_galois.addAction("gf2^50mult")
menu_item_galois.addAction("gf2^64mult")
menu_item_galois.addAction("gf2^100mult")
menu_item_galois.addAction("gf2^127mult")
menu_item_galois.addAction("gf2^128mult")
menu_item_galois.addAction("gf2^256mult")
menu_item_galois.addAction("gf2^512mult")
menu_item_hamming = menu_item_gate.addMenu("Hamming Code Functions")
menu_item_hamming.addAction("ham3")
menu_item_hamming.addAction("ham7")
menu_item_hamming.addAction("ham15")
menu_item_hbw = menu_item_gate.addMenu("Hidden Weight Coding Functions")
menu_item_hbw.addAction("hbw4")
menu_item_hbw.addAction("hbw5")
menu_item_hbw.addAction("hbw6")
menu_item_hbw.addAction("hbw7")
menu_item_hbw.addAction("hbw8")
menu_item_hbw.addAction("hbw9")
menu_item_hbw.addAction("hbw10")
menu_item_hbw.addAction("hbw11")
menu_item_hbw.addAction("hbw12")
menu_item_hbw.addAction("hbw13")
menu_item_hbw.addAction("hbw14")
menu_item_hbw.addAction("hbw15")
menu_item_hbw.addAction("hbw16")
menu_item_hbw.addAction("hbw20")
menu_item_hbw.addAction("hbw50")
menu_item_hbw.addAction("hbw100")
menu_item_hbw.addAction("hbw200")
menu_item_hbw.addAction("hbw500")
menu_item_hbw.addAction("hbw1000")
menu_item_mdd = menu_item_gate.addMenu("MDD Worst Case")
menu_item_mdd.addAction("3_17.tfc")
menu_item_mdd.addAction("4_49")
menu_item_modular = menu_item_gate.addMenu("Modula Adders")
menu_item_modular.addAction("mod5adder")
menu_item_modular.addAction("mod1024adder")
menu_item_modular.addAction("mod1048576adder")
menu_item_prime = menu_item_gate.addMenu("N-th Prime")
menu_item_prime.addAction("nth_prime3_inc")
menu_item_prime.addAction("nth_prim4_inc")
menu_item_prime.addAction("nth_prime5_inc")
menu_item_prime.addAction("nth_prime6_inc")
menu_item_prime.addAction("nth_prime7_inc")
menu_item_prime.addAction("nth_prime8_inc")
menu_item_prime.addAction("nth_prime9_inc")
menu_item_prime.addAction("nth_prime10_inc")
menu_item_prime.addAction("nth_prime11_inc")
menu_item_prime.addAction("nth_prime12_inc")
menu_item_prime.addAction("nth_prime13_inc")
menu_item_prime.addAction("nth_prime14_inc")
menu_item_prime.addAction("nth_prime15_inc")
menu_item_prime.addAction("nth_prime16-inc")
menu_item_permanent = menu_item_gate.addMenu("Permanent")
menu_item_permanent.addAction("permanent1x1")
menu_item_permanent.addAction("permanent2x2")
menu_item_permanent.addAction("permanent3x3")
menu_item_permanent.addAction("permanent4x4")
menu_item_rd = menu_item_gate.addMenu("RD-Input Weight functions")
menu_item_rd.addAction("rd53")
menu_item_rd.addAction("rd73")
menu_item_rd.addAction("rd84")
menu_item_sym = menu_item_gate.addMenu("Symmetric Functions")
menu_item_sym.addAction("6sym")
menu_item_sym.addAction("9sym")
menu_item_oth = menu_item_gate.addMenu("Others")
menu_item_oth.addAction("2_4dec")
menu_item_oth.addAction("2of5")
menu_item_oth.addAction("xor5")
self.setWindowTitle("Reversible Fault Testing")
menu_item.triggered[QAction].connect(self.truth_table_gen)
def windowaction(self, q):
print("triggered")
print(q.text())
if "New" == "New":
MainWindow.count += 1
sub = QMdiSubWindow()
sub.setWidget(QTextEdit())
sub.setWindowTitle("tst")
self.mdi.addSubWindow(sub)
sub.show()
# truth table display widget
def truth_table_gen(self, q):
MainWindow.count += 1
MainWindow.filename = q.text()
to_readfile = open(q.text(), 'r')
try:
reading_file = to_readfile.read()
writefile = open('a.tfc', 'w')
try:
writefile.write(reading_file)
finally:
writefile.close()
finally:
to_readfile.close()
subprocess.call(['python truth_gen.py'], shell=True)
exx = UserWindow()
self.mdi.addSubWindow(exx)
exx.show()
self.mdi.tileSubWindows()
def main():
app = QApplication(sys.argv)
ex = MainWindow()
ex.show()
#ex.resize(1366, 750)
sys.exit(app.exec_())
if __name__ == '__main__':
main()
when i click on button inside the Qmdi area widget, the code crashes.

Tkinter returning a variable to main

Hi I have a program that runs the following way. When a user enters a number between 1-10 and hits the GO button 3 checboxes appear Left, Middle and Right. Upon the selection of only 1 checkbox a button Next appears. I disable the other ones after 1 is selected. I would like to return to the main program which checkbox was selected. How do I do this. I can do it through the Next button or through the checkbox selection. My code is below
import Tkinter as Tk
import ctypes
def setup_fc_error_message():
lines = ['fc is out of range: Please Enter a value from 1-10:']
MessageBox = ctypes.windll.user32.MessageBoxA
MessageBox(None, "\n".join(lines), 'Setup Info', 0)
def check_fc_range(fc_user):
# fc_float = si_units(fc_string_input)
# fc_float = float(fc_string_input)
fc_string_user = str(fc_user)
if (fc_user)>=1 and (fc_user<=10):
return (float(fc_user),fc_string_user)
else:
setup_fc_error_message()
return check_fc_range()
class MainWindow(Tk.Frame):
def __init__(self, parent):
Tk.Frame.__init__(self,parent)
self.parent = parent
self.parent.title('Test')
self.initialize()
def var_states_d(self):
return self.dvar
def var_states_r(self):
return self.rvar
def var_states_l(self):
return self.lvar
def cdb(self):
# print "variable is", self.dvar.get()
self.dvar_state = self.dvar.get()
# self.band_type = StringVar()
# self.band_type.set('D')
if self.dvar_state:
self.cr = Tk.Checkbutton(self.parent, text='Middle', state='disable', variable=self.rvar,command = self.crb)
self.cr.grid(row = 2, column = 1)
self.cl = Tk.Checkbutton(self.parent, text='Right', state='disable', variable=self.lvar,command = self.clb)
self.cl.grid(row = 2, column = 2)
self.nextbutton = Tk.Button(self.parent, text='NEXT', command= self.var_states_d)
self.nextbutton.grid(row=2,column=3)
else:
self.cr = Tk.Checkbutton(self.parent, text='Middle', variable=self.rvar,command = self.crb)
self.cr.grid(row = 2, column = 1)
self.cl = Tk.Checkbutton(self.parent, text='Right', variable=self.lvar,command = self.clb)
self.cl.grid(row = 2, column = 2)
self.nextbutton = Tk.Button(self.parent, text='NEXT', state='disable')
self.nextbutton.grid(row=2,column=3)
def crb(self):
# print "variable is", self.rvar.get()
self.rvar_state = self.rvar.get()
# self.band_type = StringVar()
# self.band_type.set('R')
if self.rvar_state:
self.cd = Tk.Checkbutton(self.parent, text='Left', state='disable', variable=self.dvar,command = self.cdb)
self.cd.grid(row = 2, column = 0)
self.cl = Tk.Checkbutton(self.parent, text='Right', state='disable', variable=self.lvar,command = self.clb)
self.cl.grid(row = 2, column = 2)
self.nextbutton = Tk.Button(self.parent, text='NEXT', command= self.var_states_r)
self.nextbutton.grid(row=2,column=3)
else:
self.cd = Tk.Checkbutton(self.parent, text='Left', variable=self.dvar,command = self.cdb)
self.cd.grid(row = 2, column = 0)
self.cl = Tk.Checkbutton(self.parent, text='Right', variable=self.lvar,command = self.clb)
self.cl.grid(row = 2, column = 2)
self.nextbutton = Tk.Button(self.parent, text='NEXT', state='disable')
self.nextbutton.grid(row=2,column=3)
def clb(self):
# print "variable is", self.lvar.get()
self.lvar_state = self.lvar.get()
# self.band_type = StringVar()
# self.band_type.set('L')
if self.lvar_state:
self.cd = Tk.Checkbutton(self.parent, text='Left', state='disable', variable=self.dvar,command = self.cdb)
self.cd.grid(row = 2, column = 0)
self.cr = Tk.Checkbutton(self.parent, text='Middle', state='disable', variable=self.rvar,command = self.crb)
self.cr.grid(row = 2, column = 1)
self.nextbutton = Tk.Button(self.parent, text='NEXT', command= self.var_states_l)
self.nextbutton.grid(row=2,column=3)
else:
self.cd = Tk.Checkbutton(self.parent, text='Left', variable=self.dvar,command = self.cdb)
self.cd.grid(row = 2, column = 0)
self.cr = Tk.Checkbutton(self.parent, text='Middle', variable=self.rvar,command = self.crb)
self.cr.grid(row = 2, column = 1)
self.nextbutton = Tk.Button(self.parent, text='NEXT', state='disable')
self.nextbutton.grid(row=2,column=3)
def initialize(self):
# self.frame = Tk.Frame(parent)
# self.frame.pack()
self.fc_gui = Tk.DoubleVar(self.parent)
self.fclabel1 = Tk.Label(self.parent, text = 'Please Enter a value between 1 and 10', fg = 'black', bg = 'yellow')
self.fclabel1.grid(row = 0, column = 0)
self.fcedit1 = Tk.Entry(self.parent, textvariable = self.fc_gui, bd = 5 )
self.fcedit1.grid(row = 1, column = 0)
self.fcbutton1 = Tk.Button(self.parent, text='GO', command = self.get_fc)
self.fcbutton1.grid(row = 1, column = 1)
def add_checkbox(self):
self.dvar = Tk.IntVar()
self.cd = Tk.Checkbutton(self.parent, text='Left', variable=self.dvar,command = self.cdb)
self.cd.grid(row = 2, column = 0)
self.rvar = Tk.IntVar()
self.cr = Tk.Checkbutton(self.parent, text='Middle', variable=self.rvar,command = self.crb)
self.cr.grid(row = 2, column = 1)
self.lvar = Tk.IntVar()
self.cl = Tk.Checkbutton(self.parent, text='Right', variable=self.lvar,command = self.clb)
self.cl.grid(row = 2, column = 2)
def get_fc(self):
self.fc_user = self.fc_gui.get()
if self.fc_user:
if check_fc_range(self.fc_user):
self.add_checkbox()
return self.fc_user
######################################################GUI portion ##############################################
def main():
root = Tk.Tk()
app = MainWindow(root)
fc_gui_user = app.get_fc()
app.mainloop()
if __name__ == "__main__":
main()
I cleaned up your MainWindow class removing the cdb, crb, cld functions so you only need one for each called on_toggle to make it more efficient. You'll also notice some slight changes in the add_checkbox function using lambda to pass in the value for that specific checkbutton. And since I combined the functions I did the same for the var_states function.
I left the Tk.IntVar in there as maybe you might have needed them. Although I'm not sure what you're wanting to use them for with a Checkbutton.
As for your question, you already had a method of finding out which checkbox was selected so I'm not entirely sure what you're after, but I've outlined where you can check them.
class MainWindow(Tk.Frame):
def __init__(self, parent):
Tk.Frame.__init__(self,parent)
self.parent = parent
self.parent.title('Test')
self.initialize()
self.chk_buttons = [] # List holding each checkbutton
self.var_states = [] # List holding each Invar for checkbutton
self.clicked = False # Variable to know if a checkbutton is currently selected
def get_var_states(self, i):
# Return IntVar of clicked checkbutton
return self.var_states[i]
def on_toggle(self, pos):
# print "variable is", self.dvar.get()
self.dvar_state = self.dvar.get()
# self.band_type = StringVar()
# self.band_type.set('D')
if not self.clicked:
# Changes all except clicked checkbox to disabled
# Altering state of existing widget
for i, chk_btn in enumerate(self.chk_buttons):
if i != pos:
chk_btn.configure(state='disable')
self.nextbutton = Tk.Button(self.parent, text='NEXT', command=lambda: self.get_var_states(pos))
self.nextbutton.grid(row=2,column=3)
# You can use these if statements to do something if a certain checkbutton is clicked
# Alternately you can call self.get_var_states(pos) here, instead of adding the command
# to the Next button so it runs when a checkbutton is clicked instead of when the Next button is clicked
if pos == 0: # Left
pass
if pos == 1: # Middle
pass
if pos == 2: # Right
pass
else:
# Changes all checkbox to normal
for chk_btn in self.chk_buttons:
chk_btn.configure(state='normal')
self.nextbutton = Tk.Button(self.parent, text='NEXT', state='disable')
self.nextbutton.grid(row=2,column=3)
self.clicked = not self.clicked #Changes between True and False with each click
def initialize(self):
# self.frame = Tk.Frame(parent)
# self.frame.pack()
self.fc_gui = Tk.DoubleVar(self.parent)
self.fclabel1 = Tk.Label(self.parent, text = 'Please Enter a value between 1 and 10', fg = 'black', bg = 'yellow')
self.fclabel1.grid(row = 0, column = 0)
self.fcedit1 = Tk.Entry(self.parent, textvariable = self.fc_gui, bd = 5 )
self.fcedit1.grid(row = 1, column = 0)
self.fcbutton1 = Tk.Button(self.parent, text='GO', command = self.get_fc)
self.fcbutton1.grid(row = 1, column = 1)
def add_checkbox(self):
# Added lambda function passing in a value corresponding to the index position in the list
self.dvar = Tk.IntVar()
self.cd = Tk.Checkbutton(self.parent, text='Left', variable=self.dvar,command = lambda: self.on_toggle(0))
self.cd.grid(row = 2, column = 0)
self.rvar = Tk.IntVar()
self.cr = Tk.Checkbutton(self.parent, text='Middle', variable=self.rvar,command = lambda: self.on_toggle(1))
self.cr.grid(row = 2, column = 1)
self.lvar = Tk.IntVar()
self.cl = Tk.Checkbutton(self.parent, text='Right', variable=self.lvar,command = lambda: self.on_toggle(2))
self.cl.grid(row = 2, column = 2)
self.chk_buttons = [self.cd, self.cr, self.cl] # List of checkboxes
self.var_states = [self.dvar, self.rvar, self.lvar] # List corresponding InvVar
def get_fc(self):
self.fc_user = self.fc_gui.get()
if self.fc_user:
if check_fc_range(self.fc_user):
self.add_checkbox()
return self.fc_user