PySide, QTextEdit Append adding blank lines - python-2.7

I have this simple code: basically a tool to send some commands to cmd, and display the output from cmd in a QTextEdit.
Basically, it works.
The only problem that I have is that each time I click on send (with or without a new command), the text is appended but strange blank lines appears at the end of the QTextEdit. Even when i clear the "console", still have these lines.
Maybe it has something to do with the way I call the process, I don't know hence the need for help.
from PySide.QtCore import *
from PySide.QtGui import *
import sys
class MyWindow(QDialog):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.setWindowTitle("Send to CMD")
self.check1 = QCheckBox("Activate Variable")
self.variable = QLineEdit()
self.finalcommand = QLineEdit()
self.clearCommand = QPushButton("Clear")
self.sendCommand = QPushButton("Send")
self.clearOnSend = QCheckBox("Clear on Send")
self.process = QProcess()
self.console = QTextEdit(self)
layout = QVBoxLayout()
layout.addWidget(self.check1)
layout.addWidget(self.variable)
layout.addWidget(self.finalcommand)
layout.addWidget(self.clearOnSend)
layout.addWidget(self.clearCommand)
layout.addWidget(self.sendCommand)
layout.addWidget(self.console)
self.setLayout(layout)
self.connect(self.check1, SIGNAL("clicked()"), self.appendText)
self.variable.textChanged.connect(self.appendText)
self.clearCommand.clicked.connect(self.Clear)
self.sendCommand.clicked.connect(self.Send)
def appendText(self):
if self.check1.isChecked():
TEXT1 = "Dir" + ' ' + str(self.variable.text())
else:
TEXT1 = ""
self.finalcommand.setText(str(TEXT1))
def Clear(self):
if self.clearCommand.isEnabled():
self.console.clear()
def Send(self):
if self.clearOnSend.isChecked():
self.console.clear()
FCTS = "cmd.exe /c" + " " + str(self.finalcommand.text())
self.process.readyReadStandardOutput.connect(self.readConsole)
self.process.start(FCTS)
if not self.process.waitForStarted(0):
return False
if not self.process.waitForFinished(0):
return False
def readConsole(self):
#self.console.setText(str(self.process.readAllStandardOutput()))
self.console.append(str(self.process.readAllStandardOutput()))
app = QApplication(sys.argv)
form = MyWindow()
form.show()
app.exec_()

You probably want to use the string.rstrip() function instead of string.strip()

if you change
self.console.append(str(self.process.readAllStandardOutput()))
to
self.console.append(str([self.process.readAllStandardOutput()]))
you can see what is going on, hope this helps

def appendText(self):
if self.check1.isChecked():
TEXT1 = "Dir" + ' ' + str(self.variable.text())
else:
TEXT1 = ""
you have to remove the last line after else and just type pass
this way no new empty lines will be appended
def appendText(self):
if self.check1.isChecked():
TEXT1 = "Dir" + ' ' + str(self.variable.text())
else:
pass

Related

EncodeError: <flask_mail.Message object at 0x7f044bf07410> is not JSON serializable

My final code is looks like the following:
#client_route.route('/client/cat-<dir_code>/subscribe/<string:user_id>', methods=['POST'])
#only_client
#is_active_client
# #cache.cached(timeout=60)
def subscribe_abonent(user_id):
search_form = Search()
client_id = Client.query.filter_by(tele=session.get('client_phone') ,name=session.get('client_logged_in'), family=session.get('client_family')).first_or_404()
master = Abonent.query.filter_by(public_id=user_id, slug_direction=g.get('current_directory')).first_or_404()
client = Client.query.filter_by(id=client_id.id).first_or_404()
if session.get('client_is_not_subscriber'):
session.pop('client_is_not_subscriber')
session['client_is_subscriber'] = client.name + client.family + str(client.id)
socketio.emit('show_calendar', namespace='/masterCalendar-{}'.format(master.slug, master.public_id.replace('-','')))
if master.email is not None:
if master.subscribers_notifications:
date_now = datetime.now()
send_email(master.email, 'You got a new subscriber','client/newsletter/new_subscriber',master=master.name + ' ' + master.family, client=client.name + " " + client.family, sent=date_now)
#celery.task
def send_email(to, subject, template, **kwargs):
with current_app.app_context():
msg = Message(current_app.config['UBOOK_MAIL_SUBJECT_PREFIX'] + ' ' + subject,
sender=current_app.config['UBOOK_MAIL_SENDER'], recipients=[to])
msg.body = render_template(template + '.txt', **kwargs)
msg.html = render_template(template + '.html', **kwargs)
mail.send(msg)
Now everything is working fine, but celery not recognizing the task, the task runs inside the terminal just like your are sending email using Thread !!!
new_subscriber.txt:
Dear Vladimir, Here was {{master}}
You got a new subscriber:
Клиент: Sasha , Here was {{client}}
Получено: 2017-11-23 12:47:23 , Here was {{sent}}
Another thing that i forgot to mention that , if i removed the master, client and sent arguments and used delay() the code get freezed !!

