wxPython GUI lost response when starting a TCP server - tcp

Recently, I'm learning wxPython. So I wrote a little TCP server program with wxPython. My program will be crashed after I pressed the 'init' button. I also wrote another client program which successfully connected with this wxPython TCP server when server GUI lost response.
This really confused me.
#!/usr/bin/env python
#Boa:App:BoaApp
#coding:utf-8
import wx
import Frame1
modules ={'Frame1': [1, 'Main frame of Application', u'Frame1.py']}
class BoaApp(wx.App):
def OnInit(self):
self.main = Frame1.create(None)
self.main.Show()
self.SetTopWindow(self.main)
return True
def main():
application = BoaApp(0)
application.MainLoop()
if __name__ == '__main__':
main()
#
#Boa:Frame:Frame1
#coding:utf-8
import wx
import socket
import sys
import time
def create(parent):
return Frame1(parent)
[wxID_FRAME1, wxID_FRAME1BUTTON1, wxID_FRAME1BUTTON2, wxID_FRAME1PANEL1,
wxID_FRAME1STATICLINE1, wxID_FRAME1STATICTEXT1, wxID_FRAME1STATICTEXT2,
wxID_FRAME1TEXTCTRL1, wxID_FRAME1TEXTCTRL2, wxID_FRAME1TEXTCTRL3,
] = [wx.NewId() for _init_ctrls in range(10)]
class Frame1(wx.Frame):
def _init_ctrls(self, prnt):
# generated method, don't edit
wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
pos=wx.Point(644, 336), size=wx.Size(302, 375),
style=wx.DEFAULT_FRAME_STYLE & ~ wx.RESIZE_BORDER,
title=u'TCP SERVER')
self.SetClientSize(wx.Size(286, 337))
self.panel1 = wx.Panel(id=wxID_FRAME1PANEL1, name='panel1', parent=self,
pos=wx.Point(0, 0), size=wx.Size(286, 337),
style=wx.TAB_TRAVERSAL)
self.staticText1 = wx.StaticText(id=wxID_FRAME1STATICTEXT1,
label=u'HOST', name='staticText1', parent=self.panel1,
pos=wx.Point(32, 24), size=wx.Size(80, 24), style=0)
self.staticText2 = wx.StaticText(id=wxID_FRAME1STATICTEXT2,
label=u'PORT', name='staticText2', parent=self.panel1,
pos=wx.Point(32, 64), size=wx.Size(72, 22), style=0)
self.textCtrl1 = wx.TextCtrl(id=wxID_FRAME1TEXTCTRL1, name='textCtrl1',
parent=self.panel1, pos=wx.Point(136, 24), size=wx.Size(136, 22),
style=0, value=u'ENTER HOSTNAME')
self.textCtrl2 = wx.TextCtrl(id=wxID_FRAME1TEXTCTRL2, name='textCtrl2',
parent=self.panel1, pos=wx.Point(136, 64), size=wx.Size(136, 22),
style=0, value=u'ENTER PORT')
self.button1 = wx.Button(id=wxID_FRAME1BUTTON1, label=u'INIT',
name='button1', parent=self.panel1, pos=wx.Point(48, 112),
size=wx.Size(75, 24), style=0)
self.button2 = wx.Button(id=wxID_FRAME1BUTTON2, label=u'CLEAR',
name='button2', parent=self.panel1, pos=wx.Point(168, 112),
size=wx.Size(75, 24), style=0)
self.staticLine1 = wx.StaticLine(id=wxID_FRAME1STATICLINE1,
name='staticLine1', parent=self.panel1, pos=wx.Point(16, 152),
size=wx.Size(256, 2), style=0)
self.textCtrl3 = wx.TextCtrl(id=wxID_FRAME1TEXTCTRL3, name='textCtrl3',
parent=self.panel1, pos=wx.Point(32, 168), size=wx.Size(232, 144),
style=wx.TE_MULTILINE, value=u'MESSAGE') #STYLE CHANGED
def __init__(self, parent):
self._init_ctrls(parent)
self.Bind(wx.EVT_BUTTON, self.ServerInit, self.button1)
self.Bind(wx.EVT_BUTTON, self.CleanUp, self.button2)
def ServerInit(self, event):
self.textCtrl3.ChangeValue('')
self.HOST = ''
self.PORT = 8888
#self.GetValue()
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.textCtrl3.AppendText('Socket created\n')
try:
self.s.bind((self.HOST, self.PORT))
except socket.error , msg:
self.textCtrl3.AppendText('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] + '\n')
sys.exit(1)
self.textCtrl3.AppendText('Socket bind complete\n')
self.s.listen(10)
self.textCtrl3.AppendText('Socket now listening\n')
#now keep talking with the client
while (1):
#wait to accept a connection - blocking call
conn, addr = self.s.accept()
tempStr = 'Connected with ' + addr[0] + ':' + str(addr[1]) + '\n'
self.textCtrl3.AppendText(tempStr)
while (1):
data = conn.recv(1024)
reply = 'RECEIVED:' + data + '\n'
self.textCtrl3.AppendText(reply)
conn.sendall('SERVER RECEIVED')
conn.sendall('DISCONNECTED')
conn.close()
s.close()
def CleanUp(self, event):
self.textCtrl3.ChangeValue(' ')

Normally, you just import the other module and instantiate the class. Something like this would be better
import myFrame
# then in your OnInit
def OnInit(self):
frame = myFrame.Frame1()
Or something similar. Personally, I almost never subclass wx.App unless I plan to do some PreCreate stuff. As for why your GUI becomes unresponsive, you are doing a long running process in your ServerInit method which is blocking the GUI's main loop. You'll want to put your socket connection and communication code into a separate thread and pass the results back using wxPython's thread-safe methods. See the following links for more info:
http://wiki.wxpython.org/LongRunningTasks
http://www.blog.pythonlibrary.org/wxpython-and-threads

Related

Capturing span error for a text box with selenium python

With the script below i am trying to get the error text from a span error text box for first name when a name is not entered and the user clicks on the submit button, from a registration screen with the HTML below.(https://www.walmart.com/account/signup. However I end up just getting none instead of the text. When i try to get the text from chrome console i receive the text with the xpath and css selector as "$x("//span[#class='span-error']")[2]" and "$$(".span-error")[2]". I would like some guidance as to what I am missing, i think have tried everything i can think of.
Test case:
Get to the link Enter nothing on the first name,Get a validation
error Assert the validation error Enter an invalid name as ":::" Get
a validation error (they seem to have a couple)and so on
from time import sleep
from conftest import os
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
# LoginScreenSelectors
sel_first_name = "#first-name-su"
sel_last_name = "#last-name-su"
sel_email = "#email-su"
sel_password = "#password-su"
sel_error_message = ".span-error:nth-of-type(2)"
sel_submit = f"""[data-automation-id="signup-submit-btn"]"""
sel_required_error = f"""[data-error="required"]"""
class Login():
'''This will signup to the applcaiton '''
def __init__(self, driver):
self.driver = driver
wait = WebDriverWait(self.driver, 20)
self.first_name = wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR, sel_first_name))
)
self.last_name = wait.until(
EC.visibility_of_element_located((By.CSS_SELECTOR, sel_last_name))
)
self.email = wait.until(
EC.visibility_of_element_located((By.CSS_SELECTOR, sel_email))
)
self.password = wait.until(
EC.visibility_of_element_located((By.CSS_SELECTOR, sel_password))
)
self.submit = wait.until(
EC.visibility_of_element_located((By.CSS_SELECTOR, sel_submit))
)
def login_to_website(self):
wait = WebDriverWait(self.driver, 10)
print(self.driver.title)
self.first_name.click()
self.first_name.send_keys(" ")
self.first_name.send_keys(Keys.TAB)
self.first_name_error_message = wait.until(
EC.presence_of_all_elements_located((By.CSS_SELECTOR, sel_error_message))
)
type(self.first_name_error_message)
error_messages = []
for messages in self.first_name_error_message:
print(error_messages.append(messages.text))
#if i could get this then i could simply get the first index and then keep filtering
it but even that is proving to be difficult.
Try out this to get all elements with error messages
error_messages = self.driver.find_elements(By.XPATH, "//*[#id="sign-up-form"]/div/span[2]']")
This is how I ended up solving it.
Get the xpath as f"""[data-error="required"]""" and then with a for loop cycle through all the error messages for input fields, I hope this will help anyone that is trying to take a stab at validating happy and negative testing on the same testcase.
from time import sleep
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
# LoginScreenSelectors
sel_first_name = "#first-name-su"
sel_last_name = "#last-name-su"
sel_email = "#email-su"
sel_password = "#password-su"
sel_submit = f"""[data-automation-id="signup-submit-btn"]"""
sel_required_error = f"""[data-error="required"]"""
class Register():
'''This wil register the user to the application '''
def __init__(self, driver):
self.driver = driver
wait = WebDriverWait(self.driver, 20)
self.first_name = wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR, sel_first_name))
)
self.last_name = wait.until(
EC.visibility_of_element_located((By.CSS_SELECTOR, sel_last_name))
)
self.email = wait.until(
EC.visibility_of_element_located((By.CSS_SELECTOR, sel_email))
)
self.password = wait.until(
EC.visibility_of_element_located((By.CSS_SELECTOR, sel_password))
)
self.submit = wait.until(
EC.visibility_of_element_located((By.CSS_SELECTOR, sel_submit))
)
def login_to_website(self):
wait = WebDriverWait(self.driver, 10)
'''This will check for validaitons'''
self.last_name.send_keys("Test Automation Last Name")
self.email.send_keys("a#b.com")
self.password.send_keys("password")
self.submit.click()
self.first_name_error_message = wait.until(
EC.presence_of_all_elements_located((By.CSS_SELECTOR, sel_required_error))
)
for first_name_required_message in self.first_name_error_message:
first_name_message = first_name_required_message.text.replace("\n", ":")
# print(first_name_message)
# print(first_name_message[first_name_message.find(":") + 1:])
assert first_name_message[first_name_message.find(":") + 1:] == "First name is required."
sleep(1)
self.last_name.clear()
self.first_name.click()
self.first_name.send_keys("Test Automation First Name ")
self.submit.click()
self.last_name_error_message = wait.until(
EC.presence_of_all_elements_located((By.CSS_SELECTOR, sel_required_error)))
for last_name_required_message in self.last_name_error_message:
last_name_message = last_name_required_message.text.replace("\n", ":")
assert last_name_message[last_name_message.find(":") + 1:] == "Last name is required."
self.email.clear()
self.last_name.click()
self.last_name.send_keys("Test Automation Last Name ")
self.submit.click()
self.email_error_message = wait.until(
EC.presence_of_all_elements_located((By.CSS_SELECTOR, sel_required_error)))
for email_required_message in self.email_error_message:
email_message = email_required_message.text.replace("\n", ":")
assert email_message[email_message.find(":") + 1:] == "Email address is required."
self.password.clear()
self.email.click()
self.email.send_keys("your#email.com")
self.submit.click()
self.password_error_message = wait.until(
EC.presence_of_all_elements_located((By.CSS_SELECTOR, sel_required_error)))
'''only way i could assert it '''
for password_required_message in self.password_error_message:
password_message = password_required_message.text.replace("\n", " ")
assert password_message[password_message.find("d") + 1:]\
.replace(" ", "") == "passwordisrequired."
self.password.click()
self.password.send_keys("something123$")
self.submit.click()

