Please can some tell me why this code does seem to work. That is display a dialog box atleast.
import sys
from PySide.QtCore import *
from PySide.QtGui import *
class Form(QDialog):
def _init_(self,parent = None):
super(Form , self).__init__(parent)
self.numberLabel1 = QLabel("first Number")
self.numberLabel2 = QLabel("Second Number")
self.txtField1 = QLineEdit()
self.txtField2 = QLineEdit()
self.btnSum = QPushButton("Sum")
self.resultKeep = QLabel()
grid = QGridLayout()
grid.addWidget(self.numberLabel1,0,0)
grid.addWidget(self.txtField1,0,1)
grid.addWidget(self.numberLabel2,1,0)
grid.addWidget(self.txtField2,1,1)
grid.addWidget(self.resultKeep,0,2)
grid.addWidget(self.btnSum,0,3)
self.setLayout(grid)
if __name__ == '__init__' :
app = QApplication(sys.a`enter code here`rgv)
form = Form()
form.show()
#sys.exit(app.exec_())
Related
I'm trying to subclass QFontDialog and would like to retrieve the characteristics of the selected font. If I use getFont() a QFontDialog window appears first, ... I'm certainly doing something wrong.
Here's my example code :
from PyQt5.QtWidgets import (QFontDialog, QPushButton,
QMainWindow, QApplication,
QTabWidget, QWidget, QVBoxLayout)
import sys
class FontSelection(QFontDialog) :
def __init__(self, parent=None):
super(FontSelection, self).__init__(parent)
self.setOption(self.DontUseNativeDialog, True)
self.bouton = self.findChildren(QPushButton)
self.intitule_bouton = self.bouton[0].text().lower()
self.ouvertureBouton = [x for x in self.bouton if self.intitule_bouton in str(x.text()).lower()][0]
self.ouvertureBouton.clicked.disconnect()
self.ouvertureBouton.clicked.connect(self.font_recup)
def font_recup(self) :
self.font_capture()
def font_capture(self) :
if self.intitule_bouton in ['ok', '&ok'] :
font, self.intitule_bouton = self.getFont()
print(font)
class MainQFontDialogTry(QMainWindow):
def __init__(self):
super(MainQFontDialogTry, self).__init__()
self.setWindowTitle('QFontDialog subclassed try')
self.setGeometry(0, 0, 1000, 760)
self.setMinimumSize(1000, 760)
self.tab_widget = QTabWidget()
self.win_widget_1 = FontSelection(self)
widget = QWidget()
layout = QVBoxLayout(widget)
self.tab_widget.addTab(self.win_widget_1, "QFontDialog Tab")
layout.addWidget(self.tab_widget)
self.setCentralWidget(widget)
self.qfont = FontSelection()
self.qfont.font_recup()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MainQFontDialogTry()
ex.show()
sys.exit(app.exec_())
i am trying to record sound from pyaudio in python and making a gui for the same.
my code run fine when i use datetime library and give the filename eg.sound_2020_21_04_03_40.wav which is current date,time but when i try to take the filename from user with tkinter (from tkinter.filedialog import asksaveasfile) it is saving the sound file but its empty with 0 bytes.
can any on e help me in this. this is my coding part of stop button which terminate the code and save the file.
import tkinter as tk
import threading
import pyaudio
import wave
from tkinter import *
import tkinter.font as font
from tkinter.filedialog import asksaveasfile
class App():
chunk = 1024
sample_format = pyaudio.paInt16
channels = 2
fs = 44100
frames = []
def __init__(self, master):
self.isrecording = False
myFont = font.Font(weight="bold")
self.button1 = tk.Button(main, text='Record',command=self.startrecording,height=2,width=20,bg='#0052cc', fg='#ffffff')
self.button2 = tk.Button(main, text='stop',command=self.stoprecording,height=2,width=20,bg='#0052cc', fg='#ffffff')
self.button1['font'] = myFont
self.button2['font'] = myFont
self.button1.place(x=30, y=30)
self.button2.place(x=280, y=30)
def startrecording(self):
self.p = pyaudio.PyAudio()
self.stream = self.p.open(format=self.sample_format,channels=self.channels,rate=self.fs,frames_per_buffer=self.chunk,input=True)
self.isrecording = True
print('Recording')
t = threading.Thread(target=self.record)
t.start()
def stoprecording(self):
self.isrecording = False
print('recording complete')
self.filename = asksaveasfile(initialdir = "/",title = "Save as",mode='w',filetypes = (("audio file","*.wav"),("all files","*.*")),defaultextension=".wav")
wf = wave.open(self.filename, 'wb')
wf.setnchannels(self.channels)
wf.setsampwidth(self.p.get_sample_size(self.sample_format))
wf.setframerate(self.fs)
wf.writeframes(b''.join(self.frames))
wf.close()
main.destroy()
def record(self):
while self.isrecording:
data = self.stream.read(self.chunk)
self.frames.append(data)
main = tk.Tk()
main.title('recorder')
main.geometry('520x120')
app = App(main)
main.mainloop()
image is here
It's strange that no exceptions were risen, because when you call askopenfile(...) it returns a file object (and opens an empty file for reading - that file you have seen), but wave.open(...) expects a filename. To get it, you need to use askopenfilename(...) instead of askopenfile(...). And don't forget to import askopenfilename in the top of your code.
Here is the full code (I have refactored it according to PEP8):
import tkinter as tk
import threading
import pyaudio
import wave
from tkinter import *
import tkinter.font as font
from tkinter.filedialog import asksaveasfilename
class App():
chunk = 1024
sample_format = pyaudio.paInt16
channels = 2
fs = 44100
frames = []
def __init__(self, master):
self.isrecording = False
myFont = font.Font(weight="bold")
self.button1 = tk.Button(main, text='Record', command=self.startrecording,
height=2, width=20, bg='#0052cc', fg='#ffffff')
self.button2 = tk.Button(main, text='stop', command=self.stoprecording,
height=2, width=20, bg='#0052cc', fg='#ffffff')
self.button1['font'] = myFont
self.button2['font'] = myFont
self.button1.place(x=30, y=30)
self.button2.place(x=280, y=30)
def startrecording(self):
self.p = pyaudio.PyAudio()
self.stream = self.p.open(format=self.sample_format, channels=self.channels,
rate=self.fs, frames_per_buffer=self.chunk, input=True)
self.isrecording = True
print('Recording')
t = threading.Thread(target=self.record)
t.start()
def stoprecording(self):
self.isrecording = False
print('recording complete')
self.filename = asksaveasfilename(initialdir="/", title="Save as",
filetypes=(("audio file", "*.wav"), ("all files", "*.*")),
defaultextension=".wav")
wf = wave.open(self.filename, 'wb')
wf.setnchannels(self.channels)
wf.setsampwidth(self.p.get_sample_size(self.sample_format))
wf.setframerate(self.fs)
wf.writeframes(b''.join(self.frames))
wf.close()
main.destroy()
def record(self):
while self.isrecording:
data = self.stream.read(self.chunk)
self.frames.append(data)
print("does it")
main = tk.Tk()
main.title('recorder')
main.geometry('520x120')
app = App(main)
main.mainloop()
I have a problem with text in QTextBrowser. I have a similar code:
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
centralWidget = QWidget()
self.setCentralWidget(centralWidget)
self.textBox = QTextBrowser(centralWidget)
self.textBox.setOpenExternalLinks(True)
self.button = QPushButton(centralWidget)
self.button.setText("PUSH")
self.button.clicked.connect(self.pressed)
self.grid = QGridLayout(centralWidget)
self.grid.addWidget(self.button)
self.grid.addWidget(self.textBox)
def pressed(self):
id = 49309034
url_name = "test_link"
link = '<a href = https://stackoverflow.com/questions/{0}> {1} </a>'.format(id, url_name)
dict = {'Key': 'Value', link: 'Test link'}
for key, value in dict.items():
self.textBox.append('{0}: {1}'.format(key, value))
self.textBox.append("")
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
So, when I push button I get:
However, if I click on the link and then push button again - all text becomes 'hyperactive':
I think, the problem is in 'next line'. Because I've tried such code and it's working properly:
string = ""
for key, value in dict.items():
string += '{0}: {1}'.format(key, value) + '; '
self.textBox.append(string)
After I've clicked on the URL and pushed button
Can you help me figure this out?
Try moving the cursor before adding lines to QTextBrowser.
For example, like this:
self.textBox.moveCursor(QTextCursor.Start)
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
centralWidget = QWidget()
self.setCentralWidget(centralWidget)
self.textBox = QTextBrowser(centralWidget)
self.textBox.setOpenExternalLinks(True)
self.button = QPushButton(centralWidget)
self.button.setText("PUSH")
self.button.clicked.connect(self.pressed)
self.grid = QGridLayout(centralWidget)
self.grid.addWidget(self.button)
self.grid.addWidget(self.textBox)
def pressed(self):
self.textBox.moveCursor(QTextCursor.Start) # <---
id = 49309034
url_name = "test_link"
link = '<a href = https://stackoverflow.com/questions/{0}> {1} </a>'.format(id, url_name)
dict = {'Key': 'Value', link: 'Test link'}
for key, value in dict.items():
self.textBox.append('{0}: {1}'.format(key, value))
self.textBox.append("")
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
guys am trying to write a program that takes details from one window and imports them onto a profile of another window.. i want it be on the same app... all i see is qdialog class and I dont wanna use it
am taking data from the first window to import it to the second window
here's my code of the first
def loader(self):
widget = QWidget()
self.setCentralWidget(widget)
#layouts
self.layout = QFormLayout()
self.descriLayout = QVBoxLayout()
self.buttonLayout = QHBoxLayout()
#QFormLayout dealz
self.name = QLabel('name')
items = ['male' , 'female' , 'none']
self.sexchooser = QComboBox()
for item in items:
self.sexchooser.addItem(item)
self.age = QLabel('age')
self.optcourse = QLabel('Opted Course')
self.nameEdit = QLineEdit()
#self.nameEdit.editingFinished()
self.nameEdit.setPlaceholderText('enter name here')
self.coursEdit = QLineEdit()
self.coursEdit.setPlaceholderText('Mt || Ph || St')
self.sexLabel = QLabel('sex')
#age selector
self.ageSelector = QComboBox()
for x in range(18 , 40):
self.ageSelector.addItem(str(x))
self.descriptor = QPlainTextEdit()
self.descriptor.setPlaceholderText('describe yourself here')
self.descriptor.setUndoRedoEnabled(True)
self.layout.addRow(self.name , self.nameEdit)
self.layout.addRow(self.optcourse , self.coursEdit)
self.layout.addRow(QLabel('sex') , self.sexchooser)
self.layout.addRow(QLabel('Age') , self.ageSelector)
#buttons dealz
self.SubmitButton = QPushButton('&Submit')
self.SubmitButton.clicked.connect(self.detailer)
self.cancelButton = QPushButton("Can&cel")
self.cancelButton.clicked.connect(self.close)
self.buttonLayout.addWidget(self.SubmitButton)
self.buttonLayout.addWidget(self.cancelButton)
self.descriLayout.addLayout(self.layout)
self.descriLayout.addWidget(self.descriptor)
self.descriLayout.addLayout(self.buttonLayout)
self.show()
widget.setLayout(self.descriLayout)
self.setMinimumSize(300 , 350)
self.setMaximumSize(300 , 350)
self.setWindowTitle('DETAILS')
def detailer(self):
#the second window called here
thanks in advance
Try it:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.loader()
def loader(self):
widget = QWidget()
self.setCentralWidget(widget)
#layouts
self.layout = QFormLayout()
self.descriLayout = QVBoxLayout()
self.buttonLayout = QHBoxLayout()
#QFormLayout dealz
self.name = QLabel('name')
items = ['male' , 'female' , 'none']
self.sexchooser = QComboBox()
for item in items:
self.sexchooser.addItem(item)
self.age = QLabel('age')
self.optcourse = QLabel('Opted Course')
self.nameEdit = QLineEdit()
#self.nameEdit.editingFinished()
self.nameEdit.setPlaceholderText('enter name here')
self.coursEdit = QLineEdit()
self.coursEdit.setPlaceholderText('Mt || Ph || St')
self.sexLabel = QLabel('sex')
#age selector
self.ageSelector = QComboBox()
for x in range(18 , 40):
self.ageSelector.addItem(str(x))
self.descriptor = QPlainTextEdit()
self.descriptor.setPlaceholderText('describe yourself here')
self.descriptor.setUndoRedoEnabled(True)
self.layout.addRow(self.name , self.nameEdit)
self.layout.addRow(self.optcourse , self.coursEdit)
self.layout.addRow(QLabel('sex') , self.sexchooser)
self.layout.addRow(QLabel('Age') , self.ageSelector)
#buttons dealz
self.SubmitButton = QPushButton('&Submit')
self.SubmitButton.clicked.connect(self.detailer)
self.cancelButton = QPushButton("Can&cel")
self.cancelButton.clicked.connect(self.close)
self.buttonLayout.addWidget(self.SubmitButton)
self.buttonLayout.addWidget(self.cancelButton)
self.descriLayout.addLayout(self.layout)
self.descriLayout.addWidget(self.descriptor)
self.descriLayout.addLayout(self.buttonLayout)
self.show()
widget.setLayout(self.descriLayout)
self.setMinimumSize(300 , 350)
self.setMaximumSize(300 , 350)
self.setWindowTitle('DETAILS')
def detailer(self):
print("#the second window called here")
self.statusBar().showMessage("Switched to window 2")
valueText = " {} \n {} \n {} \n {} \n {}"\
.format(self.nameEdit.text(),
self.coursEdit.text(),
self.sexchooser.currentText(),
self.ageSelector.currentText(),
self.descriptor.toPlainText())
self.cams = Window2(valueText, self)
self.cams.show()
class Window2(QDialog):
def __init__(self, value, parent=None):
super().__init__(parent)
self.setGeometry(750, 100, 300, 350)
self.parent = parent
self.setWindowTitle('Window2')
self.setWindowIcon(self.style().standardIcon(QStyle.SP_FileDialogInfoView))
label1 = QLabel(value)
self.button = QPushButton()
self.button.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)
self.button.setIcon(self.style().standardIcon(QStyle.SP_ArrowLeft))
self.button.setIconSize(QSize(200, 200))
layoutV = QVBoxLayout()
self.pushButton = QPushButton(self)
self.pushButton.setStyleSheet('background-color: rgb(0,0,255); color: #fff')
self.pushButton.setText('Click me!')
self.pushButton.clicked.connect(self.goMainWindow)
layoutV.addWidget(self.pushButton)
layoutH = QHBoxLayout()
layoutH.addWidget(label1)
layoutH.addWidget(self.button)
layoutV.addLayout(layoutH)
self.setLayout(layoutV)
def goMainWindow(self):
self.parent.show()
self.close()
if __name__=='__main__':
app = QApplication(sys.argv)
mainwindow = MainWindow()
mainwindow.show()
sys.exit(app.exec_())
I am new to PyQt, I am trying to implement slider in PyQt4, but i don't know why code code is not generating any output.
what i want is, create 3 slider to change 3 values dynamically.
Here i am resizing font size of text "hue", "sat", "val".
Is there is any good source to learn slider in PyQt?
here is my code
PyQt4Slider.py
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(50,50,500,300)
self.setWindowTiltle("HSV")
self.home()
def home(self):
#hue = 100
#sat = 100
#val = 100
layout = QVBoxLayout()
self.l1 = QLabel("hue")
self.l2 = QLabel("sat")
self.l3 = QLabel("val")
self.l1.setAlignment(Qt.AlignCenter)
self.l2.setAlignment(Qt.AlignCenter)
self.l3.setAlignment(Qt.AlignCenter)
layout.addWidget(self.l1)
layout.addWidget(self.l1)
layout.addWidget(self.l1)
self.sl = QSlider(Qt.Horizontal)
self.s2 = QSlider(Qt.Horizontal)
self.s3 = QSlider(Qt.Horizontal)
self.sl.setMinimum(0)
self.sl.setMaximum(179)
self.sl.setValue(20)
self.sl.setTickPosition(QSlider.TicksBelow)
self.sl.setTickInterval(5)
self.s2.setMinimum(0)
self.s2.setMaximum(255)
self.s2.setValue(100)
self.s2.setTickPosition(QSlider.TicksBelow)
self.s2.setTickInterval(5)
self.s3.setMinimum(0)
self.s3.setMaximum(255)
self.s3.setValue(100)
self.s3.setTickPosition(QSlider.TicksBelow)
self.s3.setTickInterval(5)
layout.addWidget(self.s1)
self.sl.valueChanged.connect(self.valuechange)
layout.addWidget(self.s2)
self.s2.valueChanged.connect(self.valuechange)
layout.addWidget(self.s3)
self.s3.valueChanged.connect(self.valuechange)
self.setLayout(layout)
def valuechange(self):
sizel1 = self.sl.value()
self.l1.setFont("Arial",sizel1)
sizel2 = self.sl.value()
self.l2.setFont("Arial", sizel2)
sizel2 = self.sl.value()
self.l2.setFont("Arial", sizel2)
def main():
app = QApplication(sys.argv)
ex = Window()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
here is what i am getting after running code
Ran 0 tests in 0.000s
OK
Process finished with exit code 0
Empty test suite.
Most of the problems in your script are caused by typos. Here is a fixed version that should work okay:
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(50,50,500,300)
self.setWindowTitle("HSV")
self.home()
def home(self):
layout = QVBoxLayout()
self.l1 = QLabel("hue")
self.l2 = QLabel("sat")
self.l3 = QLabel("val")
self.l1.setAlignment(Qt.AlignCenter)
self.l2.setAlignment(Qt.AlignCenter)
self.l3.setAlignment(Qt.AlignCenter)
layout.addWidget(self.l1)
layout.addWidget(self.l2)
layout.addWidget(self.l3)
self.s1 = QSlider(Qt.Horizontal)
self.s2 = QSlider(Qt.Horizontal)
self.s3 = QSlider(Qt.Horizontal)
self.s1.setMinimum(0)
self.s1.setMaximum(179)
self.s1.setValue(20)
self.s1.setTickPosition(QSlider.TicksBelow)
self.s1.setTickInterval(5)
self.s2.setMinimum(0)
self.s2.setMaximum(255)
self.s2.setValue(100)
self.s2.setTickPosition(QSlider.TicksBelow)
self.s2.setTickInterval(5)
self.s3.setMinimum(0)
self.s3.setMaximum(255)
self.s3.setValue(100)
self.s3.setTickPosition(QSlider.TicksBelow)
self.s3.setTickInterval(5)
layout.addWidget(self.s1)
self.s1.valueChanged.connect(self.valuechange)
layout.addWidget(self.s2)
self.s2.valueChanged.connect(self.valuechange)
layout.addWidget(self.s3)
self.s3.valueChanged.connect(self.valuechange)
self.setLayout(layout)
# set the initial fonts
self.valuechange()
def valuechange(self):
sizel1 = self.s1.value()
self.l1.setFont(QFont("Arial", sizel1))
sizel2 = self.s2.value()
self.l2.setFont(QFont("Arial", sizel2))
sizel3 = self.s3.value()
self.l3.setFont(QFont("Arial", sizel3))
def main():
app = QApplication(sys.argv)
ex = Window()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()