How do I limit pyqt4 clipboard just only print text or image path?

def tt(self):
cb=QApplication.clipboard()
data=cb.mimeData()
#if data.hasImage():
#for path in data.urls():
#print path
if data.hasText():
tex =unicode (data.text())
print tex
if tex != "":
r = QtCore.QStringList([])
for ct in tex:
py = slug(ct, style=pypinyin.TONE, errors='ignore')
if py != '':
w = ct + '(' + py + ')'
else:
w = ct
r.append(w)
str = r.join("")
self.ui.textEdit.setText(QtCore.QString(str))
I use python2.7 and pyqt4 to make something like Chinese characters to Pinyin. So when I copy string, it's fine, the job ding very well. but when I copy image, I just want only print its path . but tex still work, slug() will go error. how do I limit it.
You can use QMimeData.hasUrls() and QMimeData.urls(). The latter returns a list of QUrl objects (which are also used for file-paths):
if data.hasUrls() or data.hasImage():
for url in data.urls():
filepath = unicode(url.toLocalFile())
print(filepath)
elif data.hasText():
tex =unicode (data.text())
...
EDIT:
Here is a test script to get clipboard information:
import sys
from PyQt4 import QtCore, QtGui
class Window(QtGui.QWidget):
def __init__(self):
super(Window, self).__init__()
self.button = QtGui.QPushButton('Get Clipboard Info', self)
self.button.clicked.connect(self.handleButton)
self.edit = QtGui.QTextEdit(self)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.edit)
layout.addWidget(self.button)
def handleButton(self):
cb = QtGui.QApplication.clipboard()
data = cb.mimeData()
output = []
if data.hasImage():
image = QtGui.QImage(data.imageData())
output.append('Image: size %s' % image.byteCount())
elif data.hasUrls():
output.append('Urls: count %s' % len(data.urls()))
for url in data.urls():
filepath = unicode(url.toLocalFile())
output.append(' %s' % filepath)
elif data.hasText():
output.append('Text: length %s' % len(data.text()))
output.append('')
output.append('Formats: count %s' % len(data.formats()))
for fmt in data.formats():
output.append(' %s' % fmt)
self.edit.setText('\n'.join(output))
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = Window()
window.setGeometry(600, 50, 300, 400)
window.show()
sys.exit(app.exec_())

Tkinter assign buttons to entries in dynamically created widgets

How can I access an Entry content with pressing the corresponding Button in dynamically created widgets?
Below is the best I come up with so far. Thank you for any help.
from Tkinter import *
class App(object):
def __init__(self, master):
self.master = master
self.mf = Frame(self.master)
self.l = ["white", "red", "blue", "brown"]
self.font = ("Arial", 30)
self.c, self.r = 1, 0
self.cc, self.rr = 0, 0
self.bel = []
for c in self.l:
action = self.print_entry
self.e = Entry(self.mf, bg=c, width=10, font=self.font)
self.e.grid(row=self.r, column=self.c)
self.b = Button(self.mf, bg=c, text=c, font=self.font)
self.b.grid(row=self.rr, column=self.cc)
self.b.config(command=action)
self.bel.append((self.b, self.e))
self.rr += 1
self.r += 1
self.mf.pack()
def print_entry(self): # this function prints the content of the entry
pass
def main():
root = Tk()
display = App(root)
root.mainloop()
if __name__=="__main__":
main()
You can pass a reference to the entry widget into the command, using lambda or functools.partial. For example:
self.b.config(command= lambda entry=self.e: action(entry))
...
def print_entry(self, entry):
print("the entry is '%s'" % entry.get())
By the way, using self.b and self.e is pointless, since those variables will only ever hold references to the last button and last entry. You should either use a local variable, and/or append the values to a list.

Using Python Tkinter .config() method