Python has stopped working while adding sizer in scrolled panel in wxpython

import wx
import wx.adv
from wx.lib.masked import NumCtrl
import wx.lib.scrolledpanel
import wx.lib.masked as masked
from wx.lib.masked import Field, BaseMaskedTextCtrl
class mainWindow(wx.Frame):
def __init__(self, camera):
#inheritence
wx.Frame.__init__(self, None, style= wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.CLIP_CHILDREN, size=(1370,720),pos=(0,0))
self.Title = "Registration"
self.SetSize(1370,720)
self.Maximize(True)
self.SetBackgroundColour('#f0f0f0')
menubar = wx.MenuBar()
#main ui
self.mainpanel = wx.Panel(self, size=(1370,720), pos=(0,0))
self.mainpanel.SetBackgroundColour('#f0f0f0')
mid_font = wx.Font(22, wx.DECORATIVE,wx.ITALIC,wx.BOLD)
#------------form panel-------------
self.scroll_panel = wx.lib.scrolledpanel.ScrolledPanel(self.mainpanel,size=(380,540), pos=(30,20),style=wx.NO_BORDER)
self.namepanel = wx.Panel(self.scroll_panel,size=(350,800), pos=(0,0),style=wx.DOUBLE_BORDER)
self.namepanel.SetForegroundColour('#1b262c')
self.Sizer = wx.BoxSizer( wx.VERTICAL )
self.scroll_panel.SetSizer(self.Sizer)
small_font = wx.Font(11, wx.DECORATIVE,wx.ITALIC,wx.BOLD)
fname = wx.StaticText(self.namepanel, -1, "First Name",pos=(30,70))
fname.SetFont(small_font)
self.fname = wx.TextCtrl(self.namepanel, pos=(155,70), size=(160, 25))
mname = wx.StaticText(self.namepanel, -1, "Middle Name",pos=(30,110))
mname.SetFont(small_font)
self.mname = wx.TextCtrl(self.namepanel, pos=(155,110), size=(160, 25))
lname = wx.StaticText(self.namepanel, -1, "Last Name",pos=(30,150))
lname.SetFont(small_font)
self.lname = wx.TextCtrl(self.namepanel, pos=(155,150), size=(160, 25))
button_font = wx.Font(12, wx.DECORATIVE,wx.NORMAL,wx.BOLD)
self.add = wx.Button(self.namepanel, -1, "Confirm", pos=(110,200),size=(130, 30),style=wx.DOUBLE_BORDER)
#self.add.Bind(wx.EVT_BUTTON, self.addinfo)
self.add.SetBackgroundColour('#FFFFFF')
self.add.SetForegroundColour('#1b262c')
self.add.SetFont(button_font)
self.Sizer.Add( self.namepanel, 0, wx.CENTER|wx.ALL, 5 )
self.scroll_panel.SetupScrolling(scrollToTop=False)
class all_module(wx.Frame):
def __init__(self):
#inheritence
wx.Frame.__init__(self, None, style= wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.CLIP_CHILDREN,pos=(0,0))
self.infopanel = wx.Panel(self,size=(1000,780), pos=(0, 0),style=wx.DOUBLE_BORDER)
self.registration = wx.Button(self.infopanel, -1, "Registration", pos=(0,0),size=(130, 30),style=wx.DOUBLE_BORDER)
self.registration.Bind(wx.EVT_BUTTON, self.register)
def register(self, event):
window = mainWindow(camera)
window.Show()
app = wx.App()
window = all_module()
window.Show()
app.MainLoop()
This is our code in which there is a simple registration scrolled panel and it is added in boxsizer. when i press close button i got this error that python has stopped working. but when i remove the sizer and i place all static text and textctrl out side the sizer, the program closes smoothly. But if i add in sizer i got the error i tried all the ways like self.Close() and self.Destroy() but nothing has worked. Any suggestion would be appreciated for us, Thanks in advance!!
Python has stopped working
.

