Good day, I can not run the following code in pyqt, I'm new and do not really understand the class, I appreciate the collaboration
Apparently the problem is how to connect the function (self.ui.lineEdit_2.returnPressed.connect (self.checkText)
# -*- coding: utf-8 -*-
import sys
from mastermind import *
from PyQt5 import QtWidgets
import random
import time
class Menu_mm(QtWidgets.QDialog):
def __init__(self,parent=None):
QtWidgets.QWidget.__init__(self,parent)
self.ui = Ui_MasterMind()
self.ui.setupUi(self)
self.ui.comboBox.addItem("Facil")
self.ui.comboBox.addItem("Dificil")
self.ui.comboBox.addItem("Legendario")
self.ui.comboBox.activated.connect(self.num)
self.ui.pushButton.clicked.connect(self.Empezar)
self.ui.label_14.setVisible(False)
self.ui.label_19.setVisible(False)
self.ui.label_20.setVisible(False)
self.ui.label_15.setVisible(False)
self.ui.label_16.setVisible(False)
def num(self):
x= self.ui.comboBox.currentText()
if x == "Facil":
self.ui.label_6.setText("3")
y=1
elif x == "Dificil":
self.ui.label_6.setText("4")
y=2
else:
self.ui.label_6.setText("5")
y=3
def Empezar(self):
x = self.ui.comboBox.currentText()
if x == "Facil":
y = 1
elif x == "Dificil":
y = 2
else:
y = 3
continuar = 1
while continuar == 1:
if y == 1:
cant_digitos = 3
elif y == 2:
cant_digitos = 4
elif y == 3:
cant_digitos = 5
print(cant_digitos)
#print("cant_digitos")
digitos = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
codigo = ''
for i in range(cant_digitos):
elegido = random.choice(digitos)
while elegido in codigo:
elegido = random.choice(digitos)
codigo = codigo + elegido
print(codigo)
global propuesta
propuesta = self.ui.lineEdit_2.text()
intentos = 1
while propuesta != codigo:
intentos = intentos + 1
aciertos = 0
coincidencias = 0
for i in range(cant_digitos):
if propuesta[i] == codigo[i]:
aciertos = aciertos + 1
elif propuesta[i] in codigo:
coincidencias = coincidencias + 1
propuesta=self.ui.lineEdit_2.text()
self.ui.lineEdit_2.returnPressed.connect(self.checkText)
print(propuesta)
self.ui.label_13.setText(str(propuesta))
self.ui.label_9.setText(str(aciertos))
self.ui.label_11.setText(str(coincidencias))
self.ui.label_14.setVisible(True)
self.ui.label_15.setVisible(True)
self.ui.label_16.setVisible(True)
def checkText(self):
propuesta =self.ui.lineEdit_2.Text()
print("si")
self.ui.lineEdit_2.clear()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
myapp = Menu_mm()
myapp.show()
sys.exit(app.exec_())
You shouldn't put the connect statement inside a loop. It's going to create a new connection for each iteration through the loop
while continuar == 1:
while propuesta != codigo:
self.ui.lineEdit_2.returnPressed.connect(self.checkText)
You probably want to make that connection in the __init__
Related
The code doesn't output what I expected. How do I get the code to output when i call the function?
import calendar
import datetime
from datetime import date
Eke, Orie, Afor, Nkwo = 0, 1, 2, 3
start_year = 1600
def IgboWeek(func):
def wrapper_func():
if date.year != start_year:
Eke = calendar.SUNDAY
Orie = calendar.MONDAY
Afor = calendar.TUESDAY
Nkwo = calendar.WEDNESDAY
calendar.THURSDAY = Eke
calendar.FRIDAY = Orie
calendar.SATURDAY = Afor
func()
return wrapper_func
#IgboWeek
def birthday():
birthday = input("Enter your birthday in the format: YYYY/MM/DD: ")
if Eke in birthday:
print("Eke")
elif Orie in birthday:
print("Orie")
elif Afor in birthday:
print("Afor")
elif Nkwo in birthday:
print("Nkwo")
else:
print("Not in a good mood for that")
Igobirthday = IgboWeek(birthday)
Igobirthday()
thanks for your read and help.
I have download a genebank flat file from NCBI, which contains many entries. I would like to extract three entries from each gene and make them into a table. How to realize it? Thank you much. the file from NCBI---->The table I hope to get
my friend writes it for me with python:
================================================================================
import os
import pandas as pd
from tqdm import tqdm
import sys
def search_line(gene_dict,gene_name,target,info,mode,l):
if '/{}='.format(target) in l:
if len(l.split('"')) == 3:
gene_dict[gene_name][mode].append('{} = '.format(target) + l.split('"')[1].strip('\n'))
keep_read = 0
info = []
else:
info = [l.split('"')[1].strip('\n')]
keep_read = target_list.index(target)
else:
if '"' in l:
info.append(l.strip().strip('"\n'))
if '{} = '.format(target) + ' '.join(info) not in gene_dict[gene_name][mode]:
gene_dict[gene_name][mode].append('{} = '.format(target) + ' '.join(info))
keep_read = 0
info = []
else:
info.append(l.strip())
keep_read = target_list.index(target)
return gene_dict,info,keep_read
def init_frame_dict(gene_dict,ids,mode):
frame_dict = {'gene': gene_dict[ids]['gene'], 'source': mode}
for target in target_list[1:]:
frame_dict[target] = ''
return frame_dict
def gen_frame(gene_dict,flat):
frame = []
for ids in gene_dict.keys():
for mode in gene_dict[ids].keys():
if mode not in extract_list:
continue
# print(mode)
data = gene_dict[ids][mode]
frame_dict = init_frame_dict(gene_dict, ids, mode)
for target_data in data:
for target in target_list[1:]:
if '{} = '.format(target) in target_data:
if frame_dict[target] != '':
frame.append(frame_dict)
# print(frame_dict)
frame_dict = init_frame_dict(gene_dict, ids, mode)
frame_dict[target] = target_data.split('{} = '.format(target))[1]
frame.append(frame_dict)
pd.DataFrame(frame).to_csv('{}.csv'.format(flat[:-5]))
def main():
for flat in os.listdir(path_root):
gene_dict = {}
if flat[-4:] != 'flat':
continue
with open (os.path.join(path_root,flat)) as f:
lines = f.read()
genes = lines.split('/gene=')
skip = False
for gene in tqdm(genes[1:]):
if skip:
break
lines = gene.split('\n')
gene_name = lines[0].split('"')[1]
#init paras
mode = 'init'
target = 'none'
read_mode = 0
info = []
#init dict
if gene_name not in gene_dict:
gene_dict[gene_name] = {'gene':gene_name,'mRNA':[],'ncRNA':[],'CDS':[],'misc_RNA':[],'exon':[],}
#proc lines
for l in lines:
if 'ORIGIN' in l:
skip = True
break
if ' mRNA' in l:
mode = 'mRNA'
elif ' ncRNA' in l:
mode = 'ncRNA'
elif ' CDS' in l:
mode = 'CDS'
elif ' misc_RNA' in l:
mode = 'misc_RNA'
elif ' exon' in l:
mode = 'exon'
# search_line(gene_dict, gene_name, target, info, mode, l)
if '/product=' in l and mode != 'init' or (target == 'product' and read_mode == target_list.index('product')):
target = 'product'
gene_dict,info,read_mode = search_line(gene_dict, gene_name, target, info, mode, l)
if '/protein_id=' in l and mode != 'init' or (target == 'protein_id' and read_mode == target_list.index('protein_id')):
target = 'protein_id'
gene_dict,info,read_mode = search_line(gene_dict, gene_name, target, info, mode, l)
if '/note=' in l and mode != 'init' or (target == 'note' and read_mode == target_list.index('note')):
target = 'note'
gene_dict,info,read_mode = search_line(gene_dict, gene_name, target, info, mode, l)
if '/transcript_id=' in l and mode != 'init' or (target == 'note' and read_mode == target_list.index('transcript_id')):
target = 'transcript_id'
gene_dict,info,read_mode = search_line(gene_dict, gene_name, target, info, mode, l)
gen_frame(gene_dict,flat)
if __name__ == '__main__':
target_list = ['none', 'product', 'transcript_id','protein_id','note']
extract_list = ['mRNA']
path_root = 'flats'
if not os.path.exists(path_root):
print('Please put your flat files in flats/ directory !')
sys.exit()
if len(os.listdir(path_root)) == 0:
print('No files found in flats/ directory.')
sys.exit()
main()
I am writing a website for Flask. I use a bunch of uWSGI + NGINX + Flask-Socketio. I use gevent as an asynchronous module. Errors occur during operation:
RuntimeError: You need to use the gevent-websocket server.
uwsgi_response_writev_headers_and_body_do(): Broken pipe [core/writer.c line 306] during >
Feb 23 12:57:55 toaa uwsgi[558436]: OSError: write error
I tried different configurations and also removed the async_mode='gevent' from the socketio initialization.
wsgi.py file:
from webapp import app, socketio
if __name__ == '__main__':
socketio.run(app, use_reloader=False, debug=True, log_output=True)
project.ini:
[uwsgi]
module = wsgi:app
master = true
gevent = 1024
gevent-monkey-patch = true
buffer-size=32768 # optionally
socket = /home/sammy/projectnew/projectnew.sock
socket-timeout = 240
chmod-socket = 664
vacuum = true
die-on-term = true
webapp/__init__.py for application app:
from gevent import monkey
monkey.patch_all()
import grpc.experimental.gevent
grpc.experimental.gevent.init_gevent()
from flask import Flask, session, request
from config import DevelopConfig, MqttConfig, MailConfig, ProductionConfig
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_mail import Mail
from flask_script import Manager
from flask_socketio import SocketIO
# from flask_mqtt import Mqtt
from flask_login import LoginManager
from flask_babel import Babel
from flask_babel_js import BabelJS
from flask_babel import lazy_gettext as _l
from apscheduler.schedulers.gevent import GeventScheduler
# from celery import Celery
app = Flask(__name__)
app.config.from_object(ProductionConfig)
app.config.from_object(MqttConfig)
app.config.from_object(MailConfig)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
mail = Mail(app)
manager = Manager(app, db)
login_manager = LoginManager(app)
login_manager.login_view = 'auth'
login_manager.login_message = _l("Необходимо авторизоваться для доступа к закрытой странице")
login_manager.login_message_category = "error"
# celery = Celery(app.name, broker=Config.CELERY_BROKER_URL)
# celery.conf.update(app.config)
scheduler = GeventScheduler()
# socketio = SocketIO(app) - Production Version
socketio = SocketIO(app, async_mode='gevent')
babel = Babel(app)
babeljs = BabelJS(app=app, view_path='/translations/')
import webapp.views
#babel.localeselector
def get_locale():
# if the user has set up the language manually it will be stored in the session,
# so we use the locale from the user settings
try:
language = session['language']
except KeyError:
language = None
if language is not None:
print(language)
return language
return request.accept_languages.best_match(app.config['LANGUAGES'].keys())
from webapp import models
if __name__ == "__main__":
manager.run()
The class in which the socket itself is used (mqtt.py):
from webapp import socketio, app
from flask import request
from flask_mqtt import Mqtt
from flask_babel import lazy_gettext as _l
from webapp.tasks import SchedulerTask
from webapp import translate_state_gate as tr_msg
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
POOL_TIME = 2
end_publish = None
devices = None
schedulers_list = list()
sch_task = None
sid_mqtt = None
code_list = list()
def __init__(self, devices, lang):
mqtt._connect()
self.devices = devices
self.sch_task = SchedulerTask()
if lang not in app.config['LANGUAGES'].keys():
lang = 'ru'
self.dict_gate = {"dict_state_button": {'con_Clos': tr_msg.MessageGate.t_message[lang]["f_open"],
'con_Open': tr_msg.MessageGate.t_message[lang]["f_close"],
"fl_OpenClos": (tr_msg.MessageGate.t_message[lang]["f_continue"],
tr_msg.MessageGate.t_message[lang]["f_stop"],
tr_msg.MessageGate.t_message[lang]["f_abort"])},
"dict_state_text": {tr_msg.MessageGate.t_message[lang]["f_open"]:\
tr_msg.MessageGate.t_message[lang]["ps_close"],
tr_msg.MessageGate.t_message[lang]["f_close"]:\
tr_msg.MessageGate.t_message[lang]["ps_open"],
tr_msg.MessageGate.t_message[lang]["f_continue"]:\
tr_msg.MessageGate.t_message[lang]["ps_stop"],
tr_msg.MessageGate.t_message[lang]["f_abort"]:\
tr_msg.MessageGate.t_message[lang]["pr_close"],
tr_msg.MessageGate.t_message[lang]["f_stop"]:\
(tr_msg.MessageGate.t_message[lang]["pr_open"],
tr_msg.MessageGate.t_message[lang]["pr_close"],
tr_msg.MessageGate.t_message[lang]["pr_move"])},
"dict_type_element": {"button": u'', "text": u'', "device_code": u'', },
"state_gate": {},
"position": {"state": u'', "stop": False},
"reverse": False,
}
self.close_msg = tr_msg.MessageGate.t_message[lang]["pr_close"]
self.open_msg = tr_msg.MessageGate.t_message[lang]["pr_open"]
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_on_connect = socketio.on('connect')(self._handle_on_connect)
self.handle_unsubscribe_all = socketio.on('unsubscribe_all')(self._handle_unsubscribe_all)
def _handle_on_connect(self):
self.sid_mqtt = request.sid
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")
# print(self.struct_state_devices)
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"], room=self.sid_mqtt)
# print(dict_dev["state_gate"]["esp_id"] + str(dict_dev["dict_type_element"]))
When you use uWSGI, the async_mode should be gevent_uwsgi:
socketio = SocketIO(app, async_mode='gevent_uwsgi')
I dont know how to fix them bug. Please help me:(
I want the fish to be animated.
import pygame
import random
import os
pygame.init()
class Game:
def __init__(self):
super().__init__()
self.WIDTH, self.HEIGHT = 1100, 700
self.player = Player()
self.player_id = self.player.id
self.main()
def main(self):
FPS = 60
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
self.draw()
pygame.display.update()
pygame.quit()
def draw(self):
#background
self.canvas = pygame.display.set_mode((self.WIDTH, self.HEIGHT))
space_background = pygame.transform.scale(pygame.image.load(os.path.join("Sprites", "background.png")), (self.WIDTH, self.HEIGHT))
pygame.display.set_caption("Akvarium")
self.canvas.blit(space_background, (0, 0))
#player
self.canvas.blit(self.player.player_fish, (self.player_id.x, self.player_id.y))
pygame.display.update()
class Sprites:
def __init__(self, x, y, id_width, id_height):
self.x, self.y = x, y
self.id = pygame.Rect(x, y, id_width, id_height)
def load_sprites(self, file_path):
sprites = [i for i in os.listdir(file_path)]
return sprites
class Player(Sprites):
IDLE = "idle"
SWIM = "swim"
LEFT = "left"
RIGHT = "right"
#player_img = pygame.image.load(os.path.join("Sprites/Player/idle_left", "tile000.png"))
def __init__(self):
x, y = 100, 100
self.player_width, self.player_height = 85, 60
super().__init__(x, y, self.player_width, self.player_height)
self.player_sprites = self.load_all_sprites()
self.movement = self.IDLE
self.directions = self.LEFT
self.tik()
def load_all_sprites(self):
sprite_sheed = {self.IDLE: {self.LEFT: [], self.RIGHT: []},
self.SWIM: {self.LEFT: [], self.RIGHT: []}}
sprite_sheed[self.IDLE][self.LEFT] = self.load_sprites("Sprites/Player/idle_left")
sprite_sheed[self.IDLE][self.RIGHT] = self.load_sprites("Sprites/Player/idle_right")
sprite_sheed[self.SWIM][self.LEFT] = self.load_sprites("Sprites/Player/swim_left")
sprite_sheed[self.SWIM][self.RIGHT] = self.load_sprites("Sprites/Player/swim_right")
return sprite_sheed
def animation(self, idx):
idx += 1
max_idx = len(self.player_sprites[self.movement][self.directions])
idx = idx % max_idx
return idx
def tik(self):
sprite_idx = self.animation(0)
self.player_img = self.player_sprites[self.movement][self.directions][int(sprite_idx)]
self.player_fish = pygame.transform.scale(self.player_img, (self.player_width, self.player_height))
Game()
a mistake is:
self.player_fish = pygame.transform.scale(self.player_img, (self.player_width, self.player_height))
TypeError: argument 1 must be pygame.Surface, not str
Python is an interpreted, high-level and general-purpose programming language. Python's design philosophy emphasizes code readability with its notable use of significant whitespace. Its language constructs and object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects.
#correct code must be
self.player_fish = pygame.transform.scale(self.canvas,(self.player_width,self.player_height))
Here self.canvas is the surface and the size is corrrect.....
Hope it helps
Sometimes I need to make multiple copies of code with incrementing numbers.
In a form I'm coding, I need to make upwards of 12 checkboxes, each of which requires the following code:
self.checkBox1 = QtGui.QCheckBox()
self.checkBox1.setGeometry(QtCore.QRect(20, 20, 70, 17))
self.checkBox1.setObjectName(_fromUtf8("checkBox1"))
The script below enables me to avoid the boring task of manually changing the numbers for each checkbox.
I just copy the 3 lines above into the windows clipboard, and then...
I insert "checkBox" into the first field in the form, "1" into the second field, and 12 into the third field.
When I hit the "ok" button, the 12 sequentially numbered copies of the 3 lines appear in the 4th field in the form.
I hope this provides some help to other people.
Marc
Here's my code:
# -*- coding: latin-1 -*-
"""
duplicate_text_with_incrementing_nos_for_programming_and_paste_to_clipboard.py
Harvest text from clipboard and run functions below, and then paste back to clipboard
"""
import sys
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4.QtCore import (Qt, SIGNAL)
from PyQt4.QtGui import (QApplication, QDialog, QHBoxLayout, QLabel,
QPushButton)
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.initUI()
def initUI(self):
okButton01 = QtGui.QPushButton("OK")
cancelButton01 = QtGui.QPushButton("Cancel")
okButton01.clicked.connect(self.fn_okButton01_clicked)
cancelButton01.clicked.connect(QtCore.QCoreApplication.instance().quit)
self.cancelButton01 = cancelButton01
prefix_label = QtGui.QLabel('Prefix')
digit_label = QtGui.QLabel('Digit')
iterations_label = QtGui.QLabel('Iterations')
clip_label = QtGui.QLabel('Clip')
prefixEdit = QtGui.QLineEdit()
digitEdit = QtGui.QLineEdit()
iterationsEdit = QtGui.QLineEdit()
reviewEdit = QtGui.QTextEdit()
self.prefix_label = prefix_label
self.digit_label = digit_label
self.iterations_label = iterations_label
self.clip_label = clip_label
self.prefixEdit = prefixEdit
self.digitEdit = digitEdit
self.iterationsEdit = iterationsEdit
self.reviewEdit = reviewEdit
hbox01 = QtGui.QHBoxLayout()
hbox01.addWidget(prefix_label)
hbox01.addWidget(prefixEdit)
hbox01.addWidget(digit_label)
hbox01.addWidget(digitEdit)
hbox01.addWidget(iterations_label)
hbox01.addWidget(iterationsEdit)
hbox03 = QtGui.QHBoxLayout()
hbox03.addWidget(clip_label)
hbox03.addWidget(reviewEdit)
self.reviewEdit.setText(fn_getText())
hbox00 = QtGui.QHBoxLayout()
hbox00.addStretch(1)
hbox00.addWidget(okButton01)
hbox00.addWidget(cancelButton01)
vbox0 = QtGui.QVBoxLayout()
vbox0.addLayout(hbox01)
vbox0.addStretch(1)
vbox0.addLayout(hbox03)
vbox0.addStretch(1)
vbox0.addLayout(hbox00)
self.setLayout(vbox0)
self.setGeometry(300, 300, 600, 300) #class PySide.QtCore.QRectF(left, top, width, height) http://srinikom.github.com/pyside-docs/PySide/QtCore/QRectF.html#PySide.QtCore.QRectF
self.setWindowTitle('Duplicate Code Strings W/Increasing Numbers')
self.show()
def fn_okButton01_clicked(self):
prefixEditText = str(self.prefixEdit.text())
digitEditText = str(self.digitEdit.text())
iterationsEditText = str(self.iterationsEdit.text())
nutext = prefixEditText + ' ' + digitEditText + ' ' + iterationsEditText
print 'Line 89: nutext = ' + str(nutext)
original_clip = self.reviewEdit.toPlainText() # PySide.QtGui.QLineEdit.text(), http://srinikom.github.com/pyside-docs/PySide/QtGui/QLineEdit.html
txt2paste2clipbd = fn_duplicate_code_with_increments(texte=str(original_clip), no_of_copies=str(iterationsEditText), string_b4_digits=str(prefixEditText), digits=str(digitEditText))
self.reviewEdit.setPlainText(txt2paste2clipbd)
setWinClipText(txt2paste2clipbd)
#self.deleteLater()
#event.accept() #http://www.qtcentre.org/threads/20895-PyQt4-Want-to-connect-a-window-s-close-button
#self.destroy()
def formm():
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
def fn_getText():
# get text from clipboard
win32clipboard.OpenClipboard()
text = win32clipboard.GetClipboardData(win32clipboard.CF_TEXT)
win32clipboard.CloseClipboard()
return text
def setWinClipText(aString):
# Send text to clipboard
import win32clipboard
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(aString)
win32clipboard.CloseClipboard()
def fn_duplicate_code_with_increments(texte, no_of_copies, string_b4_digits, digits):
"""
to do: combine args 2 and 3, and use re module to determine with chars are the digits to increment
"""
import re
import string
i = 0
tempclipDup = texte[:]
temp_instance = ''
accumulator = ''
while i <= int(no_of_copies) - 1:
i +=1
orig_str = string_b4_digits + str(digits)
replact_st = string_b4_digits + str(i)
temp_instance = tempclipDup.replace(orig_str, replact_st)
if len(accumulator) > 2:
accumulator = accumulator + '\n' + temp_instance
else:
accumulator = temp_instance
return accumulator
if 1 == 1:
import os
import sys
import subprocess
import win32clipboard
import win32con
fn_operation_log = ''
arg_sent_2this_script = ''
alternative = 1
if alternative == 1:
formm()
elif alternative == 2:
txt2paste2clipbd = fn_duplicate_code_with_increments(texte=fn_getText(), no_of_copies=3, string_b4_digits='hbox', digits=1)
setWinClipText(txt2paste2clipbd)
The property is called plainText for QTextEdit.
(Contrary to the single line QLineEdit, which has a text property)