I am trying to use the Python Tkinter .config() method to update some message text. I can't get it to work. What might I be doing wrong (see the update_message method):
#!/usr/bin/python
import alsaaudio as aa
import audioop
import Tkinter as tk
import tkFont
import threading
import Queue
# styles
BACKROUND_COLOR = '#000000'
TYPEFACE = 'Unit-Bold'
FONT_SIZE = 50
TEXT_COLOR = '#777777'
TEXTBOX_WIDTH = 400
# text
TITLE = 'listen closely'
SCORE_MESSAGE = 'your score:\n '
END_MESSAGE = 'too loud!\ntry again'
# configuration
DEVICE = 'hw:1' # hardware sound card index
CHANNELS = 1
SAMPLE_RATE = 8000 # Hz // 44100
PERIOD = 256 # Frames // 256
FORMAT = aa.PCM_FORMAT_S8 # Sound format
NOISE_THRESHOLD = 3
class Display(object):
def __init__(self, parent, queue):
self.parent = parent
self.queue = queue
self._geom = '200x200+0+0'
parent.geometry("{0}x{1}+0+0".format(
parent.winfo_screenwidth(), parent.winfo_screenheight()))
parent.overrideredirect(1)
parent.title(TITLE)
parent.configure(background=BACKROUND_COLOR)
parent.displayFont = tkFont.Font(family=TYPEFACE, size=FONT_SIZE)
self.process_queue()
def process_queue(self):
try:
score = self.queue.get(0)
self.print_message(score)
except Queue.Empty:
pass
self.parent.after(100, self.update_queue)
def update_queue(self):
try:
score = self.queue.get(0)
self.update_message(score)
except Queue.Empty:
pass
self.parent.after(100, self.update_queue)
def print_message(self, messageString):
print 'message', messageString
displayString = SCORE_MESSAGE + str(messageString)
self.message = tk.Message(
self.parent, text=displayString, bg=BACKROUND_COLOR,
font=self.parent.displayFont, fg=TEXT_COLOR, width=TEXTBOX_WIDTH, justify="c")
self.message.place(relx=.5, rely=.5, anchor="c")
def update_message(self, messageString):
print 'message', messageString
displayString = SCORE_MESSAGE + str(messageString)
self.message.config(text=displayString)
def setup_audio(queue, stop_event):
data_in = aa.PCM(aa.PCM_CAPTURE, aa.PCM_NONBLOCK, 'hw:1')
data_in.setchannels(2)
data_in.setrate(44100)
data_in.setformat(aa.PCM_FORMAT_S16_LE)
data_in.setperiodsize(256)
while not stop_event.is_set():
# Read data from device
l, data = data_in.read()
if l:
# catch frame error
try:
max_vol = audioop.rms(data, 2)
scaled_vol = max_vol // 4680
print scaled_vol
if scaled_vol <= 3:
# Too quiet, ignore
continue
queue.put(scaled_vol)
except audioop.error, e:
if e.message != "not a whole number of frames":
raise e
def main():
root = tk.Tk()
queue = Queue.Queue()
window = Display(root, queue)
stop_event = threading.Event()
audio_thread = threading.Thread(target=setup_audio,
args=[queue, stop_event])
audio_thread.start()
try:
root.mainloop()
finally:
stop_event.set()
audio_thread.join()
pass
if __name__ == '__main__':
main()
I don't want to be laying down a new message every time I update. If the .config() doesn't work, is there another method to update the text configuration of the message?
I would use string variables, first create your string variable then set it to want you want it to display at the start next make your object and in text put the sting variable then when you want to change the text in the object change the string variable.
self.messaget = StringVar()
self.messaget.set("")
self.message = tk.Message(
self.parent, textvariable=self.messaget, bg=BACKROUND_COLOR,
font=self.parent.displayFont, fg=TEXT_COLOR,
width=TEXTBOX_WIDTH, justify="c").grid()
#note renember to palce the object after you have created it either using
#.grid(row = , column =) or .pack()
#note that it is textvariable instead of text if you put text instead it will run but
#but will show PY_Var instead of the value of the variable
edit
to change the text without recreating the object you do the name of the string variable you have used and .set
self.messaget.set("hi")

Setting and Retrieving Data with TkInter