How do I connect WindowContextHelpButtonHint to a widget click?

I can add self.setWindowFlags(Qt.Window | Qt.WindowContextHelpButtonHint | Qt.WindowCloseButtonHint) to the constructor of my QMainWindow which adds the '?' button. Now I want to add contextual help information to virtually all UI components. How do I connect a click on the '?' button and then a click on some ui element (say a qlistview) such that a help message pops up?
Below is part of my program stripped to make it easy. How do I make it such that when the user clicks the '?' and then either a QDoubleSpinBox or the QListView or any of the QPushButtons that a help message displays?
I have searched for this but it seems the vast amount of questions and answers are about how to remove the '?' button or how to add it. None actually deal with how to alter the button's behaviour.
I've also tried using setInputMethodHints() to assign hints to ui components but this method doesn't accept custom strings as I assumed it would.
Btw: I also would like the '?' button to not replace the minimization button. I have yet to figure out how to achieve this either.
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
APPNAME = 'Mesoscale Brain Explorer'
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setWindowTitle(APPNAME)
self.sidebar = Sidebar()
self.setWindowFlags(Qt.Window | Qt.WindowContextHelpButtonHint | Qt.WindowCloseButtonHint)
self.setup_ui()
def setup_ui(self):
self.pl_frame = QFrame()
splitter = QSplitter(self)
self.enable = lambda yes: splitter.setEnabled(yes)
splitter.setHandleWidth(3)
splitter.setStyleSheet('QSplitter::handle {background: #cccccc;}')
splitter.addWidget(self.sidebar)
splitter.addWidget(self.pl_frame)
self.setCentralWidget(splitter)
self.menu = self.menuBar()
m = self.menu.addMenu('&File')
a = QAction('&New project', self)
a.setShortcut('Ctrl+N')
a.setStatusTip('Create new project')
m.addAction(a)
a = QAction('&Open project', self)
a.setShortcut('Ctrl+O')
a.setStatusTip('Open project')
m.addAction(a)
a = QAction("&Quit", self)
a.setShortcut("Ctrl+Q")
a.setStatusTip('Leave The App')
a.setIcon(QIcon('pics/quit.png'))
m.addAction(a)
about_action = QAction('&About ' + APPNAME, self)
about_action.setStatusTip('About ' + APPNAME)
about_action.setShortcut('F1')
m = self.menu.addMenu('&Project')
m.setEnabled(False)
a = QAction("&Close", self)
a.setStatusTip('Close project')
m.addAction(a)
self.project_menu = m
help_menu = self.menu.addMenu('&Help')
help_menu.addAction(about_action)
class Sidebar(QWidget):
open_pipeconf_requested = pyqtSignal()
open_datadialog_requested = pyqtSignal()
automate_pipeline_requested = pyqtSignal()
x_origin_changed = pyqtSignal(float)
y_origin_changed = pyqtSignal(float)
units_per_pixel_changed = pyqtSignal(float)
def __init__(self, parent=None):
super(Sidebar, self).__init__(parent)
self.x_origin = QDoubleSpinBox()
self.y_origin = QDoubleSpinBox()
self.units_per_pixel = QDoubleSpinBox()
self.setup_ui()
def setup_ui(self):
self.setContentsMargins(4, 6, 5, 0)
vbox = QVBoxLayout()
hbox = QHBoxLayout()
hbox.addWidget(QLabel('Origin:'))
hbox.addWidget(QLabel('Units per pixel:'))
vbox.addLayout(hbox)
hbox2 = QHBoxLayout()
hhbox = QHBoxLayout()
hhbox2 = QHBoxLayout()
hhbox.addWidget(QLabel("X:"))
hhbox.addWidget(self.x_origin)
hhbox.addWidget(QLabel("Y:"))
hhbox.addWidget(self.y_origin)
hhbox2.addWidget(self.units_per_pixel)
hbox2.addLayout(hhbox)
hbox2.addLayout(hhbox2)
vbox.addLayout(hbox2)
self.units_per_pixel.setDecimals(5)
self.units_per_pixel.setMaximum(100000)
self.x_origin.setMaximum(100000)
self.y_origin.setMaximum(100000)
self.pl_list = QListView()
self.pl_list.setIconSize(QSize(18, 18))
self.pl_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.pl_list.setEditTriggers(QAbstractItemView.NoEditTriggers)
vbox.addWidget(QLabel('Pipeline:'))
vbox.addWidget(self.pl_list)
pb = QPushButton('&Automation')
pb.clicked.connect(self.automate_pipeline_requested)
vbox.addWidget(pb)
vbox.addSpacerItem(QSpacerItem(0, 1, QSizePolicy.Minimum, QSizePolicy.Expanding))
pb = QPushButton('&Configure Pipeline')
pb.clicked.connect(self.open_pipeconf_requested)
vbox.addWidget(pb)
pb = QPushButton('&Manage Data')
pb.clicked.connect(self.open_datadialog_requested)
vbox.addWidget(pb)
vbox.setStretch(0, 0)
vbox.setStretch(1, 0)
vbox.setStretch(2, 0)
self.setLayout(vbox)
if __name__ == '__main__':
app = QApplication(sys.argv)
app.setApplicationName(APPNAME)
app.setOrganizationName('University of British Columbia')
w = MainWindow()
w.resize(1060, 660)
w.show()
app.exec_()
app.deleteLater()
del w
sys.exit()