I just ran into some strange behavior that has me stumped. I'm writing a simple little GUI for some in-house data processing. I want to allow a user to switch between a few different data-processing modes and input some parameters which define how the data is processed for each mode. The problem is that when the user inputs new parameters, the app ignores requests to switch modes.
The code below replicates the issue. I apologize for the size, this was the shortest code that replicates the problem.
import Tkinter as Tk
class foo(Tk.Frame):
def __init__(self):
self.master = master =Tk.Tk()
Tk.Frame.__init__(self,self.master) #Bootstrap
#Here mode and parameters as key, value pairs
self.data = {'a':'Yay',
'b':'Boo'
}
self.tex = Tk.Text(master=master)
self.tex.grid(row=0,column=0,rowspan=3,columnspan=4)
self.e = Tk.Entry(master=master)
self.e.grid(row=3,column=0,columnspan=4)
self.sv =Tk.StringVar()
self.sv.set('a')
self.b1 = Tk.Radiobutton(master=master,
text = 'a',
indicatoron = 0,
variable = self.sv,
value = 'a')
self.b2 = Tk.Radiobutton(master=master,
text = 'b',
indicatoron = 0,
variable = self.sv,
value = 'b')
self.b3 = Tk.Button(master = master,
text='Apply',command=self.Apply_Func)
self.b4 = Tk.Button(master = master,
text='Print',command=self.Print_Func)
self.b1.grid(row=4,column=0)
self.b2.grid(row=4,column=1)
self.b3.grid(row=4,column=2)
self.b4.grid(row=4,column=3)
def Apply_Func(self):
self.innerdata = self.e.get()
def Print_Func(self):
self.tex.insert(Tk.END,str(self.innerdata)+'\n')
#This is how I'm retrieving the user selected parameters
#property
def innerdata(self):
return self.data[self.sv.get()]
#And how I'm setting the user defined parameters
#innerdata.setter
def innerdata(self,value):
self.data[self.sv.get()] = value
if __name__ == "__main__":
app = foo()
app.mainloop()
Expected behavior:
1) Press button 'a' then 'print' prints:
Yay
2) Press button 'b' then 'print' prints:
Boo
3) Type 'Zep Rocks' into the entry field and press apply
4) Pressing 'print' now yields
Zep Rocks
5) Pressing 'a' then 'print' should yield
Yay
But instead yields
Zep Rocks
Which might be true, but not desired right now. What is going on here?
Edit: I have some new information. Tk.Frame in python 2.7 is not a new-style class. It isn't friendly with descriptors, so rather than interpreting the '=' as a request to use the foo.innerdata's __set__ method, it just assigns the result of self.e.get() to innerdata.
ARGLEBARGLE!!!
Still an open question: how do I get this to do what I want in a clean manner?
So the core problem is that Tk.Frame doesn't subclass from object, so it is not a new-style python class. Which means it doesn't get down with descriptors like I was trying to use. One solution that I found is to subclass my app from object instead.
Code that solves my problem is below:
import Tkinter as Tk
class foo(object):
def __init__(self,master):
self.master = master #Bootstrap
self.mainloop = master.mainloop
self.data = {'a':{'value':7,'metavalue':False},
'b':{'value':'Beeswax','metavalue':True}
}
self.tex = Tk.Text(master=master)
self.tex.grid(row=0,column=0,rowspan=3,columnspan=4)
self.e = Tk.Entry(master=master)
self.e.grid(row=3,column=0,columnspan=4)
self.sv =Tk.StringVar()
self.sv.set('a')
self.b1 = Tk.Radiobutton(master=master,
text = 'a',
indicatoron = 0,
variable = self.sv,
value = 'a')
self.b2 = Tk.Radiobutton(master=master,
text = 'b',
indicatoron = 0,
variable = self.sv,
value = 'b')
self.b3 = Tk.Button(master = master,text='Apply',command=self.Apply_Func)
self.b4 = Tk.Button(master = master,text='Print',command=self.Print_Func)
self.b1.grid(row=4,column=0)
self.b2.grid(row=4,column=1)
self.b3.grid(row=4,column=2)
self.b4.grid(row=4,column=3)
def Apply_Func(self):
self.innerdata = self.e.get()
def Print_Func(self):
self.tex.insert(Tk.END,str(self.innerdata)+'\n')
#property
def innerdata(self):
return self.data[self.sv.get()]
#innerdata.setter
def innerdata(self,value):
self.data[self.sv.get()] = value
if __name__ == "__main__":
master = Tk.Tk()
app = foo(master)
app.mainloop()