Stop the error when trying to manipulate the items of a Listbox, but no item is selected?

I am a beginner in tkinter. I am making a list of names. You can delete, select and edit it, but if I don't select anything in the list and click these buttons, it says:
Exception in Tkinter callback Traceback (most recent call last): File
"C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__ return
self.func(*args) File "C:\Users\user\Desktop\HOW_TOUGH - NEW\Change_user.py",
line 60, in Edit (idx, ) = d ValueError: need more than 0 values to unpack'''
I am planning to disable the buttons if the user doesn't click anything but I am not expert enough. Here's my code (it's a child window)
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
class Nick:
def __init__(self, master ):
self.master = master
self.window = Toplevel(master)
self.window.title('Change User')
self.window.geometry('300x300')
self.window.minsize(300, 300)
self.window.maxsize(300, 300)
self.nickname = StringVar()
self.lb = Listbox(self.window, selectmode = 'SINGLE')
f= open('users.txt','r')
rec = f.readlines()
f.close()
for i in rec:
p = i.find('|')
nickname = i[:p]
self.lb.insert(END, nickname)
self.lb.pack()
self.Ed = ttk.Button(self.window, text = 'Edit', command = self.Edit).pack()
self.Del = ttk.Button(self.window, text = 'Delete', command = self.Delete).pack()
self.Bac = ttk.Button(self.window, text = 'Back', command = self.Back).pack()
self.Okay = ttk.Button(self.window, text = 'Ok', command = self.Ok).pack()
def Back(self):
self.window.destroy()
def Delete(self):
d = self.lb.curselection()
(idx, ) = d
self.lb.delete(idx)
f = open('users.txt','r')
r = f.readlines()
f.close()
rec = r[idx]
r.remove(rec)
f = open('users.txt','w')
new = ''.join(r)
r = f.write(new)
f.close()
messagebox.showinfo(title='Success', message = 'Delete successful')
def Edit(self):
d = self.lb.curselection()
(idx, ) = d
import Edit as Edet
Edet.Edit(self.master, idx)
def Ok(self):
d = self.lb.curselection()
(idx, ) = d
get = self.lb.get(idx)
self.window.destroy()
print (get)
print (d)
The method curselection() returns an empty tuple when nothing is selected. You can skip those methods just by adding a
if not d:
return
If you want to gray out your buttons, you can do this:
button["state"] = DISABLED
Note that this won't work currently with your code as you did this:
self.button = ttk.Button(...).pack()
The problem lies in the call of pack() which returns None, effectively binding self.button to None. Just assign the button object to the variable first and then pack it. Furthermore, it's not recommended to import * from Tkinter because you're dropping ~190 names in your namespace. Just use
import tkinter as tk

AttributeError: 'QTextEdit' object has no attribute 'text'

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)

Resources